@sama-communications/sdk
Version:
A SDK client for interacting with the SAMA chat server from Web/Node.js apps
2 lines (1 loc) • 7.61 kB
JavaScript
"use strict";var w=Object.defineProperty;var S=(c,e,n)=>e in c?w(c,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):c[e]=n;var r=(c,e,n)=>S(c,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("get-browser-fingerprint");function P(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 L{constructor({endpoint:{ws:e,http:n}}){r(this,"socket",null);r(this,"wsEndpoint");r(this,"httpEndpoint");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,q({hardwareOnly:!0}).then(t=>this.deviceId=t.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,p,u,h,g,y,v,_,b,k,x,f;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||(p=s.message)!=null&&p.system_message){const{conversation_created:o,conversation_updated:d,conversation_kicked:l}=((u=s.system_message)==null?void 0:u.x)||((g=(h=s.message)==null?void 0:h.system_message)==null?void 0:g.x)||{};if(o){(y=this.onConversationCreateListener)==null||y.call(this,o);return}if(d){(v=this.onConversationUpdateListener)==null||v.call(this,d);return}if(l){(_=this.onConversationDeleteListener)==null||_.call(this,l);return}return}if(s.last_activity){(b=this.onUserActivityListener)==null||b.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}(x=this.onMessageListener)==null||x.call(this,s.message),s.message.from.toString()!==this.curerntUserId&&((f=this.onMessageEvent)==null||f.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:d,reject:l,resObjKey:m}=this.responsesPromises[o];i.error?i.error.status===403?this.responsesPromises[o].reject(i.error):l(i.error):m?i[m]?d(i[m]):l({message:"Server error."}):d(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:P(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(await fetch(`${this.httpEndpoint}/${n}`,a)).json();return console.log("[http.response]",{response:u}),u}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",{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={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")}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}};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.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 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=L;