message.service.ts 13 KB

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