qiscus-sdk-core 2.16.0 → 2.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,95 +1,105 @@
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 request = require("superagent");
43
+ const mitt = require("mitt");
44
+ const is = require("./lib/is.js");
45
+ const format = require("date-fns/format");
46
+ const distanceInWordsToNow = require("date-fns/distance_in_words_to_now");
47
+ const Comment = require("./lib/Comment.js");
48
+ const Room = require("./lib/Room.js");
49
+ const http = require("./lib/adapters/http.js");
50
+ const auth = require("./lib/adapters/auth.js");
51
+ const user = require("./lib/adapters/user.js");
52
+ const room = require("./lib/adapters/room.js");
53
+ const mqtt = require("./lib/adapters/mqtt.js");
54
+ const customEvent = require("./lib/adapters/custom-event.js");
55
+ const sync = require("./lib/adapters/sync.js");
56
+ const utils = require("./lib/utils.js");
57
+ const util = require("./lib/util.js");
58
+ const Package = require("../package.json");
59
+ const hook = require("./lib/adapters/hook.js");
60
+ const expiredToken = require("./lib/adapters/expired-token.js");
61
+ let setBackToOnline;
62
+ const UpdateCommentStatusMode = Object.freeze({
63
+ disabled: "UpdateCommentStatusMode.disabled",
64
+ throttled: "UpdateCommentStatusMode.throttled",
65
+ enabled: "UpdateCommentStatusMode.enabled"
44
66
  });
45
-
46
- /**
47
- * Qiscus Web SDK Core Class
48
- *
49
- * @export
50
- * @class QiscusSDK
51
- */
52
- var QiscusSDK = /*#__PURE__*/function () {
67
+ const _QiscusSDK = class _QiscusSDK {
53
68
  /**
54
69
  * Creates an instance of QiscusSDK.
55
70
  */
56
- function QiscusSDK() {
57
- var _this = this;
58
- (0, _classCallCheck2["default"])(this, QiscusSDK);
59
- (0, _defineProperty2["default"])(this, "_pendingComments", []);
71
+ constructor() {
72
+ __publicField(this, "_pendingComments", []);
60
73
  // 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"])();
74
+ __publicField(this, "_pendingCommentsCount", {});
75
+ __publicField(this, "_readComment", (roomId, commentId) => this._updateStatus(roomId, commentId));
76
+ __publicField(this, "_readCommentT", this._throttle(
77
+ (roomId, commentId) => {
78
+ this._updateStatus(roomId, commentId);
79
+ },
80
+ () => this._throttleDelay
81
+ ));
82
+ __publicField(this, "_deliverComment", (roomId, commentId) => this._updateStatus(roomId, void 0, commentId));
83
+ __publicField(this, "_deliverCommentT", this._throttle(
84
+ (roomId, commentId) => {
85
+ this._updateStatus(roomId, void 0, commentId);
86
+ },
87
+ () => this._throttleDelay
88
+ ));
89
+ this.events = mitt();
79
90
  this.rooms = [];
80
91
  this.selected = null;
81
92
  this.room_name_id_map = {};
82
93
  this.pendingCommentId = 0;
83
94
  this.uploadedFiles = [];
84
95
  this.chatmateStatus = null;
85
- this.version = "WEB_".concat(_package["default"].version);
96
+ this.version = `WEB_${Package.version}`;
86
97
  this.userData = {};
87
- // SDK Configuration
88
98
  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;
99
+ this.baseURL = "https://api.qiscus.com";
100
+ this.mqttURL = "wss://realtime-jogja.qiscus.com:1886/mqtt";
101
+ this.brokerLbUrl = "https://realtime-lb.qiscus.com";
102
+ this.syncOnConnect = 1e4;
93
103
  this.enableEventReport = false;
94
104
  this.enableRealtime = true;
95
105
  this.enableRealtimeCheck = true;
@@ -101,2752 +111,1884 @@ var QiscusSDK = /*#__PURE__*/function () {
101
111
  this.customEventAdapter = null;
102
112
  this.isInit = false;
103
113
  this.isSynced = false;
104
- this.syncInterval = 5000;
105
- this.sync = 'socket'; // possible values 'socket', 'http', 'both'
114
+ this.syncInterval = 5e3;
115
+ this.sync = "socket";
106
116
  this.enableLb = true;
107
117
  this.httpsync = null;
108
118
  this.eventsync = null;
109
119
  this.extras = null;
110
120
  this.last_received_comment_id = 0;
111
- this.googleMapKey = '';
121
+ this.googleMapKey = "";
112
122
  this.options = {
113
123
  avatar: true
114
124
  };
115
125
  this.isConfigLoaded = false;
116
- this.updateCommentStatusMode = QiscusSDK.UpdateCommentStatusMode.enabled;
126
+ this.updateCommentStatusMode = _QiscusSDK.UpdateCommentStatusMode.enabled;
117
127
  this.updateCommentStatusThrottleDelay = 300;
118
-
119
- // UI related Properties
120
128
  this.UI = {};
121
- this.mode = 'widget';
129
+ this.mode = "widget";
122
130
  this.avatar = true;
123
131
  this.plugins = [];
124
132
  this.isLogin = false;
125
133
  this.isLoading = false;
126
134
  this.isInit = false;
127
135
  this.emoji = false;
128
- this.isTypingStatus = '';
136
+ this.isTypingStatus = "";
129
137
  this.customTemplate = false;
130
138
  this.templateFunction = null;
131
139
  this.debugMode = false;
132
140
  this.debugMQTTMode = false;
133
141
  this._customHeader = {};
134
142
  this._forceEnableSync = true;
135
-
136
- // to prevent double receive newmessages callback
137
143
  this.lastReceiveMessages = [];
138
- this._hookAdapter = (0, _hook.hookAdapterFactory)();
144
+ this._hookAdapter = hook.hookAdapterFactory();
139
145
  this._uploadURL = null;
140
146
  this._autoRefreshToken = false;
141
147
  }
142
-
143
148
  // 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);
149
+ get uploadURL() {
150
+ return this._uploadURL || `${this.baseURL}/api/v2/sdk/upload`;
151
+ }
152
+ set uploadURL(uploadURL) {
153
+ this._uploadURL = uploadURL;
154
+ }
155
+ /**
156
+ * Initializing the SDK, set Event Listeners (callbacks)
157
+ * @param {any} config - Qiscus SDK Configurations
158
+ * @return {Promise<void>}
159
+ */
160
+ init(config) {
161
+ return __async(this, null, function* () {
162
+ var _a;
163
+ if (!config.AppId) throw new Error("Please provide valid AppId");
164
+ this.AppId = config.AppId;
165
+ const isDifferentBaseUrl = config.baseURL != null && this.baseURL !== config.baseURL;
166
+ const isDifferentMqttUrl = config.mqttURL != null && this.mqttURL !== config.mqttURL;
167
+ const isDifferentBrokerLbUrl = config.brokerLbURL != null && this.brokerLbUrl !== config.brokerLbURL;
168
+ if ((isDifferentBaseUrl || isDifferentMqttUrl) && !isDifferentBrokerLbUrl) {
169
+ this.logger(
170
+ "force disable load balancing for realtime server, because `baseURL` or `mqttURL` get changed but did not provide `brokerLbURL`"
171
+ );
172
+ this.enableLb = false;
173
+ } else if (config.enableRealtimeLB != null) {
174
+ this.enableLb = config.enableRealtimeLB;
491
175
  }
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;
176
+ if (config.updateCommentStatusMode != null)
177
+ this.updateCommentStatusMode = config.updateCommentStatusMode;
178
+ if (config.updateCommentStatusThrottleDelay != null)
179
+ this.updateCommentStatusThrottleDelay = config.updateCommentStatusThrottleDelay;
180
+ if (config.baseURL) this.baseURL = config.baseURL;
181
+ if (config.mqttURL) this.mqttURL = config.brokerUrl || config.mqttURL;
182
+ if (config.mqttURL) this.brokerUrl = config.brokerUrl || config.mqttURL;
183
+ if (config.brokerLbURL) this.brokerLbUrl = config.brokerLbURL;
184
+ if (config.uploadURL) this.uploadURL = config.uploadURL;
185
+ if (config.sync) this.sync = config.sync;
186
+ if (config.mode) this.mode = config.mode;
187
+ if (config.syncInterval) this.syncInterval = config.syncInterval || 5e3;
188
+ if (config.googleMapKey) this.googleMapKey = config.googleMapKey;
189
+ if (config.allowedFileTypes) {
190
+ this.allowedFileTypes = config.allowedFileTypes;
191
+ }
192
+ if (config.options) {
193
+ this.options = Object.assign({}, this.options, config.options);
194
+ }
195
+ if (config.customTemplate) this.customTemplate = config.customTemplate;
196
+ if (config.templateFunction) {
197
+ this.templateFunction = config.templateFunction;
198
+ }
199
+ if (config.syncInterval != null) this.syncInterval = config.syncInterval;
200
+ this.HTTPAdapter = new http({
201
+ baseURL: this.baseURL,
202
+ AppId: this.AppId,
203
+ userId: this.user_id,
204
+ version: this.version,
205
+ getCustomHeader: () => this._customHeader
501
206
  });
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);
207
+ const setterHelper = (fromUser, fromServer, defaultValue) => {
208
+ if (fromServer === "") {
209
+ if (fromUser != null) {
210
+ if (typeof fromUser !== "string") return fromUser;
211
+ if (fromUser.length > 0) return fromUser;
212
+ }
513
213
  }
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
214
+ if (fromServer != null) {
215
+ if (fromServer.length > 0) return fromServer;
216
+ if (typeof fromServer !== "string") return fromServer;
217
+ }
218
+ return defaultValue;
536
219
  };
537
- room.comments.forEach(function (it) {
538
- if (it.id <= message.id) {
539
- it.markAsDelivered(options);
220
+ const mqttWssCheck = (mqttResult) => {
221
+ if (mqttResult.includes("wss://")) {
222
+ return mqttResult;
223
+ } else {
224
+ return `wss://${mqttResult}:1886/mqtt`;
540
225
  }
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
- }
226
+ };
227
+ this.withConfig = (_a = config.withConfig) != null ? _a : true;
228
+ if (this.withConfig === true) {
229
+ yield this.HTTPAdapter.get_request("api/v2/sdk/config").then((resp) => {
230
+ resp.status == 200 ? this.isConfigLoaded = true : this.isConfigLoaded = false;
231
+ return resp.body.results;
232
+ }).then((cfg) => {
233
+ const baseUrl = this.baseURL;
234
+ const brokerLbUrl = this.brokerLbUrl;
235
+ const mqttUrl = this.mqttURL;
236
+ const enableRealtime = this.enableRealtime;
237
+ const enableRealtimeCheck = this.enableRealtimeCheck;
238
+ const syncInterval = this.syncInterval;
239
+ const syncIntervalWhenConnected = this.syncOnConnect;
240
+ const enableEventReport = this.enableEventReport;
241
+ const configExtras = {};
242
+ this.baseURL = setterHelper(config.baseURL, cfg.base_url, baseUrl);
243
+ this.brokerLbUrl = setterHelper(
244
+ config.brokerLbURL,
245
+ cfg.broker_lb_url,
246
+ brokerLbUrl
247
+ );
248
+ this.mqttURL = mqttWssCheck(
249
+ setterHelper(config.mqttURL, cfg.broker_url, mqttUrl)
250
+ );
251
+ this.enableRealtime = setterHelper(
252
+ config.enableRealtime,
253
+ cfg.enable_realtime,
254
+ enableRealtime
255
+ );
256
+ this.syncInterval = setterHelper(
257
+ config.syncInterval,
258
+ cfg.sync_interval,
259
+ syncInterval
260
+ );
261
+ this.syncOnConnect = setterHelper(
262
+ config.syncOnConnect,
263
+ cfg.sync_on_connect,
264
+ syncIntervalWhenConnected
265
+ );
266
+ this.enableRealtimeCheck = setterHelper(
267
+ null,
268
+ cfg.enable_realtime_check,
269
+ enableRealtimeCheck
270
+ );
271
+ this.enableEventReport = setterHelper(
272
+ null,
273
+ cfg.enable_event_report,
274
+ enableEventReport
275
+ );
276
+ this.extras = setterHelper(null, cfg.extras, configExtras);
277
+ this.enableSync = setterHelper(null, cfg.enable_sync, this.enableSync);
278
+ this.enableSyncEvent = setterHelper(null, cfg.enable_sync_event, this.enableSyncEvent);
279
+ this._autoRefreshToken = setterHelper(null, cfg.auto_refresh_token, false);
280
+ }).catch((err) => {
281
+ this.logger("got error when trying to get app config", err);
282
+ this.isConfigLoaded = true;
566
283
  });
567
- self.HTTPAdapter.setToken(self.userData.token);
284
+ } else {
285
+ this.isConfigLoaded = true;
286
+ }
287
+ this._getMqttClientId = () => `${this.AppId}_${this.user_id}_${Date.now()}`;
288
+ this.realtimeAdapter = new mqtt(this.mqttURL, this, this.isLogin, {
289
+ brokerLbUrl: this.brokerLbUrl,
290
+ enableLb: this.enableLb,
291
+ shouldConnect: this.enableRealtime,
292
+ getClientId: this._getMqttClientId
568
293
  });
569
- self.events.on('room-changed', function (room) {
570
- _this3.logging('room changed', room);
571
- if (self.options.roomChangedCallback) {
572
- self.options.roomChangedCallback(room);
294
+ this.realtimeAdapter.on("connected", () => {
295
+ if (this.isLogin || !this.realtimeAdapter.connected) {
296
+ this.last_received_comment_id = this.userData.last_comment_id;
297
+ this.updateLastReceivedComment(this.last_received_comment_id);
573
298
  }
574
299
  });
575
- self.events.on('file-uploaded', function (url) {
576
- if (self.options.fileUploadedCallback) {
577
- self.options.fileUploadedCallback(url);
578
- }
300
+ this.realtimeAdapter.on("close", () => {
579
301
  });
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
- }
302
+ this.realtimeAdapter.on("reconnect", () => {
303
+ var _a2, _b;
304
+ (_b = (_a2 = this.options).onReconnectCallback) == null ? void 0 : _b.call(_a2);
586
305
  });
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;
306
+ this.realtimeAdapter.on(
307
+ "message-delivered",
308
+ ({ commentId, commentUniqueId, userId }) => this._setDelivered(commentId, commentUniqueId, userId)
309
+ );
310
+ this.realtimeAdapter.on(
311
+ "message-read",
312
+ ({ commentId, commentUniqueId, userId }) => this._setRead(commentId, commentUniqueId, userId)
313
+ );
314
+ this.realtimeAdapter.on("new-message", (message) => __async(this, null, function* () {
315
+ message = yield this._hookAdapter.trigger(
316
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
317
+ message
318
+ );
319
+ this.events.emit("newmessages", [message]);
320
+ }));
321
+ this.realtimeAdapter.on(
322
+ "presence",
323
+ (data) => this.events.emit("presence", data)
324
+ );
325
+ this.realtimeAdapter.on(
326
+ "comment-deleted",
327
+ (data) => this.events.emit("comment-deleted", data)
328
+ );
329
+ this.realtimeAdapter.on(
330
+ "room-cleared",
331
+ (data) => this.events.emit("room-cleared", data)
332
+ );
333
+ this.realtimeAdapter.on(
334
+ "typing",
335
+ (data) => this.events.emit("typing", {
336
+ message: data.message,
337
+ username: data.userId,
338
+ room_id: data.roomId
339
+ })
340
+ );
341
+ this.realtimeAdapter.on("message:updated", (message) => {
342
+ if (this.options.messageUpdatedCallback != null) {
343
+ this.options.messageUpdatedCallback(message);
601
344
  }
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
345
  });
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
- }
346
+ this.realtimeAdapter.on("room-typing", (data) => {
347
+ this.events.emit("typing", {
348
+ message: data.text,
349
+ username: data.sender_name,
350
+ email: data.sender_id,
351
+ room_id: data.room_id
693
352
  });
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);
353
+ if (this.options.onRoomTypingCallback != null) {
354
+ this.events.emit("room-typing", data);
355
+ this.options.onRoomTypingCallback(data);
719
356
  }
720
357
  });
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);
358
+ this.syncAdapter = sync(() => this.HTTPAdapter, {
359
+ syncInterval: () => this.syncInterval,
360
+ getShouldSync: () => this._forceEnableSync && (this.isLogin && !this.realtimeAdapter.connected),
361
+ syncOnConnect: () => this.syncOnConnect,
362
+ lastCommentId: () => this.last_received_comment_id,
363
+ statusLogin: () => this.isLogin,
364
+ enableSync: () => this.enableSync,
365
+ enableSyncEvent: () => this.enableSyncEvent
724
366
  });
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
- }
367
+ this.syncAdapter.on("message.new", (message) => __async(this, null, function* () {
368
+ message = yield this._hookAdapter.trigger(
369
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
370
+ message
371
+ );
372
+ if (this.selected != null) {
373
+ const index = this.selected.comments.findIndex(
374
+ (it) => it.id === message.id || it.unique_id === message.unique_temp_id
375
+ );
376
+ if (index === -1) {
377
+ const _message = new Comment(message);
378
+ if (_message.room_id === this.selected.id) {
379
+ this.selected.comments.push(_message);
380
+ this.sortComments();
756
381
  }
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);
382
+ this.events.emit("newmessages", [message]);
383
+ }
384
+ } else {
385
+ this.events.emit("newmessages", [message]);
777
386
  }
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);
387
+ }));
388
+ this.syncAdapter.on("message.delivered", (message) => {
389
+ this._setDelivered(
390
+ message.comment_id,
391
+ message.comment_unique_id,
392
+ message.email
393
+ );
781
394
  });
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
- }
395
+ this.syncAdapter.on("message.read", (message) => {
396
+ this._setRead(
397
+ message.comment_id,
398
+ message.comment_unique_id,
399
+ message.email
400
+ );
791
401
  });
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
- }
402
+ this.syncAdapter.on("message.deleted", (data) => {
403
+ data.deleted_messages.forEach((it) => {
404
+ this.events.emit("comment-deleted", {
405
+ roomId: it.room_id,
406
+ commentUniqueIds: it.message_unique_ids,
407
+ isForEveryone: true,
408
+ isHard: true
409
+ });
410
+ });
801
411
  });
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
- }
412
+ this.syncAdapter.on("room.cleared", (data) => {
413
+ data.deleted_rooms.forEach((room2) => {
414
+ this.events.emit("room-cleared", room2);
415
+ });
810
416
  });
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
- }
417
+ this.syncAdapter.on("synchronize", () => {
418
+ this._pendingComments.forEach((m) => this._retrySendComment(m));
820
419
  });
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);
420
+ this.syncAdapter.on("last-message-id.new", (id) => {
421
+ this.last_received_comment_id = id;
834
422
  });
835
- self.events.on('typing', function (data) {
836
- if (self.options.typingCallback) self.options.typingCallback(data);
423
+ this.customEventAdapter = customEvent(
424
+ this.realtimeAdapter,
425
+ this.user_id
426
+ );
427
+ this.setEventListeners();
428
+ });
429
+ }
430
+ _setRead(messageId, messageUniqueId, userId) {
431
+ if (this.selected == null) return;
432
+ const room2 = this.selected;
433
+ const message = room2.comments.find(
434
+ (it) => it.id === messageId || it.unique_id === messageUniqueId
435
+ );
436
+ if (message == null) return;
437
+ if (message.status === "read") return;
438
+ const options = {
439
+ participants: room2.participants,
440
+ actor: userId,
441
+ comment_id: messageId,
442
+ activeActorId: this.user_id
443
+ };
444
+ room2.comments.forEach((it) => {
445
+ if (it.id <= message.id) {
446
+ it.markAsRead(options);
447
+ }
448
+ });
449
+ if (!message.isRead) return;
450
+ this.events.emit("comment-read", { comment: message, userId });
451
+ }
452
+ _setDelivered(messageId, messageUniqueId, userId) {
453
+ if (this.selected == null) return;
454
+ const room2 = this.selected;
455
+ const message = room2.comments.find(
456
+ (it) => it.id === messageId || it.unique_id === messageUniqueId
457
+ );
458
+ if (message == null) return;
459
+ if (message.status === "read") return;
460
+ const options = {
461
+ participants: room2.participants,
462
+ actor: userId,
463
+ comment_id: messageId,
464
+ activeActorId: this.user_id
465
+ };
466
+ room2.comments.forEach((it) => {
467
+ if (it.id <= message.id) {
468
+ it.markAsDelivered(options);
469
+ }
470
+ });
471
+ if (!message.isDelivered) return;
472
+ this.events.emit("comment-delivered", { comment: message, userId });
473
+ }
474
+ setEventListeners() {
475
+ const self = this;
476
+ this.authAdapter = new auth(self.HTTPAdapter);
477
+ if (this.userData.email != null) {
478
+ this.authAdapter.userId = this.userData.email;
479
+ }
480
+ self.events.on("start-init", () => {
481
+ self.HTTPAdapter = new http({
482
+ baseURL: self.baseURL,
483
+ AppId: self.AppId,
484
+ userId: self.user_id,
485
+ version: self.version,
486
+ getCustomHeader: () => this._customHeader
837
487
  });
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);
488
+ self.HTTPAdapter.setToken(self.userData.token);
489
+ });
490
+ self.events.on("room-changed", (room2) => {
491
+ this.logging("room changed", room2);
492
+ if (self.options.roomChangedCallback) {
493
+ self.options.roomChangedCallback(room2);
494
+ }
495
+ });
496
+ self.events.on("file-uploaded", (url) => {
497
+ if (self.options.fileUploadedCallback) {
498
+ self.options.fileUploadedCallback(url);
499
+ }
500
+ });
501
+ self.events.on("profile-updated", (user2) => {
502
+ self.username = user2.name;
503
+ self.avatar_url = user2.avatar_url;
504
+ if (self.options.updateProfileCallback) {
505
+ self.options.updateProfileCallback(user2);
506
+ }
507
+ });
508
+ self.events.on("newmessages", (comments) => {
509
+ this.logging("newmessages", comments);
510
+ const lastReceivedMessageNotEmpty = this.lastReceiveMessages.length > 0;
511
+ if (lastReceivedMessageNotEmpty && this.lastReceiveMessages[0].unique_temp_id === comments[0].unique_temp_id) {
512
+ this.logging("lastReceiveMessages double", comments);
513
+ return;
514
+ }
515
+ this.lastReceiveMessages = comments;
516
+ self._callNewMessagesCallback(comments);
517
+ comments.forEach((comment) => {
518
+ self.receiveComment(comment.room_id, comment.id);
519
+ const isActiveRoom = self.selected ? comment.room_id === self.selected.id : false;
520
+ const isAlreadyRead = comment.id <= self.last_received_comment_id;
521
+ if (isActiveRoom) {
522
+ const selected = self.selected;
523
+ const lastComment = self.selected.comments[self.selected.comments.length - 1];
524
+ if (!lastComment.isPending && !isAlreadyRead && self.user_id !== comment.email) {
525
+ self.readComment(comment.room_id, comment.id);
526
+ }
527
+ const roomLastCommentId = lastComment.id;
528
+ const commentBeforeThis = self.selected.comments.find(
529
+ (c) => c.id === lastComment.comment_before_id
530
+ );
531
+ if (!lastComment.isPending && !commentBeforeThis) {
532
+ this.logging(
533
+ "comment before id not found! ",
534
+ comment.comment_before_id
535
+ );
536
+ self.synchronize(roomLastCommentId);
537
+ }
538
+ const pendingComment = new Comment(comment);
539
+ selected.receiveComment(pendingComment);
540
+ selected.last_comment_id = pendingComment.id;
541
+ selected.last_comment_message = pendingComment.message;
845
542
  }
543
+ self.updateLastReceivedComment(comment.id);
544
+ this.sortComments();
846
545
  });
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;
546
+ });
547
+ this.events.on("login-success", (response) => {
548
+ this.isLogin = true;
549
+ this.userData = response.user;
550
+ this.last_received_comment_id = this.userData.last_comment_id;
551
+ if (!this.realtimeAdapter.connected)
552
+ this.updateLastReceivedComment(this.last_received_comment_id);
553
+ this.HTTPAdapter = new http({
554
+ baseURL: this.baseURL,
555
+ AppId: this.AppId,
556
+ userId: this.user_id,
557
+ version: this.version,
558
+ getCustomHeader: () => this._customHeader,
559
+ expiredTokenAdapterGetter: () => this.expiredTokenAdapter
866
560
  });
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);
561
+ this.HTTPAdapter.setToken(this.userData.token);
562
+ let user$1 = response.user;
563
+ this._delayedSync = utils.delayed(() => {
564
+ this.synchronize();
565
+ this.synchronizeEvent();
566
+ }, 500);
567
+ this.expiredTokenAdapter = new expiredToken.ExpiredTokenAdapter({
568
+ httpAdapter: this.HTTPAdapter,
569
+ refreshToken: user$1.refresh_token,
570
+ expiredAt: user$1.token_expires_at,
571
+ userId: this.user_id,
572
+ onTokenRefreshed: (token, refreshToken, expiredAt, oldToken) => {
573
+ this.userData.token = token;
574
+ this.userData.refresh_token = refreshToken;
575
+ this.userData.token_expires_at = expiredAt == null ? void 0 : expiredAt.toJSON();
576
+ this.events.emit("token-refreshed", { token, refreshToken, expiredAt, oldToken });
577
+ this.realtimeAdapter.unsusbcribeUserChannelByToken(oldToken);
578
+ this.realtimeAdapter.subscribeUserChannelByToken(token);
579
+ this._delayedSync();
580
+ },
581
+ getAuthenticationStatus: () => {
582
+ return this.user_id != null && this.isLogin;
874
583
  }
875
584
  });
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);
585
+ this.userAdapter = new user(this.HTTPAdapter);
586
+ this.roomAdapter = new room(this.HTTPAdapter);
587
+ this.realtimeAdapter.subscribeUserChannel();
588
+ if (this.presensePublisherId != null && this.presensePublisherId !== -1) {
589
+ clearInterval(this.presensePublisherId);
590
+ }
591
+ this.presensePublisherId = setInterval(() => {
592
+ this.realtimeAdapter.publishPresence(this.user_id, true);
593
+ }, 3500);
594
+ if (this.options.loginSuccessCallback) {
595
+ this.options.loginSuccessCallback(response);
596
+ }
597
+ this.authAdapter.userId = this.userData.email;
598
+ this.authAdapter.refreshToken = this.userData.refresh_token;
599
+ this.authAdapter.autoRefreshToken = this._autoRefreshToken;
600
+ });
601
+ self.events.on("login-error", function(error) {
602
+ if (self.options.loginErrorCallback) {
603
+ self.options.loginErrorCallback(error);
604
+ }
605
+ });
606
+ self.events.on("token-refreshed", (param) => {
607
+ var _a, _b;
608
+ (_b = (_a = this.options).authTokenRefreshedCallback) == null ? void 0 : _b.call(_a, param);
609
+ });
610
+ self.events.on("room-cleared", function(room2) {
611
+ if (self.selected) {
612
+ const currentRoom = self.selected;
613
+ if (self.selected.unique_id === room2.unique_id) {
614
+ self.selected = null;
615
+ self.selected = currentRoom;
883
616
  }
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
617
  }
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;
618
+ if (self.options.roomClearedCallback) {
619
+ self.options.roomClearedCallback(room2);
905
620
  }
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...');
621
+ });
622
+ self.events.on("comment-deleted", function(data) {
623
+ const {
624
+ roomId,
625
+ commentUniqueIds,
626
+ // eslint-disable-next-line
627
+ isForEveryone,
628
+ isHard
629
+ } = data;
630
+ if (self.selected && self.selected.id == roomId) {
631
+ commentUniqueIds.map((id) => {
632
+ const commentToBeFound = self.selected.comments.findIndex(
633
+ (comment) => comment.unique_id === id
634
+ );
635
+ if (commentToBeFound > -1) {
636
+ if (isHard) {
637
+ self.selected.comments.splice(commentToBeFound, 1);
638
+ } else {
639
+ self.selected.comments[commentToBeFound].message = "this message has been deleted";
938
640
  }
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
641
  }
955
- }, 300);
956
- });
642
+ const lastComment = self.selected.comments[self.selected.comments.length - 1];
643
+ self.selected.last_comment_id = lastComment.id;
644
+ self.selected.last_comment_message = lastComment.message;
645
+ });
646
+ }
647
+ if (self.options.commentDeletedCallback) {
648
+ self.options.commentDeletedCallback(data);
649
+ }
650
+ });
651
+ self.events.on("comment-delivered", function(response) {
652
+ self.logging("comment-delivered", response);
653
+ if (!response) return false;
654
+ if (self.options.commentDeliveredCallback) {
655
+ return self.options.commentDeliveredCallback(response);
656
+ }
657
+ });
658
+ self.events.on("chat-room-created", function(response) {
659
+ self.isLoading = false;
660
+ if (self.options.chatRoomCreatedCallback) {
661
+ self.options.chatRoomCreatedCallback(response);
662
+ }
663
+ });
664
+ self.events.on("group-room-created", function(response) {
665
+ self.isLoading = false;
666
+ if (self.options.groupRoomCreatedCallback) {
667
+ self.options.groupRoomCreatedCallback(response);
668
+ }
669
+ });
670
+ self.events.on("header-clicked", function(response) {
671
+ if (self.options.headerClickedCallback) {
672
+ self.options.headerClickedCallback(response);
673
+ }
674
+ });
675
+ self.events.on("comment-read", function(response) {
676
+ self.logging("comment-read", response);
677
+ if (self.options.commentReadCallback) {
678
+ self.options.commentReadCallback(response);
679
+ }
680
+ });
681
+ self.events.on("presence", ({ message, userId }) => {
682
+ const payload = message.split(":");
683
+ if (this.chatmateStatus !== payload[0]) {
684
+ this.chatmateStatus = payload[0] === 1 ? "Online" : `Last seen ${distanceInWordsToNow(
685
+ Number(payload[1].substring(0, 13))
686
+ )}`;
687
+ }
688
+ if (self.options.presenceCallback)
689
+ self.options.presenceCallback(message, userId);
690
+ });
691
+ self.events.on("typing", function(data) {
692
+ if (self.options.typingCallback) self.options.typingCallback(data);
693
+ });
694
+ self.events.on("message-info", function(response) {
695
+ if (self.options.messageInfoCallback) {
696
+ self.options.messageInfoCallback(response);
697
+ }
698
+ });
699
+ self.events.on("participants-added", (response) => {
700
+ if (response == null || this.selected == null) return;
701
+ this.selected.participants.push(...response);
702
+ });
703
+ self.events.on("participants-removed", (response) => {
704
+ if (response == null || this.selected == null) return;
705
+ const participants = this.selected.participants.filter(
706
+ (participant) => response.indexOf(participant.email) <= -1
707
+ );
708
+ this.selected.participants = participants;
709
+ });
710
+ self.events.on("block-user", function(response) {
711
+ if (self.options.blockUserCallback) {
712
+ self.options.blockUserCallback(response);
713
+ }
714
+ });
715
+ self.events.on("unblock-user", function(response) {
716
+ if (self.options.unblockUserCallback) {
717
+ self.options.unblockUserCallback(response);
718
+ }
719
+ });
720
+ }
721
+ onReconnectMqtt() {
722
+ if (this.options.onReconnectCallback) this.options.onReconnectedCallback();
723
+ if (!this.selected) return;
724
+ this.loadComments(this.selected.id);
725
+ }
726
+ _callNewMessagesCallback(comments) {
727
+ if (this.options.newMessagesCallback) {
728
+ this.options.newMessagesCallback(comments);
729
+ }
730
+ }
731
+ updateLastReceivedComment(id) {
732
+ if (this.last_received_comment_id < id) {
733
+ this.last_received_comment_id = id;
957
734
  }
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...');
735
+ }
736
+ /**
737
+ * Setting Up User Credentials for next API Request
738
+ * @param userId {string} - client userId (will be used for login or register)
739
+ * @param key {string} - client unique key
740
+ * @param username {string} - client username
741
+ * @param avatarURL {string} - the url for chat avatar (optional)
742
+ * @param extras {object} - extra data for user
743
+ * @return {Promise}
744
+ */
745
+ setUser(userId, key, username, avatarURL, extras) {
746
+ const self = this;
747
+ self.user_id = userId;
748
+ self.key = key;
749
+ self.username = username;
750
+ self.avatar_url = avatarURL;
751
+ let params = {
752
+ email: this.user_id,
753
+ password: this.key,
754
+ username: this.username,
755
+ extras: extras ? JSON.stringify(extras) : null
756
+ };
757
+ if (this.avatar_url) params.avatar_url = this.avatar_url;
758
+ return new Promise((resolve, reject) => {
759
+ let waitingConfig = setInterval(() => {
760
+ if (!this.isConfigLoaded) {
761
+ if (this.debugMode) {
762
+ this.logger("Waiting for init config...");
973
763
  }
974
764
  } else {
975
765
  clearInterval(waitingConfig);
976
- _this5.logger('Config Success!');
977
- _this5.events.emit('login-success', data);
766
+ this.logger("Config Success!");
767
+ self.events.emit("start-init");
768
+ let login$ = self.authAdapter.loginOrRegister(params).then(
769
+ (response) => {
770
+ self.isInit = true;
771
+ self.refresh_token = response.user.refresh_token;
772
+ self.events.emit("login-success", response);
773
+ this.realtimeAdapter.connect();
774
+ resolve(response);
775
+ },
776
+ (error) => {
777
+ self.events.emit("login-error", error);
778
+ reject(error);
779
+ }
780
+ );
781
+ return login$;
978
782
  }
979
783
  }, 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);
784
+ });
785
+ }
786
+ setUserWithIdentityToken(data) {
787
+ if (!data || !("user" in data)) return this.events.emit("login-error", data);
788
+ this.email = data.user.email;
789
+ this.user_id = data.user.email;
790
+ this.key = data.identity_token;
791
+ this.username = data.user.username;
792
+ this.avatar_url = data.user.avatar_url;
793
+ this.isInit = true;
794
+ let waitingConfig = setInterval(() => {
795
+ if (!this.isConfigLoaded) {
796
+ if (this.debugMode) {
797
+ this.logger("Waiting for init config...");
798
+ }
994
799
  } else {
995
- clearInterval(this.presensePublisherId);
996
- clearInterval(setBackToOnline);
997
- setTimeout(function () {
998
- _this6.realtimeAdapter.publishPresence(_this6.user_id, false);
999
- }, 3500);
800
+ clearInterval(waitingConfig);
801
+ this.logger("Config Success!");
802
+ this.events.emit("login-success", data);
1000
803
  }
804
+ }, 300);
805
+ }
806
+ refreshAuthToken() {
807
+ return this.expiredTokenAdapter.refreshAuthToken();
808
+ }
809
+ publishOnlinePresence(val) {
810
+ if (val === true) {
811
+ setBackToOnline = setInterval(() => {
812
+ this.realtimeAdapter.publishPresence(this.user_id, true);
813
+ }, 3500);
814
+ } else {
815
+ clearInterval(this.presensePublisherId);
816
+ clearInterval(setBackToOnline);
817
+ setTimeout(() => {
818
+ this.realtimeAdapter.publishPresence(this.user_id, false);
819
+ }, 3500);
1001
820
  }
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);
821
+ }
822
+ subscribeUserPresence(userId) {
823
+ this.realtimeAdapter.subscribeUserPresence(userId);
824
+ }
825
+ unsubscribeUserPresence(userId) {
826
+ this.realtimeAdapter.unsubscribeUserPresence(userId);
827
+ }
828
+ logout() {
829
+ return __async(this, null, function* () {
830
+ yield this.expiredTokenAdapter.logout();
831
+ clearInterval(this.presensePublisherId);
832
+ this.publishOnlinePresence(false);
833
+ this.selected = null;
834
+ this.isInit = false;
835
+ this.isLogin = false;
836
+ this.realtimeAdapter.disconnect();
837
+ this.userData = {};
838
+ });
839
+ }
840
+ get synchronize() {
841
+ return this.syncAdapter.synchronize;
842
+ }
843
+ get synchronizeEvent() {
844
+ return this.syncAdapter.synchronizeEvent;
845
+ }
846
+ disconnect() {
847
+ this.logout();
848
+ }
849
+ setActiveRoom(room2) {
850
+ if (this.selected) {
851
+ this.realtimeAdapter.unsubscribeTyping();
852
+ if (this.selected.room_type === "single") {
853
+ const unsubscribedUserId = this.selected.participants.filter(
854
+ (p) => p.email !== this.user_id
855
+ );
856
+ if (unsubscribedUserId.length > 0) {
857
+ this.realtimeAdapter.unsubscribeRoomPresence(
858
+ unsubscribedUserId[0].email
859
+ );
860
+ }
1037
861
  }
1038
- return logout;
1039
- }()
1040
- }, {
1041
- key: "synchronize",
1042
- get: function get() {
1043
- return this.syncAdapter.synchronize;
1044
862
  }
1045
- }, {
1046
- key: "synchronizeEvent",
1047
- get: function get() {
1048
- return this.syncAdapter.synchronizeEvent;
1049
- }
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
- }
863
+ if (room2.participants == null) room2.participants = [];
864
+ const targetUserId = room2.participants.find((p) => p.email !== this.user_id);
865
+ this.chatmateStatus = null;
866
+ this.isTypingStatus = null;
867
+ this.selected = room2;
868
+ const initialSubscribe = setInterval(() => {
869
+ if (this.debugMode) {
870
+ this.logger("Trying Initial Subscribe");
1073
871
  }
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');
872
+ if (this.realtimeAdapter != null) {
873
+ if (this.debugMode) {
874
+ this.logger("MQTT Connected");
1088
875
  }
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
- }
876
+ clearInterval(initialSubscribe);
877
+ if (room2.room_type === "single" && targetUserId != null) {
878
+ this.realtimeAdapter.subscribeRoomPresence(targetUserId.email);
1112
879
  }
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);
880
+ if (this.selected != null && !this.selected.isChannel) {
881
+ this.realtimeAdapter.subscribeTyping(room2.id);
882
+ this.events.emit("room-changed", this.selected);
883
+ }
884
+ if (this.debugMode && this.realtimeAdapter == null) {
885
+ this.logger("Retry");
886
+ }
887
+ } else {
888
+ if (this.debugMode) {
889
+ this.logger("MQTT Not Connected, yet");
890
+ }
891
+ }
892
+ }, 3e3);
893
+ }
894
+ /**
895
+ * Chat with targetted email
896
+ * @param userId {string} - target userId
897
+ * @param options {object} - optional data sent to qiscus database
898
+ * @return room <Room>
899
+ */
900
+ chatTarget(userId, options = {}) {
901
+ if (this.userData.length != null) return false;
902
+ const initialMessage = options ? options.message : null;
903
+ const distinctId = options.distinctId;
904
+ this.isLoading = true;
905
+ this.isTypingStatus = "";
906
+ return this.roomAdapter.getOrCreateRoom(userId, options, distinctId).then((resp) => __async(this, null, function* () {
907
+ const room2 = new Room(resp);
908
+ this.updateLastReceivedComment(room2.last_comment_id);
909
+ this.isLoading = false;
910
+ const mapIntercept = (it) => __async(this, null, function* () {
911
+ return yield this._hookAdapter.trigger(
912
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
913
+ it
914
+ );
1302
915
  });
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);
916
+ room2.comments = yield Promise.all(
917
+ room2.comments.map((comment) => mapIntercept(comment))
918
+ );
919
+ this.setActiveRoom(room2);
920
+ const lastComment = room2.comments[room2.comments.length - 1];
921
+ if (lastComment) this.readComment(room2.id, lastComment.id);
922
+ this.events.emit("chat-room-created", {
923
+ room: room2
1370
924
  });
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;
925
+ if (!initialMessage) return room2;
926
+ const topicId = room2.id;
927
+ return this.sendComment(topicId, initialMessage).then(() => Promise.resolve(room2)).catch((err) => {
928
+ console.error("Error when submit comment", err);
1382
929
  });
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);
930
+ })).catch((err) => {
931
+ console.error("Error when creating room", err);
932
+ this.isLoading = false;
933
+ return Promise.reject(err);
934
+ });
935
+ }
936
+ /**
937
+ *
938
+ * Open a group chat or target a specific room id
939
+ *
940
+ * @param {int} id
941
+ * @returns Room <Room>
942
+ * @memberof QiscusSDK
943
+ */
944
+ chatGroup(id) {
945
+ const self = this;
946
+ if (!self.isInit) return;
947
+ return self.getRoomById(id).then(
948
+ (response) => {
949
+ return Promise.resolve(response);
950
+ },
951
+ (err) => Promise.reject(err)
952
+ );
953
+ }
954
+ /**
955
+ * @param {int} id - Room Id
956
+ * @return {Room} Room data
957
+ */
958
+ getRoomById(id) {
959
+ if (!this.isInit) return;
960
+ const self = this;
961
+ self.isLoading = true;
962
+ self.isTypingStatus = "";
963
+ return self.roomAdapter.getRoomById(id).then((resp) => __async(this, null, function* () {
964
+ const roomData = resp.results.room;
965
+ const comments = [];
966
+ for (const comment of resp.results.comments.reverse()) {
967
+ const c = yield this._hookAdapter.trigger(
968
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
969
+ comment
970
+ );
971
+ comments.push(c);
1543
972
  }
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);
973
+ const room2 = new Room(__spreadProps(__spreadValues({}, roomData), {
974
+ comments,
975
+ name: roomData.room_name
1577
976
  }));
1578
- function searchMessages() {
1579
- return _searchMessages.apply(this, arguments);
977
+ self.updateLastReceivedComment(room2.last_comment_id);
978
+ self.setActiveRoom(room2);
979
+ self.isLoading = false;
980
+ const lastComment = room2.comments[room2.comments.length - 1];
981
+ if (lastComment) self.readComment(room2.id, lastComment.id);
982
+ if (room2.isChannel) {
983
+ this.realtimeAdapter.subscribeChannel(this.AppId, room2.unique_id);
1580
984
  }
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);
1593
- });
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);
985
+ return room2;
986
+ })).catch((error) => {
987
+ console.error("Error getting room by id", error);
988
+ return Promise.reject(error);
989
+ });
990
+ }
991
+ /**
992
+ * @param {int} id - Room Id
993
+ * @param {string} roomName
994
+ * @param {string} avatarURL
995
+ * @return {Room} Room data
996
+ */
997
+ getOrCreateRoomByUniqueId(id, roomName, avatarURL) {
998
+ const self = this;
999
+ self.isLoading = true;
1000
+ self.isTypingStatus = "";
1001
+ return self.roomAdapter.getOrCreateRoomByUniqueId(id, roomName, avatarURL).then((response) => __async(this, null, function* () {
1002
+ let room2 = new Room(response);
1003
+ self.updateLastReceivedComment(room2.last_comment_id);
1004
+ const mapIntercept = (item) => __async(this, null, function* () {
1005
+ return yield this._hookAdapter.trigger(hook.Hooks.MESSAGE_BEFORE_RECEIVED, item);
1602
1006
  });
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);
1007
+ room2.comments = yield Promise.all(
1008
+ room2.comments.map((it) => mapIntercept(it))
1009
+ );
1010
+ self.setActiveRoom(room2);
1011
+ self.isLoading = false;
1012
+ const lastComment = room2.comments[room2.comments.length - 1];
1013
+ if (lastComment) self.readComment(room2.id, lastComment.id);
1014
+ this.realtimeAdapter.subscribeChannel(this.AppId, room2.unique_id);
1015
+ return Promise.resolve(room2);
1016
+ })).catch((error) => {
1017
+ return Promise.reject(error);
1018
+ });
1019
+ }
1020
+ getOrCreateRoomByChannel(channel, name, avatarURL) {
1021
+ return this.getOrCreateRoomByUniqueId(channel, name, avatarURL);
1022
+ }
1023
+ sortComments() {
1024
+ this.selected && this.selected.comments.sort(function(leftSideComment, rightSideComment) {
1025
+ return leftSideComment.unix_timestamp - rightSideComment.unix_timestamp;
1026
+ });
1027
+ }
1028
+ loadRoomList() {
1029
+ return __async(this, arguments, function* (params = {}) {
1030
+ const rooms = yield this.userAdapter.loadRoomList(params);
1031
+ return rooms.map((room2) => {
1032
+ room2.last_comment_id = room2.last_comment.id;
1033
+ room2.last_comment_message = room2.last_comment.message;
1034
+ room2.last_comment_message_created_at = room2.last_comment.timestamp;
1035
+ room2.room_type = room2.chat_type;
1036
+ room2.comments = [];
1037
+ return new Room(room2);
1613
1038
  });
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);
1039
+ });
1040
+ }
1041
+ loadComments(roomId, options = {}) {
1042
+ return this.userAdapter.loadComments(roomId, options).then((comments_) => __async(this, null, function* () {
1043
+ const comments = [];
1044
+ for (const comment of comments_) {
1045
+ comments.push(
1046
+ yield this._hookAdapter.trigger(
1047
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
1048
+ comment
1049
+ )
1050
+ );
1775
1051
  }
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);
1865
- }));
1866
- function _retrySendComment(_x13) {
1867
- return _retrySendComment2.apply(this, arguments);
1052
+ if (this.selected != null) {
1053
+ this.selected.receiveComments(comments.reverse());
1054
+ this.sortComments();
1868
1055
  }
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;
1896
- });
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
- });
1056
+ return comments;
1057
+ }));
1058
+ }
1059
+ loadMore(lastCommentId, options = {}) {
1060
+ if (this.selected == null) return;
1061
+ options.last_comment_id = lastCommentId;
1062
+ options.after = false;
1063
+ return this.loadComments(this.selected.id, options);
1064
+ }
1065
+ registerDeviceToken(token, isDevelopment = false) {
1066
+ return __async(this, null, function* () {
1067
+ const res = yield this.HTTPAdapter.post(
1068
+ "api/v2/sdk/set_user_device_token",
1069
+ {
1070
+ device_token: token,
1071
+ device_platform: "rn",
1072
+ is_development: isDevelopment
1073
+ }
1074
+ );
1075
+ return res.body.results;
1076
+ });
1077
+ }
1078
+ removeDeviceToken(token, isDevelopment = false) {
1079
+ return __async(this, null, function* () {
1080
+ const res = yield this.HTTPAdapter.post(
1081
+ "api/v2/sdk/remove_user_device_token",
1082
+ {
1083
+ device_token: token,
1084
+ device_platform: "rn",
1085
+ is_development: isDevelopment
1086
+ }
1087
+ );
1088
+ return res.body.results;
1089
+ });
1090
+ }
1091
+ /**
1092
+ *
1093
+ * Search Qiscus Messages
1094
+ *
1095
+ * @param {any} [params={query,room_id,last_comment_id}]
1096
+ * @memberof qiscusSDK
1097
+ */
1098
+ searchMessages() {
1099
+ return __async(this, arguments, function* (params = {}) {
1100
+ console.warn("Deprecated: search message will be removed on next release");
1101
+ const messages = yield this.userAdapter.searchMessages(params);
1102
+ return messages.map((message) => {
1103
+ return new Comment(message);
1934
1104
  });
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'));
1971
- }
1972
- var participants = this.selected.participants;
1973
- if (!participants) {
1974
- return Promise.reject(new Error('Nothing selected room chat.'));
1105
+ });
1106
+ }
1107
+ updateProfile(user2) {
1108
+ return this.userAdapter.updateProfile(user2).then(
1109
+ (res) => {
1110
+ this.events.emit("profile-updated", user2);
1111
+ this.userData = res;
1112
+ return Promise.resolve(res);
1113
+ },
1114
+ (err) => this.logger(err)
1115
+ );
1116
+ }
1117
+ getNonce() {
1118
+ 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(
1119
+ (res) => Promise.resolve(res.body.results),
1120
+ (err) => Promise.reject(err)
1121
+ );
1122
+ }
1123
+ verifyIdentityToken(identityToken) {
1124
+ return request.post(`${this.baseURL}/api/v2/sdk/auth/verify_identity_token`).send({
1125
+ identity_token: identityToken
1126
+ }).set("qiscus_sdk_app_id", `${this.AppId}`).set("qiscus_sdk_version", `${this.version}`).then(
1127
+ (res) => Promise.resolve(res.body.results),
1128
+ (err) => Promise.reject(err)
1129
+ );
1130
+ }
1131
+ /**
1132
+ *
1133
+ * Step of submitting:
1134
+ * - we need to create a new comment object
1135
+ * - attach it with negative number id, and also the uniqueId, uniqueId is used
1136
+ * to target this particular comment when there's response from server (sent, delivered state)
1137
+ * @param {Int} topicId - the topic id of comment to be submitted
1138
+ * @param {String} commentMessage - comment to be submitted
1139
+ * @param uniqueId {String}
1140
+ * @param type {String}
1141
+ * @param payload {Object}
1142
+ * @param extras {Object}
1143
+ * @return {Promise}
1144
+ */
1145
+ // #region sendComment
1146
+ sendComment(topicId, commentMessage, uniqueId, type = "text", payload, extras) {
1147
+ return __async(this, null, function* () {
1148
+ var _a, _b, _c, _d;
1149
+ const self = this;
1150
+ if (self.options.prePostCommentCallback) {
1151
+ self.options.prePostCommentCallback(commentMessage);
1975
1152
  }
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
- });
1153
+ if (self.options.commentFormaterCallback) {
1154
+ commentMessage = self.options.commentFormaterCallback(commentMessage);
1982
1155
  }
1983
- if (payload === 'email') {
1984
- participantsExclude = participants.filter(function (participant) {
1985
- return values.indexOf(participant.email) <= -1;
1986
- });
1156
+ self.pendingCommentId--;
1157
+ const commentData = {
1158
+ room_id: topicId,
1159
+ message: commentMessage,
1160
+ username_as: this.username,
1161
+ username_real: this.user_id,
1162
+ user_avatar_url: this.userData.avatar_url,
1163
+ user_extras: this.userData.user_extras,
1164
+ id: Math.round(Date.now() * 1e6 + Date.now()),
1165
+ type: type || "text",
1166
+ timestamp: format(/* @__PURE__ */ new Date()),
1167
+ unique_id: uniqueId ? String(uniqueId) : null,
1168
+ payload: util.tryCatch(
1169
+ () => JSON.parse(payload),
1170
+ payload,
1171
+ (error) => this.logger("Error when parsing payload", error.message)
1172
+ )
1173
+ };
1174
+ const pendingComment = self.prepareCommentToBeSubmitted(commentData);
1175
+ if (type === "reply") {
1176
+ var parsedPayload = JSON.parse(payload);
1177
+ var repliedMessage = self.selected.comments.find(
1178
+ (cmt) => cmt.id === parsedPayload.replied_comment_id
1179
+ );
1180
+ parsedPayload.replied_comment_message = repliedMessage.type === "reply" ? repliedMessage.payload.text : repliedMessage.message;
1181
+ parsedPayload.replied_comment_sender_username = repliedMessage.username_as;
1182
+ pendingComment.payload = parsedPayload;
1987
1183
  }
1988
- if (payload === 'username') {
1989
- participantsExclude = participants.filter(function (participant) {
1990
- return values.indexOf(participant.username) <= -1;
1991
- });
1184
+ const extrasToBeSubmitted = extras || self.extras;
1185
+ let messageData = yield this._hookAdapter.trigger(
1186
+ hook.Hooks.MESSAGE_BEFORE_SENT,
1187
+ __spreadProps(__spreadValues({}, pendingComment), {
1188
+ extras: extrasToBeSubmitted
1189
+ })
1190
+ );
1191
+ messageData = self.prepareCommentToBeSubmitted(messageData);
1192
+ if (self.selected) self.selected.comments.push(messageData);
1193
+ const sendComment = () => this.userAdapter.postComment(
1194
+ "" + topicId,
1195
+ messageData.message,
1196
+ messageData.unique_id,
1197
+ messageData.type,
1198
+ messageData.payload,
1199
+ messageData.extras
1200
+ );
1201
+ try {
1202
+ let res = yield sendComment();
1203
+ res = yield this._hookAdapter.trigger(
1204
+ hook.Hooks.MESSAGE_BEFORE_RECEIVED,
1205
+ res
1206
+ );
1207
+ Object.assign(messageData, res);
1208
+ if (!self.selected) return Promise.resolve(messageData);
1209
+ messageData.markAsSent();
1210
+ messageData.id = res.id;
1211
+ messageData.before_id = res.comment_before_id;
1212
+ messageData.unix_timestamp = res.unix_timestamp;
1213
+ (_b = (_a = this.options).commentSentCallback) == null ? void 0 : _b.call(_a, { comment: messageData });
1214
+ self.events.emit("comment-sent", messageData);
1215
+ self.sortComments();
1216
+ const commentIndex = self._pendingComments.findIndex((c) => c.unique_id === messageData.unique_id);
1217
+ if (commentIndex > -1) {
1218
+ self._pendingComments.splice(commentIndex, 1);
1219
+ }
1220
+ return messageData;
1221
+ } catch (error) {
1222
+ messageData.markAsFailed();
1223
+ const whitelistedErrorStatus = [void 0, 408, 413, 429, 500, 502, 503, 504, 521, 522, 524];
1224
+ const message = (_d = (_c = error.message) == null ? void 0 : _c.toLowerCase()) != null ? _d : "";
1225
+ const isOffline = message.includes("offline");
1226
+ if (whitelistedErrorStatus.includes(error.status) || isOffline) {
1227
+ this._pendingComments.push(messageData);
1228
+ this.logger("Failed sending comment", error);
1229
+ }
1230
+ return Promise.reject(error);
1992
1231
  }
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");
1232
+ });
1233
+ }
1234
+ _retrySendComment(comment) {
1235
+ return __async(this, null, function* () {
1236
+ var _a, _b, _c;
1237
+ this.logger("Retrying send comment", comment);
1238
+ this._pendingCommentsCount[comment.unique_id] = ((_a = this._pendingCommentsCount[comment.unique_id]) != null ? _a : 0) + 1;
1239
+ if (this._pendingCommentsCount[comment.unique_id] > 10) {
1240
+ this.logger(
1241
+ `Exceeding maximum retry count for comment ${comment.unique_id}, not retrying anymore`
1242
+ );
1243
+ (_c = (_b = this.options).commentRetryExceedCallback) == null ? void 0 : _c.call(_b, comment);
1244
+ const index = this._pendingComments.findIndex((c) => c.unique_id === comment.unique_id);
1245
+ if (index > -1) {
1246
+ this._pendingComments.splice(index, 1);
1247
+ }
1248
+ comment.markAsFailed();
1249
+ this.events.emit("comment-retry-exceed", comment);
1250
+ return Promise.reject(new Error("Exceeding maximum retry count"));
2028
1251
  }
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) {
1252
+ return this.userAdapter.postComment(
1253
+ "" + comment.room_id,
1254
+ comment.message,
1255
+ comment.unique_id,
1256
+ comment.type,
1257
+ comment.payload,
1258
+ comment.extras
1259
+ ).then((res) => __async(this, null, function* () {
1260
+ var _a2, _b2, _c2, _d;
1261
+ if (((_a2 = this.selected) == null ? void 0 : _a2.id) !== comment.room_id) {
1262
+ return res;
1263
+ }
1264
+ Object.assign(comment, res);
1265
+ comment.markAsSent();
1266
+ comment.id = res.id;
1267
+ comment.before_id = res.comment_before_id;
1268
+ comment.unix_timestamp = res.unix_timestamp;
1269
+ const index = (_b2 = this.selected) == null ? void 0 : _b2.comments.findIndex(
1270
+ (c) => c.unique_id === comment.unique_id
1271
+ );
1272
+ if (index > -1) {
1273
+ this.selected.comments[index] = comment;
1274
+ }
1275
+ this.sortComments();
1276
+ (_d = (_c2 = this.options).commentSentCallback) == null ? void 0 : _d.call(_c2, { comment });
1277
+ this.events.emit("comment-sent", comment);
1278
+ const commentIndex = this._pendingComments.findIndex((c) => c.unique_id === comment.unique_id);
1279
+ if (commentIndex > -1) {
1280
+ this._pendingComments.splice(commentIndex, 1);
1281
+ }
1282
+ return comment;
1283
+ })).catch((err) => {
1284
+ comment.markAsFailed();
2033
1285
  return Promise.reject(err);
2034
1286
  });
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'));
1287
+ });
1288
+ }
1289
+ // #endregion
1290
+ getUsers(query = "", page = 1, limit = 20) {
1291
+ return this.HTTPAdapter.get_request("api/v2/sdk/get_user_list").query({
1292
+ query,
1293
+ page,
1294
+ limit
1295
+ }).then((resp) => {
1296
+ return Promise.resolve(resp.body.results);
1297
+ });
1298
+ }
1299
+ getParticipants(roomUniqueId, page = 1, limit = 20) {
1300
+ return this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({
1301
+ room_unique_id: roomUniqueId,
1302
+ page,
1303
+ limit
1304
+ }).then((resp) => resp.body.results);
1305
+ }
1306
+ getRoomParticipants(roomUniqueId, offset = 0) {
1307
+ console.warn(
1308
+ "`getRoomParticipants` are deprecated, use `getParticipants` instead."
1309
+ );
1310
+ return this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({
1311
+ room_unique_id: roomUniqueId,
1312
+ offset
1313
+ }).then((resp) => {
1314
+ return Promise.resolve(resp.body.results);
1315
+ });
1316
+ }
1317
+ resendComment(comment) {
1318
+ if (this.selected == null) return;
1319
+ var self = this;
1320
+ var room2 = self.selected;
1321
+ var pendingComment = room2.comments.find(
1322
+ (cmtToFind) => cmtToFind.id === comment.id
1323
+ );
1324
+ const extrasToBeSubmitted = self.extras;
1325
+ return this.userAdapter.postComment(
1326
+ "" + room2.id,
1327
+ pendingComment.message,
1328
+ pendingComment.unique_id,
1329
+ comment.type,
1330
+ comment.payload,
1331
+ extrasToBeSubmitted
1332
+ ).then(
1333
+ (res) => {
1334
+ pendingComment.markAsSent();
1335
+ pendingComment.id = res.id;
1336
+ pendingComment.before_id = res.comment_before_id;
1337
+ return new Promise((resolve, reject) => resolve(self.selected));
1338
+ },
1339
+ (err) => {
1340
+ pendingComment.markAsFailed();
1341
+ return new Promise((resolve, reject) => reject(err));
2051
1342
  }
2052
- return this.roomAdapter.removeParticipantsFromGroup(roomId, emails).then(function (res) {
2053
- _this13.events.emit('participants-removed', emails);
1343
+ );
1344
+ }
1345
+ prepareCommentToBeSubmitted(comment) {
1346
+ var commentToBeSubmitted, uniqueId;
1347
+ commentToBeSubmitted = new Comment(comment);
1348
+ uniqueId = "bq" + Date.now();
1349
+ if (comment.unique_id) uniqueId = comment.unique_id;
1350
+ commentToBeSubmitted.attachUniqueId(uniqueId);
1351
+ commentToBeSubmitted.markAsPending();
1352
+ commentToBeSubmitted.isDelivered = false;
1353
+ commentToBeSubmitted.isSent = false;
1354
+ commentToBeSubmitted.isRead = false;
1355
+ commentToBeSubmitted.unix_timestamp = Math.round(
1356
+ (/* @__PURE__ */ new Date()).getTime() / 1e3
1357
+ );
1358
+ return commentToBeSubmitted;
1359
+ }
1360
+ /**
1361
+ * Update room
1362
+ * @param {id, room_name, avatar_url, options} args
1363
+ * @return Promise
1364
+ */
1365
+ updateRoom(args) {
1366
+ return this.roomAdapter.updateRoom(args);
1367
+ }
1368
+ removeSelectedRoomParticipants(values = [], payload = "id") {
1369
+ if (is.not.array(values)) {
1370
+ return Promise.reject(new Error("`values` must have type of array"));
1371
+ }
1372
+ const participants = this.selected.participants;
1373
+ if (!participants) {
1374
+ return Promise.reject(new Error("Nothing selected room chat."));
1375
+ }
1376
+ let participantsExclude = participants;
1377
+ if (payload === "id") {
1378
+ participantsExclude = participants.filter(
1379
+ (participant) => values.indexOf(participant.id) <= -1
1380
+ );
1381
+ }
1382
+ if (payload === "email") {
1383
+ participantsExclude = participants.filter(
1384
+ (participant) => values.indexOf(participant.email) <= -1
1385
+ );
1386
+ }
1387
+ if (payload === "username") {
1388
+ participantsExclude = participants.filter(
1389
+ (participant) => values.indexOf(participant.username) <= -1
1390
+ );
1391
+ }
1392
+ this.selected.participants = participantsExclude;
1393
+ return Promise.resolve(participants);
1394
+ }
1395
+ /**
1396
+ * Create group chat room
1397
+ * @param {string} name - Chat room name
1398
+ * @param {string[]} emails - Participant to be invited
1399
+ * @returns {Promise.<Room, Error>} - Room detail
1400
+ */
1401
+ createGroupRoom(name, emails, options) {
1402
+ const self = this;
1403
+ if (!this.isLogin) throw new Error("Please initiate qiscus SDK first");
1404
+ return new utils.GroupChatBuilder(this.roomAdapter).withName(name).withOptions(options).addParticipants(emails).create().then((res) => {
1405
+ self.events.emit("group-room-created", res);
1406
+ return Promise.resolve(res);
1407
+ });
1408
+ }
1409
+ /**
1410
+ * Add array of participant into a group
1411
+ *
1412
+ * @param {any} roomId the room id this file is required for selected room_id to be process
1413
+ * @param {any} emails emails is must be an array
1414
+ * @returns Promise
1415
+ * @memberof QiscusSDK
1416
+ */
1417
+ addParticipantsToGroup(roomId, emails) {
1418
+ const self = this;
1419
+ if (!Array.isArray(emails)) {
1420
+ throw new Error(`emails' must be type of Array`);
1421
+ }
1422
+ return self.roomAdapter.addParticipantsToGroup(roomId, emails).then(
1423
+ (res) => {
1424
+ self.events.emit("participants-added", res);
2054
1425
  return Promise.resolve(res);
2055
- });
1426
+ },
1427
+ (err) => Promise.reject(err)
1428
+ );
1429
+ }
1430
+ /**
1431
+ * Remove array of participant from a group
1432
+ *
1433
+ * @param {any} roomId the room id this file is required for selected room_id to be process
1434
+ * @param {any} emails emails is must be an array
1435
+ * @returns Promise
1436
+ * @memberof QiscusSDK
1437
+ */
1438
+ removeParticipantsFromGroup(roomId, emails) {
1439
+ if (is.not.array(emails)) {
1440
+ return Promise.reject(new Error("`emails` must have type of array"));
2056
1441
  }
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) {
1442
+ return this.roomAdapter.removeParticipantsFromGroup(roomId, emails).then((res) => {
1443
+ this.events.emit("participants-removed", emails);
1444
+ return Promise.resolve(res);
1445
+ });
1446
+ }
1447
+ /**
1448
+ * Get user block list
1449
+ *
1450
+ * @param {any} page the page is optional, default=1
1451
+ * @param {any} limit the limit is optional, default=20
1452
+ * @returns Promise
1453
+ * @memberof QiscusSDK
1454
+ */
1455
+ getBlockedUser(page = 1, limit = 20) {
1456
+ const self = this;
1457
+ return self.userAdapter.getBlockedUser(page, limit).then(
1458
+ (res) => {
2073
1459
  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);
1460
+ },
1461
+ (err) => Promise.reject(err)
1462
+ );
1463
+ }
1464
+ /**
1465
+ * Add user to block list
1466
+ *
1467
+ * @param {any} email the email is required
1468
+ * @returns Promise
1469
+ * @memberof QiscusSDK
1470
+ */
1471
+ blockUser(email) {
1472
+ const self = this;
1473
+ return self.userAdapter.blockUser(email).then(
1474
+ (res) => {
1475
+ self.events.emit("block-user", res);
2092
1476
  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);
1477
+ },
1478
+ (err) => Promise.reject(err)
1479
+ );
1480
+ }
1481
+ /**
1482
+ * Remove user from block list
1483
+ *
1484
+ * @param {any} email the email is required
1485
+ * @returns Promise
1486
+ * @memberof QiscusSDK
1487
+ */
1488
+ unblockUser(email) {
1489
+ const self = this;
1490
+ return self.userAdapter.unblockUser(email).then(
1491
+ (res) => {
1492
+ self.events.emit("unblock-user", res);
2111
1493
  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);
1494
+ },
1495
+ (err) => Promise.reject(err)
1496
+ );
1497
+ }
1498
+ getUserPresences(email = []) {
1499
+ if (is.not.array(email)) {
1500
+ return Promise.reject(new Error("`email` must have type of array"));
1501
+ }
1502
+ const self = this;
1503
+ return self.userAdapter.getUserPresences(email).then(
1504
+ (res) => {
1505
+ self.events.emit("user-status", res);
2126
1506
  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");
1507
+ },
1508
+ (err) => Promise.reject(err)
1509
+ );
1510
+ }
1511
+ upload(file, callback) {
1512
+ let req = request.post(this.uploadURL);
1513
+ req = this.HTTPAdapter.setupHeaders(req);
1514
+ return req.attach("file", file).on("progress", (event) => {
1515
+ if (event.direction === "upload") callback(null, event);
1516
+ }).then((resp) => {
1517
+ const url = resp.body.results.file.url;
1518
+ callback(null, null, resp.body.results.file.url);
1519
+ return Promise.resolve(url);
1520
+ }).catch((error) => {
1521
+ callback(error);
1522
+ return Promise.reject(error);
1523
+ });
1524
+ }
1525
+ /**
1526
+ * Upload a file to qiscus sdk server
1527
+ *
1528
+ * @param {any} roomId the room id this file need to be submitted to
1529
+ * @param {any} file you can get this from event `e.target.files || e.dataTransfer.files`
1530
+ * @returns Promise
1531
+ * @memberof QiscusSDK
1532
+ */
1533
+ uploadFile(roomId, file) {
1534
+ const self = this;
1535
+ var formData = new FormData();
1536
+ formData.append("file", file);
1537
+ var xhr = new XMLHttpRequest();
1538
+ xhr.open("POST", `${self.baseURL}/api/v2/sdk/upload`, true);
1539
+ xhr.setRequestHeader("qiscus_sdk_app_id", `${self.AppId}`);
1540
+ xhr.setRequestHeader("qiscus_sdk_user_id", `${self.user_id}`);
1541
+ xhr.setRequestHeader("qiscus_sdk_token", `${self.userData.token}`);
1542
+ xhr.onload = function() {
1543
+ if (xhr.status === 200) {
1544
+ var url = JSON.parse(xhr.response).results.file.url;
1545
+ self.events.emit("fileupload", url);
1546
+ return self.sendComment(roomId, `[file] ${url} [/file]`);
1547
+ } else {
1548
+ return Promise.reject(xhr);
2219
1549
  }
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
1550
+ };
1551
+ xhr.send(formData);
1552
+ }
1553
+ addUploadedFile(name, roomId) {
1554
+ this.uploadedFiles.push(new FileUploaded(name, roomId));
1555
+ }
1556
+ removeUploadedFile(name, roomId) {
1557
+ const index = this.uploadedFiles.findIndex(
1558
+ (file) => file.name === name && file.roomId === roomId
1559
+ );
1560
+ this.uploadedFiles.splice(index, 1);
1561
+ }
1562
+ publishTyping(val) {
1563
+ this.realtimeAdapter.publishTyping(val);
1564
+ }
1565
+ /**
1566
+ * Params consisted of
1567
+ * @param {room_ids} array of room ids
1568
+ * @param {room_unique_ids} array of of room unique ids
1569
+ * @param {show_participants} show list of participants, default true
1570
+ * @param {show_removed} show removed room, default false
1571
+ * @returns
1572
+ * @memberof QiscusSDK
1573
+ */
1574
+ getRoomsInfo(params) {
1575
+ return this.userAdapter.getRoomsInfo(params);
1576
+ }
1577
+ deleteComment(roomId, commentUniqueIds, isForEveryone, isHard) {
1578
+ if (!Array.isArray(commentUniqueIds)) {
1579
+ throw new Error(`unique ids' must be type of Array`);
1580
+ }
1581
+ return this.userAdapter.deleteComment(roomId, commentUniqueIds, isForEveryone, isHard).then(
1582
+ (res) => {
1583
+ this.events.emit("comment-deleted", {
1584
+ roomId,
1585
+ commentUniqueIds,
1586
+ isForEveryone,
1587
+ isHard
2226
1588
  });
2227
1589
  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
- }
1590
+ },
1591
+ (err) => Promise.reject(err)
1592
+ );
1593
+ }
1594
+ clearRoomsCache() {
1595
+ if (this.selected) {
1596
+ this.room_name_id_map = {
1597
+ [this.selected.name]: this.selected.id
1598
+ };
1599
+ const roomLength = this.rooms.length;
1600
+ let curIndex = this.rooms.findIndex(
1601
+ (room2) => room2.id === this.selected.id
1602
+ );
1603
+ if (!(curIndex + 1 === roomLength)) {
1604
+ this.rooms.splice(curIndex + 1, roomLength - (curIndex + 1));
2255
1605
  }
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');
1606
+ curIndex = this.rooms.findIndex((room2) => room2.id === this.selected.id);
1607
+ if (curIndex > 0 && this.rooms.length > 1) {
1608
+ this.rooms.splice(1, this.rooms.length - 1);
2281
1609
  }
2282
- return this.userAdapter.clearRoomMessages(roomIds);
2283
1610
  }
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
- }
1611
+ }
1612
+ exitChatRoom() {
1613
+ this.realtimeAdapter.unsubscribeTyping();
1614
+ util.tryCatch(
1615
+ () => this.selected.participants.filter((it) => it.email !== this.user_id).map((it) => it.email),
1616
+ null,
1617
+ this.noop,
1618
+ (userIds) => userIds.forEach(
1619
+ (userId) => this.realtimeAdapter.unsubscribeRoomPresence(userId)
1620
+ )
1621
+ );
1622
+ this.selected = null;
1623
+ }
1624
+ clearRoomMessages(roomIds) {
1625
+ if (!Array.isArray(roomIds)) {
1626
+ throw new Error("room_ids must be type of array");
1627
+ }
1628
+ return this.userAdapter.clearRoomMessages(roomIds);
1629
+ }
1630
+ logging(message, params = {}) {
1631
+ if (this.debugMode) {
1632
+ console.log(message, params);
2291
1633
  }
2292
- }, {
2293
- key: "getTotalUnreadCount",
2294
- value: function getTotalUnreadCount() {
2295
- return this.roomAdapter.getTotalUnreadCount().then(function (response) {
1634
+ }
1635
+ getTotalUnreadCount() {
1636
+ return this.roomAdapter.getTotalUnreadCount().then(
1637
+ (response) => {
2296
1638
  return Promise.resolve(response);
2297
- }, function (error) {
1639
+ },
1640
+ (error) => {
2298
1641
  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
- }
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
1642
  }
2378
- return this.updateCommentStatusThrottleDelay || 300;
1643
+ );
1644
+ }
1645
+ getRoomUnreadCount() {
1646
+ return this.roomAdapter.getRoomUnreadCount();
1647
+ }
1648
+ publishEvent(...args) {
1649
+ this.customEventAdapter.publishEvent(...args);
1650
+ }
1651
+ subscribeEvent(...args) {
1652
+ this.customEventAdapter.subscribeEvent(...args);
1653
+ }
1654
+ unsubscribeEvent(...args) {
1655
+ this.customEventAdapter.unsubscribeEvent(...args);
1656
+ }
1657
+ setCustomHeader(headers) {
1658
+ if (is.not.json(headers)) {
1659
+ throw new TypeError("`headers` must have type of object");
2379
1660
  }
2380
- }, {
2381
- key: "_updateStatusEnabled",
2382
- get: function get() {
2383
- return this.updateCommentStatusMode !== QiscusSDK.UpdateCommentStatusMode.disabled;
1661
+ this._customHeader = headers;
1662
+ }
1663
+ getUserProfile() {
1664
+ return this.userAdapter.getProfile();
1665
+ }
1666
+ get Interceptor() {
1667
+ return hook.Hooks;
1668
+ }
1669
+ intercept(interceptor, callback) {
1670
+ return this._hookAdapter.intercept(interceptor, callback);
1671
+ }
1672
+ getThumbnailURL(fileURL) {
1673
+ const reURL = /^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;
1674
+ return fileURL.replace(
1675
+ reURL,
1676
+ (match, g1, g2) => match.replace(g1, "/upload/w_320,h_320,c_limit/").replace(g2, ".png")
1677
+ );
1678
+ }
1679
+ getBlurryThumbnailURL(fileURL) {
1680
+ const reURL = /^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;
1681
+ return fileURL.replace(
1682
+ reURL,
1683
+ (match, g1, g2) => match.replace(g1, "/upload/w_320,h_320,c_limit,e_blur:300/").replace(g2, ".png")
1684
+ );
1685
+ }
1686
+ get logger() {
1687
+ if (this.debugMode) return console.log.bind(console, "Qiscus ->");
1688
+ return this.noop;
1689
+ }
1690
+ noop() {
1691
+ }
1692
+ get _throttleDelay() {
1693
+ if (this.updateCommentStatusMode === _QiscusSDK.UpdateCommentStatusMode.enabled) {
1694
+ return 0;
2384
1695
  }
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();
1696
+ return this.updateCommentStatusThrottleDelay || 300;
1697
+ }
1698
+ get _updateStatusEnabled() {
1699
+ return this.updateCommentStatusMode !== _QiscusSDK.UpdateCommentStatusMode.disabled;
1700
+ }
1701
+ _updateStatus(roomId, commentId1 = null, commentId2 = null) {
1702
+ const isReceiveCommand = commentId2 != null;
1703
+ const isReadCommand = commentId1 != null;
1704
+ this.selected != null && this.selected.id === roomId || false;
1705
+ const isChannel = this.selected != null && this.selected.isChannel || false;
1706
+ const isUpdateStatusDisabled = !this._updateStatusEnabled;
1707
+ const command = (() => {
1708
+ if (isReadCommand) return "read";
1709
+ if (isReceiveCommand) return "receive";
1710
+ })();
1711
+ const isAbleToRunCommand = (() => {
1712
+ if (isChannel) return false;
1713
+ if (isReceiveCommand && isUpdateStatusDisabled) return false;
1714
+ return true;
1715
+ })();
1716
+ if (this.debugMode) {
1717
+ console.group("update-command-status");
1718
+ console.log(
1719
+ "run:",
1720
+ command,
1721
+ `on: roomId(${roomId}) commentId(${commentId1 || commentId2})`
1722
+ );
1723
+ console.log("is able to run command?", isAbleToRunCommand);
1724
+ console.groupEnd();
1725
+ }
1726
+ if (!isAbleToRunCommand) return false;
1727
+ this.userAdapter.updateCommentStatus(roomId, commentId1, commentId2).catch((err) => {
1728
+ });
1729
+ }
1730
+ readComment(roomId, commentId) {
1731
+ if (this.updateCommentStatusMode === _QiscusSDK.UpdateCommentStatusMode.enabled)
1732
+ return this._readComment(roomId, commentId);
1733
+ return this._readCommentT(roomId, commentId);
1734
+ }
1735
+ receiveComment(roomId, commentId) {
1736
+ if (this.updateCommentStatusMode === _QiscusSDK.UpdateCommentStatusMode.enabled)
1737
+ return this._deliverComment(roomId, commentId);
1738
+ return this._deliverCommentT(roomId, commentId);
1739
+ }
1740
+ _throttle(func, getWait) {
1741
+ let isWaiting = false;
1742
+ return (...args) => {
1743
+ let waitTime = getWait();
1744
+ if (!isWaiting) {
1745
+ func(...args);
1746
+ isWaiting = true;
1747
+ setTimeout(() => isWaiting = false, waitTime);
2419
1748
  }
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);
1749
+ };
1750
+ }
1751
+ /**
1752
+ * @typedef {Object} SearchMessageParams
1753
+ * @property {string} query
1754
+ * @property {Array.<number>} roomIds
1755
+ * @property {string} userId
1756
+ * @property {Array.<string>} type
1757
+ * @property {string} roomType
1758
+ * @property {number} page
1759
+ * @property {number} limit
1760
+ */
1761
+ /**
1762
+ *
1763
+ * @param {SearchMessageParams} param0
1764
+ * @returns {Array.<Object>}
1765
+ */
1766
+ searchMessage() {
1767
+ return __async(this, arguments, function* ({
1768
+ query,
1769
+ roomIds = [],
1770
+ userId,
1771
+ type,
1772
+ roomType,
1773
+ page,
1774
+ limit
1775
+ } = {}) {
1776
+ const url = "api/v2/sdk/search";
1777
+ const isValidRoomType = ["group", "single", "channel"].some(
1778
+ (it) => it === roomType
1779
+ );
1780
+ if (roomType != null && !isValidRoomType) {
1781
+ return Promise.reject(
1782
+ "Invalid room type, valid room type are: `group`, `single`, and `channel`"
1783
+ );
2528
1784
  }
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);
1785
+ const room2 = ((roomType2) => {
1786
+ const rType = roomType2 == null ? void 0 : roomType2 === "single" ? "single" : "group";
1787
+ const isPublic = roomType2 == null ? void 0 : roomType2 === "channel" ? true : false;
1788
+ return {
1789
+ type: rType,
1790
+ isPublic
1791
+ };
1792
+ })(roomType);
1793
+ return this.HTTPAdapter.post_json(url, {
1794
+ token: this.token,
1795
+ query,
1796
+ sender: userId,
1797
+ type,
1798
+ room_ids: roomIds.map((it) => String(it)),
1799
+ room_type: room2.type || void 0,
1800
+ is_public: room2.isPublic || void 0,
1801
+ page,
1802
+ limit
1803
+ }).then((res) => res.body);
1804
+ });
1805
+ }
1806
+ /**
1807
+ * @typedef {Object} GetFileListParams
1808
+ * @property {Array.<number>} roomIds
1809
+ * @property {String} fileType
1810
+ * @property {Number} page
1811
+ * @property {Number} limit
1812
+ * @property {String} includeExtensions
1813
+ * @property {String} excludeExtensions
1814
+ * @property {String} userId
1815
+ */
1816
+ /**
1817
+ * @param {GetFileListParams} param0
1818
+ */
1819
+ getFileList() {
1820
+ return __async(this, arguments, function* ({
1821
+ roomIds = [],
1822
+ fileType,
1823
+ page,
1824
+ limit,
1825
+ sender,
1826
+ userId,
1827
+ includeExtensions,
1828
+ excludeExtensions
1829
+ } = {}) {
1830
+ const url = "api/v2/sdk/file_list";
1831
+ if (!this.isLogin)
1832
+ return Promise.reject("You need to login to use this method");
1833
+ if (sender === void 0) {
1834
+ sender = this.user_id;
2604
1835
  }
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);
1836
+ if (userId === void 0) {
1837
+ sender = userId = this.user_id;
2743
1838
  }
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);
1839
+ let opts = {
1840
+ room_ids: roomIds.map((it) => String(it)),
1841
+ file_type: fileType,
1842
+ page,
1843
+ limit,
1844
+ include_extensions: includeExtensions,
1845
+ exclude_extensions: excludeExtensions
2753
1846
  };
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);
1847
+ if (sender != null) opts["sender"] = sender;
1848
+ return this.HTTPAdapter.post_json(url, opts).then((res) => res.body);
1849
+ });
1850
+ }
1851
+ _generateUniqueId() {
1852
+ return `javascript-${Date.now()}`;
1853
+ }
1854
+ generateMessage({ roomId, text, extras }) {
1855
+ const id = Date.now();
1856
+ const comment = new Comment({
1857
+ id,
1858
+ message: text,
1859
+ room_id: roomId,
1860
+ extras,
1861
+ timestamp: /* @__PURE__ */ new Date(),
1862
+ unique_id: this._generateUniqueId(),
1863
+ before_id: 0,
1864
+ username: this.userData.username,
1865
+ email: this.userData.email,
1866
+ status: "pending",
1867
+ type: "text"
1868
+ });
1869
+ return comment;
1870
+ }
1871
+ generateFileAttachmentMessage({
1872
+ roomId,
1873
+ caption,
1874
+ url,
1875
+ text = "File attachment",
1876
+ extras,
1877
+ filename,
1878
+ size
1879
+ }) {
1880
+ const id = Date.now();
1881
+ const comment = new Comment({
1882
+ id,
1883
+ message: text,
1884
+ room_id: roomId,
1885
+ extras,
1886
+ timestamp: /* @__PURE__ */ new Date(),
1887
+ unique_id: this._generateUniqueId(),
1888
+ before_id: 0,
1889
+ username: this.userData.username,
1890
+ email: this.userData.email,
1891
+ status: "pending",
1892
+ type: "file_attachment",
1893
+ payload: {
1894
+ url,
1895
+ file_name: filename,
1896
+ size,
1897
+ caption
2819
1898
  }
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);
1899
+ });
1900
+ return comment;
1901
+ }
1902
+ generateCustomMessage({ roomId, text, type, payload, extras }) {
1903
+ const id = Date.now();
1904
+ const comment = new Comment({
1905
+ id,
1906
+ message: text,
1907
+ room_id: roomId,
1908
+ extras,
1909
+ timestamp: /* @__PURE__ */ new Date(),
1910
+ unique_id: this._generateUniqueId(),
1911
+ before_id: 0,
1912
+ username: this.userData.username,
1913
+ email: this.userData.email,
1914
+ status: "pending",
1915
+ type: "custom",
1916
+ payload: { type, content: payload }
1917
+ });
1918
+ return comment;
1919
+ }
1920
+ generateReplyMessage({ roomId, text, repliedMessage, extras }) {
1921
+ const id = Date.now();
1922
+ const comment = new Comment({
1923
+ id,
1924
+ message: text,
1925
+ room_id: roomId,
1926
+ extras,
1927
+ timestamp: /* @__PURE__ */ new Date(),
1928
+ unique_id: this._generateUniqueId(),
1929
+ before_id: 0,
1930
+ username: this.userData.username,
1931
+ email: this.userData.email,
1932
+ status: "pending",
1933
+ type: "reply",
1934
+ payload: {
1935
+ text,
1936
+ replied_comment_id: repliedMessage.id,
1937
+ replied_comment_message: repliedMessage.message,
1938
+ replied_comment_type: repliedMessage.type,
1939
+ replied_comment_payload: repliedMessage.payload,
1940
+ replied_comment_sender_username: repliedMessage.username_as,
1941
+ replied_comment_sender_email: repliedMessage.username_real
2838
1942
  }
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;
1943
+ });
1944
+ return comment;
1945
+ }
1946
+ updateMessage(message) {
1947
+ return __async(this, null, function* () {
1948
+ return this.userAdapter.updateMessage(message);
1949
+ });
1950
+ }
1951
+ onMessageUpdated(handler) {
1952
+ this.realtimeAdapter.on("message:updated", handler);
1953
+ return () => this.realtimeAdapter.off("message:updated", handler);
1954
+ }
1955
+ /**
1956
+ * Manually close connection to mqtt server
1957
+ * @return {Promise<boolean>} Wheter successfully close mqtt connection or not
1958
+ */
1959
+ closeRealtimeConnection() {
1960
+ return __async(this, null, function* () {
1961
+ return this.realtimeAdapter.closeConnection();
1962
+ });
1963
+ }
1964
+ /**
1965
+ * Manually open connection to mqtt server
1966
+ * @return {Promise<boolean>} Wheter successfully connect to mqtt server or not
1967
+ */
1968
+ openRealtimeConnection() {
1969
+ return __async(this, null, function* () {
1970
+ return this.realtimeAdapter.openConnection();
1971
+ });
1972
+ }
1973
+ startSync() {
1974
+ return __async(this, null, function* () {
1975
+ this._forceEnableSync = true;
1976
+ });
1977
+ }
1978
+ stopSync() {
1979
+ return __async(this, null, function* () {
1980
+ this._forceEnableSync = false;
1981
+ });
1982
+ }
1983
+ };
1984
+ __publicField(_QiscusSDK, "UpdateCommentStatusMode", UpdateCommentStatusMode);
1985
+ __publicField(_QiscusSDK, "Interceptor", hook.Hooks);
1986
+ let QiscusSDK = _QiscusSDK;
1987
+ class FileUploaded {
1988
+ constructor(name, roomId) {
1989
+ this.name = name;
1990
+ this.roomId = roomId;
1991
+ this.progress = 0;
1992
+ }
1993
+ }
1994
+ module.exports = QiscusSDK;