@sama-communications/sdk
Version:
A SDK client for interacting with the SAMA chat server from Web/Node.js apps
2 lines (1 loc) • 8.65 kB
JavaScript
(function(o,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("get-browser-fingerprint")):typeof define=="function"&&define.amd?define(["exports","get-browser-fingerprint"],c):(o=typeof globalThis<"u"?globalThis:o||self,c(o.SAMAClient={},o.getBrowserFingerprint))})(this,function(o,c){"use strict";var I=Object.defineProperty;var E=(o,c,l)=>c in o?I(o,c,{enumerable:!0,configurable:!0,writable:!0,value:l}):o[c]=l;var r=(o,c,l)=>E(o,typeof c!="symbol"?c+"":c,l);function l(y){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)});return y!==void 0?`${e}:${y}`:e}class C{constructor({endpoint:{ws:e,http:n},organization_id:t}){r(this,"socket",null);r(this,"wsEndpoint");r(this,"httpEndpoint");r(this,"organizationId");r(this,"curerntUserId",null);r(this,"responsesPromises",{});r(this,"deviceId",null);r(this,"onMessageListener",null);r(this,"onMessageStatusListener",null);r(this,"onUserActivityListener",null);r(this,"onUserTypingListener",null);r(this,"onConversationCreateListener",null);r(this,"onConversationUpdateListener",null);r(this,"onConversationDeleteListener",null);r(this,"onConnectEvent",null);r(this,"onMessageEvent",null);r(this,"onDisconnectEvent",null);this.wsEndpoint=e,this.httpEndpoint=n,this.organizationId=t,c({hardwareOnly:!0}).then(s=>this.deviceId=s.toString())}async connect(){return new Promise((e,n)=>{this.socket=new WebSocket(this.wsEndpoint),this.socket.onopen=()=>{var t;console.log("[socket.open]"),(t=this.onConnectEvent)==null||t.call(this),e()},this.socket.onmessage=t=>{var d,p,u,_,b,x,k,w,S,q,P,R;const s=JSON.parse(t.data);if(console.log("[socket.message]",s),s.typing){(d=this.onUserTypingListener)==null||d.call(this,s.typing);return}if(s.system_message||(p=s.message)!=null&&p.system_message){const{conversation_created:a,conversation_updated:h,conversation_kicked:g}=((u=s.system_message)==null?void 0:u.x)||((b=(_=s.message)==null?void 0:_.system_message)==null?void 0:b.x)||{};if(a){(x=this.onConversationCreateListener)==null||x.call(this,a);return}if(h){(k=this.onConversationUpdateListener)==null||k.call(this,h);return}if(g){(w=this.onConversationDeleteListener)==null||w.call(this,g);return}return}if(s.last_activity){(S=this.onUserActivityListener)==null||S.call(this,s.last_activity);return}if(s.message_read){(q=this.onMessageStatusListener)==null||q.call(this,s.message_read);return}if(s.message){if(s.message.error){this.responsesPromises[Object.keys(this.responsesPromises).slice(-1)[0]].reject(s.message.error);return}(P=this.onMessageListener)==null||P.call(this,s.message),s.message.from.toString()!==this.curerntUserId&&((R=this.onMessageEvent)==null||R.call(this,s.message));return}if(s.ask){const a=s.ask.mid;this.responsesPromises[a].resolve(s.ask),delete this.responsesPromises[a];return}const i=s.response;if(i){const a=i.id;if(!a){console.error(i.error);return}const{resolve:h,reject:g,resObjKey:m}=this.responsesPromises[a];if(i.error)i.error.status===403?this.responsesPromises[a].reject(i.error):g(i.error);else if(Array.isArray(m)){const L=m.reduce((v,f)=>(i[f]!==void 0&&(v[f]=i[f]),v),{});m.every(v=>v in L)?h(L):g({message:"Server error."})}else m?i[m]?h(i[m]):g({message:"Server error."}):h(i);delete this.responsesPromises[a]}},this.socket.onerror=t=>{console.log("[socket.error]",t),n(t)},this.socket.onclose=()=>{var t;console.log("[socket.close]"),(t=this.onDisconnectEvent)==null||t.call(this),this.reconnect()}})}reconnect(){const e=()=>{navigator.onLine&&document.visibilityState==="visible"&&(this.connect(),window.removeEventListener("online",e),document.removeEventListener("visibilitychange",e))};navigator.onLine&&document.visibilityState==="visible"?this.connect():(window.addEventListener("online",e),document.addEventListener("visibilitychange",e))}async sendRequest(e,n={},t="success"){const s={request:{[e]:n,id:l(e)}};return this.sendPromise(s,t)}async sendPromise(e,n){return new Promise((t,s)=>{if(!this.socket){s("Socket is not connected.");return}this.socket.send(JSON.stringify(e)),console.log("[socket.send]",e),this.responsesPromises[e.request.id]={resolve:t,reject:s,resObjKey:n}})}async sendHttpPromise(e,n,t){console.log("[http.request]",{request:t});const s={"Content-Type":"application/json"},i=localStorage.getItem("sessionId");i&&(s.Authorization=`Bearer ${i}`);const d={method:e,credentials:"include",headers:s};t&&(d.body=JSON.stringify(t));const p=await fetch(`${this.httpEndpoint}/${n}`,d),u=await p.text();if(!p.ok)throw console.error("[http.error]",u),u||p.statusText;const _=u?JSON.parse(u):{};return console.log("[http.response]",{response:_}),_}async connectSocket(e){return this.sendRequest("connect",{token:e.token,device_id:this.deviceId})}async disconnectSocket(){return this.sendRequest("user_logout")}async userCreate(e){return this.sendRequest("user_create",{organization_id:this.organizationId,login:e.login,password:e.password},"user")}async userEdit(e){return this.sendRequest("user_edit",e,"user")}async userLogin(e){const{login:n,password:t}=e||{},s=Date.now();parseInt(localStorage.getItem("sessionExpiredAt")||`${s}`,10)-s<=0&&localStorage.removeItem("sessionId");const d={organization_id:this.organizationId,device_id:this.deviceId};return n&&t&&(d.login=n,d.password=t),await this.sendHttpPromise("POST","login",d)}async userLogout(){return await this.sendHttpPromise("POST","logout",null)}async userDelete(){return localStorage.removeItem("sessionId"),this.sendRequest("user_delete")}async userSearch(e){const n={keyword:e.keyword,ignore_ids:e.ignore_ids||[],...e.limit&&{limit:e.limit},...e.updated_at&&{updated_at:e.updated_at}};return this.sendRequest("user_search",n,"users")}async getUsersByIds(e){return this.sendRequest("get_users_by_ids",{ids:e.ids},"users")}async getParticipantsByCids(e){return this.sendRequest("get_participants_by_cids",{cids:e.cids},["users","conversations"])}async createUploadUrlForFiles(e){return this.sendRequest("create_files",e.files,"files")}async getDownloadUrlForFiles(e){return this.sendRequest("get_file_urls",{file_ids:e.file_ids},"file_urls")}async messageCreate(e){return new Promise((n,t)=>{var i;const s={message:{id:e.mid,body:e.body,cid:e.cid,attachments:e.attachments,replied_message_id:e.replied_message_id}};this.responsesPromises[s.message.id]={resolve:n,reject:t},(i=this.socket)==null||i.send(JSON.stringify(s)),console.log("[socket.send]",s)})}async messageList(e){const n={cid:e.cid,...e.ids&&{ids:e.ids},...e.limit&&{limit:e.limit},...e.updated_at&&{updated_at:e.updated_at}};return this.sendRequest("message_list",n,"messages")}async markConversationAsRead(e){return this.sendRequest("message_read",{cid:e.cid})}async subscribeToUserActivity(e){return this.sendRequest("user_last_activity_subscribe",{id:e},"last_activity")}async unsubscribeFromUserActivity(){return this.sendRequest("user_last_activity_unsubscribe")}async sendTypingStatus(e){return new Promise((n,t)=>{var i;const s={typing:{cid:e.cid}};this.responsesPromises[s.typing.cid]={resolve:n,reject:t},(i=this.socket)==null||i.send(JSON.stringify(s)),console.log("[socket.send]",s)})}async conversationCreate(e){return this.sendRequest("conversation_create",e,"conversation")}async conversationUpdate(e){var n,t;return this.sendRequest("conversation_update",{id:e.cid,name:e.name,description:e.description,participants:{add:(n=e.participants)==null?void 0:n.add,remove:(t=e.participants)==null?void 0:t.remove},image_object:e.image_object},"conversation")}async conversationList(e){const n={...e.limit&&{limit:e.limit},...e.updated_at&&{updated_at:{gt:e.updated_at.gt,lt:e.updated_at.lt}}};return this.sendRequest("conversation_list",n,"conversations")}async conversationDelete(e){return this.sendRequest("conversation_delete",{id:e.cid})}async conversationSearch(e){return this.sendRequest("conversation_search",{name:e.name},"conversations")}async conversationHandlerCreate(e){return this.sendRequest("conversation_handler_create",{cid:e.cid,content:e.content})}async getConversationHandler(e){return this.sendRequest("get_conversation_handler",{cid:e.cid},"conversation_handler")}async conversationHandlerDelete(e){return this.sendRequest("conversation_handler_delete",{cid:e.cid})}async pushSubscriptionCreate(e){return this.sendRequest("push_subscription_create",{platform:"web",web_endpoint:e.web_endpoint,web_key_auth:e.web_key_auth,web_key_p256dh:e.web_key_p256dh,device_udid:this.deviceId},"subscription")}async pushSubscriptionDelete(){return this.sendRequest("push_subscription_delete",{device_udid:this.deviceId})}}o.SAMAClient=C,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});