UNPKG

@tencentcloud/lite-chat

Version:

Tencent Cloud Chat SDK for Web/Mini Program/uni-app/React Native/Donut

2 lines (1 loc) 43.5 kB
!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={}));var w=new class{init(e){this._core=e}addAuthToUrl(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")}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){let o=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let o=32;o>0;--o)t+=e[Math.floor(62*Math.random())];return t}()}`;if(t)return`${o}.${t}`;const i=e.name||e.value||e.url||e.tempFilePath,s=i&&i.slice(i.lastIndexOf(".")+1);return s&&(o=`${o}.${s}`),o}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 S=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=!w.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}=w.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=w.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=w.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 w.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:w.getPlatform(),uint32_sdkappid:w.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=w.getFileUploadProxy();let o=e;return t&&(o=e.replace(/^https:\/\/[^/]+/,t)),o}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const P=2108,F=2251,b=2252,M=["jpg","jpeg","gif","png","bmp","image","webp"],A=20971520,O={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class T{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=w.addAuthToUrl(e.imageUrl||e.url||""),this.url=w.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=w.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function C(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 N{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 N({imageFormat:o,imageInfoArray:r,uuid:s})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:i,IN_BROWSER:s}=w.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 T(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=O[e.toUpperCase()]||O.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],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"}}}convertToBackendFormat(){const{uuid:e,imageFormat:t,imageInfoArray:o}=this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(o),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:w.removeAuthToUrl(e.imageUrl)})))}}var E=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("createImageMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,N),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:O.UNKNOWN,uuid:w.generateUUID(a),file:a,imageInfoArray:[]},d=new N(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.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 S.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=w.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 C({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(w.isSimpleCos()&&!w.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=w.addAuthToUrl(e),{width:s=0,height:r=0}=yield w.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:F});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=w.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)),M.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:P});if(i>=A)throw new o.ChatError({message:`File size exceeds limit: ${c(A)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const D=2108,R=2401,$="2.5.0",z="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 x{constructor(e){this.type=g,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:w.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 x({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"}}}convertToBackendFormat(){const{uuid:e,downloadFlag:t,fileUrl:o,fileName:i,fileSize:s}=this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:w.removeAuthToUrl(o),FileName:i,FileSize:s,UUID:e}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(w.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("createFileMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,x),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:w.generateUUID(r),file:r},d=new x(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=w.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:R});if(e.size>W)throw new o({message:`File size exceeds limit: ${c(W)}`});if(0===e.size)throw new o({code:D})}_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 S.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=w.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,$)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${$} or higher`})}if(r&&j(e,z)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${z} 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,q=2352,k=["mp4","quicktime","mov"],B=104857600;class H{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:w.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:w.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:w.addAuthToUrl(e.thumbUrl),snapshotUrl:w.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 H({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;w.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),w.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),w.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"}}}convertToBackendFormat(){const{remoteVideoUrl:e,videoFormat:t,videoSecond:o,videoSize:i,videoDownloadFlag:s,videoUUID:r,thumbUUID:n,thumbFormat:a,thumbWidth:l,snapshotWidth:d,thumbHeight:c,snapshotHeight:h,thumbSize:u,snapshotSize:p,thumbDownloadFlag:g,thumbUrl:m,snapshotUrl:f}=this.content;return{MsgType:this.type,MsgContent:{VideoUrl:w.removeAuthToUrl(e),VideoFormat:t,VideoSecond:o,VideoSize:i,VideoDownloadFlag:s,VideoUUID:r,ThumbUUID:n,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:c,SnapshotHeight:h,ThumbSize:u,SnapshotSize:p,ThumbDownloadFlag:g,ThumbUrl:w.removeAuthToUrl(m),SnapshotUrl:w.removeAuthToUrl(f)}}}}var K=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("createVideoMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,H),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:w.generateUUID(r.videoFile),thumbUUID:w.generateUUID(r.videoFile,"jpg"),thumbWidth:r.width||200,thumbHeight:r.height||200,thumbUrl:r.thumbUrl,thumbSize:r.thumbSize,thumbFormat:"jpg"},c=new H(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=w.addAuthToUrl(s);return t.updateVideoUrl(n),w.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>B)throw new o({message:`File size exceeds limit: ${c(B)}`});if(0===e.videoFile.size)throw new o({code:L});if(-1===k.indexOf(e.videoFile.type))throw new o({code:q})}_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 S.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)),r){const e=w.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:w.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),w.isEmpty(s))return{};const r=w.addAuthToUrl(s),{width:a=0,height:d=0}=yield w.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 Y{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:w.addAuthToUrl(e.url),remoteAudioUrl:w.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 Y({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"}}}convertToBackendFormat(){const{uuid:e,downloadFlag:t,remoteAudioUrl:o,size:i,second:s}=this.content;return{MsgType:this.type,MsgContent:{Url:w.removeAuthToUrl(o),Download_Flag:t,Second:s,Size:i,UUID:e}}}}const J=2108,Q=2300,G=20971520;var X=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("createAudioMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,Y),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,uuid:w.generateUUID(r)},d=new Y(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=w.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>G)throw new o({message:`File size exceeds limit: ${c(G)}`});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 S.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 Z={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}},ee={createImageMessage:Z,createAudioMessage:Z,createVideoMessage:Z,createFileMessage:Z},te={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},oe={[u]:E,[g]:V,[m]:K,[p]:X};return new class{install(e){this._core=e,E.init(e),V.init(e),K.init(e),X.init(e),S.init(e),w.init(e),e.helper.registerApi("sendMessage",this),e.helper.registerValidateConfig({auth:te,params:ee})}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=oe[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.messageStore.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,i).end(),i}}))}}}));