UNPKG

bria

Version:

CounterPath Bria Desktop API for Node.js

322 lines 16.2 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BriaClient = void 0; var eventemitter3_1 = __importDefault(require("eventemitter3")); var uuid_1 = require("uuid"); var ws_1 = __importDefault(require("ws")); var semver_1 = __importDefault(require("semver")); var sxml_1 = __importDefault(require("sxml")); var Status_1 = require("./Status"); var Audio_1 = require("./Audio"); var Call_1 = require("./Call"); var Account_1 = require("./Account"); var Voicemail_1 = require("./Voicemail"); var History_1 = require("./History"); var Presence_1 = require("./Presence"); var Collaboration_1 = require("./Collaboration"); var BringToFrontRequest_1 = __importDefault(require("../requests/BringToFrontRequest")); var Auth_1 = require("./Auth"); var Phone_1 = require("./Phone"); /** * Bria Client */ var BriaClient = /** @class */ (function (_super) { __extends(BriaClient, _super); function BriaClient(options) { var _this = _super.call(this) || this; _this.userAgent = 'node-bria'; _this.apiUrl = 'wss://cpclientapi.softphone.com:9002/counterpath/socketapi/v1'; _this.autoReconnect = false; _this.autoReconnectDelay = 500; _this.autoReconnectAttempts = 5; _this.reconnectAttempts = 0; _this.rejectUnauthorized = false; _this.populateVersion = true; _this.populateChildren = true; _this.websocketReconnect = function () { _this.reconnectAttempts++; if (_this.reconnectAttempts > _this.autoReconnectAttempts) return _this.emit('error', new Error('Failed to reconnect to Bria client (exceeded maximum attempts)')); _this.connect(); _this.emit('reconnect'); }; _this.websocketOpen = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this.reconnectAttempts = 0; this.emit('open'); if (!this.populateVersion) return [3 /*break*/, 2]; return [4 /*yield*/, this.status.getSystemInformation(true)]; case 1: _a.sent(); _a.label = 2; case 2: if (!this.populateChildren) return [3 /*break*/, 13]; return [4 /*yield*/, this.auth.populate()]; case 3: _a.sent(); return [4 /*yield*/, this.phone.populate()]; case 4: _a.sent(); return [4 /*yield*/, this.status.populate()]; case 5: _a.sent(); return [4 /*yield*/, this.audio.populate()]; case 6: _a.sent(); return [4 /*yield*/, this.call.populate()]; case 7: _a.sent(); return [4 /*yield*/, this.account.populate()]; case 8: _a.sent(); return [4 /*yield*/, this.voicemail.populate()]; case 9: _a.sent(); return [4 /*yield*/, this.history.populate()]; case 10: _a.sent(); return [4 /*yield*/, this.presence.populate()]; case 11: _a.sent(); return [4 /*yield*/, this.collaboration.populate()]; case 12: _a.sent(); _a.label = 13; case 13: this.emit('ready'); return [2 /*return*/]; } }); }); }; _this.websocketClosed = function (code, reason) { _this.emit('close', code, reason.toString()); if (_this.autoReconnect && code != 1001 /* CLOSE_GOING_AWAY */) { if (_this.autoReconnectDelay > 0) { setTimeout(_this.websocketReconnect, _this.autoReconnectDelay); } else { _this.websocketReconnect(); } } }; _this.websocketMessage = function (message) { var data = message.toString(); // why does Bria implement pseudo-http over WebSockets if (data.startsWith('HTTP/1.1 ')) { // Received a response to one of our requests from Bria var dataSplit = data.split(/\r?\n/gi); var statusMatches = dataSplit[0].match(/^HTTP\/1\.1 (\d{3}) ([\w ]+)$/i); var txMatches = dataSplit[1].match(/^Transaction-ID: ([\w-]+)$/i); var clMatches = dataSplit[3].match(/^Content-Length: (\d+)$/i); if (!statusMatches || !txMatches || !clMatches) return _this.emit('error', new Error('Invalid message received from Bria client (header invalid)')); var statusCode = parseInt(statusMatches[1], 10); var transactionId = txMatches[1]; var contentLength = parseInt(clMatches[1], 10); if (_this.listeners(transactionId).length === 0) _this.emit('warn', new Error('Received response to request without a listener')); if (contentLength === 0) return _this.emit(transactionId, statusCode, undefined, data); // why is .substr deprecated without an actual replacement // stupid js var xdsIdx = data.indexOf('<?xml'); var xmlStr = data.substring(xdsIdx, xdsIdx + contentLength - 1); var xml = new sxml_1.default.XML(xmlStr); _this.emit(transactionId, statusCode, xml, data); } else if (data.startsWith('POST /')) { // Received an async event from Bria var dataSplit = data.split(/\r?\n/gi); var pathMatches = dataSplit[0].match(/^POST \/(\w+)$/i); var clMatches = dataSplit[3].match(/^Content-Length: (\d+)$/i); if (!pathMatches || !clMatches) return _this.emit('error', new Error('Invalid event message received from Bria client (no path or Content-Length)')); var path = pathMatches[1]; var contentLength = parseInt(clMatches[1], 10); if (contentLength === 0) return _this.emit('warn', new Error('Received empty async event from Bria client')); var xdsIdx = data.indexOf('<?xml'); var xmlStr = data.substring(xdsIdx, xdsIdx + contentLength - 1); var xml = new sxml_1.default.XML(xmlStr); if (path === 'statusChange') { var evtType = xml.getProperty('type'); _this.emit("".concat(path, ".").concat(evtType), xml, data); } else { _this.emit('warn', new Error('Received unknown async event from Bria client')); } } else { return _this.emit('error', new Error('Invalid message received from Bria client')); } }; if (options) { if (options.userAgent) _this.userAgent = options.userAgent; if (options.apiUrl) _this.apiUrl = options.apiUrl; if (typeof options.autoReconnect === 'boolean') _this.autoReconnect = options.autoReconnect; if (typeof options.autoReconnectDelay === 'number' && options.autoReconnectDelay >= 0) _this.autoReconnectDelay = options.autoReconnectDelay; if (typeof options.autoReconnectAttempts === 'number') _this.autoReconnectAttempts = options.autoReconnectAttempts; if (typeof options.rejectUnauthorized === 'boolean') _this.rejectUnauthorized = options.rejectUnauthorized; if (typeof options.populateVersion === 'boolean') _this.populateVersion = options.populateVersion; if (typeof options.populateChildren === 'boolean') _this.populateChildren = options.populateChildren; } _this.auth = new Auth_1.BriaClientAuth(_this); _this.phone = new Phone_1.BriaClientPhone(_this); _this.status = new Status_1.BriaClientStatus(_this); _this.audio = new Audio_1.BriaClientAudio(_this); _this.call = new Call_1.BriaClientCall(_this); _this.account = new Account_1.BriaClientAccount(_this); _this.voicemail = new Voicemail_1.BriaClientVoicemail(_this); _this.history = new History_1.BriaClientHistory(_this); _this.presence = new Presence_1.BriaClientPresence(_this); _this.collaboration = new Collaboration_1.BriaClientCollaboration(_this); _this.connect(); return _this; } BriaClient.prototype.connect = function () { if (this.ws) { this.ws.close(1001); delete this.ws; } this.ws = new ws_1.default(this.apiUrl, { rejectUnauthorized: this.rejectUnauthorized, }); this.ws .on('open', this.websocketOpen) .on('close', this.websocketClosed) .on('message', this.websocketMessage); }; /** * Check the Bria version against the args (clientVersion < major.minor.patch) * If populateVersion is false, this function always returns FALSE. * @param version */ BriaClient.prototype.versionLt = function (version) { if (!this.clientVersion) return false; return semver_1.default.lt(this.clientVersion.systemProductVersion, version); }; /** * Check the Bria version against the args (clientVersion > major.minor.patch) * If populateVersion is false, this function always returns TRUE. * @param version */ BriaClient.prototype.versionGt = function (version) { return !this.versionLt(version); }; /** * Send a request to the Bria client * @param request BriaRequest * @returns request's transaction ID (UUID) */ BriaClient.prototype.send = function (request) { var _a; if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) != ws_1.default.OPEN) throw new Error('The Bria client is not connected'); var transactionId = (0, uuid_1.v4)(); var reqStr = request.buildRequest(this.userAgent, transactionId); this.ws.send(reqStr); return transactionId; }; /** * Send a request to the Bria client and wait for a response by transaction ID * @param request BriaRequest * @returns response */ BriaClient.prototype.sendWait = function (request) { return __awaiter(this, void 0, void 0, function () { var transactionId; var _this = this; return __generator(this, function (_a) { transactionId = this.send(request); return [2 /*return*/, new Promise(function (resolve, reject) { _this.once(transactionId, function (statusCode, x) { if (statusCode !== 200) return reject(x !== undefined ? x : statusCode); return resolve(x); }); })]; }); }); }; /** * Brings Bria window to front and takes focus * @param window Window to bring focus to * @see https://docs.counterpath.com/guides/desk/desk_api/clients/deskAPI/deskApiGettingReady.htm#getBringToFront */ BriaClient.prototype.bringToFront = function (window) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.sendWait(new BringToFrontRequest_1.default(window))]; }); }); }; return BriaClient; }(eventemitter3_1.default)); exports.BriaClient = BriaClient; //# sourceMappingURL=index.js.map