Browse Source

及时通信

warrior 3 months ago
parent
commit
a513e2327c

+ 1 - 0
angular.json

@@ -132,6 +132,7 @@
             "inlineStyleLanguage": "scss",
             "assets": [
               "projects/live-app/src/assets/js/AgoraRTC_N-4.14.0.js",
+              "projects/live-app/src/assets/js/agora-rtm-2.2.0.min.js",
               {
                 "glob": "**/*",
                 "input": "projects/live-app/public"

File diff suppressed because it is too large
+ 6 - 0
projects/live-app/src/assets/js/agora-rtm-2.2.0.min.js


+ 1 - 0
projects/live-app/src/index.html

@@ -10,6 +10,7 @@
   <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
 	<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
   <script src="./assets/js/AgoraRTC_N-4.14.0.js"></script>
+  <script src="./assets/js/agora-rtm-2.2.0.min.js"></script>
 </head>
 <body>
   <app-root></app-root>

+ 2 - 2
projects/live-app/src/moduls/live/chat/chat.component.html

@@ -42,9 +42,9 @@
   </ion-popover>
 
   <div id="container" style="overflow: hidden">
-    @for (item of list.data; track $index) {
+    @for (item of msgServe.messageList; track $index) {
     <div class="clearfix message-box">
-      @if ($index == 0 || item.create_time - list.data[$index-1].create_time >
+      @if ($index == 0 || item.create_time - msgServe.messageList[$index-1].create_time >
       60) {
       <div class="time-box">
         @if (item.istoday) {

+ 5 - 50
projects/live-app/src/moduls/live/chat/chat.component.ts

@@ -14,6 +14,7 @@ import {
 // var JIM = JIMServ.JIM;
 // var Events = JIMServ.Events;
 import * as Parse from 'parse';
+import { MessageService } from '../../../services/message.service';
 
 @Component({
   selector: 'app-chat',
@@ -29,55 +30,6 @@ export class ChatComponent implements OnInit {
   targetUser?: Parse.Object;// 对方用户
  
   text: string = '';
-  list: any = {
-    data: [
-      {
-        is_self: true,
-        avatar:
-          'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
-        msg_type: 1,
-        content: 'nihao',
-        create_time: new Date(),
-        istoday: true,
-        timeStamp: new Date(),
-        data: [
-          {
-            create_time: new Date(),
-          },
-        ],
-      },
-      {
-        is_self: true,
-        avatar:
-          'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
-        msg_type: 1,
-        content: `Use the pipe name to trace where the pipe is declared and used. To resolve this error: If the pipe is local to the NgModule, give it a unique name in the pipe's decorator and declared it in the NgModule. If the pipe is standalone or is declared in another NgModule, add it to the imports field of the standalone component or the current NgModule.`,
-        create_time: new Date(),
-        istoday: true,
-        timeStamp: new Date(),
-        data: [
-          {
-            create_time: new Date(),
-          },
-        ],
-      },
-      {
-        is_self: false,
-        avatar:
-          'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
-        msg_type: 1,
-        content: 'nihao',
-        create_time: new Date(),
-        istoday: true,
-        timeStamp: new Date(),
-        data: [
-          {
-            create_time: new Date(),
-          },
-        ],
-      },
-    ],
-  };
 
   showPreView: boolean = false; //预览图片
   viewImg: string = '';
@@ -92,6 +44,7 @@ export class ChatComponent implements OnInit {
     public toastController: ToastController,
     private loadingCtrl: LoadingController,
     private activateRoute: ActivatedRoute,
+    public msgServe:MessageService,
   ) {}
 
   ngOnInit() {
@@ -272,12 +225,13 @@ export class ChatComponent implements OnInit {
       content: this.text,
     });
     this.text = ''
+
   }
   async send(param: { msg_type: string; content: string }) {
     let that = this;
     // 2.开始发送消息
     // let isLogin = JIMServ.checkLogin();
-    this.list.data.push({
+    this.msgServe.messageList.push({
       is_self: true,
       avatar:
         'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
@@ -287,6 +241,7 @@ export class ChatComponent implements OnInit {
       istoday: true,
       timeStamp: new Date(),
     })
+    this.msgServe.publishMessage(param.content)
   }
   dismiss(evt: any) {
     this.isOpen = false;

+ 1 - 1
projects/live-app/src/moduls/live/link-page/link-page.component.html

@@ -30,7 +30,7 @@
     [style.visibility]="showTool ? 'visible' : 'hidden'"
   >
     <div class="row" style="justify-content: center">
-      @if(liveService.connection_state === 'connected'){
+      @if(liveService.connection_state === 'CONNECTED'){
       <div class="tips">
         剩余通话时长
         <span

+ 14 - 14
projects/live-app/src/moduls/tabs/my/my.component.html

@@ -7,23 +7,23 @@
           'url(https://file-cloud.fmode.cn/Qje9D4bqol/20241109/vv1tvb032259054.png)'
         "
       >
-        <img [src]="user?.get('avatar')" alt="" class="avatar" />
+        <img [src]="user.get('avatar')" alt="" class="avatar" />
       </div>
       <div class="user-right">
         <div class="user-name">
           {{
-            user?.get("nickname") ||
-              user?.get("mobile") ||
-              user?.get("username")
+            user.get("nickname") ||
+              user.get("mobile") ||
+              user.get("username")
           }}
         </div>
         <div class="user-block">
           <div class="tags">
-            @if (user?.get('sex') == '男') {
+            @if (user.get('sex') == '男') {
             <div class="sex">
               <ion-icon name="male-outline"></ion-icon>
             </div>
-            }@else if (user?.get('sex') == '女') {
+            }@else if (user.get('sex') == '女') {
             <div class="sex girl">
               <ion-icon name="male-female-outline"></ion-icon>
             </div>
@@ -35,9 +35,9 @@
               />
               23
             </div>
-            <div class="id">ID:{{ user?.id }}</div>
+            <div class="id">ID:{{ user.id }}</div>
           </div>
-          <div class="btn" (click)="toUrl('user/profile/'+user?.id)">个人主页</div>
+          <div class="btn" (click)="toUrl('user/profile/'+user.id)">个人主页</div>
         </div>
         <div class="user-footer">
           <div class="row">{{userObj.fans}} 粉丝</div>
@@ -73,10 +73,10 @@
           <div class="user-block">
             <div class="user-avatar">
               <img src="/img/2.png" alt="" class="tag" />
-              <img [src]="user?.get('avatar')" class="avatar" alt="" />
+              <img [src]="user.get('avatar')" class="avatar" alt="" />
             </div>
             <div class="user-name">
-              {{ user?.get("name") }}
+              {{ user.get("name") }}
             </div>
           </div>
           <div class="user-detail">
@@ -88,10 +88,10 @@
           <div class="user-block">
             <div class="user-avatar">
               <img src="/img/2.png" alt="" class="tag" />
-              <img [src]="user?.get('avatar')" class="avatar" alt="" />
+              <img [src]="user.get('avatar')" class="avatar" alt="" />
             </div>
             <div class="user-name">
-              {{ user?.get("name") }}
+              {{ user.get("name") }}
             </div>
           </div>
           <div class="user-detail">
@@ -103,10 +103,10 @@
           <div class="user-block">
             <div class="user-avatar">
               <img src="/img/2.png" alt="" class="tag" />
-              <img [src]="user?.get('avatar')" class="avatar" alt="" />
+              <img [src]="user.get('avatar')" class="avatar" alt="" />
             </div>
             <div class="user-name">
-              {{ user?.get("name") }}
+              {{ user.get("name") }}
             </div>
           </div>
           <div class="user-detail">

+ 3 - 1
projects/live-app/src/moduls/tabs/tabs/tabs.component.ts

@@ -8,6 +8,7 @@ import { IonicModule } from '@ionic/angular';
 import { OnInit } from '@angular/core';
 // import { MessageService } from './chat/message.service';
 import { AlertController } from '@ionic/angular';
+import { MessageService } from '../../../services/message.service';
 
 @Component({
   selector: 'live-tabs',
@@ -22,7 +23,8 @@ export class TabsComponent implements OnInit {
   // @ViewChild('tabs',{static:true}) tabs;
   constructor(
     private router: Router,
-    private alertController: AlertController
+    private alertController: AlertController,
+    private messageServ: MessageService
   ) {
     this.active = Number(localStorage.getItem('active')) || 0
     this.presentAlert();

+ 2 - 2
projects/live-app/src/services/live.service.ts

@@ -15,7 +15,7 @@ export class LiveService {
     channel: string;
     token: string;
   } = {
-    appid: '71d3357d920d4352b39ec8b8d26a7cb9',
+    appid: '',
     channel: '',
     token: '',
   };
@@ -188,8 +188,8 @@ export class LiveService {
       )
       .then(async (uid: any) => {
         // await this.client.setClientRole('host');
-        console.log('进入频道当前uid:', uid);
         this.connection_state = this.client.connectionState;
+        console.log('进入频道当前uid:', uid,'状态:',this.connection_state);
         if (!this.isAnchor) {
           // 观众进入直播间,创建直播记录
           await this.createLiveLog(uid);

+ 180 - 0
projects/live-app/src/services/message.service.ts

@@ -0,0 +1,180 @@
+import { Injectable } from '@angular/core';
+import { HttpService } from './http.service';
+import { LiveService } from './live.service';
+import * as Parse from 'parse';
+// import AgoraRTM from 'agora-rtmClient';
+declare const AgoraRTM: any;
+@Injectable({
+  providedIn: 'root',
+})
+export class MessageService {
+  rtmClient: any; // RTM实例
+  msChannelName: string = 'global_room'; // 全球频道
+  options: any = {
+    appid: '',
+    userId: Parse.User.current()?.id,
+    token:
+      '007eJxTYGh7sUrIjKd9bl9ncuOq0mvLordY/r5dWv64Y3Wz5uVrNcwKDMmJBqbmJpaGickWliapFkYWBkYWqclp5sbmaSaphhYm+juD0hsCGRlOuFsyMDIwATEjA4jPxZBjkO5maeoU4OMEACaMIUE=',
+  };
+  constructor(private liveService: LiveService, private http: HttpService) {
+    this.initRTM();
+  }
+  messageList: any = [
+    {
+      is_self: true,
+      avatar:
+        'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
+      msg_type: 1,
+      content: 'nihao',
+      create_time: new Date(),
+      istoday: true,
+      timeStamp: new Date(),
+      data: [
+        {
+          create_time: new Date(),
+        },
+      ],
+    },
+    {
+      is_self: true,
+      avatar:
+        'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
+      msg_type: 1,
+      content: `Use the pipe name to trace where the pipe is declared and used. To resolve this error: If the pipe is local to the NgModule, give it a unique name in the pipe's decorator and declared it in the NgModule. If the pipe is standalone or is declared in another NgModule, add it to the imports field of the standalone component or the current NgModule.`,
+      create_time: new Date(),
+      istoday: true,
+      timeStamp: new Date(),
+      data: [
+        {
+          create_time: new Date(),
+        },
+      ],
+    },
+    {
+      is_self: false,
+      avatar:
+        'https://file-cloud.fmode.cn/Qje9D4bqol/20241109/2t1lp0032258601.png',
+      msg_type: 1,
+      content: 'nihao',
+      create_time: new Date(),
+      istoday: true,
+      timeStamp: new Date(),
+      data: [
+        {
+          create_time: new Date(),
+        },
+      ],
+    },
+  ]; // 世界频道消息列表
+  /* 获取token */
+  async getToken(channel: string) {
+    //获取频道token记录
+    let uid = Parse.User.current()?.id;
+    let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
+    let reqBody = {
+      company: this.liveService.company, // this.aiSer.company,
+      channelName: channel,
+      type: 'withrtm',
+      account: uid,
+    };
+    let data: any = await this.http.httpRequst(baseurl, reqBody, 'POST');
+    console.log(data);
+    if (data.code == 200) {
+      this.options.token = data.data.token;
+      this.options.appid = data.data.appid;
+    }
+  }
+
+  async initRTM() {
+    await this.getToken(this.msChannelName);
+    console.log();
+    this.rtmClient = new AgoraRTM.RTM(this.options.appid, this.options.userId);
+    this.joinReady();
+    await this.loginRTM();
+    // await this.join();
+    this.subscribeMessage(this.msChannelName);
+  }
+  /* 监听频道消息 */
+  joinReady() {
+    this.rtmClient.addEventListener('message', (event: any) => {
+      this.showMessage(event.publisher, event.message);
+    });
+    console.log('initRTM');
+    // Pressence event handler.
+    this.rtmClient.addEventListener('presence', (event: any) => {
+      console.log('presence event: ', event);
+      if (event.eventType === 'SNAPSHOT') {
+        this.showMessage('INFO', 'I Join');
+      } else {
+        this.showMessage('INFO', event.publisher + ' is ' + event.eventType);
+      }
+    });
+    this.rtmClient.addEventListener('status', (event: any) => {
+      console.log('status event: ', event);
+      // The current connection state.
+      const currentState = event.state;
+      const changeReason = event.reason;
+      // this.showMessage('INFO', JSON.stringify(event));
+    });
+  }
+  /* 加入频道 */
+  async join() {
+    const options = {
+      token: this.options.token,
+      withPresence: true,
+      withLock: true,
+      withMetadata: true,
+    };
+    try {
+      const streamChannel = this.rtmClient.createStreamChannel(
+        this.msChannelName
+      );
+      const result = await streamChannel.join(options);
+    } catch (status) {
+      console.error('join channel failed: ', status);
+    }
+  }
+  async loginRTM() {
+    // console.log(this.options.token);
+    try {
+      const result = await this.rtmClient.login({ token: this.options.token });
+      // console.log(result);
+    } catch (status) {
+      console.log(status);
+    }
+  }
+
+  subscribeMessage(channelId: string, callback?: any) {
+    this.rtmClient.subscribe(channelId);
+  }
+
+  showMessage(user: any, msg: string) {
+    console.log(user, msg);
+    this.messageList.push({
+      user,
+      msg,
+    });
+    // const inputText = textInput.value;
+    // const newText = document.createTextNode(user + ": " + msg);
+    // const newLine = document.createElement("br");
+    // textDisplay.appendChild(newText);
+    // textDisplay.appendChild(newLine);
+  }
+
+  async publishMessage(message: string) {
+    const payload = { type: 'text', message: message };
+    const publishMessage = JSON.stringify(payload);
+    const publishOptions = { channelType: 'MESSAGE' };
+    try {
+      const result = await this.rtmClient.publish(
+        this.msChannelName,
+        publishMessage,
+        publishOptions
+      );
+      this.showMessage(this.options.userId, publishMessage);
+      console.log(result);
+    } catch (status) {
+      console.log(status);
+    }
+  }
+}

Some files were not shown because too many files changed in this diff