@tencentcloud/lite-chat 1.6.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/basic.es.js +1 -1
- package/basic.js +1 -1
- package/package.json +1 -1
- package/plugins/conversation.es.js +1 -1
- package/plugins/conversation.js +1 -1
- package/plugins/message-enhancer.es.js +1 -1
- package/plugins/message-enhancer.js +1 -1
- package/plugins/rich-media-message.es.js +1 -1
- package/plugins/rich-media-message.js +1 -1
- package/professional.es.js +1 -1
- package/professional.js +1 -1
- package/standard.es.js +1 -1
- package/standard.js +1 -1
|
@@ -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 g(e,t){var i={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(i[o[r]]=e[o[r]]);return i}function l(e,a,n,l){return new(n=n||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function o(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(r,o)}s((l=l.apply(e,a||[])).next())})}var z=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(m,g){return l(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:i="",method:r="PUT",url:o,qs:s,headers:a={},resources:n,dataType:l="text",uploadByIP:h,uploadIP:d}=m,u=o;if(s){let e=this._queryString(s);e&&(u+=(u.includes("?")?"&":"?")+e)}let p=new XMLHttpRequest;p.open(r.toUpperCase(),u,!0),p.responseType=l;var c=Object.assign({},a);if(h&&d&&(c.host=d),!t(c))for(let e in c)c.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,c[e]);return p.onload=()=>{var e=this._getResponseBody(p,i,h&&d),e=this._buildResponse(p,e);if(200===p.status)g(null,e);else{if(d&&!u.includes(d))return m.url=this._domainName2IP(u,d),m.uploadByIP=!0,this.request(m,g);g({code:p.status,message:JSON.stringify(p.responseText)},e)}},p.onerror=()=>{var e=this._getResponseBody(p,i,h&&d),e=this._buildResponse(p,e),t={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};g(t,e)},m.onProgress&&p.upload&&(p.upload.onprogress=e=>{var{total:e,loaded:t}=e,i=Math.min(Math.floor(100*t/e),100);m.onProgress({total:e,loaded:t,percent:i/100})}),p.send(n),p})}_buildResponse(e,t){let i={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),i[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:i,data:t}}_getResponseBody(e,t,i){return 200===e.status&&t?{location:t,uploadIP:i}:{response:e.responseText,uploadIP:i}}_queryString(i,r="&",o="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(i)?"":t(i)?Object.keys(i).map(e=>{let t=encodeURIComponent(e)+o;return Array.isArray(i[e])?i[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(i[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let x=["unknown","image","video","audio","log"];var r,e,W=new class{init(e){this._core=e}request(i,r){let e,{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:s,IN_UNI_IOS_APP:a}=null==(e=this._core)?void 0:e.utils,{resources:n="",headers:l={},url:h,downloadUrl:d=""}=i,u=h,p=null;var c=d?d.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(c){var c=decodeURIComponent(c[3]),c=c.includes("?")?c.split("?")[0]:c||"",c={key:i.fileKey||c,success_action_status:200,"Content-Type":""},m={};if(a){let[e,t]=h.split("?sign=");t&&(u=e+"?sign="+encodeURIComponent(t),m.sign=decodeURIComponent(t),m.signature=decodeURIComponent(t))}let t={url:u,header:l,name:"file",filePath:n,formData:Object.assign(Object.assign({},c),m),timeout:i.timeout||3e5};if(s){let e=g(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:i.fileType?x[i.fileType]:"image"})}return(p=o.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:d,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:d,callback:r})}}))).onProgressUpdate&&p.onProgressUpdate(e=>{i.onProgress&&i.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),p}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:i}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var o=+t.statusCode;200==o?i(null,{statusCode:o,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):i({code:o,message:JSON.stringify(t.data)},{statusCode:o,headers:r,data:void 0})}};function s(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function a(e){e=e||99999999;return Math.round(Math.random()*e)}function o(e,t=!0,i=!0){var r=Date.now();return t?i?r-e+" ms":Math.round((r-e)/1e3)+" s":i?r-e:Math.round((r-e)/1e3)}function n(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function h(e,t){return Math.round(Number(e)*10**t)/10**t}function d(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function u(e){return e<=1048576?h(e/1024,1)+"KB/s":h(e/1048576,1)+"MB/s"}let p="TIMImageElem",c="TIMSoundElem",m="TIMFileElem",f="TIMVideoFileElem",_="RichMediaMessagePlugin",v=["rich.my-imcloud.com","imrich.qcloud.com"],j=((e=r=r||{}).UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/});var I=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(i){{var[i,r]=i.split("?");if(!r)return i;let t=r.split("&").reduce((e,t)=>{var[t,i]=t.split("=");return t&&"authKey"!==t&&(e[t]=i||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?i+"?"+e:i}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(j).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return s(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(i){return l(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(i):e?this._probeImageDimensionsMiniApp(i):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=v;var i=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==i)try{JSON.parse(i).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=v}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let i,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(i=this._core)?void 0:i.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var i=this.getFileDownloadProxy(),r=this.getAuthKey(),o=this.getFileDNList(),e=(i&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,i):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,i))),r&&-1===t.indexOf("authKey=")&&function(e,t){let i=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){i=!0;break}}return i}(t,o));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:i,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:i,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,i=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{i.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:i}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===i}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,i=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),i()},t.onerror=()=>{e({width:0,height:0}),i()},t.src=r})}},y=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t=(this._core=e).utils["IN_MINI_APP"];this.httpRequest=t?W:z,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(h){return l(this,void 0,void 0,function*(){let r=_+" uploadToCOS",{ssoLog:o,utils:{safeStringify:e}}=this._core,s=h["file"];this.uploadFileType=h.uploadFileType,o.debug("uploadToCOS",r+" options:"+e(h));try{let e=Date.now(),t=yield this._createCosOptions(h),i=yield this._uploadFile(t);this._handleUploadError(i,h);var a=this._createUploadResult(s,i),n=Date.now()-e,l=`size:${d(s.size)} time:${n}ms speed:`+u(1e3*s.size/n);return o.debug("uploadToCOS",r+` ok. name:${s.name} `+l),{uploadOptions:t,response:a}}catch(e){throw console.warn(r+" failed, error:",e),e}})}_handleUploadError(e,t){var i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(403===e.statusCode)throw o(Date.now(),!1),t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new i({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:o(Date.now(),!1),uploadSpeed:u(1e3*e.size/o(Date.now(),!1))}}_createCosOptions(p){return l(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:i}=this._prepareUploadParams(p),r=this._isC2CConversation(p.message.conversationID)?1:2;try{var o=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:i,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:s,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:h,fileKey:d}=o,u=!I.isPrivateNetWork()&&o.uploadIP;return{url:this._getRawOrUploadProxyUrl(s),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:h,fileKey:d,uploadIP:u||"",onProgress:e=>this._handleUploadProgress(e,p)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){var{ssoLog:t,utils:{safeStringify:i}}=this._core,t=(t.debug("_prepareUploadParams"," prepareUploadParams:"+i(e)),e)["file"],{IN_MINI_APP:i,IN_RN_APP:r}=I.getPlatformFlags(),i=i||r,r=i&&e.message.type!==m,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+a(999999)+e;return{fileName:n(r?t.name:e),resources:i?t.url:t,uploadMethod:i?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(n){return l(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:i}}=this._core,r=I.isSimpleCos(),o=this._prepareCosRequestData(n),s=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(o,s,a){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,i=e.generateCosSpecifiedData({servcmd:o,data:s}),r=i.head.seq+o;return yield t.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(s,o,this._core);this.fetchCosTryCount=0;var a=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+i(a)),a||{}}catch(e){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(n);throw this.fetchCosTryCount=0,e}})}_processResponse(e){var t;let i=I.isSimpleCos(),l=i?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(i){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:i,uint32_exist_flag:r,str_download_url:o,str_upload_url:s,str_snapshot_url:a,str_file_key:n}=l;return{uploadIP:e,preSig:t,fileID:i,existFlag:r,downloadUrl:o,uploadUrl:s,requestSnapshotUrl:a,fileKey:n}}let{upload_url:r,download_url:o,snapshot_url:s,thumb_url:a,large_url:n,file_key:h}=l;return{uploadUrl:r,downloadUrl:o,requestSnapshotUrl:s,thumbUrl:a,largeUrl:n,fileKey:h}}_prepareCosRequestData(e){return I.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:I.getPlatform(),uint32_sdkappid:I.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(o){return l(this,void 0,void 0,function*(){return new Promise((i,r)=>{this.httpRequest.request(o,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(o).then(i).catch(r)):(this.uploadFileTryCount=0,e?r(e):i(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,i;try{var r=null==(t=e.error)?void 0:t.Code,o=null==(i=e.error)?void 0:i.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,i=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(i){let e=Date.now(),t=Date.parse(i);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=I.getFileUploadProxy();let i=e;return i=t?e.replace(/^https:\/\/[^/]+/,t):i}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let q=["jpg","jpeg","gif","png","bmp","image","webp"],U=20971520,w={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class V{constructor(e,t){this.instanceID=a(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=I.addAuthToUrl(e.imageUrl||e.url||""),this.url=I.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=I.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function P(t){var{originUrl:t,originWidth:i,originHeight:r,min:o=198}=t,i=parseInt(i)||0,r=parseInt(r)||0,s={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)s.url=t,s.width=i,s.height=r;else{r<=i?(s.width=Math.ceil(i*o/r),s.height=o):(s.width=o,s.height=Math.ceil(r*o/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";s.url=198===o?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?g(s,["url"]):s}class S{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=p;var{uuid:e,file:t,imageFormat:i,imageInfoArray:r=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:i,uuid:e,imageInfoArray:[]},this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:i,ImageInfoArray:r,UUID:o}=t,s=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new S({imageFormat:i,imageInfoArray:s,uuid:o})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:i,IN_RN_APP:r,IN_BROWSER:o}=I.getPlatformFlags();return t=e&&((i||r)&&(t=e.url),o)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var i={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},i),r=new V(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,i;e.url&&""!==e.imageUrl&&([t,...i]=e.imageUrl.split("://"),i=i.join("://"),r.includes(t)||e.setImageUrl("https://"+i))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=w[e.toUpperCase()]||w.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var i,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)i=this.content.imageInfoArray[e],t[e].size&&(i.size=t[e].size),t[e].url&&i.setImageUrl(t[e].url),t[e].width&&(i.width=t[e].width),t[e].height&&(i.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,i=t[2];t[2]=t[1],t[1]=i;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],P({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var[e]=this.content.imageInfoArray,e=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(i),UUID:e}}}parseImageInfoArray(e){return e.map(e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:I.removeAuthToUrl(e.imageUrl)}))}}var F=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(p,S),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createImageMessage(e){var t,i,r;try{var o=null==(t=this._core.store.get("login"))?void 0:t.userId,s=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),a=this._processImage(e),n=(e.payload.file=a,{imageFormat:w.UNKNOWN,uuid:I.generateUUID(a),file:a,imageInfoArray:[]}),l=new S(n);return s.setElement(l),this._messageOptionsMap.set(s.clientSequence,e),s}catch(e){throw e}}upload(r){return l(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),i=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(i),r})}_performImageUpload(r,o,i){return l(this,void 0,void 0,function*(){var e=o["to"],{uploadOptions:e,response:t}=yield y.uploadToCOS({uploadFileType:1,file:i,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:i,height:r,smallImageUrl:o,smallImageWidth:s,smallImageHeight:a,largeImageUrl:n,largeImageWidth:l,largeImageHeight:h,imageInfoArray:d}=e,e=I.addAuthToUrl(e),u={size:t,url:e,width:i,height:r};return 0<(null==d?void 0:d.length)?this._processImageInfoArray(d,t):o&&n?[Object.assign({},u),{largeImageUrl:n,largeImageWidth:l,largeImageHeight:h},{smallImageUrl:o,smallImageWidth:s,smallImageHeight:a}]:[Object.assign({},u),this._generateThumbInfo(e,i,r,720),this._generateThumbInfo(e,i,r,198)]}_generateThumbInfo(e,t,i,r){return P({originUrl:e,originWidth:t,originHeight:i,min:r})}_processImageInfoArray(e,t){let i,r,o;for(var s of e)1===s.type?(r=s,r.size=t):2===s.type?(o=s,o.size=t):(i=s,i.size=t);return[Object.assign({},i),Object.assign({},o),Object.assign({},r)]}_parseResponse(r,o){return l(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:i}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,o,"thumb"),yield this._getImageInfoByUrl(t,o,"large")),I.isSimpleCos()&&!I.isPrivateNetWork()&&(yield this._getImageInfoArray(i,o),null!=o)&&o.uploadIP){let e=this._extractDomainFromUrl(i);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,o,s){return l(this,void 0,void 0,function*(){var t;try{let e=I.addAuthToUrl(r),{width:t=0,height:i=0}=yield I.probeImageWidthHeight(e);o.width=t,o.height=i,"thumb"===s?(o.smallImageUrl=r,o.smallImageWidth=t,o.smallImageHeight=i):(o.largeImageUrl=r,o.largeImageWidth=t,o.largeImageHeight=i)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${s} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var i=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return i?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){s(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=I.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,o){return l(this,void 0,void 0,function*(){var e=_+" getDownloadIP domainName: "+r;try{var t,i=yield function(a,n){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,i="im_cos_msg.get_final_ip",r={str_domain:a},o=e.generateProtocolData({servcmd:i,data:r}),s=o.head.seq+i;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);i&&i.str_final_ip&&(console.log(e+" ok. downloadIP:"+i),(t=o.location.split("/"))[0]=i.str_final_ip,o.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,i){return l(this,void 0,void 0,function*(){try{var e=yield function(a,n){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,i="im_cos_msg.get_imageinfo",r={str_image_url:a},o=e.generateProtocolData({servcmd:i,data:r}),s=o.head.seq+i;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return i.imageInfoArray=this._processImageInfoResponse(e),i}catch(e){throw i.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:i}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),q.indexOf(r.toLowerCase())<0)throw new i.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:i}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new i.ChatError({code:2108});if(r>=U)throw new i.ChatError({message:"File size exceeds limit: "+d(U)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let b="2.5.0",M="1.18.0",i=104857600;function A(e,t){let r=e.split("."),o=t.split("."),s=Math.max(r.length,o.length);for(;r.length<s;)r.push("0");for(;o.length<s;)o.push("0");for(let i=0;i<s;i++){let e=parseInt(r[i]),t=parseInt(o[i]);if(e>t)return 1;if(e<t)return-1}return 0}let T=new class{init(e){this.core=e}};class O{constructor(e){this.type=m,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:I.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:i,FileSize:r,UUID:o}=e;return new O({downloadFlag:e,url:t,fileName:i,fileSize:r,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:i,fileName:r,fileSize:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:I.removeAuthToUrl(i),FileName:r,FileSize:o,UUID:e}}}_getFileInfo(e){var t=T.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=a(999999)+"."+t)),e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var C=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(m,O),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createFileMessage(e){var t,i,r;try{this._checkVersion();var o=this._processFile(e.payload.file),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={uuid:I.generateUUID(o),file:o},l=new O(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw e}}upload(i){return l(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(i.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),i.getElements()[0]),e=yield this._performFileUpload(t,i,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),i})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>i)throw new t({message:"File size exceeds limit: "+d(i)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,o,t){return l(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:255,file:t,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:i,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:o,IN_UNI_NATIVE_APP:s}=null==(e=this._core)?void 0:e.utils,a=(null==(a=this._core)?void 0:a.helper)["ChatError"];if(e||s){let e=I.extractFileFromInput(t);if(e)return e;throw new a({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||o){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return i?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:o}=null==(e=this._core)?void 0:e.utils,s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(e){if(!(i||r||o))throw new s({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(i&&A(e,b)<0)throw new s({message:`WXChooseMessageFile requires SDK version ${b} or higher`});if(r&&A(e,M)<0)throw new s({message:`QQChooseMessageFile requires SDK version ${M} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let B=["mp4","quicktime","mov"],N=104857600;class E{constructor(e){this.type=f,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:I.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:I.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:I.addAuthToUrl(e.thumbUrl),snapshotUrl:I.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:i,VideoSize:r,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:h,ThumbHeight:d,SnapshotHeight:u,ThumbSize:p,SnapshotSize:c,ThumbDownloadFlag:m,ThumbUrl:g,SnapshotUrl:f}=e;return new E({videoUrl:e,videoFormat:t,videoSecond:i,videoSize:r,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:h,thumbHeight:d,snapshotHeight:u,thumbSize:p,snapshotSize:c,thumbDownloadFlag:m,thumbUrl:g,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:i}=e;I.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),I.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),I.isEmpty(i)||(this.content.thumbHeight=this.content.snapshotHeight=Number(i))}validateBeforeSend(){var e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:i,videoSize:r,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:h,thumbHeight:d,snapshotHeight:u,thumbSize:p,snapshotSize:c,thumbDownloadFlag:m,thumbUrl:g,snapshotUrl:f}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:I.removeAuthToUrl(e),VideoFormat:t,VideoSecond:i,VideoSize:r,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:h,ThumbHeight:d,SnapshotHeight:u,ThumbSize:p,SnapshotSize:c,ThumbDownloadFlag:m,ThumbUrl:I.removeAuthToUrl(g),SnapshotUrl:I.removeAuthToUrl(f)}}}}var D=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(f,E),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createVideoMessage(e){var t,i,r;try{var o=this._processVideo(e),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={videoFormat:o.videoFile.type,videoSecond:h(o.videoFile.second,0),videoSize:o.videoFile.size,remoteVideoUrl:"",videoUrl:o.videoFile.url,videoUUID:I.generateUUID(o.videoFile),thumbUUID:I.generateUUID(o.videoFile,"jpg"),thumbWidth:o.width||200,thumbHeight:o.height||200,thumbUrl:o.thumbUrl,thumbSize:o.thumbSize,thumbFormat:"jpg"},l=new E(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw e}}upload(r){return l(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:i}=t,t=I.addAuthToUrl(t);return e.updateVideoUrl(t),I.isEmpty(i)||e.updateSnapshotInfo(i),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>N)throw new t({message:"File size exceeds limit: "+d(N)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===B.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(r,o,i){return l(this,void 0,void 0,function*(){var e=o["to"],{response:e,uploadOptions:t}=yield y.uploadToCOS({uploadFileType:2,file:i,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,o;try{var s=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:a,IN_BROWSER:n}=null==(o=this._core)?void 0:o.utils;let t=e.payload["file"],i={};if(a&&(i=this._processMiniVideoFile(t),t.name=i.name,t.url=i.url,t.type=i.type),n){let e=I.extractFileFromInput(t);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,i=this._processWebVideoFile(t)}return t.videoFile=i,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(_+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:i}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(s(e))throw new r({message:"FileUnsupportedInMiniApp"});let o=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return i&&(o=e.fileType||o),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:o}}_processWebVideoFile(e){var{name:t,size:i=1,duration:r=0,type:o}=e,o=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:i,second:r,type:o}}_getSnapshotInfoByUrl(s){return l(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",_+" _getSnapshotInfoByUrl url:"+s);var t,i,r,o=((yield function(s,a){return l(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:i}=a,r=t.generateCosSpecifiedData({servcmd:e,data:s}),o=r.head.seq+e;return yield i.sendPacket(r,{requestId:o})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:I.getPlatform(),cover_name:n(a(99999)),snapshot_url:s},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",_+" _getSnapshotInfoByUrl OK snapshotUrl:"+o),I.isEmpty(o))?{}:(t=I.addAuthToUrl(o),{width:i=0,height:r=0}=yield I.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:i,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class R{constructor(e){this.uploadProgress=0,this.type=c,this.content={downloadFlag:2,second:e.second,size:e.size,url:I.addAuthToUrl(e.url),remoteAudioUrl:I.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:i,Size:r,UUID:o}=e;return new R({url:e,downloadFlag:t,second:i,size:r,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:i,size:r,second:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:I.removeAuthToUrl(i),Download_Flag:t,Second:o,Size:r,UUID:e}}}}var L=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(c,R),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createAudioMessage(e){var t,i,r;try{var o=e.payload["file"],o=this._processAudioFile(e.payload.file),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={second:Math.floor((o.duration||o.second)/1e3),size:o.fileSize||o.size||1,url:o.tempFilePath||o.uri||o.url,uuid:I.generateUUID(o)},l=new R(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}upload(i){return l(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",_+" uploadAudio message:"+t(i)),this._messageOptionsMap.get(i.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),i.getElements()[0]),e=yield this._performAudioUpload(t,i,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),i})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+d(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,o,t){return l(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:3,file:t,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}}))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:i}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):i?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let t={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},k={createImageMessage:t,createAudioMessage:t,createVideoMessage:t,createFileMessage:t},H={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},K={TIMImageElem:F,TIMFileElem:C,TIMVideoFileElem:D,TIMSoundElem:L};return new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:i,MSG_IMAGE:r,MSG_VIDEO:o}}=(this._core=e)["constants"];T.init(e),F.init(e),C.init(e),D.init(e),L.init(e),y.init(e),I.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,i,r,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:H,params:k})}sendMessage(r,o){return l(this,void 0,void 0,function*(){var e,t,i;try{return yield this._upload(r),yield null==(i=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:i.sendMessage(r,o)}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"sendMessage",code:t})}})}_upload(i){return l(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(i)),!0!==i._relayFlag)try{let e=K[i.type];e&&(yield e.upload(i),t.info("_upload"," type:"+i.type))}catch(t){throw i.status=r.FAIL,t instanceof Error&&(t.data={message:i}),this._core.message.messageDataHandler.storeConversationMessage(i),t}})}}});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatRich-media-message"]=t()}(this,function(){function g(e,t){var i={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(i[o[r]]=e[o[r]]);return i}function l(e,a,n,l){return new(n=n||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function o(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(r,o)}s((l=l.apply(e,a||[])).next())})}var z=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(m,g){return l(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:i="",method:r="PUT",url:o,qs:s,headers:a={},resources:n,dataType:l="text",uploadByIP:h,uploadIP:d}=m,u=o;if(s){let e=this._queryString(s);e&&(u+=(u.includes("?")?"&":"?")+e)}let p=new XMLHttpRequest;p.open(r.toUpperCase(),u,!0),p.responseType=l;var c=Object.assign({},a);if(h&&d&&(c.host=d),!t(c))for(let e in c)c.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,c[e]);return p.onload=()=>{var e=this._getResponseBody(p,i,h&&d),e=this._buildResponse(p,e);if(200===p.status)g(null,e);else{if(d&&!u.includes(d))return m.url=this._domainName2IP(u,d),m.uploadByIP=!0,this.request(m,g);g({code:p.status,message:JSON.stringify(p.responseText)},e)}},p.onerror=()=>{var e=this._getResponseBody(p,i,h&&d),e=this._buildResponse(p,e),t={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};g(t,e)},m.onProgress&&p.upload&&(p.upload.onprogress=e=>{var{total:e,loaded:t}=e,i=Math.min(Math.floor(100*t/e),100);m.onProgress({total:e,loaded:t,percent:i/100})}),p.send(n),p})}_buildResponse(e,t){let i={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),i[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:i,data:t}}_getResponseBody(e,t,i){return 200===e.status&&t?{location:t,uploadIP:i}:{response:e.responseText,uploadIP:i}}_queryString(i,r="&",o="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(i)?"":t(i)?Object.keys(i).map(e=>{let t=encodeURIComponent(e)+o;return Array.isArray(i[e])?i[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(i[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let x=["unknown","image","video","audio","log"];var r,e,W=new class{init(e){this._core=e}request(i,r){let e,{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:s,IN_UNI_IOS_APP:a}=null==(e=this._core)?void 0:e.utils,{resources:n="",headers:l={},url:h,downloadUrl:d=""}=i,u=h,p=null;var c=d?d.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(c){var c=decodeURIComponent(c[3]),c=c.includes("?")?c.split("?")[0]:c||"",c={key:i.fileKey||c,success_action_status:200,"Content-Type":""},m={};if(a){let[e,t]=h.split("?sign=");t&&(u=e+"?sign="+encodeURIComponent(t),m.sign=decodeURIComponent(t),m.signature=decodeURIComponent(t))}let t={url:u,header:l,name:"file",filePath:n,formData:Object.assign(Object.assign({},c),m),timeout:i.timeout||3e5};if(s){let e=g(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:i.fileType?x[i.fileType]:"image"})}return(p=o.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:d,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:d,callback:r})}}))).onProgressUpdate&&p.onProgressUpdate(e=>{i.onProgress&&i.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),p}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:i}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var o=+t.statusCode;200==o?i(null,{statusCode:o,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):i({code:o,message:JSON.stringify(t.data)},{statusCode:o,headers:r,data:void 0})}};function s(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function a(e){e=e||99999999;return Math.round(Math.random()*e)}function o(e,t=!0,i=!0){var r=Date.now();return t?i?r-e+" ms":Math.round((r-e)/1e3)+" s":i?r-e:Math.round((r-e)/1e3)}function n(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function h(e,t){return Math.round(Number(e)*10**t)/10**t}function d(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function u(e){return e<=1048576?h(e/1024,1)+"KB/s":h(e/1048576,1)+"MB/s"}let p="TIMImageElem",c="TIMSoundElem",m="TIMFileElem",f="TIMVideoFileElem",_="RichMediaMessagePlugin",v=["rich.my-imcloud.com","imrich.qcloud.com"],j=((e=r=r||{}).UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/});var I=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(i){{var[i,r]=i.split("?");if(!r)return i;let t=r.split("&").reduce((e,t)=>{var[t,i]=t.split("=");return t&&"authKey"!==t&&(e[t]=i||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?i+"?"+e:i}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(j).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return s(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(i){return l(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(i):e?this._probeImageDimensionsMiniApp(i):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=v;var i=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==i)try{JSON.parse(i).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=v}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let i,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(i=this._core)?void 0:i.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var i=this.getFileDownloadProxy(),r=this.getAuthKey(),o=this.getFileDNList(),e=(i&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,i):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,i))),r&&-1===t.indexOf("authKey=")&&function(e,t){let i=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){i=!0;break}}return i}(t,o));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:i,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:i,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,i=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{i.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:i}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===i}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,i=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),i()},t.onerror=()=>{e({width:0,height:0}),i()},t.src=r})}},y=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t=(this._core=e).utils["IN_MINI_APP"];this.httpRequest=t?W:z,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(h){return l(this,void 0,void 0,function*(){let r=_+" uploadToCOS",{ssoLog:o,utils:{safeStringify:e}}=this._core,s=h["file"];this.uploadFileType=h.uploadFileType,o.debug("uploadToCOS",r+" options:"+e(h));try{let e=Date.now(),t=yield this._createCosOptions(h),i=yield this._uploadFile(t);this._handleUploadError(i,h);var a=this._createUploadResult(s,i),n=Date.now()-e,l=`size:${d(s.size)} time:${n}ms speed:`+u(1e3*s.size/n);return o.debug("uploadToCOS",r+` ok. name:${s.name} `+l),{uploadOptions:t,response:a}}catch(e){throw console.warn(r+" failed, error:",e),e}})}_handleUploadError(e,t){var i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(403===e.statusCode)throw o(Date.now(),!1),t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new i({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:o(Date.now(),!1),uploadSpeed:u(1e3*e.size/o(Date.now(),!1))}}_createCosOptions(p){return l(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:i}=this._prepareUploadParams(p),r=this._isC2CConversation(p.message.conversationID)?1:2;try{var o=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:i,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:s,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:h,fileKey:d}=o,u=!I.isPrivateNetWork()&&o.uploadIP;return{url:this._getRawOrUploadProxyUrl(s),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:a,requestSnapshotUrl:n,thumbUrl:l,largeUrl:h,fileKey:d,uploadIP:u||"",onProgress:e=>this._handleUploadProgress(e,p)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){var{ssoLog:t,utils:{safeStringify:i}}=this._core,t=(t.debug("_prepareUploadParams"," prepareUploadParams:"+i(e)),e)["file"],{IN_MINI_APP:i,IN_RN_APP:r}=I.getPlatformFlags(),i=i||r,r=i&&e.message.type!==m,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+a(999999)+e;return{fileName:n(r?t.name:e),resources:i?t.url:t,uploadMethod:i?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(n){return l(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:i}}=this._core,r=I.isSimpleCos(),o=this._prepareCosRequestData(n),s=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(o,s,a){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,i=e.generateCosSpecifiedData({servcmd:o,data:s}),r=i.head.seq+o;return yield t.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(s,o,this._core);this.fetchCosTryCount=0;var a=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+i(a)),a||{}}catch(e){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(n);throw this.fetchCosTryCount=0,e}})}_processResponse(e){var t;let i=I.isSimpleCos(),l=i?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(i){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:i,uint32_exist_flag:r,str_download_url:o,str_upload_url:s,str_snapshot_url:a,str_file_key:n}=l;return{uploadIP:e,preSig:t,fileID:i,existFlag:r,downloadUrl:o,uploadUrl:s,requestSnapshotUrl:a,fileKey:n}}let{upload_url:r,download_url:o,snapshot_url:s,thumb_url:a,large_url:n,file_key:h}=l;return{uploadUrl:r,downloadUrl:o,requestSnapshotUrl:s,thumbUrl:a,largeUrl:n,fileKey:h}}_prepareCosRequestData(e){return I.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:I.getPlatform(),uint32_sdkappid:I.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(o){return l(this,void 0,void 0,function*(){return new Promise((i,r)=>{this.httpRequest.request(o,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(o).then(i).catch(r)):(this.uploadFileTryCount=0,e?r(e):i(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,i;try{var r=null==(t=e.error)?void 0:t.Code,o=null==(i=e.error)?void 0:i.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,i=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(i){let e=Date.now(),t=Date.parse(i);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=I.getFileUploadProxy();let i=e;return i=t?e.replace(/^https:\/\/[^/]+/,t):i}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let q=["jpg","jpeg","gif","png","bmp","image","webp"],U=20971520,w={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class V{constructor(e,t){this.instanceID=a(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=I.addAuthToUrl(e.imageUrl||e.url||""),this.url=I.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=I.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function P(t){var{originUrl:t,originWidth:i,originHeight:r,min:o=198}=t,i=parseInt(i)||0,r=parseInt(r)||0,s={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)s.url=t,s.width=i,s.height=r;else{r<=i?(s.width=Math.ceil(i*o/r),s.height=o):(s.width=o,s.height=Math.ceil(r*o/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";s.url=198===o?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?g(s,["url"]):s}class S{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=p;var{uuid:e,file:t,imageFormat:i,imageInfoArray:r=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:i,uuid:e,imageInfoArray:[]},this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:i,ImageInfoArray:r,UUID:o}=t,s=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new S({imageFormat:i,imageInfoArray:s,uuid:o})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:i,IN_RN_APP:r,IN_BROWSER:o}=I.getPlatformFlags();return t=e&&((i||r)&&(t=e.url),o)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var i={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},i),r=new V(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,i;e.url&&""!==e.imageUrl&&([t,...i]=e.imageUrl.split("://"),i=i.join("://"),r.includes(t)||e.setImageUrl("https://"+i))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=w[e.toUpperCase()]||w.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var i,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)i=this.content.imageInfoArray[e],t[e].size&&(i.size=t[e].size),t[e].url&&i.setImageUrl(t[e].url),t[e].width&&(i.width=t[e].width),t[e].height&&(i.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,i=t[2];t[2]=t[1],t[1]=i;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],P({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var[e]=this.content.imageInfoArray,e=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(i),UUID:e}}}parseImageInfoArray(e){return e.map(e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:I.removeAuthToUrl(e.imageUrl)}))}}var F=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(p,S),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createImageMessage(e){var t,i,r;try{var o=null==(t=this._core.store.get("login"))?void 0:t.userId,s=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),a=this._processImage(e),n=(e.payload.file=a,{imageFormat:w.UNKNOWN,uuid:I.generateUUID(a),file:a,imageInfoArray:[]}),l=new S(n);return s.setElement(l),this._messageOptionsMap.set(s.clientSequence,e),s}catch(e){throw e}}upload(r){return l(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),i=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(i),r})}_performImageUpload(r,o,i){return l(this,void 0,void 0,function*(){var e=o["to"],{uploadOptions:e,response:t}=yield y.uploadToCOS({uploadFileType:1,file:i,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:i,height:r,smallImageUrl:o,smallImageWidth:s,smallImageHeight:a,largeImageUrl:n,largeImageWidth:l,largeImageHeight:h,imageInfoArray:d}=e,e=I.addAuthToUrl(e),u={size:t,url:e,width:i,height:r};return 0<(null==d?void 0:d.length)?this._processImageInfoArray(d,t):o&&n?[Object.assign({},u),{largeImageUrl:n,largeImageWidth:l,largeImageHeight:h},{smallImageUrl:o,smallImageWidth:s,smallImageHeight:a}]:[Object.assign({},u),this._generateThumbInfo(e,i,r,720),this._generateThumbInfo(e,i,r,198)]}_generateThumbInfo(e,t,i,r){return P({originUrl:e,originWidth:t,originHeight:i,min:r})}_processImageInfoArray(e,t){let i,r,o;for(var s of e)1===s.type?(r=s,r.size=t):2===s.type?(o=s,o.size=t):(i=s,i.size=t);return[Object.assign({},i),Object.assign({},o),Object.assign({},r)]}_parseResponse(r,o){return l(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:i}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,o,"thumb"),yield this._getImageInfoByUrl(t,o,"large")),I.isSimpleCos()&&!I.isPrivateNetWork()&&(yield this._getImageInfoArray(i,o),null!=o)&&o.uploadIP){let e=this._extractDomainFromUrl(i);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,o,s){return l(this,void 0,void 0,function*(){var t;try{let e=I.addAuthToUrl(r),{width:t=0,height:i=0}=yield I.probeImageWidthHeight(e);o.width=t,o.height=i,"thumb"===s?(o.smallImageUrl=r,o.smallImageWidth=t,o.smallImageHeight=i):(o.largeImageUrl=r,o.largeImageWidth=t,o.largeImageHeight=i)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${s} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var i=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return i?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){s(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=I.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,o){return l(this,void 0,void 0,function*(){var e=_+" getDownloadIP domainName: "+r;try{var t,i=yield function(a,n){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,i="im_cos_msg.get_final_ip",r={str_domain:a},o=e.generateProtocolData({servcmd:i,data:r}),s=o.head.seq+i;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);i&&i.str_final_ip&&(console.log(e+" ok. downloadIP:"+i),(t=o.location.split("/"))[0]=i.str_final_ip,o.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,i){return l(this,void 0,void 0,function*(){try{var e=yield function(a,n){return l(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=n,i="im_cos_msg.get_imageinfo",r={str_image_url:a},o=e.generateProtocolData({servcmd:i,data:r}),s=o.head.seq+i;return yield t.sendPacket(o,{requestId:s})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return i.imageInfoArray=this._processImageInfoResponse(e),i}catch(e){throw i.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:i}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),q.indexOf(r.toLowerCase())<0)throw new i.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:i}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new i.ChatError({code:2108});if(r>=U)throw new i.ChatError({message:"File size exceeds limit: "+d(U)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let b="2.5.0",M="1.18.0",i=104857600;function A(e,t){let r=e.split("."),o=t.split("."),s=Math.max(r.length,o.length);for(;r.length<s;)r.push("0");for(;o.length<s;)o.push("0");for(let i=0;i<s;i++){let e=parseInt(r[i]),t=parseInt(o[i]);if(e>t)return 1;if(e<t)return-1}return 0}let T=new class{init(e){this.core=e}};class O{constructor(e){this.type=m,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:I.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:i,FileSize:r,UUID:o}=e;return new O({downloadFlag:e,url:t,fileName:i,fileSize:r,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:i,fileName:r,fileSize:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:I.removeAuthToUrl(i),FileName:r,FileSize:o,UUID:e}}}_getFileInfo(e){var t=T.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=a(999999)+"."+t)),e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var C=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(m,O),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createFileMessage(e){var t,i,r;try{this._checkVersion();var o=this._processFile(e.payload.file),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={uuid:I.generateUUID(o),file:o},l=new O(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw e}}upload(i){return l(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(i.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),i.getElements()[0]),e=yield this._performFileUpload(t,i,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),i})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>i)throw new t({message:"File size exceeds limit: "+d(i)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,o,t){return l(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:255,file:t,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:i,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:o,IN_UNI_NATIVE_APP:s}=null==(e=this._core)?void 0:e.utils,a=(null==(a=this._core)?void 0:a.helper)["ChatError"];if(e||s){let e=I.extractFileFromInput(t);if(e)return e;throw new a({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||o){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return i?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:o}=null==(e=this._core)?void 0:e.utils,s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(e){if(!(i||r||o))throw new s({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(i&&A(e,b)<0)throw new s({message:`WXChooseMessageFile requires SDK version ${b} or higher`});if(r&&A(e,M)<0)throw new s({message:`QQChooseMessageFile requires SDK version ${M} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let B=["mp4","quicktime","mov"],N=104857600;class E{constructor(e){this.type=f,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:I.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:I.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:I.addAuthToUrl(e.thumbUrl),snapshotUrl:I.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:i,VideoSize:r,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:h,ThumbHeight:d,SnapshotHeight:u,ThumbSize:p,SnapshotSize:c,ThumbDownloadFlag:m,ThumbUrl:g,SnapshotUrl:f}=e;return new E({videoUrl:e,videoFormat:t,videoSecond:i,videoSize:r,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:h,thumbHeight:d,snapshotHeight:u,thumbSize:p,snapshotSize:c,thumbDownloadFlag:m,thumbUrl:g,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:i}=e;I.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),I.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),I.isEmpty(i)||(this.content.thumbHeight=this.content.snapshotHeight=Number(i))}validateBeforeSend(){var e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:i,videoSize:r,videoDownloadFlag:o,videoUUID:s,thumbUUID:a,thumbFormat:n,thumbWidth:l,snapshotWidth:h,thumbHeight:d,snapshotHeight:u,thumbSize:p,snapshotSize:c,thumbDownloadFlag:m,thumbUrl:g,snapshotUrl:f}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:I.removeAuthToUrl(e),VideoFormat:t,VideoSecond:i,VideoSize:r,VideoDownloadFlag:o,VideoUUID:s,ThumbUUID:a,ThumbFormat:n,ThumbWidth:l,SnapshotWidth:h,ThumbHeight:d,SnapshotHeight:u,ThumbSize:p,SnapshotSize:c,ThumbDownloadFlag:m,ThumbUrl:I.removeAuthToUrl(g),SnapshotUrl:I.removeAuthToUrl(f)}}}}var D=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(f,E),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createVideoMessage(e){var t,i,r;try{var o=this._processVideo(e),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={videoFormat:o.videoFile.type,videoSecond:h(o.videoFile.second,0),videoSize:o.videoFile.size,remoteVideoUrl:"",videoUrl:o.videoFile.url,videoUUID:I.generateUUID(o.videoFile),thumbUUID:I.generateUUID(o.videoFile,"jpg"),thumbWidth:o.width||200,thumbHeight:o.height||200,thumbUrl:o.thumbUrl,thumbSize:o.thumbSize,thumbFormat:"jpg"},l=new E(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw e}}upload(r){return l(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:i}=t,t=I.addAuthToUrl(t);return e.updateVideoUrl(t),I.isEmpty(i)||e.updateSnapshotInfo(i),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>N)throw new t({message:"File size exceeds limit: "+d(N)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===B.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(r,o,i){return l(this,void 0,void 0,function*(){var e=o["to"],{response:e,uploadOptions:t}=yield y.uploadToCOS({uploadFileType:2,file:i,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,o;try{var s=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:a,IN_BROWSER:n}=null==(o=this._core)?void 0:o.utils;let t=e.payload["file"],i={};if(a&&(i=this._processMiniVideoFile(t),t.name=i.name,t.url=i.url,t.type=i.type),n){let e=I.extractFileFromInput(t);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,i=this._processWebVideoFile(t)}return t.videoFile=i,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(_+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:i}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(s(e))throw new r({message:"FileUnsupportedInMiniApp"});let o=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return i&&(o=e.fileType||o),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:o}}_processWebVideoFile(e){var{name:t,size:i=1,duration:r=0,type:o}=e,o=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:i,second:r,type:o}}_getSnapshotInfoByUrl(s){return l(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",_+" _getSnapshotInfoByUrl url:"+s);var t,i,r,o=((yield function(s,a){return l(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:i}=a,r=t.generateCosSpecifiedData({servcmd:e,data:s}),o=r.head.seq+e;return yield i.sendPacket(r,{requestId:o})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:I.getPlatform(),cover_name:n(a(99999)),snapshot_url:s},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",_+" _getSnapshotInfoByUrl OK snapshotUrl:"+o),I.isEmpty(o))?{}:(t=I.addAuthToUrl(o),{width:i=0,height:r=0}=yield I.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:i,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class R{constructor(e){this.uploadProgress=0,this.type=c,this.content={downloadFlag:2,second:e.second,size:e.size,url:I.addAuthToUrl(e.url),remoteAudioUrl:I.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:i,Size:r,UUID:o}=e;return new R({url:e,downloadFlag:t,second:i,size:r,uuid:o})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:i,size:r,second:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:I.removeAuthToUrl(i),Download_Flag:t,Second:o,Size:r,UUID:e}}}}var L=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:i,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(c,R),e.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createAudioMessage(e){var t,i,r;try{var o=e.payload["file"],o=this._processAudioFile(e.payload.file),s=(e.payload.file=o,null==(t=this._core.store.get("login"))?void 0:t.userId),a=null==(r=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:s})),n={second:Math.floor((o.duration||o.second)/1e3),size:o.fileSize||o.size||1,url:o.tempFilePath||o.uri||o.url,uuid:I.generateUUID(o)},l=new R(n);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),a}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}upload(i){return l(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",_+" uploadAudio message:"+t(i)),this._messageOptionsMap.get(i.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),i.getElements()[0]),e=yield this._performAudioUpload(t,i,e),e=I.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),i})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+d(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,o,t){return l(this,void 0,void 0,function*(){var e=o["to"],e=(yield y.uploadToCOS({uploadFileType:3,file:t,to:e,message:o,onProgress:e=>{var t,i;r.updatePercent(e),null!=(i=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&i.call(t,e)}}))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:i}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):i?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let t={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},k={createImageMessage:t,createAudioMessage:t,createVideoMessage:t,createFileMessage:t},H={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},K={TIMImageElem:F,TIMFileElem:C,TIMVideoFileElem:D,TIMSoundElem:L};return new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:i,MSG_IMAGE:r,MSG_VIDEO:o}}=(this._core=e)["constants"];T.init(e),F.init(e),C.init(e),D.init(e),L.init(e),y.init(e),I.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,i,r,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:H,params:k})}sendMessage(r,o){return l(this,void 0,void 0,function*(){var e,t,i;try{return yield this._upload(r),yield null==(i=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:i.sendMessage(r,o)}catch(e){throw e}})}_upload(i){return l(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(i)),!0!==i._relayFlag)try{let e=K[i.type];e&&(yield e.upload(i),t.info("_upload"," type:"+i.type))}catch(t){throw i.status=r.FAIL,t instanceof Error&&(t.data={message:i}),this._core.message.messageDataHandler.storeConversationMessage(i),t}})}}});
|