import { Injectable } from '@angular/core'; import { MessageService } from './message.service'; import * as Parse from 'parse'; @Injectable({ providedIn: 'root', }) export class ConnectTaskService { anchorChannelName?: string; msChannelName: string = 'user_connect_room'; // 主播在线上报频道 onlineUserList: Array = []; // 在线用户列表 isSubscribe: boolean = false; constructor(private msgSer: MessageService) {} async init() { // 初始化消息服务,所有用户静默登录 await this.msgSer.initRTM(this.msChannelName); await this.anchorOnline(); this.getOnlieUserList(this.msChannelName, 'MESSAGE'); } reset(){ this.onlineUserList = []; this.isSubscribe = false; } /* 主播上线 */ async anchorOnline() { let profile = JSON.parse(localStorage.getItem('profile') || ''); const uid = Parse.User.current()?.id!; if (profile?.identyType == 'anchor' && !this.isSubscribe) { let nowChannes = await this.getWhereNow(uid); console.log('用户已订阅频道:', nowChannes); // if (!nowChannes.includes(this.msChannelName)) { console.log('订阅成功'); /* 主播订阅主播频道 */ this.msgSer.subscribeMessage(this.msChannelName); //主播开启并订阅自己的聊天频道 // } // if (!nowChannes.includes(uid)) { this.msgSer.subscribeMessage(uid, { message: true }); //开启并订阅自己的聊天频道 // } } } /* 获取用户当前所在频道 */ async getWhereNow(userId: string): Promise> { let channes: Array = []; try { const whereNowResult = await this.msgSer.rtmClient.presence.whereNow( userId ); const { channels, totalChannel } = whereNowResult; channels.forEach((channelInfo: any) => { const { channelName, channelType } = channelInfo; channes.push(channelName); }); return channes; } catch (status: any) { const { operation, reason, errorCode } = status; console.error( `${operation} failed, the error code is ${errorCode}, because of: ${reason}.` ); return []; } } /* 获取在线用户列表 */ async getOnlieUserList( channelName: string, page?: string, channelType?: string ) { if (this.onlineUserList.length > 0) return; console.log('获取在线用户列表'); const options: any = { includedUserId: true, includedState: true, }; if(page) options.page = page; try { const result = await this.msgSer.rtmClient.presence.whoNow( channelName, channelType ?? 'MESSAGE', options ); // console.log(result); // 如果 nextPage 存在,下一次调用 whoNow 时,需将 nextPage 的值填入 whoNowOptions 的 page 字段 const { totalOccupancy, occupants, nextPage } = result; occupants.forEach((userInfo: any) => { const { states, userId, statesCount } = userInfo; this.onlineUserList.push(userId); }); if (nextPage) this.getOnlieUserList(channelName, nextPage, channelType); } catch (status: any) { const { operation, reason, errorCode } = status; console.error( `${operation} failed, ErrorCode: ${errorCode}, due to: ${reason}.` ); } } }