@tencentcloud/lite-chat
Version:
Tencent Cloud Chat SDK for Web/Mini Program/uni-app/React Native/Donut
2 lines (1 loc) • 15.5 kB
JavaScript
const e=new class{init(e){this.core=e}};function t(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(s[n[i]]=e[n[i]])}return s}function s(e,t,s,n){return new(s||(s=Promise))((function(i,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}l((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const n=[3,4,5,6,17,20,21,100],i=3,o=4,r=5,a=6,l=17,u=20,c=21,g=100,h=300,_=e=>e===a||e===o,p=e=>e===r;function d(e,t){return s(this,void 0,void 0,(function*(){const{longPollingKey:n,startSequence:i,startBroadcastSeq:o,simplifiedMessage:r}=e;return function(e,t,n){return s(this,void 0,void 0,(function*(){const{helper:s,channel:i}=n,o=s.generateProtocolData({servcmd:e,data:t}),r=`${o.head.seq}${e}`;return yield i.sendPacket(o,{requestId:r})}))}("group_open_long_polling_http_svc.get_msg",{Key:n,StartSeq:i,StartBroadcastSeq:o,DownsizeFlag:r,USP:1,HoldTime:90},t)}))}class M{constructor(e){const{core:t,manager:s,groupID:n,getRequestParams:i,onSuccess:o,onFail:r}=e;this._name="Polling",this._core=t,this._manager=s,this._timeoutID=-1,this._isRunning=!1,this._groupID=n,this._getRequestParams=i,this._onSuccess=o,this._onFail=r}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getPollingInterval()}`)}isRunning(){return this._isRunning}_request(){return s(this,void 0,void 0,(function*(){try{const e=this._getRequestParams(this._groupID),t=yield d(e,this._core);this._onSuccess(this._groupID,t);const s=this._manager.getPollingInterval();this._runNextPolling(s)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}}))}_runNextPolling(e){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(`${this._name}.stop`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class m{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){const e=(null===(t=this._map.entries().next().value)||void 0===t?void 0:t[0])||"";this._map.delete(e)}this._map.set(e,1)}has(e){return this._map.has(e)}delete(e){this.has(e)&&this._map.delete(e)}clear(){this._map.clear()}}function I(s){const n=function(e){const{E:s,MCT:n,MR:i,MP:o,MTS:r,GId:a,MS:l,CCD:u,F_Account:c,IsSys:g,GInf:h,MsgBody:_}=e,p=t(e,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:s,MsgClientTime:n,MsgRandom:i,MsgPriority:o,MsgTimeStamp:r,ToGroupId:a,MsgSeq:l,CloudCustomData:u,From_Account:c,IsSystemMsg:g,GroupInfo:f(h),MsgBody:v(_)},p)}(s);return function(t){const{Event:s}=t;(_(s)||p(s))&&(t.From_Account=t.From_Account||"@TIM#SYSTEM");n=s,(n===l||(e=>e===i)(s))&&function(t){const{core:{OuterConstant:s}}=e;t.CloudCustomData=t.CloudCustomData||"",t.MsgBody=t.MsgBody.map((e=>{if(e.MsgType===s.MSG_CUSTOM){const{content:t={}}=e;e.content=Object.assign({Data:"",Desc:"",Ext:""},t)}return e}))}(t);var n;_(s)&&function(e){const{GroupJoinType:t,MsgOperatorMemberExtraInfo:s={},MsgMemberExtraInfo:n,Operator_Account:i,List_Account:o,OpType:r}=e.MsgBody||{};"number"==typeof t||1!==r&&2!==r||(e.MsgBody.GroupJoinType=2===r?0:1);n||(e.MsgBody.MsgMemberExtraInfo=o.map((e=>({UserId:e}))));1!==r||n||(e.MsgBody.MsgMemberExtraInfo=[{UserId:s.UserId}]);e.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:i,ImageUrl:"",NickName:""},s)}(t);p(s)&&function(e){const{MsgOperatorMemberExtraInfo:t={},Operator_Account:s}=e.MsgBody||{};e.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:s,ImageUrl:"",NickName:""},t),e.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*e.MsgTimeStamp},e.MsgBody),e.MsgBody=Object.keys(e.MsgBody).filter((e=>"MsgOperatorMemberExtraInfo"!==e)).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:e.MsgBody[s]})),{})}(t)}(n),n}function f(e){const s=e||{},{GN:n,GT:i,F_Hd:o,F_NN:r}=s,a=t(s,["GN","GT","F_Hd","F_NN"]),l=Object.assign({GroupName:n,GroupType:i},a);return o&&(l.From_AccountHeadurl=o),r&&(l.From_AccountNick=r),l}function v(e){let s=e;Array.isArray(e)||(s=[e]);const n=s.map((e=>{const{O_Account:s,Opt:n,L_Account:i,RT:o,UDF:r,OpInf:a,OnlineInf:l,MsgMemberExtraInfo:u}=e,c=t(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),g=Object.assign({Operator_Account:s,OpType:n,List_Account:i,ReportType:o,UserDefinedField:r},c);return a&&(g.MsgOperatorMemberExtraInfo=function(e){const{Img:s,NN:n}=e,i=t(e,["Img","NN"]);return Object.assign({ImageUrl:s,NickName:n},i)}(a)),u&&(g.MsgMemberExtraInfo=function(e){return e.map((e=>{const{Img:s,NN:n}=e,i=t(e,["Img","NN"]);return Object.assign({ImageUrl:s,NickName:n},i)}))}(u)),l&&(g.OnlineMemberInfo=function(e){const{ET:t,Num:s}=e;return{ExpireTime:t,OnlineMemberNum:s}}(l)),g}));return Array.isArray(e)?n:n[0]}var S=new class{constructor(){this._name="MessageParser",this._sequenceList=new m(200),this._messageIDList=new m(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(e,t,s=!1){this._sortServerMessageList(e,t);const n=this._handleMessageList(e,t);if(0===n.length)return;this._checkMessageStacked(n);const i=n.filter((e=>!0===e.isModified)),o=n.filter((e=>!1===e.isModified)),{OuterEvent:{MESSAGE_RECEIVED:r,MESSAGE_MODIFIED:a}}=this._core;i.length>0&&this._emitEvent({name:a,data:i}),o.length>0&&this._emitEvent({name:r,data:o})}_sortServerMessageList(e,t){t.sort(((e,t)=>e.MsgSeq-t.MsgSeq));const s=t.map((e=>e.MsgSeq));console.log(`${this._name}._sortServerMessageList groupID:${e} count:${s.length} sequenceList:${s}`),s.length=0}_handleMessageList(e,t){const{message:{messageDataHandler:s,messageHelper:n},OuterConstant:i}=this._core,o=this._avChatRoomHandler.isPollingSimplifiedMessage(),r=[],a=t.length;for(let l=0;l<a;l++){let a=t[l];o&&(a=I(a)),this._patchMessageType(a);const u=n.parseServerGroupMessage(a);if(null===this._filterMessageItem(u,a.Event))continue;const c=this._createMessage(u);null!==this._filterDuplicateMessage(c)&&(s.isMessageSentByCurrentInstance(c)||(1===u.isModified&&(c.isModified=!0),c.conversationType===i.CONV_SYSTEM&&5===c.payload.operationType&&this._onGroupDismissed(e),r.push(c)))}return r}_patchMessageType(e){const{OuterConstant:t}=this._core;_(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),p(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e,t){return n.includes(t)?t===a&&this._avChatRoomHandler.isGroupAttributesUpdated(e)?(this._avChatRoomHandler.handleGroupAttributesUpdated(e),null):(e=>e===u)(t)?(this._handleMessageRevoked(e),null):(e=>e===g)(t)?(this._onLiveCustomData(e),null):(e=>e===c)(t)?null:e:(console.warn(`${this._name}.onMessageReceived unknown event:${t}`),null)}_createMessage(e){const{message:{messageFactory:t},OuterConstant:s}=this._core;let n=s.CONV_GROUP;e.event===r&&(n=s.CONV_SYSTEM);const i=!!e.isSystemMessage,o=t.createMessage(Object.assign(Object.assign({},e),{conversationType:n,isSystemMessage:i,flow:"in"}));return o.setElement(e.elements),o}_filterDuplicateMessage(e){const{common:t}=this._core;if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}const s=this._messageIDList.has(e.ID);return s?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:${s}`),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){const{OuterConstant:t,OuterEvent:{MESSAGE_REVOKED:s}}=this._core,{groupID:n,elements:{revokeMsgList:i},revokerInfo:o}=e,r=[];i.forEach((e=>{const{tinyID:s,clientTime:i,random:a,sequence:l}=e,u={conversationID:`${t.CONV_GROUP}${n}`,ID:`${s}-${i}-${a}`,revoker:o.revoker,revokeReason:o.reason||"",revokerInfo:{userID:o.revoker,nick:"",avatar:""},sequence:l};r.push(u)})),0!==r.length&&this._emitEvent({name:s,data:r})}_onLiveCustomData(e){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:t}}=this._core,{groupID:s,sequence:n,time:i,elements:o}=e,r=(null==o?void 0:o.content)||"";this._emitEvent({name:t,data:r}),console.log(`${this._name}._onLiveCustomData groupID:${s} sequence:${n} time:${i} data:${r}`)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){const{length:t}=e;t>=100&&this._reportMessageStackedCount<5&&(this._reportMessageStackedCount+=1)}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(e){const{message:{messageHelper:t},OuterEvent:{MESSAGE_RECEIVED:s}}=this._core,i=this._avChatRoomHandler.isPollingSimplifiedMessage(),o=[],r=e.length;for(let s=0;s<r;s++){let r=e[s];i&&(r=I(r));const a=t.parseServerGroupMessage(r);if(!n.includes(r.Event)){console.warn(`${this._name}.onBroadcastMessageReceived unknown event:${r.Event}`);continue}const l=this._createMessage(a);l.isBroadcastMessage=!0,this._broadcastMessageIDMap.has(l.ID)||(o.push(l),this._broadcastMessageIDMap.set(l.ID,1))}o.length>0&&this._emitEvent({name:s,data:o})}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};var O=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._pollingInterval=h,this._currentPollingInterval=h,this._pollingIntervalPlus=2e3,this._pollingNoMessageMaxCount=20,this._pollingSimplifiedMessage=0,this._pollingNoMessageCount=0,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,S.init(e,this),console.log("AVChatRoomHandler.init")}getPollingInterval(){return this._currentPollingInterval}isPollingSimplifiedMessage(){return 0!==this._pollingSimplifiedMessage}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}handleJoinGroupResult(e){return s(this,void 0,void 0,(function*(){const{longPollingKey:t,group:s,historyMessageList:n}=e,{groupID:i}=s;return yield this._preCheck(s),this._joinedGroupMap.set(i,s),this._parentPlugin.groupDataHandler.updateLocalGroup([s]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),n.length>0&&S.onMessageReceived(i,n,!0),void 0!==t?this._startMessageLongPolling(e):{status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:s}}))}_preCheck(e){return s(this,void 0,void 0,(function*(){const{common:t,OuterConstant:s,apiMap:{quitGroup:n}}=this._core;if(t.isUnlimitedAVChatRoom())return;if(0===this._joinedAVChatRoomCount())return;if(e.type===s.GRP_LIVE)return;const[i,o]=this._joinedGroupMap.entries().next().value;o.selfInfo.role===s.GRP_MBR_ROLE_OWNER?this._parentPlugin.groupDataHandler.deleteLocalGroup(i):yield n(i),this.reset(i)}))}_startMessageLongPolling(e){const{OuterConstant:t}=this._core,{longPollingKey:s,startSequence:n=1,group:i}=e,{groupID:o}=i;return this._pollingRequestInfoMap.set(o,{longPollingKey:s,startSequence:n}),this._startPolling(o),{status:t.JOIN_STATUS_SUCCESS,group:i}}_startPolling(e){if(console.log(`${this._name}._startPolling groupID:${e}`),this._pollingInstanceMap.has(e)){const t=this._pollingInstanceMap.get(e);return void((null==t?void 0:t.isRunning())||null==t||t.start())}const t=new M({core:this._core,manager:this,groupID:e,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});t.start(),this._pollingInstanceMap.set(e,t)}_handleRequestParams(e){const{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:this._pollingSimplifiedMessage}:{longPollingKey:t,startSequence:s,simplifiedMessage:this._pollingSimplifiedMessage}}_handleSuccess(e,t){const{ErrorCode:s}=t;if(0===s)this._hasJoinedAVChatRoom(e)&&this._handleResponseData(e,t);else{const{longPollingKey:t,startSequence:n}=this._pollingRequestInfoMap.get(e)||{};console.warn(`${this._name}._handleSuccess groupID:${e} key:${t} startSeq:${n} errorCode:${s}`)}}_handleResponseData(e,t){const{Key:s,NextSeq:n,NextBroadcastSeq:i,RspMsgList:o=[],RspBroadcastMsgList:r=[]}=t;s&&n&&this._pollingRequestInfoMap.set(e,{longPollingKey:s,startSequence:n}),i&&i>this._startBroadcastSequence&&(this._startBroadcastSequence=i),o.length>0?(0!==this._pollingNoMessageCount&&(this._pollingNoMessageCount=0,this._currentPollingInterval=this._pollingInterval),S.onMessageReceived(e,o)):(this._pollingNoMessageCount+=1,this._pollingNoMessageCount===this._pollingNoMessageMaxCount&&(this._currentPollingInterval=this._pollingInterval+this._pollingIntervalPlus)),r.length>0&&S.onBroadcastMessageReceived(r)}_handleFailure(e,t){console.warn(`${this._name}._handleFailure groupID:${e} error:`,t)}_joinedAVChatRoomCount(){const{OuterConstant:e}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=this._getJoinedGroups().filter((t=>t.type===e.GRP_AVCHATROOM))),t.length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}_getJoinedGroups(){return[...this._joinedGroupMap.values()]}_stopPolling(e){if(e){console.log(`${this._name}._stopPolling groupID:${e}`);const t=this._pollingInstanceMap.get(e);return null==t||t.stop(),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),void this._parentPlugin.groupDataHandler.deleteLocalGroup(e)}console.log(`${this._name}._stopPolling all`);for(const e of this._pollingInstanceMap.values())e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear()}reset(e){this._stopPolling(e),this._pollingInterval=h,this._currentPollingInterval=h,this._pollingIntervalPlus=2e3,this._pollingNoMessageMaxCount=20,this._pollingSimplifiedMessage=0,this._pollingNoMessageCount=0,this._startBroadcastSequence=1,S.reset()}};var y=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}joinGroup(e){return s(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.joinGroup(e),{data:{group:n}}=s;return n.type===t.GRP_AVCHATROOM?O.handleJoinGroupResult(s.data):s}))}};var C=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}quitGroup(e){return s(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.quitGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&O.reset(e),s}))}};var R=new class{constructor(){this.name="AVChatRoom"}install(t,s){this._core=t,e.init(t),O.init(t,s),y.init(t,s),C.init(t,s);const{notificationCenter:n,InnerEvent:i}=t;n.subscribeInnerEvent(i.LOGOUT,this._reset,this),n.subscribeInnerEvent(i.DESTROY,this._dispose,this)}_reset(){O.reset()}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};export{R as default};