message.service.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. @Injectable({
  11. providedIn: 'root',
  12. })
  13. export class MessageService {
  14. private eventSource = new Subject<any>();
  15. event$ = this.eventSource.asObservable();
  16. company: string = 'Qje9D4bqol';
  17. rtmClient: any; // RTM实例
  18. // rtmClientMap: any = {};
  19. channelNameList: any = {}; //订阅频道状态
  20. msChannelName: string = 'global_room'; // 全球频道
  21. options: any = {
  22. connectState: false,
  23. };
  24. appid?: string;
  25. userId: string = Parse.User.current()?.id!;
  26. pageFun?: Function; //页面传入的方法
  27. alert: any; // 弹窗
  28. messageMapList: any = {};
  29. giftLogMap: any = [];
  30. giftList: Array<any> = [];//礼物列表
  31. timeg:any
  32. constructor(
  33. private alertController: AlertController,
  34. private router: Router,
  35. public toastController: ToastController,
  36. private http: HttpService,
  37. private aiServ: AiChatService
  38. ) {
  39. this.aiServ.getGift().then((data) => (this.giftList = data));
  40. }
  41. /* 获取token */
  42. async getToken() {
  43. this.userId = Parse.User.current()?.id!;
  44. //获取频道token记录
  45. let uid = Parse.User.current()?.id;
  46. let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
  47. let reqBody = {
  48. company: this.company,
  49. channelName: this.msChannelName,
  50. type: 'withrtm',
  51. account: uid,
  52. };
  53. let data: any = await this.http.httpRequst(baseurl, reqBody, 'POST');
  54. console.log(data);
  55. if (data.code == 200) {
  56. // this.options[channel] = {
  57. // token: data.data.token,
  58. // };
  59. this.options.token = data.data.token;
  60. this.appid = data.data.appid;
  61. }
  62. }
  63. async initRTM() {
  64. // let states = ['CONNECTED', 'CONNECTING'];
  65. if (this.options.connectState) return;
  66. await this.getToken();
  67. const rtmConfig = { logLevel: 'INFO', logUpload: false };
  68. this.rtmClient = new AgoraRTM.RTM(this.appid, this.userId, rtmConfig);
  69. this.joinReady();
  70. await this.loginRTM();
  71. // this.subscribeMessage(channelName);
  72. // this.publishMessage('user-online', channelName, 'USER'); //用户上线通知
  73. }
  74. /**@监听频道消息
  75. *@'USERCALLINVITATION': 用户通话邀请
  76. *@'CLOASEINVITATION': 取消通话邀请
  77. *@'REFUSEINVITATION_' + uid: 拒绝通话邀请
  78. *@'RESPONSEINVITOIN_' + uid: 接受邀请
  79. */
  80. joinReady() {
  81. this.rtmClient?.addEventListener('message', async (event: any) => {
  82. console.log('接收到一条消息:', event);
  83. let states = [
  84. 'USERCALLINVITATION',
  85. 'REFUSEINVITATION_' + this.userId,
  86. 'REFUSEINVITATION_' + event.publisher,
  87. 'CLOASEINVITATION',
  88. 'RESPONSEINVITOIN_' + this.userId,
  89. 'RESPONSEINVITOIN_' + event.publisher,
  90. ];
  91. const message = JSON.parse(event.message);
  92. let is_self = event.publisher == this.userId;
  93. console.log('自己发出的消息:', is_self, message.text);
  94. if (states.includes(message.text) || message.text.indexOf('ONUSERSENDGIFT_') > -1) {
  95. if (!is_self) {
  96. this.callPresence(message.text, event.publisher, event.channelName);
  97. }
  98. return;
  99. }
  100. this.showMessage(event);
  101. });
  102. this.rtmClient?.addEventListener('presence', (event: any) => {
  103. console.log('频道人员状态变化 ', event);
  104. let is_self = event.publisher == this.userId;
  105. //远端用户离开频道,主播在线状态
  106. if (
  107. !is_self &&
  108. event.eventType === 'REMOTE_LEAVE' &&
  109. event.channelName === this.userId
  110. ) {
  111. this.setConnectState(this.userId, 'ONLINE');
  112. }
  113. });
  114. this.rtmClient?.addEventListener('linkState', (event: any) => {
  115. console.log('连接状态: ', event);
  116. });
  117. }
  118. /* 设置频道状态 */
  119. async setConnectState(channelName: string, mode: string) {
  120. const channelType = 'MESSAGE';
  121. const states = {
  122. Mode: mode,
  123. };
  124. try {
  125. await this.rtmClient?.presence.setState(channelName, channelType, states);
  126. console.log('频道状态发生更改:', mode);
  127. } catch (err: any) {
  128. console.log(err);
  129. }
  130. }
  131. /* 呼叫事件 */
  132. async callPresence(message: string, publisher: string, channelName: string) {
  133. let userData = await this.getUserMetadata(publisher);
  134. console.log('发出消息用户:',userData);
  135. let toast;
  136. if(message.indexOf('ONUSERSENDGIFT_') > -1){
  137. let arr = message.split('_')
  138. let gift = this.giftList.find((item: any) => item.id == arr[1]);
  139. this.giftLogMap.push({
  140. gift,
  141. count:arr?.[2],
  142. user:userData
  143. })
  144. !this.timeg && this.showGiftDecrement()
  145. return
  146. }
  147. switch (message) {
  148. case 'USERCALLINVITATION':
  149. await this.setConnectState(this.userId, 'CONNECTING');
  150. console.log(`收到${userData?.nickname?.value ?? '未知用户'}通话邀请`);
  151. this.alert = await this.alertController.create({
  152. cssClass: 'my-custom-class',
  153. header: '通话邀请',
  154. message: `收到${userData?.nickname?.value ?? '未知用户'}通话邀请`,
  155. backdropDismiss: false,
  156. buttons: [
  157. {
  158. text: '拒绝',
  159. role: 'cancel',
  160. handler: async (blah) => {
  161. await this.setConnectState(this.userId, 'ONLINE');
  162. this.publishMessage(
  163. 'REFUSEINVITATION_' + publisher,
  164. channelName
  165. );
  166. },
  167. },
  168. {
  169. text: '接受',
  170. cssClass: 'secondary',
  171. handler: async () => {
  172. this.publishMessage(
  173. 'RESPONSEINVITOIN_' + publisher,
  174. channelName
  175. );
  176. let rid = await this.getRoom(this.userId);
  177. this.router.navigate(['live/link-room/' + rid]);
  178. },
  179. },
  180. ],
  181. });
  182. await this.alert.present();
  183. break;
  184. case 'CLOASEINVITATION':
  185. await this.setConnectState(this.userId, 'ONLINE');
  186. console.log(`${userData?.nickname?.value ?? '未知用户'}取消通话`);
  187. this.alert?.dismiss();
  188. toast = await this.toastController.create({
  189. message: '对方已取消通话邀请',
  190. color: 'warning',
  191. duration: 1500,
  192. });
  193. toast.present();
  194. break;
  195. case 'REFUSEINVITATION_' + this.userId:
  196. console.log(`${userData?.nickname?.value ?? '未知用户'}拒绝通话`);
  197. this.alert?.dismiss();
  198. this.eventSource.next(false);
  199. break;
  200. case 'RESPONSEINVITOIN_' + this.userId:
  201. console.log(
  202. `${userData?.nickname?.value ?? '未知用户'}同意通话,进入视频通话`
  203. );
  204. this.alert?.dismiss();
  205. this.eventSource.next(true);
  206. break;
  207. }
  208. }
  209. // 礼物消息
  210. showGiftDecrement(){
  211. this.timeg = setTimeout(() => {
  212. this.giftLogMap.shift();
  213. if(this.giftLogMap.length > 0){
  214. this.showGiftDecrement();
  215. }else{
  216. clearTimeout(this.timeg);
  217. this.timeg = null
  218. }
  219. }, 5000);
  220. }
  221. async getRoom(uid: string): Promise<string | undefined> {
  222. let query = new Parse.Query('Room');
  223. query.equalTo('company', this.company);
  224. query.equalTo('user', uid);
  225. query.notEqualTo('isDeleted', true);
  226. query.select('objectId');
  227. let r = await query.first();
  228. return r?.id;
  229. }
  230. /* 加入频道 */
  231. // async join(channelName: string) {
  232. // const options = {
  233. // token: this.options[channelName].token,
  234. // withPresence: true,
  235. // withLock: true,
  236. // withMetadata: true,
  237. // };
  238. // try {
  239. // const streamChannel =
  240. // this.rtmClientMap[channelName].rtmClient.createStreamChannel(
  241. // channelName
  242. // );
  243. // const result = await streamChannel.join(options);
  244. // } catch (status) {
  245. // console.error('join channel failed: ', status);
  246. // }
  247. // }
  248. async loginRTM() {
  249. try {
  250. await this.rtmClient?.login({
  251. token: this.options.token,
  252. });
  253. this.options.connectState = true; // 登录成功
  254. let userMateData = await this.getUserMetadata(this.userId);
  255. if (!userMateData?.nickname?.value || !userMateData?.avatar?.value) {
  256. let user = Parse.User.current();
  257. const metadata = [
  258. {
  259. key: 'nickname',
  260. value: user?.get('nickname') || user?.get('name') || user?.id,
  261. },
  262. {
  263. key: 'avatar',
  264. value:
  265. user?.get('avatar') ??
  266. 'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png',
  267. },
  268. ];
  269. const options = {
  270. userId: this.userId,
  271. addTimeStamp: true,
  272. addUserId: true,
  273. };
  274. let result = await this.rtmClient?.storage.setUserMetadata(
  275. metadata,
  276. options
  277. );
  278. console.log(JSON.stringify(result));
  279. }
  280. } catch (status) {
  281. console.log(status);
  282. }
  283. }
  284. logOutRTM() {
  285. this.rtmClient?.logout().then(() => {
  286. console.log('logout success');
  287. this.options.connectState = false;
  288. });
  289. }
  290. /* 订阅消息 */
  291. subscribeMessage(channelName: string, param?: any,deadline?: number) {
  292. if (this.channelNameList[channelName]) return;
  293. return new Promise((resolve, reject) => {
  294. const options = {
  295. withMessage: param?.message ?? false, // message 事件
  296. withPresence: param?.presence ?? false, // presence 事件
  297. beQuiet: false, // quiet 事件
  298. withMetadata: false, // metadata 事件
  299. withLock: false, // lock 事件
  300. };
  301. this.rtmClient
  302. ?.subscribe(channelName, options)
  303. .then((res: any) => {
  304. console.log('subscribeMessage', res);
  305. //订阅成功
  306. this.channelNameList[channelName] = true;
  307. if (!this.messageMapList[channelName]) {
  308. this.messageMapList[channelName] = [];
  309. if(channelName.indexOf('-') > -1 || channelName == 'global_room'){
  310. this.getHistoryMessage(channelName,deadline);
  311. }
  312. }
  313. this.pageFun?.();
  314. resolve(true);
  315. })
  316. .catch((err: any) => {
  317. console.error('subscribeMessageErr', err);
  318. resolve(false);
  319. });
  320. });
  321. }
  322. async getHistoryMessage(channelName: string,deadline?:number) {
  323. let query = new Parse.Query('MessageLog');
  324. query.equalTo('channel', channelName);
  325. query.descending('createdAt');
  326. query.skip(this.messageMapList[channelName].length);
  327. query.limit(50);
  328. query.select('content', 'from_id');
  329. deadline && query.greaterThanOrEqualTo('createdAt', new Date(deadline));
  330. let msgList = await query.find();
  331. console.log('历史消息:', msgList);
  332. msgList.forEach((item: any) => {
  333. let is_self = item?.get('from_id') == this.userId;
  334. let data: any = item?.get('content');
  335. data['is_self'] = is_self;
  336. data['istoday'] = true;
  337. data['timestamp'] = new Date(data.timestamp);
  338. this.messageMapList[channelName].unshift(data);
  339. });
  340. // this.messageMapList[channelName].unshift(...msgList);
  341. }
  342. /* 取消订阅 */
  343. unsubscribeMessage(channelName: string) {
  344. this.rtmClient
  345. ?.unsubscribe(channelName)
  346. .then((res: any) => {
  347. console.log('unsubscribeMessage', res);
  348. //订阅成功
  349. this.channelNameList[channelName] = false;
  350. })
  351. .catch((err: any) => {
  352. console.error('unsubscribeMessage', err);
  353. });
  354. }
  355. async showMessage(param: any) {
  356. let userData = await this.getUserMetadata(param.publisher);
  357. let is_self = param.publisher == this.userId;
  358. // console.log(userData);
  359. let message = JSON.parse(param.message);
  360. if (!this.messageMapList[param.channelName])
  361. this.messageMapList[param.channelName] = [];
  362. if (is_self) {
  363. this.saveMeesage({
  364. from_id: this.userId,
  365. from_username: Parse.User.current()?.get('nickname') ?? '未知用户',
  366. target_id: param.channelName,
  367. // target_name: userData?.nickname?.value ?? '未知用户',
  368. channel: param.channelName,
  369. content: {
  370. avatar:
  371. userData?.avatar?.value ??
  372. 'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png',
  373. msg_type: 1,
  374. name: userData?.nickname?.value ?? '未知用户',
  375. content: message?.text ?? '',
  376. publisher: param.publisher,
  377. timestamp: param.timestamp,
  378. },
  379. });
  380. }
  381. let data: any = {
  382. is_self: is_self,
  383. avatar:
  384. userData?.avatar?.value ??
  385. 'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png',
  386. msg_type: 1,
  387. name: userData?.nickname?.value ?? '未知用户',
  388. content: message?.text ?? '',
  389. publisher: param.publisher,
  390. timestamp: new Date(param.timestamp),
  391. istoday: true,
  392. };
  393. this.messageMapList[param.channelName].push(data);
  394. this.pageFun?.();
  395. }
  396. async saveMeesage(parse: {
  397. from_id: string;
  398. from_username: string;
  399. target_id: string;
  400. // target_name: string;
  401. channel: string;
  402. content: Object;
  403. }) {
  404. console.log(parse);
  405. let obj = Parse.Object.extend('MessageLog');
  406. let message = new obj();
  407. message.set('from_id', parse.from_id);
  408. message.set('from_username', parse.from_username);
  409. message.set('target_id', parse.target_id);
  410. // message.set('target_name', parse.target_name);
  411. message.set('channel', parse.channel);
  412. message.set('content', parse.content);
  413. message.set('company', {
  414. __type: 'Pointer',
  415. className: 'Company',
  416. objectId: this.company,
  417. });
  418. await message.save();
  419. }
  420. async getUserMetadata(uid: string) {
  421. try {
  422. const result = await this.rtmClient?.storage.getUserMetadata({
  423. userId: uid,
  424. });
  425. return result.metadata;
  426. } catch (status) {
  427. console.log(JSON.stringify(status));
  428. }
  429. }
  430. async publishMessage(
  431. message: string,
  432. channelName: string,
  433. channelType?: string
  434. ) {
  435. const payload = { type: 'text', text: message };
  436. const publishMessage = JSON.stringify(payload);
  437. const publishOptions = { channelType: channelType ?? 'MESSAGE' };
  438. try {
  439. const result = await this.rtmClient?.publish(
  440. channelName,
  441. publishMessage,
  442. publishOptions
  443. );
  444. console.log('发出消息:', result);
  445. } catch (status) {
  446. console.log('发出消息失败:', status);
  447. }
  448. }
  449. delMsg(channelName: string, index?: number,limit?: number) {
  450. this.messageMapList[channelName].splice(index ?? 0, limit ?? this.messageMapList[channelName].length);
  451. console.log(this.messageMapList[channelName]);
  452. }
  453. }