connectTask.service.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { Injectable } from '@angular/core';
  2. import { MessageService } from './message.service';
  3. import * as Parse from 'parse';
  4. import { AiChatService } from './aichart.service';
  5. @Injectable({
  6. providedIn: 'root',
  7. })
  8. export class ConnectTaskService {
  9. anchorChannelName?: string;
  10. msChannelName: string = 'user_connect_room'; // 主播在线上报频道
  11. onlineUserList = new Set(); // 在线用户列表
  12. isSubscribe: boolean = false;
  13. constructor(private msgSer: MessageService, private aiSer: AiChatService) {}
  14. async init() {
  15. // 初始化消息服务,所有用户静默登录
  16. await this.msgSer.initRTM();
  17. await this.anchorOnline();
  18. this.getOnlieUserList(this.msChannelName, 'MESSAGE');
  19. this.conncetChannels();
  20. }
  21. reset() {
  22. this.onlineUserList = new Set();
  23. this.isSubscribe = false;
  24. }
  25. /* 主播上线 */
  26. async anchorOnline() {
  27. let profile;
  28. try {
  29. profile = JSON.parse(localStorage.getItem('profile') || '');
  30. } catch (err) {
  31. console.log('profile err', err);
  32. }
  33. const uid = Parse.User.current()?.id!;
  34. let nowChannes = await this.getWhereNow(uid);
  35. console.log('用户已订阅频道:', nowChannes);
  36. await this.msgSer.setConnectState(uid, 'ONLINE'); //主播开启并订阅自己的聊天频道
  37. if (profile?.identyType == 'anchor' && !this.isSubscribe) {
  38. // if (!nowChannes.includes(this.msChannelName)) {
  39. console.log('订阅成功');
  40. /* 主播订阅主播频道 */
  41. await this.msgSer.subscribeMessage(this.msChannelName);
  42. // }
  43. // if (!nowChannes.includes(uid)) {
  44. await this.msgSer.subscribeMessage(uid, {
  45. //开启并订阅自己的聊天频道
  46. message: true,
  47. presence: true,
  48. });
  49. // }
  50. this.isSubscribe = true;
  51. }else{
  52. await this.msgSer.subscribeMessage(uid, {
  53. //开启自己聊天频道用来接受招呼消息
  54. message: true,
  55. // presence: true,
  56. });
  57. }
  58. }
  59. /* 订阅好友频道 */
  60. async conncetChannels() {
  61. let uid: any = Parse.User.current()?.id;
  62. let resultFriends = await this.aiSer.getFriends(uid);
  63. resultFriends?.data?.forEach(async (item: any) => {
  64. let channelName = item.channel;
  65. await this.msgSer.subscribeMessage(
  66. channelName,
  67. {
  68. message: true,
  69. },
  70. item.deadline
  71. );
  72. });
  73. }
  74. /* 获取用户当前所在频道 */
  75. async getWhereNow(userId: string): Promise<Array<string>> {
  76. let channes: Array<string> = [];
  77. try {
  78. const whereNowResult = await this.msgSer.rtmClient.presence.whereNow(
  79. userId
  80. );
  81. const { channels, totalChannel } = whereNowResult;
  82. channels.forEach((channelInfo: any) => {
  83. const { channelName, channelType } = channelInfo;
  84. channes.push(channelName);
  85. });
  86. return channes;
  87. } catch (status: any) {
  88. const { operation, reason, errorCode } = status;
  89. console.error(
  90. `${operation} failed, the error code is ${errorCode}, because of: ${reason}.`
  91. );
  92. return [];
  93. }
  94. }
  95. /* 获取状态 */
  96. async getState(uid: string, channelName: string, channelType?: string) {
  97. try {
  98. const result = await this.msgSer.rtmClient.presence.getState(
  99. uid,
  100. channelName,
  101. channelType ?? 'MESSAGE'
  102. );
  103. const { states, userId, statesCount } = result; // Tony 的临时状态
  104. console.log(`${userId}用户状态:${states.Mode}`);
  105. // console.log(result);
  106. return states.Mode;
  107. } catch (status: any) {
  108. const { operation, reason, errorCode } = status;
  109. console.log(
  110. `${operation} failed, ErrorCode: ${errorCode}, because of: ${reason}.`
  111. );
  112. return 'OFFLINE';
  113. }
  114. }
  115. /* 获取在线用户列表 */
  116. async getOnlieUserList(
  117. channelName: string,
  118. page?: string,
  119. channelType?: string
  120. ) {
  121. if (!channelType && this.onlineUserList.size) return;
  122. const options: any = {
  123. includedUserId: true,
  124. includedState: true,
  125. };
  126. if (page) options.page = page;
  127. try {
  128. const result = await this.msgSer?.rtmClient?.presence?.whoNow(
  129. channelName,
  130. channelType ?? 'MESSAGE',
  131. options
  132. );
  133. // console.log(result);
  134. // 如果 nextPage 存在,下一次调用 whoNow 时,需将 nextPage 的值填入 whoNowOptions 的 page 字段
  135. let totalOccupancy = result?.totalOccupancy;
  136. let occupants = result?.occupants;
  137. let nextPage = result?.nextPage;
  138. occupants?.forEach((userInfo: any) => {
  139. const { states, userId, statesCount } = userInfo;
  140. this.onlineUserList.add(userId);
  141. });
  142. console.log('获取在线用户列表:', this.onlineUserList);
  143. if (nextPage) this.getOnlieUserList(channelName, nextPage, channelType);
  144. } catch (status: any) {
  145. // const { operation, reason, errorCode } = status;
  146. console.error('getOnlieUserList err', status);
  147. // console.error(
  148. // `${operation} failed, ErrorCode: ${errorCode}, due to: ${reason}.`
  149. // );
  150. }
  151. }
  152. }