UNPKG

zby-live-sdk

Version:

This is a live SDK for weclassroom.

312 lines (301 loc) 8.93 kB
import MD5 from 'md5'; import sha256 from './sha256.js'; import { getNetworkTimestampApi } from '../network/api'; export default { // timestamp : 0, // diffTime : 0, /** * run the callback unitl checkFlag return true * @param {function | boolean} checkFlag * @param {function} callback * @param {*} param */ waitFlagToRun(checkFlag, callback, param, options, count=1) { /** * options * { repeatTimes : 重试次数限制 * interval : 间隔时间,默认 100ms * } * */ if(options && options.repeatTimes && (count > options.repeatTimes)) return; if (checkFlag()) { callback(param); return; } else { const interval = options && options.timer ? options.timer : 100; setTimeout(() => { this.waitFlagToRun(checkFlag, callback, param, options, count+1); }, interval); } }, /** * query字符串参数排序 * */ queryStringSort(param) { return param.split('&').sort().join('&'); }, /** * 生成签名相关 */ getVerifySign(param, saultKey='7qIdL2kdYQzecQJplq8QXfzpolOgUGOM') { //按照api要求,进行混合saultKey二次MD5处理 if(typeof param == 'string') { return MD5( MD5(this.queryStringSort(param) + saultKey)); } else if (typeof param == 'object') { let arr = []; for (var key in param) { arr.push((key + '=' + param[key])); } let sortedQueryString = this.queryStringSort(arr.join('&')); return MD5( MD5(sortedQueryString) + saultKey); } }, //根据值反查字典表中的键名 getMapKeyByValue(map, value) { for (let item of map) { if (map.get(item[0]) === value) { return item[0]; } } }, uuid() { var s = []; var hexDigits = '0123456789abcdef'; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = '4'; s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); s[8] = s[13] = s[18] = s[23] = '-'; var uuid = s.join(''); return uuid; }, getVerifySign1() { const appId = '1002'; const key = 'OmAIqyYz0U1/guuFo4GH6nVGNVFeHAczwpsuXzMqKdw='; const timestamp = new Date().getTime(); const RDM = this.uuid(); return { appId, RDM, timestamp, Authorization: sha256.hmacsha256(key, `${appId}&${timestamp}&${RDM}`) }; }, /** * * @param {String} idType id类型: userId, roomId, orgId * @param {Strig} streamUrl 流地址id */ getDataFromStreamUrl(idType, streamUrl){ // streamUrl 格式 // '_orgId_roomId_userId_1' //倒序 const obj = { userId: 1, roomId: 2, orgId : 3, }; if(!streamUrl){ return; }else{ return streamUrl.split('_').reverse()[obj[idType]]; } }, // getCurrentExtensionVersions(ext_id){ // if(EM){ // EM.GetExtensionVersions('zego_ext', // function(ec, content) { // console.log('GetExtensionVersions EC:' + ec + '\nContent:' + content); // }); // } // } //转换一下用户角色的定义 用户角色 '1=teacher'/'2=student'/'3=assistant'/'4=parent' translateRole(roleString) { if (typeof roleString == 'string') { if (roleString == 'teacher') { return '1'; } else if (roleString == 'student') { return '2'; } else if (roleString == 'assistant') { return '3'; } else if (roleString == 'parent') { return '4'; } } return roleString; }, //转换一下用户角色的定义 用户角色 '1=teacher'/'2=student'/'3=assistant'/'4=parent' translateRoleBack: function (roleNumber) { if (typeof roleNumber == 'string') { if (roleNumber == '1') { return 'teacher'; } else if (roleNumber == '2') { return 'student'; } else if (roleNumber == '3') { return 'assistant'; } else if (roleNumber == '4') { return 'parent'; } } return ''; }, throttle: function(fn, delay) { var context = null, timer = null, args = null; return function() { context = this; args = arguments; if (timer) return; timer = setTimeout(function() { clearTimeout(timer); timer = null; fn.apply(context, args); }, delay); }; }, // 格式化当前时间 currentTimeString() { const date = new Date(); let fmt = 'yyyy-MM-dd hh:mm:ss:S'; const o = { 'M+' : date.getMonth()+1, //月份 'd+' : date.getDate(), //日 'h+' : date.getHours(), //小时 'm+' : date.getMinutes(), //分 's+' : date.getSeconds(), //秒 'q+' : Math.floor((date.getMonth()+3)/3), //季度 'S' : date.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)); fmt=fmt.replace(RegExp.$1, (date.getFullYear()+'').substr(4 - RegExp.$1.length)); for(let k in o) { if(new RegExp('('+ k +')').test(fmt)); fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (('00'+ o[k]).substr((''+ o[k]).length))); } return fmt; }, //notice返回端上想要的uid getUidByStreamId(streamId) { if (streamId.split('_').length == 5) { return streamId; }; if (streamId && streamId.indexOf('_') > 0) { return streamId.split('_')[2]; } else { return streamId; } }, //数据上报返回真正的uid getUidByStreamIdDr(streamId) { if (streamId && streamId.indexOf('_') > 0) { return streamId.split('_')[2]; } else { return streamId; } }, toFixed(num, bit = 2) { let backNum; try { backNum = parseFloat(num).toFixed(bit); } catch (error) { backNum = num; } return backNum; }, getStreamId(args) { const {institutionId, roomId, userId, groupId} = args; return `${institutionId}_${groupId || roomId}_${userId}_1`; }, getConfId(institutionId, roomId) { return `${roomId}_${institutionId}`; }, /** * 深拷贝 * @param {*} obj 拷贝对象(object or array) * @param {*} cache 缓存数组 */ deepCopy(obj, cache = []) { // typeof [] => 'object' // typeof {} => 'object' if (obj === null || typeof obj !== 'object') { return obj; } // 如果传入的对象与缓存的相等, 则递归结束, 这样防止循环 /** * 类似下面这种 * var a = {b:1} * a.c = a * 资料: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value */ const hit = cache.filter(c => c.original === obj)[0]; if (hit) { return hit.copy; } const copy = Array.isArray(obj) ? [] : {}; // 将copy首先放入cache, 因为我们需要在递归deepCopy的时候引用它 cache.push({ original: obj, copy }); Object.keys(obj).forEach(key => { copy[key] = deepCopy(obj[key], cache); }); return copy; }, firstUpperCase(key) { if (!key) { return key; } return key.charAt(0).toUpperCase() + key.slice(1); }, getChromeVersion() { let chromeVersion = navigator.userAgent; console.log('chromeVersion',chromeVersion); let res = chromeVersion.search(/Chrome\/68/); // res == -1 ;//非68版本要升级 let isUpdateChromeVersion = res < 0 ? true : false; return isUpdateChromeVersion; }, sleep(time) { return new Promise((resolve) => setTimeout(resolve, time)); } // 获取网络时间戳 // async getNetworkTimeStamp() { // let res; // try { // res = await getNetworkTimestampApi(); // } catch (e){ // console.log('getNetworkTimeStamp1',e); // } // const res1 = new Date().getTime(); // // let timestamp = 0; // if (res && res.data.t) { // this.timestamp = +res.data.t; // this.diffTime = this.timestamp - res1; // console.log('getNetworkTimeStamp10'); // } else { // this.timestamp = new Date().getTime(); // this.diffTime = 0; // console.log('getNetworkTimeStamp11'); // // const res1 = await getNetworkTimestampApi('suning'); // // if (res1.status === 200) { // // timestamp = +res1.data.sysTime1 * 1000; // // } // } // console.log('getNetworkTimeStamp2',this.timestamp,res1,this.diffTime); // // await this.getDiffTime(); // // return this.timestamp; // }, //防抖 // debounce(fn,wait){ // var timer = null; // return function(){ // if(timer !== null){ // clearTimeout(timer); // } // timer = setTimeout(fn,wait); // } // } };