@sama-communications/sdk
Version:
A SDK client for interacting with the SAMA chat server from Web/Node.js apps
2 lines (1 loc) • 8.41 kB
JavaScript
"use strict";var P=Object.defineProperty;var R=(c,e,n)=>e in c?P(c,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):c[e]=n;var r=(c,e,n)=>R(c,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("get-browser-fingerprint");function I(c){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 c!==void 0?`${e}:${c}`: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,L({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 a,u,d,p,v,y,b,x,f,k,w,S;const s=JSON.parse(t.data);if(console.log("[socket.message]",s),s.typing){(a=this.onUserTypingListener)==null||a.call(this,s.typing);return}if(s.system_message||(u=s.message)!=null&&u.system_message){const{conversation_created:o,conversation_updated:l,conversation_kicked:h}=((d=s.system_message)==null?void 0:d.x)||((v=(p=s.message)==null?void 0:p.system_message)==null?void 0:v.x)||{};if(o){(y=this.onConversationCreateListener)==null||y.call(this,o);return}if(l){(b=this.onConversationUpdateListener)==null||b.call(this,l);return}if(h){(x=this.onConversationDeleteListener)==null||x.call(this,h);return}return}if(s.last_activity){(f=this.onUserActivityListener)==null||f.call(this,s.last_activity);return}if(s.message_read){(k=this.onMessageStatusListener)==null||k.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}(w=this.onMessageListener)==null||w.call(this,s.message),s.message.from.toString()!==this.curerntUserId&&((S=this.onMessageEvent)==null||S.call(this,s.message));return}if(s.ask){const o=s.ask.mid;this.responsesPromises[o].resolve(s.ask),delete this.responsesPromises[o];return}const i=s.response;if(i){const o=i.id;if(!o){console.error(i.error);return}const{resolve:l,reject:h,resObjKey:g}=this.responsesPromises[o];if(i.error)i.error.status===403?this.responsesPromises[o].reject(i.error):h(i.error);else if(Array.isArray(g)){const q=g.reduce((m,_)=>(i[_]!==void 0&&(m[_]=i[_]),m),{});g.every(m=>m in q)?l(q):h({message:"Server error."})}else g?i[g]?l(i[g]):h({message:"Server error."}):l(i);delete this.responsesPromises[o]}},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:I(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 a={method:e,credentials:"include",headers:s};t&&(a.body=JSON.stringify(t));const u=await fetch(`${this.httpEndpoint}/${n}`,a),d=await u.text();if(!u.ok)throw console.error("[http.error]",d),d||u.statusText;const p=d?JSON.parse(d):{};return console.log("[http.response]",{response:p}),p}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 a={organization_id:this.organizationId,device_id:this.deviceId};return n&&t&&(a.login=n,a.password=t),await this.sendHttpPromise("POST","login",a)}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})}}exports.SAMAClient=C;