qiscus-sdk-core 2.16.0 → 2.16.2

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.
package/lib/index.js CHANGED
@@ -1,95 +1,106 @@
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 _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
11
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
12
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
13
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
14
- var _superagent = _interopRequireDefault(require("superagent"));
15
- var _mitt = _interopRequireDefault(require("mitt"));
16
- var _is = _interopRequireDefault(require("./lib/is"));
17
- var _format = _interopRequireDefault(require("date-fns/format"));
18
- var _distance_in_words_to_now = _interopRequireDefault(require("date-fns/distance_in_words_to_now"));
19
- var _Comment = _interopRequireDefault(require("./lib/Comment"));
20
- var _Room = _interopRequireDefault(require("./lib/Room"));
21
- var _http = _interopRequireDefault(require("./lib/adapters/http"));
22
- var _auth = _interopRequireDefault(require("./lib/adapters/auth"));
23
- var _user = _interopRequireDefault(require("./lib/adapters/user"));
24
- var _room = _interopRequireDefault(require("./lib/adapters/room"));
25
- var _mqtt = _interopRequireDefault(require("./lib/adapters/mqtt"));
26
- var _customEvent = _interopRequireDefault(require("./lib/adapters/custom-event"));
27
- var _sync = _interopRequireDefault(require("./lib/adapters/sync"));
28
- var _utils = require("./lib/utils");
29
- var _util = require("./lib/util");
30
- var _package = _interopRequireDefault(require("../package.json"));
31
- var _hook = require("./lib/adapters/hook");
32
- var _expiredToken = require("./lib/adapters/expired-token");
33
- 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; }
34
- 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; }
35
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
36
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
37
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
38
- // helper for setup publishOnlinePresence status
39
- var setBackToOnline;
40
- var UpdateCommentStatusMode = Object.freeze({
41
- disabled: 'UpdateCommentStatusMode.disabled',
42
- throttled: 'UpdateCommentStatusMode.throttled',
43
- enabled: 'UpdateCommentStatusMode.enabled'
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 nanoid = require("nanoid");
43
+ const request = require("superagent");
44
+ const mitt = require("mitt");
45
+ const is = require("./lib/is.js");
46
+ const format = require("date-fns/format");
47
+ const distanceInWordsToNow = require("date-fns/distance_in_words_to_now");
48
+ const Comment = require("./lib/Comment.js");
49
+ const Room = require("./lib/Room.js");
50
+ const http = require("./lib/adapters/http.js");
51
+ const auth = require("./lib/adapters/auth.js");
52
+ const user = require("./lib/adapters/user.js");
53
+ const room = require("./lib/adapters/room.js");
54
+ const mqtt = require("./lib/adapters/mqtt.js");
55
+ const customEvent = require("./lib/adapters/custom-event.js");
56
+ const sync = require("./lib/adapters/sync.js");
57
+ const utils = require("./lib/utils.js");
58
+ const util = require("./lib/util.js");
59
+ const Package = require("../package.json");
60
+ const hook = require("./lib/adapters/hook.js");
61
+ const expiredToken = require("./lib/adapters/expired-token.js");
62
+ let setBackToOnline;
63
+ const UpdateCommentStatusMode = Object.freeze({
64
+ disabled: "UpdateCommentStatusMode.disabled",
65
+ throttled: "UpdateCommentStatusMode.throttled",
66
+ enabled: "UpdateCommentStatusMode.enabled"
44
67
  });
45
-
46
- /**
47
- * Qiscus Web SDK Core Class
48
- *
49
- * @export
50
- * @class QiscusSDK
51
- */
52
- var QiscusSDK = /*#__PURE__*/function () {
68
+ const _QiscusSDK = class _QiscusSDK {
53
69
  /**
54
70
  * Creates an instance of QiscusSDK.
55
71
  */
56
- function QiscusSDK() {
57
- var _this = this;
58
- (0, _classCallCheck2["default"])(this, QiscusSDK);
59
- (0, _defineProperty2["default"])(this, "_pendingComments", []);
72
+ constructor() {
73
+ __publicField(this, "_pendingComments", []);
60
74
  // count of how much does a comment has been retried
61
- (0, _defineProperty2["default"])(this, "_pendingCommentsCount", {});
62
- (0, _defineProperty2["default"])(this, "_readComment", function (roomId, commentId) {
63
- return _this._updateStatus(roomId, commentId);
64
- });
65
- (0, _defineProperty2["default"])(this, "_readCommentT", this._throttle(function (roomId, commentId) {
66
- _this._updateStatus(roomId, commentId);
67
- }, function () {
68
- return _this._throttleDelay;
69
- }));
70
- (0, _defineProperty2["default"])(this, "_deliverComment", function (roomId, commentId) {
71
- return _this._updateStatus(roomId, undefined, commentId);
72
- });
73
- (0, _defineProperty2["default"])(this, "_deliverCommentT", this._throttle(function (roomId, commentId) {
74
- _this._updateStatus(roomId, undefined, commentId);
75
- }, function () {
76
- return _this._throttleDelay;
77
- }));
78
- this.events = (0, _mitt["default"])();
75
+ __publicField(this, "_pendingCommentsCount", {});
76
+ __publicField(this, "_readComment", (roomId, commentId) => this._updateStatus(roomId, commentId));
77
+ __publicField(this, "_readCommentT", this._throttle(
78
+ (roomId, commentId) => {
79
+ this._updateStatus(roomId, commentId);
80
+ },
81
+ () => this._throttleDelay
82
+ ));
83
+ __publicField(this, "_deliverComment", (roomId, commentId) => this._updateStatus(roomId, void 0, commentId));
84
+ __publicField(this, "_deliverCommentT", this._throttle(
85
+ (roomId, commentId) => {
86
+ this._updateStatus(roomId, void 0, commentId);
87
+ },
88
+ () => this._throttleDelay
89
+ ));
90
+ this.events = mitt();
79
91
  this.rooms = [];
80
92
  this.selected = null;
81
93
  this.room_name_id_map = {};
82
94
  this.pendingCommentId = 0;
83
95
  this.uploadedFiles = [];
84
96
  this.chatmateStatus = null;
85
- this.version = "WEB_".concat(_package["default"].version);
97
+ this.version = `WEB_${Package.version}`;
86
98
  this.userData = {};
87
- // SDK Configuration
88
99
  this.AppId = null;
89
- this.baseURL = 'https://api.qiscus.com';
90
- this.mqttURL = 'wss://realtime-jogja.qiscus.com:1886/mqtt';
91
- this.brokerLbUrl = 'https://realtime-lb.qiscus.com';
92
- this.syncOnConnect = 10000;
100
+ this.baseURL = "https://api.qiscus.com";
101
+ this.mqttURL = "wss://realtime-jogja.qiscus.com:1886/mqtt";
102
+ this.brokerLbUrl = "https://realtime-lb.qiscus.com";
103
+ this.syncOnConnect = 1e4;
93
104
  this.enableEventReport = false;
94
105
  this.enableRealtime = true;
95
106
  this.enableRealtimeCheck = true;
@@ -101,2752 +112,1911 @@ var QiscusSDK = /*#__PURE__*/function () {
101
112
  this.customEventAdapter = null;
102
113
  this.isInit = false;
103
114
  this.isSynced = false;
104
- this.syncInterval = 5000;
105
- this.sync = 'socket'; // possible values 'socket', 'http', 'both'
115
+ this.syncInterval = 5e3;
116
+ this.sync = "socket";
106
117
  this.enableLb = true;
107
118
  this.httpsync = null;
108
119
  this.eventsync = null;
109
120
  this.extras = null;
110
121
  this.last_received_comment_id = 0;
111
- this.googleMapKey = '';
122
+ this.googleMapKey = "";
112
123
  this.options = {
113
124
  avatar: true
114
125
  };
115
126
  this.isConfigLoaded = false;
116
- this.updateCommentStatusMode = QiscusSDK.UpdateCommentStatusMode.enabled;
127
+ this.updateCommentStatusMode = _QiscusSDK.UpdateCommentStatusMode.enabled;
117
128
  this.updateCommentStatusThrottleDelay = 300;
118
-
119
- // UI related Properties
120
129
  this.UI = {};
121
- this.mode = 'widget';
130
+ this.mode = "widget";
122
131
  this.avatar = true;
123
132
  this.plugins = [];
124
133
  this.isLogin = false;
125
134
  this.isLoading = false;
126
135
  this.isInit = false;
127
136
  this.emoji = false;
128
- this.isTypingStatus = '';
137
+ this.isTypingStatus = "";
129
138
  this.customTemplate = false;
130
139
  this.templateFunction = null;
131
140
  this.debugMode = false;
132
141
  this.debugMQTTMode = false;
133
142
  this._customHeader = {};
134
143
  this._forceEnableSync = true;
135
-
136
- // to prevent double receive newmessages callback
137
144
  this.lastReceiveMessages = [];
138
- this._hookAdapter = (0, _hook.hookAdapterFactory)();
145
+ this._hookAdapter = hook.hookAdapterFactory();
139
146
  this._uploadURL = null;
140
147
  this._autoRefreshToken = false;
141
148
  }
142
-
143
149
  // this.uploadURL = `${this.baseURL}/api/v2/sdk/upload`
144
- return (0, _createClass2["default"])(QiscusSDK, [{
145
- key: "uploadURL",
146
- get: function get() {
147
- return this._uploadURL || "".concat(this.baseURL, "/api/v2/sdk/upload");
148
- },
149
- set: function set(uploadURL) {
150
- this._uploadURL = uploadURL;
151
- }
152
-
153
- /**
154
- * Initializing the SDK, set Event Listeners (callbacks)
155
- * @param {any} config - Qiscus SDK Configurations
156
- * @return {Promise<void>}
157
- */
158
- }, {
159
- key: "init",
160
- value: (function () {
161
- var _init = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee3(config) {
162
- var _this2 = this,
163
- _config$withConfig;
164
- var isDifferentBaseUrl, isDifferentMqttUrl, isDifferentBrokerLbUrl, setterHelper, mqttWssCheck;
165
- return _regenerator["default"].wrap(function (_context3) {
166
- while (1) switch (_context3.prev = _context3.next) {
167
- case 0:
168
- if (config.AppId) {
169
- _context3.next = 1;
170
- break;
171
- }
172
- throw new Error('Please provide valid AppId');
173
- case 1:
174
- this.AppId = config.AppId;
175
-
176
- // We need to disable realtime load balancing if user are using custom server
177
- // and did not provide a brokerLbUrl
178
- isDifferentBaseUrl = config.baseURL != null && this.baseURL !== config.baseURL;
179
- isDifferentMqttUrl = config.mqttURL != null && this.mqttURL !== config.mqttURL;
180
- isDifferentBrokerLbUrl = config.brokerLbURL != null && this.brokerLbUrl !== config.brokerLbURL; // disable realtime lb if user change baseUrl or mqttUrl but did not change
181
- // broker lb url
182
- if ((isDifferentBaseUrl || isDifferentMqttUrl) && !isDifferentBrokerLbUrl) {
183
- this.logger('' + 'force disable load balancing for realtime server, because ' + '`baseURL` or `mqttURL` get changed but ' + 'did not provide `brokerLbURL`');
184
- this.enableLb = false;
185
- } else if (config.enableRealtimeLB != null) {
186
- this.enableLb = config.enableRealtimeLB;
187
- }
188
- if (config.updateCommentStatusMode != null) this.updateCommentStatusMode = config.updateCommentStatusMode;
189
- if (config.updateCommentStatusThrottleDelay != null) this.updateCommentStatusThrottleDelay = config.updateCommentStatusThrottleDelay;
190
- if (config.baseURL) this.baseURL = config.baseURL;
191
- if (config.mqttURL) this.mqttURL = config.brokerUrl || config.mqttURL;
192
- if (config.mqttURL) this.brokerUrl = config.brokerUrl || config.mqttURL;
193
- if (config.brokerLbURL) this.brokerLbUrl = config.brokerLbURL;
194
- if (config.uploadURL) this.uploadURL = config.uploadURL;
195
- if (config.sync) this.sync = config.sync;
196
- if (config.mode) this.mode = config.mode;
197
- if (config.syncInterval) this.syncInterval = config.syncInterval || 5000;
198
- if (config.googleMapKey) this.googleMapKey = config.googleMapKey;
199
- if (config.allowedFileTypes) {
200
- this.allowedFileTypes = config.allowedFileTypes;
201
- }
202
- // Let's initialize the app based on options
203
- if (config.options) {
204
- this.options = Object.assign({}, this.options, config.options);
205
- }
206
- if (config.customTemplate) this.customTemplate = config.customTemplate;
207
- if (config.templateFunction) {
208
- this.templateFunction = config.templateFunction;
209
- }
210
- if (config.syncInterval != null) this.syncInterval = config.syncInterval;
211
- // this._customHeader = {}
212
-
213
- // set appConfig
214
- this.HTTPAdapter = new _http["default"]({
215
- baseURL: this.baseURL,
216
- AppId: this.AppId,
217
- userId: this.user_id,
218
- version: this.version,
219
- getCustomHeader: function getCustomHeader() {
220
- return _this2._customHeader;
221
- }
222
- });
223
-
224
- /**
225
- * @callback SetterCallback
226
- * @param {string | number} value
227
- * @return void
228
- */
229
- /**
230
- * @typedef {string | number | boolean | null} Parameter
231
- */
232
- /**
233
- *
234
- * @param {Parameter} fromUser
235
- * @param {Parameter} fromServer
236
- * @param {Parameter} defaultValue
237
- * @return {Parameter}
238
- */
239
- setterHelper = function setterHelper(fromUser, fromServer, defaultValue) {
240
- if (fromServer === '') {
241
- if (fromUser != null) {
242
- if (typeof fromUser !== 'string') return fromUser;
243
- if (fromUser.length > 0) return fromUser;
244
- }
245
- }
246
- if (fromServer != null) {
247
- if (fromServer.length > 0) return fromServer;
248
- if (typeof fromServer !== 'string') return fromServer;
249
- }
250
- return defaultValue;
251
- };
252
- mqttWssCheck = function mqttWssCheck(mqttResult) {
253
- if (mqttResult.includes('wss://')) {
254
- return mqttResult;
255
- } else {
256
- return "wss://".concat(mqttResult, ":1886/mqtt");
257
- }
258
- };
259
- this.withConfig = (_config$withConfig = config.withConfig) !== null && _config$withConfig !== void 0 ? _config$withConfig : true;
260
- if (!(this.withConfig === true)) {
261
- _context3.next = 3;
262
- break;
263
- }
264
- _context3.next = 2;
265
- return this.HTTPAdapter.get_request('api/v2/sdk/config').then(function (resp) {
266
- resp.status == 200 ? _this2.isConfigLoaded = true : _this2.isConfigLoaded = false;
267
- return resp.body.results;
268
- }).then(function (cfg) {
269
- var baseUrl = _this2.baseURL; // default value for baseUrl
270
- var brokerLbUrl = _this2.brokerLbUrl; // default value for brokerLbUrl
271
- var mqttUrl = _this2.mqttURL; // default value for brokerUrl
272
- var enableRealtime = _this2.enableRealtime; // default value for enableRealtime
273
- var enableRealtimeCheck = _this2.enableRealtimeCheck; // default value for enableRealtimeCheck
274
- var syncInterval = _this2.syncInterval; // default value for syncInterval
275
- var syncIntervalWhenConnected = _this2.syncOnConnect; // default value for syncIntervalWhenConnected
276
- var enableEventReport = _this2.enableEventReport; // default value for enableEventReport
277
- var configExtras = {}; // default value for extras
278
-
279
- _this2.baseURL = setterHelper(config.baseURL, cfg.base_url, baseUrl);
280
- _this2.brokerLbUrl = setterHelper(config.brokerLbURL, cfg.broker_lb_url, brokerLbUrl);
281
- _this2.mqttURL = mqttWssCheck(setterHelper(config.mqttURL, cfg.broker_url, mqttUrl));
282
- _this2.enableRealtime = setterHelper(config.enableRealtime, cfg.enable_realtime, enableRealtime);
283
- _this2.syncInterval = setterHelper(config.syncInterval, cfg.sync_interval, syncInterval);
284
- _this2.syncOnConnect = setterHelper(config.syncOnConnect, cfg.sync_on_connect, syncIntervalWhenConnected);
285
- // since user never provide this value
286
- _this2.enableRealtimeCheck = setterHelper(null, cfg.enable_realtime_check, enableRealtimeCheck);
287
- _this2.enableEventReport = setterHelper(null, cfg.enable_event_report, enableEventReport);
288
- _this2.extras = setterHelper(null, cfg.extras, configExtras);
289
- _this2.enableSync = setterHelper(null, cfg.enable_sync, _this2.enableSync);
290
- _this2.enableSyncEvent = setterHelper(null, cfg.enable_sync_event, _this2.enableSyncEvent);
291
- _this2._autoRefreshToken = setterHelper(null, cfg.auto_refresh_token, false);
292
- })["catch"](function (err) {
293
- _this2.logger('got error when trying to get app config', err);
294
- _this2.isConfigLoaded = true;
295
- });
296
- case 2:
297
- _context3.next = 4;
298
- break;
299
- case 3:
300
- this.isConfigLoaded = true;
301
- case 4:
302
- // set Event Listeners
303
-
304
- this._getMqttClientId = function () {
305
- return "".concat(_this2.AppId, "_").concat(_this2.user_id, "_").concat(Date.now());
306
- };
307
- this.realtimeAdapter = new _mqtt["default"](this.mqttURL, this, this.isLogin, {
308
- brokerLbUrl: this.brokerLbUrl,
309
- enableLb: this.enableLb,
310
- shouldConnect: this.enableRealtime,
311
- getClientId: this._getMqttClientId
312
- });
313
- this.realtimeAdapter.on('connected', function () {
314
- if (_this2.isLogin || !_this2.realtimeAdapter.connected) {
315
- _this2.last_received_comment_id = _this2.userData.last_comment_id;
316
- _this2.updateLastReceivedComment(_this2.last_received_comment_id);
317
- }
318
- });
319
- this.realtimeAdapter.on('close', function () {});
320
- this.realtimeAdapter.on('reconnect', function () {
321
- var _this2$options$onReco, _this2$options;
322
- (_this2$options$onReco = (_this2$options = _this2.options).onReconnectCallback) === null || _this2$options$onReco === void 0 || _this2$options$onReco.call(_this2$options);
323
- });
324
- this.realtimeAdapter.on('message-delivered', function (_ref) {
325
- var commentId = _ref.commentId,
326
- commentUniqueId = _ref.commentUniqueId,
327
- userId = _ref.userId;
328
- return _this2._setDelivered(commentId, commentUniqueId, userId);
329
- });
330
- this.realtimeAdapter.on('message-read', function (_ref2) {
331
- var commentId = _ref2.commentId,
332
- commentUniqueId = _ref2.commentUniqueId,
333
- userId = _ref2.userId;
334
- return _this2._setRead(commentId, commentUniqueId, userId);
335
- });
336
- this.realtimeAdapter.on('new-message', /*#__PURE__*/function () {
337
- var _ref3 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(message) {
338
- return _regenerator["default"].wrap(function (_context) {
339
- while (1) switch (_context.prev = _context.next) {
340
- case 0:
341
- _context.next = 1;
342
- return _this2._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, message);
343
- case 1:
344
- message = _context.sent;
345
- _this2.events.emit('newmessages', [message]);
346
- case 2:
347
- case "end":
348
- return _context.stop();
349
- }
350
- }, _callee);
351
- }));
352
- return function (_x2) {
353
- return _ref3.apply(this, arguments);
354
- };
355
- }());
356
- this.realtimeAdapter.on('presence', function (data) {
357
- return _this2.events.emit('presence', data);
358
- });
359
- this.realtimeAdapter.on('comment-deleted', function (data) {
360
- return _this2.events.emit('comment-deleted', data);
361
- });
362
- this.realtimeAdapter.on('room-cleared', function (data) {
363
- return _this2.events.emit('room-cleared', data);
364
- });
365
- this.realtimeAdapter.on('typing', function (data) {
366
- return _this2.events.emit('typing', {
367
- message: data.message,
368
- username: data.userId,
369
- room_id: data.roomId
370
- });
371
- });
372
- this.realtimeAdapter.on('message:updated', function (message) {
373
- if (_this2.options.messageUpdatedCallback != null) {
374
- _this2.options.messageUpdatedCallback(message);
375
- }
376
- });
377
- this.realtimeAdapter.on('room-typing', function (data) {
378
- _this2.events.emit('typing', {
379
- message: data.text,
380
- username: data.sender_name,
381
- email: data.sender_id,
382
- room_id: data.room_id
383
- });
384
- if (_this2.options.onRoomTypingCallback != null) {
385
- _this2.events.emit('room-typing', data);
386
- _this2.options.onRoomTypingCallback(data);
387
- }
388
- });
389
- this.syncAdapter = (0, _sync["default"])(function () {
390
- return _this2.HTTPAdapter;
391
- }, {
392
- getToken: function getToken() {
393
- return _this2.userData.token;
394
- },
395
- syncInterval: function syncInterval() {
396
- return _this2.syncInterval;
397
- },
398
- getShouldSync: function getShouldSync() {
399
- return _this2._forceEnableSync && _this2.isLogin && !_this2.realtimeAdapter.connected;
400
- },
401
- syncOnConnect: function syncOnConnect() {
402
- return _this2.syncOnConnect;
403
- },
404
- lastCommentId: function lastCommentId() {
405
- return _this2.last_received_comment_id;
406
- },
407
- statusLogin: function statusLogin() {
408
- return _this2.isLogin;
409
- },
410
- enableSync: function enableSync() {
411
- return _this2.enableSync;
412
- },
413
- enableSyncEvent: function enableSyncEvent() {
414
- return _this2.enableSyncEvent;
415
- }
416
- });
417
- this.syncAdapter.on('message.new', /*#__PURE__*/function () {
418
- var _ref4 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee2(message) {
419
- var index, _message;
420
- return _regenerator["default"].wrap(function (_context2) {
421
- while (1) switch (_context2.prev = _context2.next) {
422
- case 0:
423
- _context2.next = 1;
424
- return _this2._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, message);
425
- case 1:
426
- message = _context2.sent;
427
- if (_this2.selected != null) {
428
- index = _this2.selected.comments.findIndex(function (it) {
429
- return it.id === message.id || it.unique_id === message.unique_temp_id;
430
- });
431
- if (index === -1) {
432
- _message = new _Comment["default"](message);
433
- if (_message.room_id === _this2.selected.id) {
434
- _this2.selected.comments.push(_message);
435
- _this2.sortComments();
436
- }
437
- _this2.events.emit('newmessages', [message]);
438
- }
439
- } else {
440
- _this2.events.emit('newmessages', [message]);
441
- }
442
- case 2:
443
- case "end":
444
- return _context2.stop();
445
- }
446
- }, _callee2);
447
- }));
448
- return function (_x3) {
449
- return _ref4.apply(this, arguments);
450
- };
451
- }());
452
- this.syncAdapter.on('message.delivered', function (message) {
453
- _this2._setDelivered(message.comment_id, message.comment_unique_id, message.email);
454
- });
455
- this.syncAdapter.on('message.read', function (message) {
456
- _this2._setRead(message.comment_id, message.comment_unique_id, message.email);
457
- });
458
- this.syncAdapter.on('message.deleted', function (data) {
459
- data.deleted_messages.forEach(function (it) {
460
- _this2.events.emit('comment-deleted', {
461
- roomId: it.room_id,
462
- commentUniqueIds: it.message_unique_ids,
463
- isForEveryone: true,
464
- isHard: true
465
- });
466
- });
467
- });
468
- this.syncAdapter.on('room.cleared', function (data) {
469
- data.deleted_rooms.forEach(function (room) {
470
- _this2.events.emit('room-cleared', room);
471
- });
472
- });
473
- this.syncAdapter.on('synchronize', function () {
474
- _this2._pendingComments.forEach(function (m) {
475
- return _this2._retrySendComment(m);
476
- });
477
- });
478
- this.syncAdapter.on('last-message-id.new', function (id) {
479
- _this2.last_received_comment_id = id;
480
- });
481
- this.customEventAdapter = (0, _customEvent["default"])(this.realtimeAdapter, this.user_id);
482
- this.setEventListeners();
483
- case 5:
484
- case "end":
485
- return _context3.stop();
486
- }
487
- }, _callee3, this);
488
- }));
489
- function init(_x) {
490
- return _init.apply(this, arguments);
150
+ get uploadURL() {
151
+ return this._uploadURL || `${this.baseURL}/api/v2/sdk/upload`;
152
+ }
153
+ set uploadURL(uploadURL) {
154
+ this._uploadURL = uploadURL;
155
+ }
156
+ /**
157
+ * Initializing the SDK, set Event Listeners (callbacks)
158
+ * @param {any} config - Qiscus SDK Configurations
159
+ * @return {Promise<void>}
160
+ */
161
+ init(config) {
162
+ return __async(this, null, function* () {
163
+ var _a;
164
+ if (!config.AppId) throw new Error("Please provide valid AppId");
165
+ this.AppId = config.AppId;
166
+ const isDifferentBaseUrl = config.baseURL != null && this.baseURL !== config.baseURL;
167
+ const isDifferentMqttUrl = config.mqttURL != null && this.mqttURL !== config.mqttURL;
168
+ const isDifferentBrokerLbUrl = config.brokerLbURL != null && this.brokerLbUrl !== config.brokerLbURL;
169
+ if ((isDifferentBaseUrl || isDifferentMqttUrl) && !isDifferentBrokerLbUrl) {
170
+ this.logger(
171
+ "force disable load balancing for realtime server, because `baseURL` or `mqttURL` get changed but did not provide `brokerLbURL`"
172
+ );
173
+ this.enableLb = false;
174
+ } else if (config.enableRealtimeLB != null) {
175
+ this.enableLb = config.enableRealtimeLB;
491
176
  }
492
- return init;
493
- }())
494
- }, {
495
- key: "_setRead",
496
- value: function _setRead(messageId, messageUniqueId, userId) {
497
- if (this.selected == null) return;
498
- var room = this.selected;
499
- var message = room.comments.find(function (it) {
500
- return it.id === messageId || it.unique_id === messageUniqueId;
177
+ if (config.updateCommentStatusMode != null)
178
+ this.updateCommentStatusMode = config.updateCommentStatusMode;
179
+ if (config.updateCommentStatusThrottleDelay != null)
180
+ this.updateCommentStatusThrottleDelay = config.updateCommentStatusThrottleDelay;
181
+ if (config.baseURL) this.baseURL = config.baseURL;
182
+ if (config.mqttURL) this.mqttURL = config.brokerUrl || config.mqttURL;
183
+ if (config.mqttURL) this.brokerUrl = config.brokerUrl || config.mqttURL;
184
+ if (config.brokerLbURL) this.brokerLbUrl = config.brokerLbURL;
185
+ if (config.uploadURL) this.uploadURL = config.uploadURL;
186
+ if (config.sync) this.sync = config.sync;
187
+ if (config.mode) this.mode = config.mode;
188
+ if (config.syncInterval) this.syncInterval = config.syncInterval || 5e3;
189
+ if (config.googleMapKey) this.googleMapKey = config.googleMapKey;
190
+ if (config.allowedFileTypes) {
191
+ this.allowedFileTypes = config.allowedFileTypes;
192
+ }
193
+ if (config.options) {
194
+ this.options = Object.assign({}, this.options, config.options);
195
+ }
196
+ if (config.customTemplate) this.customTemplate = config.customTemplate;
197
+ if (config.templateFunction) {
198
+ this.templateFunction = config.templateFunction;
199
+ }
200
+ if (config.syncInterval != null) this.syncInterval = config.syncInterval;
201
+ this.HTTPAdapter = new http({
202
+ baseURL: this.baseURL,
203
+ AppId: this.AppId,
204
+ userId: this.user_id,
205
+ version: this.version,
206
+ getCustomHeader: () => this._customHeader
501
207
  });
502
- if (message == null) return;
503
- if (message.status === 'read') return;
504
- var options = {
505
- participants: room.participants,
506
- actor: userId,
507
- comment_id: messageId,
508
- activeActorId: this.user_id
509
- };
510
- room.comments.forEach(function (it) {
511
- if (it.id <= message.id) {
512
- it.markAsRead(options);
208
+ const setterHelper = (fromUser, fromServer, defaultValue) => {
209
+ if (fromServer === "") {
210
+ if (fromUser != null) {
211
+ if (typeof fromUser !== "string") return fromUser;
212
+ if (fromUser.length > 0) return fromUser;
213
+ }
513
214
  }
514
- });
515
- if (!message.isRead) return;
516
- this.events.emit('comment-read', {
517
- comment: message,
518
- userId: userId
519
- });
520
- }
521
- }, {
522
- key: "_setDelivered",
523
- value: function _setDelivered(messageId, messageUniqueId, userId) {
524
- if (this.selected == null) return;
525
- var room = this.selected;
526
- var message = room.comments.find(function (it) {
527
- return it.id === messageId || it.unique_id === messageUniqueId;
528
- });
529
- if (message == null) return;
530
- if (message.status === 'read') return;
531
- var options = {
532
- participants: room.participants,
533
- actor: userId,
534
- comment_id: messageId,
535
- activeActorId: this.user_id
215
+ if (fromServer != null) {
216
+ if (fromServer.length > 0) return fromServer;
217
+ if (typeof fromServer !== "string") return fromServer;
218
+ }
219
+ return defaultValue;
536
220
  };
537
- room.comments.forEach(function (it) {
538
- if (it.id <= message.id) {
539
- it.markAsDelivered(options);
221
+ const mqttWssCheck = (mqttResult) => {
222
+ if (mqttResult.includes("wss://")) {
223
+ return mqttResult;
224
+ } else {
225
+ return `wss://${mqttResult}:1886/mqtt`;
540
226
  }
541
- });
542
- if (!message.isDelivered) return;
543
- this.events.emit('comment-delivered', {
544
- comment: message,
545
- userId: userId
546
- });
547
- }
548
- }, {
549
- key: "setEventListeners",
550
- value: function setEventListeners() {
551
- var _this3 = this;
552
- var self = this;
553
- this.authAdapter = new _auth["default"](self.HTTPAdapter);
554
- if (this.userData.email != null) {
555
- this.authAdapter.userId = this.userData.email;
556
- }
557
- self.events.on('start-init', function () {
558
- self.HTTPAdapter = new _http["default"]({
559
- baseURL: self.baseURL,
560
- AppId: self.AppId,
561
- userId: self.user_id,
562
- version: self.version,
563
- getCustomHeader: function getCustomHeader() {
564
- return _this3._customHeader;
565
- }
227
+ };
228
+ this.withConfig = (_a = config.withConfig) != null ? _a : true;
229
+ if (this.withConfig === true) {
230
+ yield this.HTTPAdapter.get_request("api/v2/sdk/config").then((resp) => {
231
+ resp.status == 200 ? this.isConfigLoaded = true : this.isConfigLoaded = false;
232
+ return resp.body.results;
233
+ }).then((cfg) => {
234
+ const baseUrl = this.baseURL;
235
+ const brokerLbUrl = this.brokerLbUrl;
236
+ const mqttUrl = this.mqttURL;
237
+ const enableRealtime = this.enableRealtime;
238
+ const enableRealtimeCheck = this.enableRealtimeCheck;
239
+ const syncInterval = this.syncInterval;
240
+ const syncIntervalWhenConnected = this.syncOnConnect;
241
+ const enableEventReport = this.enableEventReport;
242
+ const configExtras = {};
243
+ this.baseURL = setterHelper(config.baseURL, cfg.base_url, baseUrl);
244
+ this.brokerLbUrl = setterHelper(
245
+ config.brokerLbURL,
246
+ cfg.broker_lb_url,
247
+ brokerLbUrl
248
+ );
249
+ this.mqttURL = mqttWssCheck(
250
+ setterHelper(config.mqttURL, cfg.broker_url, mqttUrl)
251
+ );
252
+ this.enableRealtime = setterHelper(
253
+ config.enableRealtime,
254
+ cfg.enable_realtime,
255
+ enableRealtime
256
+ );
257
+ this.syncInterval = setterHelper(
258
+ config.syncInterval,
259
+ cfg.sync_interval,
260
+ syncInterval
261
+ );
262
+ this.syncOnConnect = setterHelper(
263
+ config.syncOnConnect,
264
+ cfg.sync_on_connect,
265
+ syncIntervalWhenConnected
266
+ );
267
+ this.enableRealtimeCheck = setterHelper(
268
+ null,
269
+ cfg.enable_realtime_check,
270
+ enableRealtimeCheck
271
+ );
272
+ this.enableEventReport = setterHelper(
273
+ null,
274
+ cfg.enable_event_report,
275
+ enableEventReport
276
+ );
277
+ this.extras = setterHelper(null, cfg.extras, configExtras);
278
+ this.enableSync = setterHelper(null, cfg.enable_sync, this.enableSync);
279
+ this.enableSyncEvent = setterHelper(
280
+ null,
281
+ cfg.enable_sync_event,
282
+ this.enableSyncEvent
283
+ );
284
+ this._autoRefreshToken = setterHelper(
285
+ null,
286
+ cfg.auto_refresh_token,
287
+ false
288
+ );
289
+ }).catch((err) => {
290
+ this.logger("got error when trying to get app config", err);
291
+ this.isConfigLoaded = true;
566
292
  });
567
- self.HTTPAdapter.setToken(self.userData.token);
293
+ } else {
294
+ this.isConfigLoaded = true;
295
+ }
296
+ this._getMqttClientId = () => `${this.AppId}_${this.user_id}_${Date.now()}`;
297
+ this.realtimeAdapter = new mqtt(this.mqttURL, this, this.isLogin, {
298
+ brokerLbUrl: this.brokerLbUrl,
299
+ enableLb: this.enableLb,
300
+ shouldConnect: this.enableRealtime,
301
+ getClientId: this._getMqttClientId
568
302
  });
569
- self.events.on('room-changed', function (room) {
570
- _this3.logging('room changed', room);
571
- if (self.options.roomChangedCallback) {
572
- self.options.roomChangedCallback(room);
303
+ this.realtimeAdapter.on("connected", () => {
304
+ if (this.isLogin || !this.realtimeAdapter.connected) {
305
+ this.last_received_comment_id = this.userData.last_comment_id;
306
+ this.updateLastReceivedComment(this.last_received_comment_id);
573
307
  }
574
308
  });
575
- self.events.on('file-uploaded', function (url) {
576
- if (self.options.fileUploadedCallback) {
577
- self.options.fileUploadedCallback(url);
578
- }
309
+ this.realtimeAdapter.on("close", () => {
579
310
  });
580
- self.events.on('profile-updated', function (user) {
581
- self.username = user.name;
582
- self.avatar_url = user.avatar_url;
583
- if (self.options.updateProfileCallback) {
584
- self.options.updateProfileCallback(user);
585
- }
311
+ this.realtimeAdapter.on("reconnect", () => {
312
+ var _a2, _b;
313
+ (_b = (_a2 = this.options).onReconnectCallback) == null ? void 0 : _b.call(_a2);
586
314
  });
587
-
588
- /**
589
- * This event will be called when there's new post messages
590
- * @param {string} data - JSON Response from SYNC API / MQTT
591
- * @return {void}
592
- */
593
- self.events.on('newmessages', function (comments) {
594
- // let's convert the data into something we can use
595
- // first we need to make sure we sort this data out based on room_id
596
- _this3.logging('newmessages', comments);
597
- var lastReceivedMessageNotEmpty = _this3.lastReceiveMessages.length > 0;
598
- if (lastReceivedMessageNotEmpty && _this3.lastReceiveMessages[0].unique_temp_id === comments[0].unique_temp_id) {
599
- _this3.logging('lastReceiveMessages double', comments);
600
- return;
315
+ this.realtimeAdapter.on(
316
+ "message-delivered",
317
+ ({ commentId, commentUniqueId, userId }) => this._setDelivered(commentId, commentUniqueId, userId)
318
+ );
319
+ this.realtimeAdapter.on(
320
+ "message-read",
321
+ ({ commentId, commentUniqueId, userId }) => this._setRead(commentId, commentUniqueId, userId)
322
+ );
323
+ this.realtimeAdapter.on("new-message", (message) => __async(this, null, function* () {
324
+ message = yield this._hookAdapter.trigger(
325
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
326
+ message
327
+ );
328
+ this.events.emit("newmessages", [message]);
329
+ }));
330
+ this.realtimeAdapter.on(
331
+ "presence",
332
+ (data) => this.events.emit("presence", data)
333
+ );
334
+ this.realtimeAdapter.on(
335
+ "comment-deleted",
336
+ (data) => this.events.emit("comment-deleted", data)
337
+ );
338
+ this.realtimeAdapter.on(
339
+ "room-cleared",
340
+ (data) => this.events.emit("room-cleared", data)
341
+ );
342
+ this.realtimeAdapter.on(
343
+ "typing",
344
+ (data) => this.events.emit("typing", {
345
+ message: data.message,
346
+ username: data.userId,
347
+ room_id: data.roomId
348
+ })
349
+ );
350
+ this.realtimeAdapter.on("message:updated", (message) => {
351
+ if (this.options.messageUpdatedCallback != null) {
352
+ this.options.messageUpdatedCallback(message);
601
353
  }
602
- _this3.lastReceiveMessages = comments;
603
- self._callNewMessagesCallback(comments);
604
- comments.forEach(function (comment) {
605
- // we have this comment, so means it's already delivered, update it's delivered status
606
- self.receiveComment(comment.room_id, comment.id);
607
- var isActiveRoom = self.selected ? comment.room_id === self.selected.id : false;
608
- var isAlreadyRead = comment.id <= self.last_received_comment_id;
609
-
610
- // kalau comment ini ada di currently selected
611
- if (isActiveRoom) {
612
- var selected = self.selected;
613
- var lastComment = self.selected.comments[self.selected.comments.length - 1];
614
- // kirim event read kalau ini bukan komen kita sendiri
615
- if (!lastComment.isPending && !isAlreadyRead && self.user_id !== comment.email) {
616
- self.readComment(comment.room_id, comment.id);
617
- }
618
- // pastiin sync
619
- var roomLastCommentId = lastComment.id;
620
- var commentBeforeThis = self.selected.comments.find(function (c) {
621
- return c.id === lastComment.comment_before_id;
622
- });
623
- if (!lastComment.isPending && !commentBeforeThis) {
624
- _this3.logging('comment before id not found! ', comment.comment_before_id);
625
- // need to fix, these method does not work
626
- self.synchronize(roomLastCommentId);
627
- }
628
- // pastikan dulu komen ini komen baru, klo komen lama ga usah panggil cb
629
- var pendingComment = new _Comment["default"](comment);
630
- // fetch the comment inside the room
631
- selected.receiveComment(pendingComment);
632
- selected.last_comment_id = pendingComment.id;
633
- selected.last_comment_message = pendingComment.message;
634
- }
635
-
636
- // let's update last_received_comment_id
637
- self.updateLastReceivedComment(comment.id);
638
- _this3.sortComments();
639
- });
640
354
  });
641
-
642
- /**
643
- * This event will be called when login is sucess
644
- * Basically, it sets up necessary properties for qiscusSDK
645
- */
646
- this.events.on('login-success', function (response) {
647
- _this3.isLogin = true;
648
- _this3.userData = response.user;
649
- _this3.last_received_comment_id = _this3.userData.last_comment_id;
650
- if (!_this3.realtimeAdapter.connected) _this3.updateLastReceivedComment(_this3.last_received_comment_id);
651
-
652
- // now that we have the token, etc, we need to set all our adapters
653
- _this3.HTTPAdapter = new _http["default"]({
654
- baseURL: _this3.baseURL,
655
- AppId: _this3.AppId,
656
- userId: _this3.user_id,
657
- version: _this3.version,
658
- getCustomHeader: function getCustomHeader() {
659
- return _this3._customHeader;
660
- },
661
- expiredTokenAdapterGetter: function expiredTokenAdapterGetter() {
662
- return _this3.expiredTokenAdapter;
663
- }
664
- });
665
- _this3.HTTPAdapter.setToken(_this3.userData.token);
666
- var user = response.user;
667
- _this3._delayedSync = (0, _utils.delayed)(function () {
668
- _this3.synchronize();
669
- _this3.synchronizeEvent();
670
- }, 500);
671
- _this3.expiredTokenAdapter = new _expiredToken.ExpiredTokenAdapter({
672
- httpAdapter: _this3.HTTPAdapter,
673
- refreshToken: user.refresh_token,
674
- expiredAt: user.token_expires_at,
675
- userId: _this3.user_id,
676
- onTokenRefreshed: function onTokenRefreshed(token, refreshToken, expiredAt, oldToken) {
677
- _this3.userData.token = token;
678
- _this3.userData.refresh_token = refreshToken;
679
- _this3.userData.token_expires_at = expiredAt === null || expiredAt === void 0 ? void 0 : expiredAt.toJSON();
680
- _this3.events.emit('token-refreshed', {
681
- token: token,
682
- refreshToken: refreshToken,
683
- expiredAt: expiredAt,
684
- oldToken: oldToken
685
- });
686
- _this3.realtimeAdapter.unsusbcribeUserChannelByToken(oldToken);
687
- _this3.realtimeAdapter.subscribeUserChannelByToken(token);
688
- _this3._delayedSync();
689
- },
690
- getAuthenticationStatus: function getAuthenticationStatus() {
691
- return _this3.user_id != null && _this3.isLogin;
692
- }
355
+ this.realtimeAdapter.on("room-typing", (data) => {
356
+ this.events.emit("typing", {
357
+ message: data.text,
358
+ username: data.sender_name,
359
+ email: data.sender_id,
360
+ room_id: data.room_id
693
361
  });
694
- _this3.userAdapter = new _user["default"](_this3.HTTPAdapter);
695
- _this3.roomAdapter = new _room["default"](_this3.HTTPAdapter);
696
- _this3.realtimeAdapter.subscribeUserChannel();
697
- if (_this3.presensePublisherId != null && _this3.presensePublisherId !== -1) {
698
- clearInterval(_this3.presensePublisherId);
699
- }
700
- _this3.presensePublisherId = setInterval(function () {
701
- _this3.realtimeAdapter.publishPresence(_this3.user_id, true);
702
- }, 3500);
703
-
704
- // if (this.sync === "http" || this.sync === "both") this.activateSync();
705
- if (_this3.options.loginSuccessCallback) {
706
- _this3.options.loginSuccessCallback(response);
707
- }
708
- _this3.authAdapter.userId = _this3.userData.email;
709
- _this3.authAdapter.refreshToken = _this3.userData.refresh_token;
710
- _this3.authAdapter.autoRefreshToken = _this3._autoRefreshToken;
711
- });
712
-
713
- /**
714
- * Called when there's something wrong when connecting to qiscus SDK
715
- */
716
- self.events.on('login-error', function (error) {
717
- if (self.options.loginErrorCallback) {
718
- self.options.loginErrorCallback(error);
362
+ if (this.options.onRoomTypingCallback != null) {
363
+ this.events.emit("room-typing", data);
364
+ this.options.onRoomTypingCallback(data);
719
365
  }
720
366
  });
721
- self.events.on('token-refreshed', function (param) {
722
- var _this3$options$authTo, _this3$options;
723
- (_this3$options$authTo = (_this3$options = _this3.options).authTokenRefreshedCallback) === null || _this3$options$authTo === void 0 || _this3$options$authTo.call(_this3$options, param);
367
+ this.syncAdapter = sync(() => this.HTTPAdapter, {
368
+ syncInterval: () => this.syncInterval,
369
+ getShouldSync: () => this._forceEnableSync && this.isLogin && !this.realtimeAdapter.connected,
370
+ syncOnConnect: () => this.syncOnConnect,
371
+ lastCommentId: () => this.last_received_comment_id,
372
+ statusLogin: () => this.isLogin,
373
+ enableSync: () => this.enableSync,
374
+ enableSyncEvent: () => this.enableSyncEvent
724
375
  });
725
- self.events.on('room-cleared', function (room) {
726
- // find room
727
- if (self.selected) {
728
- var currentRoom = self.selected;
729
- if (self.selected.unique_id === room.unique_id) {
730
- self.selected = null;
731
- self.selected = currentRoom;
732
- }
733
- }
734
- if (self.options.roomClearedCallback) {
735
- self.options.roomClearedCallback(room);
736
- }
737
- });
738
- self.events.on('comment-deleted', function (data) {
739
- // get to the room id and delete the comment
740
- var roomId = data.roomId,
741
- commentUniqueIds = data.commentUniqueIds,
742
- isForEveryone = data.isForEveryone,
743
- isHard = data.isHard;
744
- if (self.selected && self.selected.id == roomId) {
745
- // loop through the array of unique_ids
746
- commentUniqueIds.map(function (id) {
747
- var commentToBeFound = self.selected.comments.findIndex(function (comment) {
748
- return comment.unique_id === id;
749
- });
750
- if (commentToBeFound > -1) {
751
- if (isHard) {
752
- self.selected.comments.splice(commentToBeFound, 1);
753
- } else {
754
- self.selected.comments[commentToBeFound].message = 'this message has been deleted';
755
- }
376
+ this.syncAdapter.on("message.new", (message) => __async(this, null, function* () {
377
+ message = yield this._hookAdapter.trigger(
378
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
379
+ message
380
+ );
381
+ if (this.selected != null) {
382
+ const index = this.selected.comments.findIndex(
383
+ (it) => it.id === message.id || it.unique_id === message.unique_temp_id
384
+ );
385
+ if (index === -1) {
386
+ const _message = new Comment(message);
387
+ if (_message.room_id === this.selected.id) {
388
+ this.selected.comments.push(_message);
389
+ this.sortComments();
756
390
  }
757
-
758
- // Find last comment object on `self.selected.comments` array
759
- var lastComment = self.selected.comments[self.selected.comments.length - 1];
760
- self.selected.last_comment_id = lastComment.id;
761
- self.selected.last_comment_message = lastComment.message;
762
- });
763
- }
764
- if (self.options.commentDeletedCallback) {
765
- self.options.commentDeletedCallback(data);
766
- }
767
- });
768
-
769
- /**
770
- * Called when the comment has been delivered
771
- */
772
- self.events.on('comment-delivered', function (response) {
773
- self.logging('comment-delivered', response);
774
- if (!response) return false;
775
- if (self.options.commentDeliveredCallback) {
776
- return self.options.commentDeliveredCallback(response);
391
+ this.events.emit("newmessages", [message]);
392
+ }
393
+ } else {
394
+ this.events.emit("newmessages", [message]);
777
395
  }
778
- // find comment with the id or unique id listed from response
779
- // const commentToFind = self.selected.comments.find(comment =>
780
- // comment.id === response.id || comment.uniqueId === response.uniqueId);
396
+ }));
397
+ this.syncAdapter.on("message.delivered", (message) => {
398
+ this._setDelivered(
399
+ message.comment_id,
400
+ message.comment_unique_id,
401
+ message.email
402
+ );
781
403
  });
782
-
783
- /**
784
- * Called when new chatroom has been created
785
- */
786
- self.events.on('chat-room-created', function (response) {
787
- self.isLoading = false;
788
- if (self.options.chatRoomCreatedCallback) {
789
- self.options.chatRoomCreatedCallback(response);
790
- }
404
+ this.syncAdapter.on("message.read", (message) => {
405
+ this._setRead(
406
+ message.comment_id,
407
+ message.comment_unique_id,
408
+ message.email
409
+ );
791
410
  });
792
-
793
- /**
794
- * Called when a new room with type of group has been created
795
- */
796
- self.events.on('group-room-created', function (response) {
797
- self.isLoading = false;
798
- if (self.options.groupRoomCreatedCallback) {
799
- self.options.groupRoomCreatedCallback(response);
800
- }
411
+ this.syncAdapter.on("message.deleted", (data) => {
412
+ data.deleted_messages.forEach((it) => {
413
+ this.events.emit("comment-deleted", {
414
+ roomId: it.room_id,
415
+ commentUniqueIds: it.message_unique_ids,
416
+ isForEveryone: true,
417
+ isHard: true
418
+ });
419
+ });
801
420
  });
802
-
803
- /**
804
- * Called when user clicked on Chat SDK Header
805
- */
806
- self.events.on('header-clicked', function (response) {
807
- if (self.options.headerClickedCallback) {
808
- self.options.headerClickedCallback(response);
809
- }
421
+ this.syncAdapter.on("room.cleared", (data) => {
422
+ data.deleted_rooms.forEach((room2) => {
423
+ this.events.emit("room-cleared", room2);
424
+ });
810
425
  });
811
-
812
- /**
813
- * Called when a comment has been read
814
- */
815
- self.events.on('comment-read', function (response) {
816
- self.logging('comment-read', response);
817
- if (self.options.commentReadCallback) {
818
- self.options.commentReadCallback(response);
819
- }
426
+ this.syncAdapter.on("synchronize", () => {
427
+ this._pendingComments.forEach((m) => this._retrySendComment(m));
820
428
  });
821
-
822
- /**
823
- * Called when there's new presence data of currently subscribed target user (last seen timestamp)
824
- * @param {string} data MQTT Payload with format of "x:xxxxxxxxxxxxx"
825
- */
826
- self.events.on('presence', function (_ref5) {
827
- var message = _ref5.message,
828
- userId = _ref5.userId;
829
- var payload = message.split(':');
830
- if (_this3.chatmateStatus !== payload[0]) {
831
- _this3.chatmateStatus = payload[0] === 1 ? 'Online' : "Last seen ".concat((0, _distance_in_words_to_now["default"])(Number(payload[1].substring(0, 13))));
832
- }
833
- if (self.options.presenceCallback) self.options.presenceCallback(message, userId);
429
+ this.syncAdapter.on("last-message-id.new", (id) => {
430
+ this.last_received_comment_id = id;
834
431
  });
835
- self.events.on('typing', function (data) {
836
- if (self.options.typingCallback) self.options.typingCallback(data);
432
+ this.customEventAdapter = customEvent(
433
+ this.realtimeAdapter,
434
+ this.user_id
435
+ );
436
+ this.setEventListeners();
437
+ });
438
+ }
439
+ _setRead(messageId, messageUniqueId, userId) {
440
+ if (this.selected == null) return;
441
+ const room2 = this.selected;
442
+ const message = room2.comments.find(
443
+ (it) => it.id === messageId || it.unique_id === messageUniqueId
444
+ );
445
+ if (message == null) return;
446
+ if (message.status === "read") return;
447
+ const options = {
448
+ participants: room2.participants,
449
+ actor: userId,
450
+ comment_id: messageId,
451
+ activeActorId: this.user_id
452
+ };
453
+ room2.comments.forEach((it) => {
454
+ if (it.id <= message.id) {
455
+ it.markAsRead(options);
456
+ }
457
+ });
458
+ if (!message.isRead) return;
459
+ this.events.emit("comment-read", { comment: message, userId });
460
+ }
461
+ _setDelivered(messageId, messageUniqueId, userId) {
462
+ if (this.selected == null) return;
463
+ const room2 = this.selected;
464
+ const message = room2.comments.find(
465
+ (it) => it.id === messageId || it.unique_id === messageUniqueId
466
+ );
467
+ if (message == null) return;
468
+ if (message.status === "read") return;
469
+ const options = {
470
+ participants: room2.participants,
471
+ actor: userId,
472
+ comment_id: messageId,
473
+ activeActorId: this.user_id
474
+ };
475
+ room2.comments.forEach((it) => {
476
+ if (it.id <= message.id) {
477
+ it.markAsDelivered(options);
478
+ }
479
+ });
480
+ if (!message.isDelivered) return;
481
+ this.events.emit("comment-delivered", { comment: message, userId });
482
+ }
483
+ setEventListeners() {
484
+ const self = this;
485
+ this.authAdapter = new auth(self.HTTPAdapter);
486
+ if (this.userData.email != null) {
487
+ this.authAdapter.userId = this.userData.email;
488
+ }
489
+ self.events.on("start-init", () => {
490
+ self.HTTPAdapter = new http({
491
+ baseURL: self.baseURL,
492
+ AppId: self.AppId,
493
+ userId: self.user_id,
494
+ version: self.version,
495
+ getCustomHeader: () => this._customHeader
837
496
  });
838
-
839
- /**
840
- * Called when user clicked on Message Info
841
- */
842
- self.events.on('message-info', function (response) {
843
- if (self.options.messageInfoCallback) {
844
- self.options.messageInfoCallback(response);
497
+ self.HTTPAdapter.setToken(self.userData.token);
498
+ });
499
+ self.events.on("room-changed", (room2) => {
500
+ this.logging("room changed", room2);
501
+ if (self.options.roomChangedCallback) {
502
+ self.options.roomChangedCallback(room2);
503
+ }
504
+ });
505
+ self.events.on("file-uploaded", (url) => {
506
+ if (self.options.fileUploadedCallback) {
507
+ self.options.fileUploadedCallback(url);
508
+ }
509
+ });
510
+ self.events.on("profile-updated", (user2) => {
511
+ self.username = user2.name;
512
+ self.avatar_url = user2.avatar_url;
513
+ if (self.options.updateProfileCallback) {
514
+ self.options.updateProfileCallback(user2);
515
+ }
516
+ });
517
+ self.events.on("newmessages", (comments) => {
518
+ this.logging("newmessages", comments);
519
+ const lastReceivedMessageNotEmpty = this.lastReceiveMessages.length > 0;
520
+ if (lastReceivedMessageNotEmpty && this.lastReceiveMessages[0].unique_temp_id === comments[0].unique_temp_id) {
521
+ this.logging("lastReceiveMessages double", comments);
522
+ return;
523
+ }
524
+ this.lastReceiveMessages = comments;
525
+ self._callNewMessagesCallback(comments);
526
+ comments.forEach((comment) => {
527
+ self.receiveComment(comment.room_id, comment.id);
528
+ const isActiveRoom = self.selected ? comment.room_id === self.selected.id : false;
529
+ const isAlreadyRead = comment.id <= self.last_received_comment_id;
530
+ if (isActiveRoom) {
531
+ const selected = self.selected;
532
+ const lastComment = self.selected.comments[self.selected.comments.length - 1];
533
+ if (!lastComment.isPending && !isAlreadyRead && self.user_id !== comment.email) {
534
+ self.readComment(comment.room_id, comment.id);
535
+ }
536
+ const roomLastCommentId = lastComment.id;
537
+ const commentBeforeThis = self.selected.comments.find(
538
+ (c) => c.id === lastComment.comment_before_id
539
+ );
540
+ if (!lastComment.isPending && !commentBeforeThis) {
541
+ this.logging(
542
+ "comment before id not found! ",
543
+ comment.comment_before_id
544
+ );
545
+ self.synchronize(roomLastCommentId);
546
+ }
547
+ const pendingComment = new Comment(comment);
548
+ selected.receiveComment(pendingComment);
549
+ selected.last_comment_id = pendingComment.id;
550
+ selected.last_comment_message = pendingComment.message;
845
551
  }
552
+ self.updateLastReceivedComment(comment.id);
553
+ this.sortComments();
846
554
  });
847
-
848
- /**
849
- * Called when new particant was added into a group
850
- */
851
- self.events.on('participants-added', function (response) {
852
- var _this3$selected$parti;
853
- if (response == null || _this3.selected == null) return;
854
- (_this3$selected$parti = _this3.selected.participants).push.apply(_this3$selected$parti, (0, _toConsumableArray2["default"])(response));
855
- });
856
-
857
- /**
858
- * Called when particant was removed from a group
859
- */
860
- self.events.on('participants-removed', function (response) {
861
- if (response == null || _this3.selected == null) return;
862
- var participants = _this3.selected.participants.filter(function (participant) {
863
- return response.indexOf(participant.email) <= -1;
864
- });
865
- _this3.selected.participants = participants;
555
+ });
556
+ this.events.on("login-success", (response) => {
557
+ this.isLogin = true;
558
+ this.userData = response.user;
559
+ this.last_received_comment_id = this.userData.last_comment_id;
560
+ if (!this.realtimeAdapter.connected)
561
+ this.updateLastReceivedComment(this.last_received_comment_id);
562
+ this.HTTPAdapter = new http({
563
+ baseURL: this.baseURL,
564
+ AppId: this.AppId,
565
+ userId: this.user_id,
566
+ version: this.version,
567
+ getCustomHeader: () => this._customHeader,
568
+ expiredTokenAdapterGetter: () => this.expiredTokenAdapter
866
569
  });
867
-
868
- /**
869
- * Called when user was added to blocked list
870
- */
871
- self.events.on('block-user', function (response) {
872
- if (self.options.blockUserCallback) {
873
- self.options.blockUserCallback(response);
570
+ this.HTTPAdapter.setToken(this.userData.token);
571
+ let user$1 = response.user;
572
+ this._delayedSync = utils.delayed(() => {
573
+ this.synchronize();
574
+ this.synchronizeEvent();
575
+ }, 500);
576
+ this.expiredTokenAdapter = new expiredToken.ExpiredTokenAdapter({
577
+ httpAdapter: this.HTTPAdapter,
578
+ refreshToken: user$1.refresh_token,
579
+ expiredAt: user$1.token_expires_at,
580
+ userId: this.user_id,
581
+ onTokenRefreshed: (token, refreshToken, expiredAt, oldToken) => {
582
+ this.userData.token = token;
583
+ this.userData.refresh_token = refreshToken;
584
+ this.userData.token_expires_at = expiredAt == null ? void 0 : expiredAt.toJSON();
585
+ this.events.emit("token-refreshed", {
586
+ token,
587
+ refreshToken,
588
+ expiredAt,
589
+ oldToken
590
+ });
591
+ this.realtimeAdapter.unsusbcribeUserChannelByToken(oldToken);
592
+ this.realtimeAdapter.subscribeUserChannelByToken(token);
593
+ this._delayedSync();
594
+ },
595
+ getAuthenticationStatus: () => {
596
+ return this.user_id != null && this.isLogin;
874
597
  }
875
598
  });
876
-
877
- /**
878
- * Called when user was removed from blocked list
879
- */
880
- self.events.on('unblock-user', function (response) {
881
- if (self.options.unblockUserCallback) {
882
- self.options.unblockUserCallback(response);
599
+ this.userAdapter = new user(this.HTTPAdapter);
600
+ this.roomAdapter = new room(this.HTTPAdapter);
601
+ this.realtimeAdapter.subscribeUserChannel();
602
+ if (this.presensePublisherId != null && this.presensePublisherId !== -1) {
603
+ clearInterval(this.presensePublisherId);
604
+ }
605
+ this.presensePublisherId = setInterval(() => {
606
+ this.realtimeAdapter.publishPresence(this.user_id, true);
607
+ }, 3500);
608
+ if (this.options.loginSuccessCallback) {
609
+ this.options.loginSuccessCallback(response);
610
+ }
611
+ this.authAdapter.userId = this.userData.email;
612
+ this.authAdapter.refreshToken = this.userData.refresh_token;
613
+ this.authAdapter.autoRefreshToken = this._autoRefreshToken;
614
+ });
615
+ self.events.on("login-error", function(error) {
616
+ if (self.options.loginErrorCallback) {
617
+ self.options.loginErrorCallback(error);
618
+ }
619
+ });
620
+ self.events.on("token-refreshed", (param) => {
621
+ var _a, _b;
622
+ (_b = (_a = this.options).authTokenRefreshedCallback) == null ? void 0 : _b.call(_a, param);
623
+ });
624
+ self.events.on("room-cleared", function(room2) {
625
+ if (self.selected) {
626
+ const currentRoom = self.selected;
627
+ if (self.selected.unique_id === room2.unique_id) {
628
+ self.selected = null;
629
+ self.selected = currentRoom;
883
630
  }
884
- });
885
- }
886
- }, {
887
- key: "onReconnectMqtt",
888
- value: function onReconnectMqtt() {
889
- if (this.options.onReconnectCallback) this.options.onReconnectedCallback();
890
- if (!this.selected) return;
891
- this.loadComments(this.selected.id);
892
- }
893
- }, {
894
- key: "_callNewMessagesCallback",
895
- value: function _callNewMessagesCallback(comments) {
896
- if (this.options.newMessagesCallback) {
897
- this.options.newMessagesCallback(comments);
898
631
  }
899
- }
900
- }, {
901
- key: "updateLastReceivedComment",
902
- value: function updateLastReceivedComment(id) {
903
- if (this.last_received_comment_id < id) {
904
- this.last_received_comment_id = id;
632
+ if (self.options.roomClearedCallback) {
633
+ self.options.roomClearedCallback(room2);
905
634
  }
906
- }
907
-
908
- /**
909
- * Setting Up User Credentials for next API Request
910
- * @param userId {string} - client userId (will be used for login or register)
911
- * @param key {string} - client unique key
912
- * @param username {string} - client username
913
- * @param avatarURL {string} - the url for chat avatar (optional)
914
- * @param extras {object} - extra data for user
915
- * @return {Promise}
916
- */
917
- }, {
918
- key: "setUser",
919
- value: function setUser(userId, key, username, avatarURL, extras) {
920
- var _this4 = this;
921
- var self = this;
922
- self.user_id = userId;
923
- self.key = key;
924
- self.username = username;
925
- self.avatar_url = avatarURL;
926
- var params = {
927
- email: this.user_id,
928
- password: this.key,
929
- username: this.username,
930
- extras: extras ? JSON.stringify(extras) : null
931
- };
932
- if (this.avatar_url) params.avatar_url = this.avatar_url;
933
- return new Promise(function (resolve, reject) {
934
- var waitingConfig = setInterval(function () {
935
- if (!_this4.isConfigLoaded) {
936
- if (_this4.debugMode) {
937
- _this4.logger('Waiting for init config...');
635
+ });
636
+ self.events.on("comment-deleted", function(data) {
637
+ const {
638
+ roomId,
639
+ commentUniqueIds,
640
+ // eslint-disable-next-line
641
+ isForEveryone,
642
+ isHard
643
+ } = data;
644
+ if (self.selected && self.selected.id == roomId) {
645
+ commentUniqueIds.map((id) => {
646
+ const commentToBeFound = self.selected.comments.findIndex(
647
+ (comment) => comment.unique_id === id
648
+ );
649
+ if (commentToBeFound > -1) {
650
+ if (isHard) {
651
+ self.selected.comments.splice(commentToBeFound, 1);
652
+ } else {
653
+ self.selected.comments[commentToBeFound].message = "this message has been deleted";
938
654
  }
939
- } else {
940
- clearInterval(waitingConfig);
941
- _this4.logger('Config Success!');
942
- self.events.emit('start-init');
943
- var login$ = self.authAdapter.loginOrRegister(params).then(function (response) {
944
- self.isInit = true;
945
- self.refresh_token = response.user.refresh_token;
946
- self.events.emit('login-success', response);
947
- _this4.realtimeAdapter.connect();
948
- resolve(response);
949
- }, function (error) {
950
- self.events.emit('login-error', error);
951
- reject(error);
952
- });
953
- return login$;
954
655
  }
955
- }, 300);
956
- });
656
+ const lastComment = self.selected.comments[self.selected.comments.length - 1];
657
+ self.selected.last_comment_id = lastComment.id;
658
+ self.selected.last_comment_message = lastComment.message;
659
+ });
660
+ }
661
+ if (self.options.commentDeletedCallback) {
662
+ self.options.commentDeletedCallback(data);
663
+ }
664
+ });
665
+ self.events.on("comment-delivered", function(response) {
666
+ self.logging("comment-delivered", response);
667
+ if (!response) return false;
668
+ if (self.options.commentDeliveredCallback) {
669
+ return self.options.commentDeliveredCallback(response);
670
+ }
671
+ });
672
+ self.events.on("chat-room-created", function(response) {
673
+ self.isLoading = false;
674
+ if (self.options.chatRoomCreatedCallback) {
675
+ self.options.chatRoomCreatedCallback(response);
676
+ }
677
+ });
678
+ self.events.on("group-room-created", function(response) {
679
+ self.isLoading = false;
680
+ if (self.options.groupRoomCreatedCallback) {
681
+ self.options.groupRoomCreatedCallback(response);
682
+ }
683
+ });
684
+ self.events.on("header-clicked", function(response) {
685
+ if (self.options.headerClickedCallback) {
686
+ self.options.headerClickedCallback(response);
687
+ }
688
+ });
689
+ self.events.on("comment-read", function(response) {
690
+ self.logging("comment-read", response);
691
+ if (self.options.commentReadCallback) {
692
+ self.options.commentReadCallback(response);
693
+ }
694
+ });
695
+ self.events.on("presence", ({ message, userId }) => {
696
+ const payload = message.split(":");
697
+ if (this.chatmateStatus !== payload[0]) {
698
+ this.chatmateStatus = payload[0] === 1 ? "Online" : `Last seen ${distanceInWordsToNow(
699
+ Number(payload[1].substring(0, 13))
700
+ )}`;
701
+ }
702
+ if (self.options.presenceCallback)
703
+ self.options.presenceCallback(message, userId);
704
+ });
705
+ self.events.on("typing", function(data) {
706
+ if (self.options.typingCallback) self.options.typingCallback(data);
707
+ });
708
+ self.events.on("message-info", function(response) {
709
+ if (self.options.messageInfoCallback) {
710
+ self.options.messageInfoCallback(response);
711
+ }
712
+ });
713
+ self.events.on("participants-added", (response) => {
714
+ if (response == null || this.selected == null) return;
715
+ this.selected.participants.push(...response);
716
+ });
717
+ self.events.on("participants-removed", (response) => {
718
+ if (response == null || this.selected == null) return;
719
+ const participants = this.selected.participants.filter(
720
+ (participant) => response.indexOf(participant.email) <= -1
721
+ );
722
+ this.selected.participants = participants;
723
+ });
724
+ self.events.on("block-user", function(response) {
725
+ if (self.options.blockUserCallback) {
726
+ self.options.blockUserCallback(response);
727
+ }
728
+ });
729
+ self.events.on("unblock-user", function(response) {
730
+ if (self.options.unblockUserCallback) {
731
+ self.options.unblockUserCallback(response);
732
+ }
733
+ });
734
+ }
735
+ onReconnectMqtt() {
736
+ if (this.options.onReconnectCallback) this.options.onReconnectedCallback();
737
+ if (!this.selected) return;
738
+ this.loadComments(this.selected.id);
739
+ }
740
+ _callNewMessagesCallback(comments) {
741
+ if (this.options.newMessagesCallback) {
742
+ this.options.newMessagesCallback(comments);
743
+ }
744
+ }
745
+ updateLastReceivedComment(id) {
746
+ if (this.last_received_comment_id < id) {
747
+ this.last_received_comment_id = id;
957
748
  }
958
- }, {
959
- key: "setUserWithIdentityToken",
960
- value: function setUserWithIdentityToken(data) {
961
- var _this5 = this;
962
- if (!data || !('user' in data)) return this.events.emit('login-error', data);
963
- this.email = data.user.email;
964
- this.user_id = data.user.email;
965
- this.key = data.identity_token;
966
- this.username = data.user.username;
967
- this.avatar_url = data.user.avatar_url;
968
- this.isInit = true;
969
- var waitingConfig = setInterval(function () {
970
- if (!_this5.isConfigLoaded) {
971
- if (_this5.debugMode) {
972
- _this5.logger('Waiting for init config...');
749
+ }
750
+ /**
751
+ * Setting Up User Credentials for next API Request
752
+ * @param userId {string} - client userId (will be used for login or register)
753
+ * @param key {string} - client unique key
754
+ * @param username {string} - client username
755
+ * @param avatarURL {string} - the url for chat avatar (optional)
756
+ * @param extras {object} - extra data for user
757
+ * @return {Promise}
758
+ */
759
+ setUser(userId, key, username, avatarURL, extras) {
760
+ const self = this;
761
+ self.user_id = userId;
762
+ self.key = key;
763
+ self.username = username;
764
+ self.avatar_url = avatarURL;
765
+ let params = {
766
+ email: this.user_id,
767
+ password: this.key,
768
+ username: this.username,
769
+ extras: extras ? JSON.stringify(extras) : null
770
+ };
771
+ if (this.avatar_url) params.avatar_url = this.avatar_url;
772
+ return new Promise((resolve, reject) => {
773
+ let waitingConfig = setInterval(() => {
774
+ if (!this.isConfigLoaded) {
775
+ if (this.debugMode) {
776
+ this.logger("Waiting for init config...");
973
777
  }
974
778
  } else {
975
779
  clearInterval(waitingConfig);
976
- _this5.logger('Config Success!');
977
- _this5.events.emit('login-success', data);
780
+ this.logger("Config Success!");
781
+ self.events.emit("start-init");
782
+ let login$ = self.authAdapter.loginOrRegister(params).then(
783
+ (response) => {
784
+ self.isInit = true;
785
+ self.refresh_token = response.user.refresh_token;
786
+ self.events.emit("login-success", response);
787
+ this.realtimeAdapter.connect();
788
+ resolve(response);
789
+ },
790
+ (error) => {
791
+ self.events.emit("login-error", error);
792
+ reject(error);
793
+ }
794
+ );
795
+ return login$;
978
796
  }
979
797
  }, 300);
980
- }
981
- }, {
982
- key: "refreshAuthToken",
983
- value: function refreshAuthToken() {
984
- return this.expiredTokenAdapter.refreshAuthToken();
985
- }
986
- }, {
987
- key: "publishOnlinePresence",
988
- value: function publishOnlinePresence(val) {
989
- var _this6 = this;
990
- if (val === true) {
991
- setBackToOnline = setInterval(function () {
992
- _this6.realtimeAdapter.publishPresence(_this6.user_id, true);
993
- }, 3500);
798
+ });
799
+ }
800
+ setUserWithIdentityToken(data) {
801
+ if (!data || !("user" in data)) return this.events.emit("login-error", data);
802
+ this.email = data.user.email;
803
+ this.user_id = data.user.email;
804
+ this.key = data.identity_token;
805
+ this.username = data.user.username;
806
+ this.avatar_url = data.user.avatar_url;
807
+ this.isInit = true;
808
+ let waitingConfig = setInterval(() => {
809
+ if (!this.isConfigLoaded) {
810
+ if (this.debugMode) {
811
+ this.logger("Waiting for init config...");
812
+ }
994
813
  } else {
995
- clearInterval(this.presensePublisherId);
996
- clearInterval(setBackToOnline);
997
- setTimeout(function () {
998
- _this6.realtimeAdapter.publishPresence(_this6.user_id, false);
999
- }, 3500);
814
+ clearInterval(waitingConfig);
815
+ this.logger("Config Success!");
816
+ this.events.emit("login-success", data);
1000
817
  }
818
+ }, 300);
819
+ }
820
+ refreshAuthToken() {
821
+ return this.expiredTokenAdapter.refreshAuthToken();
822
+ }
823
+ publishOnlinePresence(val) {
824
+ if (val === true) {
825
+ setBackToOnline = setInterval(() => {
826
+ this.realtimeAdapter.publishPresence(this.user_id, true);
827
+ }, 3500);
828
+ } else {
829
+ clearInterval(this.presensePublisherId);
830
+ clearInterval(setBackToOnline);
831
+ setTimeout(() => {
832
+ this.realtimeAdapter.publishPresence(this.user_id, false);
833
+ }, 3500);
1001
834
  }
1002
- }, {
1003
- key: "subscribeUserPresence",
1004
- value: function subscribeUserPresence(userId) {
1005
- this.realtimeAdapter.subscribeUserPresence(userId);
1006
- }
1007
- }, {
1008
- key: "unsubscribeUserPresence",
1009
- value: function unsubscribeUserPresence(userId) {
1010
- this.realtimeAdapter.unsubscribeUserPresence(userId);
1011
- }
1012
- }, {
1013
- key: "logout",
1014
- value: function () {
1015
- var _logout = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee4() {
1016
- return _regenerator["default"].wrap(function (_context4) {
1017
- while (1) switch (_context4.prev = _context4.next) {
1018
- case 0:
1019
- _context4.next = 1;
1020
- return this.expiredTokenAdapter.logout();
1021
- case 1:
1022
- clearInterval(this.presensePublisherId);
1023
- this.publishOnlinePresence(false);
1024
- this.selected = null;
1025
- this.isInit = false;
1026
- this.isLogin = false;
1027
- this.realtimeAdapter.disconnect();
1028
- this.userData = {};
1029
- case 2:
1030
- case "end":
1031
- return _context4.stop();
1032
- }
1033
- }, _callee4, this);
1034
- }));
1035
- function logout() {
1036
- return _logout.apply(this, arguments);
835
+ }
836
+ subscribeUserPresence(userId) {
837
+ this.realtimeAdapter.subscribeUserPresence(userId);
838
+ }
839
+ unsubscribeUserPresence(userId) {
840
+ this.realtimeAdapter.unsubscribeUserPresence(userId);
841
+ }
842
+ logout() {
843
+ return __async(this, null, function* () {
844
+ yield this.expiredTokenAdapter.logout();
845
+ clearInterval(this.presensePublisherId);
846
+ this.publishOnlinePresence(false);
847
+ this.selected = null;
848
+ this.isInit = false;
849
+ this.isLogin = false;
850
+ this.realtimeAdapter.disconnect();
851
+ this.userData = {};
852
+ });
853
+ }
854
+ get synchronize() {
855
+ return this.syncAdapter.synchronize;
856
+ }
857
+ get synchronizeEvent() {
858
+ return this.syncAdapter.synchronizeEvent;
859
+ }
860
+ disconnect() {
861
+ this.logout();
862
+ }
863
+ setActiveRoom(room2) {
864
+ if (this.selected) {
865
+ this.realtimeAdapter.unsubscribeTyping();
866
+ if (this.selected.room_type === "single") {
867
+ const unsubscribedUserId = this.selected.participants.filter(
868
+ (p) => p.email !== this.user_id
869
+ );
870
+ if (unsubscribedUserId.length > 0) {
871
+ this.realtimeAdapter.unsubscribeRoomPresence(
872
+ unsubscribedUserId[0].email
873
+ );
874
+ }
1037
875
  }
1038
- return logout;
1039
- }()
1040
- }, {
1041
- key: "synchronize",
1042
- get: function get() {
1043
- return this.syncAdapter.synchronize;
1044
- }
1045
- }, {
1046
- key: "synchronizeEvent",
1047
- get: function get() {
1048
- return this.syncAdapter.synchronizeEvent;
1049
876
  }
1050
- }, {
1051
- key: "disconnect",
1052
- value: function disconnect() {
1053
- this.logout();
1054
- }
1055
- }, {
1056
- key: "setActiveRoom",
1057
- value: function setActiveRoom(room) {
1058
- var _this7 = this;
1059
- // when we activate a room
1060
- // we need to unsubscribe from typing event
1061
- if (this.selected) {
1062
- this.realtimeAdapter.unsubscribeTyping();
1063
- // before we unsubscribe, we need to get the userId first
1064
- // and only unsubscribe if the previous room is having a type of 'single'
1065
- if (this.selected.room_type === 'single') {
1066
- var unsubscribedUserId = this.selected.participants.filter(function (p) {
1067
- return p.email !== _this7.user_id;
1068
- });
1069
- if (unsubscribedUserId.length > 0) {
1070
- this.realtimeAdapter.unsubscribeRoomPresence(unsubscribedUserId[0].email);
1071
- }
1072
- }
877
+ if (room2.participants == null) room2.participants = [];
878
+ const targetUserId = room2.participants.find((p) => p.email !== this.user_id);
879
+ this.chatmateStatus = null;
880
+ this.isTypingStatus = null;
881
+ this.selected = room2;
882
+ const initialSubscribe = setInterval(() => {
883
+ if (this.debugMode) {
884
+ this.logger("Trying Initial Subscribe");
1073
885
  }
1074
- if (room.participants == null) room.participants = [];
1075
- var targetUserId = room.participants.find(function (p) {
1076
- return p.email !== _this7.user_id;
1077
- });
1078
- this.chatmateStatus = null;
1079
- this.isTypingStatus = null;
1080
- this.selected = room;
1081
- // found a bug where there's a race condition, subscribing to mqtt
1082
- // while mqtt is still connecting, so we'll have to do this hack
1083
- var initialSubscribe = setInterval(function () {
1084
- // Clear Interval when realtimeAdapter has been Populated
1085
-
1086
- if (_this7.debugMode) {
1087
- _this7.logger('Trying Initial Subscribe');
886
+ if (this.realtimeAdapter != null) {
887
+ if (this.debugMode) {
888
+ this.logger("MQTT Connected");
1088
889
  }
1089
- if (_this7.realtimeAdapter != null) {
1090
- if (_this7.debugMode) {
1091
- _this7.logger('MQTT Connected');
1092
- }
1093
- clearInterval(initialSubscribe);
1094
-
1095
- // before we unsubscribe, we need to get the userId first
1096
- // and only unsubscribe if the previous room is having a type of 'single'
1097
- if (room.room_type === 'single' && targetUserId != null) {
1098
- _this7.realtimeAdapter.subscribeRoomPresence(targetUserId.email);
1099
- }
1100
- // we need to subscribe to new room typing event now
1101
- if (_this7.selected != null && !_this7.selected.isChannel) {
1102
- _this7.realtimeAdapter.subscribeTyping(room.id);
1103
- _this7.events.emit('room-changed', _this7.selected);
1104
- }
1105
- if (_this7.debugMode && _this7.realtimeAdapter == null) {
1106
- _this7.logger('Retry');
1107
- }
1108
- } else {
1109
- if (_this7.debugMode) {
1110
- _this7.logger('MQTT Not Connected, yet');
1111
- }
890
+ clearInterval(initialSubscribe);
891
+ if (room2.room_type === "single" && targetUserId != null) {
892
+ this.realtimeAdapter.subscribeRoomPresence(targetUserId.email);
893
+ }
894
+ if (this.selected != null && !this.selected.isChannel) {
895
+ this.realtimeAdapter.subscribeTyping(room2.id);
896
+ this.events.emit("room-changed", this.selected);
897
+ }
898
+ if (this.debugMode && this.realtimeAdapter == null) {
899
+ this.logger("Retry");
900
+ }
901
+ } else {
902
+ if (this.debugMode) {
903
+ this.logger("MQTT Not Connected, yet");
1112
904
  }
1113
- }, 3000);
1114
- }
1115
-
1116
- /**
1117
- * Chat with targetted email
1118
- * @param userId {string} - target userId
1119
- * @param options {object} - optional data sent to qiscus database
1120
- * @return room <Room>
1121
- */
1122
- }, {
1123
- key: "chatTarget",
1124
- value: function chatTarget(userId) {
1125
- var _this8 = this;
1126
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1127
- // make sure data already loaded first (user already logged in)
1128
- if (this.userData.length != null) return false;
1129
- var initialMessage = options ? options.message : null;
1130
- var distinctId = options.distinctId;
1131
- this.isLoading = true;
1132
- this.isTypingStatus = '';
1133
-
1134
- // Create room
1135
- return this.roomAdapter.getOrCreateRoom(userId, options, distinctId).then(/*#__PURE__*/function () {
1136
- var _ref6 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee6(resp) {
1137
- var room, mapIntercept, lastComment, topicId;
1138
- return _regenerator["default"].wrap(function (_context6) {
1139
- while (1) switch (_context6.prev = _context6.next) {
1140
- case 0:
1141
- room = new _Room["default"](resp);
1142
- _this8.updateLastReceivedComment(room.last_comment_id);
1143
- _this8.isLoading = false;
1144
- mapIntercept = /*#__PURE__*/function () {
1145
- var _ref7 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee5(it) {
1146
- return _regenerator["default"].wrap(function (_context5) {
1147
- while (1) switch (_context5.prev = _context5.next) {
1148
- case 0:
1149
- _context5.next = 1;
1150
- return _this8._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, it);
1151
- case 1:
1152
- return _context5.abrupt("return", _context5.sent);
1153
- case 2:
1154
- case "end":
1155
- return _context5.stop();
1156
- }
1157
- }, _callee5);
1158
- }));
1159
- return function mapIntercept(_x5) {
1160
- return _ref7.apply(this, arguments);
1161
- };
1162
- }();
1163
- _context6.next = 1;
1164
- return Promise.all(room.comments.map(function (comment) {
1165
- return mapIntercept(comment);
1166
- }));
1167
- case 1:
1168
- room.comments = _context6.sent;
1169
- _this8.setActiveRoom(room);
1170
- // id of last comment on this room
1171
- lastComment = room.comments[room.comments.length - 1];
1172
- if (lastComment) _this8.readComment(room.id, lastComment.id);
1173
- _this8.events.emit('chat-room-created', {
1174
- room: room
1175
- });
1176
- if (initialMessage) {
1177
- _context6.next = 2;
1178
- break;
1179
- }
1180
- return _context6.abrupt("return", room);
1181
- case 2:
1182
- topicId = room.id;
1183
- return _context6.abrupt("return", _this8.sendComment(topicId, initialMessage).then(function () {
1184
- return Promise.resolve(room);
1185
- })["catch"](function (err) {
1186
- console.error('Error when submit comment', err);
1187
- }));
1188
- case 3:
1189
- case "end":
1190
- return _context6.stop();
1191
- }
1192
- }, _callee6);
1193
- }));
1194
- return function (_x4) {
1195
- return _ref6.apply(this, arguments);
1196
- };
1197
- }())["catch"](function (err) {
1198
- console.error('Error when creating room', err);
1199
- _this8.isLoading = false;
1200
- return Promise.reject(err);
1201
- });
1202
- }
1203
-
1204
- /**
1205
- *
1206
- * Open a group chat or target a specific room id
1207
- *
1208
- * @param {int} id
1209
- * @returns Room <Room>
1210
- * @memberof QiscusSDK
1211
- */
1212
- }, {
1213
- key: "chatGroup",
1214
- value: function chatGroup(id) {
1215
- var self = this;
1216
- if (!self.isInit) return;
1217
- return self.getRoomById(id).then(function (response) {
1218
- return Promise.resolve(response);
1219
- }, function (err) {
1220
- return Promise.reject(err);
1221
- });
1222
- }
1223
-
1224
- /**
1225
- * @param {int} id - Room Id
1226
- * @return {Room} Room data
1227
- */
1228
- }, {
1229
- key: "getRoomById",
1230
- value: function getRoomById(id) {
1231
- var _this9 = this;
1232
- if (!this.isInit) return;
1233
- var self = this;
1234
- self.isLoading = true;
1235
- self.isTypingStatus = '';
1236
- return self.roomAdapter.getRoomById(id).then(/*#__PURE__*/function () {
1237
- var _ref8 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee7(resp) {
1238
- var roomData, comments, _iterator, _step, comment, c, room, lastComment, _t;
1239
- return _regenerator["default"].wrap(function (_context7) {
1240
- while (1) switch (_context7.prev = _context7.next) {
1241
- case 0:
1242
- roomData = resp.results.room;
1243
- comments = [];
1244
- _iterator = _createForOfIteratorHelper(resp.results.comments.reverse());
1245
- _context7.prev = 1;
1246
- _iterator.s();
1247
- case 2:
1248
- if ((_step = _iterator.n()).done) {
1249
- _context7.next = 5;
1250
- break;
1251
- }
1252
- comment = _step.value;
1253
- _context7.next = 3;
1254
- return _this9._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, comment);
1255
- case 3:
1256
- c = _context7.sent;
1257
- comments.push(c);
1258
- case 4:
1259
- _context7.next = 2;
1260
- break;
1261
- case 5:
1262
- _context7.next = 7;
1263
- break;
1264
- case 6:
1265
- _context7.prev = 6;
1266
- _t = _context7["catch"](1);
1267
- _iterator.e(_t);
1268
- case 7:
1269
- _context7.prev = 7;
1270
- _iterator.f();
1271
- return _context7.finish(7);
1272
- case 8:
1273
- // .map((it) =>
1274
- // this._hookAdapter.trigger(Hooks.MESSAGE_BEFORE_RECEIVED, it)
1275
- // );
1276
- room = new _Room["default"](_objectSpread(_objectSpread({}, roomData), {}, {
1277
- comments: comments,
1278
- name: roomData.room_name
1279
- }));
1280
- self.updateLastReceivedComment(room.last_comment_id);
1281
- self.setActiveRoom(room);
1282
- self.isLoading = false;
1283
- // id of last comment on this room
1284
- lastComment = room.comments[room.comments.length - 1];
1285
- if (lastComment) self.readComment(room.id, lastComment.id);
1286
- if (room.isChannel) {
1287
- _this9.realtimeAdapter.subscribeChannel(_this9.AppId, room.unique_id);
1288
- }
1289
- return _context7.abrupt("return", room);
1290
- case 9:
1291
- case "end":
1292
- return _context7.stop();
1293
- }
1294
- }, _callee7, null, [[1, 6, 7, 8]]);
1295
- }));
1296
- return function (_x6) {
1297
- return _ref8.apply(this, arguments);
1298
- };
1299
- }())["catch"](function (error) {
1300
- console.error('Error getting room by id', error);
1301
- return Promise.reject(error);
1302
- });
1303
- }
1304
-
1305
- /**
1306
- * @param {int} id - Room Id
1307
- * @param {string} roomName
1308
- * @param {string} avatarURL
1309
- * @return {Room} Room data
1310
- */
1311
- }, {
1312
- key: "getOrCreateRoomByUniqueId",
1313
- value: function getOrCreateRoomByUniqueId(id, roomName, avatarURL) {
1314
- var _this0 = this;
1315
- var self = this;
1316
- self.isLoading = true;
1317
- self.isTypingStatus = '';
1318
- return self.roomAdapter.getOrCreateRoomByUniqueId(id, roomName, avatarURL).then(/*#__PURE__*/function () {
1319
- var _ref9 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee9(response) {
1320
- var room, mapIntercept, lastComment;
1321
- return _regenerator["default"].wrap(function (_context9) {
1322
- while (1) switch (_context9.prev = _context9.next) {
1323
- case 0:
1324
- // make sure the room hasn't been pushed yet
1325
- room = new _Room["default"](response);
1326
- self.updateLastReceivedComment(room.last_comment_id);
1327
- mapIntercept = /*#__PURE__*/function () {
1328
- var _ref0 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee8(item) {
1329
- return _regenerator["default"].wrap(function (_context8) {
1330
- while (1) switch (_context8.prev = _context8.next) {
1331
- case 0:
1332
- _context8.next = 1;
1333
- return _this0._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, item);
1334
- case 1:
1335
- return _context8.abrupt("return", _context8.sent);
1336
- case 2:
1337
- case "end":
1338
- return _context8.stop();
1339
- }
1340
- }, _callee8);
1341
- }));
1342
- return function mapIntercept(_x8) {
1343
- return _ref0.apply(this, arguments);
1344
- };
1345
- }();
1346
- _context9.next = 1;
1347
- return Promise.all(room.comments.map(function (it) {
1348
- return mapIntercept(it);
1349
- }));
1350
- case 1:
1351
- room.comments = _context9.sent;
1352
- self.setActiveRoom(room);
1353
- self.isLoading = false;
1354
- lastComment = room.comments[room.comments.length - 1];
1355
- if (lastComment) self.readComment(room.id, lastComment.id);
1356
- _this0.realtimeAdapter.subscribeChannel(_this0.AppId, room.unique_id);
1357
- return _context9.abrupt("return", Promise.resolve(room));
1358
- case 2:
1359
- case "end":
1360
- return _context9.stop();
1361
- }
1362
- }, _callee9);
1363
- }));
1364
- return function (_x7) {
1365
- return _ref9.apply(this, arguments);
1366
- };
1367
- }())["catch"](function (error) {
1368
- // console.error('Error getting room by id', error)
1369
- return Promise.reject(error);
1370
- });
1371
- }
1372
- }, {
1373
- key: "getOrCreateRoomByChannel",
1374
- value: function getOrCreateRoomByChannel(channel, name, avatarURL) {
1375
- return this.getOrCreateRoomByUniqueId(channel, name, avatarURL);
1376
- }
1377
- }, {
1378
- key: "sortComments",
1379
- value: function sortComments() {
1380
- this.selected && this.selected.comments.sort(function (leftSideComment, rightSideComment) {
1381
- return leftSideComment.unix_timestamp - rightSideComment.unix_timestamp;
1382
- });
1383
- }
1384
- }, {
1385
- key: "loadRoomList",
1386
- value: function () {
1387
- var _loadRoomList = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee0() {
1388
- var params,
1389
- rooms,
1390
- _args0 = arguments;
1391
- return _regenerator["default"].wrap(function (_context0) {
1392
- while (1) switch (_context0.prev = _context0.next) {
1393
- case 0:
1394
- params = _args0.length > 0 && _args0[0] !== undefined ? _args0[0] : {};
1395
- _context0.next = 1;
1396
- return this.userAdapter.loadRoomList(params);
1397
- case 1:
1398
- rooms = _context0.sent;
1399
- return _context0.abrupt("return", rooms.map(function (room) {
1400
- room.last_comment_id = room.last_comment.id;
1401
- room.last_comment_message = room.last_comment.message;
1402
- room.last_comment_message_created_at = room.last_comment.timestamp;
1403
- room.room_type = room.chat_type;
1404
- room.comments = [];
1405
- return new _Room["default"](room);
1406
- }));
1407
- case 2:
1408
- case "end":
1409
- return _context0.stop();
1410
- }
1411
- }, _callee0, this);
1412
- }));
1413
- function loadRoomList() {
1414
- return _loadRoomList.apply(this, arguments);
1415
- }
1416
- return loadRoomList;
1417
- }()
1418
- }, {
1419
- key: "loadComments",
1420
- value: function loadComments(roomId) {
1421
- var _this1 = this;
1422
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1423
- return this.userAdapter.loadComments(roomId, options).then(/*#__PURE__*/function () {
1424
- var _ref1 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee1(comments_) {
1425
- var comments, _iterator2, _step2, comment, _t2, _t3;
1426
- return _regenerator["default"].wrap(function (_context1) {
1427
- while (1) switch (_context1.prev = _context1.next) {
1428
- case 0:
1429
- comments = [];
1430
- _iterator2 = _createForOfIteratorHelper(comments_);
1431
- _context1.prev = 1;
1432
- _iterator2.s();
1433
- case 2:
1434
- if ((_step2 = _iterator2.n()).done) {
1435
- _context1.next = 5;
1436
- break;
1437
- }
1438
- comment = _step2.value;
1439
- _t2 = comments;
1440
- _context1.next = 3;
1441
- return _this1._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, comment);
1442
- case 3:
1443
- _t2.push.call(_t2, _context1.sent);
1444
- case 4:
1445
- _context1.next = 2;
1446
- break;
1447
- case 5:
1448
- _context1.next = 7;
1449
- break;
1450
- case 6:
1451
- _context1.prev = 6;
1452
- _t3 = _context1["catch"](1);
1453
- _iterator2.e(_t3);
1454
- case 7:
1455
- _context1.prev = 7;
1456
- _iterator2.f();
1457
- return _context1.finish(7);
1458
- case 8:
1459
- if (_this1.selected != null) {
1460
- _this1.selected.receiveComments(comments.reverse());
1461
- _this1.sortComments();
1462
- }
1463
- return _context1.abrupt("return", comments);
1464
- case 9:
1465
- case "end":
1466
- return _context1.stop();
1467
- }
1468
- }, _callee1, null, [[1, 6, 7, 8]]);
1469
- }));
1470
- return function (_x9) {
1471
- return _ref1.apply(this, arguments);
1472
- };
1473
- }());
1474
- }
1475
- }, {
1476
- key: "loadMore",
1477
- value: function loadMore(lastCommentId) {
1478
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1479
- if (this.selected == null) return;
1480
- options.last_comment_id = lastCommentId;
1481
- options.after = false;
1482
- return this.loadComments(this.selected.id, options);
1483
- }
1484
- }, {
1485
- key: "registerDeviceToken",
1486
- value: function () {
1487
- var _registerDeviceToken = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee10(token) {
1488
- var isDevelopment,
1489
- res,
1490
- _args10 = arguments;
1491
- return _regenerator["default"].wrap(function (_context10) {
1492
- while (1) switch (_context10.prev = _context10.next) {
1493
- case 0:
1494
- isDevelopment = _args10.length > 1 && _args10[1] !== undefined ? _args10[1] : false;
1495
- _context10.next = 1;
1496
- return this.HTTPAdapter.post('api/v2/sdk/set_user_device_token', {
1497
- device_token: token,
1498
- device_platform: 'rn',
1499
- is_development: isDevelopment
1500
- });
1501
- case 1:
1502
- res = _context10.sent;
1503
- return _context10.abrupt("return", res.body.results);
1504
- case 2:
1505
- case "end":
1506
- return _context10.stop();
1507
- }
1508
- }, _callee10, this);
1509
- }));
1510
- function registerDeviceToken(_x0) {
1511
- return _registerDeviceToken.apply(this, arguments);
1512
- }
1513
- return registerDeviceToken;
1514
- }()
1515
- }, {
1516
- key: "removeDeviceToken",
1517
- value: function () {
1518
- var _removeDeviceToken = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee11(token) {
1519
- var isDevelopment,
1520
- res,
1521
- _args11 = arguments;
1522
- return _regenerator["default"].wrap(function (_context11) {
1523
- while (1) switch (_context11.prev = _context11.next) {
1524
- case 0:
1525
- isDevelopment = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : false;
1526
- _context11.next = 1;
1527
- return this.HTTPAdapter.post('api/v2/sdk/remove_user_device_token', {
1528
- device_token: token,
1529
- device_platform: 'rn',
1530
- is_development: isDevelopment
1531
- });
1532
- case 1:
1533
- res = _context11.sent;
1534
- return _context11.abrupt("return", res.body.results);
1535
- case 2:
1536
- case "end":
1537
- return _context11.stop();
1538
- }
1539
- }, _callee11, this);
1540
- }));
1541
- function removeDeviceToken(_x1) {
1542
- return _removeDeviceToken.apply(this, arguments);
1543
- }
1544
- return removeDeviceToken;
1545
- }()
1546
- /**
1547
- *
1548
- * Search Qiscus Messages
1549
- *
1550
- * @param {any} [params={query,room_id,last_comment_id}]
1551
- * @memberof qiscusSDK
1552
- */
1553
- }, {
1554
- key: "searchMessages",
1555
- value: (function () {
1556
- var _searchMessages = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee12() {
1557
- var params,
1558
- messages,
1559
- _args12 = arguments;
1560
- return _regenerator["default"].wrap(function (_context12) {
1561
- while (1) switch (_context12.prev = _context12.next) {
1562
- case 0:
1563
- params = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {};
1564
- console.warn('Deprecated: search message will be removed on next release');
1565
- _context12.next = 1;
1566
- return this.userAdapter.searchMessages(params);
1567
- case 1:
1568
- messages = _context12.sent;
1569
- return _context12.abrupt("return", messages.map(function (message) {
1570
- return new _Comment["default"](message);
1571
- }));
1572
- case 2:
1573
- case "end":
1574
- return _context12.stop();
1575
- }
1576
- }, _callee12, this);
1577
- }));
1578
- function searchMessages() {
1579
- return _searchMessages.apply(this, arguments);
1580
905
  }
1581
- return searchMessages;
1582
- }())
1583
- }, {
1584
- key: "updateProfile",
1585
- value: function updateProfile(user) {
1586
- var _this10 = this;
1587
- return this.userAdapter.updateProfile(user).then(function (res) {
1588
- _this10.events.emit('profile-updated', user);
1589
- _this10.userData = res;
1590
- return Promise.resolve(res);
1591
- }, function (err) {
1592
- return _this10.logger(err);
906
+ }, 3e3);
907
+ }
908
+ /**
909
+ * Chat with targetted email
910
+ * @param userId {string} - target userId
911
+ * @param options {object} - optional data sent to qiscus database
912
+ * @return room <Room>
913
+ */
914
+ chatTarget(userId, options = {}) {
915
+ if (this.userData.length != null) return false;
916
+ const initialMessage = options ? options.message : null;
917
+ const distinctId = options.distinctId;
918
+ this.isLoading = true;
919
+ this.isTypingStatus = "";
920
+ return this.roomAdapter.getOrCreateRoom(userId, options, distinctId).then((resp) => __async(this, null, function* () {
921
+ const room2 = new Room(resp);
922
+ this.updateLastReceivedComment(room2.last_comment_id);
923
+ this.isLoading = false;
924
+ const mapIntercept = (it) => __async(this, null, function* () {
925
+ return yield this._hookAdapter.trigger(
926
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
927
+ it
928
+ );
1593
929
  });
1594
- }
1595
- }, {
1596
- key: "getNonce",
1597
- value: function getNonce() {
1598
- return _superagent["default"].post("".concat(this.baseURL, "/api/v2/sdk/auth/nonce")).send().set('qiscus_sdk_app_id', "".concat(this.AppId)).set('qiscus_sdk_version', "".concat(this.version)).then(function (res) {
1599
- return Promise.resolve(res.body.results);
1600
- }, function (err) {
1601
- return Promise.reject(err);
930
+ room2.comments = yield Promise.all(
931
+ room2.comments.map((comment) => mapIntercept(comment))
932
+ );
933
+ this.setActiveRoom(room2);
934
+ const lastComment = room2.comments[room2.comments.length - 1];
935
+ if (lastComment) this.readComment(room2.id, lastComment.id);
936
+ this.events.emit("chat-room-created", {
937
+ room: room2
1602
938
  });
1603
- }
1604
- }, {
1605
- key: "verifyIdentityToken",
1606
- value: function verifyIdentityToken(identityToken) {
1607
- return _superagent["default"].post("".concat(this.baseURL, "/api/v2/sdk/auth/verify_identity_token")).send({
1608
- identity_token: identityToken
1609
- }).set('qiscus_sdk_app_id', "".concat(this.AppId)).set('qiscus_sdk_version', "".concat(this.version)).then(function (res) {
1610
- return Promise.resolve(res.body.results);
1611
- }, function (err) {
1612
- return Promise.reject(err);
939
+ if (!initialMessage) return room2;
940
+ const topicId = room2.id;
941
+ return this.sendComment(topicId, initialMessage).then(() => Promise.resolve(room2)).catch((err) => {
942
+ console.error("Error when submit comment", err);
1613
943
  });
1614
- }
1615
-
1616
- /**
1617
- *
1618
- * Step of submitting:
1619
- * - we need to create a new comment object
1620
- * - attach it with negative number id, and also the uniqueId, uniqueId is used
1621
- * to target this particular comment when there's response from server (sent, delivered state)
1622
- * @param {Int} topicId - the topic id of comment to be submitted
1623
- * @param {String} commentMessage - comment to be submitted
1624
- * @param uniqueId {String}
1625
- * @param type {String}
1626
- * @param payload {Object}
1627
- * @param extras {Object}
1628
- * @return {Promise}
1629
- */
1630
- // #region sendComment
1631
- }, {
1632
- key: "sendComment",
1633
- value: (function () {
1634
- var _sendComment = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee13(topicId, commentMessage, uniqueId) {
1635
- var _this11 = this;
1636
- var type,
1637
- payload,
1638
- extras,
1639
- self,
1640
- commentData,
1641
- pendingComment,
1642
- parsedPayload,
1643
- repliedMessage,
1644
- extrasToBeSubmitted,
1645
- messageData,
1646
- sendComment,
1647
- _this$options$comment,
1648
- _this$options,
1649
- res,
1650
- commentIndex,
1651
- _error$message$toLowe,
1652
- _error$message,
1653
- whitelistedErrorStatus,
1654
- message,
1655
- isOffline,
1656
- _args13 = arguments,
1657
- _t4;
1658
- return _regenerator["default"].wrap(function (_context13) {
1659
- while (1) switch (_context13.prev = _context13.next) {
1660
- case 0:
1661
- type = _args13.length > 3 && _args13[3] !== undefined ? _args13[3] : 'text';
1662
- payload = _args13.length > 4 ? _args13[4] : undefined;
1663
- extras = _args13.length > 5 ? _args13[5] : undefined;
1664
- self = this; // set extra data, etc
1665
- if (self.options.prePostCommentCallback) {
1666
- self.options.prePostCommentCallback(commentMessage);
1667
- }
1668
- /**
1669
- * example:
1670
- * commentFormaterCallback(msg) {
1671
- * return filterBadWords(msg) // define your own filter function and return its' value
1672
- * }
1673
- */
1674
- if (self.options.commentFormaterCallback) {
1675
- commentMessage = self.options.commentFormaterCallback(commentMessage);
1676
- }
1677
- self.pendingCommentId--;
1678
- commentData = {
1679
- room_id: topicId,
1680
- message: commentMessage,
1681
- username_as: this.username,
1682
- username_real: this.user_id,
1683
- user_avatar_url: this.userData.avatar_url,
1684
- user_extras: this.userData.user_extras,
1685
- id: Math.round(Date.now() * 1e6 + Date.now()),
1686
- type: type || 'text',
1687
- timestamp: (0, _format["default"])(new Date()),
1688
- unique_id: uniqueId ? String(uniqueId) : null,
1689
- payload: (0, _util.tryCatch)(function () {
1690
- return JSON.parse(payload);
1691
- }, payload, function (error) {
1692
- return _this11.logger('Error when parsing payload', error.message);
1693
- })
1694
- };
1695
- pendingComment = self.prepareCommentToBeSubmitted(commentData); // push this comment unto active room
1696
- if (type === 'reply') {
1697
- // change payload for pendingComment
1698
- // get the comment for current replied id
1699
- parsedPayload = JSON.parse(payload);
1700
- repliedMessage = self.selected.comments.find(function (cmt) {
1701
- return cmt.id === parsedPayload.replied_comment_id;
1702
- });
1703
- parsedPayload.replied_comment_message = repliedMessage.type === 'reply' ? repliedMessage.payload.text : repliedMessage.message;
1704
- parsedPayload.replied_comment_sender_username = repliedMessage.username_as;
1705
- pendingComment.payload = parsedPayload;
1706
- }
1707
- extrasToBeSubmitted = extras || self.extras;
1708
- _context13.next = 1;
1709
- return this._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_SENT, _objectSpread(_objectSpread({}, pendingComment), {}, {
1710
- extras: extrasToBeSubmitted
1711
- }));
1712
- case 1:
1713
- messageData = _context13.sent;
1714
- messageData = self.prepareCommentToBeSubmitted(messageData);
1715
- if (self.selected) self.selected.comments.push(messageData);
1716
- sendComment = function sendComment() {
1717
- return _this11.userAdapter.postComment('' + topicId, messageData.message, messageData.unique_id, messageData.type, messageData.payload, messageData.extras);
1718
- };
1719
- _context13.prev = 2;
1720
- _context13.next = 3;
1721
- return sendComment();
1722
- case 3:
1723
- res = _context13.sent;
1724
- _context13.next = 4;
1725
- return this._hookAdapter.trigger(_hook.Hooks.MESSAGE_BEFORE_RECEIVED, res);
1726
- case 4:
1727
- res = _context13.sent;
1728
- Object.assign(messageData, res);
1729
- if (self.selected) {
1730
- _context13.next = 5;
1731
- break;
1732
- }
1733
- return _context13.abrupt("return", Promise.resolve(messageData));
1734
- case 5:
1735
- // When the posting succeeded, we mark the Comment as sent,
1736
- // so all the interested party can be notified.
1737
- messageData.markAsSent();
1738
- messageData.id = res.id;
1739
- messageData.before_id = res.comment_before_id;
1740
- // update the timestamp also then re-sort the comment list
1741
- messageData.unix_timestamp = res.unix_timestamp;
1742
- (_this$options$comment = (_this$options = this.options).commentSentCallback) === null || _this$options$comment === void 0 || _this$options$comment.call(_this$options, {
1743
- comment: messageData
1744
- });
1745
- self.events.emit('comment-sent', messageData);
1746
- self.sortComments();
1747
- commentIndex = self._pendingComments.findIndex(function (c) {
1748
- return c.unique_id === messageData.unique_id;
1749
- });
1750
- if (commentIndex > -1) {
1751
- self._pendingComments.splice(commentIndex, 1);
1752
- }
1753
- return _context13.abrupt("return", messageData);
1754
- case 6:
1755
- _context13.prev = 6;
1756
- _t4 = _context13["catch"](2);
1757
- messageData.markAsFailed();
1758
- // From superagent: `https://forwardemail.github.io/superagent/#retrying-requests`
1759
- whitelistedErrorStatus = [undefined, 408, 413, 429, 500, 502, 503, 504, 521, 522, 524];
1760
- message = (_error$message$toLowe = (_error$message = _t4.message) === null || _error$message === void 0 ? void 0 : _error$message.toLowerCase()) !== null && _error$message$toLowe !== void 0 ? _error$message$toLowe : '';
1761
- isOffline = message.includes('offline');
1762
- if (whitelistedErrorStatus.includes(_t4.status) || isOffline) {
1763
- this._pendingComments.push(messageData);
1764
- this.logger('Failed sending comment', _t4);
1765
- }
1766
- return _context13.abrupt("return", Promise.reject(_t4));
1767
- case 7:
1768
- case "end":
1769
- return _context13.stop();
1770
- }
1771
- }, _callee13, this, [[2, 6]]);
1772
- }));
1773
- function sendComment(_x10, _x11, _x12) {
1774
- return _sendComment.apply(this, arguments);
944
+ })).catch((err) => {
945
+ console.error("Error when creating room", err);
946
+ this.isLoading = false;
947
+ return Promise.reject(err);
948
+ });
949
+ }
950
+ /**
951
+ *
952
+ * Open a group chat or target a specific room id
953
+ *
954
+ * @param {int} id
955
+ * @returns Room <Room>
956
+ * @memberof QiscusSDK
957
+ */
958
+ chatGroup(id) {
959
+ const self = this;
960
+ if (!self.isInit) return;
961
+ return self.getRoomById(id).then(
962
+ (response) => {
963
+ return Promise.resolve(response);
964
+ },
965
+ (err) => Promise.reject(err)
966
+ );
967
+ }
968
+ /**
969
+ * @param {int} id - Room Id
970
+ * @return {Room} Room data
971
+ */
972
+ getRoomById(id) {
973
+ if (!this.isInit) return;
974
+ const self = this;
975
+ self.isLoading = true;
976
+ self.isTypingStatus = "";
977
+ return self.roomAdapter.getRoomById(id).then((resp) => __async(this, null, function* () {
978
+ const roomData = resp.results.room;
979
+ const comments = [];
980
+ for (const comment of resp.results.comments.reverse()) {
981
+ const c = yield this._hookAdapter.trigger(
982
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
983
+ comment
984
+ );
985
+ comments.push(c);
1775
986
  }
1776
- return sendComment;
1777
- }())
1778
- }, {
1779
- key: "_retrySendComment",
1780
- value: function () {
1781
- var _retrySendComment2 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee15(comment) {
1782
- var _this$_pendingComment,
1783
- _this12 = this;
1784
- var _this$options$comment2, _this$options2, index;
1785
- return _regenerator["default"].wrap(function (_context15) {
1786
- while (1) switch (_context15.prev = _context15.next) {
1787
- case 0:
1788
- this.logger('Retrying send comment', comment);
1789
- this._pendingCommentsCount[comment.unique_id] = ((_this$_pendingComment = this._pendingCommentsCount[comment.unique_id]) !== null && _this$_pendingComment !== void 0 ? _this$_pendingComment : 0) + 1;
1790
-
1791
- // If it is exceeding the maximum retry count (which is 10), we will not retry anymore
1792
- if (!(this._pendingCommentsCount[comment.unique_id] > 10)) {
1793
- _context15.next = 1;
1794
- break;
1795
- }
1796
- this.logger("Exceeding maximum retry count for comment ".concat(comment.unique_id, ", not retrying anymore"));
1797
- (_this$options$comment2 = (_this$options2 = this.options).commentRetryExceedCallback) === null || _this$options$comment2 === void 0 || _this$options$comment2.call(_this$options2, comment);
1798
- // Remove the comment from pending comments
1799
- index = this._pendingComments.findIndex(function (c) {
1800
- return c.unique_id === comment.unique_id;
1801
- });
1802
- if (index > -1) {
1803
- this._pendingComments.splice(index, 1);
1804
- }
1805
- // Mark the comment as failed
1806
- comment.markAsFailed();
1807
- // Emit the event
1808
- this.events.emit('comment-retry-exceed', comment);
1809
- return _context15.abrupt("return", Promise.reject(new Error('Exceeding maximum retry count')));
1810
- case 1:
1811
- return _context15.abrupt("return", this.userAdapter.postComment('' + comment.room_id, comment.message, comment.unique_id, comment.type, comment.payload, comment.extras).then(/*#__PURE__*/function () {
1812
- var _ref10 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee14(res) {
1813
- var _this12$selected, _this12$selected2, _this12$options$comme, _this12$options;
1814
- var index, commentIndex;
1815
- return _regenerator["default"].wrap(function (_context14) {
1816
- while (1) switch (_context14.prev = _context14.next) {
1817
- case 0:
1818
- if (!(((_this12$selected = _this12.selected) === null || _this12$selected === void 0 ? void 0 : _this12$selected.id) !== comment.room_id)) {
1819
- _context14.next = 1;
1820
- break;
1821
- }
1822
- return _context14.abrupt("return", res);
1823
- case 1:
1824
- Object.assign(comment, res);
1825
- comment.markAsSent();
1826
- comment.id = res.id;
1827
- comment.before_id = res.comment_before_id;
1828
- comment.unix_timestamp = res.unix_timestamp;
1829
- index = (_this12$selected2 = _this12.selected) === null || _this12$selected2 === void 0 ? void 0 : _this12$selected2.comments.findIndex(function (c) {
1830
- return c.unique_id === comment.unique_id;
1831
- });
1832
- if (index > -1) {
1833
- _this12.selected.comments[index] = comment;
1834
- }
1835
- _this12.sortComments();
1836
- (_this12$options$comme = (_this12$options = _this12.options).commentSentCallback) === null || _this12$options$comme === void 0 || _this12$options$comme.call(_this12$options, {
1837
- comment: comment
1838
- });
1839
- _this12.events.emit('comment-sent', comment);
1840
- commentIndex = _this12._pendingComments.findIndex(function (c) {
1841
- return c.unique_id === comment.unique_id;
1842
- });
1843
- if (commentIndex > -1) {
1844
- _this12._pendingComments.splice(commentIndex, 1);
1845
- }
1846
- return _context14.abrupt("return", comment);
1847
- case 2:
1848
- case "end":
1849
- return _context14.stop();
1850
- }
1851
- }, _callee14);
1852
- }));
1853
- return function (_x14) {
1854
- return _ref10.apply(this, arguments);
1855
- };
1856
- }())["catch"](function (err) {
1857
- comment.markAsFailed();
1858
- return Promise.reject(err);
1859
- }));
1860
- case 2:
1861
- case "end":
1862
- return _context15.stop();
1863
- }
1864
- }, _callee15, this);
987
+ const room2 = new Room(__spreadProps(__spreadValues({}, roomData), {
988
+ comments,
989
+ name: roomData.room_name
1865
990
  }));
1866
- function _retrySendComment(_x13) {
1867
- return _retrySendComment2.apply(this, arguments);
991
+ self.updateLastReceivedComment(room2.last_comment_id);
992
+ self.setActiveRoom(room2);
993
+ self.isLoading = false;
994
+ const lastComment = room2.comments[room2.comments.length - 1];
995
+ if (lastComment) self.readComment(room2.id, lastComment.id);
996
+ if (room2.isChannel) {
997
+ this.realtimeAdapter.subscribeChannel(this.AppId, room2.unique_id);
1868
998
  }
1869
- return _retrySendComment;
1870
- }() // #endregion
1871
- }, {
1872
- key: "getUsers",
1873
- value: function getUsers() {
1874
- var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
1875
- var page = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
1876
- var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
1877
- return this.HTTPAdapter.get_request('api/v2/sdk/get_user_list').query({
1878
- query: query,
1879
- page: page,
1880
- limit: limit
1881
- }).then(function (resp) {
1882
- return Promise.resolve(resp.body.results);
1883
- });
1884
- }
1885
- }, {
1886
- key: "getParticipants",
1887
- value: function getParticipants(roomUniqueId) {
1888
- var page = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
1889
- var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
1890
- return this.HTTPAdapter.get_request('api/v2/sdk/room_participants').query({
1891
- room_unique_id: roomUniqueId,
1892
- page: page,
1893
- limit: limit
1894
- }).then(function (resp) {
1895
- return resp.body.results;
999
+ return room2;
1000
+ })).catch((error) => {
1001
+ console.error("Error getting room by id", error);
1002
+ return Promise.reject(error);
1003
+ });
1004
+ }
1005
+ /**
1006
+ * @param {int} id - Room Id
1007
+ * @param {string} roomName
1008
+ * @param {string} avatarURL
1009
+ * @return {Room} Room data
1010
+ */
1011
+ getOrCreateRoomByUniqueId(id, roomName, avatarURL) {
1012
+ const self = this;
1013
+ self.isLoading = true;
1014
+ self.isTypingStatus = "";
1015
+ return self.roomAdapter.getOrCreateRoomByUniqueId(id, roomName, avatarURL).then((response) => __async(this, null, function* () {
1016
+ let room2 = new Room(response);
1017
+ self.updateLastReceivedComment(room2.last_comment_id);
1018
+ const mapIntercept = (item) => __async(this, null, function* () {
1019
+ return yield this._hookAdapter.trigger(hook.Hooks.MESSAGE_BEFORE_RECEIVED, item);
1896
1020
  });
1897
- }
1898
- }, {
1899
- key: "getRoomParticipants",
1900
- value: function getRoomParticipants(roomUniqueId) {
1901
- var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1902
- console.warn('`getRoomParticipants` are deprecated, use `getParticipants` instead.');
1903
- return this.HTTPAdapter.get_request('api/v2/sdk/room_participants').query({
1904
- room_unique_id: roomUniqueId,
1905
- offset: offset
1906
- }).then(function (resp) {
1907
- return Promise.resolve(resp.body.results);
1908
- });
1909
- }
1910
- }, {
1911
- key: "resendComment",
1912
- value: function resendComment(comment) {
1913
- if (this.selected == null) return;
1914
- var self = this;
1915
- var room = self.selected;
1916
- var pendingComment = room.comments.find(function (cmtToFind) {
1917
- return cmtToFind.id === comment.id;
1918
- });
1919
- var extrasToBeSubmitted = self.extras;
1920
- return this.userAdapter.postComment('' + room.id, pendingComment.message, pendingComment.unique_id, comment.type, comment.payload, extrasToBeSubmitted).then(function (res) {
1921
- // When the posting succeeded, we mark the Comment as sent,
1922
- // so all the interested party can be notified.
1923
- pendingComment.markAsSent();
1924
- pendingComment.id = res.id;
1925
- pendingComment.before_id = res.comment_before_id;
1926
- return new Promise(function (resolve, reject) {
1927
- return resolve(self.selected);
1928
- });
1929
- }, function (err) {
1930
- pendingComment.markAsFailed();
1931
- return new Promise(function (resolve, reject) {
1932
- return reject(err);
1933
- });
1021
+ room2.comments = yield Promise.all(
1022
+ room2.comments.map((it) => mapIntercept(it))
1023
+ );
1024
+ self.setActiveRoom(room2);
1025
+ self.isLoading = false;
1026
+ const lastComment = room2.comments[room2.comments.length - 1];
1027
+ if (lastComment) self.readComment(room2.id, lastComment.id);
1028
+ this.realtimeAdapter.subscribeChannel(this.AppId, room2.unique_id);
1029
+ return Promise.resolve(room2);
1030
+ })).catch((error) => {
1031
+ return Promise.reject(error);
1032
+ });
1033
+ }
1034
+ getOrCreateRoomByChannel(channel, name, avatarURL) {
1035
+ return this.getOrCreateRoomByUniqueId(channel, name, avatarURL);
1036
+ }
1037
+ sortComments() {
1038
+ this.selected && this.selected.comments.sort(function(leftSideComment, rightSideComment) {
1039
+ return leftSideComment.unix_timestamp - rightSideComment.unix_timestamp;
1040
+ });
1041
+ }
1042
+ loadRoomList() {
1043
+ return __async(this, arguments, function* (params = {}) {
1044
+ const rooms = yield this.userAdapter.loadRoomList(params);
1045
+ return rooms.map((room2) => {
1046
+ room2.last_comment_id = room2.last_comment.id;
1047
+ room2.last_comment_message = room2.last_comment.message;
1048
+ room2.last_comment_message_created_at = room2.last_comment.timestamp;
1049
+ room2.room_type = room2.chat_type;
1050
+ room2.comments = [];
1051
+ return new Room(room2);
1934
1052
  });
1935
- }
1936
- }, {
1937
- key: "prepareCommentToBeSubmitted",
1938
- value: function prepareCommentToBeSubmitted(comment) {
1939
- var commentToBeSubmitted, uniqueId;
1940
- commentToBeSubmitted = new _Comment["default"](comment);
1941
- // We're gonna use timestamp for uniqueId for now.
1942
- // "bq" stands for "Bonjour Qiscus" by the way.
1943
- uniqueId = 'bq' + Date.now();
1944
- if (comment.unique_id) uniqueId = comment.unique_id;
1945
- commentToBeSubmitted.attachUniqueId(uniqueId);
1946
- commentToBeSubmitted.markAsPending();
1947
- commentToBeSubmitted.isDelivered = false;
1948
- commentToBeSubmitted.isSent = false;
1949
- commentToBeSubmitted.isRead = false;
1950
- commentToBeSubmitted.unix_timestamp = Math.round(new Date().getTime() / 1000);
1951
- return commentToBeSubmitted;
1952
- }
1953
-
1954
- /**
1955
- * Update room
1956
- * @param {id, room_name, avatar_url, options} args
1957
- * @return Promise
1958
- */
1959
- }, {
1960
- key: "updateRoom",
1961
- value: function updateRoom(args) {
1962
- return this.roomAdapter.updateRoom(args);
1963
- }
1964
- }, {
1965
- key: "removeSelectedRoomParticipants",
1966
- value: function removeSelectedRoomParticipants() {
1967
- var values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
1968
- var payload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id';
1969
- if (_is["default"].not.array(values)) {
1970
- return Promise.reject(new Error('`values` must have type of array'));
1053
+ });
1054
+ }
1055
+ loadComments(roomId, options = {}) {
1056
+ return this.userAdapter.loadComments(roomId, options).then((comments_) => __async(this, null, function* () {
1057
+ const comments = [];
1058
+ for (const comment of comments_) {
1059
+ comments.push(
1060
+ yield this._hookAdapter.trigger(
1061
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
1062
+ comment
1063
+ )
1064
+ );
1971
1065
  }
1972
- var participants = this.selected.participants;
1973
- if (!participants) {
1974
- return Promise.reject(new Error('Nothing selected room chat.'));
1066
+ if (this.selected != null) {
1067
+ this.selected.receiveComments(comments.reverse());
1068
+ this.sortComments();
1975
1069
  }
1976
- // start to changes selected participants with newest values
1977
- var participantsExclude = participants;
1978
- if (payload === 'id') {
1979
- participantsExclude = participants.filter(function (participant) {
1980
- return values.indexOf(participant.id) <= -1;
1981
- });
1070
+ return comments;
1071
+ }));
1072
+ }
1073
+ loadMore(lastCommentId, options = {}) {
1074
+ if (this.selected == null) return;
1075
+ options.last_comment_id = lastCommentId;
1076
+ options.after = false;
1077
+ return this.loadComments(this.selected.id, options);
1078
+ }
1079
+ registerDeviceToken(token, isDevelopment = false) {
1080
+ return __async(this, null, function* () {
1081
+ const res = yield this.HTTPAdapter.post(
1082
+ "api/v2/sdk/set_user_device_token",
1083
+ {
1084
+ device_token: token,
1085
+ device_platform: "rn",
1086
+ is_development: isDevelopment
1087
+ }
1088
+ );
1089
+ return res.body.results;
1090
+ });
1091
+ }
1092
+ removeDeviceToken(token, isDevelopment = false) {
1093
+ return __async(this, null, function* () {
1094
+ const res = yield this.HTTPAdapter.post(
1095
+ "api/v2/sdk/remove_user_device_token",
1096
+ {
1097
+ device_token: token,
1098
+ device_platform: "rn",
1099
+ is_development: isDevelopment
1100
+ }
1101
+ );
1102
+ return res.body.results;
1103
+ });
1104
+ }
1105
+ /**
1106
+ *
1107
+ * Search Qiscus Messages
1108
+ *
1109
+ * @param {any} [params={query,room_id,last_comment_id}]
1110
+ * @memberof qiscusSDK
1111
+ */
1112
+ searchMessages() {
1113
+ return __async(this, arguments, function* (params = {}) {
1114
+ console.warn("Deprecated: search message will be removed on next release");
1115
+ const messages = yield this.userAdapter.searchMessages(params);
1116
+ return messages.map((message) => {
1117
+ return new Comment(message);
1118
+ });
1119
+ });
1120
+ }
1121
+ updateProfile(user2) {
1122
+ return this.userAdapter.updateProfile(user2).then(
1123
+ (res) => {
1124
+ this.events.emit("profile-updated", user2);
1125
+ this.userData = res;
1126
+ return Promise.resolve(res);
1127
+ },
1128
+ (err) => this.logger(err)
1129
+ );
1130
+ }
1131
+ getNonce() {
1132
+ return request.post(`${this.baseURL}/api/v2/sdk/auth/nonce`).send().set("qiscus_sdk_app_id", `${this.AppId}`).set("qiscus_sdk_version", `${this.version}`).then(
1133
+ (res) => Promise.resolve(res.body.results),
1134
+ (err) => Promise.reject(err)
1135
+ );
1136
+ }
1137
+ verifyIdentityToken(identityToken) {
1138
+ return request.post(`${this.baseURL}/api/v2/sdk/auth/verify_identity_token`).send({
1139
+ identity_token: identityToken
1140
+ }).set("qiscus_sdk_app_id", `${this.AppId}`).set("qiscus_sdk_version", `${this.version}`).then(
1141
+ (res) => Promise.resolve(res.body.results),
1142
+ (err) => Promise.reject(err)
1143
+ );
1144
+ }
1145
+ /**
1146
+ *
1147
+ * Step of submitting:
1148
+ * - we need to create a new comment object
1149
+ * - attach it with negative number id, and also the uniqueId, uniqueId is used
1150
+ * to target this particular comment when there's response from server (sent, delivered state)
1151
+ * @param {Int} topicId - the topic id of comment to be submitted
1152
+ * @param {String} commentMessage - comment to be submitted
1153
+ * @param uniqueId {String}
1154
+ * @param type {String}
1155
+ * @param payload {Object}
1156
+ * @param extras {Object}
1157
+ * @return {Promise}
1158
+ */
1159
+ // #region sendComment
1160
+ sendComment(topicId, commentMessage, uniqueId, type = "text", payload, extras) {
1161
+ return __async(this, null, function* () {
1162
+ var _a, _b, _c, _d;
1163
+ const self = this;
1164
+ if (self.options.prePostCommentCallback) {
1165
+ self.options.prePostCommentCallback(commentMessage);
1982
1166
  }
1983
- if (payload === 'email') {
1984
- participantsExclude = participants.filter(function (participant) {
1985
- return values.indexOf(participant.email) <= -1;
1986
- });
1167
+ if (self.options.commentFormaterCallback) {
1168
+ commentMessage = self.options.commentFormaterCallback(commentMessage);
1987
1169
  }
1988
- if (payload === 'username') {
1989
- participantsExclude = participants.filter(function (participant) {
1990
- return values.indexOf(participant.username) <= -1;
1991
- });
1170
+ self.pendingCommentId--;
1171
+ const commentData = {
1172
+ room_id: topicId,
1173
+ message: commentMessage,
1174
+ username_as: this.username,
1175
+ username_real: this.user_id,
1176
+ user_avatar_url: this.userData.avatar_url,
1177
+ user_extras: this.userData.user_extras,
1178
+ id: Math.round(Date.now() * 1e6 + Date.now()),
1179
+ type: type || "text",
1180
+ timestamp: format(/* @__PURE__ */ new Date()),
1181
+ unique_id: uniqueId ? String(uniqueId) : null,
1182
+ payload: util.tryCatch(
1183
+ () => JSON.parse(payload),
1184
+ payload,
1185
+ (error) => this.logger("Error when parsing payload", error.message)
1186
+ )
1187
+ };
1188
+ const pendingComment = self.prepareCommentToBeSubmitted(commentData);
1189
+ if (type === "reply") {
1190
+ var parsedPayload = JSON.parse(payload);
1191
+ var repliedMessage = self.selected.comments.find(
1192
+ (cmt) => cmt.id === parsedPayload.replied_comment_id
1193
+ );
1194
+ parsedPayload.replied_comment_message = repliedMessage.type === "reply" ? repliedMessage.payload.text : repliedMessage.message;
1195
+ parsedPayload.replied_comment_sender_username = repliedMessage.username_as;
1196
+ pendingComment.payload = parsedPayload;
1992
1197
  }
1993
- this.selected.participants = participantsExclude;
1994
- return Promise.resolve(participants);
1995
- }
1996
-
1997
- /**
1998
- * Create group chat room
1999
- * @param {string} name - Chat room name
2000
- * @param {string[]} emails - Participant to be invited
2001
- * @returns {Promise.<Room, Error>} - Room detail
2002
- */
2003
- }, {
2004
- key: "createGroupRoom",
2005
- value: function createGroupRoom(name, emails, options) {
2006
- var self = this;
2007
- if (!this.isLogin) throw new Error('Please initiate qiscus SDK first');
2008
- return new _utils.GroupChatBuilder(this.roomAdapter).withName(name).withOptions(options).addParticipants(emails).create().then(function (res) {
2009
- self.events.emit('group-room-created', res);
2010
- return Promise.resolve(res);
2011
- });
2012
- }
2013
-
2014
- /**
2015
- * Add array of participant into a group
2016
- *
2017
- * @param {any} roomId the room id this file is required for selected room_id to be process
2018
- * @param {any} emails emails is must be an array
2019
- * @returns Promise
2020
- * @memberof QiscusSDK
2021
- */
2022
- }, {
2023
- key: "addParticipantsToGroup",
2024
- value: function addParticipantsToGroup(roomId, emails) {
2025
- var self = this;
2026
- if (!Array.isArray(emails)) {
2027
- throw new Error("emails' must be type of Array");
1198
+ const extrasToBeSubmitted = extras || self.extras;
1199
+ let messageData = yield this._hookAdapter.trigger(
1200
+ hook.Hooks.MESSAGE_BEFORE_SENT,
1201
+ __spreadProps(__spreadValues({}, pendingComment), {
1202
+ extras: extrasToBeSubmitted
1203
+ })
1204
+ );
1205
+ messageData = self.prepareCommentToBeSubmitted(messageData);
1206
+ if (self.selected) self.selected.comments.push(messageData);
1207
+ const sendComment = () => this.userAdapter.postComment(
1208
+ "" + topicId,
1209
+ messageData.message,
1210
+ messageData.unique_id,
1211
+ messageData.type,
1212
+ messageData.payload,
1213
+ messageData.extras
1214
+ );
1215
+ try {
1216
+ let res = yield sendComment();
1217
+ res = yield this._hookAdapter.trigger(hook.Hooks.MESSAGE_BEFORE_RECEIVED, res);
1218
+ Object.assign(messageData, res);
1219
+ if (!self.selected) return Promise.resolve(messageData);
1220
+ messageData.markAsSent();
1221
+ messageData.id = res.id;
1222
+ messageData.before_id = res.comment_before_id;
1223
+ messageData.unix_timestamp = res.unix_timestamp;
1224
+ (_b = (_a = this.options).commentSentCallback) == null ? void 0 : _b.call(_a, { comment: messageData });
1225
+ self.events.emit("comment-sent", messageData);
1226
+ self.sortComments();
1227
+ const commentIndex = self._pendingComments.findIndex(
1228
+ (c) => c.unique_id === messageData.unique_id
1229
+ );
1230
+ if (commentIndex > -1) {
1231
+ self._pendingComments.splice(commentIndex, 1);
1232
+ }
1233
+ return messageData;
1234
+ } catch (error) {
1235
+ messageData.markAsFailed();
1236
+ const whitelistedErrorStatus = [
1237
+ void 0,
1238
+ 408,
1239
+ 413,
1240
+ 429,
1241
+ 500,
1242
+ 502,
1243
+ 503,
1244
+ 504,
1245
+ 521,
1246
+ 522,
1247
+ 524
1248
+ ];
1249
+ const message = (_d = (_c = error.message) == null ? void 0 : _c.toLowerCase()) != null ? _d : "";
1250
+ const isOffline = message.includes("offline");
1251
+ if (whitelistedErrorStatus.includes(error.status) || isOffline) {
1252
+ this._pendingComments.push(messageData);
1253
+ this.logger("Failed sending comment", error);
1254
+ }
1255
+ return Promise.reject(error);
2028
1256
  }
2029
- return self.roomAdapter.addParticipantsToGroup(roomId, emails).then(function (res) {
2030
- self.events.emit('participants-added', res);
2031
- return Promise.resolve(res);
2032
- }, function (err) {
1257
+ });
1258
+ }
1259
+ _retrySendComment(comment) {
1260
+ return __async(this, null, function* () {
1261
+ var _a, _b, _c;
1262
+ this.logger("Retrying send comment", comment);
1263
+ this._pendingCommentsCount[comment.unique_id] = ((_a = this._pendingCommentsCount[comment.unique_id]) != null ? _a : 0) + 1;
1264
+ if (this._pendingCommentsCount[comment.unique_id] > 10) {
1265
+ this.logger(
1266
+ `Exceeding maximum retry count for comment ${comment.unique_id}, not retrying anymore`
1267
+ );
1268
+ (_c = (_b = this.options).commentRetryExceedCallback) == null ? void 0 : _c.call(_b, comment);
1269
+ const index = this._pendingComments.findIndex(
1270
+ (c) => c.unique_id === comment.unique_id
1271
+ );
1272
+ if (index > -1) {
1273
+ this._pendingComments.splice(index, 1);
1274
+ }
1275
+ comment.markAsFailed();
1276
+ this.events.emit("comment-retry-exceed", comment);
1277
+ return Promise.reject(new Error("Exceeding maximum retry count"));
1278
+ }
1279
+ return this.userAdapter.postComment(
1280
+ "" + comment.room_id,
1281
+ comment.message,
1282
+ comment.unique_id,
1283
+ comment.type,
1284
+ comment.payload,
1285
+ comment.extras
1286
+ ).then((res) => __async(this, null, function* () {
1287
+ var _a2, _b2, _c2, _d;
1288
+ if (((_a2 = this.selected) == null ? void 0 : _a2.id) !== comment.room_id) {
1289
+ return res;
1290
+ }
1291
+ Object.assign(comment, res);
1292
+ comment.markAsSent();
1293
+ comment.id = res.id;
1294
+ comment.before_id = res.comment_before_id;
1295
+ comment.unix_timestamp = res.unix_timestamp;
1296
+ const index = (_b2 = this.selected) == null ? void 0 : _b2.comments.findIndex(
1297
+ (c) => c.unique_id === comment.unique_id
1298
+ );
1299
+ if (index > -1) {
1300
+ this.selected.comments[index] = comment;
1301
+ }
1302
+ this.sortComments();
1303
+ (_d = (_c2 = this.options).commentSentCallback) == null ? void 0 : _d.call(_c2, { comment });
1304
+ this.events.emit("comment-sent", comment);
1305
+ const commentIndex = this._pendingComments.findIndex(
1306
+ (c) => c.unique_id === comment.unique_id
1307
+ );
1308
+ if (commentIndex > -1) {
1309
+ this._pendingComments.splice(commentIndex, 1);
1310
+ }
1311
+ return comment;
1312
+ })).catch((err) => {
1313
+ comment.markAsFailed();
2033
1314
  return Promise.reject(err);
2034
1315
  });
2035
- }
2036
-
2037
- /**
2038
- * Remove array of participant from a group
2039
- *
2040
- * @param {any} roomId the room id this file is required for selected room_id to be process
2041
- * @param {any} emails emails is must be an array
2042
- * @returns Promise
2043
- * @memberof QiscusSDK
2044
- */
2045
- }, {
2046
- key: "removeParticipantsFromGroup",
2047
- value: function removeParticipantsFromGroup(roomId, emails) {
2048
- var _this13 = this;
2049
- if (_is["default"].not.array(emails)) {
2050
- return Promise.reject(new Error('`emails` must have type of array'));
1316
+ });
1317
+ }
1318
+ // #endregion
1319
+ getUsers(query = "", page = 1, limit = 20) {
1320
+ return this.HTTPAdapter.get_request("api/v2/sdk/get_user_list").query({
1321
+ query,
1322
+ page,
1323
+ limit
1324
+ }).then((resp) => {
1325
+ return Promise.resolve(resp.body.results);
1326
+ });
1327
+ }
1328
+ getParticipants(roomUniqueId, page = 1, limit = 20) {
1329
+ return this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({
1330
+ room_unique_id: roomUniqueId,
1331
+ page,
1332
+ limit
1333
+ }).then((resp) => resp.body.results);
1334
+ }
1335
+ getRoomParticipants(roomUniqueId, offset = 0) {
1336
+ console.warn(
1337
+ "`getRoomParticipants` are deprecated, use `getParticipants` instead."
1338
+ );
1339
+ return this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({
1340
+ room_unique_id: roomUniqueId,
1341
+ offset
1342
+ }).then((resp) => {
1343
+ return Promise.resolve(resp.body.results);
1344
+ });
1345
+ }
1346
+ resendComment(comment) {
1347
+ if (this.selected == null) return;
1348
+ var self = this;
1349
+ var room2 = self.selected;
1350
+ var pendingComment = room2.comments.find(
1351
+ (cmtToFind) => cmtToFind.id === comment.id
1352
+ );
1353
+ const extrasToBeSubmitted = self.extras;
1354
+ return this.userAdapter.postComment(
1355
+ "" + room2.id,
1356
+ pendingComment.message,
1357
+ pendingComment.unique_id,
1358
+ comment.type,
1359
+ comment.payload,
1360
+ extrasToBeSubmitted
1361
+ ).then(
1362
+ (res) => {
1363
+ pendingComment.markAsSent();
1364
+ pendingComment.id = res.id;
1365
+ pendingComment.before_id = res.comment_before_id;
1366
+ return new Promise((resolve, reject) => resolve(self.selected));
1367
+ },
1368
+ (err) => {
1369
+ pendingComment.markAsFailed();
1370
+ return new Promise((resolve, reject) => reject(err));
2051
1371
  }
2052
- return this.roomAdapter.removeParticipantsFromGroup(roomId, emails).then(function (res) {
2053
- _this13.events.emit('participants-removed', emails);
1372
+ );
1373
+ }
1374
+ prepareCommentToBeSubmitted(comment) {
1375
+ let commentToBeSubmitted = new Comment(comment);
1376
+ let uniqueId = `javascript-${nanoid.nanoid()}`;
1377
+ if (comment.unique_id) uniqueId = comment.unique_id;
1378
+ commentToBeSubmitted.attachUniqueId(uniqueId);
1379
+ commentToBeSubmitted.markAsPending();
1380
+ commentToBeSubmitted.isDelivered = false;
1381
+ commentToBeSubmitted.isSent = false;
1382
+ commentToBeSubmitted.isRead = false;
1383
+ commentToBeSubmitted.unix_timestamp = Math.round(
1384
+ (/* @__PURE__ */ new Date()).getTime() / 1e3
1385
+ );
1386
+ return commentToBeSubmitted;
1387
+ }
1388
+ /**
1389
+ * Update room
1390
+ * @param {id, room_name, avatar_url, options} args
1391
+ * @return Promise
1392
+ */
1393
+ updateRoom(args) {
1394
+ return this.roomAdapter.updateRoom(args);
1395
+ }
1396
+ removeSelectedRoomParticipants(values = [], payload = "id") {
1397
+ if (is.not.array(values)) {
1398
+ return Promise.reject(new Error("`values` must have type of array"));
1399
+ }
1400
+ const participants = this.selected.participants;
1401
+ if (!participants) {
1402
+ return Promise.reject(new Error("Nothing selected room chat."));
1403
+ }
1404
+ let participantsExclude = participants;
1405
+ if (payload === "id") {
1406
+ participantsExclude = participants.filter(
1407
+ (participant) => values.indexOf(participant.id) <= -1
1408
+ );
1409
+ }
1410
+ if (payload === "email") {
1411
+ participantsExclude = participants.filter(
1412
+ (participant) => values.indexOf(participant.email) <= -1
1413
+ );
1414
+ }
1415
+ if (payload === "username") {
1416
+ participantsExclude = participants.filter(
1417
+ (participant) => values.indexOf(participant.username) <= -1
1418
+ );
1419
+ }
1420
+ this.selected.participants = participantsExclude;
1421
+ return Promise.resolve(participants);
1422
+ }
1423
+ /**
1424
+ * Create group chat room
1425
+ * @param {string} name - Chat room name
1426
+ * @param {string[]} emails - Participant to be invited
1427
+ * @returns {Promise.<Room, Error>} - Room detail
1428
+ */
1429
+ createGroupRoom(name, emails, options) {
1430
+ const self = this;
1431
+ if (!this.isLogin) throw new Error("Please initiate qiscus SDK first");
1432
+ return new utils.GroupChatBuilder(this.roomAdapter).withName(name).withOptions(options).addParticipants(emails).create().then((res) => {
1433
+ self.events.emit("group-room-created", res);
1434
+ return Promise.resolve(res);
1435
+ });
1436
+ }
1437
+ /**
1438
+ * Add array of participant into a group
1439
+ *
1440
+ * @param {any} roomId the room id this file is required for selected room_id to be process
1441
+ * @param {any} emails emails is must be an array
1442
+ * @returns Promise
1443
+ * @memberof QiscusSDK
1444
+ */
1445
+ addParticipantsToGroup(roomId, emails) {
1446
+ const self = this;
1447
+ if (!Array.isArray(emails)) {
1448
+ throw new Error(`emails' must be type of Array`);
1449
+ }
1450
+ return self.roomAdapter.addParticipantsToGroup(roomId, emails).then(
1451
+ (res) => {
1452
+ self.events.emit("participants-added", res);
2054
1453
  return Promise.resolve(res);
2055
- });
1454
+ },
1455
+ (err) => Promise.reject(err)
1456
+ );
1457
+ }
1458
+ /**
1459
+ * Remove array of participant from a group
1460
+ *
1461
+ * @param {any} roomId the room id this file is required for selected room_id to be process
1462
+ * @param {any} emails emails is must be an array
1463
+ * @returns Promise
1464
+ * @memberof QiscusSDK
1465
+ */
1466
+ removeParticipantsFromGroup(roomId, emails) {
1467
+ if (is.not.array(emails)) {
1468
+ return Promise.reject(new Error("`emails` must have type of array"));
2056
1469
  }
2057
-
2058
- /**
2059
- * Get user block list
2060
- *
2061
- * @param {any} page the page is optional, default=1
2062
- * @param {any} limit the limit is optional, default=20
2063
- * @returns Promise
2064
- * @memberof QiscusSDK
2065
- */
2066
- }, {
2067
- key: "getBlockedUser",
2068
- value: function getBlockedUser() {
2069
- var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
2070
- var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;
2071
- var self = this;
2072
- return self.userAdapter.getBlockedUser(page, limit).then(function (res) {
1470
+ return this.roomAdapter.removeParticipantsFromGroup(roomId, emails).then((res) => {
1471
+ this.events.emit("participants-removed", emails);
1472
+ return Promise.resolve(res);
1473
+ });
1474
+ }
1475
+ /**
1476
+ * Get user block list
1477
+ *
1478
+ * @param {any} page the page is optional, default=1
1479
+ * @param {any} limit the limit is optional, default=20
1480
+ * @returns Promise
1481
+ * @memberof QiscusSDK
1482
+ */
1483
+ getBlockedUser(page = 1, limit = 20) {
1484
+ const self = this;
1485
+ return self.userAdapter.getBlockedUser(page, limit).then(
1486
+ (res) => {
2073
1487
  return Promise.resolve(res);
2074
- }, function (err) {
2075
- return Promise.reject(err);
2076
- });
2077
- }
2078
-
2079
- /**
2080
- * Add user to block list
2081
- *
2082
- * @param {any} email the email is required
2083
- * @returns Promise
2084
- * @memberof QiscusSDK
2085
- */
2086
- }, {
2087
- key: "blockUser",
2088
- value: function blockUser(email) {
2089
- var self = this;
2090
- return self.userAdapter.blockUser(email).then(function (res) {
2091
- self.events.emit('block-user', res);
1488
+ },
1489
+ (err) => Promise.reject(err)
1490
+ );
1491
+ }
1492
+ /**
1493
+ * Add user to block list
1494
+ *
1495
+ * @param {any} email the email is required
1496
+ * @returns Promise
1497
+ * @memberof QiscusSDK
1498
+ */
1499
+ blockUser(email) {
1500
+ const self = this;
1501
+ return self.userAdapter.blockUser(email).then(
1502
+ (res) => {
1503
+ self.events.emit("block-user", res);
2092
1504
  return Promise.resolve(res);
2093
- }, function (err) {
2094
- return Promise.reject(err);
2095
- });
2096
- }
2097
-
2098
- /**
2099
- * Remove user from block list
2100
- *
2101
- * @param {any} email the email is required
2102
- * @returns Promise
2103
- * @memberof QiscusSDK
2104
- */
2105
- }, {
2106
- key: "unblockUser",
2107
- value: function unblockUser(email) {
2108
- var self = this;
2109
- return self.userAdapter.unblockUser(email).then(function (res) {
2110
- self.events.emit('unblock-user', res);
1505
+ },
1506
+ (err) => Promise.reject(err)
1507
+ );
1508
+ }
1509
+ /**
1510
+ * Remove user from block list
1511
+ *
1512
+ * @param {any} email the email is required
1513
+ * @returns Promise
1514
+ * @memberof QiscusSDK
1515
+ */
1516
+ unblockUser(email) {
1517
+ const self = this;
1518
+ return self.userAdapter.unblockUser(email).then(
1519
+ (res) => {
1520
+ self.events.emit("unblock-user", res);
2111
1521
  return Promise.resolve(res);
2112
- }, function (err) {
2113
- return Promise.reject(err);
2114
- });
2115
- }
2116
- }, {
2117
- key: "getUserPresences",
2118
- value: function getUserPresences() {
2119
- var email = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2120
- if (_is["default"].not.array(email)) {
2121
- return Promise.reject(new Error('`email` must have type of array'));
2122
- }
2123
- var self = this;
2124
- return self.userAdapter.getUserPresences(email).then(function (res) {
2125
- self.events.emit('user-status', res);
1522
+ },
1523
+ (err) => Promise.reject(err)
1524
+ );
1525
+ }
1526
+ getUserPresences(email = []) {
1527
+ if (is.not.array(email)) {
1528
+ return Promise.reject(new Error("`email` must have type of array"));
1529
+ }
1530
+ const self = this;
1531
+ return self.userAdapter.getUserPresences(email).then(
1532
+ (res) => {
1533
+ self.events.emit("user-status", res);
2126
1534
  return Promise.resolve(res);
2127
- }, function (err) {
2128
- return Promise.reject(err);
2129
- });
2130
- }
2131
- }, {
2132
- key: "upload",
2133
- value: function upload(file, callback) {
2134
- var req = _superagent["default"].post(this.uploadURL);
2135
- req = this.HTTPAdapter.setupHeaders(req);
2136
- return req.attach('file', file).on('progress', function (event) {
2137
- if (event.direction === 'upload') callback(null, event);
2138
- }).then(function (resp) {
2139
- var url = resp.body.results.file.url;
2140
- callback(null, null, resp.body.results.file.url);
2141
- return Promise.resolve(url);
2142
- })["catch"](function (error) {
2143
- callback(error);
2144
- return Promise.reject(error);
2145
- });
2146
- }
2147
-
2148
- /**
2149
- * Upload a file to qiscus sdk server
2150
- *
2151
- * @param {any} roomId the room id this file need to be submitted to
2152
- * @param {any} file you can get this from event `e.target.files || e.dataTransfer.files`
2153
- * @returns Promise
2154
- * @memberof QiscusSDK
2155
- */
2156
- }, {
2157
- key: "uploadFile",
2158
- value: function uploadFile(roomId, file) {
2159
- var self = this;
2160
- var formData = new FormData();
2161
- formData.append('file', file);
2162
- var xhr = new XMLHttpRequest();
2163
- xhr.open('POST', "".concat(self.baseURL, "/api/v2/sdk/upload"), true);
2164
- xhr.setRequestHeader('qiscus_sdk_app_id', "".concat(self.AppId));
2165
- xhr.setRequestHeader('qiscus_sdk_user_id', "".concat(self.user_id));
2166
- xhr.setRequestHeader('qiscus_sdk_token', "".concat(self.userData.token));
2167
- xhr.onload = function () {
2168
- if (xhr.status === 200) {
2169
- // file(s) uploaded), let's post to comment
2170
- var url = JSON.parse(xhr.response).results.file.url;
2171
- self.events.emit('fileupload', url);
2172
- // send
2173
- return self.sendComment(roomId, "[file] ".concat(url, " [/file]"));
2174
- } else {
2175
- return Promise.reject(xhr);
2176
- }
2177
- };
2178
- xhr.send(formData);
2179
- }
2180
- }, {
2181
- key: "addUploadedFile",
2182
- value: function addUploadedFile(name, roomId) {
2183
- this.uploadedFiles.push(new FileUploaded(name, roomId));
2184
- }
2185
- }, {
2186
- key: "removeUploadedFile",
2187
- value: function removeUploadedFile(name, roomId) {
2188
- var index = this.uploadedFiles.findIndex(function (file) {
2189
- return file.name === name && file.roomId === roomId;
2190
- });
2191
- this.uploadedFiles.splice(index, 1);
2192
- }
2193
- }, {
2194
- key: "publishTyping",
2195
- value: function publishTyping(val) {
2196
- this.realtimeAdapter.publishTyping(val);
2197
- }
2198
-
2199
- /**
2200
- * Params consisted of
2201
- * @param {room_ids} array of room ids
2202
- * @param {room_unique_ids} array of of room unique ids
2203
- * @param {show_participants} show list of participants, default true
2204
- * @param {show_removed} show removed room, default false
2205
- * @returns
2206
- * @memberof QiscusSDK
2207
- */
2208
- }, {
2209
- key: "getRoomsInfo",
2210
- value: function getRoomsInfo(params) {
2211
- return this.userAdapter.getRoomsInfo(params);
2212
- }
2213
- }, {
2214
- key: "deleteComment",
2215
- value: function deleteComment(roomId, commentUniqueIds, isForEveryone, isHard) {
2216
- var _this14 = this;
2217
- if (!Array.isArray(commentUniqueIds)) {
2218
- throw new Error("unique ids' must be type of Array");
1535
+ },
1536
+ (err) => Promise.reject(err)
1537
+ );
1538
+ }
1539
+ upload(file, callback) {
1540
+ let req = request.post(this.uploadURL);
1541
+ req = this.HTTPAdapter.setupHeaders(req);
1542
+ return req.attach("file", file).on("progress", (event) => {
1543
+ if (event.direction === "upload") callback(null, event);
1544
+ }).then((resp) => {
1545
+ const url = resp.body.results.file.url;
1546
+ callback(null, null, resp.body.results.file.url);
1547
+ return Promise.resolve(url);
1548
+ }).catch((error) => {
1549
+ callback(error);
1550
+ return Promise.reject(error);
1551
+ });
1552
+ }
1553
+ /**
1554
+ * Upload a file to qiscus sdk server
1555
+ *
1556
+ * @param {any} roomId the room id this file need to be submitted to
1557
+ * @param {any} file you can get this from event `e.target.files || e.dataTransfer.files`
1558
+ * @returns Promise
1559
+ * @memberof QiscusSDK
1560
+ */
1561
+ uploadFile(roomId, file) {
1562
+ const self = this;
1563
+ var formData = new FormData();
1564
+ formData.append("file", file);
1565
+ var xhr = new XMLHttpRequest();
1566
+ xhr.open("POST", `${self.baseURL}/api/v2/sdk/upload`, true);
1567
+ xhr.setRequestHeader("qiscus_sdk_app_id", `${self.AppId}`);
1568
+ xhr.setRequestHeader("qiscus_sdk_user_id", `${self.user_id}`);
1569
+ xhr.setRequestHeader("qiscus_sdk_token", `${self.userData.token}`);
1570
+ xhr.onload = function() {
1571
+ if (xhr.status === 200) {
1572
+ var url = JSON.parse(xhr.response).results.file.url;
1573
+ self.events.emit("fileupload", url);
1574
+ return self.sendComment(roomId, `[file] ${url} [/file]`);
1575
+ } else {
1576
+ return Promise.reject(xhr);
2219
1577
  }
2220
- return this.userAdapter.deleteComment(roomId, commentUniqueIds, isForEveryone, isHard).then(function (res) {
2221
- _this14.events.emit('comment-deleted', {
2222
- roomId: roomId,
2223
- commentUniqueIds: commentUniqueIds,
2224
- isForEveryone: isForEveryone,
2225
- isHard: isHard
1578
+ };
1579
+ xhr.send(formData);
1580
+ }
1581
+ addUploadedFile(name, roomId) {
1582
+ this.uploadedFiles.push(new FileUploaded(name, roomId));
1583
+ }
1584
+ removeUploadedFile(name, roomId) {
1585
+ const index = this.uploadedFiles.findIndex(
1586
+ (file) => file.name === name && file.roomId === roomId
1587
+ );
1588
+ this.uploadedFiles.splice(index, 1);
1589
+ }
1590
+ publishTyping(val) {
1591
+ this.realtimeAdapter.publishTyping(val);
1592
+ }
1593
+ /**
1594
+ * Params consisted of
1595
+ * @param {room_ids} array of room ids
1596
+ * @param {room_unique_ids} array of of room unique ids
1597
+ * @param {show_participants} show list of participants, default true
1598
+ * @param {show_removed} show removed room, default false
1599
+ * @returns
1600
+ * @memberof QiscusSDK
1601
+ */
1602
+ getRoomsInfo(params) {
1603
+ return this.userAdapter.getRoomsInfo(params);
1604
+ }
1605
+ deleteComment(roomId, commentUniqueIds, isForEveryone, isHard) {
1606
+ if (!Array.isArray(commentUniqueIds)) {
1607
+ throw new Error(`unique ids' must be type of Array`);
1608
+ }
1609
+ return this.userAdapter.deleteComment(roomId, commentUniqueIds, isForEveryone, isHard).then(
1610
+ (res) => {
1611
+ this.events.emit("comment-deleted", {
1612
+ roomId,
1613
+ commentUniqueIds,
1614
+ isForEveryone,
1615
+ isHard
2226
1616
  });
2227
1617
  return Promise.resolve(res);
2228
- }, function (err) {
2229
- return Promise.reject(err);
2230
- });
2231
- }
2232
- }, {
2233
- key: "clearRoomsCache",
2234
- value: function clearRoomsCache() {
2235
- var _this15 = this;
2236
- // remove all room except currently selected
2237
- if (this.selected) {
2238
- // clear the map
2239
- this.room_name_id_map = (0, _defineProperty2["default"])({}, this.selected.name, this.selected.id);
2240
- // get current index and array length
2241
- var roomLength = this.rooms.length;
2242
- var curIndex = this.rooms.findIndex(function (room) {
2243
- return room.id === _this15.selected.id;
2244
- });
2245
- if (!(curIndex + 1 === roomLength)) {
2246
- this.rooms.splice(curIndex + 1, roomLength - (curIndex + 1));
2247
- }
2248
- // ambil ulang cur index nya, klo udah di awal ga perlu lagi kode dibawah ini
2249
- curIndex = this.rooms.findIndex(function (room) {
2250
- return room.id === _this15.selected.id;
2251
- });
2252
- if (curIndex > 0 && this.rooms.length > 1) {
2253
- this.rooms.splice(1, this.rooms.length - 1);
2254
- }
1618
+ },
1619
+ (err) => Promise.reject(err)
1620
+ );
1621
+ }
1622
+ clearRoomsCache() {
1623
+ if (this.selected) {
1624
+ this.room_name_id_map = {
1625
+ [this.selected.name]: this.selected.id
1626
+ };
1627
+ const roomLength = this.rooms.length;
1628
+ let curIndex = this.rooms.findIndex(
1629
+ (room2) => room2.id === this.selected.id
1630
+ );
1631
+ if (!(curIndex + 1 === roomLength)) {
1632
+ this.rooms.splice(curIndex + 1, roomLength - (curIndex + 1));
2255
1633
  }
2256
- }
2257
- }, {
2258
- key: "exitChatRoom",
2259
- value: function exitChatRoom() {
2260
- var _this16 = this;
2261
- // remove all subscriber
2262
- this.realtimeAdapter.unsubscribeTyping();
2263
- (0, _util.tryCatch)(function () {
2264
- return _this16.selected.participants.filter(function (it) {
2265
- return it.email !== _this16.user_id;
2266
- }).map(function (it) {
2267
- return it.email;
2268
- });
2269
- }, null, this.noop, function (userIds) {
2270
- return userIds.forEach(function (userId) {
2271
- return _this16.realtimeAdapter.unsubscribeRoomPresence(userId);
2272
- });
2273
- });
2274
- this.selected = null;
2275
- }
2276
- }, {
2277
- key: "clearRoomMessages",
2278
- value: function clearRoomMessages(roomIds) {
2279
- if (!Array.isArray(roomIds)) {
2280
- throw new Error('room_ids must be type of array');
1634
+ curIndex = this.rooms.findIndex((room2) => room2.id === this.selected.id);
1635
+ if (curIndex > 0 && this.rooms.length > 1) {
1636
+ this.rooms.splice(1, this.rooms.length - 1);
2281
1637
  }
2282
- return this.userAdapter.clearRoomMessages(roomIds);
2283
1638
  }
2284
- }, {
2285
- key: "logging",
2286
- value: function logging(message) {
2287
- var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2288
- if (this.debugMode) {
2289
- console.log(message, params);
2290
- }
1639
+ }
1640
+ exitChatRoom() {
1641
+ this.realtimeAdapter.unsubscribeTyping();
1642
+ util.tryCatch(
1643
+ () => this.selected.participants.filter((it) => it.email !== this.user_id).map((it) => it.email),
1644
+ null,
1645
+ this.noop,
1646
+ (userIds) => userIds.forEach(
1647
+ (userId) => this.realtimeAdapter.unsubscribeRoomPresence(userId)
1648
+ )
1649
+ );
1650
+ this.selected = null;
1651
+ }
1652
+ clearRoomMessages(roomIds) {
1653
+ if (!Array.isArray(roomIds)) {
1654
+ throw new Error("room_ids must be type of array");
2291
1655
  }
2292
- }, {
2293
- key: "getTotalUnreadCount",
2294
- value: function getTotalUnreadCount() {
2295
- return this.roomAdapter.getTotalUnreadCount().then(function (response) {
1656
+ return this.userAdapter.clearRoomMessages(roomIds);
1657
+ }
1658
+ logging(message, params = {}) {
1659
+ if (this.debugMode) {
1660
+ console.log(message, params);
1661
+ }
1662
+ }
1663
+ getTotalUnreadCount() {
1664
+ return this.roomAdapter.getTotalUnreadCount().then(
1665
+ (response) => {
2296
1666
  return Promise.resolve(response);
2297
- }, function (error) {
1667
+ },
1668
+ (error) => {
2298
1669
  return Promise.reject(error);
2299
- });
2300
- }
2301
- }, {
2302
- key: "getRoomUnreadCount",
2303
- value: function getRoomUnreadCount() {
2304
- return this.roomAdapter.getRoomUnreadCount();
2305
- }
2306
- }, {
2307
- key: "publishEvent",
2308
- value: function publishEvent() {
2309
- var _this$customEventAdap;
2310
- (_this$customEventAdap = this.customEventAdapter).publishEvent.apply(_this$customEventAdap, arguments);
2311
- }
2312
- }, {
2313
- key: "subscribeEvent",
2314
- value: function subscribeEvent() {
2315
- var _this$customEventAdap2;
2316
- (_this$customEventAdap2 = this.customEventAdapter).subscribeEvent.apply(_this$customEventAdap2, arguments);
2317
- }
2318
- }, {
2319
- key: "unsubscribeEvent",
2320
- value: function unsubscribeEvent() {
2321
- var _this$customEventAdap3;
2322
- (_this$customEventAdap3 = this.customEventAdapter).unsubscribeEvent.apply(_this$customEventAdap3, arguments);
2323
- }
2324
- }, {
2325
- key: "setCustomHeader",
2326
- value: function setCustomHeader(headers) {
2327
- if (_is["default"].not.json(headers)) {
2328
- throw new TypeError('`headers` must have type of object');
2329
1670
  }
2330
- this._customHeader = headers;
2331
- }
2332
- }, {
2333
- key: "getUserProfile",
2334
- value: function getUserProfile() {
2335
- return this.userAdapter.getProfile();
2336
- }
2337
- }, {
2338
- key: "Interceptor",
2339
- get: function get() {
2340
- return _hook.Hooks;
2341
- }
2342
- }, {
2343
- key: "intercept",
2344
- value: function intercept(interceptor, callback) {
2345
- return this._hookAdapter.intercept(interceptor, callback);
2346
- }
2347
- }, {
2348
- key: "getThumbnailURL",
2349
- value: function getThumbnailURL(fileURL) {
2350
- var reURL = /^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;
2351
- return fileURL.replace(reURL, function (match, g1, g2) {
2352
- return match.replace(g1, '/upload/w_320,h_320,c_limit/').replace(g2, '.png');
2353
- });
2354
- }
2355
- }, {
2356
- key: "getBlurryThumbnailURL",
2357
- value: function getBlurryThumbnailURL(fileURL) {
2358
- var reURL = /^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;
2359
- return fileURL.replace(reURL, function (match, g1, g2) {
2360
- return match.replace(g1, '/upload/w_320,h_320,c_limit,e_blur:300/').replace(g2, '.png');
2361
- });
2362
- }
2363
- }, {
2364
- key: "logger",
2365
- get: function get() {
2366
- if (this.debugMode) return console.log.bind(console, 'Qiscus ->');
2367
- return this.noop;
2368
- }
2369
- }, {
2370
- key: "noop",
2371
- value: function noop() {}
2372
- }, {
2373
- key: "_throttleDelay",
2374
- get: function get() {
2375
- if (this.updateCommentStatusMode === QiscusSDK.UpdateCommentStatusMode.enabled) {
2376
- return 0;
2377
- }
2378
- return this.updateCommentStatusThrottleDelay || 300;
1671
+ );
1672
+ }
1673
+ getRoomUnreadCount() {
1674
+ return this.roomAdapter.getRoomUnreadCount();
1675
+ }
1676
+ publishEvent(...args) {
1677
+ this.customEventAdapter.publishEvent(...args);
1678
+ }
1679
+ subscribeEvent(...args) {
1680
+ this.customEventAdapter.subscribeEvent(...args);
1681
+ }
1682
+ unsubscribeEvent(...args) {
1683
+ this.customEventAdapter.unsubscribeEvent(...args);
1684
+ }
1685
+ setCustomHeader(headers) {
1686
+ if (is.not.json(headers)) {
1687
+ throw new TypeError("`headers` must have type of object");
2379
1688
  }
2380
- }, {
2381
- key: "_updateStatusEnabled",
2382
- get: function get() {
2383
- return this.updateCommentStatusMode !== QiscusSDK.UpdateCommentStatusMode.disabled;
1689
+ this._customHeader = headers;
1690
+ }
1691
+ getUserProfile() {
1692
+ return this.userAdapter.getProfile();
1693
+ }
1694
+ get Interceptor() {
1695
+ return hook.Hooks;
1696
+ }
1697
+ intercept(interceptor, callback) {
1698
+ return this._hookAdapter.intercept(interceptor, callback);
1699
+ }
1700
+ getThumbnailURL(fileURL) {
1701
+ const reURL = /^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;
1702
+ return fileURL.replace(
1703
+ reURL,
1704
+ (match, g1, g2) => match.replace(g1, "/upload/w_320,h_320,c_limit/").replace(g2, ".png")
1705
+ );
1706
+ }
1707
+ getBlurryThumbnailURL(fileURL) {
1708
+ const reURL = /^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;
1709
+ return fileURL.replace(
1710
+ reURL,
1711
+ (match, g1, g2) => match.replace(g1, "/upload/w_320,h_320,c_limit,e_blur:300/").replace(g2, ".png")
1712
+ );
1713
+ }
1714
+ get logger() {
1715
+ if (this.debugMode) return console.log.bind(console, "Qiscus ->");
1716
+ return this.noop;
1717
+ }
1718
+ noop() {
1719
+ }
1720
+ get _throttleDelay() {
1721
+ if (this.updateCommentStatusMode === _QiscusSDK.UpdateCommentStatusMode.enabled) {
1722
+ return 0;
2384
1723
  }
2385
- }, {
2386
- key: "_updateStatus",
2387
- value: function _updateStatus(roomId) {
2388
- var commentId1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2389
- var commentId2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
2390
- // The rules:
2391
- // if it is receive command
2392
- // - it is prohibited to send command if current room are channel
2393
- // - it is ok to send command even if no room selected
2394
- // - it is prohibited to send command when `updateCommentStatusMode` is `disabled`
2395
- // if it is read command
2396
- // - it is prohibited to send command if current room are channel
2397
- // - it is prohibited to send command if no room selected (but why was this a thing?)
2398
- // - it is ok to send command when `updateCommentStatusMode` is `disabled`
2399
-
2400
- var isReceiveCommand = commentId2 != null;
2401
- var isReadCommand = commentId1 != null;
2402
- var isSelected = this.selected != null && this.selected.id === roomId || false;
2403
- var isChannel = this.selected != null && this.selected.isChannel || false;
2404
- var isUpdateStatusDisabled = !this._updateStatusEnabled;
2405
- var command = function () {
2406
- if (isReadCommand) return 'read';
2407
- if (isReceiveCommand) return 'receive';
2408
- }();
2409
- var isAbleToRunCommand = function () {
2410
- if (isChannel) return false;
2411
- if (isReceiveCommand && isUpdateStatusDisabled) return false;
2412
- return true;
2413
- }();
2414
- if (this.debugMode) {
2415
- console.group('update-command-status');
2416
- console.log('run:', command, "on: roomId(".concat(roomId, ") commentId(").concat(commentId1 || commentId2, ")"));
2417
- console.log('is able to run command?', isAbleToRunCommand);
2418
- console.groupEnd();
1724
+ return this.updateCommentStatusThrottleDelay || 300;
1725
+ }
1726
+ get _updateStatusEnabled() {
1727
+ return this.updateCommentStatusMode !== _QiscusSDK.UpdateCommentStatusMode.disabled;
1728
+ }
1729
+ _updateStatus(roomId, commentId1 = null, commentId2 = null) {
1730
+ const isReceiveCommand = commentId2 != null;
1731
+ const isReadCommand = commentId1 != null;
1732
+ this.selected != null && this.selected.id === roomId || false;
1733
+ const isChannel = this.selected != null && this.selected.isChannel || false;
1734
+ const isUpdateStatusDisabled = !this._updateStatusEnabled;
1735
+ const command = (() => {
1736
+ if (isReadCommand) return "read";
1737
+ if (isReceiveCommand) return "receive";
1738
+ })();
1739
+ const isAbleToRunCommand = (() => {
1740
+ if (isChannel) return false;
1741
+ if (isReceiveCommand && isUpdateStatusDisabled) return false;
1742
+ return true;
1743
+ })();
1744
+ if (this.debugMode) {
1745
+ console.group("update-command-status");
1746
+ console.log(
1747
+ "run:",
1748
+ command,
1749
+ `on: roomId(${roomId}) commentId(${commentId1 || commentId2})`
1750
+ );
1751
+ console.log("is able to run command?", isAbleToRunCommand);
1752
+ console.groupEnd();
1753
+ }
1754
+ if (!isAbleToRunCommand) return false;
1755
+ this.userAdapter.updateCommentStatus(roomId, commentId1, commentId2).catch((err) => {
1756
+ });
1757
+ }
1758
+ readComment(roomId, commentId) {
1759
+ if (this.updateCommentStatusMode === _QiscusSDK.UpdateCommentStatusMode.enabled)
1760
+ return this._readComment(roomId, commentId);
1761
+ return this._readCommentT(roomId, commentId);
1762
+ }
1763
+ receiveComment(roomId, commentId) {
1764
+ if (this.updateCommentStatusMode === _QiscusSDK.UpdateCommentStatusMode.enabled)
1765
+ return this._deliverComment(roomId, commentId);
1766
+ return this._deliverCommentT(roomId, commentId);
1767
+ }
1768
+ _throttle(func, getWait) {
1769
+ let isWaiting = false;
1770
+ return (...args) => {
1771
+ let waitTime = getWait();
1772
+ if (!isWaiting) {
1773
+ func(...args);
1774
+ isWaiting = true;
1775
+ setTimeout(() => isWaiting = false, waitTime);
2419
1776
  }
2420
- if (!isAbleToRunCommand) return false;
2421
- this.userAdapter.updateCommentStatus(roomId, commentId1, commentId2)["catch"](function (err) {});
2422
- }
2423
- }, {
2424
- key: "readComment",
2425
- value: function readComment(roomId, commentId) {
2426
- if (this.updateCommentStatusMode === QiscusSDK.UpdateCommentStatusMode.enabled) return this._readComment(roomId, commentId);
2427
- return this._readCommentT(roomId, commentId);
2428
- }
2429
- }, {
2430
- key: "receiveComment",
2431
- value: function receiveComment(roomId, commentId) {
2432
- if (this.updateCommentStatusMode === QiscusSDK.UpdateCommentStatusMode.enabled) return this._deliverComment(roomId, commentId);
2433
- return this._deliverCommentT(roomId, commentId);
2434
- }
2435
- }, {
2436
- key: "_throttle",
2437
- value: function _throttle(func, getWait) {
2438
- var isWaiting = false;
2439
- return function () {
2440
- var waitTime = getWait();
2441
- if (!isWaiting) {
2442
- func.apply(void 0, arguments);
2443
- isWaiting = true;
2444
- setTimeout(function () {
2445
- return isWaiting = false;
2446
- }, waitTime);
2447
- }
2448
- };
2449
- }
2450
-
2451
- /**
2452
- * @typedef {Object} SearchMessageParams
2453
- * @property {string} query
2454
- * @property {Array.<number>} roomIds
2455
- * @property {string} userId
2456
- * @property {Array.<string>} type
2457
- * @property {string} roomType
2458
- * @property {number} page
2459
- * @property {number} limit
2460
- */
2461
- /**
2462
- *
2463
- * @param {SearchMessageParams} param0
2464
- * @returns {Array.<Object>}
2465
- */
2466
- }, {
2467
- key: "searchMessage",
2468
- value: (function () {
2469
- var _searchMessage = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee16() {
2470
- var _ref11,
2471
- query,
2472
- _ref11$roomIds,
2473
- roomIds,
2474
- userId,
2475
- type,
2476
- roomType,
2477
- page,
2478
- limit,
2479
- url,
2480
- isValidRoomType,
2481
- room,
2482
- _args16 = arguments;
2483
- return _regenerator["default"].wrap(function (_context16) {
2484
- while (1) switch (_context16.prev = _context16.next) {
2485
- case 0:
2486
- _ref11 = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : {}, query = _ref11.query, _ref11$roomIds = _ref11.roomIds, roomIds = _ref11$roomIds === void 0 ? [] : _ref11$roomIds, userId = _ref11.userId, type = _ref11.type, roomType = _ref11.roomType, page = _ref11.page, limit = _ref11.limit;
2487
- url = 'api/v2/sdk/search';
2488
- isValidRoomType = ['group', 'single', 'channel'].some(function (it) {
2489
- return it === roomType;
2490
- });
2491
- if (!(roomType != null && !isValidRoomType)) {
2492
- _context16.next = 1;
2493
- break;
2494
- }
2495
- return _context16.abrupt("return", Promise.reject('Invalid room type, valid room type are: `group`, `single`, and `channel`'));
2496
- case 1:
2497
- room = function (roomType) {
2498
- var rType = roomType == null ? undefined : roomType === 'single' ? 'single' : 'group';
2499
- var isPublic = roomType == null ? undefined : roomType === 'channel' ? true : false;
2500
- return {
2501
- type: rType,
2502
- isPublic: isPublic
2503
- };
2504
- }(roomType);
2505
- return _context16.abrupt("return", this.HTTPAdapter.post_json(url, {
2506
- token: this.token,
2507
- query: query,
2508
- sender: userId,
2509
- type: type,
2510
- room_ids: roomIds.map(function (it) {
2511
- return String(it);
2512
- }),
2513
- room_type: room.type || undefined,
2514
- is_public: room.isPublic || undefined,
2515
- page: page,
2516
- limit: limit
2517
- }).then(function (res) {
2518
- return res.body;
2519
- }));
2520
- case 2:
2521
- case "end":
2522
- return _context16.stop();
2523
- }
2524
- }, _callee16, this);
2525
- }));
2526
- function searchMessage() {
2527
- return _searchMessage.apply(this, arguments);
1777
+ };
1778
+ }
1779
+ /**
1780
+ * @typedef {Object} SearchMessageParams
1781
+ * @property {string} query
1782
+ * @property {Array.<number>} roomIds
1783
+ * @property {string} userId
1784
+ * @property {Array.<string>} type
1785
+ * @property {string} roomType
1786
+ * @property {number} page
1787
+ * @property {number} limit
1788
+ */
1789
+ /**
1790
+ *
1791
+ * @param {SearchMessageParams} param0
1792
+ * @returns {Array.<Object>}
1793
+ */
1794
+ searchMessage() {
1795
+ return __async(this, arguments, function* ({
1796
+ query,
1797
+ roomIds = [],
1798
+ userId,
1799
+ type,
1800
+ roomType,
1801
+ page,
1802
+ limit
1803
+ } = {}) {
1804
+ const url = "api/v2/sdk/search";
1805
+ const isValidRoomType = ["group", "single", "channel"].some(
1806
+ (it) => it === roomType
1807
+ );
1808
+ if (roomType != null && !isValidRoomType) {
1809
+ return Promise.reject(
1810
+ "Invalid room type, valid room type are: `group`, `single`, and `channel`"
1811
+ );
2528
1812
  }
2529
- return searchMessage;
2530
- }()
2531
- /**
2532
- * @typedef {Object} GetFileListParams
2533
- * @property {Array.<number>} roomIds
2534
- * @property {String} fileType
2535
- * @property {Number} page
2536
- * @property {Number} limit
2537
- * @property {String} includeExtensions
2538
- * @property {String} excludeExtensions
2539
- * @property {String} userId
2540
- */
2541
- /**
2542
- * @param {GetFileListParams} param0
2543
- */
2544
- )
2545
- }, {
2546
- key: "getFileList",
2547
- value: (function () {
2548
- var _getFileList = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee17() {
2549
- var _ref12,
2550
- _ref12$roomIds,
2551
- roomIds,
2552
- fileType,
2553
- page,
2554
- limit,
2555
- sender,
2556
- userId,
2557
- includeExtensions,
2558
- excludeExtensions,
2559
- url,
2560
- opts,
2561
- _args17 = arguments;
2562
- return _regenerator["default"].wrap(function (_context17) {
2563
- while (1) switch (_context17.prev = _context17.next) {
2564
- case 0:
2565
- _ref12 = _args17.length > 0 && _args17[0] !== undefined ? _args17[0] : {}, _ref12$roomIds = _ref12.roomIds, roomIds = _ref12$roomIds === void 0 ? [] : _ref12$roomIds, fileType = _ref12.fileType, page = _ref12.page, limit = _ref12.limit, sender = _ref12.sender, userId = _ref12.userId, includeExtensions = _ref12.includeExtensions, excludeExtensions = _ref12.excludeExtensions;
2566
- url = 'api/v2/sdk/file_list';
2567
- if (this.isLogin) {
2568
- _context17.next = 1;
2569
- break;
2570
- }
2571
- return _context17.abrupt("return", Promise.reject('You need to login to use this method'));
2572
- case 1:
2573
- // intended to check for undefined, so user can provide user
2574
- // with null. If null, backend can determine that we want to
2575
- // list files for all users
2576
- if (sender === undefined) {
2577
- sender = this.user_id;
2578
- }
2579
- if (userId === undefined) {
2580
- sender = userId = this.user_id;
2581
- }
2582
- opts = {
2583
- room_ids: roomIds.map(function (it) {
2584
- return String(it);
2585
- }),
2586
- file_type: fileType,
2587
- page: page,
2588
- limit: limit,
2589
- include_extensions: includeExtensions,
2590
- exclude_extensions: excludeExtensions
2591
- };
2592
- if (sender != null) opts['sender'] = sender;
2593
- return _context17.abrupt("return", this.HTTPAdapter.post_json(url, opts).then(function (res) {
2594
- return res.body;
2595
- }));
2596
- case 2:
2597
- case "end":
2598
- return _context17.stop();
2599
- }
2600
- }, _callee17, this);
2601
- }));
2602
- function getFileList() {
2603
- return _getFileList.apply(this, arguments);
1813
+ const room2 = ((roomType2) => {
1814
+ const rType = roomType2 == null ? void 0 : roomType2 === "single" ? "single" : "group";
1815
+ const isPublic = roomType2 == null ? void 0 : roomType2 === "channel" ? true : false;
1816
+ return {
1817
+ type: rType,
1818
+ isPublic
1819
+ };
1820
+ })(roomType);
1821
+ return this.HTTPAdapter.post_json(url, {
1822
+ token: this.token,
1823
+ query,
1824
+ sender: userId,
1825
+ type,
1826
+ room_ids: roomIds.map((it) => String(it)),
1827
+ room_type: room2.type || void 0,
1828
+ is_public: room2.isPublic || void 0,
1829
+ page,
1830
+ limit
1831
+ }).then((res) => res.body);
1832
+ });
1833
+ }
1834
+ /**
1835
+ * @typedef {Object} GetFileListParams
1836
+ * @property {Array.<number>} roomIds
1837
+ * @property {String} fileType
1838
+ * @property {Number} page
1839
+ * @property {Number} limit
1840
+ * @property {String} includeExtensions
1841
+ * @property {String} excludeExtensions
1842
+ * @property {String} userId
1843
+ */
1844
+ /**
1845
+ * @param {GetFileListParams} param0
1846
+ */
1847
+ getFileList() {
1848
+ return __async(this, arguments, function* ({
1849
+ roomIds = [],
1850
+ fileType,
1851
+ page,
1852
+ limit,
1853
+ sender,
1854
+ userId,
1855
+ includeExtensions,
1856
+ excludeExtensions
1857
+ } = {}) {
1858
+ const url = "api/v2/sdk/file_list";
1859
+ if (!this.isLogin)
1860
+ return Promise.reject("You need to login to use this method");
1861
+ if (sender === void 0) {
1862
+ sender = this.user_id;
2604
1863
  }
2605
- return getFileList;
2606
- }())
2607
- }, {
2608
- key: "_generateUniqueId",
2609
- value: function _generateUniqueId() {
2610
- return "javascript-".concat(Date.now());
2611
- }
2612
- }, {
2613
- key: "generateMessage",
2614
- value: function generateMessage(_ref13) {
2615
- var roomId = _ref13.roomId,
2616
- text = _ref13.text,
2617
- extras = _ref13.extras;
2618
- var id = Date.now();
2619
- var comment = new _Comment["default"]({
2620
- id: id,
2621
- message: text,
2622
- room_id: roomId,
2623
- extras: extras,
2624
- timestamp: new Date(),
2625
- unique_id: this._generateUniqueId(),
2626
- before_id: 0,
2627
- username: this.userData.username,
2628
- email: this.userData.email,
2629
- status: 'pending',
2630
- type: 'text'
2631
- });
2632
- return comment;
2633
- }
2634
- }, {
2635
- key: "generateFileAttachmentMessage",
2636
- value: function generateFileAttachmentMessage(_ref14) {
2637
- var roomId = _ref14.roomId,
2638
- caption = _ref14.caption,
2639
- url = _ref14.url,
2640
- _ref14$text = _ref14.text,
2641
- text = _ref14$text === void 0 ? 'File attachment' : _ref14$text,
2642
- extras = _ref14.extras,
2643
- filename = _ref14.filename,
2644
- size = _ref14.size;
2645
- var id = Date.now();
2646
- var comment = new _Comment["default"]({
2647
- id: id,
2648
- message: text,
2649
- room_id: roomId,
2650
- extras: extras,
2651
- timestamp: new Date(),
2652
- unique_id: this._generateUniqueId(),
2653
- before_id: 0,
2654
- username: this.userData.username,
2655
- email: this.userData.email,
2656
- status: 'pending',
2657
- type: 'file_attachment',
2658
- payload: {
2659
- url: url,
2660
- file_name: filename,
2661
- size: size,
2662
- caption: caption
2663
- }
2664
- });
2665
- return comment;
2666
- }
2667
- }, {
2668
- key: "generateCustomMessage",
2669
- value: function generateCustomMessage(_ref15) {
2670
- var roomId = _ref15.roomId,
2671
- text = _ref15.text,
2672
- type = _ref15.type,
2673
- payload = _ref15.payload,
2674
- extras = _ref15.extras;
2675
- var id = Date.now();
2676
- var comment = new _Comment["default"]({
2677
- id: id,
2678
- message: text,
2679
- room_id: roomId,
2680
- extras: extras,
2681
- timestamp: new Date(),
2682
- unique_id: this._generateUniqueId(),
2683
- before_id: 0,
2684
- username: this.userData.username,
2685
- email: this.userData.email,
2686
- status: 'pending',
2687
- type: 'custom',
2688
- payload: {
2689
- type: type,
2690
- content: payload
2691
- }
2692
- });
2693
- return comment;
2694
- }
2695
- }, {
2696
- key: "generateReplyMessage",
2697
- value: function generateReplyMessage(_ref16) {
2698
- var roomId = _ref16.roomId,
2699
- text = _ref16.text,
2700
- repliedMessage = _ref16.repliedMessage,
2701
- extras = _ref16.extras;
2702
- var id = Date.now();
2703
- var comment = new _Comment["default"]({
2704
- id: id,
2705
- message: text,
2706
- room_id: roomId,
2707
- extras: extras,
2708
- timestamp: new Date(),
2709
- unique_id: this._generateUniqueId(),
2710
- before_id: 0,
2711
- username: this.userData.username,
2712
- email: this.userData.email,
2713
- status: 'pending',
2714
- type: 'reply',
2715
- payload: {
2716
- text: text,
2717
- replied_comment_id: repliedMessage.id,
2718
- replied_comment_message: repliedMessage.message,
2719
- replied_comment_type: repliedMessage.type,
2720
- replied_comment_payload: repliedMessage.payload,
2721
- replied_comment_sender_username: repliedMessage.username_as,
2722
- replied_comment_sender_email: repliedMessage.username_real
2723
- }
2724
- });
2725
- return comment;
2726
- }
2727
- }, {
2728
- key: "updateMessage",
2729
- value: function () {
2730
- var _updateMessage = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee18(message) {
2731
- return _regenerator["default"].wrap(function (_context18) {
2732
- while (1) switch (_context18.prev = _context18.next) {
2733
- case 0:
2734
- return _context18.abrupt("return", this.userAdapter.updateMessage(message));
2735
- case 1:
2736
- case "end":
2737
- return _context18.stop();
2738
- }
2739
- }, _callee18, this);
2740
- }));
2741
- function updateMessage(_x15) {
2742
- return _updateMessage.apply(this, arguments);
1864
+ if (userId === void 0) {
1865
+ sender = userId = this.user_id;
2743
1866
  }
2744
- return updateMessage;
2745
- }()
2746
- }, {
2747
- key: "onMessageUpdated",
2748
- value: function onMessageUpdated(handler) {
2749
- var _this17 = this;
2750
- this.realtimeAdapter.on('message:updated', handler);
2751
- return function () {
2752
- return _this17.realtimeAdapter.off('message:updated', handler);
1867
+ let opts = {
1868
+ room_ids: roomIds.map((it) => String(it)),
1869
+ file_type: fileType,
1870
+ page,
1871
+ limit,
1872
+ include_extensions: includeExtensions,
1873
+ exclude_extensions: excludeExtensions
2753
1874
  };
2754
- }
2755
-
2756
- /**
2757
- * Manually close connection to mqtt server
2758
- * @return {Promise<boolean>} Wheter successfully close mqtt connection or not
2759
- */
2760
- }, {
2761
- key: "closeRealtimeConnection",
2762
- value: (function () {
2763
- var _closeRealtimeConnection = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee19() {
2764
- return _regenerator["default"].wrap(function (_context19) {
2765
- while (1) switch (_context19.prev = _context19.next) {
2766
- case 0:
2767
- return _context19.abrupt("return", this.realtimeAdapter.closeConnection());
2768
- case 1:
2769
- case "end":
2770
- return _context19.stop();
2771
- }
2772
- }, _callee19, this);
2773
- }));
2774
- function closeRealtimeConnection() {
2775
- return _closeRealtimeConnection.apply(this, arguments);
2776
- }
2777
- return closeRealtimeConnection;
2778
- }()
2779
- /**
2780
- * Manually open connection to mqtt server
2781
- * @return {Promise<boolean>} Wheter successfully connect to mqtt server or not
2782
- */
2783
- )
2784
- }, {
2785
- key: "openRealtimeConnection",
2786
- value: (function () {
2787
- var _openRealtimeConnection = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee20() {
2788
- return _regenerator["default"].wrap(function (_context20) {
2789
- while (1) switch (_context20.prev = _context20.next) {
2790
- case 0:
2791
- return _context20.abrupt("return", this.realtimeAdapter.openConnection());
2792
- case 1:
2793
- case "end":
2794
- return _context20.stop();
2795
- }
2796
- }, _callee20, this);
2797
- }));
2798
- function openRealtimeConnection() {
2799
- return _openRealtimeConnection.apply(this, arguments);
2800
- }
2801
- return openRealtimeConnection;
2802
- }())
2803
- }, {
2804
- key: "startSync",
2805
- value: function () {
2806
- var _startSync = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee21() {
2807
- return _regenerator["default"].wrap(function (_context21) {
2808
- while (1) switch (_context21.prev = _context21.next) {
2809
- case 0:
2810
- this._forceEnableSync = true;
2811
- case 1:
2812
- case "end":
2813
- return _context21.stop();
2814
- }
2815
- }, _callee21, this);
2816
- }));
2817
- function startSync() {
2818
- return _startSync.apply(this, arguments);
1875
+ if (sender != null) opts["sender"] = sender;
1876
+ return this.HTTPAdapter.post_json(url, opts).then((res) => res.body);
1877
+ });
1878
+ }
1879
+ _generateUniqueId() {
1880
+ return `javascript-${nanoid.nanoid()}`;
1881
+ }
1882
+ generateMessage({ roomId, text, extras }) {
1883
+ const id = Date.now();
1884
+ const comment = new Comment({
1885
+ id,
1886
+ message: text,
1887
+ room_id: roomId,
1888
+ extras,
1889
+ timestamp: /* @__PURE__ */ new Date(),
1890
+ unique_id: this._generateUniqueId(),
1891
+ before_id: 0,
1892
+ username: this.userData.username,
1893
+ email: this.userData.email,
1894
+ status: "pending",
1895
+ type: "text"
1896
+ });
1897
+ return comment;
1898
+ }
1899
+ generateFileAttachmentMessage({
1900
+ roomId,
1901
+ caption,
1902
+ url,
1903
+ text = "File attachment",
1904
+ extras,
1905
+ filename,
1906
+ size
1907
+ }) {
1908
+ const id = Date.now();
1909
+ const comment = new Comment({
1910
+ id,
1911
+ message: text,
1912
+ room_id: roomId,
1913
+ extras,
1914
+ timestamp: /* @__PURE__ */ new Date(),
1915
+ unique_id: this._generateUniqueId(),
1916
+ before_id: 0,
1917
+ username: this.userData.username,
1918
+ email: this.userData.email,
1919
+ status: "pending",
1920
+ type: "file_attachment",
1921
+ payload: {
1922
+ url,
1923
+ file_name: filename,
1924
+ size,
1925
+ caption
2819
1926
  }
2820
- return startSync;
2821
- }()
2822
- }, {
2823
- key: "stopSync",
2824
- value: function () {
2825
- var _stopSync = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee22() {
2826
- return _regenerator["default"].wrap(function (_context22) {
2827
- while (1) switch (_context22.prev = _context22.next) {
2828
- case 0:
2829
- this._forceEnableSync = false;
2830
- case 1:
2831
- case "end":
2832
- return _context22.stop();
2833
- }
2834
- }, _callee22, this);
2835
- }));
2836
- function stopSync() {
2837
- return _stopSync.apply(this, arguments);
1927
+ });
1928
+ return comment;
1929
+ }
1930
+ generateCustomMessage({ roomId, text, type, payload, extras }) {
1931
+ const id = Date.now();
1932
+ const comment = new Comment({
1933
+ id,
1934
+ message: text,
1935
+ room_id: roomId,
1936
+ extras,
1937
+ timestamp: /* @__PURE__ */ new Date(),
1938
+ unique_id: this._generateUniqueId(),
1939
+ before_id: 0,
1940
+ username: this.userData.username,
1941
+ email: this.userData.email,
1942
+ status: "pending",
1943
+ type: "custom",
1944
+ payload: { type, content: payload }
1945
+ });
1946
+ return comment;
1947
+ }
1948
+ generateReplyMessage({ roomId, text, repliedMessage, extras }) {
1949
+ const id = Date.now();
1950
+ const comment = new Comment({
1951
+ id,
1952
+ message: text,
1953
+ room_id: roomId,
1954
+ extras,
1955
+ timestamp: /* @__PURE__ */ new Date(),
1956
+ unique_id: this._generateUniqueId(),
1957
+ before_id: 0,
1958
+ username: this.userData.username,
1959
+ email: this.userData.email,
1960
+ status: "pending",
1961
+ type: "reply",
1962
+ payload: {
1963
+ text,
1964
+ replied_comment_id: repliedMessage.id,
1965
+ replied_comment_message: repliedMessage.message,
1966
+ replied_comment_type: repliedMessage.type,
1967
+ replied_comment_payload: repliedMessage.payload,
1968
+ replied_comment_sender_username: repliedMessage.username_as,
1969
+ replied_comment_sender_email: repliedMessage.username_real
2838
1970
  }
2839
- return stopSync;
2840
- }()
2841
- }]);
2842
- }();
2843
- (0, _defineProperty2["default"])(QiscusSDK, "UpdateCommentStatusMode", UpdateCommentStatusMode);
2844
- (0, _defineProperty2["default"])(QiscusSDK, "Interceptor", _hook.Hooks);
2845
- var FileUploaded = /*#__PURE__*/(0, _createClass2["default"])(function FileUploaded(name, roomId) {
2846
- (0, _classCallCheck2["default"])(this, FileUploaded);
2847
- this.name = name;
2848
- this.roomId = roomId;
2849
- this.progress = 0;
2850
- });
2851
- var _default = exports["default"] = QiscusSDK;
2852
- module.exports = exports.default;
1971
+ });
1972
+ return comment;
1973
+ }
1974
+ updateMessage(message) {
1975
+ return __async(this, null, function* () {
1976
+ return this.userAdapter.updateMessage(message);
1977
+ });
1978
+ }
1979
+ onMessageUpdated(handler) {
1980
+ this.realtimeAdapter.on("message:updated", handler);
1981
+ return () => this.realtimeAdapter.off("message:updated", handler);
1982
+ }
1983
+ /**
1984
+ * Manually close connection to mqtt server
1985
+ * @return {Promise<boolean>} Wheter successfully close mqtt connection or not
1986
+ */
1987
+ closeRealtimeConnection() {
1988
+ return __async(this, null, function* () {
1989
+ return this.realtimeAdapter.closeConnection();
1990
+ });
1991
+ }
1992
+ /**
1993
+ * Manually open connection to mqtt server
1994
+ * @return {Promise<boolean>} Wheter successfully connect to mqtt server or not
1995
+ */
1996
+ openRealtimeConnection() {
1997
+ return __async(this, null, function* () {
1998
+ return this.realtimeAdapter.openConnection();
1999
+ });
2000
+ }
2001
+ startSync() {
2002
+ return __async(this, null, function* () {
2003
+ this._forceEnableSync = true;
2004
+ });
2005
+ }
2006
+ stopSync() {
2007
+ return __async(this, null, function* () {
2008
+ this._forceEnableSync = false;
2009
+ });
2010
+ }
2011
+ };
2012
+ __publicField(_QiscusSDK, "UpdateCommentStatusMode", UpdateCommentStatusMode);
2013
+ __publicField(_QiscusSDK, "Interceptor", hook.Hooks);
2014
+ let QiscusSDK = _QiscusSDK;
2015
+ class FileUploaded {
2016
+ constructor(name, roomId) {
2017
+ this.name = name;
2018
+ this.roomId = roomId;
2019
+ this.progress = 0;
2020
+ }
2021
+ }
2022
+ module.exports = QiscusSDK;