@tencentcloud/lite-chat
Version:
Tencent Cloud Chat SDK for Web/Mini Program/uni-app
2 lines (1 loc) • 9.91 kB
JavaScript
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatPush-token-register"]=n()}(this,function(){"use strict";const e=new class{init(e){this.core=e}};function n(e,n,t,s){return new(t||(t=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t(function(e){e(n)})).then(r,c)}a((s=s.apply(e,n||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const t=0,s=1,o=2,i="im_open_push.msg_webpush",r="push_online_presence_task",c=12e4;function a(n){const{common:{filterProtocolDataInvalidFields:t,calcBodyCRC:s}}=e.core,{servcmd:o,data:i}=n,r=function(n){const{store:t,common:{generateSequence:s},utils:{platform:o,base16EncodeBinaryString:i},constants:{WEB_PUSH_ACCOUNT_TYPE:r}}=e.core,c=t.get("webPush")||{},a=t.get("instance")||{};return{servcmd:n,ver:"v4",platform:o,websdkappid:537048168,websdkversion:"1.7.3",a2:c.a2Key||void 0,tinyid:c.tinyID||void 0,status_instid:c.statusInstanceId||0,sdkappid:a.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:c.a2Key?void 0:c.userId,usersig:c.a2Key?void 0:c.userSig,sdkability:478343027,sdkability_ext:i(""),cappid:a.applicationID||0,tjgID:"",seq:s(),cs:0,idtype:r}}(o),c=t(i);return r.cs=s(o,c),{head:r,body:c}}function u(){return function(){var e;if("undefined"==typeof window)return!1;if(window.matchMedia){const e=window.matchMedia("(display-mode: standalone)").matches,n=window.matchMedia("(display-mode: fullscreen)").matches;if(e)return!0;if(n){const e=!!(null===document||void 0===document?void 0:document.querySelector('link[rel="manifest"]')),n="serviceWorker"in navigator&&null!==navigator.serviceWorker.controller;return e||n}}if("undefined"!=typeof navigator&&!0===navigator.standalone)return!0;return!("undefined"==typeof document||!(null===document||void 0===document?void 0:document.referrer)||!(null===(e=null===document||void 0===document?void 0:document.referrer)||void 0===e?void 0:e.includes("android-app://")))}()?o:function(){const{utils:{IS_IOS:n,IS_ANDROID:t,USER_AGENT:s}}=e.core;if(n||t)return!0;if("undefined"!=typeof navigator){const e=navigator;if(e.userAgentData&&e.userAgentData.mobile)return!0}const o=s.toLowerCase();return/android|webos|iphone|ipad|ipod|blackberry|windows phone|mobile|opera mini|iemobile/i.test(o)}()?s:t}function d(){return n(this,void 0,void 0,function*(){var n,t,s;const{channel:o,store:i}=e.core,r="im_open_status.wslogin",c=a({servcmd:r,data:{State:"Online",is_web_uniapp:0,InstType:0,WebClientType:u(),IsWebPushLogin:1,DomainList:[(null===(n=null===window||void 0===window?void 0:window.location)||void 0===n?void 0:n.origin)||""],SdkVer:(null===(t=i.get("instance"))||void 0===t?void 0:t.version)||"",PushVer:(null===(s=i.get("webPush"))||void 0===s?void 0:s.pushSDKVersion)||""}}),d=`${c.head.seq}${r}`;return o.sendPacket(c,{timeout:9e4,requestId:d})})}var h=new class{constructor(){this._latestLoginAt=0,this._helloInterval=c}init(e){this._core=e;const{helper:{registerExperimentalAPI:n},notificationCenter:t,InnerEvent:{ERROR:s,FORCE_OFFLINE:o,DESTROY:i,RECONNECTED:r},constants:{ERROR_CODE:c}}=e;t.subscribeInnerEvent(o,this._handleForceOfflineFromServerPush,this),t.subscribeInnerEvent(s,c.ACCOUNT_A2KEY_EXPIRED,this._handleForceOfflineFromResponse,this,this._isWebPushEvent),t.subscribeInnerEvent(r,this._reLoginWebPush,this),t.subscribeInnerEvent(i,this._dispose,this),n("loginWebPush",this),n("logoutWebPush",this),n("setWebPushToken",this)}loginWebPush(e){return n(this,void 0,void 0,function*(){const{store:n,common:{ChatError:t},constants:{ERROR_CODE:s},utils:{safeStringify:o},ssoLog:i}=this._core;i.debug("loginWebPush.start",o(e));try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new t({functionName:"loginWebPush",code:s.REPEAT_LOGIN});const{userID:r,userSig:a,pushSDKVersion:u}=e;n.set("webPush",{userId:r,userSig:a,pushSDKVersion:u});const h=yield d();if(h){i.info("loginWebPush",o(h),{eventType:4});const{HelloInterval:e,TimeStamp:n,WebPushPubKey:t,InstId:s,A2Key:r,TinyId:a}=h;return this._helloInterval=1e3*e||c,this._latestLoginAt=0,this._handleLoginWebPushSuccess({helloInterval:e,serverTimeSeconds:n,instanceID:s,a2Key:r,tinyID:a,vapid:t}),{code:0,data:{vapid:t}}}}catch(e){const{errorCode:n,errorInfo:r}=e;n!==s.REPEAT_LOGIN&&(this._latestLoginAt=0),i.error("loginWebPush",o(e));throw new t({functionName:"loginWebPush",code:n,message:r})}})}setWebPushToken(t){return n(this,void 0,void 0,function*(){const{utils:{safeStringify:s},ssoLog:o,common:{ChatError:i}}=this._core;o.debug("setWebPushToken.start",s(t));try{const i=yield function(t){return n(this,void 0,void 0,function*(){var n;const{store:s,channel:o}=e.core,{browserType:i,pushToken:r,webPushAuthKey:c,webPushP256:u,pushSDKVersion:d,browserVersion:h,browserPlatform:l,browserLanguage:v}=t,g="offline_push_status.webpush_set_token",f=a({servcmd:g,data:{InstType:i,Auth:c,Endpoint:r,P256:u,SdkVer:(null===(n=s.get("instance"))||void 0===n?void 0:n.version)||"",PushVer:d,DevMod:h,DevOS:l,Lang:v}}),_=`${f.head.seq}${g}`;return o.sendPacket(f,{requestId:_})})}(t);return o.info("setWebPushToken",s(i)),i}catch(e){const{errorCode:n,errorInfo:t}=e;o.error("setWebPushToken",s(e));throw new i({functionName:"loginWebPush",code:n,message:t})}})}logoutWebPush(t){return n(this,void 0,void 0,function*(){const{utils:{safeStringify:s},ssoLog:o,common:{ChatError:i,taskScheduler:r}}=this._core;o.debug("logoutWebPush.start",s(t));const{needLogoutFromServer:c=!0}=t||{};try{return c&&(yield function(){return n(this,void 0,void 0,function*(){const n="im_open_status.wslogout",t=a({servcmd:n,data:{wslogout_type:0,isWebUniapp:0}}),s=`${t.head.seq}${n}`;return e.core.channel.sendPacket(t,{requestId:s})})}()),o.info("logoutWebPush"),{code:0,data:{}}}catch(e){const{errorCode:n,errorInfo:t}=e;throw o.error("logoutWebPush",s(e)),new i({functionName:"logoutWebPush",code:n,message:t})}finally{this._reset()}})}_isLoginIn(){var e;return!0===(null===(e=this._core.store.get("webPush"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_handleLoginWebPushSuccess(e){var n;const{store:t,common:{taskScheduler:s}}=this._core,{timeManager:o}=this._core.common,{serverTimeSeconds:i,a2Key:c,tinyID:a,instanceID:u,vapid:d}=e;if(!0!==(null===(n=t.get("login"))||void 0===n?void 0:n.isLoggedIn)){const e=1e3*i;o.calculateTimeOffsetWithServer(this._latestLoginAt,e)}t.set("webPush",{a2Key:c,tinyID:a,statusInstanceId:u,isLoggedIn:!0,vapid:d}),s.addTask({id:r,intervalMs:this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_handleForceOfflineFromResponse(e){this._isLoginIn()&&this.logoutWebPush({needLogoutFromServer:!1})}_isWebPushEvent(e){const{head:n}=e||{},{constants:{WEB_PUSH_ACCOUNT_TYPE:t}}=this._core;return(null==n?void 0:n.idtype)===t}_createRepeatLoginResponse(){var e;const{store:n,common:{getErrorMessage:t}}=this._core;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:t({code:"RepeatLogin",replacement1:null===(e=n.get("webPush"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_handleForceOfflineFromServerPush(e){this.logoutWebPush({needLogoutFromServer:!1})}_reLoginWebPush(){return n(this,void 0,void 0,function*(){const{store:e,ssoLog:n,utils:{safeStringify:t}}=this._core;try{if(!this._isLoginIn())return;const n=yield d();if(n){const{InstId:t}=n;e.set("webPush",{statusInstanceId:t})}}catch(e){n.warn("_reLoginWebPush",t(e))}})}_sendOnlinePresenceRequest(){return n(this,void 0,void 0,function*(){try{yield function(){const n="im_open_status.wshello",t=a({servcmd:n,data:{isWebUniapp:0}}),s=`${t.head.seq}${n}`;return e.core.channel.sendPacket(t,{requestId:s})}()}catch(e){this._core.ssoLog.warn("pushTokenRegister._sendOnlinePresenceRequest",` error:${e.message}`)}})}_reset(){this._latestLoginAt=0,this._core.store.clear("webPush"),this._core.helper.taskScheduler.removeTask(r)}_dispose(){const{notificationCenter:e,InnerEvent:{ERROR:n},constants:{ERROR_CODE:t}}=this._core;this._reset(),e.unSubscribeInnerEvent(n,t.ACCOUNT_A2KEY_EXPIRED,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(n,t.MSG_A2KEY_EXPIRED,this._handleForceOfflineFromResponse,this)}};var l=new class{init(e){const{notificationCenter:n}=e;this._core=e,n.subscribeInnerEvent(i,this._handleOnlinePushMessage,this)}_handleOnlinePushMessage(e){var n;const{utils:{isEmpty:t}}=this._core;((null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.EventArray)||[]).forEach(e=>{if(!t(e.C2cMsgArray)){const n=e.C2cMsgArray||[];this._processServerMessages(n)}})}_processServerMessages(e){const{message:n,OuterConstant:{CONV_C2C:t},notificationCenter:s,OuterEvent:{WEB_PUSH_MESSAGE_RECEIVED:o}}=this._core,i=e.map(e=>{const{WebPushExtension:s,WebInfo:o,WebpushMsg:i}=e,r=n.messageHelper.parseServerPushMessage(e),c=n.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:t,flow:"in"})),{elements:a}=r;return c.setElement(a),c.webPush={extension:s,content:i,info:o},c});(null==i?void 0:i.length)>0&&s.emitOuterEvent(o,{name:o,data:i})}reset(){const{notificationCenter:e}=this._core;e.unSubscribeInnerEvent(i,this._handleOnlinePushMessage,this)}dispose(){this.reset()}};return new class{constructor(){this.name="PushTokenRegisterPlugin"}install(n){this._core=n,e.init(n),h.init(n),l.init(n),n.notificationCenter.subscribeInnerEvent(n.InnerEvent.LOGOUT,this._reset,this),n.notificationCenter.subscribeInnerEvent(n.InnerEvent.DESTROY,this._dispose,this)}_reset(){l.reset()}_dispose(){const{notificationCenter:e,InnerEvent:n}=this._core;this._reset(),e.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}}});