UNPKG

@hsaadawy/ngx-chat

Version:
947 lines (932 loc) 329 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs'), require('rxjs/operators'), require('@xmpp/client'), require('@angular/common/http'), require('@angular/common'), require('@angular/router'), require('@angular/cdk/text-field'), require('@angular/forms'), require('@angular/animations'), require('@xmpp/jid')) : typeof define === 'function' && define.amd ? define('@pazznetwork/ngx-chat', ['exports', '@angular/core', 'rxjs', 'rxjs/operators', '@xmpp/client', '@angular/common/http', '@angular/common', '@angular/router', '@angular/cdk/text-field', '@angular/forms', '@angular/animations', '@xmpp/jid'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.pazznetwork = global.pazznetwork || {}, global.pazznetwork["ngx-chat"] = {}), global.ng.core, global.rxjs, global.rxjs.operators, global["@xmpp/client"], global.ng.common.http, global.ng.common, global.ng.router, global.ng.cdk.textField, global.ng.forms, global.ng.animations, global["@xmpp/jid"])); })(this, (function (exports, core, rxjs, operators, client, http, common, router, textField, forms, animations, jid) { 'use strict'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ 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); }; function __extends(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 __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(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()); }); } function __generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function () { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } var FileDropComponent = /** @class */ (function () { function FileDropComponent() { this.fileUpload = new core.EventEmitter(); this.enabled = true; this.isDropTarget = false; } FileDropComponent.prototype.onDragOver = function (event) { if (this.enabled) { event.preventDefault(); event.stopPropagation(); this.isDropTarget = true; } }; FileDropComponent.prototype.onDragLeave = function (event) { event.preventDefault(); event.stopPropagation(); this.isDropTarget = false; }; FileDropComponent.prototype.onDrop = function (event) { return __awaiter(this, void 0, void 0, function () { var i, dataTransferItem; return __generator(this, function (_a) { if (this.enabled) { event.preventDefault(); event.stopPropagation(); this.isDropTarget = false; // tslint:disable-next-line:prefer-for-of for (i = 0; i < event.dataTransfer.items.length; i++) { dataTransferItem = event.dataTransfer.items[i]; if (dataTransferItem.kind === 'file') { this.fileUpload.emit(dataTransferItem.getAsFile()); } } } return [2 /*return*/]; }); }); }; return FileDropComponent; }()); FileDropComponent.decorators = [ { type: core.Component, args: [{ selector: 'ngx-chat-filedrop', template: "<div>\r\n <div class=\"drop-message\"\r\n [class.drop-message--visible]=\"isDropTarget\">\r\n {{dropMessage}}\r\n </div>\r\n <div>\r\n <ng-content></ng-content>\r\n </div>\r\n</div>\r\n", styles: [".drop-message{pointer-events:none;display:none}.drop-message--visible{position:absolute;top:0;bottom:0;left:0;right:0;display:flex;justify-content:center;align-content:center;flex-direction:column;text-align:center;font-size:1.5em;z-index:999;background-color:#fff9;padding:1em}\n"] },] } ]; FileDropComponent.propDecorators = { fileUpload: [{ type: core.Output }], dropMessage: [{ type: core.Input }], enabled: [{ type: core.Input }], onDragOver: [{ type: core.HostListener, args: ['dragover', ['$event'],] }, { type: core.HostListener, args: ['dragenter', ['$event'],] }], onDragLeave: [{ type: core.HostListener, args: ['dragleave', ['$event'],] }, { type: core.HostListener, args: ['dragexit', ['$event'],] }], onDrop: [{ type: core.HostListener, args: ['drop', ['$event'],] }] }; var ReplyMessageEvent = /** @class */ (function () { function ReplyMessageEvent() { this.replyMessageEmitter$ = new core.EventEmitter(); } ReplyMessageEvent.prototype.changeReplyMessage = function (replyMessage) { debugger; this.replyMessageEmitter$.emit(replyMessage); }; return ReplyMessageEvent; }()); /** * The chat service token gives you access to the main chat api and is implemented by default with an XMPP adapter, * you can always reuse the api and ui with a new service implementing the ChatService interface and providing the * said implementation with the token */ var CHAT_SERVICE_TOKEN = new core.InjectionToken('ngxChatService'); var ChatMessageInputComponent = /** @class */ (function () { function ChatMessageInputComponent(chatService, replyMessageEvent) { var _this = this; this.chatService = chatService; this.replyMessageEvent = replyMessageEvent; this.messageSent = new core.EventEmitter(); this.message = ""; this.messageItem = ""; debugger; this.replyMessageEvent.replyMessageEmitter$.subscribe(function (item) { // this.message = item _this.messageItem = item; }); } ChatMessageInputComponent.prototype.ngOnInit = function () { }; ChatMessageInputComponent.prototype.onSendMessage = function ($event) { if ($event) { $event.preventDefault(); } if (this.Reply != '') { this.chatService.sendMessage(this.recipient, "<div class=\"messageItem\">" + this.Reply + "</div>" + this.message); this.Reply = ''; } else { this.chatService.sendMessage(this.recipient, this.message); } this.message = ""; // this.messageSent.emit(); }; ChatMessageInputComponent.prototype.focus = function () { this.chatInput.nativeElement.focus(); }; ChatMessageInputComponent.prototype.delete = function () { debugger; this.Reply = ''; }; return ChatMessageInputComponent; }()); ChatMessageInputComponent.decorators = [ { type: core.Component, args: [{ selector: "ngx-chat-message-input", template: "<div *ngIf=\"Reply!=''\" style=\" background: #8e89896b;\r\ncolor: #fff;\r\nposition: relative;\r\ntop: -9px;\r\nwidth: 105%;\r\nleft: -3%;\r\npadding: 4px 6px;\r\nborder-radius: 4px 4px 0 0;\">\r\n\r\n <div [innerHTML]=\"Reply\"></div>\r\n <i class=\"fas fa-times\" style=\"font-family: 'Font Awesome 5 Pro' !important;float: right;padding: 0 5px; position: absolute;\r\n right: 0;\r\n top: 4px;\" (click)=\"delete()\" aria-hidden=\"true\"></i>\r\n\r\n</div>\r\n\r\n<textarea class=\"chat-input\" #chatInput [(ngModel)]=\"message\" (keydown.enter)=\"onSendMessage($event)\"\r\n cdkTextareaAutosize cdkAutosizeMinRows=\"1\" cdkAutosizeMaxRows=\"5\"\r\n placeholder=\"{{chatService.translations.placeholder}}\"></textarea>\r\n", styles: ["@keyframes ngx-chat-message-in{0%{transform:translate(50px);opacity:0}to{transform:none;opacity:1}}@keyframes ngx-chat-message-out{0%{transform:translate(-50px);opacity:0}to{transform:none;opacity:1}}.messageItem{background-color:red;width:100%;border-radius:2px}*{box-sizing:border-box;margin:0;padding:0;font-family:\"Helvetica\",\"Arial\",serif}.chat-input{border:none;width:100%;font-size:1em;padding:0;display:block;resize:none;overflow-x:hidden;outline:none}\n"] },] } ]; ChatMessageInputComponent.ctorParameters = function () { return [ { type: undefined, decorators: [{ type: core.Inject, args: [CHAT_SERVICE_TOKEN,] }] }, { type: ReplyMessageEvent, decorators: [{ type: core.Inject, args: [ReplyMessageEvent,] }] } ]; }; ChatMessageInputComponent.propDecorators = { recipient: [{ type: core.Input }], Reply: [{ type: core.Input }], messageSent: [{ type: core.Output }], chatInput: [{ type: core.ViewChild, args: ["chatInput",] }] }; exports.MessageState = void 0; (function (MessageState) { /** * Not yet sent */ MessageState["SENDING"] = "sending"; /** * Sent, but neither received nor seen by the recipient */ MessageState["SENT"] = "sent"; /** * The recipient client has received the message but the recipient has not seen it yet */ MessageState["RECIPIENT_RECEIVED"] = "recipientReceived"; /** * The message has been seen by the recipient */ MessageState["RECIPIENT_SEEN"] = "recipientSeen"; })(exports.MessageState || (exports.MessageState = {})); exports.Direction = void 0; (function (Direction) { Direction["in"] = "in"; Direction["out"] = "out"; })(exports.Direction || (exports.Direction = {})); var AbstractXmppPlugin = /** @class */ (function () { function AbstractXmppPlugin() { } AbstractXmppPlugin.prototype.onBeforeOnline = function () { return Promise.resolve(); }; AbstractXmppPlugin.prototype.onOffline = function () { }; AbstractXmppPlugin.prototype.afterSendMessage = function (message, messageStanza) { return; }; AbstractXmppPlugin.prototype.beforeSendMessage = function (messageStanza, message) { return; }; AbstractXmppPlugin.prototype.handleStanza = function (stanza) { return false; }; AbstractXmppPlugin.prototype.afterReceiveMessage = function (message, messageStanza, messageReceivedEvent) { return; }; return AbstractXmppPlugin; }()); /** * XEP-0191: Blocking Command * https://xmpp.org/extensions/xep-0191.html */ var BlockPlugin = /** @class */ (function (_super) { __extends(BlockPlugin, _super); function BlockPlugin(xmppChatAdapter, serviceDiscoveryPlugin) { var _this = _super.call(this) || this; _this.xmppChatAdapter = xmppChatAdapter; _this.serviceDiscoveryPlugin = serviceDiscoveryPlugin; _this.supportsBlock$ = new rxjs.BehaviorSubject('unknown'); return _this; } BlockPlugin.prototype.onBeforeOnline = function () { return __awaiter(this, void 0, void 0, function () { var supportsBlock; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.determineSupportForBlock()]; case 1: supportsBlock = _b.sent(); this.supportsBlock$.next(supportsBlock); if (!supportsBlock) return [3 /*break*/, 3]; return [4 /*yield*/, this.requestBlockedJids()]; case 2: _b.sent(); _b.label = 3; case 3: return [2 /*return*/]; } }); }); }; BlockPlugin.prototype.determineSupportForBlock = function () { return __awaiter(this, void 0, void 0, function () { var e_1; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, , 3]); return [4 /*yield*/, this.serviceDiscoveryPlugin.supportsFeature(this.xmppChatAdapter.chatConnectionService.userJid.domain, 'urn:xmpp:blocking')]; case 1: return [2 /*return*/, _b.sent()]; case 2: e_1 = _b.sent(); return [2 /*return*/, false]; case 3: return [2 /*return*/]; } }); }); }; BlockPlugin.prototype.onOffline = function () { this.supportsBlock$.next('unknown'); this.xmppChatAdapter.blockedContactIds$.next(new Set()); }; BlockPlugin.prototype.blockJid = function (jid) { return this.xmppChatAdapter.chatConnectionService.sendIq(client.xml('iq', { type: 'set' }, client.xml('block', { xmlns: 'urn:xmpp:blocking' }, client.xml('item', { jid: jid })))); }; BlockPlugin.prototype.unblockJid = function (jid) { return this.xmppChatAdapter.chatConnectionService.sendIq(client.xml('iq', { type: 'set' }, client.xml('unblock', { xmlns: 'urn:xmpp:blocking' }, client.xml('item', { jid: jid })))); }; BlockPlugin.prototype.requestBlockedJids = function () { return __awaiter(this, void 0, void 0, function () { var blockListResponse, blockedJids; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.xmppChatAdapter.chatConnectionService.sendIq(client.xml('iq', { type: 'get' }, client.xml('blocklist', { xmlns: 'urn:xmpp:blocking' })))]; case 1: blockListResponse = _b.sent(); blockedJids = blockListResponse .getChild('blocklist') .getChildren('item') .map(function (e) { return e.attrs.jid; }); this.xmppChatAdapter.blockedContactIds$.next(new Set(blockedJids)); return [2 /*return*/]; } }); }); }; BlockPlugin.prototype.handleStanza = function (stanza) { var _a; var from = stanza.attrs.from; if (from && from === ((_a = this.xmppChatAdapter.chatConnectionService.userJid) === null || _a === void 0 ? void 0 : _a.bare().toString())) { var blockPush = stanza.getChild('block', 'urn:xmpp:blocking'); var unblockPush = stanza.getChild('unblock', 'urn:xmpp:blocking'); var blockList_1 = this.xmppChatAdapter.blockedContactIds$.getValue(); if (blockPush) { blockPush.getChildren('item') .map(function (e) { return e.attrs.jid; }) .forEach(function (jid) { return blockList_1.add(jid); }); this.xmppChatAdapter.blockedContactIds$.next(blockList_1); return true; } else if (unblockPush) { var jidsToUnblock = unblockPush.getChildren('item').map(function (e) { return e.attrs.jid; }); if (jidsToUnblock.length === 0) { // unblock everyone blockList_1.clear(); } else { // unblock individually jidsToUnblock.forEach(function (jid) { return blockList_1.delete(jid); }); } this.xmppChatAdapter.blockedContactIds$.next(blockList_1); return true; } } return false; }; return BlockPlugin; }(AbstractXmppPlugin)); var AbstractStanzaBuilder = /** @class */ (function () { function AbstractStanzaBuilder() { } return AbstractStanzaBuilder; }()); var IqResponseError = /** @class */ (function (_super) { __extends(IqResponseError, _super); function IqResponseError(errorStanza) { var _this = _super.call(this, IqResponseError.extractErrorTextFromErrorResponse(errorStanza, IqResponseError.extractErrorDataFromErrorResponse(errorStanza))) || this; _this.errorStanza = errorStanza; var _b = IqResponseError.extractErrorDataFromErrorResponse(errorStanza), code = _b.code, type = _b.type, condition = _b.condition; _this.errorCode = code; _this.errorType = type; _this.errorCondition = condition; return _this; } IqResponseError.extractErrorDataFromErrorResponse = function (stanza) { var _a; var errorElement = stanza.getChild('error'); var errorCode = Number(errorElement === null || errorElement === void 0 ? void 0 : errorElement.attrs.code) || undefined; var errorType = errorElement === null || errorElement === void 0 ? void 0 : errorElement.attrs.type; var errorCondition = (_a = errorElement === null || errorElement === void 0 ? void 0 : errorElement.children.filter(function (childElement) { return childElement.getName() !== 'text' && childElement.attrs.xmlns === IqResponseError.ERROR_ELEMENT_NS; })[0]) === null || _a === void 0 ? void 0 : _a.getName(); return { code: errorCode, type: errorType, condition: errorCondition, }; }; IqResponseError.extractErrorTextFromErrorResponse = function (stanza, _b) { var code = _b.code, type = _b.type, condition = _b.condition; var _a; var additionalData = [ "errorCode: " + (code !== null && code !== void 0 ? code : '[unknown]'), "errorType: " + (type !== null && type !== void 0 ? type : '[unknown]'), "errorCondition: " + (condition !== null && condition !== void 0 ? condition : '[unknown]') ].join(', '); var errorText = ((_a = stanza.getChild('error')) === null || _a === void 0 ? void 0 : _a.getChildText('text', IqResponseError.ERROR_ELEMENT_NS)) || 'Unknown error'; return "IqResponseError: " + errorText + (additionalData ? " (" + additionalData + ")" : ''); }; return IqResponseError; }(Error)); IqResponseError.ERROR_ELEMENT_NS = 'urn:ietf:params:xml:ns:xmpp-stanzas'; var PUBSUB_EVENT_XMLNS = 'http://jabber.org/protocol/pubsub#event'; var PublishStanzaBuilder = /** @class */ (function (_super) { __extends(PublishStanzaBuilder, _super); function PublishStanzaBuilder(options) { var _this = _super.call(this) || this; _this.publishOptions = { persistItems: false, }; if (options) { _this.publishOptions = Object.assign(Object.assign({}, _this.publishOptions), options); } return _this; } PublishStanzaBuilder.prototype.toStanza = function () { var _a = this.publishOptions, node = _a.node, id = _a.id, persistItems = _a.persistItems; // necessary as a 'event-only' publish is currently broken in ejabberd, see // https://github.com/processone/ejabberd/issues/2799 var data = this.publishOptions.data || client.xml('data'); return client.xml('iq', { type: 'set' }, client.xml('pubsub', { xmlns: 'http://jabber.org/protocol/pubsub' }, client.xml('publish', { node: node }, client.xml('item', { id: id }, data)), client.xml('publish-options', {}, client.xml('x', { xmlns: 'jabber:x:data', type: 'submit' }, client.xml('field', { var: 'FORM_TYPE', type: 'hidden' }, client.xml('value', {}, 'http://jabber.org/protocol/pubsub#publish-options')), client.xml('field', { var: 'pubsub#persist_items' }, client.xml('value', {}, persistItems ? 1 : 0)), client.xml('field', { var: 'pubsub#access_model' }, client.xml('value', {}, 'whitelist')))))); }; return PublishStanzaBuilder; }(AbstractStanzaBuilder)); var RetrieveDataStanzaBuilder = /** @class */ (function (_super) { __extends(RetrieveDataStanzaBuilder, _super); function RetrieveDataStanzaBuilder(node) { var _this = _super.call(this) || this; _this.node = node; return _this; } RetrieveDataStanzaBuilder.prototype.toStanza = function () { return client.xml('iq', { type: 'get' }, client.xml('pubsub', { xmlns: 'http://jabber.org/protocol/pubsub' }, client.xml('items', { node: this.node }))); }; return RetrieveDataStanzaBuilder; }(AbstractStanzaBuilder)); /** * XEP-0060 Publish Subscribe (https://xmpp.org/extensions/xep-0060.html) * XEP-0223 Persistent Storage of Private Data via PubSub (https://xmpp.org/extensions/xep-0223.html) */ var PublishSubscribePlugin = /** @class */ (function (_super) { __extends(PublishSubscribePlugin, _super); function PublishSubscribePlugin(xmppChatAdapter, serviceDiscoveryPlugin) { var _this = _super.call(this) || this; _this.xmppChatAdapter = xmppChatAdapter; _this.serviceDiscoveryPlugin = serviceDiscoveryPlugin; _this.publish$ = new rxjs.Subject(); _this.supportsPrivatePublish = new rxjs.BehaviorSubject('unknown'); return _this; } PublishSubscribePlugin.prototype.onBeforeOnline = function () { return this.determineSupportForPrivatePublish(); }; PublishSubscribePlugin.prototype.onOffline = function () { this.supportsPrivatePublish.next('unknown'); }; PublishSubscribePlugin.prototype.storePrivatePayloadPersistent = function (node, id, data) { var _this = this; return new Promise(function (resolve, reject) { _this.supportsPrivatePublish .pipe(operators.filter(function (support) { return support !== 'unknown'; })) .subscribe(function (support) { if (!support) { reject(new Error('does not support private publish subscribe')); } else { resolve(_this.xmppChatAdapter.chatConnectionService.sendIq(new PublishStanzaBuilder({ node: node, id: id, data: data, persistItems: true }).toStanza())); } }); }); }; PublishSubscribePlugin.prototype.privateNotify = function (node, data, id) { var _this = this; return new Promise(function (resolve, reject) { _this.supportsPrivatePublish .pipe(operators.filter(function (support) { return support !== 'unknown'; })) .subscribe(function (support) { if (!support) { reject(new Error('does not support private publish subscribe')); } else { resolve(_this.xmppChatAdapter.chatConnectionService.sendIq(new PublishStanzaBuilder({ node: node, id: id, data: data, persistItems: false }).toStanza())); } }); }); }; PublishSubscribePlugin.prototype.handleStanza = function (stanza) { var eventElement = stanza.getChild('event', PUBSUB_EVENT_XMLNS); if (stanza.is('message') && eventElement) { this.publish$.next(eventElement); return true; } return false; }; PublishSubscribePlugin.prototype.retrieveNodeItems = function (node) { return __awaiter(this, void 0, void 0, function () { var iqResponseStanza, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.xmppChatAdapter.chatConnectionService.sendIq(new RetrieveDataStanzaBuilder(node).toStanza())]; case 1: iqResponseStanza = _a.sent(); return [2 /*return*/, iqResponseStanza.getChild('pubsub').getChild('items').getChildren('item')]; case 2: e_1 = _a.sent(); if (e_1 instanceof IqResponseError && (e_1.errorCondition === 'item-not-found' || e_1.errorCode === 404)) { return [2 /*return*/, []]; } throw e_1; case 3: return [2 /*return*/]; } }); }); }; PublishSubscribePlugin.prototype.determineSupportForPrivatePublish = function () { return __awaiter(this, void 0, void 0, function () { var isSupported, service, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.serviceDiscoveryPlugin.findService('pubsub', 'pep')]; case 1: service = _a.sent(); isSupported = service.features.includes('http://jabber.org/protocol/pubsub#publish-options'); return [3 /*break*/, 3]; case 2: e_2 = _a.sent(); isSupported = false; return [3 /*break*/, 3]; case 3: this.supportsPrivatePublish.next(isSupported); return [2 /*return*/]; } }); }); }; return PublishSubscribePlugin; }(AbstractXmppPlugin)); var MUC_SUB_FEATURE_ID = 'urn:xmpp:mucsub:0'; exports.MUC_SUB_EVENT_TYPE = void 0; (function (MUC_SUB_EVENT_TYPE) { MUC_SUB_EVENT_TYPE["presence"] = "urn:xmpp:mucsub:nodes:presence"; MUC_SUB_EVENT_TYPE["messages"] = "urn:xmpp:mucsub:nodes:messages"; MUC_SUB_EVENT_TYPE["affiliations"] = "urn:xmpp:mucsub:nodes:affiliations"; MUC_SUB_EVENT_TYPE["subscribers"] = "urn:xmpp:mucsub:nodes:subscribers"; MUC_SUB_EVENT_TYPE["config"] = "urn:xmpp:mucsub:nodes:config"; MUC_SUB_EVENT_TYPE["subject"] = "urn:xmpp:mucsub:nodes:subject"; MUC_SUB_EVENT_TYPE["system"] = "urn:xmpp:mucsub:nodes:system"; })(exports.MUC_SUB_EVENT_TYPE || (exports.MUC_SUB_EVENT_TYPE = {})); /** * support for https://docs.ejabberd.im/developer/xmpp-clients-bots/extensions/muc-sub/ */ var MucSubPlugin = /** @class */ (function (_super) { __extends(MucSubPlugin, _super); function MucSubPlugin(xmppChatAdapter, serviceDiscoveryPlugin) { var _this = _super.call(this) || this; _this.xmppChatAdapter = xmppChatAdapter; _this.serviceDiscoveryPlugin = serviceDiscoveryPlugin; _this.supportsMucSub$ = new rxjs.BehaviorSubject('unknown'); return _this; } MucSubPlugin.prototype.onBeforeOnline = function () { return this.determineSupportForMucSub(); }; MucSubPlugin.prototype.determineSupportForMucSub = function () { return __awaiter(this, void 0, void 0, function () { var isSupported, service, e_1; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 2, , 3]); return [4 /*yield*/, this.serviceDiscoveryPlugin.findService('conference', 'text')]; case 1: service = _c.sent(); isSupported = service.features.includes(MUC_SUB_FEATURE_ID); return [3 /*break*/, 3]; case 2: e_1 = _c.sent(); isSupported = false; return [3 /*break*/, 3]; case 3: this.supportsMucSub$.next(isSupported); return [2 /*return*/]; } }); }); }; MucSubPlugin.prototype.onOffline = function () { this.supportsMucSub$.next('unknown'); }; MucSubPlugin.prototype.subscribeRoom = function (roomJid, nodes) { if (nodes === void 0) { nodes = []; } return __awaiter(this, void 0, void 0, function () { var nick; return __generator(this, function (_c) { switch (_c.label) { case 0: nick = this.xmppChatAdapter.chatConnectionService.userJid.local; return [4 /*yield*/, this.xmppChatAdapter.chatConnectionService.sendIq(makeSubscribeRoomStanza(roomJid, nick, nodes))]; case 1: _c.sent(); return [2 /*return*/]; } }); }); }; MucSubPlugin.prototype.unsubscribeRoom = function (roomJid) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, this.xmppChatAdapter.chatConnectionService.sendIq(makeUnsubscribeRoomStanza(roomJid))]; case 1: _c.sent(); return [2 /*return*/]; } }); }); }; /** * A room moderator can unsubscribe others providing the their jid as attribute to the information query (iq) * see: https://docs.ejabberd.im/developer/xmpp-clients-bots/extensions/muc-sub/#unsubscribing-from-a-muc-room * @param roomJid for the room to be unsubscribed from * @param jid user id to be unsubscribed */ MucSubPlugin.prototype.unsubscribeJidFromRoom = function (roomJid, jid) { this.xmppChatAdapter.chatConnectionService.sendIq(client.xml('iq', { type: 'set', to: roomJid }, client.xml('unsubscribe', { xmlns: 'urn:xmpp:mucsub:0', jid: jid }))); }; /** * A user can query the MUC service to get their list of subscriptions. * see: https://docs.ejabberd.im/developer/xmpp-clients-bots/extensions/muc-sub/#g dd ddetting-list-of-subscribed-rooms */ MucSubPlugin.prototype.getSubscribedRooms = function () { return __awaiter(this, void 0, void 0, function () { var _c, local, domain, from, subscriptions; return __generator(this, function (_d) { switch (_d.label) { case 0: _c = this.xmppChatAdapter.chatConnectionService.userJid, local = _c.local, domain = _c.domain; from = local + "@" + domain; return [4 /*yield*/, this.xmppChatAdapter.chatConnectionService.sendIq(client.xml('iq', { type: 'get', from: from, to: 'muc.' + domain }, client.xml('subscriptions', { xmlns: 'urn:xmpp:mucsub:0' })))]; case 1: subscriptions = _d.sent(); return [2 /*return*/, subscriptions.getChildren('subscription').map(function (sub) { return sub.getAttr('jid'); })]; } }); }); }; /** * A subscriber or room moderator can get the list of subscribers by sending <subscriptions/> request directly to the room JID. * see: https://docs.ejabberd.im/developer/xmpp-clients-bots/extensions/muc-sub/#getting-list-of-subscribers-of-a-room * @param roomJid of the room the get a subscriber list from */ MucSubPlugin.prototype.getSubscribers = function (roomJid) { this.xmppChatAdapter.chatConnectionService.sendIq(client.xml('iq', { type: 'get', to: roomJid }, client.xml('subscriptions', { xmlns: 'urn:xmpp:mucsub:0' }))); }; MucSubPlugin.prototype.retrieveSubscriptions = function () { var _a, _b; return __awaiter(this, void 0, void 0, function () { var service, result, subscriptions; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, this.serviceDiscoveryPlugin.findService('conference', 'text')]; case 1: service = _c.sent(); return [4 /*yield*/, this.xmppChatAdapter.chatConnectionService.sendIq(makeRetrieveSubscriptionsStanza(service.jid))]; case 2: result = _c.sent(); subscriptions = (_b = (_a = result .getChild('subscriptions', MUC_SUB_FEATURE_ID)) === null || _a === void 0 ? void 0 : _a.getChildren('subscription')) === null || _b === void 0 ? void 0 : _b.map(function (subscriptionElement) { var _a, _b; var subscribedEvents = (_b = (_a = subscriptionElement .getChildren('event')) === null || _a === void 0 ? void 0 : _a.map(function (eventElement) { return eventElement.attrs.node; })) !== null && _b !== void 0 ? _b : []; return [subscriptionElement.attrs.jid, subscribedEvents]; }); return [2 /*return*/, new Map(subscriptions)]; }