message.service.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import { Injectable } from '@angular/core';
  2. import { HttpService } from './http.service';
  3. import * as Parse from 'parse';
  4. import { AlertController, ToastController } from '@ionic/angular';
  5. // import AgoraRTM from 'agora-rtmClient';
  6. import { Subject } from 'rxjs';
  7. import { Router } from '@angular/router';
  8. import { AiChatService } from './aichart.service';
  9. declare const AgoraRTM: any;
  10. import { VapInit } from '../lib/vap-player/index'
  11. @Injectable({
  12. providedIn: 'root',
  13. })
  14. export class MessageService {
  15. private eventSource = new Subject<any>();
  16. event$ = this.eventSource.asObservable();
  17. private eventplay = new Subject<any>();
  18. eventplay$ = this.eventplay.asObservable();
  19. company: string = 'Qje9D4bqol';
  20. rtmClient: any; // RTM实例
  21. // rtmClientMap: any = {};
  22. channelNameList: any = {}; //订阅频道状态
  23. msChannelName: string = 'global_room'; // 全球频道
  24. options: any = {
  25. connectState: false,
  26. };
  27. appid?: string;
  28. userId: string = Parse.User.current()?.id!;
  29. pageFun?: Function; //页面传入的方法
  30. alert: any; // 弹窗
  31. messageMapList: any = {};
  32. giftLogMap: any = [];
  33. giftList: Array<any> = []; //礼物列表
  34. timeg: any;
  35. isPlayer: boolean = false;
  36. private audioPlayer: HTMLAudioElement | null = null;
  37. private loopPlayAudio(audioUrl: string, rep?:boolean) {
  38. if (this.audioPlayer) {
  39. this.audioPlayer.pause();
  40. this.audioPlayer.currentTime = 0;
  41. }
  42. this.audioPlayer = new Audio(audioUrl);
  43. this.audioPlayer.loop = rep; // 设置循环播放
  44. this.audioPlayer.play().catch(error => {
  45. console.error('播放音频失败:', error);
  46. });
  47. }
  48. reset() {
  49. this.options = { connectState: false };
  50. this.rtmClient = null;
  51. this.channelNameList = {};
  52. this.messageMapList = {};
  53. }
  54. constructor(
  55. private alertController: AlertController,
  56. private router: Router,
  57. private toastController: ToastController,
  58. private http: HttpService,
  59. private aiServ: AiChatService
  60. ) {
  61. this.aiServ.getGift().then((data) => (this.giftList = data));
  62. }
  63. /* 获取token */
  64. async getToken() {
  65. this.userId = Parse.User.current()?.id!;
  66. //获取频道token记录
  67. let uid = Parse.User.current()?.id;
  68. let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
  69. let reqBody = {
  70. company: this.company,
  71. channelName: this.msChannelName,
  72. type: 'withrtm',
  73. account: uid,
  74. };
  75. let data: any = await this.http.httpRequst(baseurl, reqBody, 'POST');
  76. console.log(data);
  77. if (data.code == 200) {
  78. // this.options[channel] = {
  79. // token: data.data.token,
  80. // };
  81. this.options.token = data.data.token;
  82. this.appid = data.data.appid;
  83. }
  84. }
  85. async initRTM() {
  86. // let states = ['CONNECTED', 'CONNECTING'];
  87. if (this.options.connectState) return;
  88. await this.getToken();
  89. const rtmConfig = { logLevel: 'error', logUpload: false };
  90. this.rtmClient = new AgoraRTM.RTM(this.appid, this.userId, rtmConfig);
  91. this.joinReady();
  92. await this.loginRTM();
  93. // this.subscribeMessage(channelName);
  94. // this.publishMessage('user-online', channelName, 'USER'); //用户上线通知
  95. }
  96. /**@监听频道消息
  97. *@'USERCALLINVITATION': 用户通话邀请
  98. *@'CLOASEINVITATION': 取消通话邀请
  99. *@'REFUSEINVITATION_' + uid: 拒绝通话邀请
  100. *@'RESPONSEINVITOIN_' + uid: 接受邀请
  101. *@'USERGREETING_' + '': 问候
  102. */
  103. joinReady() {
  104. this.rtmClient?.addEventListener('message', async (event: any) => {
  105. console.log('接收到一条消息:', event);
  106. let states = [
  107. 'USERCALLINVITATION',
  108. 'REFUSEINVITATION_' + this.userId,
  109. 'REFUSEINVITATION_' + event.publisher,
  110. 'CLOASEINVITATION',
  111. 'RESPONSEINVITOIN_' + this.userId,
  112. 'RESPONSEINVITOIN_' + event.publisher,
  113. ];
  114. const message = JSON.parse(event.message);
  115. let is_self = event.publisher == this.userId;
  116. console.log('自己发出的消息:', is_self, message.text);
  117. if (
  118. states.includes(message.text) ||
  119. message.text.indexOf('ONUSERSENDGIFT_') > -1 ||
  120. message.text.indexOf('USERGREETING_') > -1
  121. ) {
  122. if (!is_self) {
  123. this.callPresence(message.text, event.publisher, event.channelName);
  124. }
  125. //呼出播放声音
  126. if (message.text == 'USERCALLINVITATION') {
  127. this.loopPlayAudio('mp3/call.mp3',true);
  128. } else if (message.text == 'CLOASEINVITATION') {
  129. if (this.audioPlayer) {
  130. this.audioPlayer.pause();
  131. this.audioPlayer.currentTime = 0;
  132. }
  133. }
  134. return;
  135. }
  136. this.showMessage(event);
  137. });
  138. this.rtmClient?.addEventListener('presence', (event: any) => {
  139. console.log('频道人员状态变化 ', event);
  140. let is_self = event.publisher == this.userId;
  141. //远端用户离开频道,主播在线状态
  142. if (
  143. !is_self &&
  144. event.eventType === 'REMOTE_LEAVE' &&
  145. event.channelName === this.userId
  146. ) {
  147. this.setConnectState(this.userId, 'ONLINE');
  148. }
  149. });
  150. this.rtmClient?.addEventListener('linkState', (event: any) => {
  151. console.log('连接状态: ', event);
  152. });
  153. }
  154. /* 设置频道状态 */
  155. async setConnectState(channelName: string, mode: string) {
  156. const channelType = 'MESSAGE';
  157. const states = {
  158. Mode: mode,
  159. };
  160. try {
  161. await this.rtmClient?.presence.setState(channelName, channelType, states);
  162. console.log('频道状态发生更改:', mode);
  163. } catch (err: any) {
  164. console.log(err);
  165. }
  166. }
  167. /* 呼叫事件 */
  168. async callPresence(message: string, publisher: string, channelName: string) {
  169. let userData = await this.getUserMetadata(publisher);
  170. console.log('向我发出事件用户:', userData);
  171. let toast;
  172. if (message.indexOf('ONUSERSENDGIFT_') > -1) {
  173. let arr = message.split('_');
  174. let gift = this.giftList.find((item: any) => item.id == arr[1]);
  175. // let r = await this.aiServ.getGift(undefined,arr[1])
  176. // let gift = r[0]
  177. this.giftLogMap.push({
  178. gift,
  179. count: arr?.[2],
  180. user: userData,
  181. });
  182. !this.isPlayer && setTimeout(() => {
  183. // this.playGift(this.giftLogMap.slice(-1)[0]);
  184. let obj = this.giftLogMap.slice(-1)[0]
  185. this.eventplay.next({
  186. video: obj.gift.video,
  187. config: obj.gift.config,
  188. });
  189. }, 0);
  190. return;
  191. }
  192. if (message.indexOf('USERGREETING_') > -1) {
  193. this.loopPlayAudio('mp3/message.mp3')
  194. let arr = message.split('_');
  195. this.alert = await this.alertController.create({
  196. cssClass: 'my-custom-class',
  197. header: '收到打招呼消息',
  198. message: `${userData?.nickname?.value ?? '未知用户'}:${arr[1]}`,
  199. backdropDismiss: false,
  200. buttons: [
  201. {
  202. text: '关闭',
  203. role: 'cancel',
  204. handler: async (blah) => {
  205. },
  206. },
  207. {
  208. text: '查看主页',
  209. cssClass: 'secondary',
  210. handler: async () => {
  211. this.router.navigate(['user/profile/' + publisher]);
  212. },
  213. },
  214. ],
  215. });
  216. await this.alert.present();
  217. return;
  218. }
  219. switch (message) {
  220. case 'USERCALLINVITATION':
  221. this.loopPlayAudio('mp3/call.mp3',true);
  222. await this.setConnectState(this.userId, 'CONNECTING');
  223. // console.log(`收到${userData?.nickname?.value ?? '未知用户'}通话邀请`);
  224. this.alert = await this.alertController.create({
  225. cssClass: 'my-custom-class',
  226. header: '通话邀请',
  227. message: `收到${userData?.nickname?.value ?? '未知用户'}通话邀请`,
  228. backdropDismiss: false,
  229. buttons: [
  230. {
  231. text: '拒绝',
  232. role: 'cancel',
  233. handler: async (blah) => {
  234. await this.setConnectState(this.userId, 'ONLINE');
  235. this.publishMessage(
  236. 'REFUSEINVITATION_' + publisher,
  237. channelName
  238. );
  239. // 停止播放音频
  240. if (this.audioPlayer) {
  241. this.audioPlayer.pause();
  242. this.audioPlayer.currentTime = 0;
  243. }
  244. },
  245. },
  246. {
  247. text: '接受',
  248. cssClass: 'secondary',
  249. handler: async () => {
  250. this.publishMessage(
  251. 'RESPONSEINVITOIN_' + publisher,
  252. channelName
  253. );
  254. let rid = await this.getRoom(this.userId);
  255. this.router.navigate(['live/link-room/' + rid]);
  256. // 停止播放音频
  257. if (this.audioPlayer) {
  258. this.audioPlayer.pause();
  259. this.audioPlayer.currentTime = 0;
  260. }
  261. },
  262. },
  263. ],
  264. });
  265. await this.alert.present();
  266. break;
  267. case 'CLOASEINVITATION':
  268. await this.setConnectState(this.userId, 'ONLINE');
  269. // console.log(`${userData?.nickname?.value ?? '未知用户'}取消通话`);
  270. this.alert?.dismiss();
  271. toast = await this.toastController.create({
  272. message: '对方已取消通话邀请',
  273. color: 'warning',
  274. duration: 1500,
  275. });
  276. toast.present();
  277. // 停止播放音频
  278. if (this.audioPlayer) {
  279. this.audioPlayer.pause();
  280. this.audioPlayer.currentTime = 0;
  281. }
  282. break;
  283. case 'REFUSEINVITATION_' + this.userId:
  284. // console.log(`${userData?.nickname?.value ?? '未知用户'}拒绝通话`);
  285. this.alert?.dismiss();
  286. this.eventSource.next(false);
  287. // 停止播放音频
  288. if (this.audioPlayer) {
  289. this.audioPlayer.pause();
  290. this.audioPlayer.currentTime = 0;
  291. }
  292. break;
  293. case 'RESPONSEINVITOIN_' + this.userId:
  294. // console.log(`${userData?.nickname?.value ?? '未知用户'}同意通话,进入视频通话`);
  295. this.alert?.dismiss();
  296. this.eventSource.next(true);
  297. // 停止播放音频
  298. if (this.audioPlayer) {
  299. this.audioPlayer.pause();
  300. this.audioPlayer.currentTime = 0;
  301. }
  302. break;
  303. }
  304. }
  305. // 礼物消息
  306. // showGiftDecrement() {
  307. // this.timeg = setTimeout(() => {
  308. // this.giftLogMap.shift();
  309. // if (this.giftLogMap.length > 0) {
  310. // this.showGiftDecrement();
  311. // } else {
  312. // clearTimeout(this.timeg);
  313. // this.timeg = null;
  314. // }
  315. // }, 5000);
  316. // }
  317. playGift(giftModule: any) {
  318. console.log(giftModule);
  319. this.isPlayer = true
  320. let dom = document.getElementById('vap-gift');
  321. console.log(dom);
  322. let vapPlayer = VapInit({
  323. container: dom, // 要渲染的载体,dom元素
  324. src: giftModule.gift?.video, // vap动画地址
  325. config: giftModule.gift?.config, // 播放vap动画需要的 json文件。必填
  326. width: window.innerWidth, // 容器宽度
  327. height: window.innerHeight, // 容器高度
  328. fps: 30, // 帧数,json文件中有这个视频的帧数的,可以看一下,
  329. mute: false, // 静音
  330. type: 1, // 组件基于type字段做了实例化缓存,不同的VAP实例应该使用不同的type值(如0、1、2等)
  331. loop: false, // 循环
  332. precache: true, // 预加载视频,下载完再播。小动画建议边下边播,大动画还是先下后播吧,因为太大了或者网络不好,会一卡一卡的。
  333. beginPoint: 0, // 起始播放时间点(单位秒),在一些浏览器中可能无效
  334. accurate: true, // 是否启用精准模式(使用requestVideoFrameCallback提升融合效果,浏览器不兼容时自动降级)
  335. });
  336. vapPlayer.play(); // 开始播放
  337. vapPlayer.on('ended', () => {
  338. // 监听播放完成的事件
  339. vapPlayer.destroy();
  340. vapPlayer = null;
  341. console.log('播放结束');
  342. this.giftLogMap.pop();
  343. if (this.giftLogMap.length > 0) {
  344. this.playGift(this.giftLogMap.slice(-1)[0]);
  345. } else {
  346. this.isPlayer = false
  347. }
  348. });
  349. vapPlayer.on('playering', function () { console.log('playering'); })
  350. }
  351. async getRoom(uid: string): Promise<string | undefined> {
  352. let query = new Parse.Query('Room');
  353. query.equalTo('company', this.company);
  354. query.equalTo('user', uid);
  355. query.notEqualTo('isDeleted', true);
  356. query.select('objectId');
  357. let r = await query.first();
  358. return r?.id;
  359. }
  360. /* 加入频道 */
  361. // async join(channelName: string) {
  362. // const options = {
  363. // token: this.options[channelName].token,
  364. // withPresence: true,
  365. // withLock: true,
  366. // withMetadata: true,
  367. // };
  368. // try {
  369. // const streamChannel =
  370. // this.rtmClientMap[channelName].rtmClient.createStreamChannel(
  371. // channelName
  372. // );
  373. // const result = await streamChannel.join(options);
  374. // } catch (status) {
  375. // console.error('join channel failed: ', status);
  376. // }
  377. // }
  378. async loginRTM() {
  379. try {
  380. await this.rtmClient?.login({
  381. token: this.options.token,
  382. });
  383. this.options.connectState = true; // 登录成功
  384. let userMateData = await this.getUserMetadata(this.userId);
  385. if (!userMateData?.nickname?.value || !userMateData?.avatar?.value) {
  386. let user = Parse.User.current();
  387. const metadata = [
  388. {
  389. key: 'nickname',
  390. value: user?.get('nickname') || user?.get('name') || user?.id,
  391. },
  392. {
  393. key: 'avatar',
  394. value:
  395. user?.get('avatar') ??
  396. 'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png',
  397. },
  398. ];
  399. const options = {
  400. userId: this.userId,
  401. addTimeStamp: true,
  402. addUserId: true,
  403. };
  404. let result = await this.rtmClient?.storage.setUserMetadata(
  405. metadata,
  406. options
  407. );
  408. console.log(JSON.stringify(result));
  409. }
  410. } catch (status) {
  411. console.log(status);
  412. }
  413. }
  414. logOutRTM() {
  415. this.rtmClient?.logout().then(() => {
  416. console.log('logout success');
  417. this.options.connectState = false;
  418. });
  419. }
  420. /* 订阅消息 */
  421. subscribeMessage(channelName: string, param?: any, deadline?: number): any {
  422. if (this.channelNameList[channelName]) { return };
  423. return new Promise((resolve, reject) => {
  424. const options = {
  425. withMessage: param?.message ?? false, // message 事件
  426. withPresence: param?.presence ?? false, // presence 事件
  427. beQuiet: false, // quiet 事件
  428. withMetadata: false, // metadata 事件
  429. withLock: false, // lock 事件
  430. };
  431. this.rtmClient
  432. ?.subscribe(channelName, options)
  433. .then((res: any) => {
  434. console.log('subscribeMessage', res);
  435. //订阅成功
  436. this.channelNameList[channelName] = true;
  437. if (!this.messageMapList[channelName]) {
  438. this.messageMapList[channelName] = [];
  439. if (channelName.indexOf('-') > -1 || channelName == 'global_room') {
  440. this.getHistoryMessage(channelName, deadline);
  441. }
  442. }
  443. this.pageFun?.();
  444. resolve(true);
  445. })
  446. .catch((err: any) => {
  447. console.error('subscribeMessageErr', err);
  448. resolve(false);
  449. });
  450. });
  451. }
  452. async getHistoryMessage(channelName: string, deadline?: number) {
  453. let query = new Parse.Query('MessageLog');
  454. query.equalTo('channel', channelName);
  455. query.descending('createdAt');
  456. query.skip(this.messageMapList[channelName].length);
  457. query.limit(50);
  458. query.select('content', 'from_id');
  459. deadline && query.greaterThanOrEqualTo('createdAt', new Date(deadline));
  460. let msgList = await query.find();
  461. console.log('历史消息:', msgList);
  462. msgList.forEach((item: any) => {
  463. let is_self = item?.get('from_id') == this.userId;
  464. let data: any = item?.get('content');
  465. data['is_self'] = is_self;
  466. data['istoday'] = true;
  467. data['timestamp'] = new Date(data.timestamp);
  468. this.messageMapList[channelName].unshift(data);
  469. });
  470. // this.messageMapList[channelName].unshift(...msgList);
  471. }
  472. /* 取消订阅 */
  473. unsubscribeMessage(channelName: string) {
  474. this.rtmClient
  475. ?.unsubscribe(channelName)
  476. .then((res: any) => {
  477. console.log('unsubscribeMessage', res);
  478. //订阅成功
  479. this.channelNameList[channelName] = false;
  480. })
  481. .catch((err: any) => {
  482. console.error('unsubscribeMessage', err);
  483. });
  484. }
  485. async showMessage(param: any) {
  486. let userData = await this.getUserMetadata(param.publisher);
  487. let is_self = param.publisher == this.userId;
  488. // console.log(userData);
  489. let message = JSON.parse(param.message);
  490. if (!this.messageMapList[param.channelName])
  491. this.messageMapList[param.channelName] = [];
  492. if (is_self) {
  493. this.saveMeesage({
  494. from_id: this.userId,
  495. from_username: Parse.User.current()?.get('nickname') ?? '未知用户',
  496. target_id: param.channelName,
  497. // target_name: userData?.nickname?.value ?? '未知用户',
  498. channel: param.channelName,
  499. content: {
  500. avatar:
  501. userData?.avatar?.value ??
  502. 'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png',
  503. msg_type: 1,
  504. name: userData?.nickname?.value ?? '未知用户',
  505. content: message?.text ?? '',
  506. publisher: param.publisher,
  507. timestamp: param.timestamp,
  508. },
  509. });
  510. }
  511. let data: any = {
  512. is_self: is_self,
  513. avatar:
  514. userData?.avatar?.value ??
  515. 'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png',
  516. msg_type: 1,
  517. name: userData?.nickname?.value ?? '未知用户',
  518. content: message?.text ?? '',
  519. publisher: param.publisher,
  520. timestamp: new Date(param.timestamp),
  521. istoday: true,
  522. };
  523. this.messageMapList[param.channelName].push(data);
  524. this.pageFun?.();
  525. }
  526. async saveMeesage(parse: {
  527. from_id: string;
  528. from_username: string;
  529. target_id: string;
  530. // target_name: string;
  531. channel: string;
  532. content: Object;
  533. }) {
  534. console.log(parse);
  535. let obj = Parse.Object.extend('MessageLog');
  536. let message = new obj();
  537. message.set('from_id', parse.from_id);
  538. message.set('from_username', parse.from_username);
  539. message.set('target_id', parse.target_id);
  540. // message.set('target_name', parse.target_name);
  541. message.set('channel', parse.channel);
  542. message.set('content', parse.content);
  543. message.set('company', {
  544. __type: 'Pointer',
  545. className: 'Company',
  546. objectId: this.company,
  547. });
  548. await message.save();
  549. }
  550. async getUserMetadata(uid: string) {
  551. try {
  552. const result = await this.rtmClient?.storage.getUserMetadata({
  553. userId: uid,
  554. });
  555. return result.metadata;
  556. } catch (status) {
  557. console.log(JSON.stringify(status));
  558. }
  559. }
  560. async publishMessage(
  561. message: string,
  562. channelName: string,
  563. channelType?: string
  564. ) {
  565. const payload = { type: 'text', text: message };
  566. const publishMessage = JSON.stringify(payload);
  567. const publishOptions = { channelType: channelType ?? 'MESSAGE' };
  568. try {
  569. const result = await this.rtmClient?.publish(
  570. channelName,
  571. publishMessage,
  572. publishOptions
  573. );
  574. console.log('发出消息:', result);
  575. } catch (status) {
  576. console.log('发出消息失败:', status);
  577. }
  578. }
  579. delMsg(channelName: string, index?: number, limit?: number) {
  580. this.messageMapList[channelName].splice(
  581. index ?? 0,
  582. limit ?? this.messageMapList[channelName].length
  583. );
  584. console.log(this.messageMapList[channelName]);
  585. }
  586. }