UNPKG

zby-live-sdk

Version:

This is a live SDK for weclassroom.

197 lines (186 loc) 6.74 kB
import pomeloClient from './polemo'; import dealReceiveStreamMsg from '../stream-msg'; import defaultApi from '../../default/extend'; import util from '../../util/util'; import polemoUtil from './util'; import zbysdk from '../../zby-live-sdk'; import dataReport from '../../network/dataReport'; import {getApiCloudBaseUrl} from '../../config/config.js'; let sendMsgCheckIntervalTimer = null; let sendMsgCheckIntervalTime = 3000; const pomeloObj = { isInRoom: false, sendMsgCacheList: {}, sendMsgCheckList: {}, sendMsgIndex: 0, initParams: null, async joinRoom(args, cb) { if (!args) { return; } this.log('channel_log : start joining pomelo ......'); const { userId, roomId, chatUrl, userName, role, institutionId, guid} = args; const _args = { userId, roomId, host: chatUrl, userName, institutionId, guid, role: polemoUtil.translateRole(role) }; this.log(`joinRoom: args: ${JSON.stringify(_args)}`); this.initParams = _args; // 定时检查发送消息列表 // this.checkSendMsgList(); const res = await pomeloClient.joinRoom({ ..._args, roomId: util.getConfId(institutionId, roomId) }, dealCb); // 加入房间成功 if (res.code === 200) { this.log('joinRoom success'); this.isInRoom = true; await this.checkFailedAndCacheMSg(); this.checkSendMsgList(); } else { this.log('joinRoom failed'); dataReport.pomeloState({state: 2, desc: 'joinRoom failed'}); } try { dataReport.joinRoomResult({ code: res.code === 200 ? '0' : '3', // cloud_api_response: JSON.stringify(window.zby_sdk_cloud_data), cloud_api_response: window.zby_sdk_cloud_data, cloud_api_url: `${getApiCloudBaseUrl()}/rtccloud/class/init`, chat_url: chatUrl }); } catch (e) {}; }, // 离开房间重置所有变量 leaveRoom() { this.log('leaveRoom'); this.isInRoom = false; this.sendMsgCacheList = {}; sendMsgCheckIntervalTimer = null; pomeloClient.disconnect(); }, async sendChannelMsg(data) { const currTime = new Date().getTime(); // 记录缓存列表 this.sendMsgIndex++; const { role, userId } = this.initParams; const params = { type: 'streamMessage', online_trace_id: `pc${util.firstUpperCase(role)}${util.uuid()}`, body: JSON.stringify({ message: JSON.stringify(data), trace_id: `sdk_1.0_${(currTime).toString().padStart(16, '123456')}`, index: this.sendMsgIndex, save: '0', targetid: data.targetId, mtype: 'stream', uuid: `${userId}_2_${this.sendMsgIndex}_${currTime}` }), }; if (this.isInRoom) { // 加入房间成功直接发送消息 const res = await this.sendChannelMsgInner(params, data.target || '*'); if (res.code !== 200) { this.sendMsgCheckList[params.online_trace_id] = params; } } else { // 为加入房间成功先缓存消息队列 this.cacheSendChannelMsg(params, data.target); } }, // 缓存消息队列 cacheSendChannelMsg(data, target) { const len = Object.keys(this.sendMsgCacheList).length; // 大于100条不再缓存 if (len > 100) { return; } this.sendMsgCacheList[data.online_trace_id] = { data, target }; }, // 发送消息 async sendChannelMsgInner(data, target = '*') { this.log(`sendChannelMsgInner: data: ${JSON.stringify(data)}, target: ${target}`); try { dataReport.pomeloSendMsg({api:data.body.api,data:{...data,body:JSON.parse(data.body)},target}); } catch(e) { defaultApi.writeLog(`pomeloSendMsg_error ${JSON.stringify(e)}`, null, 'error'); } if (this.isInRoom && !this.checkSocketConnected()) { this.joinRoom(this.initParams); return { code: 500, message: 'Socket not connected' }; } return pomeloClient.sendChannelMessage(data, target); }, checkSocketConnected() { if (pomeloClient && pomeloClient.socket && (pomeloClient.socket.readyState === pomeloClient.socket.OPEN)) { return true; } else { return false; } }, // 遍历失败和缓存消息 async checkFailedAndCacheMSg() { // 遍历失败消息 const len = Object.keys(this.sendMsgCheckList).length; if (len > 0) { this.log(`checkSendMsgList-sendMsgCheckList :${JSON.stringify(this.sendMsgCheckList)}`); for(let index in this.sendMsgCheckList) { const msg = this.sendMsgCheckList[index]; const res = await this.sendChannelMsgInner(msg.data, msg.target); if (res.code === 200) { delete this.sendMsgCheckList[index]; } } } // 遍历缓存消息 const len1 = Object.keys(this.sendMsgCacheList).length; if (len1 > 0) { this.log(`checkSendMsgList-sendMsgCacheList :${JSON.stringify(this.sendMsgCacheList)}`); for(let index in this.sendMsgCacheList) { const msg = this.sendMsgCacheList[index]; const res = await this.sendChannelMsgInner(msg.data, msg.target); if (res.code === 200) { delete this.sendMsgCacheList[index]; } } } }, // 定时检查缓存队列 async checkSendMsgList() { sendMsgCheckIntervalTimer = setInterval(async () => { if (!this.isInRoom) { return false; } this.checkFailedAndCacheMSg(); }, sendMsgCheckIntervalTime); }, log(msg) { defaultApi.writeLog(msg, 'channel-pomelo'); } }; function dealCb(msg) { try { const body = JSON.parse(msg.body); // 收发消息 if (msg.type === 'streamMessage') { const { roomId, userId, userName, institutionId, role } = pomeloObj.initParams; const baseInfo = { roomId, userId, userName, institutionId, role: polemoUtil.translateRole('', role), target: msg.from }; const message = {...JSON.parse(body.message), ...body}; dealReceiveStreamMsg(message, baseInfo); } // 切换sdk if (msg.type === 'streamsdk') { defaultApi.writeLog(`change sdk signal received: ${body.data}, current: ${window.current_sdk_type}`); if (body.data === 'talrtc' || window.current_sdk_type !== body.data) { zbysdk.changeSDK(); } else { defaultApi.writeLog(`change sdk signal received: ${body.data}, same with current sdk, ignore.`); } } } catch (error) { const msg = error instanceof Error ? error.message : JSON.stringify(error); defaultApi.writeLog(`dealCb error: ${msg}`, null, 'error'); } } export default pomeloObj;