import { Event, LogLevel, Method, Route, UserData, UserResponse } from "./models"; import Utils from "./utils"; import io from "socket.io-client"; import { EventEmitter } from "events"; export default class LinxSdkModule { utils: Utils; user: UserData; groups: any; #socket: any; socket: any; handler = new EventEmitter(); constructor(apiKey: string, host: string, debug: boolean = false) { this.utils = new Utils(apiKey, host, debug); } async init(user: string, password: string): Promise { try { const login: UserResponse = await this.utils.request(Method.POST, Route.LOGIN, { login: user, password: password, }); if (!login.success) new Error("Failed to initialize SDK"); this.user = login.data; this.utils.setToken(this.user.token); this.groups = await this.getGroups(); await this.establishWsConnection(); this.utils.log("The SDK initialized successfully"); } catch (err) { this.utils.log(JSON.stringify(err.message), LogLevel.ERROR); throw new Error(err.message); } } models() { enum USER_EVENTS { CONNECT = "connect", } return USER_EVENTS; } establishWsConnection() { return new Promise((resolve, reject) => { const hubAddress = this.user.account.configuration.hub_address; this.#socket = io(hubAddress, { rejectUnauthorized: false, secure: true }); this.#socket.on(Event.CONNECT, () => { this.sendArs(true); this.utils.log("The connection with the WS server was successfully established"); this.handler.emit(Event.CONNECT); resolve(); }); [Event.CONNECT_ERROR, Event.CONNECT_TIMEOUT, Event.DISCONNECT].forEach((eventType) => { this.#socket.on(eventType, (message: string) => { this.handler.emit(eventType); reject(new Error("Failed to initialize HUB connection")); }); }); }); } sendArs(ars: boolean) { this.#socket.emit( "ars", JSON.stringify({ ars, userAgent: "Dispatcher", asset_id: this.user.asset.id, account_id: this.user.account.id, asset_sip_id: this.user.asset.sip_id, fake: false, }), ); } sendGroupMonitoring() { const monitoringObject = { asset_alias: this.user.asset.name, asset_id: this.user.asset.id, asset_sip_id: this.user.asset.sip_id, group_id: 1, group_sip_id: 100190001, request_ptt_groups_status: false, scan_group_ids: [], }; this.#socket.emit("group-monitoring", JSON.stringify(monitoringObject)); } async getGroups() { const getGroupsRoute = Route.GROUPS.replace("$1", this.user.account.id.toString()); const groups: UserResponse = await this.utils.request(Method.GET, getGroupsRoute); if (!groups) throw new Error("Could not get the groups for your account"); return groups; } }