@tencentcloud/lite-chat 1.4.1 → 1.4.2

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(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 t(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 o=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(g,m){return t(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 s=["unknown","image","video","audio","log"];var U,i=new class{init(e){this._core=e}request(i,t){let r,{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:a,IN_UNI_IOS_APP:n}=null==(r=this._core)?void 0:r.utils,{resources:l="",headers:d={},url:h,downloadUrl:u=""}=i,c=h,p=null;var g=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(g){var g=decodeURIComponent(g[3]),g=g.includes("?")?g.split("?")[0]:g||"",g={key:i.fileKey||g,success_action_status:200,"Content-Type":""},m={};if(n){let[e,t]=h.split("?sign=");t&&(c=e+"?sign="+encodeURIComponent(t),m.sign=decodeURIComponent(t),m.signature=decodeURIComponent(t))}let r={url:c,header:d,name:"file",filePath:l,formData:Object.assign(Object.assign({},g),m),timeout:i.timeout||3e5};if(a){let t=e(r,["name"]);r=Object.assign(Object.assign({},t),{fileName:"file",fileType:i.fileType?s[i.fileType]:"image"})}return(p=o.uploadFile(Object.assign(Object.assign({},r),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})}}))).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: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 r(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function n(e){e=e||99999999;return Math.round(Math.random()*e)}function a(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 l(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function d(e,t){return Math.round(Number(e)*10**t)/10**t}function c(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function h(e){return e<=1048576?d(e/1024,1)+"KB/s":d(e/1048576,1)+"MB/s"}let u="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",m="TIMVideoFileElem",f="RichMediaMessagePlugin",_=["rich.my-imcloud.com","imrich.qcloud.com"],v=1,I=2,y=3,w=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(U=U||{}),{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 S=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(w).some(e=>e.test(t))}extractFileFromInput(e){return r(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?Array.isArray(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(r){return t(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=_;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=_}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})}},P=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?i:o,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return t(this,void 0,void 0,function*(){var t=f+" 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:${c(e.size)} time:${a}ms speed:`+h(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 a(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:a(Date.now(),!1),uploadSpeed:h(1e3*e.size/a(Date.now(),!1))}}_createCosOptions(c){return t(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=!S.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(f+" prepareUploadParams:",e);var t=e["file"],{IN_MINI_APP:r,IN_RN_APP:i}=S.getPlatformFlags(),r=r||i,i=r&&e.message.type!==g,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+n(999999)+e;return{fileName:l(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(n){return t(this,void 0,void 0,function*(){var r=f+" fetchCosSignatureUrl",i=S.isSimpleCos(),o=this._prepareCosRequestData(n),s=i?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(o,s,a){return t(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}})}(s,o,this._core);this.fetchCosTryCount=0;var a=this._processResponse(e);return console.log(r+` ok. isSimpleCos:${i} data:`,a),a||{}}catch(e){if(console.error(r+" failed, error:",e),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(n);throw this.fetchCosTryCount=0,e}})}_processResponse(e){var t;let r=S.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 S.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:S.getPlatform(),uint32_sdkappid:S.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 t(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=S.getFileUploadProxy();let r=e;return r=t?e.replace(/^https:\/\/[^/]+/,t):r}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let F=2108,M=2251,b=2252,A=["jpg","jpeg","gif","png","bmp","image","webp"],O=20971520,T={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class N{constructor(e,t){this.instanceID=n(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=S.addAuthToUrl(e.imageUrl||e.url||""),this.url=S.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=S.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function C(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?e(s,["url"]):s}class E{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=u;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 E({imageFormat:r,imageInfoArray:s,uuid:o})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:r,IN_RN_APP:i,IN_BROWSER:o}=S.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 N(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=T[e.toUpperCase()]||T.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],C({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:S.removeAuthToUrl(e.imageUrl)}))}}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:"createImageMessage",context:this}),null!=(t=null==i?void 0:i.messageFactory)&&t.registerElementClass(u,E),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(f+" 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:T.UNKNOWN,uuid:S.generateUUID(i),file:i,imageInfoArray:[]},d=new E(l);return r.setElement(d),this._messageOptionsMap.set(r.clientSequence,o),console.log(f+" 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(f+" createImageMessage error:",o),o}}upload(i){return t(this,void 0,void 0,function*(){console.log(f+" 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 t(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:v,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)}},{uploadOptions:e,response:t}=yield P.uploadToCOS(e);return this._parseResponse(e,t)})}_generateImageInfo(e){console.log(f+" 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=S.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 C({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 t(this,void 0,void 0,function*(){console.log(f+" 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")),S.isSimpleCos()&&!S.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 t(this,void 0,void 0,function*(){try{var e=S.addAuthToUrl(i),{width:t=0,height:r=0}=yield S.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:M});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(f+" _processImage error:",e),e}}_processMiniAppImageFile(e){r(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=S.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(o,s){return t(this,void 0,void 0,function*(){var e=f+" getDownloadIP domainName: "+o;try{var r,i=yield function(a,n){return t(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}})}(o,this._core);i&&i.str_final_ip&&(console.log(e+" ok. downloadIP:"+i),(r=s.location.split("/"))[0]=i.str_final_ip,s.location=r.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(i,o){return t(this,void 0,void 0,function*(){var r=f+"._getImageInfoArray";try{var e=yield function(a,n){return t(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}})}(i,this._core);return o.imageInfoArray=this._processImageInfoResponse(e),console.log(r+" ok"),o}catch(e){throw o.imageInfoArray=void 0,console.warn(r+" 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)),A.indexOf(i.toLowerCase())<0)throw new r.ChatError({code:b})}_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:F});if(i>=O)throw new r.ChatError({message:"File size exceeds limit: "+c(O)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let $=2108,R=2401,z="2.5.0",x="1.18.0",W=104857600;function j(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}class q{constructor(e){this.type=g,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:S.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 q({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:S.removeAuthToUrl(r),FileName:i,FileSize:o,UUID:e}}}_getFileInfo(e){return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(S.getPlatform().IN_UNI_NATIVE_APP&&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=n(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 V=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,q),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(f+" 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:S.generateUUID(t),file:t},d=new q(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,r),console.log(f+" 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(f+" createFileMessage error:",r),r}}upload(r){return t(this,void 0,void 0,function*(){console.log(f+" 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=S.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:R});if(e.size>W)throw new t({message:"File size exceeds limit: "+c(W)});if(0===e.size)throw new t({code:$})}_performFileUpload(i,o,r){return t(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:v,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)}},e=(yield P.uploadToCOS(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=S.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&&j(e,z)<0)throw new s({message:`WXChooseMessageFile requires SDK version ${z} or higher`});if(i&&j(e,x)<0)throw new s({message:`QQChooseMessageFile requires SDK version ${x} 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=2108,k=2352,B=["mp4","quicktime","mov"],H=104857600;class K{constructor(e){this.type=m,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:S.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:S.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:S.addAuthToUrl(e.thumbUrl),snapshotUrl:S.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 K({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;S.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),S.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),S.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:S.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:S.removeAuthToUrl(m),SnapshotUrl:S.removeAuthToUrl(f)}}}}var Y=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(m,K),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(f+" 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:d(t.videoFile.second,0),videoSize:t.videoFile.size,remoteVideoUrl:"",videoUrl:t.videoFile.url,videoUUID:S.generateUUID(t.videoFile),thumbUUID:S.generateUUID(t.videoFile,"jpg"),thumbWidth:t.width||200,thumbHeight:t.height||200,thumbUrl:t.thumbUrl,thumbSize:t.thumbSize,thumbFormat:"jpg"},h=new K(l);return n.setElement(h),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(f+" createVideoMessage error:",r),r}}upload(i){return t(this,void 0,void 0,function*(){console.log(f+" 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=S.addAuthToUrl(t);return e.updateVideoUrl(t),S.isEmpty(r)||e.updateSnapshotInfo(r),i})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>H)throw new t({message:"File size exceeds limit: "+c(H)});if(0===e.videoFile.size)throw new t({code:L});if(-1===B.indexOf(e.videoFile.type))throw new t({code:k})}_performVideoUpload(i,o,r){return t(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:I,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)}},{response:e,uploadOptions:t}=yield P.uploadToCOS(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),n){let e=S.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(f+" _processFile error:",e),e}}_processMiniVideoFile(e){var t=(null==(t=this._core)?void 0:t.utils)["IN_ALIPAY_MINI_APP"],i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(t)throw new i({message:"VideoUnsupportedInAlipay"});if(r(e))throw new i({message:"FileUnsupportedInMiniApp"});return{url:(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_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(s){return t(this,void 0,void 0,function*(){try{console.log(f+" _getSnapshotInfoByUrl url:",s);var e,r,i,o=((yield function(s,a){return t(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:S.getPlatform(),cover_name:l(n(99999)),snapshot_url:s},this._core))||{})["download_url"];return(console.log(f+" _getSnapshotInfoByUrl OK snapshotUrl:",o),S.isEmpty(o))?{}:(e=S.addAuthToUrl(o),{width:r=0,height:i=0}=yield S.probeImageWidthHeight(e),{snapshotUrl:e,snapshotWidth:r,snapshotHeight:i})}catch(e){throw console.error(f+" _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 G{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:S.addAuthToUrl(e.url),remoteAudioUrl:S.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 G({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:S.removeAuthToUrl(r),Download_Flag:t,Second:o,Size:i,UUID:e}}}}let J=2108,Q=2300,X=20971520;var Z=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,G),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(f+" 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:S.generateUUID(s)},d=new G(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(f+" createAudioMessage error:",t),t}}upload(r){return t(this,void 0,void 0,function*(){console.log(f+" 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=S.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:Q});if(e.size>X)throw new t({message:"File size exceeds limit: "+c(X)});if(0===e.size)throw new t({code:J})}_performAudioUpload(i,o,r){return t(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:y,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)}},e=(yield P.uploadToCOS(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 ee={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}},te={createImageMessage:ee,createAudioMessage:ee,createVideoMessage:ee,createFileMessage:ee},oe={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},se={[u]:D,[g]:V,[m]:Y,[p]:Z};var ie=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"];D.init(e),V.init(e),Y.init(e),Z.init(e),P.init(e),S.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,r,i,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:oe,params:te})}sendMessage(i,o){return t(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 t(this,void 0,void 0,function*(){var t,r;if(!0!==i._relayFlag)try{let t=se[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=U.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}})}};export{ie as default};
1
+ function e(e,t){var o={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(o[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(o[s[i]]=e[s[i]])}return o}function t(e,t,o,s){return new(o||(o=Promise))((function(i,r){function n(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var o=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,o){return t(this,void 0,void 0,(function*(){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:i="",method:r="PUT",url:n,qs:a,headers:l={},resources:d,dataType:c="text",uploadByIP:h,uploadIP:u}=e;let p=n;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(r.toUpperCase(),p,!0),g.responseType=c;const m=Object.assign({},l);if(h&&u&&(m.host=u),!s(m))for(const e in m)m.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,m[e]);return g.onload=()=>{const t=this._getResponseBody(g,i,h&&u),s=this._buildResponse(g,t);if(200===g.status)o(null,s);else{if(u&&!p.includes(u))return e.url=this._domainName2IP(p,u),e.uploadByIP=!0,this.request(e,o);o({code:g.status,message:JSON.stringify(g.responseText)},s)}},g.onerror=()=>{const e=this._getResponseBody(g,i,h&&u),t=this._buildResponse(g,e),s={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(s,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:s}=t,i=Math.min(Math.floor(100*s/o),100);e.onProgress({total:o,loaded:s,percent:i/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,s]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=s}})),{statusCode:e.status,statusMessage:e.statusText,headers:o,data:t}}_getResponseBody(e,t,o){return 200===e.status&&t?{location:t,uploadIP:o}:{response:e.responseText,uploadIP:o}}_queryString(e,t="&",o="="){var s;const{isEmpty:i,isPlainObject:r}=null===(s=this._core)||void 0===s?void 0:s.utils;return i(e)?"":r(e)?Object.keys(e).map((s=>{const i=encodeURIComponent(s)+o;return Array.isArray(e[s])?e[s].map((e=>i+encodeURIComponent(e))).join(t):i+encodeURIComponent(e[s])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const s=["unknown","image","video","audio","log"];var i=new class{init(e){this._core=e}request(t,o){var i;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(i=this._core)||void 0===i?void 0:i.utils,{resources:l="",headers:d={},url:c,downloadUrl:h=""}=t;let u=c,p=null;const g=h?h.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const m=decodeURIComponent(g[3]),f=m.includes("?")?m.split("?")[0]:m||"",_={key:t.fileKey||f,success_action_status:200,"Content-Type":""},v={};if(a){const[e,t]=c.split("?sign=");t&&(u=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let I={url:u,header:d,name:"file",filePath:l,formData:Object.assign(Object.assign({},_),v),timeout:t.timeout||3e5};if(n){const o=e(I,["name"]);I=Object.assign(Object.assign({},o),{fileName:"file",fileType:t.fileType?s[t.fileType]:"image"})}return p=r.uploadFile(Object.assign(Object.assign({},I),{success:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})},fail:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})}})),p.onProgressUpdate&&p.onProgressUpdate((e=>{t.onProgress&&t.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})})),p}_handleResponse(e){const{downloadUrl:t,response:o,callback:s}=e,i={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(i[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?s(null,{statusCode:r,headers:i,data:Object.assign(Object.assign({},o.data),{location:t})}):s({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:i,data:void 0})}};function r(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function n(e){const t=e||99999999;return Math.round(Math.random()*t)}function a(e,t=!0,o=!0){const s=Date.now();return t?o?s-e+" ms":`${Math.round((s-e)/1e3)} s`:o?s-e:Math.round((s-e)/1e3)}function l(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function d(e,t){return Math.round(Number(e)*10**t)/10**t}function c(e){const t=1024,o=1048576;return e<t?`${e}B`:e<o?`${Math.floor(e/t)}KB`:`${Math.floor(e/o)}MB`}function h(e){if(e<=1048576){return`${d(e/1024,1)}KB/s`}return`${d(e/1048576,1)}MB/s`}const u="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",m="TIMVideoFileElem",f="RichMediaMessagePlugin",_=["rich.my-imcloud.com","imrich.qcloud.com"],v=1,I=2,y=3;var U;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(U||(U={}));const w={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 S=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[o,s]=e.split("?");if(!s)return o;const i=s.split("&").reduce(((e,o)=>{const[s,i]=o.split("=");return s&&s!==t&&(e[s]=i||""),e}),{}),r=Object.keys(i).map((e=>`${e}${i[e]?`=${i[e]}`:""}`)).join("&");return r?`${o}?${r}`:o}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(w).some((t=>t.test(e)))}extractFileFromInput(e){return r(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let o=t;for(;null!==Object.getPrototypeOf(o);)o=Object.getPrototypeOf(o);return t===o}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return t(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:o,IN_BROWSER:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:s?this._probeImageDimensionsWeb(e):o?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:o}=t;return"0"!==o}getFileDNList(){var e;let t=_;const o=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:s}=o;if(void 0===s)return t;try{JSON.parse(s).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=_}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var o;let s=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(o=this._core)||void 0===o?void 0:o.utils.randomString()}`;if(t)return`${s}.${t}`;const i=e.name||e.value||e.url||e.tempFilePath,r=i&&i.slice(i.lastIndexOf(".")+1);return r&&(s=`${s}.${r}`),s}processResourceUrl(e){if(!e)return"";let t=e;const o=this.getFileDownloadProxy(),s=this.getAuthKey(),i=this.getFileDNList();o&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,o):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,o)));const r=s&&-1===t.indexOf("authKey=")&&function(e,t){let o=!1;if(e){const s=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),i=s&&s[2]||"";if(i.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(i.endsWith(t[e])){o=!0;break}}return o}(t,i);return r&&(t=t.indexOf("?")>-1?`${t}&authKey=${s}`:`${t}?authKey=${s}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:s,IN_UNI_NATIVE_APP:i}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:s,IN_UNI_NATIVE_APP:i}}isEmpty(e){var t;const{isEmpty:o}=null===(t=this._core)||void 0===t?void 0:t.utils;return o(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:o}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{o.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:o,IE_VERSION:s}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||o&&9===s}_probeImageDimensionsWeb(e){return new Promise((t=>{const o=new Image,s=()=>{o.onload=null,o.onerror=null,o.src=""};o.onload=()=>{t({width:o.width,height:o.height}),s()},o.onerror=()=>{t({width:0,height:0}),s()},o.src=e}))}};var P=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;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?i:o,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return t(this,void 0,void 0,(function*(){const t=`${f} uploadToCOS`,{file:o}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const s=Date.now(),i=yield this._createCosOptions(e),r=yield this._uploadFile(i);this._handleUploadError(r,e);const n=this._createUploadResult(o,r),a=Date.now()-s,l=c(o.size),d=`size:${l} time:${a}ms speed:${h(1e3*o.size/a)}`;return console.log(`${t} ok. name:${o.name} ${d}`),{uploadOptions:i,response:n}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var o,s;const{ChatError:i}=null===(o=this._core)||void 0===o?void 0:o.helper;if(403===e.statusCode)throw a(Date.now(),!1),t.url,(null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.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:a(Date.now(),!1),uploadSpeed:h(1e3*e.size/a(Date.now(),!1))}}_createCosOptions(e){return t(this,void 0,void 0,(function*(){const{fileName:t,resources:o,uploadMethod:s}=this._prepareUploadParams(e),i=this._isC2CConversation(e.message.conversationID)?1:2;try{const r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:s,duration:this.duration,userID:e.message.from,conversationType:i}),{uploadUrl:n,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h}=r,u=!S.isPrivateNetWork()&&r.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:t,resources:o,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h,uploadIP:u||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${f} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:o,IN_RN_APP:s}=S.getPlatformFlags(),i=o||s,r=i&&e.message.type!==g,{name:a}=t,d=a.slice(a.lastIndexOf(".")),c=`${n(999999)}${d}`;return{fileName:l(r?t.name:c),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(e){return t(this,void 0,void 0,(function*(){const o=`${f} fetchCosSignatureUrl`,s=S.isSimpleCos(),i=this._prepareCosRequestData(e),r=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,o,s){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=s,r=t.generateCosSpecifiedData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return yield i.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(r,i,this._core);this.fetchCosTryCount=0;const n=this._processResponse(e);return console.log(`${o} ok. isSimpleCos:${s} data:`,n),n||{}}catch(t){if(console.error(`${o} failed, error:`,t),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}}))}_processResponse(e){var t;const o=S.isSimpleCos(),s=o?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!s)return{};if(o){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:o,uint32_exist_flag:i,str_download_url:r,str_upload_url:n,str_snapshot_url:a,str_file_key:l}=s;return{uploadIP:e,preSig:t,fileID:o,existFlag:i,downloadUrl:r,uploadUrl:n,requestSnapshotUrl:a,fileKey:l}}const{upload_url:i,download_url:r,snapshot_url:n,thumb_url:a,large_url:l,file_key:d}=s;return{uploadUrl:i,downloadUrl:r,requestSnapshotUrl:n,thumbUrl:a,largeUrl:l,fileKey:d}}_prepareCosRequestData(e){return S.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:S.getPlatform(),uint32_sdkappid:S.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(e){return t(this,void 0,void 0,(function*(){return new Promise(((t,o)=>{this.httpRequest.request(e,((s,i)=>{s&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(s)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(o)):(this.uploadFileTryCount=0,s?o(s):t(i))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,o;try{const s=null===(t=e.error)||void 0===t?void 0:t.Code,i=null===(o=e.error)||void 0===o?void 0:o.Message;return"RequestTimeTooSkewed"===s||"AccessDenied"===s&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,o,s;const i=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(s=e.error)||void 0===s?void 0:s.ServerTime);if(!i)return!1;const r=Date.now(),n=Date.parse(i);return Math.abs(r+this.systemClockOffset-n)>=3e4}_syncSystemClock(e){var t,o,s;const i=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(s=e.error)||void 0===s?void 0:s.ServerTime);if(i){const e=Date.now(),t=Date.parse(i);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=S.getFileUploadProxy();let o=e;return t&&(o=e.replace(/^https:\/\/[^/]+/,t)),o}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const F=2108,M=2251,b=2252,A=["jpg","jpeg","gif","png","bmp","image","webp"],O=20971520,T={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class N{constructor(e,t){this.instanceID=n(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=S.addAuthToUrl(e.imageUrl||e.url||""),this.url=S.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=S.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function C(t){const{originUrl:o,originWidth:s,originHeight:i,min:r=198}=t,n=parseInt(s)||0,a=parseInt(i)||0,l={url:void 0,width:0,height:0};if((n<=a?n:a)<=r)l.url=o,l.width=n,l.height=a;else{a<=n?(l.width=Math.ceil(n*r/a),l.height=r):(l.width=r,l.height=Math.ceil(a*r/n));const e=o&&o.indexOf("?")>-1?`${o}&`:`${o}?`;l.url=198===r?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===o){return e(l,["url"])}return l}class E{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=u;const{uuid:t,file:o,imageFormat:s,imageInfoArray:i=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(o),this.content={imageFormat:s,uuid:t,imageInfoArray:[]},this.initImageInfoArray(i),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:o,ImageInfoArray:s,UUID:i}=t,r=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(s);return new E({imageFormat:o,imageInfoArray:r,uuid:i})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:s,IN_BROWSER:i}=S.getPlatformFlags();return e?((o||s)&&(t=e.url),i&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let o=0;o<3;o++){const s=e[o]||Object.assign({},t),i=new N(s,this._imageMemoryURL);i.setSizeType(o+1),i.setType(o),this.addImageInfo(i)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[o,...s]=t.imageUrl.split("://"),i=s.join("://");e.includes(o)||t.setImageUrl(`https://${i}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=T[e.toUpperCase()]||T.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let o;for(let s=0;s<t;s++)o=this.content.imageInfoArray[s],e[s].size&&(o.size=e[s].size),e[s].url&&o.setImageUrl(e[s].url),e[s].width&&(o.width=e[s].width),e[s].height&&(o.height=e[s].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],C({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:s,imageFormat:i,imageInfoArray:r}=o;return{MsgType:this.type,MsgContent:{ImageFormat:i,ImageInfoArray:this.parseImageInfoArray(r),UUID:s}}}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:S.removeAuthToUrl(e.imageUrl)})))}}var D=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createImageMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,E),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createImageMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${f} createImageMessage options:`,e);const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,n=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:r})),a=this._processImage(e);e.payload.file=a;const l={imageFormat:T.UNKNOWN,uuid:S.generateUUID(a),file:a,imageInfoArray:[]},d=new E(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,e),console.log(`${f} createImageMessage OK imageMessage:`,n),i.end(),n}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createImageMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadImage message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(o);const s=yield this._performImageUpload(t,e,o),i=this._generateImageInfo(s);return t.updateImageFormat(null==s?void 0:s.fileType),t.updateImageInfoArray(i),e}))}_performImageUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:v,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{uploadOptions:r,response:n}=yield P.uploadToCOS(i);return this._parseResponse(r,n)}))}_generateImageInfo(e){console.log(`${f} generateImageInfo`);const{location:t,fileSize:o,width:s,height:i,smallImageUrl:r,smallImageWidth:n,smallImageHeight:a,largeImageUrl:l,largeImageWidth:d,largeImageHeight:c,imageInfoArray:h}=e,u=S.addAuthToUrl(t),p={size:o,url:u,width:s,height:i};return(null==h?void 0:h.length)>0?this._processImageInfoArray(h,o):r&&l?[Object.assign({},p),{largeImageUrl:l,largeImageWidth:d,largeImageHeight:c},{smallImageUrl:r,smallImageWidth:n,smallImageHeight:a}]:[Object.assign({},p),this._generateThumbInfo(u,s,i,720),this._generateThumbInfo(u,s,i,198)]}_generateThumbInfo(e,t,o,s){return C({originUrl:e,originWidth:t,originHeight:o,min:s})}_processImageInfoArray(e,t){let o,s,i;for(const r of e)1===r.type?(s=r,s.size=t):2===r.type?(i=r,i.size=t):(o=r,o.size=t);return[Object.assign({},o),Object.assign({},i),Object.assign({},s)]}_parseResponse(e,o){return t(this,void 0,void 0,(function*(){console.log(`${f} parseResponse`);try{const{thumbUrl:t,largeUrl:s,downloadUrl:i}=e;t&&s&&(yield this._getImageInfoByUrl(t,o,"thumb"),yield this._getImageInfoByUrl(s,o,"large"));if(S.isSimpleCos()&&!S.isPrivateNetWork()&&(yield this._getImageInfoArray(i,o),null==o?void 0:o.uploadIP)){const e=this._extractDomainFromUrl(i);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,o,s){return t(this,void 0,void 0,(function*(){try{const t=S.addAuthToUrl(e),{width:i=0,height:r=0}=yield S.probeImageWidthHeight(t);o.width=i,o.height=r,"thumb"===s?(o.smallImageUrl=e,o.smallImageWidth=i,o.smallImageHeight=r):(o.largeImageUrl=e,o.largeImageWidth=i,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:M});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:s}=e.payload;return s=o?this._processMiniAppImageFile(s):this._processWebImageFile(s),s}catch(e){throw console.warn(`${f} _processImage error:`,e),e}}_processMiniAppImageFile(e){r(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const 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;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper,s=S.extractFileFromInput(e);if(!s)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return s}_getDownloadIP(e,o){return t(this,void 0,void 0,(function*(){const s=`${f} getDownloadIP domainName: ${e}`;try{const i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=o,i="im_cos_msg.get_final_ip",r={str_domain:e},n=t.generateProtocolData({servcmd:i,data:r}),a=`${n.head.seq}${i}`;return yield s.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!i||!i.str_final_ip)return;console.log(`${s} ok. downloadIP:${i}`);const r=o.location.split("/");r[0]=i.str_final_ip,o.location=r.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,o){return t(this,void 0,void 0,(function*(){const s=`${f}._getImageInfoArray`;try{const i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=o,i="im_cos_msg.get_imageinfo",r={str_image_url:e},n=t.generateProtocolData({servcmd:i,data:r}),a=`${n.head.seq}${i}`;return yield s.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return o.imageInfoArray=this._processImageInfoResponse(i),console.log(`${s} ok`),o}catch(e){throw o.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.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){const{utils:t,helper:o}=this._core;let s="";if(t.IN_MINI_APP&&(s=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(s=e.name.slice(e.name.lastIndexOf(".")+1)),A.indexOf(s.toLowerCase())<0)throw new o.ChatError({code:b})}_checkImageSize(e){const{utils:t,helper:o}=this._core;let s=0;if(s=(t.IN_MINI_APP,e.size),0===s)throw new o.ChatError({code:F});if(s>=O)throw new o.ChatError({message:`File size exceeds limit: ${c(O)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const $=2108,R=2401,z="2.5.0",x="1.18.0",W=104857600;function j(e,t){const o=e.split("."),s=t.split("."),i=Math.max(o.length,s.length);for(;o.length<i;)o.push("0");for(;s.length<i;)s.push("0");for(let e=0;e<i;e++){const t=parseInt(o[e]),i=parseInt(s[e]);if(t>i)return 1;if(t<i)return-1}return 0}class q{constructor(e){this.type=g,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:S.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:o,Url:s,FileName:i,FileSize:r,UUID:n}=t;return new q({downloadFlag:o,url:s,fileName:i,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:s,downloadFlag:i,fileUrl:r,fileName:n,fileSize:a}=o;return{MsgType:this.type,MsgContent:{Download_Flag:i,Url:S.removeAuthToUrl(r),FileName:n,FileSize:a,UUID:s}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(S.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${n(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 V=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createFileMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,q),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createFileMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${f} createFileMessage options:`,e),this._checkVersion();const r=this._processFile(e.payload.file);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={uuid:S.generateUUID(r),file:r},d=new q(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${f} createFileMessage success fileMessage:`,a),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createFileMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const o=e.getElements()[0],s=yield this._performFileUpload(o,e,t),i=S.addAuthToUrl(null==s?void 0:s.location);return o.updateFileUrl(i),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:R});if(e.size>W)throw new o({message:`File size exceeds limit: ${c(W)}`});if(0===e.size)throw new o({code:$})}_performFileUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:v,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r}=yield P.uploadToCOS(i);return r}))}_processFile(e){var t,o;const{IN_BROWSER:s,IN_RN_APP:i,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:l}=null===(o=this._core)||void 0===o?void 0:o.helper;if(s||a){const t=S.extractFileFromInput(e);if(!t)throw new l({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(r||n){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return i?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:o,IN_MINI_APP:s,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(s){if(!(i||r||n))throw new a({message:"Unsupported mini app environment"});const e=o.getSystemInfoSync().SDKVersion;if(i&&j(e,z)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${z} or higher`})}if(r&&j(e,x)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${x} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const L=2108,k=2352,B=["mp4","quicktime","mov"],H=104857600;class K{constructor(e){this.type=m,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:S.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:S.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:S.addAuthToUrl(e.thumbUrl),snapshotUrl:S.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:o,VideoFormat:s,VideoSecond:i,VideoSize:r,VideoDownloadFlag:n,VideoUUID:a,ThumbUUID:l,ThumbFormat:d,ThumbWidth:c,SnapshotWidth:h,ThumbHeight:u,SnapshotHeight:p,ThumbSize:g,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:_,SnapshotUrl:v}=t;return new K({videoUrl:o,videoFormat:s,videoSecond:i,videoSize:r,videoDownloadFlag:n,videoUUID:a,thumbUUID:l,thumbFormat:d,thumbWidth:c,snapshotWidth:h,thumbHeight:u,snapshotHeight:p,thumbSize:g,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:_,snapshotUrl:v})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:o,snapshotHeight:s}=e;S.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),S.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),S.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{remoteVideoUrl:s,videoFormat:i,videoSecond:r,videoSize:n,videoDownloadFlag:a,videoUUID:l,thumbUUID:d,thumbFormat:c,thumbWidth:h,snapshotWidth:u,thumbHeight:p,snapshotHeight:g,thumbSize:m,snapshotSize:f,thumbDownloadFlag:_,thumbUrl:v,snapshotUrl:I}=o;return{MsgType:this.type,MsgContent:{VideoUrl:S.removeAuthToUrl(s),VideoFormat:i,VideoSecond:r,VideoSize:n,VideoDownloadFlag:a,VideoUUID:l,ThumbUUID:d,ThumbFormat:c,ThumbWidth:h,SnapshotWidth:u,ThumbHeight:p,SnapshotHeight:g,ThumbSize:m,SnapshotSize:f,ThumbDownloadFlag:_,ThumbUrl:S.removeAuthToUrl(v),SnapshotUrl:S.removeAuthToUrl(I)}}}}var Y=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createVideoMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,K),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createVideoMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${f} createVideoMessage options:`,e);const r=this._processVideo(e);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={videoFormat:r.videoFile.type,videoSecond:d(r.videoFile.second,0),videoSize:r.videoFile.size,remoteVideoUrl:"",videoUrl:r.videoFile.url,videoUUID:S.generateUUID(r.videoFile),thumbUUID:S.generateUUID(r.videoFile,"jpg"),thumbWidth:r.width||200,thumbHeight:r.height||200,thumbUrl:r.thumbUrl,thumbSize:r.thumbSize,thumbFormat:"jpg"},c=new K(l);return a.setElement(c),this._messageOptionsMap.set(a.clientSequence,e),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createVideoMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadVideo message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(o);const s=yield this._performVideoUpload(t,e,o),{location:i,snapshotInfo:r}=s,n=S.addAuthToUrl(i);return t.updateVideoUrl(n),S.isEmpty(r)||t.updateSnapshotInfo(r),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>H)throw new o({message:`File size exceeds limit: ${c(H)}`});if(0===e.videoFile.size)throw new o({code:L});if(-1===B.indexOf(e.videoFile.type))throw new o({code:k})}_performVideoUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:I,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r,uploadOptions:n}=yield P.uploadToCOS(i);return{snapshotInfo:yield this._getSnapshotInfoByUrl(n.requestSnapshotUrl),location:r.location}}))}_processVideo(e){var t,o;try{const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:i,IN_BROWSER:r}=null===(o=this._core)||void 0===o?void 0:o.utils;let{file:n}=e.payload,a={};if(i&&(a=this._processMiniVideoFile(n),n.name=a.name,n.url=a.url),r){const e=S.extractFileFromInput(n);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});n=e,a=this._processWebVideoFile(n)}return n.videoFile=a,n.thumbUrl="",n.thumbSize=0,n}catch(e){throw console.warn(`${f} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,o;const{IN_ALIPAY_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:i}=null===(o=this._core)||void 0===o?void 0:o.helper;if(s)throw new i({message:"VideoUnsupportedInAlipay"});if(r(e))throw new i({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:o=1,duration:s=0,type:i}=e,r=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:o,second:s,type:r}}_getSnapshotInfoByUrl(e){return t(this,void 0,void 0,(function*(){try{console.log(`${f} _getSnapshotInfoByUrl url:`,e);const o={version:1,platform:S.getPlatform(),cover_name:l(n(99999)),snapshot_url:e},s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const t="im_cos_msg.video_cover",{helper:s,channel:i}=o,r=s.generateCosSpecifiedData({servcmd:t,data:e}),n=`${r.head.seq}${t}`;return yield i.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(o,this._core),{download_url:i}=s||{};if(console.log(`${f} _getSnapshotInfoByUrl OK snapshotUrl:`,i),S.isEmpty(i))return{};const r=S.addAuthToUrl(i),{width:a=0,height:d=0}=yield S.probeImageWidthHeight(r);return{snapshotUrl:r,snapshotWidth:a,snapshotHeight:d}}catch(e){throw console.error(`${f} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class G{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:S.addAuthToUrl(e.url),remoteAudioUrl:S.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:o,Download_Flag:s,Second:i,Size:r,UUID:n}=t;return new G({url:o,downloadFlag:s,second:i,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:s,downloadFlag:i,remoteAudioUrl:r,size:n,second:a}=o;return{MsgType:this.type,MsgContent:{Url:S.removeAuthToUrl(r),Download_Flag:i,Second:a,Size:n,UUID:s}}}}const J=2108,Q=2300,X=20971520;var Z=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createAudioMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,G),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createAudioMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${f} createAudioMessage options:`,e);let{file:r}=e.payload;r=this._processAudioFile(e.payload.file),e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={second:Math.floor((r.duration||r.second)/1e3),size:r.fileSize||r.size||1,url:r.tempFilePath||r.uri||r.url,uuid:S.generateUUID(r)},d=new G(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createAudioMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const o=e.getElements()[0],s=yield this._performAudioUpload(o,e,t),i=S.addAuthToUrl(null==s?void 0:s.location);return o.updateAudioUrl(i),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:Q});if(e.size>X)throw new o({message:`File size exceeds limit: ${c(X)}`});if(0===e.size)throw new o({code:J})}_performAudioUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:y,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r}=yield P.uploadToCOS(i);return r}))}_processAudioFile(e){var t;const{IN_MINI_APP:o,IN_BROWSER:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return o?this._processMiniFile(e):s?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){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const ee={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}},te={createImageMessage:ee,createAudioMessage:ee,createVideoMessage:ee,createFileMessage:ee},oe={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},se={[u]:D,[g]:V,[m]:Y,[p]:Z};var ie=new class{constructor(){this.name="RichMediaMessage"}install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:o,MSG_IMAGE:s,MSG_VIDEO:i}}}=e;D.init(e),V.init(e),Y.init(e),Z.init(e),P.init(e),S.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,o,s,i].includes(e[0].type)}),e.helper.registerValidateConfig({auth:oe,params:te})}sendMessage(e,o){return t(this,void 0,void 0,(function*(){var t,s,i;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(i=null===(s=null===(t=this._core)||void 0===t?void 0:t.message)||void 0===s?void 0:s.messageSender)||void 0===i?void 0:i.sendMessage(e,o)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return t(this,void 0,void 0,(function*(){var t,o;if(!0!==e._relayFlag)try{const t=se[e.type];if(t){const o=this._core.ssoLog.createSSOLogData({method:"upload"});o.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),o.end()}}catch(s){throw e.status=U.FAIL,s instanceof Error&&(s.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,s).end(),s}}))}};export{ie as default};
@@ -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 i(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function s(e){e=e||99999999;return Math.round(Math.random()*e)}function a(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){return i(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?Array.isArray(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]: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 a(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:a(Date.now(),!1),uploadSpeed:c(1e3*e.size/a(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=""+s(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 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=s(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 V(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){i(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)),q.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}class O{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 O({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){return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(I.getPlatform().IN_UNI_NATIVE_APP&&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=s(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 T=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,O),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 O(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:1,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 N{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 N({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 E=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,N),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 N(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),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 t=(null==(t=this._core)?void 0:t.utils)["IN_ALIPAY_MINI_APP"],r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(i(e))throw new r({message:"FileUnsupportedInMiniApp"});return{url:(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_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(s(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 D{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 D({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 R=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,D),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 D(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}},k={createImageMessage:t,createAudioMessage:t,createVideoMessage:t,createFileMessage:t},B={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},H={TIMImageElem:P,TIMFileElem:T,TIMVideoFileElem:E,TIMSoundElem:R};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"];P.init(e),T.init(e),E.init(e),R.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:B,params:k})}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=H[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(){"use strict";function e(e,t){var o={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(o[i[s]]=e[i[s]])}return o}function t(e,t,o,i){return new(o||(o=Promise))((function(s,r){function n(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var o=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,o){return t(this,void 0,void 0,(function*(){var t;const{isEmpty:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:s="",method:r="PUT",url:n,qs:a,headers:l={},resources:d,dataType:c="text",uploadByIP:h,uploadIP:u}=e;let p=n;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(r.toUpperCase(),p,!0),g.responseType=c;const m=Object.assign({},l);if(h&&u&&(m.host=u),!i(m))for(const e in m)m.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,m[e]);return g.onload=()=>{const t=this._getResponseBody(g,s,h&&u),i=this._buildResponse(g,t);if(200===g.status)o(null,i);else{if(u&&!p.includes(u))return e.url=this._domainName2IP(p,u),e.uploadByIP=!0,this.request(e,o);o({code:g.status,message:JSON.stringify(g.responseText)},i)}},g.onerror=()=>{const e=this._getResponseBody(g,s,h&&u),t=this._buildResponse(g,e),i={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(i,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:i}=t,s=Math.min(Math.floor(100*i/o),100);e.onProgress({total:o,loaded:i,percent:s/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,i]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=i}})),{statusCode:e.status,statusMessage:e.statusText,headers:o,data:t}}_getResponseBody(e,t,o){return 200===e.status&&t?{location:t,uploadIP:o}:{response:e.responseText,uploadIP:o}}_queryString(e,t="&",o="="){var i;const{isEmpty:s,isPlainObject:r}=null===(i=this._core)||void 0===i?void 0:i.utils;return s(e)?"":r(e)?Object.keys(e).map((i=>{const s=encodeURIComponent(i)+o;return Array.isArray(e[i])?e[i].map((e=>s+encodeURIComponent(e))).join(t):s+encodeURIComponent(e[i])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const i=["unknown","image","video","audio","log"];var s=new class{init(e){this._core=e}request(t,o){var s;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:l="",headers:d={},url:c,downloadUrl:h=""}=t;let u=c,p=null;const g=h?h.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const m=decodeURIComponent(g[3]),f=m.includes("?")?m.split("?")[0]:m||"",_={key:t.fileKey||f,success_action_status:200,"Content-Type":""},v={};if(a){const[e,t]=c.split("?sign=");t&&(u=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let I={url:u,header:d,name:"file",filePath:l,formData:Object.assign(Object.assign({},_),v),timeout:t.timeout||3e5};if(n){const o=e(I,["name"]);I=Object.assign(Object.assign({},o),{fileName:"file",fileType:t.fileType?i[t.fileType]:"image"})}return p=r.uploadFile(Object.assign(Object.assign({},I),{success:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})},fail:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})}})),p.onProgressUpdate&&p.onProgressUpdate((e=>{t.onProgress&&t.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})})),p}_handleResponse(e){const{downloadUrl:t,response:o,callback:i}=e,s={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(s[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?i(null,{statusCode:r,headers:s,data:Object.assign(Object.assign({},o.data),{location:t})}):i({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:s,data:void 0})}};function r(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function n(e){const t=e||99999999;return Math.round(Math.random()*t)}function a(e,t=!0,o=!0){const i=Date.now();return t?o?i-e+" ms":`${Math.round((i-e)/1e3)} s`:o?i-e:Math.round((i-e)/1e3)}function l(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function d(e,t){return Math.round(Number(e)*10**t)/10**t}function c(e){const t=1024,o=1048576;return e<t?`${e}B`:e<o?`${Math.floor(e/t)}KB`:`${Math.floor(e/o)}MB`}function h(e){if(e<=1048576){return`${d(e/1024,1)}KB/s`}return`${d(e/1048576,1)}MB/s`}const u="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",m="TIMVideoFileElem",f="RichMediaMessagePlugin",_=["rich.my-imcloud.com","imrich.qcloud.com"],v=1,I=2,y=3;var U;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(U||(U={}));const w={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 S=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[o,i]=e.split("?");if(!i)return o;const s=i.split("&").reduce(((e,o)=>{const[i,s]=o.split("=");return i&&i!==t&&(e[i]=s||""),e}),{}),r=Object.keys(s).map((e=>`${e}${s[e]?`=${s[e]}`:""}`)).join("&");return r?`${o}?${r}`:o}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(w).some((t=>t.test(e)))}extractFileFromInput(e){return r(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let o=t;for(;null!==Object.getPrototypeOf(o);)o=Object.getPrototypeOf(o);return t===o}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return t(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:o,IN_BROWSER:i}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:i?this._probeImageDimensionsWeb(e):o?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:o}=t;return"0"!==o}getFileDNList(){var e;let t=_;const o=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:i}=o;if(void 0===i)return t;try{JSON.parse(i).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=_}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var o;let i=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(o=this._core)||void 0===o?void 0:o.utils.randomString()}`;if(t)return`${i}.${t}`;const s=e.name||e.value||e.url||e.tempFilePath,r=s&&s.slice(s.lastIndexOf(".")+1);return r&&(i=`${i}.${r}`),i}processResourceUrl(e){if(!e)return"";let t=e;const o=this.getFileDownloadProxy(),i=this.getAuthKey(),s=this.getFileDNList();o&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,o):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,o)));const r=i&&-1===t.indexOf("authKey=")&&function(e,t){let o=!1;if(e){const i=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),s=i&&i[2]||"";if(s.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(s.endsWith(t[e])){o=!0;break}}return o}(t,s);return r&&(t=t.indexOf("?")>-1?`${t}&authKey=${i}`:`${t}?authKey=${i}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:i,IN_UNI_NATIVE_APP:s}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:i,IN_UNI_NATIVE_APP:s}}isEmpty(e){var t;const{isEmpty:o}=null===(t=this._core)||void 0===t?void 0:t.utils;return o(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:o}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{o.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:o,IE_VERSION:i}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||o&&9===i}_probeImageDimensionsWeb(e){return new Promise((t=>{const o=new Image,i=()=>{o.onload=null,o.onerror=null,o.src=""};o.onload=()=>{t({width:o.width,height:o.height}),i()},o.onerror=()=>{t({width:0,height:0}),i()},o.src=e}))}};var P=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;const{IN_MINI_APP:i}=e.utils;this.httpRequest=i?s:o,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return t(this,void 0,void 0,(function*(){const t=`${f} uploadToCOS`,{file:o}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const i=Date.now(),s=yield this._createCosOptions(e),r=yield this._uploadFile(s);this._handleUploadError(r,e);const n=this._createUploadResult(o,r),a=Date.now()-i,l=c(o.size),d=`size:${l} time:${a}ms speed:${h(1e3*o.size/a)}`;return console.log(`${t} ok. name:${o.name} ${d}`),{uploadOptions:s,response:n}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var o,i;const{ChatError:s}=null===(o=this._core)||void 0===o?void 0:o.helper;if(403===e.statusCode)throw a(Date.now(),!1),t.url,(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.uploadIP)&&e.data.uploadIP,new s({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:a(Date.now(),!1),uploadSpeed:h(1e3*e.size/a(Date.now(),!1))}}_createCosOptions(e){return t(this,void 0,void 0,(function*(){const{fileName:t,resources:o,uploadMethod:i}=this._prepareUploadParams(e),s=this._isC2CConversation(e.message.conversationID)?1:2;try{const r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:i,duration:this.duration,userID:e.message.from,conversationType:s}),{uploadUrl:n,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h}=r,u=!S.isPrivateNetWork()&&r.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:t,resources:o,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h,uploadIP:u||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${f} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:o,IN_RN_APP:i}=S.getPlatformFlags(),s=o||i,r=s&&e.message.type!==g,{name:a}=t,d=a.slice(a.lastIndexOf(".")),c=`${n(999999)}${d}`;return{fileName:l(r?t.name:c),resources:s?t.url:t,uploadMethod:s?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(e){return t(this,void 0,void 0,(function*(){const o=`${f} fetchCosSignatureUrl`,i=S.isSimpleCos(),s=this._prepareCosRequestData(e),r=i?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,o,i){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=i,r=t.generateCosSpecifiedData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(r,s,this._core);this.fetchCosTryCount=0;const n=this._processResponse(e);return console.log(`${o} ok. isSimpleCos:${i} data:`,n),n||{}}catch(t){if(console.error(`${o} failed, error:`,t),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}}))}_processResponse(e){var t;const o=S.isSimpleCos(),i=o?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!i)return{};if(o){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:o,uint32_exist_flag:s,str_download_url:r,str_upload_url:n,str_snapshot_url:a,str_file_key:l}=i;return{uploadIP:e,preSig:t,fileID:o,existFlag:s,downloadUrl:r,uploadUrl:n,requestSnapshotUrl:a,fileKey:l}}const{upload_url:s,download_url:r,snapshot_url:n,thumb_url:a,large_url:l,file_key:d}=i;return{uploadUrl:s,downloadUrl:r,requestSnapshotUrl:n,thumbUrl:a,largeUrl:l,fileKey:d}}_prepareCosRequestData(e){return S.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:S.getPlatform(),uint32_sdkappid:S.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(e){return t(this,void 0,void 0,(function*(){return new Promise(((t,o)=>{this.httpRequest.request(e,((i,s)=>{i&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(i)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(o)):(this.uploadFileTryCount=0,i?o(i):t(s))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,o;try{const i=null===(t=e.error)||void 0===t?void 0:t.Code,s=null===(o=e.error)||void 0===o?void 0:o.Message;return"RequestTimeTooSkewed"===i||"AccessDenied"===i&&"Request has expired"===s}catch(e){return!1}}_isClockOutOfSync(e){var t,o,i;const s=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(i=e.error)||void 0===i?void 0:i.ServerTime);if(!s)return!1;const r=Date.now(),n=Date.parse(s);return Math.abs(r+this.systemClockOffset-n)>=3e4}_syncSystemClock(e){var t,o,i;const s=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(i=e.error)||void 0===i?void 0:i.ServerTime);if(s){const e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=S.getFileUploadProxy();let o=e;return t&&(o=e.replace(/^https:\/\/[^/]+/,t)),o}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const F=2108,M=2251,b=2252,A=["jpg","jpeg","gif","png","bmp","image","webp"],O=20971520,T={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class C{constructor(e,t){this.instanceID=n(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=S.addAuthToUrl(e.imageUrl||e.url||""),this.url=S.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=S.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function N(t){const{originUrl:o,originWidth:i,originHeight:s,min:r=198}=t,n=parseInt(i)||0,a=parseInt(s)||0,l={url:void 0,width:0,height:0};if((n<=a?n:a)<=r)l.url=o,l.width=n,l.height=a;else{a<=n?(l.width=Math.ceil(n*r/a),l.height=r):(l.width=r,l.height=Math.ceil(a*r/n));const e=o&&o.indexOf("?")>-1?`${o}&`:`${o}?`;l.url=198===r?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===o){return e(l,["url"])}return l}class E{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=u;const{uuid:t,file:o,imageFormat:i,imageInfoArray:s=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(o),this.content={imageFormat:i,uuid:t,imageInfoArray:[]},this.initImageInfoArray(s),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:o,ImageInfoArray:i,UUID:s}=t,r=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(i);return new E({imageFormat:o,imageInfoArray:r,uuid:s})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:i,IN_BROWSER:s}=S.getPlatformFlags();return e?((o||i)&&(t=e.url),s&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let o=0;o<3;o++){const i=e[o]||Object.assign({},t),s=new C(i,this._imageMemoryURL);s.setSizeType(o+1),s.setType(o),this.addImageInfo(s)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[o,...i]=t.imageUrl.split("://"),s=i.join("://");e.includes(o)||t.setImageUrl(`https://${s}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=T[e.toUpperCase()]||T.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let o;for(let i=0;i<t;i++)o=this.content.imageInfoArray[i],e[i].size&&(o.size=e[i].size),e[i].url&&o.setImageUrl(e[i].url),e[i].width&&(o.width=e[i].width),e[i].height&&(o.height=e[i].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],N({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:i,imageFormat:s,imageInfoArray:r}=o;return{MsgType:this.type,MsgContent:{ImageFormat:s,ImageInfoArray:this.parseImageInfoArray(r),UUID:i}}}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:S.removeAuthToUrl(e.imageUrl)})))}}var D=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:i,InnerEvent:s,message:r}=e;i.registerApi({apiName:"createImageMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,E),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,o,i,s,r;try{const s=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${f} createImageMessage options:`,e);const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,n=null===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.createMessage(Object.assign(Object.assign({},e),{from:r})),a=this._processImage(e);e.payload.file=a;const l={imageFormat:T.UNKNOWN,uuid:S.generateUUID(a),file:a,imageInfoArray:[]},d=new E(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,e),console.log(`${f} createImageMessage OK imageMessage:`,n),s.end(),n}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===r||r.call(s,e).end(),console.error(`${f} createImageMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadImage message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(o);const i=yield this._performImageUpload(t,e,o),s=this._generateImageInfo(i);return t.updateImageFormat(null==i?void 0:i.fileType),t.updateImageInfoArray(s),e}))}_performImageUpload(e,o,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:v,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{uploadOptions:r,response:n}=yield P.uploadToCOS(s);return this._parseResponse(r,n)}))}_generateImageInfo(e){console.log(`${f} generateImageInfo`);const{location:t,fileSize:o,width:i,height:s,smallImageUrl:r,smallImageWidth:n,smallImageHeight:a,largeImageUrl:l,largeImageWidth:d,largeImageHeight:c,imageInfoArray:h}=e,u=S.addAuthToUrl(t),p={size:o,url:u,width:i,height:s};return(null==h?void 0:h.length)>0?this._processImageInfoArray(h,o):r&&l?[Object.assign({},p),{largeImageUrl:l,largeImageWidth:d,largeImageHeight:c},{smallImageUrl:r,smallImageWidth:n,smallImageHeight:a}]:[Object.assign({},p),this._generateThumbInfo(u,i,s,720),this._generateThumbInfo(u,i,s,198)]}_generateThumbInfo(e,t,o,i){return N({originUrl:e,originWidth:t,originHeight:o,min:i})}_processImageInfoArray(e,t){let o,i,s;for(const r of e)1===r.type?(i=r,i.size=t):2===r.type?(s=r,s.size=t):(o=r,o.size=t);return[Object.assign({},o),Object.assign({},s),Object.assign({},i)]}_parseResponse(e,o){return t(this,void 0,void 0,(function*(){console.log(`${f} parseResponse`);try{const{thumbUrl:t,largeUrl:i,downloadUrl:s}=e;t&&i&&(yield this._getImageInfoByUrl(t,o,"thumb"),yield this._getImageInfoByUrl(i,o,"large"));if(S.isSimpleCos()&&!S.isPrivateNetWork()&&(yield this._getImageInfoArray(s,o),null==o?void 0:o.uploadIP)){const e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,o,i){return t(this,void 0,void 0,(function*(){try{const t=S.addAuthToUrl(e),{width:s=0,height:r=0}=yield S.probeImageWidthHeight(t);o.width=s,o.height=r,"thumb"===i?(o.smallImageUrl=e,o.smallImageWidth=s,o.smallImageHeight=r):(o.largeImageUrl=e,o.largeImageWidth=s,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${i} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:M});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:i}=e.payload;return i=o?this._processMiniAppImageFile(i):this._processWebImageFile(i),i}catch(e){throw console.warn(`${f} _processImage error:`,e),e}}_processMiniAppImageFile(e){r(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const 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;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper,i=S.extractFileFromInput(e);if(!i)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return i}_getDownloadIP(e,o){return t(this,void 0,void 0,(function*(){const i=`${f} getDownloadIP domainName: ${e}`;try{const s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=o,s="im_cos_msg.get_final_ip",r={str_domain:e},n=t.generateProtocolData({servcmd:s,data:r}),a=`${n.head.seq}${s}`;return yield i.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!s||!s.str_final_ip)return;console.log(`${i} ok. downloadIP:${s}`);const r=o.location.split("/");r[0]=s.str_final_ip,o.location=r.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,o){return t(this,void 0,void 0,(function*(){const i=`${f}._getImageInfoArray`;try{const s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=o,s="im_cos_msg.get_imageinfo",r={str_image_url:e},n=t.generateProtocolData({servcmd:s,data:r}),a=`${n.head.seq}${s}`;return yield i.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return o.imageInfoArray=this._processImageInfoResponse(s),console.log(`${i} ok`),o}catch(e){throw o.imageInfoArray=void 0,console.warn(`${i} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.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){const{utils:t,helper:o}=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)),A.indexOf(i.toLowerCase())<0)throw new o.ChatError({code:b})}_checkImageSize(e){const{utils:t,helper:o}=this._core;let i=0;if(i=(t.IN_MINI_APP,e.size),0===i)throw new o.ChatError({code:F});if(i>=O)throw new o.ChatError({message:`File size exceeds limit: ${c(O)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const R=2108,$=2401,z="2.5.0",x="1.18.0",W=104857600;function j(e,t){const o=e.split("."),i=t.split("."),s=Math.max(o.length,i.length);for(;o.length<s;)o.push("0");for(;i.length<s;)i.push("0");for(let e=0;e<s;e++){const t=parseInt(o[e]),s=parseInt(i[e]);if(t>s)return 1;if(t<s)return-1}return 0}class q{constructor(e){this.type=g,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:S.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:o,Url:i,FileName:s,FileSize:r,UUID:n}=t;return new q({downloadFlag:o,url:i,fileName:s,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:i,downloadFlag:s,fileUrl:r,fileName:n,fileSize:a}=o;return{MsgType:this.type,MsgContent:{Download_Flag:s,Url:S.removeAuthToUrl(r),FileName:n,FileSize:a,UUID:i}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(S.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${n(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 V=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:i,InnerEvent:s,message:r}=e;i.registerApi({apiName:"createFileMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,q),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,o,i,s,r;try{const s=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${f} createFileMessage options:`,e),this._checkVersion();const r=this._processFile(e.payload.file);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.createMessage(Object.assign(Object.assign({},e),{from:n})),l={uuid:S.generateUUID(r),file:r},d=new q(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${f} createFileMessage success fileMessage:`,a),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===r||r.call(s,e).end(),console.error(`${f} createFileMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const o=e.getElements()[0],i=yield this._performFileUpload(o,e,t),s=S.addAuthToUrl(null==i?void 0:i.location);return o.updateFileUrl(s),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:$});if(e.size>W)throw new o({message:`File size exceeds limit: ${c(W)}`});if(0===e.size)throw new o({code:R})}_performFileUpload(e,o,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:v,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r}=yield P.uploadToCOS(s);return r}))}_processFile(e){var t,o;const{IN_BROWSER:i,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:l}=null===(o=this._core)||void 0===o?void 0:o.helper;if(i||a){const t=S.extractFileFromInput(e);if(!t)throw new l({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(r||n){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return s?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:o,IN_MINI_APP:i,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(i){if(!(s||r||n))throw new a({message:"Unsupported mini app environment"});const e=o.getSystemInfoSync().SDKVersion;if(s&&j(e,z)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${z} or higher`})}if(r&&j(e,x)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${x} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const L=2108,k=2352,B=["mp4","quicktime","mov"],H=104857600;class K{constructor(e){this.type=m,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:S.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:S.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:S.addAuthToUrl(e.thumbUrl),snapshotUrl:S.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:o,VideoFormat:i,VideoSecond:s,VideoSize:r,VideoDownloadFlag:n,VideoUUID:a,ThumbUUID:l,ThumbFormat:d,ThumbWidth:c,SnapshotWidth:h,ThumbHeight:u,SnapshotHeight:p,ThumbSize:g,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:_,SnapshotUrl:v}=t;return new K({videoUrl:o,videoFormat:i,videoSecond:s,videoSize:r,videoDownloadFlag:n,videoUUID:a,thumbUUID:l,thumbFormat:d,thumbWidth:c,snapshotWidth:h,thumbHeight:u,snapshotHeight:p,thumbSize:g,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:_,snapshotUrl:v})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:o,snapshotHeight:i}=e;S.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),S.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),S.isEmpty(i)||(this.content.thumbHeight=this.content.snapshotHeight=Number(i))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{remoteVideoUrl:i,videoFormat:s,videoSecond:r,videoSize:n,videoDownloadFlag:a,videoUUID:l,thumbUUID:d,thumbFormat:c,thumbWidth:h,snapshotWidth:u,thumbHeight:p,snapshotHeight:g,thumbSize:m,snapshotSize:f,thumbDownloadFlag:_,thumbUrl:v,snapshotUrl:I}=o;return{MsgType:this.type,MsgContent:{VideoUrl:S.removeAuthToUrl(i),VideoFormat:s,VideoSecond:r,VideoSize:n,VideoDownloadFlag:a,VideoUUID:l,ThumbUUID:d,ThumbFormat:c,ThumbWidth:h,SnapshotWidth:u,ThumbHeight:p,SnapshotHeight:g,ThumbSize:m,SnapshotSize:f,ThumbDownloadFlag:_,ThumbUrl:S.removeAuthToUrl(v),SnapshotUrl:S.removeAuthToUrl(I)}}}}var Y=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:i,InnerEvent:s,message:r}=e;i.registerApi({apiName:"createVideoMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,K),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,o,i,s,r;try{const s=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${f} createVideoMessage options:`,e);const r=this._processVideo(e);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.createMessage(Object.assign(Object.assign({},e),{from:n})),l={videoFormat:r.videoFile.type,videoSecond:d(r.videoFile.second,0),videoSize:r.videoFile.size,remoteVideoUrl:"",videoUrl:r.videoFile.url,videoUUID:S.generateUUID(r.videoFile),thumbUUID:S.generateUUID(r.videoFile,"jpg"),thumbWidth:r.width||200,thumbHeight:r.height||200,thumbUrl:r.thumbUrl,thumbSize:r.thumbSize,thumbFormat:"jpg"},c=new K(l);return a.setElement(c),this._messageOptionsMap.set(a.clientSequence,e),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===r||r.call(s,e).end(),console.error(`${f} createVideoMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadVideo message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(o);const i=yield this._performVideoUpload(t,e,o),{location:s,snapshotInfo:r}=i,n=S.addAuthToUrl(s);return t.updateVideoUrl(n),S.isEmpty(r)||t.updateSnapshotInfo(r),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>H)throw new o({message:`File size exceeds limit: ${c(H)}`});if(0===e.videoFile.size)throw new o({code:L});if(-1===B.indexOf(e.videoFile.type))throw new o({code:k})}_performVideoUpload(e,o,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:I,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r,uploadOptions:n}=yield P.uploadToCOS(s);return{snapshotInfo:yield this._getSnapshotInfoByUrl(n.requestSnapshotUrl),location:r.location}}))}_processVideo(e){var t,o;try{const{ChatError:i}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:s,IN_BROWSER:r}=null===(o=this._core)||void 0===o?void 0:o.utils;let{file:n}=e.payload,a={};if(s&&(a=this._processMiniVideoFile(n),n.name=a.name,n.url=a.url),r){const e=S.extractFileFromInput(n);if(!e)throw new i({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});n=e,a=this._processWebVideoFile(n)}return n.videoFile=a,n.thumbUrl="",n.thumbSize=0,n}catch(e){throw console.warn(`${f} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,o;const{IN_ALIPAY_MINI_APP:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:s}=null===(o=this._core)||void 0===o?void 0:o.helper;if(i)throw new s({message:"VideoUnsupportedInAlipay"});if(r(e))throw new s({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:o=1,duration:i=0,type:s}=e,r=s.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:o,second:i,type:r}}_getSnapshotInfoByUrl(e){return t(this,void 0,void 0,(function*(){try{console.log(`${f} _getSnapshotInfoByUrl url:`,e);const o={version:1,platform:S.getPlatform(),cover_name:l(n(99999)),snapshot_url:e},i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const t="im_cos_msg.video_cover",{helper:i,channel:s}=o,r=i.generateCosSpecifiedData({servcmd:t,data:e}),n=`${r.head.seq}${t}`;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(o,this._core),{download_url:s}=i||{};if(console.log(`${f} _getSnapshotInfoByUrl OK snapshotUrl:`,s),S.isEmpty(s))return{};const r=S.addAuthToUrl(s),{width:a=0,height:d=0}=yield S.probeImageWidthHeight(r);return{snapshotUrl:r,snapshotWidth:a,snapshotHeight:d}}catch(e){throw console.error(`${f} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class G{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:S.addAuthToUrl(e.url),remoteAudioUrl:S.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:o,Download_Flag:i,Second:s,Size:r,UUID:n}=t;return new G({url:o,downloadFlag:i,second:s,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:i,downloadFlag:s,remoteAudioUrl:r,size:n,second:a}=o;return{MsgType:this.type,MsgContent:{Url:S.removeAuthToUrl(r),Download_Flag:s,Second:a,Size:n,UUID:i}}}}const J=2108,Q=2300,X=20971520;var Z=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:i,InnerEvent:s,message:r}=e;i.registerApi({apiName:"createAudioMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,G),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,o,i,s,r;try{const s=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${f} createAudioMessage options:`,e);let{file:r}=e.payload;r=this._processAudioFile(e.payload.file),e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.createMessage(Object.assign(Object.assign({},e),{from:n})),l={second:Math.floor((r.duration||r.second)/1e3),size:r.fileSize||r.size||1,url:r.tempFilePath||r.uri||r.url,uuid:S.generateUUID(r)},d=new G(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===r||r.call(s,e).end(),console.error(`${f} createAudioMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const o=e.getElements()[0],i=yield this._performAudioUpload(o,e,t),s=S.addAuthToUrl(null==i?void 0:i.location);return o.updateAudioUrl(s),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:Q});if(e.size>X)throw new o({message:`File size exceeds limit: ${c(X)}`});if(0===e.size)throw new o({code:J})}_performAudioUpload(e,o,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:y,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r}=yield P.uploadToCOS(s);return r}))}_processAudioFile(e){var t;const{IN_MINI_APP:o,IN_BROWSER:i}=null===(t=this._core)||void 0===t?void 0:t.utils;return o?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){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const ee={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}},te={createImageMessage:ee,createAudioMessage:ee,createVideoMessage:ee,createFileMessage:ee},oe={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},ie={[u]:D,[g]:V,[m]:Y,[p]:Z};return new class{constructor(){this.name="RichMediaMessage"}install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:o,MSG_IMAGE:i,MSG_VIDEO:s}}}=e;D.init(e),V.init(e),Y.init(e),Z.init(e),P.init(e),S.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,o,i,s].includes(e[0].type)}),e.helper.registerValidateConfig({auth:oe,params:te})}sendMessage(e,o){return t(this,void 0,void 0,(function*(){var t,i,s;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(s=null===(i=null===(t=this._core)||void 0===t?void 0:t.message)||void 0===i?void 0:i.messageSender)||void 0===s?void 0:s.sendMessage(e,o)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return t(this,void 0,void 0,(function*(){var t,o;if(!0!==e._relayFlag)try{const t=ie[e.type];if(t){const o=this._core.ssoLog.createSSOLogData({method:"upload"});o.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),o.end()}}catch(i){throw e.status=U.FAIL,i instanceof Error&&(i.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,i).end(),i}}))}}}));
@@ -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,e,n,t){return new(n||(n=Promise))((function(s,a){function o(i){try{g(t.next(i))}catch(i){a(i)}}function r(i){try{g(t.throw(i))}catch(i){a(i)}}function g(i){var e;i.done?s(i.value):(e=i.value,e instanceof n?e:new n((function(i){i(e)}))).then(o,r)}g((t=t.apply(i,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const 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=>{if(i.type===o){const{cloudCustomData:e="",payload:{data:n=""}={}}=i,t=e.match(/"type":"tsignaling"/),s=n.match(/inviteID/),a=n.match(/actionType/);return t||s&&a}return!1}))}function p(i){const{data:e}=i.payload;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||i>53)throw new Error("Number of digits must be between 0 and 53");if(i<=30)return Math.floor(Math.random()*(1<<i));const e=i-30;return Math.floor(Math.random()*(1<<e))*(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,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){const e=`${d}.isInvitationValid`,{inviteID:n,groupID:t,inviter:s}=i,a=s===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(n))return!1;const{inviteeList:o}=this._onlineSignalingMap.get(n);if(console.log(`${e} inviteID:${n} inviteeList:${o} groupID:${t}`),t){if(a)return o.length>0;const i=this._core.common.getCurrentUserID();return o.includes(i)}return!0}updateSignaling(i){const e=`${d}.updateSignaling`,{inviteID:n,inviter:t,inviteeList:s,groupID:a}=i;if(console.log(`${e} inviteID:${n} inviter:${t} groupID:${a}`),a&&this.hasSignaling(n)){const i=s[0],{inviteeList:t}=this._onlineSignalingMap.get(n);t.includes(i)&&(t.splice(t.indexOf(i),1),console.log(`${e} remove ${i}. localInviteeList.length:${t.length}`)),0===t.length&&this.removeSignaling(n)}else this.removeSignaling(n)}setSignalingListenStatus(i){this._isSignalingListening=i}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var i,e;this._reset(),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var E=new class{init(i){this._core=i}createInviteSignaling(i){const e=this._generateInviteID(),n=this._createInviteSignalingData(Object.assign(Object.assign({},i),{inviteID:e})),{groupID:t,inviteeList:s}=n,a=t||s[0];return{signaling:this._createSignaling(n,a),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createAcceptSignaling(i){const e=this._createAcceptSignalingData(i),{groupID:n,inviter:t}=e,s=n||t;return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createCancelSignaling(i){const e=this._createCancelSignalingData(i),{groupID:n,inviteeList:t}=e,s=n||t[0];return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createRejectSignaling(i){const e=this._createRejectSignalingData(i),{groupID:n,inviter:t}=e,s=n||t;return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(i)}}createTimeoutSignaling(i){const{isInviter:e=!1}=i,n=this._createTimeoutSignalingData(i),{groupID:t,inviteeList:s,inviter:a}=n,o=t||(e?s[0]:a);return{signaling:this._createSignaling(n,o),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(n)}}_createSignalingExtensionOptions(i){var e,n;const{data:t="",onlineUserOnly:s,inviteID:a="",offlinePushInfo:o,actionType:r}=i,g=(null===(n=null===(e=D.getSignaling(a))||void 0===e?void 0:e.signaling)||void 0===n?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:s||g,offlinePushInfo:o,messageControlInfo:this._createMessageControlInfo(t,r)}}_createMessageControlInfo(i,e){const n=e===a&&!!i.match(/excludeTimeoutSignalingFromHistoryMessage/),t=!!i.match(/excludeFromHistoryMessage/)||!!i.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:n||t,excludedFromLastMessage:n||t}}_createInviteSignalingData(i){const n=`${d}._createInviteSignalingData`,{userID:t,timeout:s=0,groupID:a="",inviteeList:o=[]}=i,r=this._core.common.getCurrentUserID(),g=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:e,inviter:r,inviteeList:a?o:[t],timeout:s});return console.log(`${n} signalingData:`,g),g}_createAcceptSignalingData(i){const e=`${d}._createAcceptSignalingData`,{inviteID:n}=i,s=this._core.common.getCurrentUserID(),{inviter:a,groupID:o}=D.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:t,groupID:o,inviter:a,inviteeList:[s]});return console.log(`${e} signalingData:`,r),r}_createCancelSignalingData(i){const e=`${d}._createCancelSignalingData`,{inviteID:t}=i,s=this._core.common.getCurrentUserID(),{inviteeList:a,groupID:o}=D.getSignaling(t),r=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:n,groupID:o,inviter:s,inviteeList:a});return console.log(`${e} signalingData:`,r),r}_createRejectSignalingData(i){const e=`${d}._createRejectSignalingData`,{inviteID:n}=i,t=this._core.common.getCurrentUserID(),{inviter:a,groupID:o}=D.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:s,groupID:o,inviter:a,inviteeList:[t]});return console.log(`${e} signalingData:`,r),r}_createTimeoutSignalingData(i){const e=`${d}._createTimeoutSignalingData`,{isInviter:n=!1,inviteID:t}=i,{inviteeList:s,inviter:o}=D.getSignaling(t),r=this._core.common.getCurrentUserID(),g=Object.assign(Object.assign({},this._generateBaseSignalData(i)),{actionType:a,inviter:o,inviteeList:n?s:[r]});return console.log(`${e} signalingData:`,g),g}_createSignaling(i,e){var n,t,s;const{groupID:a=""}=i,o={to:e,conversationType:a?g:r,priority:"High",payload:{data:JSON.stringify(i)}};return null===(s=null===(t=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===t?void 0:t.messageFactory)||void 0===s?void 0:s.createCustomMessage(o)}_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){const{data:e="",inviteID:n="",groupID:t=""}=i;return{businessID:1,timeout:0,data:e,inviteID:n,groupID:t}}};var O=new class{constructor(){this._isProcessingSignaling=!1}init(i){this._core=i,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 i;console.log(`${d}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:n,signalingData:t,signalingExtensionOptions:s}=E.createInviteSignaling(e),a=yield this._sendSignaling(n,s);if(0===(null==a?void 0:a.code)){const{inviteID:e,timeout:s}=t;return D.saveSignaling(e,Object.assign(Object.assign({},t),{signaling:n})),s>0&&(null===(i=this._core)||void 0===i||i.helper.taskScheduler.addOnceTask({id:`${_}-${e}`,intervalMs:1e3*(s+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},a),{inviteID:e})}return a}catch(i){throw console.error(`${d}.invite error:${i}`),i}}))}accept(e){return i(this,void 0,void 0,(function*(){console.log(`${d}.accept params:${JSON.stringify(e)}`);try{const{inviteID:i}=e;this._validateBeforeAccept(i),this._isProcessingSignaling=!0;const{signaling:n,signalingData:t,signalingExtensionOptions:s}=E.createAcceptSignaling(e),a=yield this._sendSignaling(n,s);return 0===(null==a?void 0:a.code)?(D.updateSignaling(t),Object.assign(Object.assign({},a),{inviteID:i})):a}catch(i){throw console.error(`${d}.accept error:${i}`),i}finally{this._isProcessingSignaling=!1}}))}cancel(e){return i(this,void 0,void 0,(function*(){console.log(`${d}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:i}=e;this._validateBeforeCancel(i),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:t}=E.createCancelSignaling(e),s=yield this._sendSignaling(n,t);return 0===(null==s?void 0:s.code)?(D.removeSignaling(i),Object.assign(Object.assign({},s),{inviteID:i})):s}catch(i){throw console.error(`${d}.cancel error:${i}`),i}finally{this._isProcessingSignaling=!1}}))}reject(e){return i(this,void 0,void 0,(function*(){console.log(`${d}.reject params:${JSON.stringify(e)}`);try{const{inviteID:i}=e;this._validateBeforeReject(i),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:t}=E.createRejectSignaling(e),s=yield this._sendSignaling(n,t);return 0===(null==s?void 0:s.code)?(D.removeSignaling(i),Object.assign(Object.assign({},s),{inviteID:i})):s}catch(i){throw console.error(`${d}.reject error:${i}`),i}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return i(this,void 0,void 0,(function*(){var i,n;console.log(`${d}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:t,data:s}=e;let a="";try{this._validateBeforeModifyInvitation(t);const e=D.getSignaling(t),{signaling:o}=e,r=function(i,e){var n={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&e.indexOf(t)<0&&(n[t]=i[t]);if(null!=i&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(t=Object.getOwnPropertySymbols(i);s<t.length;s++)e.indexOf(t[s])<0&&Object.prototype.propertyIsEnumerable.call(i,t[s])&&(n[t[s]]=i[t[s]])}return n}(e,["signaling"]);a=o.payload.data,r.data=s,o.payload.data=JSON.stringify(r);const g=yield null===(n=null===(i=this._core)||void 0===i?void 0:i.message.messageAction)||void 0===n?void 0:n.modifyMessage(o);return D.hasSignaling(t)&&D.saveSignaling(t,Object.assign(Object.assign({},r),{signaling:o})),g}catch(i){if(a){const{signaling:i}=D.getSignaling(t);i.payload.data=a}throw i}}))}getSignalingInfo(i){if(0===S([i]).length)return;const n=p(i),t={businessID:n.businessID||1,inviteID:n.inviteID,groupID:n.groupID||"",inviter:n.inviter||"",inviteeList:n.inviteeList||[],data:n.data||"",actionType:n.actionType||e,timeout:n.timeout||0};return console.log(`${d} getSignalingInfo `,t),t}addSignalingListener(i,e,n){var t,s;i===(null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&D.setSignalingListenStatus(!0),null===(s=this._core)||void 0===s||s.notificationCenter.subscribeOuterEvent(i,e,n)}removeSignalingListener(i,e,n){var t,s;i===(null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED)&&D.setSignalingListenStatus(!1),null===(s=this._core)||void 0===s||s.notificationCenter.unSubscribeOuterEvent(i,e,n)}handleInvitationExpiryTimer(i){const e=D.getOnlineSignalingMap(),n=this._core.common.getCurrentUserID();if(!e.has(i))return;const t=e.get(i).inviter===n;this._sendTimeoutNotice({inviteID:i,isInviter:t})}_sendSignaling(e,n){return i(this,void 0,void 0,(function*(){var i,t,s;return null===(s=null===(t=null===(i=this._core)||void 0===i?void 0:i.message)||void 0===t?void 0:t.messageSender)||void 0===s?void 0:s.sendMessage(e,n)}))}_sendTimeoutNotice(e){return i(this,void 0,void 0,(function*(){var i,n,t;console.log(`${d}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:s,inviteID:a}=e,{signaling:o,signalingData:r,signalingExtensionOptions:g}=E.createTimeoutSignaling(e),l=yield this._sendSignaling(o,g);if(0===(null==l?void 0:l.code)){const{data:e,groupID:g,inviteeList:l,inviter:c}=r;null===(i=this._core)||void 0===i||i.notificationCenter.emitOuterEvent(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:g,inviteID:a,inviteeList:l,inviter:c,isSelfTimeout:!0,message:o}}),s?D.removeSignaling(a):D.updateSignaling(r)}}))}_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){const e=l,{userID:n}=i,t=this._core.common.getCurrentUserID();if(n===t)throw new this._core.helper.ChatError({functionName:e,message:`cannot invite yourself, currentUserId:${t}, inviteeId:${n}`})}_validateBeforeAccept(i){const e=c;this._validateInviteId(e,i),this._validateProcessStatus(e);const n=this._core.common.getCurrentUserID(),{inviteeList:t}=D.getSignaling(i);if(!t.includes(n)){const t=`userID:${n} not in inviteeList. inviteID:${i}`;throw new this._core.helper.ChatError({functionName:e,message:t})}}_validateBeforeCancel(i){const e=v;this._validateInviteId(e,i),this._validateProcessStatus(e);const n=this._core.common.getCurrentUserID(),{inviter:t}=D.getSignaling(i);if(t!==n){const i=`unmatched inviter:${t} and my userID:${n}`;throw new this._core.helper.ChatError({functionName:e,message:i})}}_validateBeforeReject(i){const e=u;this._validateInviteId(e,i),this._validateProcessStatus(e);const n=this._core.common.getCurrentUserID(),{inviteeList:t}=D.getSignaling(i);if(!t.includes(n)){const t=`userID:${n} not in inviteeList. inviteID:${i}`;throw new this._core.helper.ChatError({functionName:e,message:t})}}_validateBeforeModifyInvitation(i){const e=h;this._validateInviteId(e,i)}_dispose(){var i,e;this._reset(),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}};var 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,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=>{const e=p(i);if(e){const n=this._actionProcessor.get(e.actionType);null==n||n(e,i)}}))}_handleMessageReceived(i){if(!D.getSignalingListenStatus())return;const e=S(i.data);0!==e.length&&this.handleActionSignaling(e)}_handleMessageModified(i){if(!D.getSignalingListenStatus())return;const e=S(i.data);e.length>0&&e.forEach((i=>{const e=p(i);e&&this._onInvitationModified(e,i)}))}_onNewInvitationReceived(i,e){var n,t;const s=`${d}._onNewInvitationReceived`,{inviteID:a,inviteeList:o,groupID:r}=i,g=this._core.common.getCurrentUserID();console.log(`${s} signalingData:${JSON.stringify(i)}}`);if(r&&!o.includes(g))return;let{timeout:l}=i;const c=Date.now()/1e3-e.time;l>0&&c>0&&l>c&&(l-=c);const v=D.getSignaling(a);v!==i&&(v||D.saveSignaling(a,Object.assign(Object.assign({},i),{signaling:e})),l>0&&(null===(n=this._core)||void 0===n||n.helper.taskScheduler.addOnceTask({id:`${_}-${a}`,intervalMs:1e3*l,callback:O.handleInvitationExpiryTimer.bind(O,a)})),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{inviteeList:o})}))}_onInviteeRejected(i){var e;const n=`${d}._onInviteeRejected`,{inviteID:t,inviter:s,groupID:a,inviteeList:o}=i,r=D.hasSignaling(t);console.log(`${n} inviteID:${t} hasInviteID:${r} inviter:${s} groupID:${a}`),r&&(D.updateSignaling(i),this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:o[0]})}))}_onInviteeAccepted(i){var e;const n=`${d}._onInviteeAccepted`,{inviteID:t,inviter:s,groupID:a,inviteeList:o}=i,r=D.hasSignaling(t);console.log(`${n} inviteID:${t} hasInviteID:${r} inviter:${s} groupID:${a}`),r&&(D.updateSignaling(i),this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{invitee:o[0]})}))}_onInvitationCancelled(i){var e;const n=`${d}._onInvitationCancelled`,{inviteID:t,inviter:s,groupID:a}=i,o=D.hasSignaling(t);console.log(`${n} inviteID:${t} hasInviteID:${o} inviter:${s} groupID:${a}`),o&&(D.removeSignaling(t),this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(i)}))}_onInvitationTimeout(i){var e;const n=`${d}._onInvitationTimeout`,{inviteID:t,inviteeList:s}=i,a=D.hasSignaling(t);console.log(`${n} inviteID:${t} hasInviteID:${a} data:${i.data}`),a&&(D.updateSignaling(i),this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(i)),{inviteeList:s,isSelfTimeout:!1})}))}_onInvitationModified(i,e){var n;const t=`${d}._onInvitationModified`,{inviteID:s,data:a}=i,o=D.hasSignaling(s);console.log(`${t} inviteID:${s} data:${a}`),o&&(D.saveSignaling(s,Object.assign(Object.assign({},i),{signaling:e})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:s,data:a}}))}_emitEvent(i){var e;null===(e=this._core)||void 0===e||e.notificationCenter.emitOuterEvent(i.name,i)}_generateBaseEmitData(i){const{inviteID:e,inviter:n,groupID:t,data:s}=i;return{inviteID:e,inviter:n,groupID:t,data:s||""}}_dispose(){var i,e,n;null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var y=new class{constructor(){this._offlineSignalingMap=new Map}init(i){this._core=i;const{notificationCenter:e,helper:n,constants:{InnerEvent:t,WORKFLOW_STEP:s,WORKFLOW_NAME:a}}=i;e.subscribeInnerEvent(t.DESTROY,this._dispose,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),n.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_LOGIN,s.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(i){const{result:{unreadMessageMap:e}={}}=i||{};if(!(0!==(null==e?void 0:e.size)&&D.getSignalingListenStatus()))return;const n=S([...e.values()]);if(0!==n.length&&(n.forEach((i=>{this._handleC2CActionType(i)})),this._offlineSignalingMap.size>0)){const i=this._sortOfflineSignalingByTime();b.handleActionSignaling(i)}}_handleC2CActionType(i){const n=p(i);if(!n)return;const{actionType:t}=n;t===e?this._saveValidOfflineInvite(n,i):this._removeOfflineInvite(n)}_saveValidOfflineInvite(i,e){const{inviteID:n,inviteeList:t=[],timeout:s=0}=i,a=this._core.common.getCurrentUserID();if(!t.includes(a))return;const o=Date.now()/1e3-e.time;s>0&&o>s&&0!==s||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},i),{signalingList:[e]}))}_removeOfflineInvite(i){const{inviteID:e=""}=i;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let i=[];return this._offlineSignalingMap.forEach((e=>{i=[...i,...e.signalingList]})),i.sort(((i,e)=>i.time-e.time))}_dispose(){var i,e;this._reset(),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const $={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};