qiscus-sdk-core 2.16.0 → 2.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,26 +1,51 @@
1
1
  "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports["default"] = void 0;
8
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
10
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
11
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
12
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
13
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
14
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
15
- var _match2 = require("../match");
16
- var _mitt = _interopRequireDefault(require("mitt"));
17
- var _connect = _interopRequireDefault(require("mqtt/lib/connect"));
18
- var _superagent = _interopRequireDefault(require("superagent"));
19
- var _lodash = _interopRequireDefault(require("lodash.debounce"));
20
- var _util = require("../util");
21
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
22
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
23
- var MqttAdapter = exports["default"] = /*#__PURE__*/function () {
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+ var __async = (__this, __arguments, generator) => {
23
+ return new Promise((resolve, reject) => {
24
+ var fulfilled = (value) => {
25
+ try {
26
+ step(generator.next(value));
27
+ } catch (e) {
28
+ reject(e);
29
+ }
30
+ };
31
+ var rejected = (value) => {
32
+ try {
33
+ step(generator.throw(value));
34
+ } catch (e) {
35
+ reject(e);
36
+ }
37
+ };
38
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
39
+ step((generator = generator.apply(__this, __arguments)).next());
40
+ });
41
+ };
42
+ const match = require("../match.js");
43
+ const mitt = require("mitt");
44
+ const connect = require("mqtt/lib/connect");
45
+ const request = require("superagent");
46
+ const debounce = require("lodash.debounce");
47
+ const util = require("../util.js");
48
+ class MqttAdapter {
24
49
  /**
25
50
  * @typedef {Function} GetClientId
26
51
  * @return {string}
@@ -38,667 +63,416 @@ var MqttAdapter = exports["default"] = /*#__PURE__*/function () {
38
63
  * @param {boolean} login
39
64
  * @param {MqttAdapterParams} obj
40
65
  */
41
- function MqttAdapter(_url, core, login, _ref) {
42
- var _this = this;
43
- var _ref$shouldConnect = _ref.shouldConnect,
44
- shouldConnect = _ref$shouldConnect === void 0 ? true : _ref$shouldConnect,
45
- brokerLbUrl = _ref.brokerLbUrl,
46
- enableLb = _ref.enableLb,
47
- getClientId = _ref.getClientId;
48
- (0, _classCallCheck2["default"])(this, MqttAdapter);
49
- (0, _defineProperty2["default"])(this, "_getClientId", function () {
50
- if (_this.getClientId == null) return "".concat(_this.core.AppId, "_").concat(_this.core.user_id, "_").concat(Date.now());
51
- return _this.getClientId();
66
+ constructor(url, core, login, { shouldConnect = true, brokerLbUrl, enableLb, getClientId }) {
67
+ __publicField(this, "_getClientId", () => {
68
+ if (this.getClientId == null)
69
+ return `${this.core.AppId}_${this.core.user_id}_${Date.now()}`;
70
+ return this.getClientId();
52
71
  });
53
- (0, _defineProperty2["default"])(this, "__mqtt_connected_handler", function () {
54
- _this.emitter.emit('connected');
72
+ __publicField(this, "__mqtt_connected_handler", () => {
73
+ this.emitter.emit("connected");
55
74
  });
56
- (0, _defineProperty2["default"])(this, "__mqtt_reconnect_handler", function () {
57
- _this.emitter.emit('reconnect');
75
+ __publicField(this, "__mqtt_reconnect_handler", () => {
76
+ this.emitter.emit("reconnect");
58
77
  });
59
- (0, _defineProperty2["default"])(this, "__mqtt_closed_handler", function () {
60
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
61
- args[_key] = arguments[_key];
62
- }
63
- _this.emitter.emit('close', args);
78
+ __publicField(this, "__mqtt_closed_handler", (...args) => {
79
+ this.emitter.emit("close", args);
64
80
  });
65
- (0, _defineProperty2["default"])(this, "__mqtt_message_handler", function (t, m) {
66
- var message = m.toString();
67
- var func = _this.matcher(t);
68
- _this.logger('message', t, m);
81
+ __publicField(this, "__mqtt_message_handler", (t, m) => {
82
+ const message = m.toString();
83
+ const func = this.matcher(t);
84
+ this.logger("message", t, m);
69
85
  if (func != null) func(message);
70
86
  });
71
- (0, _defineProperty2["default"])(this, "__mqtt_error_handler", function (err) {
72
- if (err && err.message === 'client disconnecting') return;
73
- _this.emitter.emit('error', err.message);
74
- _this.logger('error', err.message);
87
+ __publicField(this, "__mqtt_error_handler", (err) => {
88
+ if (err && err.message === "client disconnecting") return;
89
+ this.emitter.emit("error", err.message);
90
+ this.logger("error", err.message);
75
91
  });
76
- (0, _defineProperty2["default"])(this, "__mqtt_conneck", function (brokerUrl) {
77
- var topics = [];
78
- var opts = {
92
+ __publicField(this, "__mqtt_conneck", (brokerUrl) => {
93
+ const topics = [];
94
+ const opts = {
79
95
  will: {
80
- topic: "u/".concat(_this.core.user_id, "/s"),
96
+ topic: `u/${this.core.user_id}/s`,
81
97
  payload: 0,
82
98
  retain: true
83
99
  },
84
- clientId: _this._getClientId()
100
+ clientId: this._getClientId()
85
101
  // reconnectPeriod: 0,
86
102
  // connectTimeout: 1 * 1000,
87
103
  };
88
- if (brokerUrl == null) brokerUrl = _this.cacheRealtimeURL;
89
- if (_this.mqtt != null) {
90
- var _topics = Object.keys(_this.mqtt._resubscribeTopics);
91
- topics.push.apply(topics, _topics);
92
- _this.mqtt.removeAllListeners();
93
- _this.mqtt.end(true);
94
- delete _this.mqtt;
95
- _this.mqtt = null;
104
+ if (brokerUrl == null) brokerUrl = this.cacheRealtimeURL;
105
+ if (this.mqtt != null) {
106
+ const _topics = Object.keys(this.mqtt._resubscribeTopics);
107
+ topics.push(..._topics);
108
+ this.mqtt.removeAllListeners();
109
+ this.mqtt.end(true);
110
+ delete this.mqtt;
111
+ this.mqtt = null;
96
112
  }
97
- var mqtt = (0, _connect["default"])(brokerUrl, opts);
98
-
99
- // #region Mqtt Listener
100
- mqtt.addListener('connect', _this.__mqtt_connected_handler);
101
- mqtt.addListener('reconnect', _this.__mqtt_reconnect_handler);
102
- mqtt.addListener('close', _this.__mqtt_closed_handler);
103
- mqtt.addListener('error', _this.__mqtt_error_handler);
104
- mqtt.addListener('message', _this.__mqtt_message_handler);
105
- // #endregion
106
-
107
- _this.logger("resubscribe to old topics ".concat(topics));
108
- topics.forEach(function (topic) {
109
- return mqtt.subscribe(topic);
110
- });
113
+ const mqtt = connect(brokerUrl, opts);
114
+ mqtt.addListener("connect", this.__mqtt_connected_handler);
115
+ mqtt.addListener("reconnect", this.__mqtt_reconnect_handler);
116
+ mqtt.addListener("close", this.__mqtt_closed_handler);
117
+ mqtt.addListener("error", this.__mqtt_error_handler);
118
+ mqtt.addListener("message", this.__mqtt_message_handler);
119
+ this.logger(`resubscribe to old topics ${topics}`);
120
+ topics.forEach((topic) => mqtt.subscribe(topic));
111
121
  return mqtt;
112
122
  });
113
- (0, _defineProperty2["default"])(this, "_on_close_handler", (0, _lodash["default"])(/*#__PURE__*/(0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee() {
114
- var shouldReconnect, _yield$wrapP, _yield$wrapP2, url, err;
115
- return _regenerator["default"].wrap(function (_context) {
116
- while (1) switch (_context.prev = _context.next) {
117
- case 0:
118
- shouldReconnect = _this.enableLb === true &&
119
- // appConfig enabling realtime lb
120
- _this.core.isLogin === true &&
121
- // is logged in
122
- _this.shouldConnect === true &&
123
- // should reconnect?
124
- !_this.willConnectToRealtime; // is there still reconnect process in progress?
125
- if (_this.logEnabled) {
126
- console.group('@mqtt.closed');
127
- console.log("this.enableLb(".concat(_this.enableLb, ")"));
128
- console.log("this.core.isLogin(".concat(_this.core.isLogin, ")"));
129
- console.log("this.shouldConnect(".concat(_this.shouldConnect, ")"));
130
- console.log("this.willConnectToRealtime(".concat(_this.willConnectToRealtime, ")"));
131
- console.log("shouldReconnect(".concat(shouldReconnect, ")"));
132
- console.groupEnd();
133
- }
134
- if (shouldReconnect) {
135
- _context.next = 1;
136
- break;
137
- }
138
- return _context.abrupt("return");
139
- case 1:
140
- _this.willConnectToRealtime = true;
141
- _context.next = 2;
142
- return (0, _util.wrapP)(_this.getMqttNode());
143
- case 2:
144
- _yield$wrapP = _context.sent;
145
- _yield$wrapP2 = (0, _slicedToArray2["default"])(_yield$wrapP, 2);
146
- url = _yield$wrapP2[0];
147
- err = _yield$wrapP2[1];
148
- if (err) {
149
- _this.logger("cannot get new brokerURL, using old url instead (".concat(_this.cacheRealtimeURL, ")"));
150
- _this.mqtt = _this.__mqtt_conneck(_this.cacheRealtimeURL);
151
- } else {
152
- _this.cacheRealtimeURL = url;
153
- _this.logger('trying to reconnect to', url);
154
- _this.mqtt = _this.__mqtt_conneck(url);
155
- }
156
- _this.willConnectToRealtime = false;
157
- case 3:
158
- case "end":
159
- return _context.stop();
160
- }
161
- }, _callee);
162
- })), 1000));
163
- (0, _defineProperty2["default"])(this, "subscribtionBuffer", []);
164
- (0, _defineProperty2["default"])(this, "unsubscribtionBuffer", []);
165
- (0, _defineProperty2["default"])(this, "publishBuffer", []);
166
- this.emitter = (0, _mitt["default"])();
123
+ __publicField(this, "_on_close_handler", debounce(() => __async(this, null, function* () {
124
+ const shouldReconnect = this.enableLb === true && // appConfig enabling realtime lb
125
+ this.core.isLogin === true && // is logged in
126
+ this.shouldConnect === true && // should reconnect?
127
+ !this.willConnectToRealtime;
128
+ if (this.logEnabled) {
129
+ console.group("@mqtt.closed");
130
+ console.log(`this.enableLb(${this.enableLb})`);
131
+ console.log(`this.core.isLogin(${this.core.isLogin})`);
132
+ console.log(`this.shouldConnect(${this.shouldConnect})`);
133
+ console.log(`this.willConnectToRealtime(${this.willConnectToRealtime})`);
134
+ console.log(`shouldReconnect(${shouldReconnect})`);
135
+ console.groupEnd();
136
+ }
137
+ if (!shouldReconnect) return;
138
+ this.willConnectToRealtime = true;
139
+ const [url, err] = yield util.wrapP(this.getMqttNode());
140
+ if (err) {
141
+ this.logger(
142
+ `cannot get new brokerURL, using old url instead (${this.cacheRealtimeURL})`
143
+ );
144
+ this.mqtt = this.__mqtt_conneck(this.cacheRealtimeURL);
145
+ } else {
146
+ this.cacheRealtimeURL = url;
147
+ this.logger("trying to reconnect to", url);
148
+ this.mqtt = this.__mqtt_conneck(url);
149
+ }
150
+ this.willConnectToRealtime = false;
151
+ }), 1e3));
152
+ __publicField(this, "subscribtionBuffer", []);
153
+ __publicField(this, "unsubscribtionBuffer", []);
154
+ __publicField(this, "publishBuffer", []);
155
+ this.emitter = mitt();
167
156
  this.core = core;
168
157
  this.mqtt = null;
169
158
  this.brokerLbUrl = brokerLbUrl;
170
159
  this.getClientId = getClientId;
171
160
  this.enableLb = enableLb;
172
161
  this.shouldConnect = shouldConnect;
173
- this.matcher = (0, _match2.match)((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])({}, (0, _match2.when)(this.reNewMessage), function (topic) {
174
- return _this.newMessageHandler.bind(_this, topic);
175
- }), (0, _match2.when)(this.reNotification), function (topic) {
176
- return _this.notificationHandler.bind(_this, topic);
177
- }), (0, _match2.when)(this.reTyping), function (topic) {
178
- return _this.typingHandler.bind(_this, topic);
179
- }), (0, _match2.when)(this.reRoomTyping), function (topic) {
180
- return _this.roomTypingHandler.bind(_this, topic);
181
- }), (0, _match2.when)(this.reDelivery), function (topic) {
182
- return _this.deliveryReceiptHandler.bind(_this, topic);
183
- }), (0, _match2.when)(this.reRead), function (topic) {
184
- return _this.readReceiptHandler.bind(_this, topic);
185
- }), (0, _match2.when)(this.reOnlineStatus), function (topic) {
186
- return _this.onlinePresenceHandler.bind(_this, topic);
187
- }), (0, _match2.when)(this.reChannelMessage), function (topic) {
188
- return _this.channelMessageHandler.bind(_this, topic);
189
- }), (0, _match2.when)(this.reMessageUpdated), function (topic) {
190
- return _this.messageUpdatedHandler.bind(_this, topic);
191
- }), (0, _match2.when)(), function (topic) {
192
- return _this.logger('topic not handled', topic);
193
- }));
194
- var _mqtt = this.__mqtt_conneck(_url);
195
- this.mqtt = _mqtt;
196
-
197
- // if appConfig set realtimeEnabled to false,
198
- // we intentionally end mqtt connection here.
199
- // TODO: Make a better way to not connect
200
- // to broker, but still having mqtt client initiated.
201
- if (!shouldConnect) _mqtt.end(true);
162
+ this.matcher = match.match({
163
+ [match.when(this.reNewMessage)]: (topic) => this.newMessageHandler.bind(this, topic),
164
+ [match.when(this.reNotification)]: (topic) => this.notificationHandler.bind(this, topic),
165
+ [match.when(this.reTyping)]: (topic) => this.typingHandler.bind(this, topic),
166
+ [match.when(this.reRoomTyping)]: (topic) => this.roomTypingHandler.bind(this, topic),
167
+ [match.when(this.reDelivery)]: (topic) => this.deliveryReceiptHandler.bind(this, topic),
168
+ [match.when(this.reRead)]: (topic) => this.readReceiptHandler.bind(this, topic),
169
+ [match.when(this.reOnlineStatus)]: (topic) => this.onlinePresenceHandler.bind(this, topic),
170
+ [match.when(this.reChannelMessage)]: (topic) => this.channelMessageHandler.bind(this, topic),
171
+ [match.when(this.reMessageUpdated)]: (topic) => this.messageUpdatedHandler.bind(this, topic),
172
+ [match.when()]: (topic) => this.logger("topic not handled", topic)
173
+ });
174
+ let mqtt = this.__mqtt_conneck(url);
175
+ this.mqtt = mqtt;
176
+ if (!shouldConnect) mqtt.end(true);
202
177
  this.willConnectToRealtime = false;
203
-
204
- // handle load balencer
205
- this.emitter.on('close', this._on_close_handler);
206
- // this.emitter.on('connected', () => {
207
- // this.willConnectToRealtime = false
208
- // })
209
- }
210
- return (0, _createClass2["default"])(MqttAdapter, [{
211
- key: "cacheRealtimeURL",
212
- get: function get() {
213
- return this.core.mqttURL;
214
- },
215
- set: function set(url) {
216
- this.core.mqttURL = url;
217
- }
218
- }, {
219
- key: "connect",
220
- value: function connect() {
178
+ this.emitter.on("close", this._on_close_handler);
179
+ }
180
+ get cacheRealtimeURL() {
181
+ return this.core.mqttURL;
182
+ }
183
+ set cacheRealtimeURL(url) {
184
+ this.core.mqttURL = url;
185
+ }
186
+ connect() {
187
+ this.mqtt = this.__mqtt_conneck();
188
+ }
189
+ /**
190
+ * @return {Promise<boolean>}
191
+ */
192
+ openConnection() {
193
+ return __async(this, null, function* () {
194
+ this.shouldConnect = true;
221
195
  this.mqtt = this.__mqtt_conneck();
222
- }
223
-
224
- /**
225
- * @return {Promise<boolean>}
226
- */
227
- }, {
228
- key: "openConnection",
229
- value: (function () {
230
- var _openConnection = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee2() {
231
- return _regenerator["default"].wrap(function (_context2) {
232
- while (1) switch (_context2.prev = _context2.next) {
233
- case 0:
234
- this.shouldConnect = true;
235
- this.mqtt = this.__mqtt_conneck();
236
- case 1:
237
- case "end":
238
- return _context2.stop();
239
- }
240
- }, _callee2, this);
241
- }));
242
- function openConnection() {
243
- return _openConnection.apply(this, arguments);
244
- }
245
- return openConnection;
246
- }()
247
- /**
248
- * @return {Promise<boolean>}
249
- */
250
- )
251
- }, {
252
- key: "closeConnection",
253
- value: (function () {
254
- var _closeConnection = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee3() {
255
- var _this2 = this;
256
- return _regenerator["default"].wrap(function (_context3) {
257
- while (1) switch (_context3.prev = _context3.next) {
258
- case 0:
259
- this.shouldConnect = false;
260
- this.mqtt.end(true, function (err) {
261
- if (err) {
262
- _this2.logger('error when close connection', err.message);
263
- }
264
- });
265
- this.mqtt = null;
266
- case 1:
267
- case "end":
268
- return _context3.stop();
269
- }
270
- }, _callee3, this);
271
- }));
272
- function closeConnection() {
273
- return _closeConnection.apply(this, arguments);
274
- }
275
- return closeConnection;
276
- }())
277
- }, {
278
- key: "getMqttNode",
279
- value: function () {
280
- var _getMqttNode = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee4() {
281
- var res, url, port;
282
- return _regenerator["default"].wrap(function (_context4) {
283
- while (1) switch (_context4.prev = _context4.next) {
284
- case 0:
285
- _context4.next = 1;
286
- return _superagent["default"].get(this.brokerLbUrl);
287
- case 1:
288
- res = _context4.sent;
289
- url = res.body.data.url;
290
- port = res.body.data.wss_port;
291
- return _context4.abrupt("return", "wss://".concat(url, ":").concat(port, "/mqtt"));
292
- case 2:
293
- case "end":
294
- return _context4.stop();
295
- }
296
- }, _callee4, this);
297
- }));
298
- function getMqttNode() {
299
- return _getMqttNode.apply(this, arguments);
300
- }
301
- return getMqttNode;
302
- }()
303
- }, {
304
- key: "connected",
305
- get: function get() {
306
- if (this.mqtt == null) return false;
307
- return this.mqtt.connected;
308
- }
309
- }, {
310
- key: "subscribe",
311
- value: function subscribe() {
312
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
313
- args[_key2] = arguments[_key2];
314
- }
315
- this.subscribtionBuffer.push(args);
316
- while (this.mqtt != null && this.subscribtionBuffer.length > 0) {
317
- var subs = this.subscribtionBuffer.shift();
318
- if (subs != null) {
319
- var _this$mqtt;
320
- this.logger('subscribe topic', subs);
321
- (_this$mqtt = this.mqtt).subscribe.apply(_this$mqtt, (0, _toConsumableArray2["default"])(subs));
322
- }
323
- }
324
- }
325
- }, {
326
- key: "unsubscribe",
327
- value: function unsubscribe() {
328
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
329
- args[_key3] = arguments[_key3];
330
- }
331
- this.unsubscribtionBuffer.push(args);
332
- while (this.mqtt != null && this.unsubscribtionBuffer.length > 0) {
333
- var subs = this.unsubscribtionBuffer.shift();
334
- if (subs != null) {
335
- var _this$mqtt2;
336
- this.logger('unsubscribe topic', subs);
337
- (_this$mqtt2 = this.mqtt).unsubscribe.apply(_this$mqtt2, (0, _toConsumableArray2["default"])(subs));
196
+ });
197
+ }
198
+ /**
199
+ * @return {Promise<boolean>}
200
+ */
201
+ closeConnection() {
202
+ return __async(this, null, function* () {
203
+ this.shouldConnect = false;
204
+ this.mqtt.end(true, (err) => {
205
+ if (err) {
206
+ this.logger("error when close connection", err.message);
338
207
  }
339
- }
340
- }
341
- }, {
342
- key: "publish",
343
- value: function publish(topic, payload) {
344
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
345
- this.publishBuffer.push({
346
- topic: topic,
347
- payload: payload,
348
- options: options
349
208
  });
350
- while (this.mqtt != null && this.publishBuffer.length > 0) {
351
- var data = this.publishBuffer.shift();
352
- if (data != null) {
353
- this.logger('publish to', data.topic, data.payload, data.options);
354
- this.mqtt.publish(data.topic, data.payload.toString(), data.options);
355
- }
209
+ this.mqtt = null;
210
+ });
211
+ }
212
+ getMqttNode() {
213
+ return __async(this, null, function* () {
214
+ const res = yield request.get(this.brokerLbUrl);
215
+ const url = res.body.data.url;
216
+ const port = res.body.data.wss_port;
217
+ return `wss://${url}:${port}/mqtt`;
218
+ });
219
+ }
220
+ get connected() {
221
+ if (this.mqtt == null) return false;
222
+ return this.mqtt.connected;
223
+ }
224
+ subscribe(...args) {
225
+ this.subscribtionBuffer.push(args);
226
+ while (this.mqtt != null && this.subscribtionBuffer.length > 0) {
227
+ const subs = this.subscribtionBuffer.shift();
228
+ if (subs != null) {
229
+ this.logger("subscribe topic", subs);
230
+ this.mqtt.subscribe(...subs);
356
231
  }
357
232
  }
358
- }, {
359
- key: "emit",
360
- value: function emit() {
361
- var _this$emitter;
362
- (_this$emitter = this.emitter).emit.apply(_this$emitter, arguments);
363
- }
364
- }, {
365
- key: "on",
366
- value: function on() {
367
- var _this$emitter2;
368
- (_this$emitter2 = this.emitter).on.apply(_this$emitter2, arguments);
369
- }
370
- }, {
371
- key: "off",
372
- value: function off() {
373
- var _this$emitter3;
374
- (_this$emitter3 = this.emitter).off.apply(_this$emitter3, arguments);
375
- }
376
- }, {
377
- key: "logEnabled",
378
- get: function get() {
379
- return this.core.debugMQTTMode;
380
- }
381
- }, {
382
- key: "logger",
383
- get: function get() {
384
- if (!this.core.debugMQTTMode) return this.noop;
385
- return console.log.bind(console, 'QRealtime ->');
386
- }
387
-
388
- // #region regexp
389
- }, {
390
- key: "reNewMessage",
391
- get: function get() {
392
- return /^(.+)\/c$/i;
393
- }
394
- }, {
395
- key: "reNotification",
396
- get: function get() {
397
- return /^(.+)\/n$/i;
398
- }
399
- }, {
400
- key: "reTyping",
401
- get: function get() {
402
- return /^r\/([\d]+)\/([\d]+)\/(.+)\/t$/i;
403
- }
404
- }, {
405
- key: "reRoomTyping",
406
- get: function get() {
407
- return /^r\/(.+)\/typing$/i;
408
- }
409
- }, {
410
- key: "reDelivery",
411
- get: function get() {
412
- return /^r\/([\d]+)\/([\d]+)\/(.+)\/d$/i;
413
- }
414
- }, {
415
- key: "reRead",
416
- get: function get() {
417
- return /^r\/([\d]+)\/([\d]+)\/(.+)\/r$/i;
418
- }
419
- }, {
420
- key: "reOnlineStatus",
421
- get: function get() {
422
- return /^u\/(.+)\/s$/i;
423
- }
424
- }, {
425
- key: "reChannelMessage",
426
- get: function get() {
427
- return /^(.+)\/(.+)\/c$/i;
428
- }
429
- }, {
430
- key: "reMessageUpdated",
431
- get: function get() {
432
- return /^(.+)\/update$/i;
433
- }
434
- // #endregion
435
- }, {
436
- key: "noop",
437
- value: function noop() {}
438
- }, {
439
- key: "newMessageHandler",
440
- value: function newMessageHandler(topic, message) {
441
- message = JSON.parse(message);
442
- this.logger('on:new-message', message);
443
- this.emit('new-message', message);
444
- }
445
- }, {
446
- key: "notificationHandler",
447
- value: function notificationHandler(topic, message) {
448
- var _this3 = this;
449
- this.logger('on:notification', message);
450
- message = JSON.parse(message);
451
- var data = message.payload.data;
452
- if ('deleted_messages' in data) {
453
- data.deleted_messages.forEach(function (message) {
454
- _this3.emit('comment-deleted', {
455
- roomId: message.room_id,
456
- commentUniqueIds: message.message_unique_ids,
457
- isForEveryone: true,
458
- isHard: true
459
- });
460
- });
461
- }
462
- if ('deleted_rooms' in data) {
463
- data.deleted_rooms.forEach(function (room) {
464
- _this3.emit('room-cleared', room);
465
- });
233
+ }
234
+ unsubscribe(...args) {
235
+ this.unsubscribtionBuffer.push(args);
236
+ while (this.mqtt != null && this.unsubscribtionBuffer.length > 0) {
237
+ const subs = this.unsubscribtionBuffer.shift();
238
+ if (subs != null) {
239
+ this.logger("unsubscribe topic", subs);
240
+ this.mqtt.unsubscribe(...subs);
466
241
  }
467
242
  }
468
-
469
- /**
470
- * @param {string} t
471
- * @param {string} message
472
- */
473
- }, {
474
- key: "roomTypingHandler",
475
- value: function roomTypingHandler(t, message) {
476
- var _t$match;
477
- this.logger('on:room-typing', t);
478
- // topic: r/{roomId}/typing
479
-
480
- var roomId = (_t$match = t.match(this.reRoomTyping)) === null || _t$match === void 0 ? void 0 : _t$match[1];
481
-
482
- /**
483
- * {
484
- * "room_id": "12333",
485
- * "status": "typing_on",// or "typing_off"
486
- * "sender_id": "user-987",
487
- * "sender_name": "Botku AI",
488
- * "text": "Analyzing your request..." // optional, max 50 chars
489
- * }
490
- * @typedef {Object} RoomTypingPayload
491
- * @property {number} room_id
492
- * @property {('typing_on'|'typing_off')} status
493
- * @property {string} sender_id
494
- * @property {string} text
495
- */
496
-
497
- /**
498
- * @type {RoomTypingPayload}
499
- */
500
- var parsedMessage = JSON.parse(message);
501
- this.emit('room-typing', _objectSpread(_objectSpread({}, parsedMessage), {}, {
502
- room_id: roomId
503
- }));
504
- }
505
- }, {
506
- key: "typingHandler",
507
- value: function typingHandler(t, message) {
508
- this.logger('on:typing', t);
509
- // r/{roomId}/{roomId}/{userId}/t
510
- var topic = t.match(this.reTyping);
511
- if (topic[3] === this.core.user_id) return;
512
- var userId = topic[3];
513
- var roomId = topic[1];
514
- this.emit('typing', {
515
- message: message,
516
- userId: userId,
517
- roomId: roomId
518
- });
519
-
520
- // TODO: Don't allow side-effect
521
- // it should be handled in the UI not core
522
- if (this.core.selected == null) return;
523
- if (message === '1' && roomId === this.core.selected.id) {
524
- var actor = this.core.selected.participants.find(function (it) {
525
- return it.email === userId;
526
- });
527
- if (actor == null) return;
528
- var displayName = actor.username;
529
- this.core.isTypingStatus = "".concat(displayName, " is typing ...");
530
- } else {
531
- this.core.isTypingStatus = null;
243
+ }
244
+ publish(topic, payload, options = {}) {
245
+ this.publishBuffer.push({ topic, payload, options });
246
+ while (this.mqtt != null && this.publishBuffer.length > 0) {
247
+ const data = this.publishBuffer.shift();
248
+ if (data != null) {
249
+ this.logger("publish to", data.topic, data.payload, data.options);
250
+ this.mqtt.publish(
251
+ data.topic,
252
+ data.payload.toString(),
253
+ data.options
254
+ );
532
255
  }
533
256
  }
534
- }, {
535
- key: "deliveryReceiptHandler",
536
- value: function deliveryReceiptHandler(t, message) {
537
- this.logger('on:delivered', t, message);
538
- // r/{roomId}/{roomId}/{userId}/d
539
- var topic = t.match(this.reDelivery);
540
- var data = message.split(':');
541
- var commentId = Number(data[0]);
542
- var commentUniqueId = data[1];
543
- var userId = topic[3];
544
- this.emit('message-delivered', {
545
- commentId: commentId,
546
- commentUniqueId: commentUniqueId,
547
- userId: userId
548
- });
549
- }
550
- }, {
551
- key: "readReceiptHandler",
552
- value: function readReceiptHandler(t, message) {
553
- this.logger('on:read', t, message);
554
- // r/{roomId}/{roomId}/{userId}/r
555
- var topic = t.match(this.reRead);
556
- var data = message.split(':');
557
- var commentId = Number(data[0]);
558
- var commentUniqueId = data[1];
559
- var userId = topic[3];
560
- this.emit('message-read', {
561
- commentId: commentId,
562
- commentUniqueId: commentUniqueId,
563
- userId: userId
564
- });
565
- }
566
- }, {
567
- key: "onlinePresenceHandler",
568
- value: function onlinePresenceHandler(topic, message) {
569
- this.logger('on:online-presence', topic, message);
570
- // u/guest-1002/s
571
- var topicData = this.reOnlineStatus.exec(topic);
572
- var userId = topicData[1];
573
- this.emit('presence', {
574
- message: message,
575
- userId: userId
257
+ }
258
+ emit(...args) {
259
+ this.emitter.emit(...args);
260
+ }
261
+ on(...args) {
262
+ this.emitter.on(...args);
263
+ }
264
+ off(...args) {
265
+ this.emitter.off(...args);
266
+ }
267
+ get logEnabled() {
268
+ return this.core.debugMQTTMode;
269
+ }
270
+ get logger() {
271
+ if (!this.core.debugMQTTMode) return this.noop;
272
+ return console.log.bind(console, "QRealtime ->");
273
+ }
274
+ // #region regexp
275
+ get reNewMessage() {
276
+ return /^(.+)\/c$/i;
277
+ }
278
+ get reNotification() {
279
+ return /^(.+)\/n$/i;
280
+ }
281
+ get reTyping() {
282
+ return /^r\/([\d]+)\/([\d]+)\/(.+)\/t$/i;
283
+ }
284
+ get reRoomTyping() {
285
+ return /^r\/(.+)\/typing$/i;
286
+ }
287
+ get reDelivery() {
288
+ return /^r\/([\d]+)\/([\d]+)\/(.+)\/d$/i;
289
+ }
290
+ get reRead() {
291
+ return /^r\/([\d]+)\/([\d]+)\/(.+)\/r$/i;
292
+ }
293
+ get reOnlineStatus() {
294
+ return /^u\/(.+)\/s$/i;
295
+ }
296
+ get reChannelMessage() {
297
+ return /^(.+)\/(.+)\/c$/i;
298
+ }
299
+ get reMessageUpdated() {
300
+ return /^(.+)\/update$/i;
301
+ }
302
+ // #endregion
303
+ noop() {
304
+ }
305
+ newMessageHandler(topic, message) {
306
+ message = JSON.parse(message);
307
+ this.logger("on:new-message", message);
308
+ this.emit("new-message", message);
309
+ }
310
+ notificationHandler(topic, message) {
311
+ this.logger("on:notification", message);
312
+ message = JSON.parse(message);
313
+ const data = message.payload.data;
314
+ if ("deleted_messages" in data) {
315
+ data.deleted_messages.forEach((message2) => {
316
+ this.emit("comment-deleted", {
317
+ roomId: message2.room_id,
318
+ commentUniqueIds: message2.message_unique_ids,
319
+ isForEveryone: true,
320
+ isHard: true
321
+ });
576
322
  });
577
323
  }
578
- }, {
579
- key: "channelMessageHandler",
580
- value: function channelMessageHandler(topic, message) {
581
- this.logger('on:channel-message', topic, message);
582
- this.emit('new-message', JSON.parse(message));
583
- }
584
- }, {
585
- key: "messageUpdatedHandler",
586
- value: function messageUpdatedHandler(topic, message) {
587
- message = JSON.parse(message);
588
- this.logger('on:message-updated', topic, message);
589
- this.emit('message:updated', message);
590
- }
591
-
592
- // #region old-methods
593
- }, {
594
- key: "subscribeChannel",
595
- value: function subscribeChannel(appId, uniqueId) {
596
- this.subscribe("".concat(appId, "/").concat(uniqueId, "/c"));
597
- }
598
- }, {
599
- key: "subscribeRoom",
600
- value: function subscribeRoom(roomId) {
601
- if (this.core.selected == null) return;
602
- roomId = roomId || this.core.selected.id;
603
- this.subscribe("r/".concat(roomId, "/typing"));
604
- this.subscribe("r/".concat(roomId, "/").concat(roomId, "/+/t"));
605
- this.subscribe("r/".concat(roomId, "/").concat(roomId, "/+/d"));
606
- this.subscribe("r/".concat(roomId, "/").concat(roomId, "/+/r"));
607
- }
608
- }, {
609
- key: "unsubscribeRoom",
610
- value: function unsubscribeRoom(roomId) {
611
- if (this.core.selected == null) return;
612
- roomId = roomId || this.core.selected.id;
613
- this.unsubscribe("r/".concat(roomId, "/typing"));
614
- this.unsubscribe("r/".concat(roomId, "/").concat(roomId, "/+/t"));
615
- this.unsubscribe("r/".concat(roomId, "/").concat(roomId, "/+/d"));
616
- this.unsubscribe("r/".concat(roomId, "/").concat(roomId, "/+/r"));
617
- }
618
- }, {
619
- key: "subscribeTyping",
620
- get: function get() {
621
- return this.subscribeRoom.bind(this);
622
- }
623
- }, {
624
- key: "unsubscribeTyping",
625
- get: function get() {
626
- return this.unsubscribeRoom.bind(this);
627
- }
628
- }, {
629
- key: "subscribeUserChannel",
630
- value: function subscribeUserChannel() {
631
- this.subscribe("".concat(this.core.userData.token, "/c"));
632
- this.subscribe("".concat(this.core.userData.token, "/n"));
633
- this.subscribe("".concat(this.core.userData.token, "/update"));
634
- }
635
- }, {
636
- key: "subscribeUserChannelByToken",
637
- value: function subscribeUserChannelByToken(token) {
638
- this.subscribe("".concat(token, "/c"));
639
- this.subscribe("".concat(token, "/n"));
640
- this.subscribe("".concat(token, "/update"));
641
- }
642
- }, {
643
- key: "unsubscribeUserChannel",
644
- value: function unsubscribeUserChannel() {
645
- this.unsubscribe("".concat(this.core.userData.token, "/c"));
646
- this.unsubscribe("".concat(this.core.userData.token, "/n"));
647
- this.unsubscribe("".concat(this.core.userData.token, "/update"));
648
- }
649
- }, {
650
- key: "unsusbcribeUserChannelByToken",
651
- value: function unsusbcribeUserChannelByToken(token) {
652
- this.unsubscribe("".concat(token, "/c"));
653
- this.unsubscribe("".concat(token, "/n"));
654
- this.unsubscribe("".concat(token, "/update"));
655
- }
656
- }, {
657
- key: "publishPresence",
658
- value: function publishPresence(userId) {
659
- var isOnline = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
660
- isOnline ? this.publish("u/".concat(userId, "/s"), 1, {
661
- retain: true
662
- }) : this.publish("u/".concat(userId, "/s"), 0, {
663
- retain: true
324
+ if ("deleted_rooms" in data) {
325
+ data.deleted_rooms.forEach((room) => {
326
+ this.emit("room-cleared", room);
664
327
  });
665
328
  }
666
- }, {
667
- key: "disconnect",
668
- value: function disconnect() {
669
- this.publishPresence(this.core.userData.email, false);
670
- this.unsubscribe(Object.keys(this.mqtt._resubscribeTopics));
671
- }
672
- }, {
673
- key: "subscribeUserPresence",
674
- value: function subscribeUserPresence(userId) {
675
- this.subscribe("u/".concat(userId, "/s"));
676
- }
677
- }, {
678
- key: "unsubscribeUserPresence",
679
- value: function unsubscribeUserPresence(userId) {
680
- this.unsubscribe("u/".concat(userId, "/s"));
681
- }
682
- }, {
683
- key: "subscribeRoomPresence",
684
- get: function get() {
685
- return this.subscribeUserPresence.bind(this);
686
- }
687
- }, {
688
- key: "unsubscribeRoomPresence",
689
- get: function get() {
690
- return this.unsubscribeUserPresence.bind(this);
691
- }
692
- }, {
693
- key: "publishTyping",
694
- value: function publishTyping(status) {
695
- if (this.core.selected == null) return;
696
- var roomId = this.core.selected.id;
697
- var userId = this.core.user_id;
698
- this.publish("r/".concat(roomId, "/").concat(roomId, "/").concat(userId, "/t"), status);
329
+ }
330
+ /**
331
+ * @param {string} t
332
+ * @param {string} message
333
+ */
334
+ roomTypingHandler(t, message) {
335
+ var _a;
336
+ this.logger("on:room-typing", t);
337
+ let roomId = (_a = t.match(this.reRoomTyping)) == null ? void 0 : _a[1];
338
+ let parsedMessage = JSON.parse(message);
339
+ this.emit("room-typing", __spreadProps(__spreadValues({}, parsedMessage), { room_id: roomId }));
340
+ }
341
+ typingHandler(t, message) {
342
+ this.logger("on:typing", t);
343
+ const topic = t.match(this.reTyping);
344
+ if (topic[3] === this.core.user_id) return;
345
+ const userId = topic[3];
346
+ const roomId = topic[1];
347
+ this.emit("typing", {
348
+ message,
349
+ userId,
350
+ roomId
351
+ });
352
+ if (this.core.selected == null) return;
353
+ if (message === "1" && roomId === this.core.selected.id) {
354
+ const actor = this.core.selected.participants.find(
355
+ (it) => it.email === userId
356
+ );
357
+ if (actor == null) return;
358
+ const displayName = actor.username;
359
+ this.core.isTypingStatus = `${displayName} is typing ...`;
360
+ } else {
361
+ this.core.isTypingStatus = null;
699
362
  }
700
-
701
- // #endregion
702
- }]);
703
- }();
704
- module.exports = exports.default;
363
+ }
364
+ deliveryReceiptHandler(t, message) {
365
+ this.logger("on:delivered", t, message);
366
+ const topic = t.match(this.reDelivery);
367
+ const data = message.split(":");
368
+ const commentId = Number(data[0]);
369
+ const commentUniqueId = data[1];
370
+ const userId = topic[3];
371
+ this.emit("message-delivered", {
372
+ commentId,
373
+ commentUniqueId,
374
+ userId
375
+ });
376
+ }
377
+ readReceiptHandler(t, message) {
378
+ this.logger("on:read", t, message);
379
+ const topic = t.match(this.reRead);
380
+ const data = message.split(":");
381
+ const commentId = Number(data[0]);
382
+ const commentUniqueId = data[1];
383
+ const userId = topic[3];
384
+ this.emit("message-read", {
385
+ commentId,
386
+ commentUniqueId,
387
+ userId
388
+ });
389
+ }
390
+ onlinePresenceHandler(topic, message) {
391
+ this.logger("on:online-presence", topic, message);
392
+ const topicData = this.reOnlineStatus.exec(topic);
393
+ const userId = topicData[1];
394
+ this.emit("presence", { message, userId });
395
+ }
396
+ channelMessageHandler(topic, message) {
397
+ this.logger("on:channel-message", topic, message);
398
+ this.emit("new-message", JSON.parse(message));
399
+ }
400
+ messageUpdatedHandler(topic, message) {
401
+ message = JSON.parse(message);
402
+ this.logger("on:message-updated", topic, message);
403
+ this.emit("message:updated", message);
404
+ }
405
+ // #region old-methods
406
+ subscribeChannel(appId, uniqueId) {
407
+ this.subscribe(`${appId}/${uniqueId}/c`);
408
+ }
409
+ subscribeRoom(roomId) {
410
+ if (this.core.selected == null) return;
411
+ roomId = roomId || this.core.selected.id;
412
+ this.subscribe(`r/${roomId}/typing`);
413
+ this.subscribe(`r/${roomId}/${roomId}/+/t`);
414
+ this.subscribe(`r/${roomId}/${roomId}/+/d`);
415
+ this.subscribe(`r/${roomId}/${roomId}/+/r`);
416
+ }
417
+ unsubscribeRoom(roomId) {
418
+ if (this.core.selected == null) return;
419
+ roomId = roomId || this.core.selected.id;
420
+ this.unsubscribe(`r/${roomId}/typing`);
421
+ this.unsubscribe(`r/${roomId}/${roomId}/+/t`);
422
+ this.unsubscribe(`r/${roomId}/${roomId}/+/d`);
423
+ this.unsubscribe(`r/${roomId}/${roomId}/+/r`);
424
+ }
425
+ get subscribeTyping() {
426
+ return this.subscribeRoom.bind(this);
427
+ }
428
+ get unsubscribeTyping() {
429
+ return this.unsubscribeRoom.bind(this);
430
+ }
431
+ subscribeUserChannel() {
432
+ this.subscribe(`${this.core.userData.token}/c`);
433
+ this.subscribe(`${this.core.userData.token}/n`);
434
+ this.subscribe(`${this.core.userData.token}/update`);
435
+ }
436
+ subscribeUserChannelByToken(token) {
437
+ this.subscribe(`${token}/c`);
438
+ this.subscribe(`${token}/n`);
439
+ this.subscribe(`${token}/update`);
440
+ }
441
+ unsubscribeUserChannel() {
442
+ this.unsubscribe(`${this.core.userData.token}/c`);
443
+ this.unsubscribe(`${this.core.userData.token}/n`);
444
+ this.unsubscribe(`${this.core.userData.token}/update`);
445
+ }
446
+ unsusbcribeUserChannelByToken(token) {
447
+ this.unsubscribe(`${token}/c`);
448
+ this.unsubscribe(`${token}/n`);
449
+ this.unsubscribe(`${token}/update`);
450
+ }
451
+ publishPresence(userId, isOnline = true) {
452
+ isOnline ? this.publish(`u/${userId}/s`, 1, { retain: true }) : this.publish(`u/${userId}/s`, 0, { retain: true });
453
+ }
454
+ disconnect() {
455
+ this.publishPresence(this.core.userData.email, false);
456
+ this.unsubscribe(Object.keys(this.mqtt._resubscribeTopics));
457
+ }
458
+ subscribeUserPresence(userId) {
459
+ this.subscribe(`u/${userId}/s`);
460
+ }
461
+ unsubscribeUserPresence(userId) {
462
+ this.unsubscribe(`u/${userId}/s`);
463
+ }
464
+ get subscribeRoomPresence() {
465
+ return this.subscribeUserPresence.bind(this);
466
+ }
467
+ get unsubscribeRoomPresence() {
468
+ return this.unsubscribeUserPresence.bind(this);
469
+ }
470
+ publishTyping(status) {
471
+ if (this.core.selected == null) return;
472
+ const roomId = this.core.selected.id;
473
+ const userId = this.core.user_id;
474
+ this.publish(`r/${roomId}/${roomId}/${userId}/t`, status);
475
+ }
476
+ // #endregion
477
+ }
478
+ module.exports = MqttAdapter;