@tencentcloud/lite-chat 1.1.0 → 1.1.1-beta.1

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/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "@tencentcloud/lite-chat",
3
- "version": "1.1.0",
3
+ "version": "1.1.1-beta.1",
4
4
  "description": "Tencent Cloud Chat SDK for Web/Mini Program/uni-app/React Native/Donut",
5
5
  "main": "index.js",
6
6
  "module": "index.es.js",
7
+ "types": "index.d.ts",
7
8
  "exports": {
8
9
  ".": {
9
10
  "import": "./index.es.js",
10
- "require": "./index.js"
11
+ "require": "./index.js",
12
+ "types": "./index.d.ts"
11
13
  },
12
14
  "./plugins/*": {
13
15
  "import": "./plugins/*.es.js",
14
- "require": "./plugins/*.js"
16
+ "require": "./plugins/*.js",
17
+ "types": "./plugins/*.d.ts"
15
18
  }
16
19
  },
17
20
  "keywords": ["chat", "real-time chat", "uni-app", "React Native", "Donut", "push", "messaging", "IM", "trtc"],
@@ -0,0 +1,8 @@
1
+ declare const conversationPlugin: {
2
+ [key: string]: any;
3
+ };
4
+
5
+ export default conversationPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/conversation' {
7
+ export default conversationPlugin;
8
+ }
@@ -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).liteChatConversation=t()}(this,(function(){"use strict";function e(e,t,s,n){return new(s||(s=Promise))((function(o,i){function a(e){try{l(n.next(e))}catch(e){i(e)}}function r(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(a,r)}l((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t="C2C",s="GROUP",n="TOPIC",o="@TIM#SYSTEM",i="AVChatRoom",a="Room",r="Live",l="TIMTextElem",u="TIMImageElem",d="TIMSoundElem",c="TIMFileElem",p="TIMFaceElem",g="TIMVideoFileElem",v="TIMLocationElem",h="TIMGroupTipElem",m="TIMGroupSystemNoticeElem",C="TIMCustomElem",_="TIMRelayElem",M="AcceptAndNotify",f="AcceptNotNotify",y="Discard",T="AcceptNotNotifyExceptAt";var I,L,S;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(I||(I={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(L||(L={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(S||(S={}));const E=e=>void 0===e,D=e=>"string"==typeof e,O=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===(e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()})(e),R=e=>O(e)||(e=>null!==e&&"object"==typeof e)(e),k=(e,t,s,n)=>{if(!R(e)||!R(t))return 0;let o=0;const i=Object.keys(t);let a;for(let r=0,l=i.length;r<l;r++)if(a=i[r],!(E(t[a])||s&&s.includes(a)))if(R(e[a])&&R(t[a]))o+=k(e[a],t[a],s,n);else{if(n&&n.includes(t[a]))continue;e[a]!==t[a]&&(e[a]=t[a],o+=1)}return o},P=(e,t)=>{if(E(t))return"";switch(e){case l:return t.text||"";case u:return"[Image]";case v:return"[Location]";case d:return"[Voice]";case g:return"[Video]";case c:return"[File]";case C:return"[Custom Messages]";case h:return"[Group Notification]";case m:return"[Group System Message]";case p:return"[Animated Sticker]";case _:return"[Chat Record]";default:return""}},G=e=>({lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:P(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null});function N(e){const t=[];if(!D(e))return t;const s=e.length;if(0===s)return t;for(let n=s-1;n>=0;n--)"1"===e[n]&&t.push(2**(s-n-1));return t}class b{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=G(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark="",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){E(this.userProfile)&&this.type===t?this.userProfile={}:E(this.groupProfile)&&this.type===s&&(this.groupProfile={}),this.subType&&this.type===s&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){const{nextUnreadCount:o,isFromGetConversations:a,isUnreadC2CMessage:r}=e;E(o)||(this.subType!==i?a&&this.type===s||a&&this.type===n||r&&this.type===t?this.unreadCount=o:this.unreadCount+=o:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=G(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{sequence:n,time:o}=e;return this.type===t&&n===this.lastMessage.lastSequence&&o===this.lastMessage.lastTime||this.type===s&&n===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}}var U=new class{constructor(){this._name="ConversationFactory",this._pagingStatus="",this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._pagingConvIDMap=new Map,this._convMap=new Map,this._convTotalUnreadCount=0}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n}=e;n.registerApi("getConversationList",this),n.registerApi("getConversationProfile",this),n.registerApi("setMessageRead",this),n.registerApi("getTotalUnreadMessageCount",this),n.registerApi("setConversationDraft",this),t.subscribeInnerEvent(s.RE_LOGIN,this._recoverConversations,this),t.subscribeInnerEvent(s.LOGIN,this.handleLoginSuccess,this),t.subscribeInnerEvent(s.NEW_MESSAGE,this._handleNewMessage,this),t.subscribeInnerEvent(s.MESSAGE_DELETED,this._handleMessageDeleted,this),t.subscribeInnerEvent(s.MESSAGE_REVOKED,this._handleMessageRevoked,this),t.subscribeInnerEvent(s.MESSAGE_MODIFIED,this._handleMessageModified,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),console.log(`${this._name}.install`)}handleLoginSuccess(){this.syncConvList()}_handleNewMessage(e){const{conversationOptionsList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:o=!0}=e;if(console.log(`${this._name}._handleNewMessage, conversationOptionsList length:`,t.length),0===t.length)return;this._updateLocalConvList({conversationOptionsList:t,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:o});t.filter((e=>this._isConvNeedShow(e.conversationID))).length>0&&this._onConversationListUpdate()}_handleMessageDeleted(e){var s,n,o,i;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const a=(null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageStore)||void 0===n?void 0:n.getLocalMessageList(e))||[];let r={};for(let e=(a.length||0)-1;e>=0;e--)if(!a[e].isDeleted){r=a[e];break}const l=this._convMap.get(e);if(!l)return;let u=!1;l.lastMessage.lastSequence===r.sequence&&l.lastMessage.lastTime===r.time||((null===(i=null===(o=this._core)||void 0===o?void 0:o.helper)||void 0===i?void 0:i.isEmpty(r))&&(r=void 0),l.updateLastMessage(r),u=!0),e.startsWith(t)&&this._updateUnreadCount(e),u&&(this._onConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. \n update conversationID:${e} with lastMessage:`,l.lastMessage))}_handleMessageRevoked(e){console.log(`${this._name}._handleMessageRevoked`,JSON.stringify(e));const{messageList:t=[],updateUnreadCount:s=!0}=e;if(0===t.length)return;let n=null,o=!1;t.forEach((e=>{n=this._convMap.get(e.conversationID),n&&(s&&n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(e.revoker),o=!0))})),o&&this._onConversationListUpdate()}_handleMessageModified(e){var t,s;console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:n,message:o}=e,i=this._convMap.get(n);if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(i))return;const{lastMessage:a}=i;a&&a.lastTime===o.time&&a.lastSequence===o.sequence&&a.version!==o.version&&(a.type=o.type,a.payload=o.payload,a.messageForShow=P(o.type,o.payload),a.cloudCustomData=o.cloudCustomData,a.version=o.version,this._onConversationListUpdate(),console.log(`${this._name} conversationID:${n} lastMessage updated`))}syncConvList(){return e(this,arguments,void 0,(function*(e=!0){yield this._pagingGetConvList(e),this._pagingStatus=I.RESOLVED,this._onConversationListUpdate()}))}_pagingGetConvList(t){return e(this,void 0,void 0,(function*(){try{this._pagingStatus=I.PENDING;const s=yield function(t,s){return e(this,void 0,void 0,(function*(){const{pagingTimeStamp:e,pagingStartIndex:n,pagingPinnedTimeStamp:o,pagingPinnedStartIndex:i}=t;try{const t="recentcontact.page_get",a=null==s?void 0:s.helper.generateProtocolData({servcmd:t,data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:null==s?void 0:s.store.get("login").userId,StartIndex:n,TimeStamp:e,TopStartIndex:i,TopTimeStamp:o}}),r=`${a.head.seq}${t}`;return yield s.channel.sendPacket(a,{requestId:r})}catch(e){throw console.warn(`ConversationService.pagingGetConvList error: ${e}`),e}}))}({pagingTimeStamp:t?this._pagingTimeStamp:0,pagingStartIndex:t?this._pagingStartIndex:0,pagingPinnedTimeStamp:t?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:t?this._pagingPinnedStartIndex:0},this._core);if(s){const{CompleteFlag:e,SessionItem:n=[],TimeStamp:o,StartIndex:i,TopTimeStamp:a,TopStartIndex:r}=s;if(n.length>0){const e=this._getConvOptions(n);this._pagingConvIDMap=new Map([...this._pagingConvIDMap,...e.map((e=>[e.conversationID,1]))]),this._updateLocalConvList({conversationOptionsList:e,isFromGetConversations:!0,updateUnreadCount:!0}),this._onConversationListUpdate()}this._pagingTimeStamp=o,this._pagingStartIndex=i,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=r,1!==e&&this._pagingGetConvList(t)}}catch(e){throw console.error(`${this._name}._pagingGetConvList fail:`,e),e}}))}_getConvOptions(e){const n=this._convertConvKey(e).filter((({type:e,userID:t})=>1===e&&!this._isNonExistentAccount(t)||2===e)),o=this._core.store.get("login").userId;return n.map((e=>{var n,i,a,r,l,u,d,c,p,g,v,h;if(E(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===L.C2C){const s={userID:e.userID,nick:e.nick,avatar:e.peerAvatar},g=null===(a=null===(i=null===(n=this._core)||void 0===n?void 0:n.user)||void 0===i?void 0:i.userProfile)||void 0===a?void 0:a.createProfile(e.userID,[s]);return{conversationID:`${t}${e.userID}`,type:t,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(r=e.lastMsg)||void 0===r?void 0:r.elements[0])?null===(l=e.lastMsg)||void 0===l?void 0:l.elements[0].type:null,payload:(null===(u=e.lastMsg)||void 0===u?void 0:u.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(d=e.lastMsg)||void 0===d?void 0:d.cloudCustomData)||"",isRevoked:e.lastMessageFlag===S.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:e.lastC2CMsgFromAccount===o&&e.time<=e.c2cPeerReadTime,revoker:(null===(p=null===(c=e.lastMsg)||void 0===c?void 0:c.revokerInfo)||void 0===p?void 0:p.revoker)||null},unreadCount:0,userProfile:g,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:N(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}return{conversationID:`${s}${e.groupID}`,type:s,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null===(g=e.lastMsg)||void 0===g?void 0:g.cloudCustomData)||"",isRevoked:e.lastMessageFlag===S.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(h=null===(v=e.lastMsg)||void 0===v?void 0:v.revokerInfo)||void 0===h?void 0:h.revoker)||null}),groupProfile:{groupID:e.groupID,name:e.groupNick,avatar:e.groupImage,type:e.groupType,nextMessageSeq:e.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(e),peerReadTime:0,isPinned:1===e.isPinned,version:0,customData:e.customMark||"",markList:N(e.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(e.messageRemindType),subType:e.groupType}}))}_convertConvKey(e){return e.map((e=>({type:e.Type,userID:e.To_Account,nick:e.C2cNick,peerAvatar:e.C2cImage,time:e.MsgTimeStamp,sequence:e.MsgSeq,lastC2CMsgFromAccount:e.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(e.LastMsg),lastMessageFlag:e.LastMsgFlags,c2cPeerReadTime:e.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount})))}_convertLastMsgKey(e){var t,s,n,o;if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(e))return null;let i="",a=null;return e.MsgBody&&(i=null===(n=e.MsgBody[0])||void 0===n?void 0:n.MsgType,a=this._parseContent(i,e.MsgBody[0])),{event:e.Event,elements:[{type:i,content:a,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(o=e.RevokerInfo)||void 0===o?void 0:o.revoker}}}_parseContent(e,t){var s;if(!t)return t;const n=this._core.message.messageFactory.getElementClass(e);return n?null===(s=n.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return(function(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}(e,["LayersOverLimit"])).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=M:1===e?t=y:2===e?t=f:3===e&&(t=T),t}_patchTypeAndPayload(e){const{event:t,elements:s=[]}=e.lastMsg||{};return E(t)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:h,payload:{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,n=t-s;return n>0?n:0}_updateLocalConvList(e){const{newConvList:t}=this._getTmpConvListMapping(e);this._convMap=new Map(this._sortConvList([...this._convMap])),this._core.store.set("conversation",{conversationMap:this._convMap}),console.log(`${this._name}._updateLocalConvList newConvList: ${t.length}`)}_getTmpConvListMapping(e){const{conversationOptionsList:n,isFromGetConversations:o,isInstantMessage:i,isUnreadC2CMessage:a=!1,updateUnreadCount:r}=e,l=[],u=null==n?void 0:n.length;for(let e=0;e<u;e++){const u=new b(n[e]),{conversationID:d,type:c}=u;if(!this._isNonExistentAccount(d))if(this._convMap.has(d)){const l=this._convMap.get(d);if(o){this._convMap.set(d,u),c===t?u.unreadCount=l.unreadCount:c===s&&(u.groupProfile=JSON.parse(JSON.stringify(l.groupProfile)));continue}this._mergeConversationInfo({conversationID:d,tmpConversation:u,lastMessage:n[e].lastMessage,isFromGetConversations:o,isInstantMessage:i}),this._patchLastMessage({conversationID:d,lastMessage:n[e].lastMessage,isInstantMessage:i}),!0===r&&(null==l||l.updateUnreadCount({nextUnreadCount:u.unreadCount,isFromGetConversations:o,isUnreadC2CMessage:a}))}else l.push(u),this._convMap.set(d,u)}return{newConvList:l}}_isNonExistentAccount(e){let s;return e.startsWith(t)&&(s=e.replace(t,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}_mergeConversationInfo(e){var t,s;const{conversationID:n,tmpConversation:o,lastMessage:i,isFromGetConversations:a,isInstantMessage:r}=e,l=this._convMap.get(n),u=["unreadCount","allowType","adminForbidType","payload"];!1===r&&u.push("lastMessage"),a&&u.push("isPinned"),E(r)&&i&&null===(null==l?void 0:l.lastMessage.payload)&&(l.lastMessage.payload=i.payload),(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(null==l?void 0:l.lastMessage.revoker))||(l.lastMessage.revoker=null);k(l,o,u,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{conversationID:t,lastMessage:n,isInstantMessage:o}=e,i=this._convMap.get(t);if(i&&n){const{payload:e,nameCard:t,nick:a,cloudCustomData:r=""}=n;o&&(e&&(i.lastMessage.payload=e),i.type===s&&(i.lastMessage.nameCard=t,i.lastMessage.nick=a)),i.lastMessage.cloudCustomData!==r&&(i.lastMessage.cloudCustomData=r)}}_sortConvList(e){const t=[],s=[],n=[],o=[];return e.forEach((e=>{var i,a,r,l;!0===e[1].isPinned?(null===(a=null===(i=this._core)||void 0===i?void 0:i.helper)||void 0===a?void 0:a.isEmpty(e[1].lastMessage.lastTime))?s.push(e):t.push(e):(null===(l=null===(r=this._core)||void 0===r?void 0:r.helper)||void 0===l?void 0:l.isEmpty(e[1].lastMessage.lastTime))?o.push(e):n.push(e)})),t.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(s).concat(n.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime))).concat(o)}_getLocalConvList(){return[...this._convMap.values()].filter((e=>this._isConvNeedShow(e.conversationID)))}_isConvNeedShow(e){const t=this._getLocalConversation(e);if(E(t))return!0;const o=t.type===n,i=t.type===s&&t.subType===a,l=t.type===s&&t.subType===r;return!(o||i||l)}_getLocalConversation(e){return this._convMap.get(e)}_updateUnreadCount(e,t=!0){var s,n;let o=!1;const i=this._getLocalConversation(e),a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageStore)||void 0===n?void 0:n.getLocalMessageList(e);if(!i)return o;const r=i.unreadCount,l=null==a?void 0:a.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;return r!==l&&(i.unreadCount=l,o=!0,console.log(`${this._name}._updateUnreadCount\n from ${r} to ${l}, conversationID:${e}`),!0===t&&this._onConversationListUpdate()),o}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_onConversationListUpdate(){var e;const t=this._getLocalConvList();this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.CONVERSATION_LIST_UPDATED,data:t}),this._onTotalUnreadCountUpdate()}_onTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._convTotalUnreadCount!==t&&(console.log(`${this._name}._onTotalUnreadCountUpdate from ${this._convTotalUnreadCount} to ${t}`),this._convTotalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}getConversationList(t){return e(this,void 0,void 0,(function*(){return{code:0,data:{conversationList:this._getConversationList(t),isSyncCompleted:this._isSyncCompleted()}}}))}_getConversationList(e){if(E(e))return this._getLocalConvList();if(O(e)){if(0===e.length)return[];return this._getLocalConvList().filter((t=>e.includes(t.conversationID)))}if((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s})(e)){const{type:t,markType:s,groupName:n,hasUnreadCount:o,hasGroupAtInfo:i}=e;return this._getLocalConvList().filter((e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,i)))}return[]}_isSyncCompleted(){return this._pagingStatus===I.RESOLVED}_filterType(e,n){return n!==t&&n!==s||e.type===n}_filterGroupName(e,t){return!D(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){return null===(s=t)||!("number"==typeof s&&!Number.isNaN(s-0)||"object"==typeof s&&s.constructor===Number)||(0===t?0===e.markList.length:e.markList.includes(t));var s}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_recoverConversations(){return e(this,void 0,void 0,(function*(){try{yield this.syncConvList(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.RECOVER_CONVERSATIONS_COMPLETED)}catch(e){console.debug(e)}}))}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}getConversationProfile(n){return e(this,void 0,void 0,(function*(){let e;return this._convMap.has(n)?e=this._convMap.get(n):(e=new b({conversationID:n}),(e=>D(e)&&e.slice(0,3)===t)(n)?(e.type=t,e.userProfile={userID:n.replace(t,"")}):(e.type=s,e.groupProfile={groupID:n.replace(s,"")}),this._convMap.set(n,e)),{code:0,data:{conversation:e}}}))}setMessageRead(t){return e(this,void 0,void 0,(function*(){console.log(`${this._name}.setMessageRead ok, ${JSON.stringify(t)}`)}))}setConversationDraft(t){return e(this,void 0,void 0,(function*(){return console.log(`${this._name}.setConversationDraft , ${JSON.stringify(t)}`),{code:0,data:{conversation:{}}}}))}getTotalUnreadMessageCount(){const e=this._getLocalConvList();let t=0;return e.forEach((e=>{e.type!==o&&(""!==e.messageRemindType&&e.messageRemindType!==M||(t+=e.unreadCount))})),t}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.RE_LOGIN,this._recoverConversations,this),e.unSubscribeInnerEvent(t.LOGIN,this.handleLoginSuccess,this),e.unSubscribeInnerEvent(t.NEW_MESSAGE,this._handleNewMessage,this),e.unSubscribeInnerEvent(t.MESSAGE_DELETED,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(t.MESSAGE_REVOKED,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(t.MESSAGE_MODIFIED,this._handleMessageModified,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const A={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0},F={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationID is invalid."}]};return{install:function(e){U.install(e),e.helper.registerValidateConfig({auth:A,params:F})},handleLoginSuccess:function(){U.handleLoginSuccess()}}}));
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).TencentCloudChatConversation=t()}(this,(function(){"use strict";function e(e,t,s,n){return new(s||(s=Promise))((function(o,i){function a(e){try{l(n.next(e))}catch(e){i(e)}}function r(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(a,r)}l((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t="C2C",s="GROUP",n="TOPIC",o="@TIM#SYSTEM",i="AVChatRoom",a="Room",r="Live",l="TIMTextElem",u="TIMImageElem",d="TIMSoundElem",c="TIMFileElem",p="TIMFaceElem",g="TIMVideoFileElem",v="TIMLocationElem",h="TIMGroupTipElem",m="TIMGroupSystemNoticeElem",C="TIMCustomElem",_="TIMRelayElem",M="AcceptAndNotify",f="AcceptNotNotify",y="Discard",T="AcceptNotNotifyExceptAt";var I,L,S;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(I||(I={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(L||(L={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(S||(S={}));const E=e=>void 0===e,D=e=>"string"==typeof e,O=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===(e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()})(e),R=e=>O(e)||(e=>null!==e&&"object"==typeof e)(e),k=(e,t,s,n)=>{if(!R(e)||!R(t))return 0;let o=0;const i=Object.keys(t);let a;for(let r=0,l=i.length;r<l;r++)if(a=i[r],!(E(t[a])||s&&s.includes(a)))if(R(e[a])&&R(t[a]))o+=k(e[a],t[a],s,n);else{if(n&&n.includes(t[a]))continue;e[a]!==t[a]&&(e[a]=t[a],o+=1)}return o},P=(e,t)=>{if(E(t))return"";switch(e){case l:return t.text||"";case u:return"[Image]";case v:return"[Location]";case d:return"[Voice]";case g:return"[Video]";case c:return"[File]";case C:return"[Custom Messages]";case h:return"[Group Notification]";case m:return"[Group System Message]";case p:return"[Animated Sticker]";case _:return"[Chat Record]";default:return""}},G=e=>({lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:P(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null});function N(e){const t=[];if(!D(e))return t;const s=e.length;if(0===s)return t;for(let n=s-1;n>=0;n--)"1"===e[n]&&t.push(2**(s-n-1));return t}class b{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=G(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark="",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){E(this.userProfile)&&this.type===t?this.userProfile={}:E(this.groupProfile)&&this.type===s&&(this.groupProfile={}),this.subType&&this.type===s&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){const{nextUnreadCount:o,isFromGetConversations:a,isUnreadC2CMessage:r}=e;E(o)||(this.subType!==i?a&&this.type===s||a&&this.type===n||r&&this.type===t?this.unreadCount=o:this.unreadCount+=o:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=G(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{sequence:n,time:o}=e;return this.type===t&&n===this.lastMessage.lastSequence&&o===this.lastMessage.lastTime||this.type===s&&n===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}}var U=new class{constructor(){this._name="ConversationFactory",this._pagingStatus="",this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._pagingConvIDMap=new Map,this._convMap=new Map,this._convTotalUnreadCount=0}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n}=e;n.registerApi("getConversationList",this),n.registerApi("getConversationProfile",this),n.registerApi("setMessageRead",this),n.registerApi("getTotalUnreadMessageCount",this),n.registerApi("setConversationDraft",this),t.subscribeInnerEvent(s.RE_LOGIN,this._recoverConversations,this),t.subscribeInnerEvent(s.LOGIN,this.handleLoginSuccess,this),t.subscribeInnerEvent(s.NEW_MESSAGE,this._handleNewMessage,this),t.subscribeInnerEvent(s.MESSAGE_DELETED,this._handleMessageDeleted,this),t.subscribeInnerEvent(s.MESSAGE_REVOKED,this._handleMessageRevoked,this),t.subscribeInnerEvent(s.MESSAGE_MODIFIED,this._handleMessageModified,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),console.log(`${this._name}.install`)}handleLoginSuccess(){this.syncConvList()}_handleNewMessage(e){const{conversationOptionsList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:o=!0}=e;if(console.log(`${this._name}._handleNewMessage, conversationOptionsList length:`,t.length),0===t.length)return;this._updateLocalConvList({conversationOptionsList:t,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:o});t.filter((e=>this._isConvNeedShow(e.conversationID))).length>0&&this._onConversationListUpdate()}_handleMessageDeleted(e){var s,n,o,i;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const a=(null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageStore)||void 0===n?void 0:n.getLocalMessageList(e))||[];let r={};for(let e=(a.length||0)-1;e>=0;e--)if(!a[e].isDeleted){r=a[e];break}const l=this._convMap.get(e);if(!l)return;let u=!1;l.lastMessage.lastSequence===r.sequence&&l.lastMessage.lastTime===r.time||((null===(i=null===(o=this._core)||void 0===o?void 0:o.helper)||void 0===i?void 0:i.isEmpty(r))&&(r=void 0),l.updateLastMessage(r),u=!0),e.startsWith(t)&&this._updateUnreadCount(e),u&&(this._onConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. \n update conversationID:${e} with lastMessage:`,l.lastMessage))}_handleMessageRevoked(e){console.log(`${this._name}._handleMessageRevoked`,JSON.stringify(e));const{messageList:t=[],updateUnreadCount:s=!0}=e;if(0===t.length)return;let n=null,o=!1;t.forEach((e=>{n=this._convMap.get(e.conversationID),n&&(s&&n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(e.revoker),o=!0))})),o&&this._onConversationListUpdate()}_handleMessageModified(e){var t,s;console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:n,message:o}=e,i=this._convMap.get(n);if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(i))return;const{lastMessage:a}=i;a&&a.lastTime===o.time&&a.lastSequence===o.sequence&&a.version!==o.version&&(a.type=o.type,a.payload=o.payload,a.messageForShow=P(o.type,o.payload),a.cloudCustomData=o.cloudCustomData,a.version=o.version,this._onConversationListUpdate(),console.log(`${this._name} conversationID:${n} lastMessage updated`))}syncConvList(){return e(this,arguments,void 0,(function*(e=!0){yield this._pagingGetConvList(e),this._pagingStatus=I.RESOLVED,this._onConversationListUpdate()}))}_pagingGetConvList(t){return e(this,void 0,void 0,(function*(){try{this._pagingStatus=I.PENDING;const s=yield function(t,s){return e(this,void 0,void 0,(function*(){const{pagingTimeStamp:e,pagingStartIndex:n,pagingPinnedTimeStamp:o,pagingPinnedStartIndex:i}=t;try{const t="recentcontact.page_get",a=null==s?void 0:s.helper.generateProtocolData({servcmd:t,data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:null==s?void 0:s.store.get("login").userId,StartIndex:n,TimeStamp:e,TopStartIndex:i,TopTimeStamp:o}}),r=`${a.head.seq}${t}`;return yield s.channel.sendPacket(a,{requestId:r})}catch(e){throw console.warn(`ConversationService.pagingGetConvList error: ${e}`),e}}))}({pagingTimeStamp:t?this._pagingTimeStamp:0,pagingStartIndex:t?this._pagingStartIndex:0,pagingPinnedTimeStamp:t?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:t?this._pagingPinnedStartIndex:0},this._core);if(s){const{CompleteFlag:e,SessionItem:n=[],TimeStamp:o,StartIndex:i,TopTimeStamp:a,TopStartIndex:r}=s;if(n.length>0){const e=this._getConvOptions(n);this._pagingConvIDMap=new Map([...this._pagingConvIDMap,...e.map((e=>[e.conversationID,1]))]),this._updateLocalConvList({conversationOptionsList:e,isFromGetConversations:!0,updateUnreadCount:!0}),this._onConversationListUpdate()}this._pagingTimeStamp=o,this._pagingStartIndex=i,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=r,1!==e&&this._pagingGetConvList(t)}}catch(e){throw console.error(`${this._name}._pagingGetConvList fail:`,e),e}}))}_getConvOptions(e){const n=this._convertConvKey(e).filter((({type:e,userID:t})=>1===e&&!this._isNonExistentAccount(t)||2===e)),o=this._core.store.get("login").userId;return n.map((e=>{var n,i,a,r,l,u,d,c,p,g,v,h;if(E(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===L.C2C){const s={userID:e.userID,nick:e.nick,avatar:e.peerAvatar},g=null===(a=null===(i=null===(n=this._core)||void 0===n?void 0:n.user)||void 0===i?void 0:i.userProfile)||void 0===a?void 0:a.createProfile(e.userID,[s]);return{conversationID:`${t}${e.userID}`,type:t,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(r=e.lastMsg)||void 0===r?void 0:r.elements[0])?null===(l=e.lastMsg)||void 0===l?void 0:l.elements[0].type:null,payload:(null===(u=e.lastMsg)||void 0===u?void 0:u.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(d=e.lastMsg)||void 0===d?void 0:d.cloudCustomData)||"",isRevoked:e.lastMessageFlag===S.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:e.lastC2CMsgFromAccount===o&&e.time<=e.c2cPeerReadTime,revoker:(null===(p=null===(c=e.lastMsg)||void 0===c?void 0:c.revokerInfo)||void 0===p?void 0:p.revoker)||null},unreadCount:0,userProfile:g,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:N(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}return{conversationID:`${s}${e.groupID}`,type:s,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null===(g=e.lastMsg)||void 0===g?void 0:g.cloudCustomData)||"",isRevoked:e.lastMessageFlag===S.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(h=null===(v=e.lastMsg)||void 0===v?void 0:v.revokerInfo)||void 0===h?void 0:h.revoker)||null}),groupProfile:{groupID:e.groupID,name:e.groupNick,avatar:e.groupImage,type:e.groupType,nextMessageSeq:e.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(e),peerReadTime:0,isPinned:1===e.isPinned,version:0,customData:e.customMark||"",markList:N(e.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(e.messageRemindType),subType:e.groupType}}))}_convertConvKey(e){return e.map((e=>({type:e.Type,userID:e.To_Account,nick:e.C2cNick,peerAvatar:e.C2cImage,time:e.MsgTimeStamp,sequence:e.MsgSeq,lastC2CMsgFromAccount:e.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(e.LastMsg),lastMessageFlag:e.LastMsgFlags,c2cPeerReadTime:e.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount})))}_convertLastMsgKey(e){var t,s,n,o;if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(e))return null;let i="",a=null;return e.MsgBody&&(i=null===(n=e.MsgBody[0])||void 0===n?void 0:n.MsgType,a=this._parseContent(i,e.MsgBody[0])),{event:e.Event,elements:[{type:i,content:a,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(o=e.RevokerInfo)||void 0===o?void 0:o.revoker}}}_parseContent(e,t){var s;if(!t)return t;const n=this._core.message.messageFactory.getElementClass(e);return n?null===(s=n.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return(function(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}(e,["LayersOverLimit"])).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=M:1===e?t=y:2===e?t=f:3===e&&(t=T),t}_patchTypeAndPayload(e){const{event:t,elements:s=[]}=e.lastMsg||{};return E(t)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:h,payload:{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,n=t-s;return n>0?n:0}_updateLocalConvList(e){const{newConvList:t}=this._getTmpConvListMapping(e);this._convMap=new Map(this._sortConvList([...this._convMap])),this._core.store.set("conversation",{conversationMap:this._convMap}),console.log(`${this._name}._updateLocalConvList newConvList: ${t.length}`)}_getTmpConvListMapping(e){const{conversationOptionsList:n,isFromGetConversations:o,isInstantMessage:i,isUnreadC2CMessage:a=!1,updateUnreadCount:r}=e,l=[],u=null==n?void 0:n.length;for(let e=0;e<u;e++){const u=new b(n[e]),{conversationID:d,type:c}=u;if(!this._isNonExistentAccount(d))if(this._convMap.has(d)){const l=this._convMap.get(d);if(o){this._convMap.set(d,u),c===t?u.unreadCount=l.unreadCount:c===s&&(u.groupProfile=JSON.parse(JSON.stringify(l.groupProfile)));continue}this._mergeConversationInfo({conversationID:d,tmpConversation:u,lastMessage:n[e].lastMessage,isFromGetConversations:o,isInstantMessage:i}),this._patchLastMessage({conversationID:d,lastMessage:n[e].lastMessage,isInstantMessage:i}),!0===r&&(null==l||l.updateUnreadCount({nextUnreadCount:u.unreadCount,isFromGetConversations:o,isUnreadC2CMessage:a}))}else l.push(u),this._convMap.set(d,u)}return{newConvList:l}}_isNonExistentAccount(e){let s;return e.startsWith(t)&&(s=e.replace(t,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}_mergeConversationInfo(e){var t,s;const{conversationID:n,tmpConversation:o,lastMessage:i,isFromGetConversations:a,isInstantMessage:r}=e,l=this._convMap.get(n),u=["unreadCount","allowType","adminForbidType","payload"];!1===r&&u.push("lastMessage"),a&&u.push("isPinned"),E(r)&&i&&null===(null==l?void 0:l.lastMessage.payload)&&(l.lastMessage.payload=i.payload),(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(null==l?void 0:l.lastMessage.revoker))||(l.lastMessage.revoker=null);k(l,o,u,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{conversationID:t,lastMessage:n,isInstantMessage:o}=e,i=this._convMap.get(t);if(i&&n){const{payload:e,nameCard:t,nick:a,cloudCustomData:r=""}=n;o&&(e&&(i.lastMessage.payload=e),i.type===s&&(i.lastMessage.nameCard=t,i.lastMessage.nick=a)),i.lastMessage.cloudCustomData!==r&&(i.lastMessage.cloudCustomData=r)}}_sortConvList(e){const t=[],s=[],n=[],o=[];return e.forEach((e=>{var i,a,r,l;!0===e[1].isPinned?(null===(a=null===(i=this._core)||void 0===i?void 0:i.helper)||void 0===a?void 0:a.isEmpty(e[1].lastMessage.lastTime))?s.push(e):t.push(e):(null===(l=null===(r=this._core)||void 0===r?void 0:r.helper)||void 0===l?void 0:l.isEmpty(e[1].lastMessage.lastTime))?o.push(e):n.push(e)})),t.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(s).concat(n.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime))).concat(o)}_getLocalConvList(){return[...this._convMap.values()].filter((e=>this._isConvNeedShow(e.conversationID)))}_isConvNeedShow(e){const t=this._getLocalConversation(e);if(E(t))return!0;const o=t.type===n,i=t.type===s&&t.subType===a,l=t.type===s&&t.subType===r;return!(o||i||l)}_getLocalConversation(e){return this._convMap.get(e)}_updateUnreadCount(e,t=!0){var s,n;let o=!1;const i=this._getLocalConversation(e),a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageStore)||void 0===n?void 0:n.getLocalMessageList(e);if(!i)return o;const r=i.unreadCount,l=null==a?void 0:a.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;return r!==l&&(i.unreadCount=l,o=!0,console.log(`${this._name}._updateUnreadCount\n from ${r} to ${l}, conversationID:${e}`),!0===t&&this._onConversationListUpdate()),o}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_onConversationListUpdate(){var e;const t=this._getLocalConvList();this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.CONVERSATION_LIST_UPDATED,data:t}),this._onTotalUnreadCountUpdate()}_onTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._convTotalUnreadCount!==t&&(console.log(`${this._name}._onTotalUnreadCountUpdate from ${this._convTotalUnreadCount} to ${t}`),this._convTotalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}getConversationList(t){return e(this,void 0,void 0,(function*(){return{code:0,data:{conversationList:this._getConversationList(t),isSyncCompleted:this._isSyncCompleted()}}}))}_getConversationList(e){if(E(e))return this._getLocalConvList();if(O(e)){if(0===e.length)return[];return this._getLocalConvList().filter((t=>e.includes(t.conversationID)))}if((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s})(e)){const{type:t,markType:s,groupName:n,hasUnreadCount:o,hasGroupAtInfo:i}=e;return this._getLocalConvList().filter((e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,i)))}return[]}_isSyncCompleted(){return this._pagingStatus===I.RESOLVED}_filterType(e,n){return n!==t&&n!==s||e.type===n}_filterGroupName(e,t){return!D(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){return null===(s=t)||!("number"==typeof s&&!Number.isNaN(s-0)||"object"==typeof s&&s.constructor===Number)||(0===t?0===e.markList.length:e.markList.includes(t));var s}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_recoverConversations(){return e(this,void 0,void 0,(function*(){try{yield this.syncConvList(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.RECOVER_CONVERSATIONS_COMPLETED)}catch(e){console.debug(e)}}))}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}getConversationProfile(n){return e(this,void 0,void 0,(function*(){let e;return this._convMap.has(n)?e=this._convMap.get(n):(e=new b({conversationID:n}),(e=>D(e)&&e.slice(0,3)===t)(n)?(e.type=t,e.userProfile={userID:n.replace(t,"")}):(e.type=s,e.groupProfile={groupID:n.replace(s,"")}),this._convMap.set(n,e)),{code:0,data:{conversation:e}}}))}setMessageRead(t){return e(this,void 0,void 0,(function*(){console.log(`${this._name}.setMessageRead ok, ${JSON.stringify(t)}`)}))}setConversationDraft(t){return e(this,void 0,void 0,(function*(){return console.log(`${this._name}.setConversationDraft , ${JSON.stringify(t)}`),{code:0,data:{conversation:{}}}}))}getTotalUnreadMessageCount(){const e=this._getLocalConvList();let t=0;return e.forEach((e=>{e.type!==o&&(""!==e.messageRemindType&&e.messageRemindType!==M||(t+=e.unreadCount))})),t}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.RE_LOGIN,this._recoverConversations,this),e.unSubscribeInnerEvent(t.LOGIN,this.handleLoginSuccess,this),e.unSubscribeInnerEvent(t.NEW_MESSAGE,this._handleNewMessage,this),e.unSubscribeInnerEvent(t.MESSAGE_DELETED,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(t.MESSAGE_REVOKED,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(t.MESSAGE_MODIFIED,this._handleMessageModified,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const A={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0},F={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationID is invalid."}]};return{install:function(e){U.install(e),e.helper.registerValidateConfig({auth:A,params:F})},handleLoginSuccess:function(){U.handleLoginSuccess()}}}));
@@ -0,0 +1,8 @@
1
+ declare const friendPlugin: {
2
+ [key: string]: any;
3
+ };
4
+
5
+ export default friendPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/friend' {
7
+ export default friendPlugin;
8
+ }
@@ -1 +1 @@
1
- function t(t,i,n,e){return new(n||(n=Promise))((function(r,o){function s(t){try{a(e.next(t))}catch(t){o(t)}}function c(t){try{a(e.throw(t))}catch(t){o(t)}}function a(t){var i;t.done?r(t.value):(i=t.value,i instanceof n?i:new n((function(t){t(i)}))).then(s,c)}a((e=e.apply(t,i||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const i="friend";var n=new class{init(t){this._core=t;const{helper:i}=t;i.registerApi("getFriendList",this)}getFriendList(){return t(this,void 0,void 0,(function*(){return console.log(`${i} getFriendList`),{code:0,data:[]}}))}};var e=new class{init(t){this._core=t;const{helper:i}=t;i.registerApi("getFriendApplicationList",this)}getFriendApplicationList(){return t(this,void 0,void 0,(function*(){return console.log(`${i} getFriendApplicationList`),{code:0,data:{friendApplicationList:[],unreadCount:0}}}))}};var r=new class{init(t){this._core=t}};const o={getFriendList:!0,getFriendApplicationList:!0};var s=new class{install(t){n.init(t),e.init(t),r.init(t),t.helper.registerValidateConfig({auth:o})}};export{s as default};
1
+ function t(t,i,e,n){return new(e||(e=Promise))((function(r,s){function o(t){try{a(n.next(t))}catch(t){s(t)}}function c(t){try{a(n.throw(t))}catch(t){s(t)}}function a(t){var i;t.done?r(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(o,c)}a((n=n.apply(t,i||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const i="friend";var e=new class{init(t){this._core=t;const{helper:i}=t;i.registerApi("getBlacklist",this)}getBlacklist(){return t(this,void 0,void 0,(function*(){return console.log(`${i} getBlacklist`),{code:0,data:[]}}))}};var n=new class{init(t){this._core=t;const{helper:i}=t;i.registerApi("getFriendList",this)}getFriendList(){return t(this,void 0,void 0,(function*(){return console.log(`${i} getFriendList`),{code:0,data:[]}}))}};var r=new class{init(t){this._core=t;const{helper:i}=t;i.registerApi("getFriendApplicationList",this)}getFriendApplicationList(){return t(this,void 0,void 0,(function*(){return console.log(`${i} getFriendApplicationList`),{code:0,data:{friendApplicationList:[],unreadCount:0}}}))}};var s=new class{init(t){this._core=t}};const o={getBlacklist:!0,getFriendList:!0,getFriendApplicationList:!0};var c=new class{install(t){e.init(t),n.init(t),r.init(t),s.init(t),t.helper.registerValidateConfig({auth:o})}};export{c as default};
package/plugins/friend.js CHANGED
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).liteChatFriend=e()}(this,(function(){"use strict";function t(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{d(n.next(t))}catch(t){r(t)}}function c(t){try{d(n.throw(t))}catch(t){r(t)}}function d(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,c)}d((n=n.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const e="friend";var i=new class{init(t){this._core=t;const{helper:e}=t;e.registerApi("getFriendList",this)}getFriendList(){return t(this,void 0,void 0,(function*(){return console.log(`${e} getFriendList`),{code:0,data:[]}}))}};var n=new class{init(t){this._core=t;const{helper:e}=t;e.registerApi("getFriendApplicationList",this)}getFriendApplicationList(){return t(this,void 0,void 0,(function*(){return console.log(`${e} getFriendApplicationList`),{code:0,data:{friendApplicationList:[],unreadCount:0}}}))}};var o=new class{init(t){this._core=t}};const r={getFriendList:!0,getFriendApplicationList:!0};return new class{install(t){i.init(t),n.init(t),o.init(t),t.helper.registerValidateConfig({auth:r})}}}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).TencentCloudChatFriend=e()}(this,(function(){"use strict";function t(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function c(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,c)}l((n=n.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const e="friend";var i=new class{init(t){this._core=t;const{helper:e}=t;e.registerApi("getBlacklist",this)}getBlacklist(){return t(this,void 0,void 0,(function*(){return console.log(`${e} getBlacklist`),{code:0,data:[]}}))}};var n=new class{init(t){this._core=t;const{helper:e}=t;e.registerApi("getFriendList",this)}getFriendList(){return t(this,void 0,void 0,(function*(){return console.log(`${e} getFriendList`),{code:0,data:[]}}))}};var o=new class{init(t){this._core=t;const{helper:e}=t;e.registerApi("getFriendApplicationList",this)}getFriendApplicationList(){return t(this,void 0,void 0,(function*(){return console.log(`${e} getFriendApplicationList`),{code:0,data:{friendApplicationList:[],unreadCount:0}}}))}};var r=new class{init(t){this._core=t}};const s={getBlacklist:!0,getFriendList:!0,getFriendApplicationList:!0};return new class{install(t){i.init(t),n.init(t),o.init(t),r.init(t),t.helper.registerValidateConfig({auth:s})}}}));
@@ -0,0 +1,8 @@
1
+ declare const groupPlugin: {
2
+ [key: string]: any;
3
+ };
4
+
5
+ export default groupPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/group' {
7
+ export default groupPlugin;
8
+ }
package/plugins/group.js CHANGED
@@ -1 +1 @@
1
- !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e="undefined"!=typeof globalThis?globalThis:e||self).liteChatGroup=r()}(this,(function(){"use strict";function e(e,r,o,t){return new(o||(o=Promise))((function(i,n){function s(e){try{u(t.next(e))}catch(e){n(e)}}function c(e){try{u(t.throw(e))}catch(e){n(e)}}function u(e){var r;e.done?i(e.value):(r=e.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,c)}u((t=t.apply(e,r||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const r="group";var o=new class{init(e){this._core=e;const{helper:r}=e;r.registerApi("searchGroupByID",this),r.registerApi("getGroupList",this),r.registerApi("getGroupApplicationList",this)}searchGroupByID(o){return e(this,void 0,void 0,(function*(){try{console.log(`${r} searchGroupByID: groupID: ${o}`);const t=yield function(r,o){return e(this,void 0,void 0,(function*(){try{const{helper:e,channel:t}=o,i="group_open_http_svc.get_group_public_info",n={GroupIdList:[r]},s=e.generateProtocolData({servcmd:i,data:n}),c=`${s.head.seq}${i}`;return yield t.sendPacket(s,{requestId:c})}catch(e){throw console.warn("searchGroupByID error:",e),e}}))}(o,this._core);return this._parseSearchGroupByIDResponse(t),{code:0,data:{group:{groupID:o}}}}catch(e){throw console.warn(`${r} searchGroupByID error:`,e),e}}))}getGroupList(){return e(this,void 0,void 0,(function*(){return console.log(`${r} getGroupList`),{code:0,data:{groupList:[]}}}))}getGroupApplicationList(){return e(this,void 0,void 0,(function*(){return console.log(`${r} getGroupApplicationList`),{code:0,data:{applicationList:[]}}}))}_parseSearchGroupByIDResponse(e){var r;const o=null===(r=e.GroupInfo)||void 0===r?void 0:r[0];if(0!==(null==o?void 0:o.ErrorCode))throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:null==o?void 0:o.ErrorCode,message:null==o?void 0:o.ErrorCode});return e}};var t=new class{init(e){this._core=e}};var i=new class{init(e){this._core=e}};var n=new class{init(e){this._core=e}};var s=new class{init(e){this._core=e}};const c={searchGroupByID:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]},u={getGroupList:!0,searchGroupByID:!0,getGroupApplicationList:!0};return new class{install(e){o.init(e),t.init(e),i.init(e),n.init(e),s.init(e),e.helper.registerValidateConfig({auth:u,params:c})}}}));
1
+ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChatGroup=r()}(this,(function(){"use strict";function e(e,r,o,t){return new(o||(o=Promise))((function(i,n){function s(e){try{u(t.next(e))}catch(e){n(e)}}function c(e){try{u(t.throw(e))}catch(e){n(e)}}function u(e){var r;e.done?i(e.value):(r=e.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,c)}u((t=t.apply(e,r||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const r="group";var o=new class{init(e){this._core=e;const{helper:r}=e;r.registerApi("searchGroupByID",this),r.registerApi("getGroupList",this),r.registerApi("getGroupApplicationList",this)}searchGroupByID(o){return e(this,void 0,void 0,(function*(){try{console.log(`${r} searchGroupByID: groupID: ${o}`);const t=yield function(r,o){return e(this,void 0,void 0,(function*(){try{const{helper:e,channel:t}=o,i="group_open_http_svc.get_group_public_info",n={GroupIdList:[r]},s=e.generateProtocolData({servcmd:i,data:n}),c=`${s.head.seq}${i}`;return yield t.sendPacket(s,{requestId:c})}catch(e){throw console.warn("searchGroupByID error:",e),e}}))}(o,this._core);return this._parseSearchGroupByIDResponse(t),{code:0,data:{group:{groupID:o}}}}catch(e){throw console.warn(`${r} searchGroupByID error:`,e),e}}))}getGroupList(){return e(this,void 0,void 0,(function*(){return console.log(`${r} getGroupList`),{code:0,data:{groupList:[]}}}))}getGroupApplicationList(){return e(this,void 0,void 0,(function*(){return console.log(`${r} getGroupApplicationList`),{code:0,data:{applicationList:[]}}}))}_parseSearchGroupByIDResponse(e){var r;const o=null===(r=e.GroupInfo)||void 0===r?void 0:r[0];if(0!==(null==o?void 0:o.ErrorCode))throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:null==o?void 0:o.ErrorCode,message:null==o?void 0:o.ErrorCode});return e}};var t=new class{init(e){this._core=e}};var i=new class{init(e){this._core=e}};var n=new class{init(e){this._core=e}};var s=new class{init(e){this._core=e}};const c={searchGroupByID:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]},u={getGroupList:!0,searchGroupByID:!0,getGroupApplicationList:!0};return new class{install(e){o.init(e),t.init(e),i.init(e),n.init(e),s.init(e),e.helper.registerValidateConfig({auth:u,params:c})}}}));
@@ -0,0 +1,8 @@
1
+ declare const messageEnhancerPlugin: {
2
+ [key: string]: any;
3
+ };
4
+
5
+ export default messageEnhancerPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/message-enhancer' {
7
+ export default messageEnhancerPlugin;
8
+ }
@@ -1 +1 @@
1
- !function(e,s){"object"==typeof exports&&"undefined"!=typeof module?module.exports=s():"function"==typeof define&&define.amd?define(s):(e="undefined"!=typeof globalThis?globalThis:e||self)["liteChatMessage-enhancer"]=s()}(this,(function(){"use strict";const e={deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}},s={deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextMessage:!0};function t(e,s,t,n){return new(t||(t=Promise))((function(o,r){function i(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var s;e.done?o(e.value):(s=e.value,s instanceof t?s:new t((function(e){e(s)}))).then(i,a)}c((n=n.apply(e,s||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this._core=e}deleteMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,messageIdentifiers:t}=e,n="openim.delete_c2c_msg_ramble",o={From_Account:this._getCurrentUserId(),To_Account:s,MsgKeyList:t},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,from:t,sequence:n,time:o,random:r}=e,i="openim.msgwithdraw",a={MsgInfo:{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:r,MsgTimeStamp:o}},c=this._core.helper.generateProtocolData({servcmd:i,data:a}),g=`${c.head.seq}${i}`;return this._core.channel.sendPacket(c,{requestId:g})}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}}class o{constructor(e){this._core=e}deleteMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,messageIdentifiers:t}=e,n="group_open_http_svc.delete_group_ramble_msg_by_seq",o={GroupId:s,Deleter_Account:this._getCurrentUserId(),Seqs:t},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,sequence:t}=e,n="group_open_http_svc.group_msg_recall",o={GroupId:s,MsgSeqList:[{MsgSeq:t}]},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}}const r=2116,i="C2C",a="GROUP",c=20,g=1,l=300;var u,d,h;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(u||(u={})),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(d||(d={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(h||(h={}));class v{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:s,sequence:t,random:n,tinyID:o,clientTime:r,revokeReason:i,revoker:a}=e;let c={};const{messageStore:g}=this._core.message;return c=g.revokeMessage({conversationID:s,sequence:t,random:n}),c||(c={conversationID:s,sequence:t},o&&r&&n&&(c.ID=`${o}-${r}-${n}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:i,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return t(this,void 0,void 0,(function*(){const s=e.map((e=>e.revoker));try{const t=yield this._fetchUserInfos(s);t&&e.forEach((e=>{const{revoker:s}=e;t[s]&&(e.revokerInfo.nick=t[s].nick||"",e.revokerInfo.avatar=t[s].avatar||"",e.revokerInfo.userID=s)}))}catch(e){console.debug(e)}}))}filterValidMessages(e){return e.filter((e=>{const s=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),t=1===(null==e?void 0:e.isPlaceMessage);if(!s){this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return s&&!t}))}_fetchUserInfos(e){return t(this,void 0,void 0,(function*(){var s,t;const n=yield null===(s=this._core.user.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(t=n.data)||void 0===t?void 0:t.reduce(((e,{userID:s,nick:t,avatar:n})=>(e[s]={nick:t||"",avatar:n||""},e)),{}):null}))}}var M=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}install(e){this._core=e,this._groupMessageAction=new o(e),this._c2cMessageAction=new n(e),this._messageHelper=new v(e);const{notificationCenter:s,helper:t,InnerEvent:r}=e;s.subscribeInnerEvent(r.DESTROY,this._dispose,this),t.registerApi("deleteMessage",this),t.registerApi("revokeMessage",this),t.registerApi("resendMessage",this)}deleteMessage(e){return t(this,void 0,void 0,(function*(){let s=[],t=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:r});if(e.forEach((e=>{const{conversationID:r,conversationType:i,status:a,_onlineOnlyFlag:c,sequence:g,random:l,time:u}=e||{};if("success"===a&&r===n&&i===o){if(!c){const e="C2C"===i?`${g}_${l}_${u}`:String(g);s.push(e)}t.push(e)}})),0===s.length)return this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}};s.length>30&&(s=s.slice(0,30),t=t.slice(0,30));try{return"C2C"===o?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:s}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:s}),this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}}}catch(e){const{errorCode:s}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:s})}}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){var s;const t=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:n,isRevoked:o}=e;let r=null;if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(o)throw new this._core.helper.ChatError({message:"message has been revoked"});t.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(r="C2C"===n?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),r){const{RecallRetList:n}=r,o=(null===(s=null==n?void 0:n[0])||void 0===s?void 0:s.RetCode)||0;if(0!==o)throw new this._core.helper.ChatError({code:o});return t.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(e){const{errorCode:s}=e,t=new this._core.helper.ChatError({functionName:"revokeMessage",code:s});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(t).end(),t}}))}resendMessage(e,s){return t(this,void 0,void 0,(function*(){var t,n;return e.isResend=!0,e.status="unSend",null===(n=null===(t=this._core)||void 0===t?void 0:t.apiMap)||void 0===n?void 0:n.sendMessage(e,s)}))}_handleDeleteMessageSuccess(e){0!==e.length&&(e.forEach((e=>{e.isDeleted=!0;const s=this._core.message.messageStore.getLocalMessageList(e.conversationID);null==s||s.forEach((s=>{s.ID===e.ID&&(s.isDeleted=!0)}))})),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_DELETED,e[0].conversationID))}_handleRevokeMessageSuccess(e){return t(this,void 0,void 0,(function*(){var s;e.isRevoked=!0,e.revoker=null===(s=this._core.store.get("login"))||void 0===s?void 0:s.userId,yield this._messageHelper.updateRevokerInfo([e]),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_REVOKED,[e])}))}_dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}};class _{static parseServerPushElement(e){const{MsgContent:s={Text:""}}=e,{Text:t}=s;return new _({text:t})}constructor(e){this.type="TIMTextElem",this.content={text:e.text||""}}validateBeforeSend(){var e,s;return(null===(s=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===s?void 0:s.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}convertToBackendFormat(){const{text:e}=this.content;return{MsgType:this.type,MsgContent:{Text:e}}}}var p=new class{install(e){this._core=e,e.message.messageFactory.registerElementClass(u.MSG_TEXT,_),e.helper.registerApi("createTextMessage",this)}createTextMessage(e){var s,t;if(!e)return null;const n="string"==typeof e.payload?e.payload:(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.text)||"",o=new _({text:n}),r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:r}));return i.setElement(o),i}};class m{install(e){this._messageHelper=new v(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:n},InnerEventSubType:{C2C_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleC2CNotifyMessage,this),s.subscribeInnerEvent(n,this._dispose,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:s}=e;null==s||s.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return t(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:s}}=e,t=[],{notificationCenter:n,OuterEvent:o,InnerEvent:r}=this._core;s.forEach((e=>{const{MsgRand:s,MsgSeq:n,To_Account:o,From_Account:r,RevokerInfo:{Revoker_Account:i,Reason:a}}=e,c=this._getCurrentUserId()===r?`C2C${o}`:`C2C${r}`,g=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:s,revoker:i,revokeReason:a});t.push(g)})),0!==t.length&&n.emitInnerEvent(r.MESSAGE_REVOKED,{revokedMessages:t,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(t),n.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:t})}catch(e){console.debug(e)}}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s,DESTROY:t},InnerEventSubType:{C2C_NOTIFY_MESSAGE:n}}=this._core;e.unSubscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this),e.unSubscribeInnerEvent(t,this._dispose,this)}}class E{install(e){this._messageHelper=new v(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:n},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleGroupNotifyMessage,this),s.subscribeInnerEvent(n,this._dispose,this)}_handleGroupNotifyMessage(e){const{GroupTips:s}=e;null==s||s.forEach((e=>{var s;Array.isArray(null===(s=null==e?void 0:e.MsgBody)||void 0===s?void 0:s.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return t(this,void 0,void 0,(function*(){try{const{RevokerInfo:s,MsgBody:{GroupWithdrawInfoArray:t}}=e,n=[],{notificationCenter:o,OuterEvent:r,InnerEvent:i}=this._core;t.forEach((e=>{const{Random:t,MsgSeq:o,GroupId:r,MsgClientTime:i,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:g=(null==s?void 0:s.Revoker_Account)||"",Reason:l=(null==s?void 0:s.Reason)||""}}=e,u=c?`GROUP${c}`:`GROUP${r}`,d=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:o,random:t,tinyID:a,clientTime:i,revoker:g,revokeReason:l});n.push(d)})),0!==n.length&&(o.emitInnerEvent(i.MESSAGE_REVOKED,{revokedMessages:n,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(n),o.emitOuterEvent(r.MESSAGE_REVOKED,{name:r.MESSAGE_REVOKED,data:n}))}catch(e){console.debug(e)}}))}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s,DESTROY:t},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:n}}=this._core;e.unSubscribeInnerEvent(s,n,this._handleGroupNotifyMessage,this),e.unSubscribeInnerEvent(t,this._dispose,this)}}var I=new class{constructor(){this._c2cMessageReceiver=new m,this._groupMessageReceiver=new E}install(e){this._c2cMessageReceiver.install(e),this._groupMessageReceiver.install(e)}};class f{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new v(e)}getRoamingMessagesByAnchor(e){return t(this,void 0,void 0,(function*(){try{const s=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:n,direction:o,sequence:r}=e,i=t.replace(a,"");let c=r;if(o===h.BACKWARD){if("number"!=typeof r)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};c=r+n-1}const g={GroupId:i,ReqMsgNumber:n,WithRecalledMsg:1,Version:1};c&&(g.ReqMsgSeq=c);const l="group_open_http_svc.group_msg_get",u=this._core.helper.generateProtocolData({servcmd:l,data:g}),v=`${u.head.seq}${l}`,M=yield this._core.channel.sendPacket(u,{requestId:v});if(M){const{RspMsgList:e,NextReqMsgSeq:t=0,IsFinished:n,InvisibleMsgSeq:a}=M;s.setLogInfo({message:`groupID:${i} sequence:${r} reqSeq:${c} direction:${o}\n complete:${n} nextSequence:${t} remoteMsgCount:${e.length} invisibleSequenceList:${a}`}).end();const g=[];for(let s=0;s<e.length;s++){const t=e[s],n=this._parseMessage(t);g.push(n)}g.reverse();return{messageList:g,invisibleSequenceList:a,nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:[d.NO_MORE_DATA,d.DATA_HAS_EXPIRED].includes(n)}}}catch(e){const s=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(s).end()}}))}recoverHistoryMessage(e){return t(this,void 0,void 0,(function*(){const{message:{messageReceiver:s,messageStore:n},notificationCenter:o,OuterEvent:r}=this._core;null==e||e.forEach((e=>t(this,void 0,void 0,(function*(){const{conversationID:t,lastMessage:i}=e;let a=this._getLocalLastMessageSequence(t);const c=i.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:c})){const e=c-a;let i=!1;const g=Math.ceil(e/20);for(let e=0;e<g;e++)try{const e=c-a,g=Math.min(20,e),l=yield this.getRoamingMessagesByAnchor({conversationID:t,sequence:a+g,direction:h.FORWARD,count:g}),{nextReqMessageIDFromServer:u,hasNoMoreHistoryMessage:d,messageList:v}=l;i=d&&u<0,a=v[v.length-1].sequence;const M=[];if(Array.isArray(v)&&(v.forEach((e=>{s.groupMessageReceiver.updateMessageProfile(e);n.storeConversationMessage(e)&&M.push(e)})),M.length>0&&o.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:M})),i)break}catch(e){console.debug(e);break}}}))))}))}updateLastMessageSequenceMapOnDisconnect(){const e=this._core.message.messageStore.getContinuousMessagesByConversation();for(const[s,t]of e){if(s.startsWith("C2C"))continue;const e=Array.from(t.values());if((null==e?void 0:e.length)>0){const t=e[e.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(s,t)}}}_shouldRecoverHistory(e){const{localLastMessageSequence:s,serverLastMessageSequence:t}=e;if("number"!=typeof s||"number"!=typeof t)return!1;const n=t-s;return 0!==t&&s&&(n>=g&&n<l)}_getLocalLastMessageSequence(e){if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=this._core.message.messageStore.getLocalMessageList(e),t=s[s.length-1];return null==t?void 0:t.sequence}_parseMessage(e){const s=a,t=this._core.message.messageHelper.parseServerGroupMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:s,flow:"in"}));return n.setElement(t.elements),n}}var S=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}install(e){this._core=e,this._groupMessageHistory=new f(e),this._messageHelper=new v(e);const{InnerEvent:s,notificationCenter:t}=e;e.helper.registerApi("getMessageList",this),e.helper.registerApi("getMessageListHopping",this),t.subscribeInnerEvent(s.RECOVER_CONVERSATIONS_COMPLETED,this._recoverHistoryMessage,this),t.subscribeInnerEvent(s.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}getMessageList(e){return t(this,void 0,void 0,(function*(){try{const s=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:t,nextReqMessageID:n}=e;const o=c;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:n});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:o})){let e=null;if(t.startsWith(a)&&(e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(n),count:o,direction:h.FORWARD})),e){const{nextReqMessageIDFromServer:o,hasNoMoreHistoryMessage:i,messageList:a}=e,c=this._messageHelper.filterValidMessages(a),g=this._core.message.messageStore.prependLocalMessageList({messageList:c,conversationID:t}),l=this._core.message.messageStore.getLocalMessageList(t).slice(0,g.length+r),u=l.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(u);const d={nextReqMessageID:i?"":String(o),messageList:l,isCompleted:i},h=l.map((e=>e.sequence));return s.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${n} \n availableLocalMessagesCount: ${r} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}s.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${n} availableLocalMessagesCount: ${r}}`}).end();return{code:0,data:this._getMessageListFromMemory({conversationID:t,nextReqMessageID:n,count:o})}}catch(e){const s=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(s).end(),console.debug(s)}}))}getMessageListHopping(e){return t(this,void 0,void 0,(function*(){var s,t;const{conversationID:n,sequence:o,direction:r=h.FORWARD}=e,{isEmpty:i}=this._core.helper;if(![h.BACKWARD,h.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:g=c}=e;g=g>c?c:g;let l=null;if(n.startsWith(a)&&(l=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:n,sequence:o,count:g,direction:r})),l){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,messageList:a,invisibleSequenceList:c}=l,g=this._messageHelper.filterValidMessages(a);if(this._core.message.messageStore.storeSparseMessageList(g),r===h.FORWARD){const s=n&&e<1;return{code:0,data:{messageList:g,isCompleted:s,nextMessageSeq:s?"":e}}}if(r===h.BACKWARD){if(i(a)&&i(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(s=null==a?void 0:a[a.length-1])||void 0===s?void 0:s.sequence)||0,n=(null===(t=null==c?void 0:c[c.length-1])||void 0===t?void 0:t.sequence)||0;return{code:0,data:{messageList:g.filter((e=>e.sequence>=o)),isCompleted:!1,nextMessageSeq:Math.max(e,n)+1}}}return{code:0,data:l}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:s}){const t=this._core.message.messageStore.getLocalMessageList(e),{length:n}=t;if(!s)return n;let o=-1;return(null==e?void 0:e.startsWith(i))?o=t.findIndex((e=>e.ID===s)):(null==e?void 0:e.startsWith(a))&&(o=t.findIndex((e=>s.includes("-")?e.ID===s:String(e.sequence)===s))),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:s,targetCount:t}){return!!this._clearedConversations.has(e)||s<=t&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory({conversationID:e,nextReqMessageID:s,count:t}){const n=this._core.message.messageStore.getLocalMessageList(e),o=n.length;let r=o,a={isCompleted:!1,nextReqMessageID:"",messageList:[]},c=0,g=o;return s?s&&(g=n.findIndex((t=>e.startsWith(i)?t.ID===s:String(t.sequence)===s)),c=g>t?g-t:0,r=g):c=o>t?o-t:0,a.nextReqMessageID=0===c?"":this._generateNextReqMessageID({conversationID:e,targetIndex:c}),a.messageList=n.slice(c,g),a.isCompleted=r<=t,a}_generateNextReqMessageID({conversationID:e,targetIndex:s}){const t=this._core.message.messageStore.getLocalMessageList(e);return e.startsWith("C2C")?t[s].ID:String(t[s].sequence)}_recoverHistoryMessage(){const{conversationMap:e}=this._core.store.get("conversation")||{};if(e instanceof Map){const s=[...e.values()].filter((e=>e.type===a));this._groupMessageHistory.recoverHistoryMessage(s)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}_dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.unSubscribeInnerEvent(s.RECOVER_CONVERSATIONS_COMPLETED,this._recoverHistoryMessage,this),e.unSubscribeInnerEvent(s.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this),e.unSubscribeInnerEvent(s.DESTROY,this._dispose,this)}};var R=new class{install(e){this._core=e;const{helper:s}=e;s.registerApi("getMessageReactions",this),s.registerApi("getMessageReadReceiptList",this)}getMessageReadReceiptList(e){return t(this,void 0,void 0,(function*(){return console.log("getMessageReadReceiptList: options: ",e),{code:0,data:{messageList:[]}}}))}getMessageReactions(e){return t(this,void 0,void 0,(function*(){return console.log("getMessageReactions: options: ",e),{code:0,data:[]}}))}};return function(t){M.install(t),p.install(t),I.install(t),S.install(t),R.install(t),t.helper.registerValidateConfig({auth:s,params:e})}}));
1
+ !function(e,s){"object"==typeof exports&&"undefined"!=typeof module?module.exports=s():"function"==typeof define&&define.amd?define(s):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatMessage-enhancer"]=s()}(this,(function(){"use strict";const e={deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}},s={deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextMessage:!0};function t(e,s,t,n){return new(t||(t=Promise))((function(o,r){function i(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var s;e.done?o(e.value):(s=e.value,s instanceof t?s:new t((function(e){e(s)}))).then(i,a)}c((n=n.apply(e,s||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this._core=e}deleteMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,messageIdentifiers:t}=e,n="openim.delete_c2c_msg_ramble",o={From_Account:this._getCurrentUserId(),To_Account:s,MsgKeyList:t},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,from:t,sequence:n,time:o,random:r}=e,i="openim.msgwithdraw",a={MsgInfo:{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:r,MsgTimeStamp:o}},c=this._core.helper.generateProtocolData({servcmd:i,data:a}),g=`${c.head.seq}${i}`;return this._core.channel.sendPacket(c,{requestId:g})}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}}class o{constructor(e){this._core=e}deleteMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,messageIdentifiers:t}=e,n="group_open_http_svc.delete_group_ramble_msg_by_seq",o={GroupId:s,Deleter_Account:this._getCurrentUserId(),Seqs:t},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,sequence:t}=e,n="group_open_http_svc.group_msg_recall",o={GroupId:s,MsgSeqList:[{MsgSeq:t}]},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}}const r=2116,i="C2C",a="GROUP",c=20,g=1,l=300;var u,d,h;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(u||(u={})),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(d||(d={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(h||(h={}));class v{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:s,sequence:t,random:n,tinyID:o,clientTime:r,revokeReason:i,revoker:a}=e;let c={};const{messageStore:g}=this._core.message;return c=g.revokeMessage({conversationID:s,sequence:t,random:n}),c||(c={conversationID:s,sequence:t},o&&r&&n&&(c.ID=`${o}-${r}-${n}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:i,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return t(this,void 0,void 0,(function*(){const s=e.map((e=>e.revoker));try{const t=yield this._fetchUserInfos(s);t&&e.forEach((e=>{const{revoker:s}=e;t[s]&&(e.revokerInfo.nick=t[s].nick||"",e.revokerInfo.avatar=t[s].avatar||"",e.revokerInfo.userID=s)}))}catch(e){console.debug(e)}}))}filterValidMessages(e){return e.filter((e=>{const s=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),t=1===(null==e?void 0:e.isPlaceMessage);if(!s){this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return s&&!t}))}_fetchUserInfos(e){return t(this,void 0,void 0,(function*(){var s,t;const n=yield null===(s=this._core.user.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(t=n.data)||void 0===t?void 0:t.reduce(((e,{userID:s,nick:t,avatar:n})=>(e[s]={nick:t||"",avatar:n||""},e)),{}):null}))}}var M=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}install(e){this._core=e,this._groupMessageAction=new o(e),this._c2cMessageAction=new n(e),this._messageHelper=new v(e);const{notificationCenter:s,helper:t,InnerEvent:r}=e;s.subscribeInnerEvent(r.DESTROY,this._dispose,this),t.registerApi("deleteMessage",this),t.registerApi("revokeMessage",this),t.registerApi("resendMessage",this)}deleteMessage(e){return t(this,void 0,void 0,(function*(){let s=[],t=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:r});if(e.forEach((e=>{const{conversationID:r,conversationType:i,status:a,_onlineOnlyFlag:c,sequence:g,random:l,time:u}=e||{};if("success"===a&&r===n&&i===o){if(!c){const e="C2C"===i?`${g}_${l}_${u}`:String(g);s.push(e)}t.push(e)}})),0===s.length)return this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}};s.length>30&&(s=s.slice(0,30),t=t.slice(0,30));try{return"C2C"===o?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:s}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:s}),this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}}}catch(e){const{errorCode:s}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:s})}}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){var s;const t=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:n,isRevoked:o}=e;let r=null;if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(o)throw new this._core.helper.ChatError({message:"message has been revoked"});t.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(r="C2C"===n?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),r){const{RecallRetList:n}=r,o=(null===(s=null==n?void 0:n[0])||void 0===s?void 0:s.RetCode)||0;if(0!==o)throw new this._core.helper.ChatError({code:o});return t.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(e){const{errorCode:s}=e,t=new this._core.helper.ChatError({functionName:"revokeMessage",code:s});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(t).end(),t}}))}resendMessage(e,s){return t(this,void 0,void 0,(function*(){var t,n;return e.isResend=!0,e.status="unSend",null===(n=null===(t=this._core)||void 0===t?void 0:t.apiMap)||void 0===n?void 0:n.sendMessage(e,s)}))}_handleDeleteMessageSuccess(e){0!==e.length&&(e.forEach((e=>{e.isDeleted=!0;const s=this._core.message.messageStore.getLocalMessageList(e.conversationID);null==s||s.forEach((s=>{s.ID===e.ID&&(s.isDeleted=!0)}))})),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_DELETED,e[0].conversationID))}_handleRevokeMessageSuccess(e){return t(this,void 0,void 0,(function*(){var s;e.isRevoked=!0,e.revoker=null===(s=this._core.store.get("login"))||void 0===s?void 0:s.userId,yield this._messageHelper.updateRevokerInfo([e]),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_REVOKED,[e])}))}_dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}};class _{static parseServerPushElement(e){const{MsgContent:s={Text:""}}=e,{Text:t}=s;return new _({text:t})}constructor(e){this.type="TIMTextElem",this.content={text:e.text||""}}validateBeforeSend(){var e,s;return(null===(s=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===s?void 0:s.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}convertToBackendFormat(){const{text:e}=this.content;return{MsgType:this.type,MsgContent:{Text:e}}}}var p=new class{install(e){this._core=e,e.message.messageFactory.registerElementClass(u.MSG_TEXT,_),e.helper.registerApi("createTextMessage",this)}createTextMessage(e){var s,t;if(!e)return null;const n="string"==typeof e.payload?e.payload:(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.text)||"",o=new _({text:n}),r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:r}));return i.setElement(o),i}};class m{install(e){this._messageHelper=new v(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:n},InnerEventSubType:{C2C_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleC2CNotifyMessage,this),s.subscribeInnerEvent(n,this._dispose,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:s}=e;null==s||s.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return t(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:s}}=e,t=[],{notificationCenter:n,OuterEvent:o,InnerEvent:r}=this._core;s.forEach((e=>{const{MsgRand:s,MsgSeq:n,To_Account:o,From_Account:r,RevokerInfo:{Revoker_Account:i,Reason:a}}=e,c=this._getCurrentUserId()===r?`C2C${o}`:`C2C${r}`,g=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:s,revoker:i,revokeReason:a});t.push(g)})),0!==t.length&&n.emitInnerEvent(r.MESSAGE_REVOKED,{revokedMessages:t,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(t),n.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:t})}catch(e){console.debug(e)}}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s,DESTROY:t},InnerEventSubType:{C2C_NOTIFY_MESSAGE:n}}=this._core;e.unSubscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this),e.unSubscribeInnerEvent(t,this._dispose,this)}}class E{install(e){this._messageHelper=new v(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:n},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleGroupNotifyMessage,this),s.subscribeInnerEvent(n,this._dispose,this)}_handleGroupNotifyMessage(e){const{GroupTips:s}=e;null==s||s.forEach((e=>{var s;Array.isArray(null===(s=null==e?void 0:e.MsgBody)||void 0===s?void 0:s.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return t(this,void 0,void 0,(function*(){try{const{RevokerInfo:s,MsgBody:{GroupWithdrawInfoArray:t}}=e,n=[],{notificationCenter:o,OuterEvent:r,InnerEvent:i}=this._core;t.forEach((e=>{const{Random:t,MsgSeq:o,GroupId:r,MsgClientTime:i,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:g=(null==s?void 0:s.Revoker_Account)||"",Reason:l=(null==s?void 0:s.Reason)||""}}=e,u=c?`GROUP${c}`:`GROUP${r}`,d=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:o,random:t,tinyID:a,clientTime:i,revoker:g,revokeReason:l});n.push(d)})),0!==n.length&&(o.emitInnerEvent(i.MESSAGE_REVOKED,{revokedMessages:n,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(n),o.emitOuterEvent(r.MESSAGE_REVOKED,{name:r.MESSAGE_REVOKED,data:n}))}catch(e){console.debug(e)}}))}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s,DESTROY:t},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:n}}=this._core;e.unSubscribeInnerEvent(s,n,this._handleGroupNotifyMessage,this),e.unSubscribeInnerEvent(t,this._dispose,this)}}var I=new class{constructor(){this._c2cMessageReceiver=new m,this._groupMessageReceiver=new E}install(e){this._c2cMessageReceiver.install(e),this._groupMessageReceiver.install(e)}};class f{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new v(e)}getRoamingMessagesByAnchor(e){return t(this,void 0,void 0,(function*(){try{const s=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:n,direction:o,sequence:r}=e,i=t.replace(a,"");let c=r;if(o===h.BACKWARD){if("number"!=typeof r)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};c=r+n-1}const g={GroupId:i,ReqMsgNumber:n,WithRecalledMsg:1,Version:1};c&&(g.ReqMsgSeq=c);const l="group_open_http_svc.group_msg_get",u=this._core.helper.generateProtocolData({servcmd:l,data:g}),v=`${u.head.seq}${l}`,M=yield this._core.channel.sendPacket(u,{requestId:v});if(M){const{RspMsgList:e,NextReqMsgSeq:t=0,IsFinished:n,InvisibleMsgSeq:a}=M;s.setLogInfo({message:`groupID:${i} sequence:${r} reqSeq:${c} direction:${o}\n complete:${n} nextSequence:${t} remoteMsgCount:${e.length} invisibleSequenceList:${a}`}).end();const g=[];for(let s=0;s<e.length;s++){const t=e[s],n=this._parseMessage(t);g.push(n)}g.reverse();return{messageList:g,invisibleSequenceList:a,nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:[d.NO_MORE_DATA,d.DATA_HAS_EXPIRED].includes(n)}}}catch(e){const s=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(s).end()}}))}recoverHistoryMessage(e){return t(this,void 0,void 0,(function*(){const{message:{messageReceiver:s,messageStore:n},notificationCenter:o,OuterEvent:r}=this._core;null==e||e.forEach((e=>t(this,void 0,void 0,(function*(){const{conversationID:t,lastMessage:i}=e;let a=this._getLocalLastMessageSequence(t);const c=i.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:c})){const e=c-a;let i=!1;const g=Math.ceil(e/20);for(let e=0;e<g;e++)try{const e=c-a,g=Math.min(20,e),l=yield this.getRoamingMessagesByAnchor({conversationID:t,sequence:a+g,direction:h.FORWARD,count:g}),{nextReqMessageIDFromServer:u,hasNoMoreHistoryMessage:d,messageList:v}=l;i=d&&u<0,a=v[v.length-1].sequence;const M=[];if(Array.isArray(v)&&(v.forEach((e=>{s.groupMessageReceiver.updateMessageProfile(e);n.storeConversationMessage(e)&&M.push(e)})),M.length>0&&o.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:M})),i)break}catch(e){console.debug(e);break}}}))))}))}updateLastMessageSequenceMapOnDisconnect(){const e=this._core.message.messageStore.getContinuousMessagesByConversation();for(const[s,t]of e){if(s.startsWith("C2C"))continue;const e=Array.from(t.values());if((null==e?void 0:e.length)>0){const t=e[e.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(s,t)}}}_shouldRecoverHistory(e){const{localLastMessageSequence:s,serverLastMessageSequence:t}=e;if("number"!=typeof s||"number"!=typeof t)return!1;const n=t-s;return 0!==t&&s&&(n>=g&&n<l)}_getLocalLastMessageSequence(e){if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=this._core.message.messageStore.getLocalMessageList(e),t=s[s.length-1];return null==t?void 0:t.sequence}_parseMessage(e){const s=a,t=this._core.message.messageHelper.parseServerGroupMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:s,flow:"in"}));return n.setElement(t.elements),n}}var S=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}install(e){this._core=e,this._groupMessageHistory=new f(e),this._messageHelper=new v(e);const{InnerEvent:s,notificationCenter:t}=e;e.helper.registerApi("getMessageList",this),e.helper.registerApi("getMessageListHopping",this),t.subscribeInnerEvent(s.RECOVER_CONVERSATIONS_COMPLETED,this._recoverHistoryMessage,this),t.subscribeInnerEvent(s.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}getMessageList(e){return t(this,void 0,void 0,(function*(){try{const s=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:t,nextReqMessageID:n}=e;const o=c;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:n});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:o})){let e=null;if(t.startsWith(a)&&(e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(n),count:o,direction:h.FORWARD})),e){const{nextReqMessageIDFromServer:o,hasNoMoreHistoryMessage:i,messageList:a}=e,c=this._messageHelper.filterValidMessages(a),g=this._core.message.messageStore.prependLocalMessageList({messageList:c,conversationID:t}),l=this._core.message.messageStore.getLocalMessageList(t).slice(0,g.length+r),u=l.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(u);const d={nextReqMessageID:i?"":String(o),messageList:l,isCompleted:i},h=l.map((e=>e.sequence));return s.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${n} \n availableLocalMessagesCount: ${r} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}s.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${n} availableLocalMessagesCount: ${r}}`}).end();return{code:0,data:this._getMessageListFromMemory({conversationID:t,nextReqMessageID:n,count:o})}}catch(e){const s=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(s).end(),console.debug(s)}}))}getMessageListHopping(e){return t(this,void 0,void 0,(function*(){var s,t;const{conversationID:n,sequence:o,direction:r=h.FORWARD}=e,{isEmpty:i}=this._core.helper;if(![h.BACKWARD,h.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:g=c}=e;g=g>c?c:g;let l=null;if(n.startsWith(a)&&(l=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:n,sequence:o,count:g,direction:r})),l){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,messageList:a,invisibleSequenceList:c}=l,g=this._messageHelper.filterValidMessages(a);if(this._core.message.messageStore.storeSparseMessageList(g),r===h.FORWARD){const s=n&&e<1;return{code:0,data:{messageList:g,isCompleted:s,nextMessageSeq:s?"":e}}}if(r===h.BACKWARD){if(i(a)&&i(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(s=null==a?void 0:a[a.length-1])||void 0===s?void 0:s.sequence)||0,n=(null===(t=null==c?void 0:c[c.length-1])||void 0===t?void 0:t.sequence)||0;return{code:0,data:{messageList:g.filter((e=>e.sequence>=o)),isCompleted:!1,nextMessageSeq:Math.max(e,n)+1}}}return{code:0,data:l}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:s}){const t=this._core.message.messageStore.getLocalMessageList(e),{length:n}=t;if(!s)return n;let o=-1;return(null==e?void 0:e.startsWith(i))?o=t.findIndex((e=>e.ID===s)):(null==e?void 0:e.startsWith(a))&&(o=t.findIndex((e=>s.includes("-")?e.ID===s:String(e.sequence)===s))),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:s,targetCount:t}){return!!this._clearedConversations.has(e)||s<=t&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory({conversationID:e,nextReqMessageID:s,count:t}){const n=this._core.message.messageStore.getLocalMessageList(e),o=n.length;let r=o,a={isCompleted:!1,nextReqMessageID:"",messageList:[]},c=0,g=o;return s?s&&(g=n.findIndex((t=>e.startsWith(i)?t.ID===s:String(t.sequence)===s)),c=g>t?g-t:0,r=g):c=o>t?o-t:0,a.nextReqMessageID=0===c?"":this._generateNextReqMessageID({conversationID:e,targetIndex:c}),a.messageList=n.slice(c,g),a.isCompleted=r<=t,a}_generateNextReqMessageID({conversationID:e,targetIndex:s}){const t=this._core.message.messageStore.getLocalMessageList(e);return e.startsWith("C2C")?t[s].ID:String(t[s].sequence)}_recoverHistoryMessage(){const{conversationMap:e}=this._core.store.get("conversation")||{};if(e instanceof Map){const s=[...e.values()].filter((e=>e.type===a));this._groupMessageHistory.recoverHistoryMessage(s)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}_dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.unSubscribeInnerEvent(s.RECOVER_CONVERSATIONS_COMPLETED,this._recoverHistoryMessage,this),e.unSubscribeInnerEvent(s.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this),e.unSubscribeInnerEvent(s.DESTROY,this._dispose,this)}};var R=new class{install(e){this._core=e;const{helper:s}=e;s.registerApi("getMessageReactions",this),s.registerApi("getMessageReadReceiptList",this)}getMessageReadReceiptList(e){return t(this,void 0,void 0,(function*(){return console.log("getMessageReadReceiptList: options: ",e),{code:0,data:{messageList:[]}}}))}getMessageReactions(e){return t(this,void 0,void 0,(function*(){return console.log("getMessageReactions: options: ",e),{code:0,data:[]}}))}};return function(t){M.install(t),p.install(t),I.install(t),S.install(t),R.install(t),t.helper.registerValidateConfig({auth:s,params:e})}}));
@@ -0,0 +1,8 @@
1
+ declare const richMediaMessagePlugin: {
2
+ [key: string]: any;
3
+ };
4
+
5
+ export default conversationPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/rich-media-message' {
7
+ export default richMediaMessagePlugin;
8
+ }
@@ -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)["liteChatRich-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}}))}}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatRich-media-message"]=t()}(this,(function(){"use strict";function e(e,t){var o={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(o[i[s]]=e[i[s]])}return o}function t(e,t,o,i){return new(o||(o=Promise))((function(s,r){function n(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var o=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,o){return t(this,void 0,void 0,(function*(){var t;const{isEmpty:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:s="",method:r="PUT",url:n,qs:a,headers:l={},resources:d,dataType:c="text",uploadByIP:h,uploadIP:u}=e;let p=n;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(r.toUpperCase(),p,!0),g.responseType=c;const m=Object.assign({},l);if(h&&u&&(m.host=u),!i(m))for(const e in m)m.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,m[e]);return g.onload=()=>{const t=this._getResponseBody(g,s,h&&u),i=this._buildResponse(g,t);if(200===g.status)o(null,i);else{if(u&&!p.includes(u))return e.url=this._domainName2IP(p,u),e.uploadByIP=!0,this.request(e,o);o({code:g.status,message:JSON.stringify(g.responseText)},i)}},g.onerror=()=>{const e=this._getResponseBody(g,s,h&&u),t=this._buildResponse(g,e),i={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(i,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:i}=t,s=Math.min(Math.floor(100*i/o),100);e.onProgress({total:o,loaded:i,percent:s/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,i]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=i}})),{statusCode:e.status,statusMessage:e.statusText,headers:o,data:t}}_getResponseBody(e,t,o){return 200===e.status&&t?{location:t,uploadIP:o}:{response:e.responseText,uploadIP:o}}_queryString(e,t="&",o="="){var i;const{isEmpty:s,isPlainObject:r}=null===(i=this._core)||void 0===i?void 0:i.utils;return s(e)?"":r(e)?Object.keys(e).map((i=>{const s=encodeURIComponent(i)+o;return Array.isArray(e[i])?e[i].map((e=>s+encodeURIComponent(e))).join(t):s+encodeURIComponent(e[i])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const i=["unknown","image","video","audio","log"];var s=new class{init(e){this._core=e}request(t,o){var s;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:l="",headers:d={},url:c,downloadUrl:h=""}=t;let u=c,p=null;const g=h?h.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const m=decodeURIComponent(g[3]),f=m.includes("?")?m.split("?")[0]:m||"",_={key:t.fileKey||f,success_action_status:200,"Content-Type":""},v={};if(a){const[e,t]=c.split("?sign=");t&&(u=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let I={url:u,header:d,name:"file",filePath:l,formData:Object.assign(Object.assign({},_),v),timeout:t.timeout||3e5};if(n){const o=e(I,["name"]);I=Object.assign(Object.assign({},o),{fileName:"file",fileType:t.fileType?i[t.fileType]:"image"})}return p=r.uploadFile(Object.assign(Object.assign({},I),{success:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})},fail:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})}})),p.onProgressUpdate&&p.onProgressUpdate((e=>{t.onProgress&&t.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})})),p}_handleResponse(e){const{downloadUrl:t,response:o,callback:i}=e,s={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(s[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?i(null,{statusCode:r,headers:s,data:Object.assign(Object.assign({},o.data),{location:t})}):i({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:s,data:void 0})}};function r(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function n(e){const t=e||99999999;return Math.round(Math.random()*t)}function a(e,t=!0,o=!0){const i=Date.now();return t?o?i-e+" ms":`${Math.round((i-e)/1e3)} s`:o?i-e:Math.round((i-e)/1e3)}function l(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function d(e,t){return Math.round(Number(e)*10**t)/10**t}function c(e){const t=1024,o=1048576;return e<t?`${e}B`:e<o?`${Math.floor(e/t)}KB`:`${Math.floor(e/o)}MB`}function h(e){if(e<=1048576){return`${d(e/1024,1)}KB/s`}return`${d(e/1048576,1)}MB/s`}const u="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",m="TIMVideoFileElem",f="RichMediaMessagePlugin",_=["rich.my-imcloud.com","imrich.qcloud.com"],v=1,I=2,y=3;var U;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(U||(U={}));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}}))}}}));
@@ -0,0 +1,8 @@
1
+ declare const userEnhancerPlugin: {
2
+ [key: string]: any;
3
+ };
4
+
5
+ export default userEnhancerPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/user-enhancer' {
7
+ export default userEnhancerPlugin;
8
+ }
@@ -1 +0,0 @@
1
- function s(s,e,t,r){return new(t||(t=Promise))((function(i,n){function u(s){try{c(r.next(s))}catch(s){n(s)}}function a(s){try{c(r.throw(s))}catch(s){n(s)}}function c(s){var e;s.done?i(s.value):(e=s.value,e instanceof t?e:new t((function(s){s(e)}))).then(u,a)}c((r=r.apply(s,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const e="user-enhancer";var t=new class{init(s){this._core=s;const{helper:e}=s;e.registerApi("getBlacklist",this)}getBlacklist(){return s(this,void 0,void 0,(function*(){return console.log(`${e} getBlacklist`),{code:0,data:[]}}))}};var r=new class{init(s){this._core=s;const{helper:e}=s;e.registerApi("subscribeUserStatus",this),e.registerApi("unsubscribeUserStatus",this)}subscribeUserStatus(s){return console.log(`${e} subscribeUserStatus options: `,s),{code:0,data:{failureUserList:[]}}}unsubscribeUserStatus(s){return console.log(`${e} unsubscribeUserStatus options: `,s),{code:0,data:{failureUserList:[]}}}};const i={subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}}},n={getBlacklist:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};var u=new class{install(s){t.init(s),r.init(s),s.helper.registerValidateConfig({auth:n,params:i})}};export{u as default};
@@ -1 +0,0 @@
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)["liteChatUser-enhancer"]=t()}(this,(function(){"use strict";function e(e,t,s,r){return new(s||(s=Promise))((function(i,n){function u(e){try{a(r.next(e))}catch(e){n(e)}}function o(e){try{a(r.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(u,o)}a((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t="user-enhancer";var s=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi("getBlacklist",this)}getBlacklist(){return e(this,void 0,void 0,(function*(){return console.log(`${t} getBlacklist`),{code:0,data:[]}}))}};var r=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi("subscribeUserStatus",this),t.registerApi("unsubscribeUserStatus",this)}subscribeUserStatus(e){return console.log(`${t} subscribeUserStatus options: `,e),{code:0,data:{failureUserList:[]}}}unsubscribeUserStatus(e){return console.log(`${t} unsubscribeUserStatus options: `,e),{code:0,data:{failureUserList:[]}}}};const i={subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}}},n={getBlacklist:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};return new class{install(e){s.init(e),r.init(e),e.helper.registerValidateConfig({auth:n,params:i})}}}));