@tencentcloud/lite-chat 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatRich-media-message"]=t()}(this,function(){function m(e,t){var r={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(r[o[i]]=e[o[i]]);return r}function d(e,a,n,l){return new(n=n||Promise)(function(r,t){function i(e){try{s(l.next(e))}catch(e){t(e)}}function o(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(i,o)}s((l=l.apply(e,a||[])).next())})}var z=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(g,m){return d(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:r="",method:i="PUT",url:o,qs:s,headers:a={},resources:n,dataType:l="text",uploadByIP:d,uploadIP:h}=g,u=o;if(s){let e=this._queryString(s);e&&(u+=(u.includes("?")?"&":"?")+e)}let c=new XMLHttpRequest;c.open(i.toUpperCase(),u,!0),c.responseType=l;var p=Object.assign({},a);if(d&&h&&(p.host=h),!t(p))for(let e in p)p.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&c.setRequestHeader(e,p[e]);return c.onload=()=>{var e=this._getResponseBody(c,r,d&&h),e=this._buildResponse(c,e);if(200===c.status)m(null,e);else{if(h&&!u.includes(h))return g.url=this._domainName2IP(u,h),g.uploadByIP=!0,this.request(g,m);m({code:c.status,message:JSON.stringify(c.responseText)},e)}},c.onerror=()=>{var e=this._getResponseBody(c,r,d&&h),e=this._buildResponse(c,e),t={code:c.status,message:0===c.status?"CORS blocked or network error":JSON.stringify(c.responseText)};m(t,e)},g.onProgress&&c.upload&&(c.upload.onprogress=e=>{var{total:e,loaded:t}=e,r=Math.min(Math.floor(100*t/e),100);g.onProgress({total:e,loaded:t,percent:r/100})}),c.send(n),c})}_buildResponse(e,t){let r={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),r[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:r,data:t}}_getResponseBody(e,t,r){return 200===e.status&&t?{location:t,uploadIP:r}:{response:e.responseText,uploadIP:r}}_queryString(r,i="&",o="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(r)?"":t(r)?Object.keys(r).map(e=>{let t=encodeURIComponent(e)+o;return Array.isArray(r[e])?r[e].map(e=>t+encodeURIComponent(e)).join(i):t+encodeURIComponent(r[e])}).filter(Boolean).join(i):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let x=["unknown","image","video","audio","log"];var o,e,W=new class{init(e){this._core=e}request(r,i){let e,{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:s,IN_UNI_IOS_APP:a}=null==(e=this._core)?void 0:e.utils,{resources:n="",headers:l={},url:d,downloadUrl:h=""}=r,u=d,c=null;var p=h?h.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(p){var p=decodeURIComponent(p[3]),p=p.includes("?")?p.split("?")[0]:p||"",p={key:r.fileKey||p,success_action_status:200,"Content-Type":""},g={};if(a){let[e,t]=d.split("?sign=");t&&(u=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:u,header:l,name:"file",filePath:n,formData:Object.assign(Object.assign({},p),g),timeout:r.timeout||3e5};if(s){let e=m(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:r.fileType?x[r.fileType]:"image"})}return(c=o.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:h,callback:i})},fail:e=>{this._handleResponse({response:e,downloadUrl:h,callback:i})}}))).onProgressUpdate&&c.onProgressUpdate(e=>{r.onProgress&&r.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),c}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:r}=e,i={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(i[e.toLowerCase()]=t.header[e]);var o=+t.statusCode;200==o?r(null,{statusCode:o,headers:i,data:Object.assign(Object.assign({},t.data),{location:e})}):r({code:o,message:JSON.stringify(t.data)},{statusCode:o,headers:i,data:void 0})}};function s(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function a(e){e=e||99999999;return Math.round(Math.random()*e)}function i(e,t=!0,r=!0){var i=Date.now();return t?r?i-e+" ms":Math.round((i-e)/1e3)+" s":r?i-e:Math.round((i-e)/1e3)}function n(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function h(e,t){return Math.round(Number(e)*10**t)/10**t}function u(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function c(e){return e<=1048576?h(e/1024,1)+"KB/s":h(e/1048576,1)+"MB/s"}let l="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",f="TIMVideoFileElem",_="RichMediaMessagePlugin",v=["rich.my-imcloud.com","imrich.qcloud.com"],j=((e=o=o||{}).UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/});var I=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(r){{var[r,i]=r.split("?");if(!i)return r;let t=i.split("&").reduce((e,t)=>{var[t,r]=t.split("=");return t&&"authKey"!==t&&(e[t]=r||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?r+"?"+e:r}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(j).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return s(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(r){return d(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(r):e?this._probeImageDimensionsMiniApp(r):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=v;var r=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==r)try{JSON.parse(r).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=v}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let r,i=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(r=this._core)?void 0:r.utils.randomString());return t?i+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),i=e?i+"."+e:i)}processResourceUrl(e){if(!e)return"";let t=e;var r=this.getFileDownloadProxy(),i=this.getAuthKey(),o=this.getFileDNList(),e=(r&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,r):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,r))),i&&-1===t.indexOf("authKey=")&&function(e,t){let r=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),i=e&&e[2]||"";if(i.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(i.endsWith(t[e])){r=!0;break}}return r}(t,o));return t=e?-1<t.indexOf("?")?t+"&authKey="+i:t+"?authKey="+i:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:r,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:r,IN_UNI_NATIVE_APP:i}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,r=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{r.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:r}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===r}_probeImageDimensionsWeb(i){return new Promise(e=>{let t=new Image,r=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),r()},t.onerror=()=>{e({width:0,height:0}),r()},t.src=i})}},y=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t=(this._core=e).utils["IN_MINI_APP"];this.httpRequest=t?W:z,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return d(this,void 0,void 0,function*(){var t=_+" uploadToCOS",e=l["file"];this.uploadFileType=l.uploadFileType,console.log(t+" options:",l);try{var r=Date.now(),i=yield this._createCosOptions(l),o=yield this._uploadFile(i),s=(this._handleUploadError(o,l),this._createUploadResult(e,o)),a=Date.now()-r,n=`size:${u(e.size)} time:${a}ms speed:`+c(1e3*e.size/a);return console.log(t+` ok. name:${e.name} `+n),{uploadOptions:i,response:s}}catch(e){throw console.warn(t+" failed, error:",e),e}})}_handleUploadError(e,t){var r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(403===e.statusCode)throw i(Date.now(),!1),t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new r({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:i(Date.now(),!1),uploadSpeed:c(1e3*e.size/i(Date.now(),!1))}}_createCosOptions(c){return d(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:r}=this._prepareUploadParams(c),i=this._isC2CConversation(c.message.conversationID)?1:2;try{var o=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:r,duration:this.duration,userID:c.message.from,conversationType:i}),{uploadUrl:s,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:d,fileKey:h}=o,u=!I.isPrivateNetWork()&&o.uploadIP;return{url:this._getRawOrUploadProxyUrl(s),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:d,fileKey:h,uploadIP:u||"",onProgress:e=>this._handleUploadProgress(e,c)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){console.log(_+" prepareUploadParams:",e);var t=e["file"],{IN_MINI_APP:r,IN_RN_APP:i}=I.getPlatformFlags(),r=r||i,i=r&&e.message.type!==g,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+a(999999)+e;return{fileName:n(i?t.name:e),resources:r?t.url:t,uploadMethod:r?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(a){return d(this,void 0,void 0,function*(){var t=_+" fetchCosSignatureUrl",r=I.isSimpleCos(),i=this._prepareCosRequestData(a),o=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(o,s,a){return d(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,r=e.generateCosSpecifiedData({servcmd:o,data:s}),i=r.head.seq+o;return yield t.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getCosSig error:",e),e}})}(o,i,this._core);this.fetchCosTryCount=0;var s=this._processResponse(e);return console.log(t+` ok. isSimpleCos:${r} data:`,s),s||{}}catch(e){if(console.error(t+" failed, error:",e),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(a);throw this.fetchCosTryCount=0,e}})}_processResponse(e){var t;let r=I.isSimpleCos(),l=r?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(r){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:r,uint32_exist_flag:i,str_download_url:o,str_upload_url:s,str_snapshot_url:a,str_file_key:n}=l;return{uploadIP:e,preSig:t,fileID:r,existFlag:i,downloadUrl:o,uploadUrl:s,requestSnapshotUrl:a,fileKey:n}}let{upload_url:i,download_url:o,snapshot_url:s,thumb_url:a,large_url:n,file_key:d}=l;return{uploadUrl:i,downloadUrl:o,requestSnapshotUrl:s,thumbUrl:a,largeUrl:n,fileKey:d}}_prepareCosRequestData(e){return I.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:I.getPlatform(),uint32_sdkappid:I.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(o){return d(this,void 0,void 0,function*(){return new Promise((r,i)=>{this.httpRequest.request(o,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(o).then(r).catch(i)):(this.uploadFileTryCount=0,e?i(e):r(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,r;try{var i=null==(t=e.error)?void 0:t.Code,o=null==(r=e.error)?void 0:r.Message;return"RequestTimeTooSkewed"===i||"AccessDenied"===i&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,r=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(r){let e=Date.now(),t=Date.parse(r);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=I.getFileUploadProxy();let r=e;return r=t?e.replace(/^https:\/\/[^/]+/,t):r}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let V=["jpg","jpeg","gif","png","bmp","image","webp"],U=20971520,w={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class q{constructor(e,t){this.instanceID=a(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=I.addAuthToUrl(e.imageUrl||e.url||""),this.url=I.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=I.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function S(t){var{originUrl:t,originWidth:r,originHeight:i,min:o=198}=t,r=parseInt(r)||0,i=parseInt(i)||0,s={url:void 0,width:0,height:0};if((r<=i?r:i)<=o)s.url=t,s.width=r,s.height=i;else{i<=r?(s.width=Math.ceil(r*o/i),s.height=o):(s.width=o,s.height=Math.ceil(i*o/r));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";s.url=198===o?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?m(s,["url"]):s}class F{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=l;var{uuid:e,file:t,imageFormat:r,imageInfoArray:i=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:r,uuid:e,imageInfoArray:[]},this.initImageInfoArray(i),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:r,ImageInfoArray:i,UUID:o}=t,s=i.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new F({imageFormat:r,imageInfoArray:s,uuid:o})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:r,IN_RN_APP:i,IN_BROWSER:o}=I.getPlatformFlags();return t=e&&((r||i)&&(t=e.url),o)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var r={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var i=t[e]||Object.assign({},r),i=new q(i,this._imageMemoryURL);i.setSizeType(e+1),i.setType(e),this.addImageInfo(i)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let i=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,r;e.url&&""!==e.imageUrl&&([t,...r]=e.imageUrl.split("://"),r=r.join("://"),i.includes(t)||e.setImageUrl("https://"+r))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=w[e.toUpperCase()]||w.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var r,i=this.content.imageInfoArray.length;for(let e=0;e<i;e++)r=this.content.imageInfoArray[e],t[e].size&&(r.size=t[e].size),t[e].url&&r.setImageUrl(t[e].url),t[e].width&&(r.width=t[e].width),t[e].height&&(r.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,r=t[2];t[2]=t[1],t[1]=r;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],S({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var[e]=this.content.imageInfoArray,e=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:r}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(r),UUID:e}}}parseImageInfoArray(e){return e.map(e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:I.removeAuthToUrl(e.imageUrl)}))}}var P=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:r,message:i}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==i?void 0:i.messageFactory)&&t.registerElementClass(l,F),e.subscribeInnerEvent(r.DESTROY,this._dispose,this)}createImageMessage(o){var s,a,n,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createImageMessage"}),t=(console.log(_+" createImageMessage options:",o),null==(s=this._core.store.get("login"))?void 0:s.userId),r=null==(n=null==(a=this._core)?void 0:a.message.messageFactory)?void 0:n.createMessage(Object.assign(Object.assign({},o),{from:t})),i=this._processImage(o);o.payload.file=i;var l={imageFormat:w.UNKNOWN,uuid:I.generateUUID(i),file:i,imageInfoArray:[]},d=new F(l);return r.setElement(d),this._messageOptionsMap.set(r.clientSequence,o),console.log(_+" createImageMessage OK imageMessage:",r),e.end(),r}catch(o){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)&&t.call(e,o).end(),console.error(_+" createImageMessage error:",o),o}}upload(i){return d(this,void 0,void 0,function*(){console.log(_+" uploadImage message:",i);var e=i.getElements()[0],t=this._messageOptionsMap.get(i.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,i,t)),r=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(r),i})}_performImageUpload(i,o,r){return d(this,void 0,void 0,function*(){var e=o["to"],{uploadOptions:e,response:t}=yield y.uploadToCOS({uploadFileType:1,file:r,to:e,message:o,onProgress:e=>{var t,r;i.updatePercent(e),null!=(r=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&r.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){console.log(_+" generateImageInfo");var{location:e,fileSize:t,width:r,height:i,smallImageUrl:o,smallImageWidth:s,smallImageHeight:a,largeImageUrl:n,largeImageWidth:l,largeImageHeight:d,imageInfoArray:h}=e,e=I.addAuthToUrl(e),u={size:t,url:e,width:r,height:i};return 0<(null==h?void 0:h.length)?this._processImageInfoArray(h,t):o&&n?[Object.assign({},u),{largeImageUrl:n,largeImageWidth:l,largeImageHeight:d},{smallImageUrl:o,smallImageWidth:s,smallImageHeight:a}]:[Object.assign({},u),this._generateThumbInfo(e,r,i,720),this._generateThumbInfo(e,r,i,198)]}_generateThumbInfo(e,t,r,i){return S({originUrl:e,originWidth:t,originHeight:r,min:i})}_processImageInfoArray(e,t){let r,i,o;for(var s of e)1===s.type?(i=s,i.size=t):2===s.type?(o=s,o.size=t):(r=s,r.size=t);return[Object.assign({},r),Object.assign({},o),Object.assign({},i)]}_parseResponse(i,o){return d(this,void 0,void 0,function*(){console.log(_+" parseResponse");try{var{thumbUrl:e,largeUrl:t,downloadUrl:r}=i;if(e&&t&&(yield this._getImageInfoByUrl(e,o,"thumb"),yield this._getImageInfoByUrl(t,o,"large")),I.isSimpleCos()&&!I.isPrivateNetWork()&&(yield this._getImageInfoArray(r,o),null!=o)&&o.uploadIP){let e=this._extractDomainFromUrl(r);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw console.error("Failed to parse response:",e),e}})}_extractDomainFromUrl(e){try{var t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(i,o,s){return d(this,void 0,void 0,function*(){try{var e=I.addAuthToUrl(i),{width:t=0,height:r=0}=yield I.probeImageWidthHeight(e);o.width=t,o.height=r,"thumb"===s?(o.smallImageUrl=i,o.smallImageWidth=t,o.smallImageHeight=r):(o.largeImageUrl=i,o.largeImageWidth=t,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var r=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],i=e.payload["file"];return r?this._processMiniAppImageFile(i):this._processWebImageFile(i)}catch(e){throw console.warn(_+" _processImage error:",e),e}}_processMiniAppImageFile(e){s(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=I.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(i,o){return d(this,void 0,void 0,function*(){var e=_+" getDownloadIP domainName: "+i;try{var t,r=yield function(a,n){return d(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,r="im_cos_msg.get_final_ip",i={str_domain:a},o=e.generateProtocolData({servcmd:r,data:i}),s=o.head.seq+r;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(i,this._core);r&&r.str_final_ip&&(console.log(e+" ok. downloadIP:"+r),(t=o.location.split("/"))[0]=r.str_final_ip,o.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(r,i){return d(this,void 0,void 0,function*(){var t=_+"._getImageInfoArray";try{var e=yield function(a,n){return d(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,r="im_cos_msg.get_imageinfo",i={str_image_url:a},o=e.generateProtocolData({servcmd:r,data:i}),s=o.head.seq+r;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(r,this._core);return i.imageInfoArray=this._processImageInfoResponse(e),console.log(t+" ok"),i}catch(e){throw i.imageInfoArray=void 0,console.warn(t+" failed, error:",e),e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:r}=this._core;let i="";if(t.IN_MINI_APP&&(i=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(i=e.name.slice(e.name.lastIndexOf(".")+1)),V.indexOf(i.toLowerCase())<0)throw new r.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:r}=this._core,i=0;if(t.IN_MINI_APP,0===(i=e.size))throw new r.ChatError({code:2108});if(i>=U)throw new r.ChatError({message:"File size exceeds limit: "+u(U)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let M="2.5.0",b="1.18.0",r=104857600;function A(e,t){let i=e.split("."),o=t.split("."),s=Math.max(i.length,o.length);for(;i.length<s;)i.push("0");for(;o.length<s;)o.push("0");for(let r=0;r<s;r++){let e=parseInt(i[r]),t=parseInt(o[r]);if(e>t)return 1;if(e<t)return-1}return 0}let O=new class{init(e){this.core=e}};class T{constructor(e){this.type=g,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:I.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:r,FileSize:i,UUID:o}=e;return new T({downloadFlag:e,url:t,fileName:r,fileSize:i,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:r,fileName:i,fileSize:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:I.removeAuthToUrl(r),FileName:i,FileSize:o,UUID:e}}}_getFileInfo(e){var t=O.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=a(999999)+"."+t)),e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var N=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:r,message:i}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==i?void 0:i.messageFactory)&&t.registerElementClass(g,T),e.subscribeInnerEvent(r.DESTROY,this._dispose,this)}createFileMessage(r){var i,o,s,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createFileMessage"}),t=(console.log(_+" createFileMessage options:",r),this._checkVersion(),this._processFile(r.payload.file));r.payload.file=t;var a=null==(i=this._core.store.get("login"))?void 0:i.userId,n=null==(s=null==(o=this._core)?void 0:o.message.messageFactory)?void 0:s.createMessage(Object.assign(Object.assign({},r),{from:a})),l={uuid:I.generateUUID(t),file:t},d=new T(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,r),console.log(_+" createFileMessage success fileMessage:",n),e.end(),n}catch(r){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)&&t.call(e,r).end(),console.error(_+" createFileMessage error:",r),r}}upload(r){return d(this,void 0,void 0,function*(){console.log(_+" uploadFile message:",r);var e=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),r.getElements()[0]),e=yield this._performFileUpload(t,r,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),r})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>r)throw new t({message:"File size exceeds limit: "+u(r)});if(0===e.size)throw new t({code:2108})}_performFileUpload(i,o,t){return d(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:255,file:t,to:e,message:o,onProgress:e=>{var t,r;i.updatePercent(e),null!=(r=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&r.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:r,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:o,IN_UNI_NATIVE_APP:s}=null==(e=this._core)?void 0:e.utils,a=(null==(a=this._core)?void 0:a.helper)["ChatError"];if(e||s){let e=I.extractFileFromInput(t);if(e)return e;throw new a({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(i||o){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return r?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:o}=null==(e=this._core)?void 0:e.utils,s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(e){if(!(r||i||o))throw new s({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(r&&A(e,M)<0)throw new s({message:`WXChooseMessageFile requires SDK version ${M} or higher`});if(i&&A(e,b)<0)throw new s({message:`QQChooseMessageFile requires SDK version ${b} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let L=["mp4","quicktime","mov"],C=104857600;class E{constructor(e){this.type=f,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:I.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:I.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:I.addAuthToUrl(e.thumbUrl),snapshotUrl:I.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:r,VideoSize:i,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:h,SnapshotHeight:u,ThumbSize:c,SnapshotSize:p,ThumbDownloadFlag:g,ThumbUrl:m,SnapshotUrl:f}=e;return new E({videoUrl:e,videoFormat:t,videoSecond:r,videoSize:i,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:d,thumbHeight:h,snapshotHeight:u,thumbSize:c,snapshotSize:p,thumbDownloadFlag:g,thumbUrl:m,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:r}=e;I.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),I.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),I.isEmpty(r)||(this.content.thumbHeight=this.content.snapshotHeight=Number(r))}validateBeforeSend(){var e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:r,videoSize:i,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:d,thumbHeight:h,snapshotHeight:u,thumbSize:c,snapshotSize:p,thumbDownloadFlag:g,thumbUrl:m,snapshotUrl:f}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:I.removeAuthToUrl(e),VideoFormat:t,VideoSecond:r,VideoSize:i,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:h,SnapshotHeight:u,ThumbSize:c,SnapshotSize:p,ThumbDownloadFlag:g,ThumbUrl:I.removeAuthToUrl(m),SnapshotUrl:I.removeAuthToUrl(f)}}}}var D=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:r,message:i}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==i?void 0:i.messageFactory)&&t.registerElementClass(f,E),e.subscribeInnerEvent(r.DESTROY,this._dispose,this)}createVideoMessage(r){var i,o,s,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"}),t=(console.log(_+" createVideoMessage options:",r),this._processVideo(r));r.payload.file=t;var a=null==(i=this._core.store.get("login"))?void 0:i.userId,n=null==(s=null==(o=this._core)?void 0:o.message.messageFactory)?void 0:s.createMessage(Object.assign(Object.assign({},r),{from:a})),l={videoFormat:t.videoFile.type,videoSecond:h(t.videoFile.second,0),videoSize:t.videoFile.size,remoteVideoUrl:"",videoUrl:t.videoFile.url,videoUUID:I.generateUUID(t.videoFile),thumbUUID:I.generateUUID(t.videoFile,"jpg"),thumbWidth:t.width||200,thumbHeight:t.height||200,thumbUrl:t.thumbUrl,thumbSize:t.thumbSize,thumbFormat:"jpg"},d=new E(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,r),e.end(),n}catch(r){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)&&t.call(e,r).end(),console.error(_+" createVideoMessage error:",r),r}}upload(i){return d(this,void 0,void 0,function*(){console.log(_+" uploadVideo message:",i);var e=i.getElements()[0],t=this._messageOptionsMap.get(i.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,i,t)),{location:t,snapshotInfo:r}=t,t=I.addAuthToUrl(t);return e.updateVideoUrl(t),I.isEmpty(r)||e.updateSnapshotInfo(r),i})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>C)throw new t({message:"File size exceeds limit: "+u(C)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===L.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(i,o,r){return d(this,void 0,void 0,function*(){var e=o["to"],{response:e,uploadOptions:t}=yield y.uploadToCOS({uploadFileType:2,file:r,to:e,message:o,onProgress:e=>{var t,r;i.updatePercent(e),null!=(r=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&r.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var i,o;try{var s=(null==(i=this._core)?void 0:i.helper)["ChatError"],{IN_MINI_APP:a,IN_BROWSER:n}=null==(o=this._core)?void 0:o.utils;let t=e.payload["file"],r={};if(a&&(r=this._processMiniVideoFile(t),t.name=r.name,t.url=r.url,t.type=r.type),n){let e=I.extractFileFromInput(t);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,r=this._processWebVideoFile(t)}return t.videoFile=r,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(_+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:r}=null==(t=this._core)?void 0:t.utils,i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(t)throw new i({message:"VideoUnsupportedInAlipay"});if(s(e))throw new i({message:"FileUnsupportedInMiniApp"});let o=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return r&&(o=e.fileType||o),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:o}}_processWebVideoFile(e){var{name:t,size:r=1,duration:i=0,type:o}=e,o=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:r,second:i,type:o}}_getSnapshotInfoByUrl(o){return d(this,void 0,void 0,function*(){try{console.log(_+" _getSnapshotInfoByUrl url:",o);var e,t,r,i=((yield function(s,a){return d(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:r}=a,i=t.generateCosSpecifiedData({servcmd:e,data:s}),o=i.head.seq+e;return yield r.sendPacket(i,{requestId:o})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:I.getPlatform(),cover_name:n(a(99999)),snapshot_url:o},this._core))||{})["download_url"];return(console.log(_+" _getSnapshotInfoByUrl OK snapshotUrl:",i),I.isEmpty(i))?{}:(e=I.addAuthToUrl(i),{width:t=0,height:r=0}=yield I.probeImageWidthHeight(e),{snapshotUrl:e,snapshotWidth:t,snapshotHeight:r})}catch(e){throw console.error(_+" _getSnapshotInfoByUrl error:",e),e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class R{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:I.addAuthToUrl(e.url),remoteAudioUrl:I.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:r,Size:i,UUID:o}=e;return new R({url:e,downloadFlag:t,second:r,size:i,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:r,size:i,second:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:I.removeAuthToUrl(r),Download_Flag:t,Second:o,Size:i,UUID:e}}}}var k=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:r,message:i}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==i?void 0:i.messageFactory)&&t.registerElementClass(p,R),e.subscribeInnerEvent(r.DESTROY,this._dispose,this)}createAudioMessage(t){var r,i,e,o;try{let e=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(_+" createAudioMessage options:",t);t.payload["file"];var s=this._processAudioFile(t.payload.file),a=(t.payload.file=s,null==(o=this._core.store.get("login"))?void 0:o.userId),n=null==(i=null==(r=this._core)?void 0:r.message.messageFactory)?void 0:i.createMessage(Object.assign(Object.assign({},t),{from:a})),l={second:Math.floor((s.duration||s.second)/1e3),size:s.fileSize||s.size||1,url:s.tempFilePath||s.uri||s.url,uuid:I.generateUUID(s)},d=new R(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,t),e.end(),n}catch(t){throw null!=(o=(e=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)&&o.call(e,t).end(),console.error(_+" createAudioMessage error:",t),t}}upload(r){return d(this,void 0,void 0,function*(){console.log(_+" uploadAudio message:",r);var e=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadAudio(e),r.getElements()[0]),e=yield this._performAudioUpload(t,r,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),r})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+u(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(i,o,t){return d(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:3,file:t,to:e,message:o,onProgress:e=>{var t,r;i.updatePercent(e),null!=(r=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&r.call(t,e)}}))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:r}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):r?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let t={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},B={createImageMessage:t,createAudioMessage:t,createVideoMessage:t,createFileMessage:t},H={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},K={TIMImageElem:P,TIMFileElem:N,TIMVideoFileElem:D,TIMSoundElem:k};return new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:r,MSG_IMAGE:i,MSG_VIDEO:o}}=(this._core=e)["constants"];O.init(e),P.init(e),N.init(e),D.init(e),k.init(e),y.init(e),I.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,r,i,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:H,params:B})}sendMessage(i,o){return d(this,void 0,void 0,function*(){var e,t,r;try{return console.log("sendMessage message:",i),yield this._upload(i),yield null==(r=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:r.sendMessage(i,o)}catch(e){throw console.error("sendMessage error:",e),e}})}_upload(i){return d(this,void 0,void 0,function*(){var t,r;if(!0!==i._relayFlag)try{let t=K[i.type];if(t){let e=this._core.ssoLog.createSSOLogData({method:"upload"});e.setLogInfo({message:"type:"+i.type}),yield t.upload(i),e.end()}}catch(e){throw i.status=o.FAIL,e instanceof Error&&(e.data={message:i}),this._core.message.messageDataHandler.storeConversationMessage(i),null!=(r=(t=this._core.ssoLog.getSSOLogData("upload")).setError)&&r.call(t,e).end(),e}})}}});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatRich-media-message"]=t()}(this,function(){function g(e,t){var i={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(i[o[r]]=e[o[r]]);return i}function l(e,a,n,l){return new(n=n||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function o(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(r,o)}s((l=l.apply(e,a||[])).next())})}var z=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(m,g){return l(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:i="",method:r="PUT",url:o,qs:s,headers:a={},resources:n,dataType:l="text",uploadByIP:h,uploadIP:d}=m,u=o;if(s){let e=this._queryString(s);e&&(u+=(u.includes("?")?"&":"?")+e)}let p=new XMLHttpRequest;p.open(r.toUpperCase(),u,!0),p.responseType=l;var c=Object.assign({},a);if(h&&d&&(c.host=d),!t(c))for(let e in c)c.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,c[e]);return p.onload=()=>{var e=this._getResponseBody(p,i,h&&d),e=this._buildResponse(p,e);if(200===p.status)g(null,e);else{if(d&&!u.includes(d))return m.url=this._domainName2IP(u,d),m.uploadByIP=!0,this.request(m,g);g({code:p.status,message:JSON.stringify(p.responseText)},e)}},p.onerror=()=>{var e=this._getResponseBody(p,i,h&&d),e=this._buildResponse(p,e),t={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};g(t,e)},m.onProgress&&p.upload&&(p.upload.onprogress=e=>{var{total:e,loaded:t}=e,i=Math.min(Math.floor(100*t/e),100);m.onProgress({total:e,loaded:t,percent:i/100})}),p.send(n),p})}_buildResponse(e,t){let i={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),i[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:i,data:t}}_getResponseBody(e,t,i){return 200===e.status&&t?{location:t,uploadIP:i}:{response:e.responseText,uploadIP:i}}_queryString(i,r="&",o="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(i)?"":t(i)?Object.keys(i).map(e=>{let t=encodeURIComponent(e)+o;return Array.isArray(i[e])?i[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(i[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let x=["unknown","image","video","audio","log"];var r,e,W=new class{init(e){this._core=e}request(i,r){let e,{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:s,IN_UNI_IOS_APP:a}=null==(e=this._core)?void 0:e.utils,{resources:n="",headers:l={},url:h,downloadUrl:d=""}=i,u=h,p=null;var c=d?d.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(c){var c=decodeURIComponent(c[3]),c=c.includes("?")?c.split("?")[0]:c||"",c={key:i.fileKey||c,success_action_status:200,"Content-Type":""},m={};if(a){let[e,t]=h.split("?sign=");t&&(u=e+"?sign="+encodeURIComponent(t),m.sign=decodeURIComponent(t),m.signature=decodeURIComponent(t))}let t={url:u,header:l,name:"file",filePath:n,formData:Object.assign(Object.assign({},c),m),timeout:i.timeout||3e5};if(s){let e=g(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:i.fileType?x[i.fileType]:"image"})}return(p=o.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:d,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:d,callback:r})}}))).onProgressUpdate&&p.onProgressUpdate(e=>{i.onProgress&&i.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),p}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:i}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var o=+t.statusCode;200==o?i(null,{statusCode:o,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):i({code:o,message:JSON.stringify(t.data)},{statusCode:o,headers:r,data:void 0})}};function s(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function a(e){e=e||99999999;return Math.round(Math.random()*e)}function o(e,t=!0,i=!0){var r=Date.now();return t?i?r-e+" ms":Math.round((r-e)/1e3)+" s":i?r-e:Math.round((r-e)/1e3)}function n(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function h(e,t){return Math.round(Number(e)*10**t)/10**t}function d(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function u(e){return e<=1048576?h(e/1024,1)+"KB/s":h(e/1048576,1)+"MB/s"}let p="TIMImageElem",c="TIMSoundElem",m="TIMFileElem",f="TIMVideoFileElem",_="RichMediaMessagePlugin",v=["rich.my-imcloud.com","imrich.qcloud.com"],j=((e=r=r||{}).UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/});var I=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(i){{var[i,r]=i.split("?");if(!r)return i;let t=r.split("&").reduce((e,t)=>{var[t,i]=t.split("=");return t&&"authKey"!==t&&(e[t]=i||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?i+"?"+e:i}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(j).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return s(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(i){return l(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(i):e?this._probeImageDimensionsMiniApp(i):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=v;var i=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==i)try{JSON.parse(i).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=v}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let i,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(i=this._core)?void 0:i.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var i=this.getFileDownloadProxy(),r=this.getAuthKey(),o=this.getFileDNList(),e=(i&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,i):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,i))),r&&-1===t.indexOf("authKey=")&&function(e,t){let i=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){i=!0;break}}return i}(t,o));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:i,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:i,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,i=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{i.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:i}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===i}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,i=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),i()},t.onerror=()=>{e({width:0,height:0}),i()},t.src=r})}},y=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t=(this._core=e).utils["IN_MINI_APP"];this.httpRequest=t?W:z,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(h){return l(this,void 0,void 0,function*(){let r=_+" uploadToCOS",{ssoLog:o,utils:{safeStringify:e}}=this._core,s=h["file"];this.uploadFileType=h.uploadFileType,o.debug("uploadToCOS",r+" options:"+e(h));try{let e=Date.now(),t=yield this._createCosOptions(h),i=yield this._uploadFile(t);this._handleUploadError(i,h);var a=this._createUploadResult(s,i),n=Date.now()-e,l=`size:${d(s.size)} time:${n}ms speed:`+u(1e3*s.size/n);return o.debug("uploadToCOS",r+` ok. name:${s.name} `+l),{uploadOptions:t,response:a}}catch(e){throw console.warn(r+" failed, error:",e),e}})}_handleUploadError(e,t){var i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(403===e.statusCode)throw o(Date.now(),!1),t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new i({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:o(Date.now(),!1),uploadSpeed:u(1e3*e.size/o(Date.now(),!1))}}_createCosOptions(p){return l(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:i}=this._prepareUploadParams(p),r=this._isC2CConversation(p.message.conversationID)?1:2;try{var o=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:i,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:s,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:h,fileKey:d}=o,u=!I.isPrivateNetWork()&&o.uploadIP;return{url:this._getRawOrUploadProxyUrl(s),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:h,fileKey:d,uploadIP:u||"",onProgress:e=>this._handleUploadProgress(e,p)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){var{ssoLog:t,utils:{safeStringify:i}}=this._core,t=(t.debug("_prepareUploadParams"," prepareUploadParams:"+i(e)),e)["file"],{IN_MINI_APP:i,IN_RN_APP:r}=I.getPlatformFlags(),i=i||r,r=i&&e.message.type!==m,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+a(999999)+e;return{fileName:n(r?t.name:e),resources:i?t.url:t,uploadMethod:i?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(n){return l(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:i}}=this._core,r=I.isSimpleCos(),o=this._prepareCosRequestData(n),s=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(o,s,a){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,i=e.generateCosSpecifiedData({servcmd:o,data:s}),r=i.head.seq+o;return yield t.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(s,o,this._core);this.fetchCosTryCount=0;var a=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+i(a)),a||{}}catch(e){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(n);throw this.fetchCosTryCount=0,e}})}_processResponse(e){var t;let i=I.isSimpleCos(),l=i?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(i){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:i,uint32_exist_flag:r,str_download_url:o,str_upload_url:s,str_snapshot_url:a,str_file_key:n}=l;return{uploadIP:e,preSig:t,fileID:i,existFlag:r,downloadUrl:o,uploadUrl:s,requestSnapshotUrl:a,fileKey:n}}let{upload_url:r,download_url:o,snapshot_url:s,thumb_url:a,large_url:n,file_key:h}=l;return{uploadUrl:r,downloadUrl:o,requestSnapshotUrl:s,thumbUrl:a,largeUrl:n,fileKey:h}}_prepareCosRequestData(e){return I.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:I.getPlatform(),uint32_sdkappid:I.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(o){return l(this,void 0,void 0,function*(){return new Promise((i,r)=>{this.httpRequest.request(o,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(o).then(i).catch(r)):(this.uploadFileTryCount=0,e?r(e):i(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,i;try{var r=null==(t=e.error)?void 0:t.Code,o=null==(i=e.error)?void 0:i.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,i=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(i){let e=Date.now(),t=Date.parse(i);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=I.getFileUploadProxy();let i=e;return i=t?e.replace(/^https:\/\/[^/]+/,t):i}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let q=["jpg","jpeg","gif","png","bmp","image","webp"],U=20971520,w={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class V{constructor(e,t){this.instanceID=a(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=I.addAuthToUrl(e.imageUrl||e.url||""),this.url=I.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=I.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function P(t){var{originUrl:t,originWidth:i,originHeight:r,min:o=198}=t,i=parseInt(i)||0,r=parseInt(r)||0,s={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)s.url=t,s.width=i,s.height=r;else{r<=i?(s.width=Math.ceil(i*o/r),s.height=o):(s.width=o,s.height=Math.ceil(r*o/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";s.url=198===o?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?g(s,["url"]):s}class S{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=p;var{uuid:e,file:t,imageFormat:i,imageInfoArray:r=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:i,uuid:e,imageInfoArray:[]},this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:i,ImageInfoArray:r,UUID:o}=t,s=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new S({imageFormat:i,imageInfoArray:s,uuid:o})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:i,IN_RN_APP:r,IN_BROWSER:o}=I.getPlatformFlags();return t=e&&((i||r)&&(t=e.url),o)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var i={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},i),r=new V(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,i;e.url&&""!==e.imageUrl&&([t,...i]=e.imageUrl.split("://"),i=i.join("://"),r.includes(t)||e.setImageUrl("https://"+i))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=w[e.toUpperCase()]||w.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var i,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)i=this.content.imageInfoArray[e],t[e].size&&(i.size=t[e].size),t[e].url&&i.setImageUrl(t[e].url),t[e].width&&(i.width=t[e].width),t[e].height&&(i.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,i=t[2];t[2]=t[1],t[1]=i;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],P({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var[e]=this.content.imageInfoArray,e=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(i),UUID:e}}}parseImageInfoArray(e){return e.map(e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:I.removeAuthToUrl(e.imageUrl)}))}}var F=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(p,S),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createImageMessage(e){var t,i,r;try{var o=null==(t=this._core.store.get("login"))?void 0:t.userId,s=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),a=this._processImage(e),n=(e.payload.file=a,{imageFormat:w.UNKNOWN,uuid:I.generateUUID(a),file:a,imageInfoArray:[]}),l=new S(n);return s.setElement(l),this._messageOptionsMap.set(s.clientSequence,e),s}catch(e){throw e}}upload(r){return l(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),i=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(i),r})}_performImageUpload(r,o,i){return l(this,void 0,void 0,function*(){var e=o["to"],{uploadOptions:e,response:t}=yield y.uploadToCOS({uploadFileType:1,file:i,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:i,height:r,smallImageUrl:o,smallImageWidth:s,smallImageHeight:a,largeImageUrl:n,largeImageWidth:l,largeImageHeight:h,imageInfoArray:d}=e,e=I.addAuthToUrl(e),u={size:t,url:e,width:i,height:r};return 0<(null==d?void 0:d.length)?this._processImageInfoArray(d,t):o&&n?[Object.assign({},u),{largeImageUrl:n,largeImageWidth:l,largeImageHeight:h},{smallImageUrl:o,smallImageWidth:s,smallImageHeight:a}]:[Object.assign({},u),this._generateThumbInfo(e,i,r,720),this._generateThumbInfo(e,i,r,198)]}_generateThumbInfo(e,t,i,r){return P({originUrl:e,originWidth:t,originHeight:i,min:r})}_processImageInfoArray(e,t){let i,r,o;for(var s of e)1===s.type?(r=s,r.size=t):2===s.type?(o=s,o.size=t):(i=s,i.size=t);return[Object.assign({},i),Object.assign({},o),Object.assign({},r)]}_parseResponse(r,o){return l(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:i}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,o,"thumb"),yield this._getImageInfoByUrl(t,o,"large")),I.isSimpleCos()&&!I.isPrivateNetWork()&&(yield this._getImageInfoArray(i,o),null!=o)&&o.uploadIP){let e=this._extractDomainFromUrl(i);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,o,s){return l(this,void 0,void 0,function*(){var t;try{let e=I.addAuthToUrl(r),{width:t=0,height:i=0}=yield I.probeImageWidthHeight(e);o.width=t,o.height=i,"thumb"===s?(o.smallImageUrl=r,o.smallImageWidth=t,o.smallImageHeight=i):(o.largeImageUrl=r,o.largeImageWidth=t,o.largeImageHeight=i)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${s} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var i=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return i?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){s(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=I.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,o){return l(this,void 0,void 0,function*(){var e=_+" getDownloadIP domainName: "+r;try{var t,i=yield function(a,n){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,i="im_cos_msg.get_final_ip",r={str_domain:a},o=e.generateProtocolData({servcmd:i,data:r}),s=o.head.seq+i;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);i&&i.str_final_ip&&(console.log(e+" ok. downloadIP:"+i),(t=o.location.split("/"))[0]=i.str_final_ip,o.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,i){return l(this,void 0,void 0,function*(){try{var e=yield function(a,n){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,i="im_cos_msg.get_imageinfo",r={str_image_url:a},o=e.generateProtocolData({servcmd:i,data:r}),s=o.head.seq+i;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return i.imageInfoArray=this._processImageInfoResponse(e),i}catch(e){throw i.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:i}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),q.indexOf(r.toLowerCase())<0)throw new i.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:i}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new i.ChatError({code:2108});if(r>=U)throw new i.ChatError({message:"File size exceeds limit: "+d(U)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let b="2.5.0",M="1.18.0",i=104857600;function A(e,t){let r=e.split("."),o=t.split("."),s=Math.max(r.length,o.length);for(;r.length<s;)r.push("0");for(;o.length<s;)o.push("0");for(let i=0;i<s;i++){let e=parseInt(r[i]),t=parseInt(o[i]);if(e>t)return 1;if(e<t)return-1}return 0}let T=new class{init(e){this.core=e}};class O{constructor(e){this.type=m,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:I.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:i,FileSize:r,UUID:o}=e;return new O({downloadFlag:e,url:t,fileName:i,fileSize:r,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:i,fileName:r,fileSize:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:I.removeAuthToUrl(i),FileName:r,FileSize:o,UUID:e}}}_getFileInfo(e){var t=T.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=a(999999)+"."+t)),e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var C=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(m,O),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createFileMessage(e){var t,i,r;try{this._checkVersion();var o=this._processFile(e.payload.file),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={uuid:I.generateUUID(o),file:o},l=new O(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw e}}upload(i){return l(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(i.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),i.getElements()[0]),e=yield this._performFileUpload(t,i,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),i})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>i)throw new t({message:"File size exceeds limit: "+d(i)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,o,t){return l(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:255,file:t,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:i,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:o,IN_UNI_NATIVE_APP:s}=null==(e=this._core)?void 0:e.utils,a=(null==(a=this._core)?void 0:a.helper)["ChatError"];if(e||s){let e=I.extractFileFromInput(t);if(e)return e;throw new a({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||o){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return i?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:o}=null==(e=this._core)?void 0:e.utils,s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(e){if(!(i||r||o))throw new s({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(i&&A(e,b)<0)throw new s({message:`WXChooseMessageFile requires SDK version ${b} or higher`});if(r&&A(e,M)<0)throw new s({message:`QQChooseMessageFile requires SDK version ${M} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let B=["mp4","quicktime","mov"],N=104857600;class E{constructor(e){this.type=f,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:I.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:I.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:I.addAuthToUrl(e.thumbUrl),snapshotUrl:I.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:i,VideoSize:r,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:h,ThumbHeight:d,SnapshotHeight:u,ThumbSize:p,SnapshotSize:c,ThumbDownloadFlag:m,ThumbUrl:g,SnapshotUrl:f}=e;return new E({videoUrl:e,videoFormat:t,videoSecond:i,videoSize:r,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:h,thumbHeight:d,snapshotHeight:u,thumbSize:p,snapshotSize:c,thumbDownloadFlag:m,thumbUrl:g,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:i}=e;I.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),I.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),I.isEmpty(i)||(this.content.thumbHeight=this.content.snapshotHeight=Number(i))}validateBeforeSend(){var e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:i,videoSize:r,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:h,thumbHeight:d,snapshotHeight:u,thumbSize:p,snapshotSize:c,thumbDownloadFlag:m,thumbUrl:g,snapshotUrl:f}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:I.removeAuthToUrl(e),VideoFormat:t,VideoSecond:i,VideoSize:r,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:h,ThumbHeight:d,SnapshotHeight:u,ThumbSize:p,SnapshotSize:c,ThumbDownloadFlag:m,ThumbUrl:I.removeAuthToUrl(g),SnapshotUrl:I.removeAuthToUrl(f)}}}}var D=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(f,E),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createVideoMessage(e){var t,i,r;try{var o=this._processVideo(e),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={videoFormat:o.videoFile.type,videoSecond:h(o.videoFile.second,0),videoSize:o.videoFile.size,remoteVideoUrl:"",videoUrl:o.videoFile.url,videoUUID:I.generateUUID(o.videoFile),thumbUUID:I.generateUUID(o.videoFile,"jpg"),thumbWidth:o.width||200,thumbHeight:o.height||200,thumbUrl:o.thumbUrl,thumbSize:o.thumbSize,thumbFormat:"jpg"},l=new E(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw e}}upload(r){return l(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:i}=t,t=I.addAuthToUrl(t);return e.updateVideoUrl(t),I.isEmpty(i)||e.updateSnapshotInfo(i),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>N)throw new t({message:"File size exceeds limit: "+d(N)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===B.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(r,o,i){return l(this,void 0,void 0,function*(){var e=o["to"],{response:e,uploadOptions:t}=yield y.uploadToCOS({uploadFileType:2,file:i,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,o;try{var s=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:a,IN_BROWSER:n}=null==(o=this._core)?void 0:o.utils;let t=e.payload["file"],i={};if(a&&(i=this._processMiniVideoFile(t),t.name=i.name,t.url=i.url,t.type=i.type),n){let e=I.extractFileFromInput(t);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,i=this._processWebVideoFile(t)}return t.videoFile=i,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(_+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:i}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(s(e))throw new r({message:"FileUnsupportedInMiniApp"});let o=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return i&&(o=e.fileType||o),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:o}}_processWebVideoFile(e){var{name:t,size:i=1,duration:r=0,type:o}=e,o=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:i,second:r,type:o}}_getSnapshotInfoByUrl(s){return l(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",_+" _getSnapshotInfoByUrl url:"+s);var t,i,r,o=((yield function(s,a){return l(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:i}=a,r=t.generateCosSpecifiedData({servcmd:e,data:s}),o=r.head.seq+e;return yield i.sendPacket(r,{requestId:o})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:I.getPlatform(),cover_name:n(a(99999)),snapshot_url:s},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",_+" _getSnapshotInfoByUrl OK snapshotUrl:"+o),I.isEmpty(o))?{}:(t=I.addAuthToUrl(o),{width:i=0,height:r=0}=yield I.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:i,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class R{constructor(e){this.uploadProgress=0,this.type=c,this.content={downloadFlag:2,second:e.second,size:e.size,url:I.addAuthToUrl(e.url),remoteAudioUrl:I.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:i,Size:r,UUID:o}=e;return new R({url:e,downloadFlag:t,second:i,size:r,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:i,size:r,second:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:I.removeAuthToUrl(i),Download_Flag:t,Second:o,Size:r,UUID:e}}}}var L=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(c,R),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createAudioMessage(e){var t,i,r;try{var o=e.payload["file"],o=this._processAudioFile(e.payload.file),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={second:Math.floor((o.duration||o.second)/1e3),size:o.fileSize||o.size||1,url:o.tempFilePath||o.uri||o.url,uuid:I.generateUUID(o)},l=new R(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}upload(i){return l(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",_+" uploadAudio message:"+t(i)),this._messageOptionsMap.get(i.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),i.getElements()[0]),e=yield this._performAudioUpload(t,i,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),i})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+d(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,o,t){return l(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:3,file:t,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}}))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:i}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):i?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let t={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},k={createImageMessage:t,createAudioMessage:t,createVideoMessage:t,createFileMessage:t},H={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},K={TIMImageElem:F,TIMFileElem:C,TIMVideoFileElem:D,TIMSoundElem:L};return new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:i,MSG_IMAGE:r,MSG_VIDEO:o}}=(this._core=e)["constants"];T.init(e),F.init(e),C.init(e),D.init(e),L.init(e),y.init(e),I.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,i,r,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:H,params:k})}sendMessage(r,o){return l(this,void 0,void 0,function*(){var e,t,i;try{return yield this._upload(r),yield null==(i=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:i.sendMessage(r,o)}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"sendMessage",code:t})}})}_upload(i){return l(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(i)),!0!==i._relayFlag)try{let e=K[i.type];e&&(yield e.upload(i),t.info("_upload"," type:"+i.type))}catch(t){throw i.status=r.FAIL,t instanceof Error&&(t.data={message:i}),this._core.message.messageDataHandler.storeConversationMessage(i),t}})}}});
@@ -1 +1 @@
1
- function i(i,r,o,g){return new(o=o||Promise)(function(n,e){function t(i){try{s(g.next(i))}catch(i){e(i)}}function a(i){try{s(g.throw(i))}catch(i){e(i)}}function s(i){var e;i.done?n(i.value):((e=i.value)instanceof o?e:new o(function(i){i(e)})).then(t,a)}s((g=g.apply(i,r||[])).next())})}let e=1,n=2,t=3,s=4,a=5,o="TIMCustomElem",r="C2C",g="GROUP",l="invite",c="accept",v="cancel",u="reject",h="modifyInvitation",d="signaling",I=8010,_="signaling-timeout";function S(i){return i.filter(i=>{var e,n;return i.type===o&&({cloudCustomData:i="",payload:{data:n=""}={}}=i,i=i.match(/"type":"tsignaling"/),e=n.match(/inviteID/),n=n.match(/actionType/),i||e&&n)})}function p(i){var e=i.payload["data"];try{return JSON.parse(e)}catch(i){return console.error(i),null}}function f(i,e){return i.toString(16).padStart(e,"0")}function m(i){if(i<0||53<i)throw new Error("Number of digits must be between 0 and 53");return i<=30?Math.floor(Math.random()*(1<<i)):(i=i-30,Math.floor(Math.random()*(1<<i))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var D=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(i){(this._core=i).notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(i){return this._onlineSignalingMap.has(i)}getSignaling(i){return this._onlineSignalingMap.get(i)}saveSignaling(i,e){return this._onlineSignalingMap.set(i,e)}removeSignaling(i){return this._onlineSignalingMap.delete(i)}isInvitationValid(i){var e=d+".isInvitationValid",{inviteID:i,groupID:n,inviter:t}=i,t=t===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(i))return!1;var a=this._onlineSignalingMap.get(i)["inviteeList"];if(console.log(e+` inviteID:${i} inviteeList:${a} groupID:`+n),n){if(t)return 0<a.length;let i=this._core.common.getCurrentUserID();return a.includes(i)}return!0}updateSignaling(i){let n=d+".updateSignaling",{inviteID:t,inviter:e,inviteeList:a,groupID:s}=i;if(console.log(n+` inviteID:${t} inviter:${e} groupID:`+s),s&&this.hasSignaling(t)){let i=a[0],e=this._onlineSignalingMap.get(t)["inviteeList"];e.includes(i)&&(e.splice(e.indexOf(i),1),console.log(n+` remove ${i}. localInviteeList.length:`+e.length)),0===e.length&&this.removeSignaling(t)}else this.removeSignaling(t)}setSignalingListenStatus(i){this._isSignalingListening=i}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},E=new class{init(i){this._core=i}createInviteSignaling(i){var e=this._generateInviteID(),e=this._createInviteSignalingData(Object.assign(Object.assign({},i),{inviteID:e})),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createAcceptSignaling(i){var e=this._createAcceptSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createCancelSignaling(i){var e=this._createCancelSignalingData(i),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createRejectSignaling(i){var e=this._createRejectSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createTimeoutSignaling(i){var{isInviter:e=!1}=i,i=this._createTimeoutSignalingData(i),{groupID:n,inviteeList:t,inviter:a}=i,n=n||(e?t[0]:a);return{signaling:this._createSignaling(i,n),signalingData:i,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}_createSignalingExtensionOptions(i){var{data:i="",onlineUserOnly:e,inviteID:n="",offlinePushInfo:t,actionType:a}=i,n=(null==(n=null==(n=D.getSignaling(n))?void 0:n.signaling)?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:e||n,offlinePushInfo:t,messageControlInfo:this._createMessageControlInfo(i,a)}}_createMessageControlInfo(i,e){e=e===a&&!!i.match(/excludeTimeoutSignalingFromHistoryMessage/),i=!!i.match(/excludeFromHistoryMessage/)||!!i.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:e||i,excludedFromLastMessage:e||i}}_createInviteSignalingData(i){var n=d+"._createInviteSignalingData",{userID:t,timeout:a=0,groupID:s="",inviteeList:r=[]}=i,o=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:e,inviter:o,inviteeList:s?r:[t],timeout:a});return console.log(n+" signalingData:",i),i}_createAcceptSignalingData(i){var e=d+"._createAcceptSignalingData",n=i["inviteID"],a=this._core.common.getCurrentUserID(),{inviter:n,groupID:s}=D.getSignaling(n),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:t,groupID:s,inviter:n,inviteeList:[a]});return console.log(e+" signalingData:",i),i}_createCancelSignalingData(i){var e=d+"._createCancelSignalingData",t=i["inviteID"],a=this._core.common.getCurrentUserID(),{inviteeList:t,groupID:s}=D.getSignaling(t),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:n,groupID:s,inviter:a,inviteeList:t});return console.log(e+" signalingData:",i),i}_createRejectSignalingData(i){var e=d+"._createRejectSignalingData",n=i["inviteID"],t=this._core.common.getCurrentUserID(),{inviter:n,groupID:a}=D.getSignaling(n),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:s,groupID:a,inviter:n,inviteeList:[t]});return console.log(e+" signalingData:",i),i}_createTimeoutSignalingData(i){var e=d+"._createTimeoutSignalingData",{isInviter:n=!1,inviteID:t}=i,{inviteeList:t,inviter:s}=D.getSignaling(t),r=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:a,inviter:s,inviteeList:n?t:[r]});return console.log(e+" signalingData:",i),i}_createSignaling(i,e){var{groupID:n=""}=i,e={to:e,conversationType:n?g:r,priority:"High",payload:{data:JSON.stringify(i)}};return null==(n=null==(i=null==(n=this._core)?void 0:n.message)?void 0:i.messageFactory)?void 0:n.createCustomMessage(e)}_generateInviteID(){return[f(m(32),8),f(m(16),4),f(16384|m(12),4),f(32768|m(14),4),f(m(48),12)].join("-")}_generateBaseSignalData(i){var{data:i="",inviteID:e="",groupID:n=""}=i;return{businessID:1,timeout:0,data:i,inviteID:e,groupID:n}}},O=new class{constructor(){this._isProcessingSignaling=!1}init(i){(this._core=i).helper.registerApi({apiName:"invite",context:this}),i.helper.registerApi({apiName:"accept",context:this}),i.helper.registerApi({apiName:"cancel",context:this}),i.helper.registerApi({apiName:"reject",context:this}),i.helper.registerApi({apiName:"modifyInvitation",context:this}),i.helper.registerApi({apiName:"getSignalingInfo",context:this}),i.helper.registerApi({apiName:"addSignalingListener",context:this}),i.helper.registerApi({apiName:"removeSignalingListener",context:this}),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}invite(e){return i(this,void 0,void 0,function*(){var n;console.log(d+".invite params:"+JSON.stringify(e));try{this._validateBeforeInvite(e);var{signaling:t,signalingData:a,signalingExtensionOptions:i}=E.createInviteSignaling(e),s=yield this._sendSignaling(t,i);if(0!==(null==s?void 0:s.code))return s;{let{inviteID:i,timeout:e}=a;return D.saveSignaling(i,Object.assign(Object.assign({},a),{signaling:t})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:_+"-"+i,intervalMs:1e3*(e+5),callback:this.handleInvitationExpiryTimer.bind(this,i)})),Object.assign(Object.assign({},s),{inviteID:i})}}catch(n){throw console.error(d+".invite error:"+n),n}})}accept(s){return i(this,void 0,void 0,function*(){console.log(d+".accept params:"+JSON.stringify(s));try{var i=s["inviteID"],{signaling:e,signalingData:n,signalingExtensionOptions:t}=(this._validateBeforeAccept(i),this._isProcessingSignaling=!0,E.createAcceptSignaling(s)),a=yield this._sendSignaling(e,t);return 0===(null==a?void 0:a.code)?(D.updateSignaling(n),Object.assign(Object.assign({},a),{inviteID:i})):a}catch(i){throw console.error(d+".accept error:"+i),i}finally{this._isProcessingSignaling=!1}})}cancel(a){return i(this,void 0,void 0,function*(){console.log(d+".cancel params:"+JSON.stringify(a));try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeCancel(i),this._isProcessingSignaling=!0,E.createCancelSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(D.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw console.error(d+".cancel error:"+i),i}finally{this._isProcessingSignaling=!1}})}reject(a){return i(this,void 0,void 0,function*(){console.log(d+".reject params:"+JSON.stringify(a));try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeReject(i),this._isProcessingSignaling=!0,E.createRejectSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(D.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw console.error(d+".reject error:"+i),i}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return i(this,void 0,void 0,function*(){console.log(d+".modifyInvitation params:"+JSON.stringify(e));var t,a,{inviteID:s,data:r}=e;let o="";try{this._validateBeforeModifyInvitation(s);let i=D.getSignaling(s),e=i["signaling"],n=function(i,e){var n={};for(a in i)Object.prototype.hasOwnProperty.call(i,a)&&e.indexOf(a)<0&&(n[a]=i[a]);if(null!=i&&"function"==typeof Object.getOwnPropertySymbols)for(var t=0,a=Object.getOwnPropertySymbols(i);t<a.length;t++)e.indexOf(a[t])<0&&Object.prototype.propertyIsEnumerable.call(i,a[t])&&(n[a[t]]=i[a[t]]);return n}(i,["signaling"]);o=e.payload.data,n.data=r,e.payload.data=JSON.stringify(n);var g=yield null==(a=null==(t=this._core)?void 0:t.message.messageAction)?void 0:a.modifyMessage(e);return D.hasSignaling(s)&&D.saveSignaling(s,Object.assign(Object.assign({},n),{signaling:e})),g}catch(t){if(o){let i=D.getSignaling(s)["signaling"];i.payload.data=o}throw t}})}getSignalingInfo(i){if(0!==S([i]).length)return i={businessID:(i=p(i)).businessID||1,inviteID:i.inviteID,groupID:i.groupID||"",inviter:i.inviter||"",inviteeList:i.inviteeList||[],data:i.data||"",actionType:i.actionType||e,timeout:i.timeout||0},console.log(d+" getSignalingInfo ",i),i}addSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&D.setSignalingListenStatus(!0),null!=(t=this._core)&&t.notificationCenter.subscribeOuterEvent(i,e,n)}removeSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&D.setSignalingListenStatus(!1),null!=(t=this._core)&&t.notificationCenter.unSubscribeOuterEvent(i,e,n)}handleInvitationExpiryTimer(i){var e=D.getOnlineSignalingMap(),n=this._core.common.getCurrentUserID();e.has(i)&&(e=e.get(i).inviter===n,this._sendTimeoutNotice({inviteID:i,isInviter:e}))}_sendSignaling(e,n){return i(this,void 0,void 0,function*(){var i;return null==(i=null==(i=null==(i=this._core)?void 0:i.message)?void 0:i.messageSender)?void 0:i.sendMessage(e,n)})}_sendTimeoutNotice(n){return i(this,void 0,void 0,function*(){var a;console.log(d+"._sendTimeoutNotice params:"+JSON.stringify(n));let{isInviter:s,inviteID:r}=n,{signaling:o,signalingData:g,signalingExtensionOptions:i}=E.createTimeoutSignaling(n),e=yield this._sendSignaling(o,i);if(0===(null==e?void 0:e.code)){let{data:i,groupID:e,inviteeList:n,inviter:t}=g;null!=(a=this._core)&&a.notificationCenter.emitOuterEvent(null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,{name:null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,data:{data:i,groupID:e,inviteID:r,inviteeList:n,inviter:t,isSelfTimeout:!0,message:o}}),s?D.removeSignaling(r):D.updateSignaling(g)}})}_validateInviteId(i,e){if(!D.hasSignaling(e))throw new this._core.helper.ChatError({functionName:i,code:I})}_validateProcessStatus(i){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:i,message:"processing other signaling operations"})}_validateBeforeInvite(i){var e=l,i=i["userID"],n=this._core.common.getCurrentUserID();if(i===n)throw new this._core.helper.ChatError({functionName:e,message:`cannot invite yourself, currentUserId:${n}, inviteeId:`+i})}_validateBeforeAccept(e){var n=c;this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=D.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeCancel(i){var e=v,n=(this._validateInviteId(e,i),this._validateProcessStatus(e),this._core.common.getCurrentUserID()),t=D.getSignaling(i)["inviter"];if(t!==n){let i=`unmatched inviter:${t} and my userID:`+n;throw new this._core.helper.ChatError({functionName:e,message:i})}}_validateBeforeReject(e){var n=u;this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=D.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeModifyInvitation(i){var e=h;this._validateInviteId(e,i)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},b=new class{constructor(){this._actionProcessor=new Map([[e,this._onNewInvitationReceived.bind(this)],[s,this._onInviteeRejected.bind(this)],[t,this._onInviteeAccepted.bind(this)],[n,this._onInvitationCancelled.bind(this)],[a,this._onInvitationTimeout.bind(this)]])}init(i){(this._core=i).notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),i.notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(i){i.forEach(i=>{var e,n=p(i);n&&null!=(e=this._actionProcessor.get(n.actionType))&&e(n,i)})}_handleMessageReceived(i){D.getSignalingListenStatus()&&0!==(i=S(i.data)).length&&this.handleActionSignaling(i)}_handleMessageModified(i){D.getSignalingListenStatus()&&0<(i=S(i.data)).length&&i.forEach(i=>{var e=p(i);e&&this._onInvitationModified(e,i)})}_onNewInvitationReceived(e,n){var t=d+"._onNewInvitationReceived",{inviteID:a,inviteeList:s,groupID:r}=e,o=this._core.common.getCurrentUserID();if(console.log(t+` signalingData:${JSON.stringify(e)}}`),!r||s.includes(o)){let i=e["timeout"];var t=Date.now()/1e3-n.time,r=(0<i&&0<t&&i>t&&(i-=t),D.getSignaling(a));r!==e&&(r||D.saveSignaling(a,Object.assign(Object.assign({},e),{signaling:n})),0<i&&(null!=(o=this._core)&&o.helper.taskScheduler.addOnceTask({id:_+"-"+a,intervalMs:1e3*i,callback:O.handleInvitationExpiryTimer.bind(O,a)})),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:s})}))}}_onInviteeRejected(i){var e=d+"._onInviteeRejected",{inviteID:n,inviter:t,groupID:a,inviteeList:s}=i,r=D.hasSignaling(n);console.log(e+` inviteID:${n} hasInviteID:${r} inviter:${t} groupID:`+a),r&&(D.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:s[0]})}))}_onInviteeAccepted(i){var e=d+"._onInviteeAccepted",{inviteID:n,inviter:t,groupID:a,inviteeList:s}=i,r=D.hasSignaling(n);console.log(e+` inviteID:${n} hasInviteID:${r} inviter:${t} groupID:`+a),r&&(D.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:s[0]})}))}_onInvitationCancelled(i){var e=d+"._onInvitationCancelled",{inviteID:n,inviter:t,groupID:a}=i,s=D.hasSignaling(n);console.log(e+` inviteID:${n} hasInviteID:${s} inviter:${t} groupID:`+a),s&&(D.removeSignaling(n),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(i)}))}_onInvitationTimeout(i){var e=d+"._onInvitationTimeout",{inviteID:n,inviteeList:t}=i,a=D.hasSignaling(n);console.log(e+` inviteID:${n} hasInviteID:${a} data:`+i.data),a&&(D.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{inviteeList:t,isSelfTimeout:!1})}))}_onInvitationModified(i,e){var n=d+"._onInvitationModified",{inviteID:t,data:a}=i,s=D.hasSignaling(t);console.log(n+` inviteID:${t} data:`+a),s&&(D.saveSignaling(t,Object.assign(Object.assign({},i),{signaling:e})),this._emitEvent({name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:t,data:a}}))}_emitEvent(i){var e;null!=(e=this._core)&&e.notificationCenter.emitOuterEvent(i.name,i)}_generateBaseEmitData(i){var{inviteID:i,inviter:e,groupID:n,data:t}=i;return{inviteID:i,inviter:e,groupID:n,data:t||""}}_dispose(){var i;null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},y=new class{constructor(){this._offlineSignalingMap=new Map}init(i){var{notificationCenter:i,helper:e,constants:{InnerEvent:n,WORKFLOW_STEP:t,WORKFLOW_NAME:a}}=this._core=i;i.subscribeInnerEvent(n.DESTROY,this._dispose,this),i.subscribeInnerEvent(n.LOGOUT,this._reset,this),e.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_LOGIN,t.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(i){var{result:{unreadMessageMap:i}={}}=i||{};if(0!==(null==i?void 0:i.size)&&D.getSignalingListenStatus()){i=S([...i.values()]);if(0!==i.length&&(i.forEach(i=>{this._handleC2CActionType(i)}),0<this._offlineSignalingMap.size)){let i=this._sortOfflineSignalingByTime();b.handleActionSignaling(i)}}}_handleC2CActionType(i){var n,t=p(i);t&&(n=t["actionType"],n===e?this._saveValidOfflineInvite(t,i):this._removeOfflineInvite(t))}_saveValidOfflineInvite(i,e){var{inviteID:n,inviteeList:t=[],timeout:a=0}=i,s=this._core.common.getCurrentUserID();t.includes(s)&&(t=Date.now()/1e3-e.time,0<a&&a<t&&0!==a||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},i),{signalingList:[e]})))}_removeOfflineInvite(i){var{inviteID:i=""}=i;this._offlineSignalingMap.has(i)&&this._offlineSignalingMap.delete(i)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach(i=>{e=[...e,...i.signalingList]}),e.sort((i,e)=>i.time-e.time)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let $={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},C={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var T=new class{constructor(){this.name="Signaling"}install(i){O.init(i),b.init(i),E.init(i),D.init(i),y.init(i),i.helper.registerValidateConfig({auth:C,params:$})}};export{T as default};
1
+ function i(i,r,o,g){return new(o=o||Promise)(function(n,e){function t(i){try{s(g.next(i))}catch(i){e(i)}}function a(i){try{s(g.throw(i))}catch(i){e(i)}}function s(i){var e;i.done?n(i.value):((e=i.value)instanceof o?e:new o(function(i){i(e)})).then(t,a)}s((g=g.apply(i,r||[])).next())})}let e=1,n=2,t=3,s=4,a=5,o="TIMCustomElem",r="C2C",g="GROUP",l="invite",c="accept",v="cancel",u="reject",h="modifyInvitation",d="signaling",_=8010,I="signaling-timeout";function S(i){return i.filter(i=>{var e,n;return i.type===o&&({cloudCustomData:i="",payload:{data:n=""}={}}=i,i=i.match(/"type":"tsignaling"/),e=n.match(/inviteID/),n=n.match(/actionType/),i||e&&n)})}function p(i){var e=i.payload["data"];try{return JSON.parse(e)}catch(i){return console.error(i),null}}function f(i,e){return i.toString(16).padStart(e,"0")}function D(i){if(i<0||53<i)throw new Error("Number of digits must be between 0 and 53");return i<=30?Math.floor(Math.random()*(1<<i)):(i=i-30,Math.floor(Math.random()*(1<<i))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var m=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(i){(this._core=i).notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(i){return this._onlineSignalingMap.has(i)}getSignaling(i){return this._onlineSignalingMap.get(i)}saveSignaling(i,e){return this._onlineSignalingMap.set(i,e)}removeSignaling(i){return this._onlineSignalingMap.delete(i)}isInvitationValid(i){var e=d+".isInvitationValid",{inviteID:i,groupID:n,inviter:t}=i,t=t===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(i))return!1;var a=this._onlineSignalingMap.get(i)["inviteeList"];if(console.log(e+` inviteID:${i} inviteeList:${a} groupID:`+n),n){if(t)return 0<a.length;let i=this._core.common.getCurrentUserID();return a.includes(i)}return!0}updateSignaling(i){let n=d+".updateSignaling",{inviteID:t,inviter:e,inviteeList:a,groupID:s}=i;if(console.log(n+` inviteID:${t} inviter:${e} groupID:`+s),s&&this.hasSignaling(t)){let i=a[0],e=this._onlineSignalingMap.get(t)["inviteeList"];e.includes(i)&&(e.splice(e.indexOf(i),1),console.log(n+` remove ${i}. localInviteeList.length:`+e.length)),0===e.length&&this.removeSignaling(t)}else this.removeSignaling(t)}setSignalingListenStatus(i){this._isSignalingListening=i}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},E=new class{init(i){this._core=i}createInviteSignaling(i){var e=this._generateInviteID(),e=this._createInviteSignalingData(Object.assign(Object.assign({},i),{inviteID:e})),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createAcceptSignaling(i){var e=this._createAcceptSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createCancelSignaling(i){var e=this._createCancelSignalingData(i),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createRejectSignaling(i){var e=this._createRejectSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createTimeoutSignaling(i){var{isInviter:e=!1}=i,i=this._createTimeoutSignalingData(i),{groupID:n,inviteeList:t,inviter:a}=i,n=n||(e?t[0]:a);return{signaling:this._createSignaling(i,n),signalingData:i,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}_createSignalingExtensionOptions(i){var{data:i="",onlineUserOnly:e,inviteID:n="",offlinePushInfo:t,actionType:a}=i,n=(null==(n=null==(n=m.getSignaling(n))?void 0:n.signaling)?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:e||n,offlinePushInfo:t,messageControlInfo:this._createMessageControlInfo(i,a)}}_createMessageControlInfo(i,e){e=e===a&&!!i.match(/excludeTimeoutSignalingFromHistoryMessage/),i=!!i.match(/excludeFromHistoryMessage/)||!!i.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:e||i,excludedFromLastMessage:e||i}}_createInviteSignalingData(i){var n=d+"._createInviteSignalingData",{userID:t,timeout:a=0,groupID:s="",inviteeList:r=[]}=i,o=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:e,inviter:o,inviteeList:s?r:[t],timeout:a});return console.log(n+" signalingData:",i),i}_createAcceptSignalingData(i){var e=d+"._createAcceptSignalingData",n=i["inviteID"],a=this._core.common.getCurrentUserID(),{inviter:n,groupID:s}=m.getSignaling(n),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:t,groupID:s,inviter:n,inviteeList:[a]});return console.log(e+" signalingData:",i),i}_createCancelSignalingData(i){var e=d+"._createCancelSignalingData",t=i["inviteID"],a=this._core.common.getCurrentUserID(),{inviteeList:t,groupID:s}=m.getSignaling(t),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:n,groupID:s,inviter:a,inviteeList:t});return console.log(e+" signalingData:",i),i}_createRejectSignalingData(i){var e=d+"._createRejectSignalingData",n=i["inviteID"],t=this._core.common.getCurrentUserID(),{inviter:n,groupID:a}=m.getSignaling(n),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:s,groupID:a,inviter:n,inviteeList:[t]});return console.log(e+" signalingData:",i),i}_createTimeoutSignalingData(i){var e=d+"._createTimeoutSignalingData",{isInviter:n=!1,inviteID:t}=i,{inviteeList:t,inviter:s}=m.getSignaling(t),r=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:a,inviter:s,inviteeList:n?t:[r]});return console.log(e+" signalingData:",i),i}_createSignaling(i,e){var{groupID:n=""}=i,e={to:e,conversationType:n?g:r,priority:"High",payload:{data:JSON.stringify(i)}};return null==(n=null==(i=null==(n=this._core)?void 0:n.message)?void 0:i.messageFactory)?void 0:n.createCustomMessage(e)}_generateInviteID(){return[f(D(32),8),f(D(16),4),f(16384|D(12),4),f(32768|D(14),4),f(D(48),12)].join("-")}_generateBaseSignalData(i){var{data:i="",inviteID:e="",groupID:n=""}=i;return{businessID:1,timeout:0,data:i,inviteID:e,groupID:n}}},O=new class{constructor(){this._isProcessingSignaling=!1}init(i){(this._core=i).helper.registerApi({apiName:"invite",context:this}),i.helper.registerApi({apiName:"accept",context:this}),i.helper.registerApi({apiName:"cancel",context:this}),i.helper.registerApi({apiName:"reject",context:this}),i.helper.registerApi({apiName:"modifyInvitation",context:this}),i.helper.registerApi({apiName:"getSignalingInfo",context:this}),i.helper.registerApi({apiName:"addSignalingListener",context:this}),i.helper.registerApi({apiName:"removeSignalingListener",context:this}),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}invite(e){return i(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(e);var{signaling:t,signalingData:a,signalingExtensionOptions:i}=E.createInviteSignaling(e),s=yield this._sendSignaling(t,i);if(0!==(null==s?void 0:s.code))return s;{let{inviteID:i,timeout:e}=a;return m.saveSignaling(i,Object.assign(Object.assign({},a),{signaling:t})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:I+"-"+i,intervalMs:1e3*(e+5),callback:this.handleInvitationExpiryTimer.bind(this,i)})),Object.assign(Object.assign({},s),{inviteID:i})}}catch(n){throw n}})}accept(s){return i(this,void 0,void 0,function*(){try{var i=s["inviteID"],{signaling:e,signalingData:n,signalingExtensionOptions:t}=(this._validateBeforeAccept(i),this._isProcessingSignaling=!0,E.createAcceptSignaling(s)),a=yield this._sendSignaling(e,t);return 0===(null==a?void 0:a.code)?(m.updateSignaling(n),Object.assign(Object.assign({},a),{inviteID:i})):a}catch(i){throw i}finally{this._isProcessingSignaling=!1}})}cancel(a){return i(this,void 0,void 0,function*(){try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeCancel(i),this._isProcessingSignaling=!0,E.createCancelSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(m.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw i}finally{this._isProcessingSignaling=!1}})}reject(a){return i(this,void 0,void 0,function*(){try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeReject(i),this._isProcessingSignaling=!0,E.createRejectSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(m.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw i}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return i(this,void 0,void 0,function*(){var t,a,{inviteID:s,data:r}=e;let o="";try{this._validateBeforeModifyInvitation(s);let i=m.getSignaling(s),e=i["signaling"],n=function(i,e){var n={};for(a in i)Object.prototype.hasOwnProperty.call(i,a)&&e.indexOf(a)<0&&(n[a]=i[a]);if(null!=i&&"function"==typeof Object.getOwnPropertySymbols)for(var t=0,a=Object.getOwnPropertySymbols(i);t<a.length;t++)e.indexOf(a[t])<0&&Object.prototype.propertyIsEnumerable.call(i,a[t])&&(n[a[t]]=i[a[t]]);return n}(i,["signaling"]);o=e.payload.data,n.data=r,e.payload.data=JSON.stringify(n);var g=yield null==(a=null==(t=this._core)?void 0:t.message.messageAction)?void 0:a.modifyMessage(e);return m.hasSignaling(s)&&m.saveSignaling(s,Object.assign(Object.assign({},n),{signaling:e})),g}catch(t){if(o){let i=m.getSignaling(s)["signaling"];i.payload.data=o}throw t}})}getSignalingInfo(i){var{ssoLog:n,utils:{safeStringify:t}}=this._core;if(0!==S([i]).length)return i={businessID:(i=p(i)).businessID||1,inviteID:i.inviteID,groupID:i.groupID||"",inviter:i.inviter||"",inviteeList:i.inviteeList||[],data:i.data||"",actionType:i.actionType||e,timeout:i.timeout||0},n.debug(d+" getSignalingInfo "+t(i)),i}addSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&m.setSignalingListenStatus(!0),null!=(t=this._core)&&t.notificationCenter.subscribeOuterEvent(i,e,n)}removeSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&m.setSignalingListenStatus(!1),null!=(t=this._core)&&t.notificationCenter.unSubscribeOuterEvent(i,e,n)}handleInvitationExpiryTimer(i){var e=m.getOnlineSignalingMap(),n=this._core.common.getCurrentUserID();e.has(i)&&(e=e.get(i).inviter===n,this._sendTimeoutNotice({inviteID:i,isInviter:e}))}_sendSignaling(e,n){return i(this,void 0,void 0,function*(){var i;return null==(i=null==(i=null==(i=this._core)?void 0:i.message)?void 0:i.messageSender)?void 0:i.sendMessage(e,n)})}_sendTimeoutNotice(n){return i(this,void 0,void 0,function*(){var a;this._core.ssoLog.debug("_sendTimeoutNotice",d+"._sendTimeoutNotice params:"+JSON.stringify(n));let{isInviter:s,inviteID:r}=n,{signaling:o,signalingData:g,signalingExtensionOptions:i}=E.createTimeoutSignaling(n),e=yield this._sendSignaling(o,i);if(0===(null==e?void 0:e.code)){let{data:i,groupID:e,inviteeList:n,inviter:t}=g;null!=(a=this._core)&&a.notificationCenter.emitOuterEvent(null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,{name:null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,data:{data:i,groupID:e,inviteID:r,inviteeList:n,inviter:t,isSelfTimeout:!0,message:o}}),s?m.removeSignaling(r):m.updateSignaling(g)}})}_validateInviteId(i,e){if(!m.hasSignaling(e))throw new this._core.helper.ChatError({functionName:i,code:_})}_validateProcessStatus(i){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:i,message:"processing other signaling operations"})}_validateBeforeInvite(i){var e=l,i=i["userID"],n=this._core.common.getCurrentUserID();if(i===n)throw new this._core.helper.ChatError({functionName:e,message:`cannot invite yourself, currentUserId:${n}, inviteeId:`+i})}_validateBeforeAccept(e){var n=c;this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=m.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeCancel(i){var e=v,n=(this._validateInviteId(e,i),this._validateProcessStatus(e),this._core.common.getCurrentUserID()),t=m.getSignaling(i)["inviter"];if(t!==n){let i=`unmatched inviter:${t} and my userID:`+n;throw new this._core.helper.ChatError({functionName:e,message:i})}}_validateBeforeReject(e){var n=u;this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=m.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeModifyInvitation(i){var e=h;this._validateInviteId(e,i)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},b=new class{constructor(){this._actionProcessor=new Map([[e,this._onNewInvitationReceived.bind(this)],[s,this._onInviteeRejected.bind(this)],[t,this._onInviteeAccepted.bind(this)],[n,this._onInvitationCancelled.bind(this)],[a,this._onInvitationTimeout.bind(this)]])}init(i){(this._core=i).notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),i.notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(i){i.forEach(i=>{var e,n=p(i);n&&null!=(e=this._actionProcessor.get(n.actionType))&&e(n,i)})}_handleMessageReceived(i){m.getSignalingListenStatus()&&0!==(i=S(i.data)).length&&this.handleActionSignaling(i)}_handleMessageModified(i){m.getSignalingListenStatus()&&0<(i=S(i.data)).length&&i.forEach(i=>{var e=p(i);e&&this._onInvitationModified(e,i)})}_onNewInvitationReceived(e,n){var t=d+"._onNewInvitationReceived",{inviteID:a,inviteeList:s,groupID:r}=e,o=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",t+` signalingData:${JSON.stringify(e)}}`),!r||s.includes(o)){let i=e["timeout"];var t=Date.now()/1e3-n.time,r=(0<i&&0<t&&i>t&&(i-=t),m.getSignaling(a));r!==e&&(r||m.saveSignaling(a,Object.assign(Object.assign({},e),{signaling:n})),0<i&&(null!=(o=this._core)&&o.helper.taskScheduler.addOnceTask({id:I+"-"+a,intervalMs:1e3*i,callback:O.handleInvitationExpiryTimer.bind(O,a)})),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:s})}))}}_onInviteeRejected(i){var e=d+"._onInviteeRejected",{inviteID:n,inviter:t,groupID:a,inviteeList:s}=i,r=m.hasSignaling(n);this._core.ssoLog.debug("_onInviteeRejected",e+` inviteID:${n} hasInviteID:${r} inviter:${t} groupID:`+a),r&&(m.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:s[0]})}))}_onInviteeAccepted(i){var e=d+"._onInviteeAccepted",{inviteID:n,inviter:t,groupID:a,inviteeList:s}=i,r=m.hasSignaling(n);this._core.ssoLog.debug("_onInviteeAccepted",e+` inviteID:${n} hasInviteID:${r} inviter:${t} groupID:`+a),r&&(m.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:s[0]})}))}_onInvitationCancelled(i){var e=d+"._onInvitationCancelled",{inviteID:n,inviter:t,groupID:a}=i,s=m.hasSignaling(n);this._core.ssoLog.debug("_onInvitationCancelled",e+` inviteID:${n} hasInviteID:${s} inviter:${t} groupID:`+a),s&&(m.removeSignaling(n),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(i)}))}_onInvitationTimeout(i){var e=d+"._onInvitationTimeout",{inviteID:n,inviteeList:t}=i,a=m.hasSignaling(n);this._core.ssoLog.debug("_onInvitationTimeout",e+` inviteID:${n} hasInviteID:${a} data:`+i.data),a&&(m.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{inviteeList:t,isSelfTimeout:!1})}))}_onInvitationModified(i,e){var n=d+"._onInvitationModified",{inviteID:t,data:a}=i,s=m.hasSignaling(t);this._core.ssoLog.debug("_onInvitationModified",n+` inviteID:${t} data:`+a),s&&(m.saveSignaling(t,Object.assign(Object.assign({},i),{signaling:e})),this._emitEvent({name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:t,data:a}}))}_emitEvent(i){var e;null!=(e=this._core)&&e.notificationCenter.emitOuterEvent(i.name,i)}_generateBaseEmitData(i){var{inviteID:i,inviter:e,groupID:n,data:t}=i;return{inviteID:i,inviter:e,groupID:n,data:t||""}}_dispose(){var i;null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},y=new class{constructor(){this._offlineSignalingMap=new Map}init(i){var{notificationCenter:i,helper:e,constants:{InnerEvent:n,WORKFLOW_STEP:t,WORKFLOW_NAME:a}}=this._core=i;i.subscribeInnerEvent(n.DESTROY,this._dispose,this),i.subscribeInnerEvent(n.LOGOUT,this._reset,this),e.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_LOGIN,t.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(i){var{result:{unreadMessageMap:i}={}}=i||{};if(0!==(null==i?void 0:i.size)&&m.getSignalingListenStatus()){i=S([...i.values()]);if(0!==i.length&&(i.forEach(i=>{this._handleC2CActionType(i)}),0<this._offlineSignalingMap.size)){let i=this._sortOfflineSignalingByTime();b.handleActionSignaling(i)}}}_handleC2CActionType(i){var n,t=p(i);t&&(n=t["actionType"],n===e?this._saveValidOfflineInvite(t,i):this._removeOfflineInvite(t))}_saveValidOfflineInvite(i,e){var{inviteID:n,inviteeList:t=[],timeout:a=0}=i,s=this._core.common.getCurrentUserID();t.includes(s)&&(t=Date.now()/1e3-e.time,0<a&&a<t&&0!==a||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},i),{signalingList:[e]})))}_removeOfflineInvite(i){var{inviteID:i=""}=i;this._offlineSignalingMap.has(i)&&this._offlineSignalingMap.delete(i)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach(i=>{e=[...e,...i.signalingList]}),e.sort((i,e)=>i.time-e.time)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let C={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},T={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var M=new class{constructor(){this.name="Signaling"}install(i){O.init(i),b.init(i),E.init(i),m.init(i),y.init(i),i.helper.registerValidateConfig({auth:T,params:C})}};export{M as default};
@@ -1 +1 @@
1
- !function(i,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(i="undefined"!=typeof globalThis?globalThis:i||self).TencentCloudChatSignaling=e()}(this,function(){function t(i,r,o,g){return new(o=o||Promise)(function(n,e){function t(i){try{s(g.next(i))}catch(i){e(i)}}function a(i){try{s(g.throw(i))}catch(i){e(i)}}function s(i){var e;i.done?n(i.value):((e=i.value)instanceof o?e:new o(function(i){i(e)})).then(t,a)}s((g=g.apply(i,r||[])).next())})}let l="signaling",o="signaling-timeout";function e(i){return i.filter(i=>{var e,n;return"TIMCustomElem"===i.type&&({cloudCustomData:i="",payload:{data:n=""}={}}=i,i=i.match(/"type":"tsignaling"/),e=n.match(/inviteID/),n=n.match(/actionType/),i||e&&n)})}function a(i){var e=i.payload["data"];try{return JSON.parse(e)}catch(i){return console.error(i),null}}function i(i,e){return i.toString(16).padStart(e,"0")}function n(i){if(i<0||53<i)throw new Error("Number of digits must be between 0 and 53");return i<=30?Math.floor(Math.random()*(1<<i)):(i=i-30,Math.floor(Math.random()*(1<<i))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var c=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(i){(this._core=i).notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(i){return this._onlineSignalingMap.has(i)}getSignaling(i){return this._onlineSignalingMap.get(i)}saveSignaling(i,e){return this._onlineSignalingMap.set(i,e)}removeSignaling(i){return this._onlineSignalingMap.delete(i)}isInvitationValid(i){l;var{inviteID:i,groupID:e,inviter:n}=i,n=n===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(i))return!1;var t=this._onlineSignalingMap.get(i)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${i} inviteeList:${t} groupID:`+e),e){if(n)return 0<t.length;let i=this._core.common.getCurrentUserID();return t.includes(i)}return!0}updateSignaling(i){let n=l+".updateSignaling",{inviteID:t,inviter:e,inviteeList:a,groupID:s}=i;if(console.log(n+` inviteID:${t} inviter:${e} groupID:`+s),s&&this.hasSignaling(t)){let i=a[0],e=this._onlineSignalingMap.get(t)["inviteeList"];e.includes(i)&&(e.splice(e.indexOf(i),1),console.log(n+` remove ${i}. localInviteeList.length:`+e.length)),0===e.length&&this.removeSignaling(t)}else this.removeSignaling(t)}setSignalingListenStatus(i){this._isSignalingListening=i}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},v=new class{init(i){this._core=i}createInviteSignaling(i){var e=this._generateInviteID(),e=this._createInviteSignalingData(Object.assign(Object.assign({},i),{inviteID:e})),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createAcceptSignaling(i){var e=this._createAcceptSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createCancelSignaling(i){var e=this._createCancelSignalingData(i),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createRejectSignaling(i){var e=this._createRejectSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createTimeoutSignaling(i){var{isInviter:e=!1}=i,i=this._createTimeoutSignalingData(i),{groupID:n,inviteeList:t,inviter:a}=i,n=n||(e?t[0]:a);return{signaling:this._createSignaling(i,n),signalingData:i,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}_createSignalingExtensionOptions(i){var{data:i="",onlineUserOnly:e,inviteID:n="",offlinePushInfo:t,actionType:a}=i,n=(null==(n=null==(n=c.getSignaling(n))?void 0:n.signaling)?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:e||n,offlinePushInfo:t,messageControlInfo:this._createMessageControlInfo(i,a)}}_createMessageControlInfo(i,e){e=5===e&&!!i.match(/excludeTimeoutSignalingFromHistoryMessage/),i=!!i.match(/excludeFromHistoryMessage/)||!!i.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:e||i,excludedFromLastMessage:e||i}}_createInviteSignalingData(i){l;var{userID:e,timeout:n=0,groupID:t="",inviteeList:a=[]}=i,s=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:1,inviter:s,inviteeList:t?a:[e],timeout:n});return console.log("signaling._createInviteSignalingData signalingData:",i),i}_createAcceptSignalingData(i){l;var e=i["inviteID"],n=this._core.common.getCurrentUserID(),{inviter:e,groupID:t}=c.getSignaling(e),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:3,groupID:t,inviter:e,inviteeList:[n]});return console.log("signaling._createAcceptSignalingData signalingData:",i),i}_createCancelSignalingData(i){l;var e=i["inviteID"],n=this._core.common.getCurrentUserID(),{inviteeList:e,groupID:t}=c.getSignaling(e),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:2,groupID:t,inviter:n,inviteeList:e});return console.log("signaling._createCancelSignalingData signalingData:",i),i}_createRejectSignalingData(i){l;var e=i["inviteID"],n=this._core.common.getCurrentUserID(),{inviter:e,groupID:t}=c.getSignaling(e),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:4,groupID:t,inviter:e,inviteeList:[n]});return console.log("signaling._createRejectSignalingData signalingData:",i),i}_createTimeoutSignalingData(i){l;var{isInviter:e=!1,inviteID:n}=i,{inviteeList:n,inviter:t}=c.getSignaling(n),a=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:5,inviter:t,inviteeList:e?n:[a]});return console.log("signaling._createTimeoutSignalingData signalingData:",i),i}_createSignaling(i,e){var{groupID:n=""}=i,e={to:e,conversationType:n?"GROUP":"C2C",priority:"High",payload:{data:JSON.stringify(i)}};return null==(n=null==(i=null==(n=this._core)?void 0:n.message)?void 0:i.messageFactory)?void 0:n.createCustomMessage(e)}_generateInviteID(){return[i(n(32),8),i(n(16),4),i(16384|n(12),4),i(32768|n(14),4),i(n(48),12)].join("-")}_generateBaseSignalData(i){var{data:i="",inviteID:e="",groupID:n=""}=i;return{businessID:1,timeout:0,data:i,inviteID:e,groupID:n}}},g=new class{constructor(){this._isProcessingSignaling=!1}init(i){(this._core=i).helper.registerApi({apiName:"invite",context:this}),i.helper.registerApi({apiName:"accept",context:this}),i.helper.registerApi({apiName:"cancel",context:this}),i.helper.registerApi({apiName:"reject",context:this}),i.helper.registerApi({apiName:"modifyInvitation",context:this}),i.helper.registerApi({apiName:"getSignalingInfo",context:this}),i.helper.registerApi({apiName:"addSignalingListener",context:this}),i.helper.registerApi({apiName:"removeSignalingListener",context:this}),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}invite(e){return t(this,void 0,void 0,function*(){var n;console.log(l+".invite params:"+JSON.stringify(e));try{this._validateBeforeInvite(e);var{signaling:t,signalingData:a,signalingExtensionOptions:i}=v.createInviteSignaling(e),s=yield this._sendSignaling(t,i);if(0!==(null==s?void 0:s.code))return s;{let{inviteID:i,timeout:e}=a;return c.saveSignaling(i,Object.assign(Object.assign({},a),{signaling:t})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:o+"-"+i,intervalMs:1e3*(e+5),callback:this.handleInvitationExpiryTimer.bind(this,i)})),Object.assign(Object.assign({},s),{inviteID:i})}}catch(n){throw console.error(l+".invite error:"+n),n}})}accept(s){return t(this,void 0,void 0,function*(){console.log(l+".accept params:"+JSON.stringify(s));try{var i=s["inviteID"],{signaling:e,signalingData:n,signalingExtensionOptions:t}=(this._validateBeforeAccept(i),this._isProcessingSignaling=!0,v.createAcceptSignaling(s)),a=yield this._sendSignaling(e,t);return 0===(null==a?void 0:a.code)?(c.updateSignaling(n),Object.assign(Object.assign({},a),{inviteID:i})):a}catch(i){throw console.error(l+".accept error:"+i),i}finally{this._isProcessingSignaling=!1}})}cancel(a){return t(this,void 0,void 0,function*(){console.log(l+".cancel params:"+JSON.stringify(a));try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeCancel(i),this._isProcessingSignaling=!0,v.createCancelSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(c.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw console.error(l+".cancel error:"+i),i}finally{this._isProcessingSignaling=!1}})}reject(a){return t(this,void 0,void 0,function*(){console.log(l+".reject params:"+JSON.stringify(a));try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeReject(i),this._isProcessingSignaling=!0,v.createRejectSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(c.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw console.error(l+".reject error:"+i),i}finally{this._isProcessingSignaling=!1}})}modifyInvitation(i){return t(this,void 0,void 0,function*(){console.log(l+".modifyInvitation params:"+JSON.stringify(i));var t,a,{inviteID:s,data:r}=i;let o="";try{this._validateBeforeModifyInvitation(s);let i=c.getSignaling(s),e=i["signaling"],n=function(i,e){var n={};for(a in i)Object.prototype.hasOwnProperty.call(i,a)&&e.indexOf(a)<0&&(n[a]=i[a]);if(null!=i&&"function"==typeof Object.getOwnPropertySymbols)for(var t=0,a=Object.getOwnPropertySymbols(i);t<a.length;t++)e.indexOf(a[t])<0&&Object.prototype.propertyIsEnumerable.call(i,a[t])&&(n[a[t]]=i[a[t]]);return n}(i,["signaling"]);o=e.payload.data,n.data=r,e.payload.data=JSON.stringify(n);var g=yield null==(a=null==(t=this._core)?void 0:t.message.messageAction)?void 0:a.modifyMessage(e);return c.hasSignaling(s)&&c.saveSignaling(s,Object.assign(Object.assign({},n),{signaling:e})),g}catch(t){if(o){let i=c.getSignaling(s)["signaling"];i.payload.data=o}throw t}})}getSignalingInfo(i){if(0!==e([i]).length)return i={businessID:(i=a(i)).businessID||1,inviteID:i.inviteID,groupID:i.groupID||"",inviter:i.inviter||"",inviteeList:i.inviteeList||[],data:i.data||"",actionType:i.actionType||1,timeout:i.timeout||0},console.log(l+" getSignalingInfo ",i),i}addSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&c.setSignalingListenStatus(!0),null!=(t=this._core)&&t.notificationCenter.subscribeOuterEvent(i,e,n)}removeSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&c.setSignalingListenStatus(!1),null!=(t=this._core)&&t.notificationCenter.unSubscribeOuterEvent(i,e,n)}handleInvitationExpiryTimer(i){var e=c.getOnlineSignalingMap(),n=this._core.common.getCurrentUserID();e.has(i)&&(e=e.get(i).inviter===n,this._sendTimeoutNotice({inviteID:i,isInviter:e}))}_sendSignaling(e,n){return t(this,void 0,void 0,function*(){var i;return null==(i=null==(i=null==(i=this._core)?void 0:i.message)?void 0:i.messageSender)?void 0:i.sendMessage(e,n)})}_sendTimeoutNotice(n){return t(this,void 0,void 0,function*(){var a;console.log(l+"._sendTimeoutNotice params:"+JSON.stringify(n));let{isInviter:s,inviteID:r}=n,{signaling:o,signalingData:g,signalingExtensionOptions:i}=v.createTimeoutSignaling(n),e=yield this._sendSignaling(o,i);if(0===(null==e?void 0:e.code)){let{data:i,groupID:e,inviteeList:n,inviter:t}=g;null!=(a=this._core)&&a.notificationCenter.emitOuterEvent(null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,{name:null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,data:{data:i,groupID:e,inviteID:r,inviteeList:n,inviter:t,isSelfTimeout:!0,message:o}}),s?c.removeSignaling(r):c.updateSignaling(g)}})}_validateInviteId(i,e){if(!c.hasSignaling(e))throw new this._core.helper.ChatError({functionName:i,code:8010})}_validateProcessStatus(i){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:i,message:"processing other signaling operations"})}_validateBeforeInvite(i){var i=i["userID"],e=this._core.common.getCurrentUserID();if(i===e)throw new this._core.helper.ChatError({functionName:"invite",message:`cannot invite yourself, currentUserId:${e}, inviteeId:`+i})}_validateBeforeAccept(e){var n="accept";this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=c.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeCancel(i){var e="cancel",n=(this._validateInviteId(e,i),this._validateProcessStatus(e),this._core.common.getCurrentUserID()),t=c.getSignaling(i)["inviter"];if(t!==n){let i=`unmatched inviter:${t} and my userID:`+n;throw new this._core.helper.ChatError({functionName:e,message:i})}}_validateBeforeReject(e){var n="reject";this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=c.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeModifyInvitation(i){this._validateInviteId("modifyInvitation",i)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},s=new class{constructor(){this._actionProcessor=new Map([[1,this._onNewInvitationReceived.bind(this)],[4,this._onInviteeRejected.bind(this)],[3,this._onInviteeAccepted.bind(this)],[2,this._onInvitationCancelled.bind(this)],[5,this._onInvitationTimeout.bind(this)]])}init(i){(this._core=i).notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),i.notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(i){i.forEach(i=>{var e,n=a(i);n&&null!=(e=this._actionProcessor.get(n.actionType))&&e(n,i)})}_handleMessageReceived(i){c.getSignalingListenStatus()&&0!==(i=e(i.data)).length&&this.handleActionSignaling(i)}_handleMessageModified(i){c.getSignalingListenStatus()&&0<(i=e(i.data)).length&&i.forEach(i=>{var e=a(i);e&&this._onInvitationModified(e,i)})}_onNewInvitationReceived(e,n){l;var{inviteID:t,inviteeList:a,groupID:s}=e,r=this._core.common.getCurrentUserID();if(console.log(`signaling._onNewInvitationReceived signalingData:${JSON.stringify(e)}}`),!s||a.includes(r)){let i=e["timeout"];var s=Date.now()/1e3-n.time,r=(0<i&&0<s&&i>s&&(i-=s),c.getSignaling(t));r!==e&&(r||c.saveSignaling(t,Object.assign(Object.assign({},e),{signaling:n})),0<i&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:o+"-"+t,intervalMs:1e3*i,callback:g.handleInvitationExpiryTimer.bind(g,t)})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:a})}))}}_onInviteeRejected(i){l;var{inviteID:e,inviter:n,groupID:t,inviteeList:a}=i,s=c.hasSignaling(e);console.log(`signaling._onInviteeRejected inviteID:${e} hasInviteID:${s} inviter:${n} groupID:`+t),s&&(c.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:a[0]})}))}_onInviteeAccepted(i){l;var{inviteID:e,inviter:n,groupID:t,inviteeList:a}=i,s=c.hasSignaling(e);console.log(`signaling._onInviteeAccepted inviteID:${e} hasInviteID:${s} inviter:${n} groupID:`+t),s&&(c.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:a[0]})}))}_onInvitationCancelled(i){l;var{inviteID:e,inviter:n,groupID:t}=i,a=c.hasSignaling(e);console.log(`signaling._onInvitationCancelled inviteID:${e} hasInviteID:${a} inviter:${n} groupID:`+t),a&&(c.removeSignaling(e),this._emitEvent({name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(i)}))}_onInvitationTimeout(i){l;var{inviteID:e,inviteeList:n}=i,t=c.hasSignaling(e);console.log(`signaling._onInvitationTimeout inviteID:${e} hasInviteID:${t} data:`+i.data),t&&(c.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{inviteeList:n,isSelfTimeout:!1})}))}_onInvitationModified(i,e){l;var{inviteID:n,data:t}=i,a=c.hasSignaling(n);console.log(`signaling._onInvitationModified inviteID:${n} data:`+t),a&&(c.saveSignaling(n,Object.assign(Object.assign({},i),{signaling:e})),this._emitEvent({name:null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:n,data:t}}))}_emitEvent(i){var e;null!=(e=this._core)&&e.notificationCenter.emitOuterEvent(i.name,i)}_generateBaseEmitData(i){var{inviteID:i,inviter:e,groupID:n,data:t}=i;return{inviteID:i,inviter:e,groupID:n,data:t||""}}_dispose(){var i;null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},r=new class{constructor(){this._offlineSignalingMap=new Map}init(i){var{notificationCenter:i,helper:e,constants:{InnerEvent:n,WORKFLOW_STEP:t,WORKFLOW_NAME:a}}=this._core=i;i.subscribeInnerEvent(n.DESTROY,this._dispose,this),i.subscribeInnerEvent(n.LOGOUT,this._reset,this),e.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_LOGIN,t.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(i){var{result:{unreadMessageMap:i}={}}=i||{};if(0!==(null==i?void 0:i.size)&&c.getSignalingListenStatus()){i=e([...i.values()]);if(0!==i.length&&(i.forEach(i=>{this._handleC2CActionType(i)}),0<this._offlineSignalingMap.size)){let i=this._sortOfflineSignalingByTime();s.handleActionSignaling(i)}}}_handleC2CActionType(i){var e,n=a(i);n&&(e=n["actionType"],1===e?this._saveValidOfflineInvite(n,i):this._removeOfflineInvite(n))}_saveValidOfflineInvite(i,e){var{inviteID:n,inviteeList:t=[],timeout:a=0}=i,s=this._core.common.getCurrentUserID();t.includes(s)&&(t=Date.now()/1e3-e.time,0<a&&a<t&&0!==a||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},i),{signalingList:[e]})))}_removeOfflineInvite(i){var{inviteID:i=""}=i;this._offlineSignalingMap.has(i)&&this._offlineSignalingMap.delete(i)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach(i=>{e=[...e,...i.signalingList]}),e.sort((i,e)=>i.time-e.time)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let h={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},u={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};return new class{constructor(){this.name="Signaling"}install(i){g.init(i),s.init(i),v.init(i),c.init(i),r.init(i),i.helper.registerValidateConfig({auth:u,params:h})}}});
1
+ !function(i,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(i="undefined"!=typeof globalThis?globalThis:i||self).TencentCloudChatSignaling=e()}(this,function(){function t(i,r,o,g){return new(o=o||Promise)(function(n,e){function t(i){try{s(g.next(i))}catch(i){e(i)}}function a(i){try{s(g.throw(i))}catch(i){e(i)}}function s(i){var e;i.done?n(i.value):((e=i.value)instanceof o?e:new o(function(i){i(e)})).then(t,a)}s((g=g.apply(i,r||[])).next())})}let l="signaling",o="signaling-timeout";function a(i){return i.filter(i=>{var e,n;return"TIMCustomElem"===i.type&&({cloudCustomData:i="",payload:{data:n=""}={}}=i,i=i.match(/"type":"tsignaling"/),e=n.match(/inviteID/),n=n.match(/actionType/),i||e&&n)})}function s(i){var e=i.payload["data"];try{return JSON.parse(e)}catch(i){return console.error(i),null}}function i(i,e){return i.toString(16).padStart(e,"0")}function e(i){if(i<0||53<i)throw new Error("Number of digits must be between 0 and 53");return i<=30?Math.floor(Math.random()*(1<<i)):(i=i-30,Math.floor(Math.random()*(1<<i))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var c=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(i){(this._core=i).notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(i){return this._onlineSignalingMap.has(i)}getSignaling(i){return this._onlineSignalingMap.get(i)}saveSignaling(i,e){return this._onlineSignalingMap.set(i,e)}removeSignaling(i){return this._onlineSignalingMap.delete(i)}isInvitationValid(i){l;var{inviteID:i,groupID:e,inviter:n}=i,n=n===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(i))return!1;var t=this._onlineSignalingMap.get(i)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${i} inviteeList:${t} groupID:`+e),e){if(n)return 0<t.length;let i=this._core.common.getCurrentUserID();return t.includes(i)}return!0}updateSignaling(i){let n=l+".updateSignaling",{inviteID:t,inviter:e,inviteeList:a,groupID:s}=i;if(console.log(n+` inviteID:${t} inviter:${e} groupID:`+s),s&&this.hasSignaling(t)){let i=a[0],e=this._onlineSignalingMap.get(t)["inviteeList"];e.includes(i)&&(e.splice(e.indexOf(i),1),console.log(n+` remove ${i}. localInviteeList.length:`+e.length)),0===e.length&&this.removeSignaling(t)}else this.removeSignaling(t)}setSignalingListenStatus(i){this._isSignalingListening=i}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},v=new class{init(i){this._core=i}createInviteSignaling(i){var e=this._generateInviteID(),e=this._createInviteSignalingData(Object.assign(Object.assign({},i),{inviteID:e})),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createAcceptSignaling(i){var e=this._createAcceptSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createCancelSignaling(i){var e=this._createCancelSignalingData(i),{groupID:n,inviteeList:t}=e,n=n||t[0];return{signaling:this._createSignaling(e,n),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createRejectSignaling(i){var e=this._createRejectSignalingData(i),{groupID:n,inviter:t}=e;return{signaling:this._createSignaling(e,n||t),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createTimeoutSignaling(i){var{isInviter:e=!1}=i,i=this._createTimeoutSignalingData(i),{groupID:n,inviteeList:t,inviter:a}=i,n=n||(e?t[0]:a);return{signaling:this._createSignaling(i,n),signalingData:i,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}_createSignalingExtensionOptions(i){var{data:i="",onlineUserOnly:e,inviteID:n="",offlinePushInfo:t,actionType:a}=i,n=(null==(n=null==(n=c.getSignaling(n))?void 0:n.signaling)?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:e||n,offlinePushInfo:t,messageControlInfo:this._createMessageControlInfo(i,a)}}_createMessageControlInfo(i,e){e=5===e&&!!i.match(/excludeTimeoutSignalingFromHistoryMessage/),i=!!i.match(/excludeFromHistoryMessage/)||!!i.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:e||i,excludedFromLastMessage:e||i}}_createInviteSignalingData(i){l;var{userID:e,timeout:n=0,groupID:t="",inviteeList:a=[]}=i,s=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:1,inviter:s,inviteeList:t?a:[e],timeout:n});return console.log("signaling._createInviteSignalingData signalingData:",i),i}_createAcceptSignalingData(i){l;var e=i["inviteID"],n=this._core.common.getCurrentUserID(),{inviter:e,groupID:t}=c.getSignaling(e),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:3,groupID:t,inviter:e,inviteeList:[n]});return console.log("signaling._createAcceptSignalingData signalingData:",i),i}_createCancelSignalingData(i){l;var e=i["inviteID"],n=this._core.common.getCurrentUserID(),{inviteeList:e,groupID:t}=c.getSignaling(e),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:2,groupID:t,inviter:n,inviteeList:e});return console.log("signaling._createCancelSignalingData signalingData:",i),i}_createRejectSignalingData(i){l;var e=i["inviteID"],n=this._core.common.getCurrentUserID(),{inviter:e,groupID:t}=c.getSignaling(e),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:4,groupID:t,inviter:e,inviteeList:[n]});return console.log("signaling._createRejectSignalingData signalingData:",i),i}_createTimeoutSignalingData(i){l;var{isInviter:e=!1,inviteID:n}=i,{inviteeList:n,inviter:t}=c.getSignaling(n),a=this._core.common.getCurrentUserID(),i=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:5,inviter:t,inviteeList:e?n:[a]});return console.log("signaling._createTimeoutSignalingData signalingData:",i),i}_createSignaling(i,e){var{groupID:n=""}=i,e={to:e,conversationType:n?"GROUP":"C2C",priority:"High",payload:{data:JSON.stringify(i)}};return null==(n=null==(i=null==(n=this._core)?void 0:n.message)?void 0:i.messageFactory)?void 0:n.createCustomMessage(e)}_generateInviteID(){return[i(e(32),8),i(e(16),4),i(16384|e(12),4),i(32768|e(14),4),i(e(48),12)].join("-")}_generateBaseSignalData(i){var{data:i="",inviteID:e="",groupID:n=""}=i;return{businessID:1,timeout:0,data:i,inviteID:e,groupID:n}}},g=new class{constructor(){this._isProcessingSignaling=!1}init(i){(this._core=i).helper.registerApi({apiName:"invite",context:this}),i.helper.registerApi({apiName:"accept",context:this}),i.helper.registerApi({apiName:"cancel",context:this}),i.helper.registerApi({apiName:"reject",context:this}),i.helper.registerApi({apiName:"modifyInvitation",context:this}),i.helper.registerApi({apiName:"getSignalingInfo",context:this}),i.helper.registerApi({apiName:"addSignalingListener",context:this}),i.helper.registerApi({apiName:"removeSignalingListener",context:this}),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.LOGOUT,this._reset,this)}invite(e){return t(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(e);var{signaling:t,signalingData:a,signalingExtensionOptions:i}=v.createInviteSignaling(e),s=yield this._sendSignaling(t,i);if(0!==(null==s?void 0:s.code))return s;{let{inviteID:i,timeout:e}=a;return c.saveSignaling(i,Object.assign(Object.assign({},a),{signaling:t})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:o+"-"+i,intervalMs:1e3*(e+5),callback:this.handleInvitationExpiryTimer.bind(this,i)})),Object.assign(Object.assign({},s),{inviteID:i})}}catch(n){throw n}})}accept(s){return t(this,void 0,void 0,function*(){try{var i=s["inviteID"],{signaling:e,signalingData:n,signalingExtensionOptions:t}=(this._validateBeforeAccept(i),this._isProcessingSignaling=!0,v.createAcceptSignaling(s)),a=yield this._sendSignaling(e,t);return 0===(null==a?void 0:a.code)?(c.updateSignaling(n),Object.assign(Object.assign({},a),{inviteID:i})):a}catch(i){throw i}finally{this._isProcessingSignaling=!1}})}cancel(a){return t(this,void 0,void 0,function*(){try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeCancel(i),this._isProcessingSignaling=!0,v.createCancelSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(c.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw i}finally{this._isProcessingSignaling=!1}})}reject(a){return t(this,void 0,void 0,function*(){try{var i=a["inviteID"],{signaling:e,signalingExtensionOptions:n}=(this._validateBeforeReject(i),this._isProcessingSignaling=!0,v.createRejectSignaling(a)),t=yield this._sendSignaling(e,n);return 0===(null==t?void 0:t.code)?(c.removeSignaling(i),Object.assign(Object.assign({},t),{inviteID:i})):t}catch(i){throw i}finally{this._isProcessingSignaling=!1}})}modifyInvitation(i){return t(this,void 0,void 0,function*(){var t,a,{inviteID:s,data:r}=i;let o="";try{this._validateBeforeModifyInvitation(s);let i=c.getSignaling(s),e=i["signaling"],n=function(i,e){var n={};for(a in i)Object.prototype.hasOwnProperty.call(i,a)&&e.indexOf(a)<0&&(n[a]=i[a]);if(null!=i&&"function"==typeof Object.getOwnPropertySymbols)for(var t=0,a=Object.getOwnPropertySymbols(i);t<a.length;t++)e.indexOf(a[t])<0&&Object.prototype.propertyIsEnumerable.call(i,a[t])&&(n[a[t]]=i[a[t]]);return n}(i,["signaling"]);o=e.payload.data,n.data=r,e.payload.data=JSON.stringify(n);var g=yield null==(a=null==(t=this._core)?void 0:t.message.messageAction)?void 0:a.modifyMessage(e);return c.hasSignaling(s)&&c.saveSignaling(s,Object.assign(Object.assign({},n),{signaling:e})),g}catch(t){if(o){let i=c.getSignaling(s)["signaling"];i.payload.data=o}throw t}})}getSignalingInfo(i){var{ssoLog:e,utils:{safeStringify:n}}=this._core;if(0!==a([i]).length)return i={businessID:(i=s(i)).businessID||1,inviteID:i.inviteID,groupID:i.groupID||"",inviter:i.inviter||"",inviteeList:i.inviteeList||[],data:i.data||"",actionType:i.actionType||1,timeout:i.timeout||0},e.debug(l+" getSignalingInfo "+n(i)),i}addSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&c.setSignalingListenStatus(!0),null!=(t=this._core)&&t.notificationCenter.subscribeOuterEvent(i,e,n)}removeSignalingListener(i,e,n){var t;i===(null==(t=this._core)?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&c.setSignalingListenStatus(!1),null!=(t=this._core)&&t.notificationCenter.unSubscribeOuterEvent(i,e,n)}handleInvitationExpiryTimer(i){var e=c.getOnlineSignalingMap(),n=this._core.common.getCurrentUserID();e.has(i)&&(e=e.get(i).inviter===n,this._sendTimeoutNotice({inviteID:i,isInviter:e}))}_sendSignaling(e,n){return t(this,void 0,void 0,function*(){var i;return null==(i=null==(i=null==(i=this._core)?void 0:i.message)?void 0:i.messageSender)?void 0:i.sendMessage(e,n)})}_sendTimeoutNotice(n){return t(this,void 0,void 0,function*(){var a;this._core.ssoLog.debug("_sendTimeoutNotice",l+"._sendTimeoutNotice params:"+JSON.stringify(n));let{isInviter:s,inviteID:r}=n,{signaling:o,signalingData:g,signalingExtensionOptions:i}=v.createTimeoutSignaling(n),e=yield this._sendSignaling(o,i);if(0===(null==e?void 0:e.code)){let{data:i,groupID:e,inviteeList:n,inviter:t}=g;null!=(a=this._core)&&a.notificationCenter.emitOuterEvent(null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,{name:null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_TIMEOUT,data:{data:i,groupID:e,inviteID:r,inviteeList:n,inviter:t,isSelfTimeout:!0,message:o}}),s?c.removeSignaling(r):c.updateSignaling(g)}})}_validateInviteId(i,e){if(!c.hasSignaling(e))throw new this._core.helper.ChatError({functionName:i,code:8010})}_validateProcessStatus(i){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:i,message:"processing other signaling operations"})}_validateBeforeInvite(i){var i=i["userID"],e=this._core.common.getCurrentUserID();if(i===e)throw new this._core.helper.ChatError({functionName:"invite",message:`cannot invite yourself, currentUserId:${e}, inviteeId:`+i})}_validateBeforeAccept(e){var n="accept";this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=c.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeCancel(i){var e="cancel",n=(this._validateInviteId(e,i),this._validateProcessStatus(e),this._core.common.getCurrentUserID()),t=c.getSignaling(i)["inviter"];if(t!==n){let i=`unmatched inviter:${t} and my userID:`+n;throw new this._core.helper.ChatError({functionName:e,message:i})}}_validateBeforeReject(e){var n="reject";this._validateInviteId(n,e),this._validateProcessStatus(n);let t=this._core.common.getCurrentUserID(),i=c.getSignaling(e)["inviteeList"];if(!i.includes(t)){let i=`userID:${t} not in inviteeList. inviteID:`+e;throw new this._core.helper.ChatError({functionName:n,message:i})}}_validateBeforeModifyInvitation(i){this._validateInviteId("modifyInvitation",i)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},n=new class{constructor(){this._actionProcessor=new Map([[1,this._onNewInvitationReceived.bind(this)],[4,this._onInviteeRejected.bind(this)],[3,this._onInviteeAccepted.bind(this)],[2,this._onInvitationCancelled.bind(this)],[5,this._onInvitationTimeout.bind(this)]])}init(i){(this._core=i).notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),i.notificationCenter.subscribeOuterEvent(i.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),i.notificationCenter.subscribeInnerEvent(i.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(i){i.forEach(i=>{var e,n=s(i);n&&null!=(e=this._actionProcessor.get(n.actionType))&&e(n,i)})}_handleMessageReceived(i){c.getSignalingListenStatus()&&0!==(i=a(i.data)).length&&this.handleActionSignaling(i)}_handleMessageModified(i){c.getSignalingListenStatus()&&0<(i=a(i.data)).length&&i.forEach(i=>{var e=s(i);e&&this._onInvitationModified(e,i)})}_onNewInvitationReceived(e,n){l;var{inviteID:t,inviteeList:a,groupID:s}=e,r=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`signaling._onNewInvitationReceived signalingData:${JSON.stringify(e)}}`),!s||a.includes(r)){let i=e["timeout"];var s=Date.now()/1e3-n.time,r=(0<i&&0<s&&i>s&&(i-=s),c.getSignaling(t));r!==e&&(r||c.saveSignaling(t,Object.assign(Object.assign({},e),{signaling:n})),0<i&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:o+"-"+t,intervalMs:1e3*i,callback:g.handleInvitationExpiryTimer.bind(g,t)})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:a})}))}}_onInviteeRejected(i){l;var{inviteID:e,inviter:n,groupID:t,inviteeList:a}=i,s=c.hasSignaling(e);this._core.ssoLog.debug("_onInviteeRejected",`signaling._onInviteeRejected inviteID:${e} hasInviteID:${s} inviter:${n} groupID:`+t),s&&(c.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:a[0]})}))}_onInviteeAccepted(i){l;var{inviteID:e,inviter:n,groupID:t,inviteeList:a}=i,s=c.hasSignaling(e);this._core.ssoLog.debug("_onInviteeAccepted",`signaling._onInviteeAccepted inviteID:${e} hasInviteID:${s} inviter:${n} groupID:`+t),s&&(c.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:a[0]})}))}_onInvitationCancelled(i){l;var{inviteID:e,inviter:n,groupID:t}=i,a=c.hasSignaling(e);this._core.ssoLog.debug("_onInvitationCancelled",`signaling._onInvitationCancelled inviteID:${e} hasInviteID:${a} inviter:${n} groupID:`+t),a&&(c.removeSignaling(e),this._emitEvent({name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(i)}))}_onInvitationTimeout(i){l;var{inviteID:e,inviteeList:n}=i,t=c.hasSignaling(e);this._core.ssoLog.debug("_onInvitationTimeout",`signaling._onInvitationTimeout inviteID:${e} hasInviteID:${t} data:`+i.data),t&&(c.updateSignaling(i),this._emitEvent({name:null==(e=this._core)?void 0:e.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{inviteeList:n,isSelfTimeout:!1})}))}_onInvitationModified(i,e){l;var{inviteID:n,data:t}=i,a=c.hasSignaling(n);this._core.ssoLog.debug("_onInvitationModified",`signaling._onInvitationModified inviteID:${n} data:`+t),a&&(c.saveSignaling(n,Object.assign(Object.assign({},i),{signaling:e})),this._emitEvent({name:null==(a=this._core)?void 0:a.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:n,data:t}}))}_emitEvent(i){var e;null!=(e=this._core)&&e.notificationCenter.emitOuterEvent(i.name,i)}_generateBaseEmitData(i){var{inviteID:i,inviter:e,groupID:n,data:t}=i;return{inviteID:i,inviter:e,groupID:n,data:t||""}}_dispose(){var i;null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},r=new class{constructor(){this._offlineSignalingMap=new Map}init(i){var{notificationCenter:i,helper:e,constants:{InnerEvent:n,WORKFLOW_STEP:t,WORKFLOW_NAME:a}}=this._core=i;i.subscribeInnerEvent(n.DESTROY,this._dispose,this),i.subscribeInnerEvent(n.LOGOUT,this._reset,this),e.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_LOGIN,t.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(i){var{result:{unreadMessageMap:i}={}}=i||{};if(0!==(null==i?void 0:i.size)&&c.getSignalingListenStatus()){i=a([...i.values()]);if(0!==i.length&&(i.forEach(i=>{this._handleC2CActionType(i)}),0<this._offlineSignalingMap.size)){let i=this._sortOfflineSignalingByTime();n.handleActionSignaling(i)}}}_handleC2CActionType(i){var e,n=s(i);n&&(e=n["actionType"],1===e?this._saveValidOfflineInvite(n,i):this._removeOfflineInvite(n))}_saveValidOfflineInvite(i,e){var{inviteID:n,inviteeList:t=[],timeout:a=0}=i,s=this._core.common.getCurrentUserID();t.includes(s)&&(t=Date.now()/1e3-e.time,0<a&&a<t&&0!==a||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},i),{signalingList:[e]})))}_removeOfflineInvite(i){var{inviteID:i=""}=i;this._offlineSignalingMap.has(i)&&this._offlineSignalingMap.delete(i)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach(i=>{e=[...e,...i.signalingList]}),e.sort((i,e)=>i.time-e.time)}_dispose(){var i;this._reset(),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(i=this._core)&&i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let h={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},u={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};return new class{constructor(){this.name="Signaling"}install(i){g.init(i),n.init(i),v.init(i),c.init(i),r.init(i),i.helper.registerValidateConfig({auth:u,params:h})}}});
@@ -1 +1 @@
1
- let e=new class{init(e){this.core=e}},t="@TOPIC#_",s=7,o=8,i=17,n=18,r=20,c=300,a=0,u=3600,p=3021,l=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],d=t=>{var{common:{getMessagePreviewText:s}}=e["core"];return{lastTime:(null==t?void 0:t.time)||0,lastSequence:(null==t?void 0:t.sequence)||0,fromAccount:(null==t?void 0:t.from)||"",payload:(null==t?void 0:t.payload)||null,type:(null==t?void 0:t.type)||"",messageForShow:s(null==t?void 0:t.type,null==t?void 0:t.payload),nick:(null==t?void 0:t.nick)||"",avatar:(null==t?void 0:t.avatar)||"",version:(null==t?void 0:t.version)||0,cloudCustomData:(null==t?void 0:t.cloudCustomData)||"",isRevoked:(null==t?void 0:t.isRevoked)||!1,revoker:(null==t?void 0:t.revoker)||null}};class h{constructor(e){this.topicID="",this.topicName="",this.avatar="",this.introduction="",this.notification="",this.unreadCount=0,this.muteAllMembers=!1,this.customData="",this.groupAtInfoList=[],this.nextMessageSeq=0,this.lastMessage=d(),this.selfInfo={muteTime:0,readedSequence:0,messageRemindType:"",excludedUnreadSequenceList:void 0},this._init(e)}_init(e){for(var t in e)l.includes(t)&&("lastMessage"===t?this[t]=d(e[t]):"selfInfo"===t?this.updateSelfInfo(e[t]):this[t]="muteAllMembers"===t?1===e[t]:e[t])}updateUnreadCount(e=0){this.unreadCount=e}updateReadSequence(e=0,t=!1){t&&(this.selfInfo.readedSequence=e)}updateNextMessageSeq(e){this.nextMessageSeq=e}updateLastMessage(e){this.lastMessage=d(e)}updateGroupAtInfoList(t){var{common:{updateGroupAtInfo:s}}=e["core"];s(t,this.groupAtInfoList)}updateTopic(t){var{utils:{isUndefined:s},common:{deepMerge:i}}=e["core"];s(t.selfInfo)||this.updateSelfInfo(t.selfInfo),s(t.muteAllMembers)||(this.muteAllMembers=1===t.muteAllMembers),i(this,t,["groupID","lastMessageTime","selfInfo","muteAllMembers","lastMsg","groupAtInfoList"])}updateSelfInfo(t){var{common:{deepMerge:s}}=e["core"];return 0<s(this.selfInfo,t,[],[""])}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){return e===(null==(e=this.lastMessage)?void 0:e.lastSequence)}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}clearGroupAtInfoList(){this.groupAtInfoList.length=0}}var g=new class{constructor(){this._name="TopicDataHandler",this._topicMap=new Map,this._topicRequestInfo=new Map}init(e){var{helper:e,constants:t,notificationCenter:s,InnerEvent:{LOGOUT:i,DESTROY:o}}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.TOPIC_REQUEST_INFO_RESET,this._resetTopicRequestInfo,this),s.subscribeInnerEvent(i,this._reset,this),s.subscribeInnerEvent(o,this._dispose,this),console.log(this._name+".init")}_hasTopic(e,t){return!(null==(e=this._topicMap.get(e))||!e.get(t))}_setTopic(e,t,s){null!=(e=this._topicMap.get(e))&&e.set(t,s)}_deleteTopic(e,t){null!=(e=this._topicMap.get(e))&&e.delete(t)}getTopic(e,t){return null==(e=this._topicMap.get(e))?void 0:e.get(t)}updateTopic(e){e.forEach(e=>{var{groupID:t,topicID:s}=e;let i=null;this._topicMap.has(t)||this._topicMap.set(t,new Map),this._hasTopic(t,s)?null!=(i=this.getTopic(t,s))&&i.updateTopic(e):(this._getLastMessage(e),i=new h(e),this._setTopic(t,s,i));e=this.computeUnreadCount(i);null!=i&&i.updateUnreadCount(e)})}_getLastMessage(s){var{isEmpty:i,isUndefined:o,isArray:n}=this._core["utils"];if(!o(s.lastMsg)){let e=null,t="";t=(n(s.lastMsg.elements)?(e=s.lastMsg.elements[0].content,s.lastMsg.elements[0]):(e=s.lastMsg.elements.content,s.lastMsg.elements)).type;o={payload:e,type:t,time:s.lastMsg.time,sequence:s.lastMsg.sequence,from:s.lastMsg.from,nick:s.lastMsg.nick,avatar:s.lastMsg.avatar,version:s.lastMsg.messageVersion,cloudCustomData:s.lastMsg.cloudCustomData,isRevoked:2===s.lastMsg.isPlaceMessage,revoker:i(s.lastMsg.revokerInfo)?null:s.lastMsg.revokerInfo.revoker};s.lastMessage=o}}computeUnreadCount(s){let{excludedUnreadSequenceList:e=[],readedSequence:i}=s.selfInfo,o=s.nextMessageSeq-s.selfInfo.readedSequence-1;if(0<e.length){let t=0;e.forEach(e=>{e>i&&e<=s.nextMessageSeq-1&&(t+=1)}),1<=t&&(o-=t)}return 0<o?o:0}updateTopicAtInfo(e){0!==e.length&&e.forEach(e=>{var t=this._core["utils"]["isEmpty"],e=e["groupAtInfoList"];t(e)||this.updateGroupAtInfoList(e)})}updateGroupAtInfoList(s,r=!1){if(0!==s.length){let{common:{getCurrentUserID:e},utils:{isUndefined:o,isEmpty:t}}=this._core,n=e(),a=null;s.forEach(e=>{var{groupID:t,topicID:s,from:i}=e;i!==n&&((a=this.getTopic(t,s))&&a.updateGroupAtInfoList(e),o(a))&&r&&(this.updateTopic([{groupID:t,topicID:s}]),null!=(i=this.getTopic(t,s)))&&i.updateGroupAtInfoList(e)}),t(a)||this.emitTopicUpdate(a)}}getTopicList(e,t=[]){var e=this._topicMap.get(e),s=[];return e&&s.push(...e.values()),0<t.length?s.filter(e=>t.includes(e.topicID)):s}deleteTopicList(t,e=[]){this._topicMap.has(t)&&(e.forEach(e=>{this._hasTopic(t,e)&&this._deleteTopic(t,e)}),console.log(this._name+`.deleteTopicList groupID:${t} topicID:`+e.join(",")))}clearGroupAtInfoList(e,t){var s=this._core["utils"]["isEmpty"],e=this.getTopic(e,t);s(null==e?void 0:e.groupAtInfoList)||(null!=e&&e.clearGroupAtInfoList(),console.log(this._name+".clearGroupAtInfoList topicID:"+t))}markMessageAsRead(e,s){let{message:{messageDataHandler:t},OuterConstant:{CONV_GROUP:i}}=this._core,o=(null==t?void 0:t.getLocalMessageList(""+i+e))||[];if(0!==o.length){e=o["length"];for(let t=e-1;0<=t;t--){let e=o[t];if(!(s&&e.sequence>s)){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}updateUnreadCount(e,t){var{message:{messageDataHandler:s},OuterConstant:{CONV_GROUP:i}}=this._core;let o=!1;e=this.getTopic(e,t);e&&(s=(null==s?void 0:s.getLocalMessageList(""+i+t))||[],i=e.unreadCount,s=null==s?void 0:s.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount topicID:${t} currentUnreadCount:${i} newUnreadCount:`+s),i!==s&&(e.updateUnreadCount(s),o=!0),o)&&this.emitTopicUpdate(e)}updateSelfInfo(e){var{groupID:e,topicID:t,selfInfo:s}=e,i=this.getTopic(e,t);if(i){let e=i.updateSelfInfo(s);console.log(`${this._name}.updateSelfInfo topicID:${t} info:${JSON.stringify(s)} isUpdated:`+e),e&&this.emitTopicUpdate(i)}}getTopicRequestInfo(e){return this._topicRequestInfo.get(e)||{}}setTopicRequestInfo(e,t){return this._topicRequestInfo.set(e,t)}emitTopicUpdate(e){var{OuterEvent:t,notificationCenter:s}=this._core;s.emitOuterEvent(t.TOPIC_UPDATED,{name:t.TOPIC_UPDATED,data:e})}_resetTopicRequestInfo(){this._topicRequestInfo.clear()}_reset(){this._topicMap.clear(),this._topicRequestInfo.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let _=(t="")=>{var{OuterConstant:s}=e["core"];return t.replace(s.CONV_GROUP,"")},m=(e="")=>e.split(t)[0];var I=new class{constructor(){this._name="TopicMessageHandler"}init(e){var{helper:e,notificationCenter:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:i},InnerEvent:{MESSAGE_PUSH:o,TOPIC_NEW_MESSAGE:n,TOPIC_MESSAGE_DELETED:a,TOPIC_MESSAGE_REVOKED:r,TOPIC_MESSAGE_MODIFIED:c,DESTROY:u}}=this._core=e,{TOPIC_AT_TIPS:l,TOPIC_LATEST_MESSAGE:p}=t["InnerEventSubType"];e.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,i.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(s.RECEIVE_GROUP_NEW_MESSAGE,i.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.subscribeInnerEvent(n,this._handleNewMessage,this),t.subscribeInnerEvent(a,this._handleMessageDeleted,this),t.subscribeInnerEvent(r,this._handleMessageRevoked,this),t.subscribeInnerEvent(c,this._handleMessageModified,this),t.subscribeInnerEvent(o,l,this._handleTopicAtTips,this),t.subscribeInnerEvent(o,p,this._handleLatestMessage,this),t.subscribeInnerEvent(u,this._dispose,this),console.log(this._name+".init")}_handleUnreadSyncFinished(e){let s,{WORKFLOW_STEP:t}=this._core.constants,{groupTipList:i=[]}=e.result[t.UNREAD_MESSAGE_SYNC]||{};for(let t=0;t<i.length;t++){let e=i[t];12===e.Event&&null!=(s=e.GroupTips[0].MsgBody)&&s.TopicId&&this._handleTopicAtTips(e)}}_handleNewMessage(e){var{conversationUpdateFieldList:e=[]}=e.result||{};if(0!==e.length){var t=this._core["common"]["isTopic"];if(t(e[0].conversationID)){let a=this._core["common"]["getCurrentUserID"];e.forEach(e=>{let{conversationID:t="",lastMessage:o}=e,s=_(t),i=m(s),n=g.getTopic(i,s);if(n){let{from:e,sequence:t}=o,s=t+1,i=e===a();if(s>n.nextMessageSeq){n.updateNextMessageSeq(s),n.updateLastMessage(o),n.updateReadSequence(t,i);let e=i?0:g.computeUnreadCount(n);n.updateUnreadCount(e),this._emitTopicUpdate(n)}}})}}}_handleMessageDeleted(s){var i=_(s),o=m(i),o=g.getTopic(o,i);if(console.log(this._name+`._handleMessageDeleted, topicID:${i} hasTopic:`+!!o),o){var{message:{messageDataHandler:n},utils:{isEmpty:a}}=this._core,r=(null==n?void 0:n.getLocalMessageList(s))||[];let t={};for(let e=(r.length||0)-1;0<=e;e--)if(!r[e].isDeleted){t=r[e];break}let e=!1;o.lastMessage.lastSequence!==t.sequence&&(a(t)&&(t={}),o.updateLastMessage(t),e=!0),e&&(this._emitTopicUpdate(o),console.log(this._name+`._handleMessageDeleted, topicID:${i} with lastMessage:`+o.lastMessage))}}_handleMessageRevoked(e){var{messageList:e=[]}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+e.length),0!==e.length){let o=null,n=!1;e.forEach(e=>{var{to:e,sequence:t,revoker:s}=e,i=m(e);if(o=g.getTopic(i,e)){o.reduceUnreadCount()&&(n=!0),o.isLastMessageRevoked(t)&&(o.setLastMessageRevoked(!0),o.setLastMessageRevoker(s),n=!0);let{excludedUnreadSequenceList:e=[]}=o.selfInfo;e.push(t),o.updateSelfInfo({excludedUnreadSequenceList:e})}}),n&&this._emitTopicUpdate(o)}}_handleMessageModified(e){let{conversationID:t,messageList:s}=e,i=_(t),o=m(i),r=g.getTopic(o,i);if(console.log(`${this._name}._handleMessageModified topicID:${i} hasTopic:`+!!r),r){var c=r["lastMessage"];if(c){let a=(null==s?void 0:s[0])||{};if(this._shouldUpdateLastMessage(c,a)){let{getMessagePreviewText:e}=this._core["common"],{time:t,sequence:s,elements:i,cloudCustomData:o,messageVersion:n}=a;c.type=i[0].type,c.payload=i[0].content,c.messageForShow=e(c.type,c.payload),c.cloudCustomData=o,c.version=n,c.lastSequence=s,c.lastTime=t,this._emitTopicUpdate(r)}}}}_shouldUpdateLastMessage(e,t){var s;return null===e.payload||({sequence:t,messageVersion:s}=t,e.lastSequence===t&&e.version!==s)}_emitTopicUpdate(e){var{notificationCenter:t,OuterEvent:s}=this._core;t.emitOuterEvent(s.TOPIC_UPDATED,{name:s.TOPIC_UPDATED,data:e})}_handleTopicAtTips(e){let{GroupTips:t=[]}=e,n=[],a=!1;t.forEach(e=>{var{GroupAtTips:e,MsgBody:t,MsgRandom:s,ClientSeq:i}=e;let o={};e?o=this._convertAtInfo(e):t&&(o=this._convertAtInfo(t),a=!0),o.__random=s,o.__sequence=i,n.push(o)}),g.updateGroupAtInfoList(n,a)}_convertAtInfo(e){var{From_Account:e,GroupId:t,TopicId:s,MsgSeq:i,GroupAtType:o}=e;return{groupID:t,topicID:s,from:e,sequence:i,groupAtType:o}}_handleLatestMessage(e){let{utils:{isEmpty:t},message:{messageHelper:i,messageFactory:o}}=this._core,{NewMsg:n,NoUnreadSeqList:a}=e||{};if(!t(n)){let{TopicId:e}=n["GroupInfo"],t=i.parseServerGroupMessage(n),s=o.createMessage(t);s.setElement(t.elements),this._updateUnreadCountAndLastMessage({topicID:e,message:s,excludedUnreadSequenceList:a})}}_updateUnreadCountAndLastMessage(e){let{isUndefined:t}=this._core["utils"],{topicID:s,message:i,excludedUnreadSequenceList:o}=e,n=m(s),a=g.getTopic(n,s);if(a){let e=a.selfInfo.excludedUnreadSequenceList||[];if(t(o)||(e=o),i._isExcludedFromUnreadCount&&e.push(i.sequence),a.updateSelfInfo({excludedUnreadSequenceList:e}),console.log(`${this._name}._updateUnreadCountAndLastMessage latest message sequence:${i.sequence} lastMessage sequence:`+a.lastMessage.lastSequence),i.sequence>a.lastMessage.lastSequence){let e=i.sequence+1,t=(a.updateLastMessage(i),a.updateNextMessageSeq(e),g.computeUnreadCount(a));a.updateUnreadCount(t),this._emitTopicUpdate(a)}}}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,TOPIC_NEW_MESSAGE:s,TOPIC_MESSAGE_DELETED:i,TOPIC_MESSAGE_REVOKED:o,TOPIC_MESSAGE_MODIFIED:n,DESTROY:a}}=this._core,{TOPIC_AT_TIPS:r,TOPIC_LATEST_MESSAGE:c}=e["InnerEventSubType"];e.unSubscribeInnerEvent(s,this._handleNewMessage,this),e.unSubscribeInnerEvent(i,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(o,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,r,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,c,this._handleLatestMessage,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},T=new class{constructor(){this._name="TopicOperationHandler"}init(e){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core=e,{TOPIC_TIPS_NOTIFICATION:i,TOPIC_SYSTEM_NOTIFICATION:o,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.subscribeInnerEvent(t,i,this._handleTopicTips,this),e.subscribeInnerEvent(t,o,this._handleTopicNotices,this),e.subscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.subscribeInnerEvent(s,this._dispose,this),console.log(this._name+".init")}_handleTopicTips(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var i=t[e];i.MsgBody.OpType!==s?i.MsgBody.OpType!==o?this._emitTopicTips(i):this._handleTopicProfileUpdated(i):this._handleMuteTimeUpdated(i)}}_handleMuteTimeUpdated(e){var{getCurrentUserID:t}=this._core["common"],{GroupInfo:{GroupId:s,TopicId:i},MsgBody:{MsgMemberInfo:o=[]}}=e;for(let e=0;e<o.length;e++){var{User_Account:n,ShutupTime:a}=o[e];if(n===t()&&0<=a){g.updateSelfInfo({groupID:s,topicID:i,selfInfo:{muteTime:a}});break}}}_handleTopicProfileUpdated(e){var{GroupInfo:{GroupId:e,TopicId:t},MsgBody:{MsgTopicNewInfo:{CustomString:s,ShutupAll:i,TopicFaceUrl:o,TopicIntroduction:n,TopicName:a,TopicNotification:r}}}=e,c=g.getTopic(e,t);c&&(c.updateTopic({groupID:e,topicID:t,customData:s,muteAllMembers:i,avatar:o,introduction:n,topicName:a,notification:r}),g.emitTopicUpdate(c))}_handleTopicNotices(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e],{MsgBody:{ReportType:o,TopicIdArray:a,MsgFlag:c},GroupInfo:{GroupId:u,TopicId:l}}=s;o===i?this._handleTopicCreated({groupID:u,topicID:l}):o===n?this._handleTopicDeleted({groupID:u,topicIDList:a}):o===r?this._handleMessageRemindTypeUpdated({groupID:u,topicID:l,messageRemindType:c}):this._emitTopicNotices(s)}}_handleTopicCreated(e){var{OuterEvent:t,notificationCenter:s}=this._core;g.setTopicRequestInfo(e.groupID,{}),s.emitOuterEvent(t.TOPIC_CREATED,{name:t.TOPIC_CREATED,data:e})}_handleTopicDeleted(e){var{OuterEvent:t,notificationCenter:s}=this._core,{groupID:i,topicIDList:o=[]}=e;g.deleteTopicList(i,o),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){var{groupID:e,topicID:t,messageRemindType:s}=e;g.updateSelfInfo({groupID:e,topicID:t,selfInfo:{messageRemindType:s}})}_handleTopicMessageReadSynced(e){let t=e["GroupTips"],{isUndefined:s}=this._core["utils"];t.forEach(e=>{e=e.MsgBody.GroupReadInfoArray;s(e)||e.forEach(e=>{var{GroupId:e,TopicId:t,LastReadMsgSeq:s}=e;console.log(this._name+`._handleTopicMessageReadSynced topicID:${t} lastReadSequence:`+s),g.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),g.clearGroupAtInfoList(e,t),g.markMessageAsRead(t,s),g.updateUnreadCount(e,t)})})}_emitTopicTips(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:i,OuterEvent:o,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=i.MSG_GRP_TIP,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=i.CONV_GROUP,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:[e]})}_emitTopicNotices(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:i,OuterEvent:o,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=i.MSG_GRP_SYS_NOTICE,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=i.CONV_SYSTEM,t.conversationID=i.CONV_SYSTEM,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:[e]})}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{TOPIC_TIPS_NOTIFICATION:i,TOPIC_SYSTEM_NOTIFICATION:o,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,i,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,o,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};function f(e,a,r,c){return new(r=r||Promise)(function(s,t){function i(e){try{n(c.next(e))}catch(e){t(e)}}function o(e){try{n(c.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(i,o)}n((c=c.apply(e,a||[])).next())})}var M=new class{constructor(){this._name="GetJoinedCommunityHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getJoinedCommunityList",context:this})}getJoinedCommunityList(){return f(this,void 0,void 0,function*(){var e=this._core["apiMap"]["getGroupList"],e=(yield e(!0)).filter(e=>!0===e.isSupportTopic);return console.log(this._name+".getJoinedCommunityList ok, count:"+e.length),{code:0,data:{groupList:e}}})}},v=new class{constructor(){this._name="CreateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(n){return f(this,void 0,void 0,function*(){let s="createTopicInCommunity",{utils:{isUndefined:e},common:{isTopic:t},helper:{ChatError:i}}=this._core,o=n["topicID"];if(!e(o)&&!t(o)){let e=new i({functionName:s,code:p});throw console.error(this._name+`.${s} fail:`,e),e}try{let e=yield function(r,c){return f(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:i,notification:o,introduction:n,customData:a}=r;return c.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.create_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:i,Notification:o,Introduction:n,CustomString:a}})})}(n,this._core),{TopicId:t=""}=e||{};return console.log(this._name+`.${s} ok, topicID:`+t),g.updateTopic([Object.assign(Object.assign({},n),{topicID:t})]),{code:0,data:{topicID:t}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},E=new class{constructor(){this._name="DeleteTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteTopicFromCommunity",context:this})}deleteTopicFromCommunity(c){return f(this,void 0,void 0,function*(){var s="deleteTopicFromCommunity",{groupID:a,topicIDList:r=[]}=c;try{let e=yield function(s,i){return f(this,void 0,void 0,function*(){var{groupID:e,topicIDList:t}=s;return i.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.destroy_topic",data:{GroupId:e,TopicIdList:t}})})}({groupID:a,topicIDList:r},this._core),{DestroyResultItem:t=[]}=e||{},i=[],o=[],n=[];return t.forEach(e=>{var{TopicId:e,ErrorCode:t,ErrorInfo:s}=e;0===t?(i.push({topicID:e}),n.push(e)):o.push({topicID:e,code:t,message:s})}),0<n.length&&g.deleteTopicList(c.groupID,n),console.log(`${this._name}.${s} ok, groupID:${a} success:${i.length} fail:`+o.length),{code:0,data:{successTopicList:i,failureTopicList:o}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},S=new class{constructor(){this._name="GetTopicHandler",this._getCloudConfig=e=>{var t=this._core["store"];return(t.get("cloudConfig")||{})[e]}}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getTopicList",context:this})}getTopicList(e){return f(this,void 0,void 0,function*(){var{groupID:t,topicIDList:s=[]}=e,i=0===s.length;if(this._isFetchingFromCache(t,i)){let e=g.getTopicList(t,s);if(i||e.length===s.length)return console.log(this._name+`.getTopicList groupID:${t} from cache, count:`+e.length),{code:0,data:{successTopicList:e,failureTopicList:[]}}}return this._getTopicListFromServer({groupID:t,topicIDList:s},i)})}_isFetchingFromCache(e,t){var{hasFetchedAllTopics:e=!1,time:s=0}=g.getTopicRequestInfo(e);return!(!e&&(t||e))&&Date.now()-s<this._getCacheDuration()}_getCacheDuration(){var{isUndefined:e}=this._core["utils"];let t=this._getCloudConfig("topic_cache_time");return!e(t)&&(t=parseInt(t,10))>=a&&t<=u?1e3*t:1e3*c}_getTopicListFromServer(u,l){return f(this,void 0,void 0,function*(){var i="_getTopicListFromServer",{isEmpty:o}=this._core["utils"],c=u["groupID"];try{let e=yield function(s,i){return f(this,void 0,void 0,function*(){var{groupID:e,topicIDList:t}=s;return i.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.get_topic",data:{GroupId:e,TopicIdList:t,MemberInfoFilter:["NoUnreadSeqList"]}})})}(u,this._core),{TopicAndSelfInfo:t=[]}=e||{},n=[],a=[],r=[],s=(this._convertTopicInfoList(t).forEach(e=>{var{topic:e,selfInfo:t,code:s,message:i}=e,o=e["topicID"];0===s?(n.push(Object.assign(Object.assign({},e),{selfInfo:t})),a.push(o)):r.push({topicID:o,code:s,message:i})}),g.updateTopic(n),g.updateTopicAtInfo(n),console.log(`${this._name}.${i} groupID:${c} from remote, success count:${a.length}, fail count:`+r.length),[]);return o(a)||(g.setTopicRequestInfo(c,{hasFetchedAllTopics:l,time:Date.now()}),s=g.getTopicList(c,a)),{code:0,data:{successTopicList:s,failureTopicList:r}}}catch(e){throw console.error(this._name+`.${i} failed, error:`,e),e}})}_convertTopicInfoList(e){let o=[];return e.forEach(e=>{var{TopicInfo:e={},SelfInfo:t={},ErrorCode:s,ErrorInfo:i}=e;o.push({code:s,message:i,topic:this._convertTopicInfo(e),selfInfo:this._convertSelfInfo(t)})}),o}_convertTopicInfo(e){var t,s,i,o,n,a,r,c,u,l,p,d=this._core["utils"]["isEmpty"];return d(e)?{}:({CreateTime:d,CustomString:e,FaceUrl:t,GroupId:s,LastMsgTime:i,NextMsgSeq:o,Introduction:n,Notification:a,ShutUpAllFlag:r,TopicId:c,TopicName:u,LastMsg:l,AtInfoList:p}=e,{createTime:d,customData:e,avatar:t,groupID:s,lastMessageTime:i,nextMessageSeq:o,introduction:n,notification:a,muteAllMembers:r,topicID:c,topicName:u,lastMsg:this._convertLastMsg(l),groupAtInfoList:this._convertAtInfoList({groupID:s,topicID:c,atInfoList:p})})}_convertLastMsg(e){var t,{utils:{isUndefined:s},OuterConstant:i}=this._core;if(!s(e))return 4===e.Event&&(e.MsgBody.MsgType=i.MSG_GRP_TIP),{messageHelper:s}=this._core["message"],i=s.parseServerGroupMessage(e),{From_AccountHeadurl:s,From_AccountNick:e,LastMsgSeq:t}=e,Object.assign(Object.assign({},i),{avatar:s,nick:e,sequence:t})}_convertAtInfoList(e){let{groupID:i,topicID:o,atInfoList:t=[]}=e;if(0===t.length)return[];let n=[];return t.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:i,topicID:o,groupAtType:e,sequence:t,from:s})}),n}_convertSelfInfo(e){var t,s,i,o=this._core["utils"]["isEmpty"];return o(e)?{}:({InheritGroupReceiveOption:o,MsgFlag:e,MsgSeq:t,NoUnreadSeqList:s,ShutUpTime:i}=e,{inheritGroupReceiveOption:o,messageRemindType:e,readedSequence:t,excludedUnreadSequenceList:s,muteTime:i})}},D=new class{constructor(){this._name="UpdateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(n){return f(this,void 0,void 0,function*(){var t="updateTopicProfile",{isUndefined:e}=this._core["utils"],{groupID:s,topicID:i,muteAllMembers:o}=n;e(n.muteAllMembers)||(n.muteAllMembers=!0===o?"On":"Off");try{return yield function(c,u){return f(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:i,notification:o,introduction:n,customData:a,muteAllMembers:r}=c;return u.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:i,Notification:o,Introduction:n,CustomString:a,ShutUpAllMember:r}})})}(n,this._core),console.log(this._name+`.${t} ok, topicID:`+i),g.updateTopic([n]),{code:0,data:{topic:g.getTopic(s,i)}}}catch(e){throw console.error(this._name+`.${t} failed, topicID:${i} error:`,e),e}})}},C=new class{constructor(){this._name="MessageReadHandler"}init(e){let{helper:t,common:{isTopic:s}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>s(e[0].conversationID)})}setMessageRead(l){return f(this,void 0,void 0,function*(){let{utils:{isEmpty:e},ssoLog:t,helper:{ChatError:o}}=this._core,s=l["conversationID"],i={code:0,data:{}},n=_(s),a=m(n),r=g.getTopic(a,n);if(console.log(this._name+`.setMessageRead topicID:${n} unreadCount:`+((null==r?void 0:r.unreadCount)||0)),r&&(e(r.groupAtInfoList)||this._deleteTopicAtTips(a,n),0!==r.unreadCount)){var c=this._getLocalMessageMaxSequence(r),u=t.createSSOLogData({method:"setMessageRead"});u.setLogInfo({message:"conversationID:"+s,moreMessage:"lastMessageSequence:"+c});try{yield this._setTopicMessageRead(a,n,c),u.end()}catch(e){let{errorCode:t,errorInfo:s}=e,i=new o({functionName:"setMessageRead",code:t,message:s});throw u.setError(i).end(),i}}return i})}_deleteTopicAtTips(n,a){return f(this,void 0,void 0,function*(){console.log(this._name+`._deleteTopicAtTips groupID:${n} topicID:`+a);let e=g.getTopic(n,a);if(e){var i=(null==e?void 0:e.groupAtInfoList)||[];if(0!==i.length)try{let{common:{getCurrentUserID:t},OuterConstant:{CONV_AT_ALL:s}}=this._core;var o=[...i];0===(o=i.filter(e=>!e.atTypeArray.includes(s))).length?g.clearGroupAtInfoList(n,a):(yield function(t,s){return f(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:o.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteTopicAtTips ok. count:"+i.length),g.clearGroupAtInfoList(n,a))}catch(e){console.error(this._name+"._deleteTopicAtTips fail:",e)}}})}_getLocalMessageMaxSequence(e){var{message:{messageDataHandler:t},OuterConstant:{CONV_GROUP:s}}=this._core,i=e["topicID"],t=t.getLocalMessageList(""+s+i),s=Math.max(...t.map(e=>e.sequence));let o=(null==(i=null==e?void 0:e.lastMessage)?void 0:i.lastSequence)||0;return s>o&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${o} to `+s),o=s),o}_setTopicMessageRead(e,t,s){return f(this,void 0,void 0,function*(){try{yield function(i,o){return f(this,void 0,void 0,function*(){var{groupID:e,topicID:t,lastMessageSequence:s}=i;return o.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.msg_read_report",data:{GroupId:e,TopicId:t,MsgReadedSeq:s}})})}({groupID:e,topicID:t,lastMessageSequence:s},this._core),console.log(this._name+"._setTopicMessageRead ok, lastReadSequence:"+s),g.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),g.markMessageAsRead(t,s),g.updateUnreadCount(e,t)}catch(e){throw console.error(this._name+"._setTopicMessageRead fail:",e),e}})}},A=new class{init(e){console.log("TopicAction.init"),M.init(e),v.init(e),E.init(e),S.init(e),D.init(e),C.init(e)}};let L={required:!0,rules:["string"],allowEmpty:!1},y={createTopicInCommunity:{groupID:L,topicName:L},deleteTopicFromCommunity:{groupID:L,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:L,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:L,topicID:L}},O={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0};var R=new class{constructor(){this.name="Topic"}install(t){e.init(t),g.init(t),I.init(t),T.init(t),A.init(t),t.helper.registerValidateConfig({auth:O,params:y})}};export{R as default};
1
+ let e=new class{init(e){this.core=e}},t="@TOPIC#_",s=7,o=8,i=17,n=18,r=20,c=300,a=0,u=3600,p=3021,l=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],d=t=>{var{common:{getMessagePreviewText:s}}=e["core"];return{lastTime:(null==t?void 0:t.time)||0,lastSequence:(null==t?void 0:t.sequence)||0,fromAccount:(null==t?void 0:t.from)||"",payload:(null==t?void 0:t.payload)||null,type:(null==t?void 0:t.type)||"",messageForShow:s(null==t?void 0:t.type,null==t?void 0:t.payload),nick:(null==t?void 0:t.nick)||"",avatar:(null==t?void 0:t.avatar)||"",version:(null==t?void 0:t.version)||0,cloudCustomData:(null==t?void 0:t.cloudCustomData)||"",isRevoked:(null==t?void 0:t.isRevoked)||!1,revoker:(null==t?void 0:t.revoker)||null}};class h{constructor(e){this.topicID="",this.topicName="",this.avatar="",this.introduction="",this.notification="",this.unreadCount=0,this.muteAllMembers=!1,this.customData="",this.groupAtInfoList=[],this.nextMessageSeq=0,this.lastMessage=d(),this.selfInfo={muteTime:0,readedSequence:0,messageRemindType:"",excludedUnreadSequenceList:void 0},this._init(e)}_init(e){for(var t in e)l.includes(t)&&("lastMessage"===t?this[t]=d(e[t]):"selfInfo"===t?this.updateSelfInfo(e[t]):this[t]="muteAllMembers"===t?1===e[t]:e[t])}updateUnreadCount(e=0){this.unreadCount=e}updateReadSequence(e=0,t=!1){t&&(this.selfInfo.readedSequence=e)}updateNextMessageSeq(e){this.nextMessageSeq=e}updateLastMessage(e){this.lastMessage=d(e)}updateGroupAtInfoList(t){var{common:{updateGroupAtInfo:s}}=e["core"];s(t,this.groupAtInfoList)}updateTopic(t){var{utils:{isUndefined:s},common:{deepMerge:i}}=e["core"];s(t.selfInfo)||this.updateSelfInfo(t.selfInfo),s(t.muteAllMembers)||(this.muteAllMembers=1===t.muteAllMembers),i(this,t,["groupID","lastMessageTime","selfInfo","muteAllMembers","lastMsg","groupAtInfoList"])}updateSelfInfo(t){var{common:{deepMerge:s}}=e["core"];return 0<s(this.selfInfo,t,[],[""])}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){return e===(null==(e=this.lastMessage)?void 0:e.lastSequence)}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}clearGroupAtInfoList(){this.groupAtInfoList.length=0}}var g=new class{constructor(){this._name="TopicDataHandler",this._topicMap=new Map,this._topicRequestInfo=new Map}init(e){var{helper:t,constants:s,notificationCenter:i,InnerEvent:{LOGOUT:o,DESTROY:n}}=this._core=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.TOPIC_REQUEST_INFO_RESET,this._resetTopicRequestInfo,this),i.subscribeInnerEvent(o,this._reset,this),i.subscribeInnerEvent(n,this._dispose,this),e.ssoLog.debug(this._name+".init")}_hasTopic(e,t){return!(null==(e=this._topicMap.get(e))||!e.get(t))}_setTopic(e,t,s){null!=(e=this._topicMap.get(e))&&e.set(t,s)}_deleteTopic(e,t){null!=(e=this._topicMap.get(e))&&e.delete(t)}getTopic(e,t){return null==(e=this._topicMap.get(e))?void 0:e.get(t)}updateTopic(e){e.forEach(e=>{var{groupID:t,topicID:s}=e;let i=null;this._topicMap.has(t)||this._topicMap.set(t,new Map),this._hasTopic(t,s)?null!=(i=this.getTopic(t,s))&&i.updateTopic(e):(this._getLastMessage(e),i=new h(e),this._setTopic(t,s,i));e=this.computeUnreadCount(i);null!=i&&i.updateUnreadCount(e)})}_getLastMessage(s){var{isEmpty:i,isUndefined:o,isArray:n}=this._core["utils"];if(!o(s.lastMsg)){let e=null,t="";t=(n(s.lastMsg.elements)?(e=s.lastMsg.elements[0].content,s.lastMsg.elements[0]):(e=s.lastMsg.elements.content,s.lastMsg.elements)).type;o={payload:e,type:t,time:s.lastMsg.time,sequence:s.lastMsg.sequence,from:s.lastMsg.from,nick:s.lastMsg.nick,avatar:s.lastMsg.avatar,version:s.lastMsg.messageVersion,cloudCustomData:s.lastMsg.cloudCustomData,isRevoked:2===s.lastMsg.isPlaceMessage,revoker:i(s.lastMsg.revokerInfo)?null:s.lastMsg.revokerInfo.revoker};s.lastMessage=o}}computeUnreadCount(s){let{excludedUnreadSequenceList:e=[],readedSequence:i}=s.selfInfo,o=s.nextMessageSeq-s.selfInfo.readedSequence-1;if(0<e.length){let t=0;e.forEach(e=>{e>i&&e<=s.nextMessageSeq-1&&(t+=1)}),1<=t&&(o-=t)}return 0<o?o:0}updateTopicAtInfo(e){0!==e.length&&e.forEach(e=>{var t=this._core["utils"]["isEmpty"],e=e["groupAtInfoList"];t(e)||this.updateGroupAtInfoList(e)})}updateGroupAtInfoList(s,r=!1){if(0!==s.length){let{common:{getCurrentUserID:e},utils:{isUndefined:o,isEmpty:t}}=this._core,n=e(),a=null;s.forEach(e=>{var{groupID:t,topicID:s,from:i}=e;i!==n&&((a=this.getTopic(t,s))&&a.updateGroupAtInfoList(e),o(a))&&r&&(this.updateTopic([{groupID:t,topicID:s}]),null!=(i=this.getTopic(t,s)))&&i.updateGroupAtInfoList(e)}),t(a)||this.emitTopicUpdate(a)}}getTopicList(e,t=[]){var e=this._topicMap.get(e),s=[];return e&&s.push(...e.values()),0<t.length?s.filter(e=>t.includes(e.topicID)):s}deleteTopicList(t,e=[]){this._topicMap.has(t)&&(e.forEach(e=>{this._hasTopic(t,e)&&this._deleteTopic(t,e)}),console.log(this._name+`.deleteTopicList groupID:${t} topicID:`+e.join(",")))}clearGroupAtInfoList(e,t){var s=this._core["utils"]["isEmpty"],e=this.getTopic(e,t);s(null==e?void 0:e.groupAtInfoList)||(null!=e&&e.clearGroupAtInfoList(),console.log(this._name+".clearGroupAtInfoList topicID:"+t))}markMessageAsRead(e,s){let{message:{messageDataHandler:t},OuterConstant:{CONV_GROUP:i}}=this._core,o=(null==t?void 0:t.getLocalMessageList(""+i+e))||[];if(0!==o.length){e=o["length"];for(let t=e-1;0<=t;t--){let e=o[t];if(!(s&&e.sequence>s)){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}updateUnreadCount(e,t){var{message:{messageDataHandler:s},OuterConstant:{CONV_GROUP:i}}=this._core;let o=!1;e=this.getTopic(e,t);e&&(s=(null==s?void 0:s.getLocalMessageList(""+i+t))||[],i=e.unreadCount,s=null==s?void 0:s.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount topicID:${t} currentUnreadCount:${i} newUnreadCount:`+s),i!==s&&(e.updateUnreadCount(s),o=!0),o)&&this.emitTopicUpdate(e)}updateSelfInfo(e){var{groupID:e,topicID:t,selfInfo:s}=e,i=this.getTopic(e,t);if(i){let e=i.updateSelfInfo(s);console.log(`${this._name}.updateSelfInfo topicID:${t} info:${JSON.stringify(s)} isUpdated:`+e),e&&this.emitTopicUpdate(i)}}getTopicRequestInfo(e){return this._topicRequestInfo.get(e)||{}}setTopicRequestInfo(e,t){return this._topicRequestInfo.set(e,t)}emitTopicUpdate(e){var{OuterEvent:t,notificationCenter:s}=this._core;s.emitOuterEvent(t.TOPIC_UPDATED,{name:t.TOPIC_UPDATED,data:e})}_resetTopicRequestInfo(){this._topicRequestInfo.clear()}_reset(){this._topicMap.clear(),this._topicRequestInfo.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let _=(t="")=>{var{OuterConstant:s}=e["core"];return t.replace(s.CONV_GROUP,"")},m=(e="")=>e.split(t)[0];var I=new class{constructor(){this._name="TopicMessageHandler"}init(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:o},InnerEvent:{MESSAGE_PUSH:n,TOPIC_NEW_MESSAGE:a,TOPIC_MESSAGE_DELETED:r,TOPIC_MESSAGE_REVOKED:c,TOPIC_MESSAGE_MODIFIED:u,DESTROY:p}}=this._core=e,{TOPIC_AT_TIPS:l,TOPIC_LATEST_MESSAGE:d}=s["InnerEventSubType"];t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,o.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_NEW_MESSAGE,o.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s.subscribeInnerEvent(a,this._handleNewMessage,this),s.subscribeInnerEvent(r,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,this._handleMessageRevoked,this),s.subscribeInnerEvent(u,this._handleMessageModified,this),s.subscribeInnerEvent(n,l,this._handleTopicAtTips,this),s.subscribeInnerEvent(n,d,this._handleLatestMessage,this),s.subscribeInnerEvent(p,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleUnreadSyncFinished(e){let s,{WORKFLOW_STEP:t}=this._core.constants,{groupTipList:i=[]}=e.result[t.UNREAD_MESSAGE_SYNC]||{};for(let t=0;t<i.length;t++){let e=i[t];12===e.Event&&null!=(s=e.GroupTips[0].MsgBody)&&s.TopicId&&this._handleTopicAtTips(e)}}_handleNewMessage(e){var{conversationUpdateFieldList:e=[]}=e.result||{};if(0!==e.length){var t=this._core["common"]["isTopic"];if(t(e[0].conversationID)){let a=this._core["common"]["getCurrentUserID"];e.forEach(e=>{let{conversationID:t="",lastMessage:o}=e,s=_(t),i=m(s),n=g.getTopic(i,s);if(n){let{from:e,sequence:t}=o,s=t+1,i=e===a();if(s>n.nextMessageSeq){n.updateNextMessageSeq(s),n.updateLastMessage(o),n.updateReadSequence(t,i);let e=i?0:g.computeUnreadCount(n);n.updateUnreadCount(e),this._emitTopicUpdate(n)}}})}}}_handleMessageDeleted(s){var i=_(s),o=m(i),o=g.getTopic(o,i);if(console.log(this._name+`._handleMessageDeleted, topicID:${i} hasTopic:`+!!o),o){var{message:{messageDataHandler:n},utils:{isEmpty:a}}=this._core,r=(null==n?void 0:n.getLocalMessageList(s))||[];let t={};for(let e=(r.length||0)-1;0<=e;e--)if(!r[e].isDeleted){t=r[e];break}let e=!1;o.lastMessage.lastSequence!==t.sequence&&(a(t)&&(t={}),o.updateLastMessage(t),e=!0),e&&(this._emitTopicUpdate(o),console.log(this._name+`._handleMessageDeleted, topicID:${i} with lastMessage:`+o.lastMessage))}}_handleMessageRevoked(e){var{messageList:e=[]}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+e.length),0!==e.length){let o=null,n=!1;e.forEach(e=>{var{to:e,sequence:t,revoker:s}=e,i=m(e);if(o=g.getTopic(i,e)){o.reduceUnreadCount()&&(n=!0),o.isLastMessageRevoked(t)&&(o.setLastMessageRevoked(!0),o.setLastMessageRevoker(s),n=!0);let{excludedUnreadSequenceList:e=[]}=o.selfInfo;e.push(t),o.updateSelfInfo({excludedUnreadSequenceList:e})}}),n&&this._emitTopicUpdate(o)}}_handleMessageModified(e){let{conversationID:t,messageList:s}=e,i=_(t),o=m(i),r=g.getTopic(o,i);if(console.log(`${this._name}._handleMessageModified topicID:${i} hasTopic:`+!!r),r){var c=r["lastMessage"];if(c){let a=(null==s?void 0:s[0])||{};if(this._shouldUpdateLastMessage(c,a)){let{getMessagePreviewText:e}=this._core["common"],{time:t,sequence:s,elements:i,cloudCustomData:o,messageVersion:n}=a;c.type=i[0].type,c.payload=i[0].content,c.messageForShow=e(c.type,c.payload),c.cloudCustomData=o,c.version=n,c.lastSequence=s,c.lastTime=t,this._emitTopicUpdate(r)}}}}_shouldUpdateLastMessage(e,t){var s;return null===e.payload||({sequence:t,messageVersion:s}=t,e.lastSequence===t&&e.version!==s)}_emitTopicUpdate(e){var{notificationCenter:t,OuterEvent:s}=this._core;t.emitOuterEvent(s.TOPIC_UPDATED,{name:s.TOPIC_UPDATED,data:e})}_handleTopicAtTips(e){let{GroupTips:t=[]}=e,n=[],a=!1;t.forEach(e=>{var{GroupAtTips:e,MsgBody:t,MsgRandom:s,ClientSeq:i}=e;let o={};e?o=this._convertAtInfo(e):t&&(o=this._convertAtInfo(t),a=!0),o.__random=s,o.__sequence=i,n.push(o)}),g.updateGroupAtInfoList(n,a)}_convertAtInfo(e){var{From_Account:e,GroupId:t,TopicId:s,MsgSeq:i,GroupAtType:o}=e;return{groupID:t,topicID:s,from:e,sequence:i,groupAtType:o}}_handleLatestMessage(e){let{utils:{isEmpty:t},message:{messageHelper:i,messageFactory:o}}=this._core,{NewMsg:n,NoUnreadSeqList:a}=e||{};if(!t(n)){let{TopicId:e}=n["GroupInfo"],t=i.parseServerGroupMessage(n),s=o.createMessage(t);s.setElement(t.elements),this._updateUnreadCountAndLastMessage({topicID:e,message:s,excludedUnreadSequenceList:a})}}_updateUnreadCountAndLastMessage(e){let{isUndefined:t}=this._core["utils"],{topicID:s,message:i,excludedUnreadSequenceList:o}=e,n=m(s),a=g.getTopic(n,s);if(a){let e=a.selfInfo.excludedUnreadSequenceList||[];if(t(o)||(e=o),i._isExcludedFromUnreadCount&&e.push(i.sequence),a.updateSelfInfo({excludedUnreadSequenceList:e}),console.log(`${this._name}._updateUnreadCountAndLastMessage latest message sequence:${i.sequence} lastMessage sequence:`+a.lastMessage.lastSequence),i.sequence>a.lastMessage.lastSequence){let e=i.sequence+1,t=(a.updateLastMessage(i),a.updateNextMessageSeq(e),g.computeUnreadCount(a));a.updateUnreadCount(t),this._emitTopicUpdate(a)}}}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,TOPIC_NEW_MESSAGE:s,TOPIC_MESSAGE_DELETED:i,TOPIC_MESSAGE_REVOKED:o,TOPIC_MESSAGE_MODIFIED:n,DESTROY:a}}=this._core,{TOPIC_AT_TIPS:r,TOPIC_LATEST_MESSAGE:c}=e["InnerEventSubType"];e.unSubscribeInnerEvent(s,this._handleNewMessage,this),e.unSubscribeInnerEvent(i,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(o,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,r,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,c,this._handleLatestMessage,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},T=new class{constructor(){this._name="TopicOperationHandler"}init(e){var{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:i}}=this._core=e,{TOPIC_TIPS_NOTIFICATION:o,TOPIC_SYSTEM_NOTIFICATION:n,TOPIC_MESSAGE_READ_SYNC:a}=t["InnerEventSubType"];t.subscribeInnerEvent(s,o,this._handleTopicTips,this),t.subscribeInnerEvent(s,n,this._handleTopicNotices,this),t.subscribeInnerEvent(s,a,this._handleTopicMessageReadSynced,this),t.subscribeInnerEvent(i,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleTopicTips(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var i=t[e];i.MsgBody.OpType!==s?i.MsgBody.OpType!==o?this._emitTopicTips(i):this._handleTopicProfileUpdated(i):this._handleMuteTimeUpdated(i)}}_handleMuteTimeUpdated(e){var{getCurrentUserID:t}=this._core["common"],{GroupInfo:{GroupId:s,TopicId:i},MsgBody:{MsgMemberInfo:o=[]}}=e;for(let e=0;e<o.length;e++){var{User_Account:n,ShutupTime:a}=o[e];if(n===t()&&0<=a){g.updateSelfInfo({groupID:s,topicID:i,selfInfo:{muteTime:a}});break}}}_handleTopicProfileUpdated(e){var{GroupInfo:{GroupId:e,TopicId:t},MsgBody:{MsgTopicNewInfo:{CustomString:s,ShutupAll:i,TopicFaceUrl:o,TopicIntroduction:n,TopicName:a,TopicNotification:r}}}=e,c=g.getTopic(e,t);c&&(c.updateTopic({groupID:e,topicID:t,customData:s,muteAllMembers:i,avatar:o,introduction:n,topicName:a,notification:r}),g.emitTopicUpdate(c))}_handleTopicNotices(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e],{MsgBody:{ReportType:o,TopicIdArray:a,MsgFlag:c},GroupInfo:{GroupId:u,TopicId:p}}=s;o===i?this._handleTopicCreated({groupID:u,topicID:p}):o===n?this._handleTopicDeleted({groupID:u,topicIDList:a}):o===r?this._handleMessageRemindTypeUpdated({groupID:u,topicID:p,messageRemindType:c}):this._emitTopicNotices(s)}}_handleTopicCreated(e){var{OuterEvent:t,notificationCenter:s}=this._core;g.setTopicRequestInfo(e.groupID,{}),s.emitOuterEvent(t.TOPIC_CREATED,{name:t.TOPIC_CREATED,data:e})}_handleTopicDeleted(e){var{OuterEvent:t,notificationCenter:s}=this._core,{groupID:i,topicIDList:o=[]}=e;g.deleteTopicList(i,o),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){var{groupID:e,topicID:t,messageRemindType:s}=e;g.updateSelfInfo({groupID:e,topicID:t,selfInfo:{messageRemindType:s}})}_handleTopicMessageReadSynced(e){let t=e["GroupTips"],{isUndefined:s}=this._core["utils"];t.forEach(e=>{e=e.MsgBody.GroupReadInfoArray;s(e)||e.forEach(e=>{var{GroupId:e,TopicId:t,LastReadMsgSeq:s}=e;console.log(this._name+`._handleTopicMessageReadSynced topicID:${t} lastReadSequence:`+s),g.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),g.clearGroupAtInfoList(e,t),g.markMessageAsRead(t,s),g.updateUnreadCount(e,t)})})}_emitTopicTips(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:i,OuterEvent:o,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=i.MSG_GRP_TIP,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=i.CONV_GROUP,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:[e]})}_emitTopicNotices(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:i,OuterEvent:o,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=i.MSG_GRP_SYS_NOTICE,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=i.CONV_SYSTEM,t.conversationID=i.CONV_SYSTEM,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:[e]})}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{TOPIC_TIPS_NOTIFICATION:i,TOPIC_SYSTEM_NOTIFICATION:o,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,i,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,o,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};function f(e,a,r,c){return new(r=r||Promise)(function(s,t){function i(e){try{n(c.next(e))}catch(e){t(e)}}function o(e){try{n(c.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(i,o)}n((c=c.apply(e,a||[])).next())})}var M=new class{constructor(){this._name="GetJoinedCommunityHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getJoinedCommunityList",context:this})}getJoinedCommunityList(){return f(this,void 0,void 0,function*(){var e=this._core["apiMap"]["getGroupList"],e=(yield e(!0)).filter(e=>!0===e.isSupportTopic);return console.log(this._name+".getJoinedCommunityList ok, count:"+e.length),{code:0,data:{groupList:e}}})}},v=new class{constructor(){this._name="CreateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(n){return f(this,void 0,void 0,function*(){let s="createTopicInCommunity",{utils:{isUndefined:e},common:{isTopic:t},helper:{ChatError:i}}=this._core,o=n["topicID"];if(!e(o)&&!t(o)){let e=new i({functionName:s,code:p});throw console.error(this._name+`.${s} fail:`,e),e}try{let e=yield function(r,c){return f(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:i,notification:o,introduction:n,customData:a}=r;return c.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.create_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:i,Notification:o,Introduction:n,CustomString:a}})})}(n,this._core),{TopicId:t=""}=e||{};return console.log(this._name+`.${s} ok, topicID:`+t),g.updateTopic([Object.assign(Object.assign({},n),{topicID:t})]),{code:0,data:{topicID:t}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},E=new class{constructor(){this._name="DeleteTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteTopicFromCommunity",context:this})}deleteTopicFromCommunity(c){return f(this,void 0,void 0,function*(){var s="deleteTopicFromCommunity",{groupID:a,topicIDList:r=[]}=c;try{let e=yield function(s,i){return f(this,void 0,void 0,function*(){var{groupID:e,topicIDList:t}=s;return i.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.destroy_topic",data:{GroupId:e,TopicIdList:t}})})}({groupID:a,topicIDList:r},this._core),{DestroyResultItem:t=[]}=e||{},i=[],o=[],n=[];return t.forEach(e=>{var{TopicId:e,ErrorCode:t,ErrorInfo:s}=e;0===t?(i.push({topicID:e}),n.push(e)):o.push({topicID:e,code:t,message:s})}),0<n.length&&g.deleteTopicList(c.groupID,n),console.log(`${this._name}.${s} ok, groupID:${a} success:${i.length} fail:`+o.length),{code:0,data:{successTopicList:i,failureTopicList:o}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},S=new class{constructor(){this._name="GetTopicHandler",this._getCloudConfig=e=>{var t=this._core["store"];return(t.get("cloudConfig")||{})[e]}}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getTopicList",context:this})}getTopicList(e){return f(this,void 0,void 0,function*(){var{groupID:t,topicIDList:s=[]}=e,i=0===s.length;if(this._isFetchingFromCache(t,i)){let e=g.getTopicList(t,s);if(i||e.length===s.length)return console.log(this._name+`.getTopicList groupID:${t} from cache, count:`+e.length),{code:0,data:{successTopicList:e,failureTopicList:[]}}}return this._getTopicListFromServer({groupID:t,topicIDList:s},i)})}_isFetchingFromCache(e,t){var{hasFetchedAllTopics:e=!1,time:s=0}=g.getTopicRequestInfo(e);return!(!e&&(t||e))&&Date.now()-s<this._getCacheDuration()}_getCacheDuration(){var{isUndefined:e}=this._core["utils"];let t=this._getCloudConfig("topic_cache_time");return!e(t)&&(t=parseInt(t,10))>=a&&t<=u?1e3*t:1e3*c}_getTopicListFromServer(u,p){return f(this,void 0,void 0,function*(){var i="_getTopicListFromServer",{isEmpty:o}=this._core["utils"],c=u["groupID"];try{let e=yield function(s,i){return f(this,void 0,void 0,function*(){var{groupID:e,topicIDList:t}=s;return i.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.get_topic",data:{GroupId:e,TopicIdList:t,MemberInfoFilter:["NoUnreadSeqList"]}})})}(u,this._core),{TopicAndSelfInfo:t=[]}=e||{},n=[],a=[],r=[],s=(this._convertTopicInfoList(t).forEach(e=>{var{topic:e,selfInfo:t,code:s,message:i}=e,o=e["topicID"];0===s?(n.push(Object.assign(Object.assign({},e),{selfInfo:t})),a.push(o)):r.push({topicID:o,code:s,message:i})}),g.updateTopic(n),g.updateTopicAtInfo(n),console.log(`${this._name}.${i} groupID:${c} from remote, success count:${a.length}, fail count:`+r.length),[]);return o(a)||(g.setTopicRequestInfo(c,{hasFetchedAllTopics:p,time:Date.now()}),s=g.getTopicList(c,a)),{code:0,data:{successTopicList:s,failureTopicList:r}}}catch(e){throw console.error(this._name+`.${i} failed, error:`,e),e}})}_convertTopicInfoList(e){let o=[];return e.forEach(e=>{var{TopicInfo:e={},SelfInfo:t={},ErrorCode:s,ErrorInfo:i}=e;o.push({code:s,message:i,topic:this._convertTopicInfo(e),selfInfo:this._convertSelfInfo(t)})}),o}_convertTopicInfo(e){var t,s,i,o,n,a,r,c,u,p,l,d=this._core["utils"]["isEmpty"];return d(e)?{}:({CreateTime:d,CustomString:e,FaceUrl:t,GroupId:s,LastMsgTime:i,NextMsgSeq:o,Introduction:n,Notification:a,ShutUpAllFlag:r,TopicId:c,TopicName:u,LastMsg:p,AtInfoList:l}=e,{createTime:d,customData:e,avatar:t,groupID:s,lastMessageTime:i,nextMessageSeq:o,introduction:n,notification:a,muteAllMembers:r,topicID:c,topicName:u,lastMsg:this._convertLastMsg(p),groupAtInfoList:this._convertAtInfoList({groupID:s,topicID:c,atInfoList:l})})}_convertLastMsg(e){var t,{utils:{isUndefined:s},OuterConstant:i}=this._core;if(!s(e))return 4===e.Event&&(e.MsgBody.MsgType=i.MSG_GRP_TIP),{messageHelper:s}=this._core["message"],i=s.parseServerGroupMessage(e),{From_AccountHeadurl:s,From_AccountNick:e,LastMsgSeq:t}=e,Object.assign(Object.assign({},i),{avatar:s,nick:e,sequence:t})}_convertAtInfoList(e){let{groupID:i,topicID:o,atInfoList:t=[]}=e;if(0===t.length)return[];let n=[];return t.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:i,topicID:o,groupAtType:e,sequence:t,from:s})}),n}_convertSelfInfo(e){var t,s,i,o=this._core["utils"]["isEmpty"];return o(e)?{}:({InheritGroupReceiveOption:o,MsgFlag:e,MsgSeq:t,NoUnreadSeqList:s,ShutUpTime:i}=e,{inheritGroupReceiveOption:o,messageRemindType:e,readedSequence:t,excludedUnreadSequenceList:s,muteTime:i})}},D=new class{constructor(){this._name="UpdateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(n){return f(this,void 0,void 0,function*(){var t="updateTopicProfile",{isUndefined:e}=this._core["utils"],{groupID:s,topicID:i,muteAllMembers:o}=n;e(n.muteAllMembers)||(n.muteAllMembers=!0===o?"On":"Off");try{return yield function(c,u){return f(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:i,notification:o,introduction:n,customData:a,muteAllMembers:r}=c;return u.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:i,Notification:o,Introduction:n,CustomString:a,ShutUpAllMember:r}})})}(n,this._core),console.log(this._name+`.${t} ok, topicID:`+i),g.updateTopic([n]),{code:0,data:{topic:g.getTopic(s,i)}}}catch(e){throw console.error(this._name+`.${t} failed, topicID:${i} error:`,e),e}})}},C=new class{constructor(){this._name="MessageReadHandler"}init(e){let{helper:t,common:{isTopic:s}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>s(e[0].conversationID)})}setMessageRead(p){return f(this,void 0,void 0,function*(){let{utils:{isEmpty:e},ssoLog:t,helper:{ChatError:i}}=this._core,s=p["conversationID"],o={code:0,data:{}},n=_(s),a=m(n),r=g.getTopic(a,n),c=this._name+`.setMessageRead topicID:${n} conversationID:${s} unreadCount:`+((null==r?void 0:r.unreadCount)||0);if(o.successLog={message:c},!r)return o;if(e(r.groupAtInfoList)||this._deleteTopicAtTips(a,n),0===r.unreadCount)return o;var u=this._getLocalMessageMaxSequence(r);try{yield this._setTopicMessageRead(a,n,u)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"setMessageRead",code:t,message:s,moreMessage:c})}return Object.assign(Object.assign({},o),{successLog:{message:c+" lastMessageSequence:"+u}})})}_deleteTopicAtTips(n,a){return f(this,void 0,void 0,function*(){this._core.ssoLog.debug("_deleteTopicAtTips",this._name+`._deleteTopicAtTips groupID:${n} topicID:`+a);let e=g.getTopic(n,a);if(e){var i=(null==e?void 0:e.groupAtInfoList)||[];if(0!==i.length)try{let{common:{getCurrentUserID:t},OuterConstant:{CONV_AT_ALL:s}}=this._core;var o=[...i];0===(o=i.filter(e=>!e.atTypeArray.includes(s))).length?g.clearGroupAtInfoList(n,a):(yield function(t,s){return f(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:o.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),this._core.ssoLog.debug(this._name+"._deleteTopicAtTips ok. count:"+i.length),g.clearGroupAtInfoList(n,a))}catch(e){console.error(this._name+"._deleteTopicAtTips fail:",e)}}})}_getLocalMessageMaxSequence(e){var{message:{messageDataHandler:t},OuterConstant:{CONV_GROUP:s}}=this._core,i=e["topicID"],t=t.getLocalMessageList(""+s+i),s=Math.max(...t.map(e=>e.sequence));let o=(null==(i=null==e?void 0:e.lastMessage)?void 0:i.lastSequence)||0;return s>o&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${o} to `+s),o=s),o}_setTopicMessageRead(e,t,s){return f(this,void 0,void 0,function*(){try{yield function(i,o){return f(this,void 0,void 0,function*(){var{groupID:e,topicID:t,lastMessageSequence:s}=i;return o.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.msg_read_report",data:{GroupId:e,TopicId:t,MsgReadedSeq:s}})})}({groupID:e,topicID:t,lastMessageSequence:s},this._core),console.log(this._name+"._setTopicMessageRead ok, lastReadSequence:"+s),g.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),g.markMessageAsRead(t,s),g.updateUnreadCount(e,t)}catch(e){throw console.error(this._name+"._setTopicMessageRead fail:",e),e}})}},L=new class{init(e){e.ssoLog.debug("TopicAction.init"),M.init(e),v.init(e),E.init(e),S.init(e),D.init(e),C.init(e)}};let A={required:!0,rules:["string"],allowEmpty:!1},y={createTopicInCommunity:{groupID:A,topicName:A},deleteTopicFromCommunity:{groupID:A,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:A,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:A,topicID:A}},O={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0};var R=new class{constructor(){this.name="Topic"}install(t){e.init(t),g.init(t),I.init(t),T.init(t),L.init(t),t.helper.registerValidateConfig({auth:O,params:y})}};export{R as default};