UNPKG

@sama-communications/sdk

Version:

A SDK client for interacting with the SAMA chat server from Web/Node.js apps

316 lines (315 loc) 12.3 kB
var P = Object.defineProperty; var I = (c, e, t) => e in c ? P(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t; var r = (c, e, t) => I(c, typeof e != "symbol" ? e + "" : e, t); import E from "get-browser-fingerprint"; function C(c) { const e = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (t) => { const n = Math.random() * 16 | 0; return (t === "x" ? n : n & 3 | 8).toString(16); }); return c !== void 0 ? `${e}:${c}` : e; } class A { constructor({ endpoint: { ws: e, http: t }, organization_id: n }) { 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, "onMessageEditListener"); r(this, "onMessageDeleteListener"); 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 = t, this.organizationId = n, E({ hardwareOnly: !0 }).then((s) => this.deviceId = s.toString()); } async connect() { return new Promise((e, t) => { this.socket = new WebSocket(this.wsEndpoint), this.socket.onopen = () => { var n; console.log("[socket.open]"), (n = this.onConnectEvent) == null || n.call(this), e(); }, this.socket.onmessage = (n) => { var a, u, d, h, y, v, f, w, b, k, q, x, R, S; const s = JSON.parse(n.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: m } = ((d = s.system_message) == null ? void 0 : d.x) || ((y = (h = s.message) == null ? void 0 : h.system_message) == null ? void 0 : y.x) || {}; if (o) { (v = this.onConversationCreateListener) == null || v.call(this, o); return; } if (l) { (f = this.onConversationUpdateListener) == null || f.call(this, l); return; } if (m) { (w = this.onConversationDeleteListener) == null || w.call(this, m); 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_edit) { (q = this.onMessageEditListener) == null || q.call(this, s.message_edit); return; } if (s.message_delete) { (x = this.onMessageDeleteListener) == null || x.call(this, s.message_delete); return; } if (s.message) { if (s.message.error) { this.responsesPromises[Object.keys(this.responsesPromises).slice(-1)[0]].reject(s.message.error); return; } (R = this.onMessageListener) == null || R.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: m, resObjKey: g } = this.responsesPromises[o]; if (i.error) i.error.status === 403 ? this.responsesPromises[o].reject(i.error) : m(i.error); else if (Array.isArray(g)) { const L = g.reduce((p, _) => (i[_] !== void 0 && (p[_] = i[_]), p), {}); g.every((p) => p in L) ? l(L) : m({ message: "Server error." }); } else g ? i[g] ? l(i[g]) : m({ message: "Server error." }) : l(i); delete this.responsesPromises[o]; } }, this.socket.onerror = (n) => { console.log("[socket.error]", n), t(n); }, this.socket.onclose = () => { var n; console.log("[socket.close]"), (n = this.onDisconnectEvent) == null || n.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, t = {}, n = "success") { const s = { request: { [e]: t, id: C(e) } }; return this.sendPromise(s, n); } async sendPromise(e, t) { return new Promise((n, 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: n, reject: s, resObjKey: t }; }); } async sendHttpPromise(e, t, n) { console.log("[http.request]", { request: n }); const s = { "Content-Type": "application/json" }, i = localStorage.getItem("sessionId"); i && (s.Authorization = `Bearer ${i}`); const a = { method: e, credentials: "include", headers: s }; n && (a.body = JSON.stringify(n)); const u = await fetch(`${this.httpEndpoint}/${t}`, a), d = await u.text(); if (!u.ok) throw console.error("[http.error]", d), d || u.statusText; const h = d ? JSON.parse(d) : {}; return console.log("[http.response]", { response: h }), h; } 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, email: e.email, password: e.password }, "user"); } async userEdit(e) { return this.sendRequest("user_edit", e, "user"); } async userLogin(e) { const { login: t, password: n } = 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 t && n && (a.login = t, a.password = n), await this.sendHttpPromise("POST", "login", a); } async userLogout() { return await this.sendHttpPromise("POST", "logout", null); } async userSendOTPToken(e) { const t = { organization_id: this.organizationId, device_id: this.deviceId, email: e.email }; return this.sendRequest("user_send_otp", t); } async userResetPassword(e) { const t = { organization_id: this.organizationId, device_id: this.deviceId, email: e.email, token: e.token, new_password: e.new_password }; return this.sendRequest("user_reset_password", t); } async userDelete() { return localStorage.removeItem("sessionId"), this.sendRequest("user_delete"); } async userSearch(e) { const t = { 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", t, "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((t, n) => { var i; const s = { message: { id: e.mid, body: e.body, cid: e.cid, attachments: e.attachments, replied_message_id: e.replied_message_id, forwarded_message_id: e.forwarded_message_id } }; this.responsesPromises[s.message.id] = { resolve: t, reject: n }, (i = this.socket) == null || i.send(JSON.stringify(s)), console.log("[socket.send]", s); }); } async messageEdit(e) { return this.sendRequest("message_edit", { id: e.mid, body: e.body }); } async messageDelete(e) { return this.sendRequest("message_delete", { cid: e.cid, ids: e.mids, type: e.type ?? "myself" }); } async messageList(e) { const t = { 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", t, "messages"); } async messageSummary(e) { return this.sendRequest("message_summary", { cid: e.cid, filter: e.filter }, "message"); } async messageTone(e) { return this.sendRequest("message_tone", { body: e.body, tone: e.tone }, "message"); } 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((t, n) => { var i; const s = { typing: { cid: e.cid } }; this.responsesPromises[s.typing.cid] = { resolve: t, reject: n }, (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 t, n; return this.sendRequest("conversation_update", { id: e.cid, name: e.name, description: e.description, participants: { add: (t = e.participants) == null ? void 0 : t.add, remove: (n = e.participants) == null ? void 0 : n.remove }, image_object: e.image_object }, "conversation"); } async conversationList(e) { const t = { ...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", t, "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 }); } } export { A as SAMAClient };