mezon-sdk 2.8.27 → 2.8.29

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.
Files changed (49) hide show
  1. package/dist/cjs/mezon-client/client/MezonClient.d.ts +19 -79
  2. package/dist/cjs/mezon-client/client/MezonClient.js +108 -504
  3. package/dist/cjs/mezon-client/client/MezonClient.js.map +1 -1
  4. package/dist/cjs/mezon-client/client/MezonClientCore.d.ts +65 -0
  5. package/dist/cjs/mezon-client/client/MezonClientCore.js +426 -0
  6. package/dist/cjs/mezon-client/client/MezonClientCore.js.map +1 -0
  7. package/dist/cjs/mezon-client/manager/socket_manager.d.ts +2 -2
  8. package/dist/cjs/mezon-client/manager/socket_manager.js +18 -24
  9. package/dist/cjs/mezon-client/manager/socket_manager.js.map +1 -1
  10. package/dist/cjs/mezon-client/structures/Clan.d.ts +2 -8
  11. package/dist/cjs/mezon-client/structures/Clan.js +1 -6
  12. package/dist/cjs/mezon-client/structures/Clan.js.map +1 -1
  13. package/dist/cjs/mezon-client/structures/TextChannel.js +4 -4
  14. package/dist/cjs/mezon-client/structures/TextChannel.js.map +1 -1
  15. package/dist/cjs/mezon-client/structures/User.d.ts +1 -5
  16. package/dist/cjs/mezon-client/structures/User.js +0 -30
  17. package/dist/cjs/mezon-client/structures/User.js.map +1 -1
  18. package/dist/cjs/rtapi/realtime.d.ts +497 -673
  19. package/dist/cjs/rtapi/realtime.js +134 -107
  20. package/dist/cjs/rtapi/realtime.js.map +1 -1
  21. package/dist/cjs/sqlite/MessageDatabase.d.ts +1 -1
  22. package/dist/cjs/sqlite/MessageDatabase.js +25 -22
  23. package/dist/cjs/sqlite/MessageDatabase.js.map +1 -1
  24. package/dist/esm/mezon-client/client/MezonClient.d.ts +19 -79
  25. package/dist/esm/mezon-client/client/MezonClient.js +110 -532
  26. package/dist/esm/mezon-client/client/MezonClient.js.map +1 -1
  27. package/dist/esm/mezon-client/client/MezonClientCore.d.ts +65 -0
  28. package/dist/esm/mezon-client/client/MezonClientCore.js +449 -0
  29. package/dist/esm/mezon-client/client/MezonClientCore.js.map +1 -0
  30. package/dist/esm/mezon-client/manager/socket_manager.d.ts +2 -2
  31. package/dist/esm/mezon-client/manager/socket_manager.js +15 -21
  32. package/dist/esm/mezon-client/manager/socket_manager.js.map +1 -1
  33. package/dist/esm/mezon-client/structures/Clan.d.ts +2 -8
  34. package/dist/esm/mezon-client/structures/Clan.js +1 -11
  35. package/dist/esm/mezon-client/structures/Clan.js.map +1 -1
  36. package/dist/esm/mezon-client/structures/TextChannel.js +4 -4
  37. package/dist/esm/mezon-client/structures/TextChannel.js.map +1 -1
  38. package/dist/esm/mezon-client/structures/User.d.ts +1 -5
  39. package/dist/esm/mezon-client/structures/User.js +0 -30
  40. package/dist/esm/mezon-client/structures/User.js.map +1 -1
  41. package/dist/esm/rtapi/realtime.d.ts +497 -673
  42. package/dist/esm/rtapi/realtime.js +123 -97
  43. package/dist/esm/rtapi/realtime.js.map +1 -1
  44. package/dist/esm/sqlite/MessageDatabase.d.ts +1 -1
  45. package/dist/esm/sqlite/MessageDatabase.js +24 -21
  46. package/dist/esm/sqlite/MessageDatabase.js.map +1 -1
  47. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  48. package/dist/tsconfig.tsbuildinfo +1 -1
  49. package/package.json +1 -1
@@ -1,472 +1,109 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MezonClient = void 0;
4
- // src/client/MezonClient.ts
5
- const events_1 = require("events");
6
- const CacheManager_1 = require("../utils/CacheManager");
7
- const Clan_1 = require("../structures/Clan");
8
- const TextChannel_1 = require("../structures/TextChannel");
9
- // import { User } from "../structures/User";
10
- const Message_1 = require("../structures/Message");
11
- const api_1 = require("../../api");
12
- const socket_manager_1 = require("../manager/socket_manager");
13
- const session_manager_1 = require("../manager/session_manager");
14
- const event_manager_1 = require("../manager/event_manager");
15
- const web_socket_adapter_pb_1 = require("../../web_socket_adapter_pb");
4
+ const MezonClientCore_1 = require("./MezonClientCore");
16
5
  const constants_1 = require("../../constants");
17
- const helper_1 = require("../../utils/helper");
18
- const channel_manager_1 = require("../manager/channel_manager");
19
6
  const User_1 = require("../structures/User");
20
- const AsyncThrottleQueue_1 = require("../utils/AsyncThrottleQueue");
21
- const MessageDatabase_1 = require("../../sqlite/MessageDatabase");
22
- const mmn_client_js_1 = require("mmn-client-js");
23
- const MAX_TIME_RETRY = 10;
24
- const DEFAULT_HOST = "gw.mezon.ai";
25
- const DEFAULT_PORT = "443";
26
- const DEFAULT_API_KEY = "";
27
- const DEFAULT_SSL = true;
28
- const DEFAULT_TIMEOUT_MS = 7000;
29
- const DEFAULT_MMN_API = "https://dong.mezon.ai/mmn-api/";
30
- const DEFAULT_ZK_API = "https://dong.mezon.ai/zk-api/";
31
- class MezonClient extends events_1.EventEmitter {
7
+ const Clan_1 = require("../structures/Clan");
8
+ class MezonClient extends MezonClientCore_1.MezonClientCore {
32
9
  constructor(config) {
33
- super();
34
- this.messageQueue = new AsyncThrottleQueue_1.AsyncThrottleQueue();
35
- const { botId, token = DEFAULT_API_KEY, host = DEFAULT_HOST, port = DEFAULT_PORT, useSSL = DEFAULT_SSL, timeout = DEFAULT_TIMEOUT_MS, mmnApiUrl = DEFAULT_MMN_API, zkApiUrl = DEFAULT_ZK_API, } = config;
36
- if (!botId)
37
- throw new Error("botId is required");
38
- if (!token)
39
- throw new Error("token is required");
40
- const scheme = useSSL ? "https://" : "http://";
41
- this.token = token;
42
- this.clientId = botId;
43
- this.host = host;
44
- this.port = port;
45
- this.useSSL = useSSL;
46
- this.timeout = timeout;
47
- this.loginBasePath = `${scheme}${host}:${port}`;
48
- this.mmnApiUrl = mmnApiUrl;
49
- this.zkApiUrl = zkApiUrl;
50
- this.messageDB = new MessageDatabase_1.MessageDatabase();
51
- }
52
- get mmnClient() {
53
- if (!this._mmnClient) {
54
- throw new Error("MmnClient not initialized");
55
- }
56
- return this._mmnClient;
57
- }
58
- get zkClient() {
59
- if (!this._zkClient) {
60
- throw new Error("ZkClient not initialized");
61
- }
62
- return this._zkClient;
10
+ super(config);
11
+ this._internalListenersBound = false;
63
12
  }
64
13
  initManager(basePath, sessionApi) {
65
- this.eventManager = new event_manager_1.EventManager();
66
- this.clans = new CacheManager_1.CacheManager(this._fetchClanFromAPI.bind(this));
67
- this.channels = new CacheManager_1.CacheManager(this._fetchChannelFromAPI.bind(this));
68
- this.apiClient = new api_1.MezonApi(this.token, basePath, this.timeout);
69
- this.sessionManager = new session_manager_1.SessionManager(this.apiClient, sessionApi);
70
- this.socketManager = new socket_manager_1.SocketManager(this.host, this.port, this.useSSL, new web_socket_adapter_pb_1.WebSocketAdapterPb(), this.apiClient, this.eventManager, this.messageQueue, this, this.messageDB);
71
- this.channelManager = new channel_manager_1.ChannelManager(this.apiClient, this.socketManager, this.sessionManager);
72
- if (this.mmnApiUrl) {
73
- this._mmnClient = new mmn_client_js_1.MmnClient({
74
- baseUrl: this.mmnApiUrl,
75
- timeout: this.timeout,
76
- });
77
- }
78
- if (this.zkApiUrl) {
79
- this._zkClient = new mmn_client_js_1.ZkClient({
80
- endpoint: this.zkApiUrl,
81
- timeout: this.timeout,
82
- });
83
- }
84
- }
85
- async handleClientLogin() {
86
- var _a;
87
- const tempApiClient = new api_1.MezonApi(this.token, this.loginBasePath, this.timeout);
88
- const tempSessionManager = new session_manager_1.SessionManager(tempApiClient);
89
- let sessionApi = null;
90
- try {
91
- sessionApi = await tempSessionManager.authenticate(this.clientId, this.token);
92
- }
93
- catch (error) {
94
- (_a = this.socketManager) === null || _a === void 0 ? void 0 : _a.closeSocket();
95
- throw new Error("Some thing went wrong, please reset bot!");
96
- }
97
- if (sessionApi === null || sessionApi === void 0 ? void 0 : sessionApi.api_url) {
98
- const { host, port, useSSL } = (0, helper_1.parseUrlToHostAndSSL)(sessionApi.api_url);
99
- this.host = host;
100
- this.port = port || (useSSL ? "443" : "80");
101
- this.useSSL = useSSL;
102
- const scheme = this.useSSL ? "https://" : "http://";
103
- const basePath = `${scheme}${this.host}:${this.port}`;
104
- this.initManager(basePath, sessionApi);
105
- }
106
- const sessionConnected = await this.socketManager.connect(sessionApi);
107
- if (sessionConnected === null || sessionConnected === void 0 ? void 0 : sessionConnected.token) {
108
- await this.socketManager.connectSocket(sessionConnected.token);
109
- await this.channelManager.initAllDmChannels(sessionConnected.token);
110
- }
111
- this.emit("ready");
112
- return JSON.stringify(sessionApi !== null && sessionApi !== void 0 ? sessionApi : {});
113
- }
114
- /** Login bot */
115
- async login() {
116
- var _a;
117
- try {
118
- return await (0, helper_1.waitFor2nTimeout)(() => this.handleClientLogin(), MAX_TIME_RETRY);
119
- }
120
- catch (error) {
121
- (_a = this.socketManager) === null || _a === void 0 ? void 0 : _a.closeSocket();
122
- throw new Error(`Some thing went wrong, please reset bot!. ${error}`);
123
- }
124
- }
125
- /** Create DM channel */
126
- async createDMchannel(userId) {
127
- try {
128
- if (!(0, helper_1.isValidUserId)(userId))
129
- return null;
130
- const socket = this.socketManager.getSocket();
131
- const request = {
132
- clan_id: "",
133
- channel_id: "0",
134
- category_id: "0",
135
- type: constants_1.ChannelType.CHANNEL_TYPE_DM,
136
- user_ids: [userId],
137
- channel_private: 1,
138
- };
139
- try {
140
- const channelDM = await this.apiClient.createChannelDesc(this.sessionManager.getSession().token, request);
141
- if (channelDM) {
142
- await (0, helper_1.sleep)(100);
143
- await socket.joinChat(channelDM.clan_id, channelDM.channel_id, channelDM.type, false);
144
- const clanDm = this.clans.get("0");
145
- if (clanDm) {
146
- const userRaw = {
147
- id: userId,
148
- dmChannelId: channelDM.channel_id,
149
- };
150
- const user = new User_1.User(userRaw, clanDm, this.messageQueue, this.socketManager, this.channelManager);
151
- clanDm.users.set(userId, user);
152
- }
153
- return channelDM;
154
- }
155
- }
156
- catch (error) {
157
- console.log("error createDMchannel", userId, error === null || error === void 0 ? void 0 : error.status);
158
- }
159
- return null;
160
- }
161
- catch (e) {
162
- return null;
163
- }
14
+ super.initManager(basePath, sessionApi);
15
+ this._setupInternalListeners();
164
16
  }
165
- async getEphemeralKeyPair() {
166
- if (!this._mmnClient) {
167
- throw new Error("MmnClient not initialized");
168
- }
169
- return this._mmnClient.generateEphemeralKeyPair();
170
- }
171
- async getAddress(user_id) {
172
- if (!this._mmnClient) {
173
- throw new Error("MmnClient not initialized");
174
- }
175
- return this._mmnClient.getAddressFromUserId(user_id);
176
- }
177
- async getZkProofs(data) {
178
- if (!this._zkClient) {
179
- throw new Error("ZkClient not initialized");
180
- }
181
- const req = {
182
- userId: data.user_id,
183
- jwt: data.jwt,
184
- address: data.address,
185
- ephemeralPublicKey: data.ephemeral_public_key,
186
- };
187
- return this._zkClient.getZkProofs(req);
188
- }
189
- async getCurrentNonce(user_id, tag) {
190
- if (!this._mmnClient) {
191
- throw new Error("MmnClient not initialized");
192
- }
193
- return this._mmnClient.getCurrentNonce(user_id, tag || "pending");
194
- }
195
- async sendToken(tokenEvent) {
196
- var _a, _b, _c, _d, _e;
197
- if (!this._mmnClient) {
198
- throw new Error("MmnClient not initialized");
199
- }
200
- if (!this.keyGen) {
201
- this.keyGen = await this.getEphemeralKeyPair();
202
- }
203
- if (!this.addressMMN) {
204
- this.addressMMN = await this.getAddress(this.clientId);
205
- }
206
- if (!this.zkProofs) {
207
- this.zkProofs = await this.getZkProofs({
208
- user_id: this.clientId,
209
- jwt: (_a = this.sessionManager.getSession()) === null || _a === void 0 ? void 0 : _a.id_token,
210
- address: this.addressMMN,
211
- ephemeral_public_key: this.keyGen.publicKey,
212
- });
213
- }
214
- const sender_id = (_b = tokenEvent === null || tokenEvent === void 0 ? void 0 : tokenEvent.sender_id) !== null && _b !== void 0 ? _b : this.clientId;
215
- const receiver_id = tokenEvent.receiver_id;
216
- const mmn_extra_info = Object.assign(Object.assign({ ExtraAttribute: (_c = tokenEvent === null || tokenEvent === void 0 ? void 0 : tokenEvent.extra_attribute) !== null && _c !== void 0 ? _c : "", UserSenderUsername: (_d = tokenEvent === null || tokenEvent === void 0 ? void 0 : tokenEvent.sender_name) !== null && _d !== void 0 ? _d : "", type: mmn_client_js_1.ETransferType.TransferToken }, ((_e = tokenEvent === null || tokenEvent === void 0 ? void 0 : tokenEvent.mmn_extra_info) !== null && _e !== void 0 ? _e : {})), { UserSenderId: sender_id, UserReceiverId: receiver_id });
217
- const nonce = await this.getCurrentNonce(this.clientId, "pending");
218
- const result = await this._mmnClient.sendTransaction({
219
- sender: sender_id,
220
- recipient: receiver_id,
221
- amount: this._mmnClient.scaleAmountToDecimals(tokenEvent.amount),
222
- nonce: nonce.nonce + 1,
223
- textData: (tokenEvent === null || tokenEvent === void 0 ? void 0 : tokenEvent.note) || "No note",
224
- extraInfo: mmn_extra_info,
225
- publicKey: this.keyGen.publicKey,
226
- privateKey: this.keyGen.privateKey,
227
- zkProof: this.zkProofs.proof,
228
- zkPub: this.zkProofs.public_input,
229
- });
230
- if (!result.ok) {
231
- let errorMsg = result.error;
232
- try {
233
- const parsed = JSON.parse(result.error);
234
- errorMsg = parsed.message || result.error;
235
- }
236
- catch (_) { }
237
- throw new Error(`Transaction failed: ${errorMsg}`);
238
- }
239
- return result;
240
- }
241
- async addQuickMenuAccess(body) {
242
- var _a, _b, _c;
243
- const id = (0, helper_1.generateSnowflakeId)();
244
- const sessionToken = this.sessionManager.getSession();
245
- if (!sessionToken)
246
- return;
247
- const bot_id = this.clientId;
248
- const payload = {
249
- channel_id: "0",
250
- clan_id: (_a = body === null || body === void 0 ? void 0 : body.clan_id) !== null && _a !== void 0 ? _a : "0",
251
- menu_type: (_b = body === null || body === void 0 ? void 0 : body.menu_type) !== null && _b !== void 0 ? _b : 1,
252
- action_msg: body.action_msg,
253
- background: (_c = body === null || body === void 0 ? void 0 : body.background) !== null && _c !== void 0 ? _c : "",
254
- menu_name: body.menu_name,
255
- id,
256
- bot_id,
257
- };
258
- try {
259
- return await this.apiClient.addQuickMenuAccess(sessionToken.token, payload);
260
- }
261
- catch (error) {
262
- throw error;
263
- }
264
- }
265
- async deleteQuickMenuAccess(botId) {
266
- const sessionToken = this.sessionManager.getSession();
267
- if (!sessionToken)
17
+ _setupInternalListeners() {
18
+ if (this._internalListenersBound)
268
19
  return;
269
- const botIdPayload = botId !== null && botId !== void 0 ? botId : this.clientId;
270
- try {
271
- return await this.apiClient.deleteQuickMenuAccess(sessionToken.token, botIdPayload);
272
- }
273
- catch (error) {
274
- throw error;
275
- }
20
+ this._internalListenersBound = true;
21
+ this.on(constants_1.Events.ChannelMessage.toString(), this._onChannelMessageInternal.bind(this));
22
+ this.on(constants_1.Events.ChannelCreated.toString(), this._onChannelCreatedInternal.bind(this));
23
+ this.on(constants_1.Events.ChannelUpdated.toString(), this._onChannelUpdatedInternal.bind(this));
24
+ this.on(constants_1.Events.ChannelDeleted.toString(), this._onChannelDeletedInternal.bind(this));
25
+ this.on(constants_1.Events.UserClanRemoved.toString(), this._onUserClanRemovedInternal.bind(this));
26
+ this.on(constants_1.Events.AddClanUser.toString(), this._onAddClanUserInternal.bind(this));
27
+ this.on(constants_1.Events.UserChannelAdded.toString(), this._onUserChannelAddedInternal.bind(this));
28
+ this.on(constants_1.Events.TokenSend.toString(), this._onTokenSendInternal.bind(this));
29
+ this.on(constants_1.Events.Notifications.toString(), this._onNotificationsInternal.bind(this));
276
30
  }
277
- /** Listen to messages user sends on the channel, thread */
278
- async onChannelMessage(listener) {
279
- this.on(constants_1.Events.ChannelMessage.toString(), async (e) => {
280
- // handle init cache channel, message, user
281
- await this._initChannelMessageCache(e);
282
- await this._initUserClanCache(e);
283
- listener(e);
284
- });
31
+ onChannelMessage(listener) {
32
+ this.on(constants_1.Events.ChannelMessage.toString(), listener);
285
33
  return this;
286
34
  }
287
- /** Listen to channel created */
288
35
  onChannelCreated(listener) {
289
- this.on(constants_1.Events.ChannelCreated.toString(), async (e) => {
290
- this._updateCacheChannel(e);
291
- listener(e);
292
- });
36
+ this.on(constants_1.Events.ChannelCreated.toString(), listener);
293
37
  return this;
294
38
  }
295
- /** Listen to channel updated */
296
39
  onChannelUpdated(listener) {
297
- this.on(constants_1.Events.ChannelUpdated.toString(), async (e) => {
298
- if (e.channel_type === constants_1.ChannelType.CHANNEL_TYPE_THREAD &&
299
- e.status === 1) {
300
- const socket = this.socketManager.getSocket();
301
- await socket.joinChat(e.clan_id, e.channel_id, e.channel_type, false);
302
- }
303
- this._updateCacheChannel(e);
304
- listener(e);
305
- });
40
+ this.on(constants_1.Events.ChannelUpdated.toString(), listener);
306
41
  return this;
307
42
  }
308
- /** Listen to channel deleted */
309
43
  onChannelDeleted(listener) {
310
- this.on(constants_1.Events.ChannelDeleted.toString(), async (e) => {
311
- const clan = this.clans.get(e.clan_id);
312
- if (!clan)
313
- return;
314
- this.channels.delete(e.channel_id);
315
- clan.channels.delete(e.channel_id);
316
- listener(e);
317
- });
44
+ this.on(constants_1.Events.ChannelDeleted.toString(), listener);
318
45
  return this;
319
46
  }
320
- /** Listen to user send token to each other */
321
47
  onTokenSend(listener) {
322
- this.on(constants_1.Events.TokenSend.toString(), async (e) => {
323
- if (e.sender_id === this.clientId) {
324
- const clan = this.clans.get("0");
325
- const receiver = await (clan === null || clan === void 0 ? void 0 : clan.users.fetch(e.receiver_id));
326
- await (receiver === null || receiver === void 0 ? void 0 : receiver.sendDM({
327
- t: `Funds Transferred: ${(+e.amount).toLocaleString()}₫ | ${e.note}`,
328
- }, constants_1.TypeMessage.SendToken));
329
- }
330
- listener(e);
331
- });
48
+ this.on(constants_1.Events.TokenSend.toString(), listener);
332
49
  return this;
333
50
  }
334
- /** Listen to user react to messages on the channel, thread */
335
51
  onMessageReaction(listener) {
336
52
  this.on(constants_1.Events.MessageReaction.toString(), listener);
337
53
  return this;
338
54
  }
339
- /** Listen to user react to messages on the channel, thread */
340
55
  onUserChannelRemoved(listener) {
341
56
  this.on(constants_1.Events.UserChannelRemoved.toString(), listener);
342
57
  return this;
343
58
  }
344
- /** Listen to user leaved/removed in the channel */
345
59
  onUserClanRemoved(listener) {
346
- this.on(constants_1.Events.UserClanRemoved.toString(), async (e) => {
347
- const clan = this.clans.get(e.clan_id);
348
- if (!clan)
349
- return;
350
- e.user_ids.forEach((user_id) => {
351
- clan.users.delete(user_id);
352
- });
353
- listener(e);
354
- });
60
+ this.on(constants_1.Events.UserClanRemoved.toString(), listener);
355
61
  return this;
356
62
  }
357
- /** Listen to user added in the channel */
358
63
  onUserChannelAdded(listener) {
359
- this.on(constants_1.Events.UserChannelAdded.toString(), async (e) => {
360
- var _a;
361
- const socket = this.socketManager.getSocket();
362
- if ((_a = e === null || e === void 0 ? void 0 : e.users) === null || _a === void 0 ? void 0 : _a.some((user) => user.user_id == this.clientId)) {
363
- await socket.joinChat(e.clan_id, e.channel_desc.channel_id, e.channel_desc.type, !e.channel_desc.channel_private);
364
- }
365
- listener(e);
366
- });
64
+ this.on(constants_1.Events.UserChannelAdded.toString(), listener);
367
65
  return this;
368
66
  }
369
- /** Listen to users give coffee to each other */
370
67
  onGiveCoffee(listener) {
371
68
  this.on(constants_1.Events.GiveCoffee.toString(), listener);
372
69
  return this;
373
70
  }
374
- /** Listen to clan create new role */
375
71
  onRoleEvent(listener) {
376
72
  this.on(constants_1.Events.RoleEvent.toString(), listener);
377
73
  return this;
378
74
  }
379
- /** Listen to assigning a role to user */
380
75
  onRoleAssign(listener) {
381
76
  this.on(constants_1.Events.RoleAssign.toString(), listener);
382
77
  return this;
383
78
  }
384
79
  onNotification(listener) {
385
- this.on(constants_1.Events.Notifications.toString(), async (e) => {
386
- const notifications = e.notifications;
387
- if (notifications && notifications.length) {
388
- notifications.forEach(async (noti) => {
389
- var _a;
390
- const content = JSON.parse((_a = noti === null || noti === void 0 ? void 0 : noti.content) !== null && _a !== void 0 ? _a : {});
391
- if (noti.code === -2) {
392
- const session = this.sessionManager.getSession();
393
- await this.apiClient.requestFriend(session.token, content.username, noti.sender_id);
394
- }
395
- });
396
- }
397
- listener(e);
398
- });
80
+ this.on(constants_1.Events.Notifications.toString(), listener);
399
81
  return this;
400
82
  }
401
- /** Listen to user added in CLAN */
402
83
  onAddClanUser(listener) {
403
- this.on(constants_1.Events.AddClanUser.toString(), async (e) => {
404
- var _a;
405
- if (e.user.user_id === this.clientId) {
406
- this.socketManager.getSocket().joinClanChat(e.clan_id);
407
- const clan = this.clans.get(e.clan_id);
408
- if (!clan) {
409
- const clanObj = new Clan_1.Clan({
410
- id: e.clan_id,
411
- name: "unknown",
412
- welcome_channel_id: "",
413
- clan_name: "",
414
- }, this, this.apiClient, this.socketManager, (_a = this.sessionManager.getSession()) === null || _a === void 0 ? void 0 : _a.token, this.messageQueue, this.messageDB);
415
- await clanObj.loadChannels();
416
- this.clans.set(e.clan_id, clanObj);
417
- }
418
- }
419
- else {
420
- const userRaw = {
421
- id: e.user.user_id,
422
- username: e.user.username,
423
- clan_nick: "",
424
- clan_avatar: "",
425
- avartar: e.user.avatar,
426
- display_name: e.user.display_name,
427
- dmChannelId: "",
428
- };
429
- const clan = this.clans.get(e.clan_id);
430
- if (clan) {
431
- const user = new User_1.User(userRaw, clan, this.messageQueue, this.socketManager, this.channelManager);
432
- clan.users.set(e.user.user_id, user);
433
- }
434
- const clanDm = this.clans.get("0");
435
- if (clanDm) {
436
- const user = new User_1.User(userRaw, clanDm, this.messageQueue, this.socketManager, this.channelManager);
437
- clanDm.users.set(e.user.user_id, user);
438
- }
439
- }
440
- listener(e);
441
- });
84
+ this.on(constants_1.Events.AddClanUser.toString(), listener);
442
85
  return this;
443
86
  }
444
- /** Listen to clan create a new event */
445
87
  onClanEventCreated(listener) {
446
88
  this.on(constants_1.Events.ClanEventCreated.toString(), listener);
447
89
  return this;
448
90
  }
449
- /** Listen to user lick a button on embed message */
450
91
  onMessageButtonClicked(listener) {
451
92
  this.on(constants_1.Events.MessageButtonClicked.toString(), listener);
452
93
  return this;
453
94
  }
454
- /** Listen to user joined a stream room */
455
95
  onStreamingJoinedEvent(listener) {
456
96
  this.on(constants_1.Events.StreamingJoinedEvent.toString(), listener);
457
97
  return this;
458
98
  }
459
- /** Listen to user leaved a stream room */
460
99
  onStreamingLeavedEvent(listener) {
461
100
  this.on(constants_1.Events.StreamingLeavedEvent.toString(), listener);
462
101
  return this;
463
102
  }
464
- /** Listen to user selected a input dropdown */
465
103
  onDropdownBoxSelected(listener) {
466
104
  this.on(constants_1.Events.DropdownBoxSelected.toString(), listener);
467
105
  return this;
468
106
  }
469
- /** Listen to user accepted call 1-1 */
470
107
  onWebrtcSignalingFwd(listener) {
471
108
  this.on(constants_1.Events.WebrtcSignalingFwd.toString(), listener);
472
109
  return this;
@@ -491,135 +128,102 @@ class MezonClient extends events_1.EventEmitter {
491
128
  this.on(constants_1.Events.QuickMenu.toString(), listener);
492
129
  return this;
493
130
  }
494
- closeSocket() {
495
- this.socketManager.closeSocket();
496
- this.eventManager = new event_manager_1.EventManager(); // Reset event manager
131
+ async _onChannelMessageInternal(e) {
132
+ await this._initChannelMessageCache(e);
133
+ await this._initUserClanCache(e);
497
134
  }
498
- getListFriends(limit, state, cursor) {
499
- const session = this.sessionManager.getSession();
500
- return this.apiClient.getListFriends(session.token, limit, state, cursor);
135
+ async _onChannelCreatedInternal(e) {
136
+ this._updateCacheChannel(e);
501
137
  }
502
- acceptFriend(userId, username) {
503
- const session = this.sessionManager.getSession();
504
- return this.apiClient.requestFriend(session.token, username, userId);
138
+ async _onChannelUpdatedInternal(e) {
139
+ if (e.channel_type === constants_1.ChannelType.CHANNEL_TYPE_THREAD && e.status === 1) {
140
+ const socket = this.socketManager.getSocket();
141
+ await socket.joinChat(e.clan_id, e.channel_id, e.channel_type, false);
142
+ }
143
+ this._updateCacheChannel(e);
505
144
  }
506
- addFriend(username) {
507
- const session = this.sessionManager.getSession();
508
- return this.apiClient.requestFriend(session.token, username);
145
+ async _onChannelDeletedInternal(e) {
146
+ const clan = this.clans.get(e.clan_id);
147
+ if (!clan)
148
+ return;
149
+ this.channels.delete(e.channel_id);
150
+ clan.channels.delete(e.channel_id);
509
151
  }
510
- async _fetchClanFromAPI(id) {
511
- throw Error(`Can not find clan ${id}!`);
152
+ async _onUserClanRemovedInternal(e) {
153
+ const clan = this.clans.get(e.clan_id);
154
+ if (!clan)
155
+ return;
156
+ e.user_ids.forEach((user_id) => {
157
+ clan.users.delete(user_id);
158
+ });
512
159
  }
513
- async _fetchChannelFromAPI(id) {
160
+ async _onAddClanUserInternal(e) {
514
161
  var _a;
515
- try {
516
- const session = this.sessionManager.getSession();
517
- const channelDetail = await this.apiClient.listChannelDetail(session.token, id);
518
- const clanId = (_a = channelDetail === null || channelDetail === void 0 ? void 0 : channelDetail.clan_id) !== null && _a !== void 0 ? _a : "0";
519
- const clan = this.clans.get(clanId);
520
- const channel = new TextChannel_1.TextChannel(channelDetail, clan, this.socketManager, this.messageQueue, this.messageDB);
521
- this.channels.set(channel.id, channel);
522
- clan === null || clan === void 0 ? void 0 : clan.channels.set(channel.id, channel);
523
- return channel;
524
- }
525
- catch (error) {
526
- throw Error(`Can not find channel ${id}!`);
527
- }
528
- }
529
- async _initChannelMessageCache(e) {
530
- const { clan_id, channel_id, sender_id, message_id, content, reactions, mentions, attachments, references, create_time_seconds, topic_id, } = e;
531
- try {
532
- if (clan_id && clan_id !== "0") {
533
- const clan = this.clans.get(clan_id);
534
- if (clan) {
535
- try {
536
- await clan.loadChannels();
537
- }
538
- catch (err) {
539
- console.warn("Failed to load channels", err);
540
- }
541
- }
162
+ if (e.user.user_id === this.clientId) {
163
+ this.socketManager.getSocket().joinClanChat(e.clan_id);
164
+ const clan = this.clans.get(e.clan_id);
165
+ if (!clan) {
166
+ const clanObj = new Clan_1.Clan({
167
+ id: e.clan_id,
168
+ name: "unknown",
169
+ welcome_channel_id: "",
170
+ clan_name: "",
171
+ }, this, this.apiClient, this.socketManager, (_a = this.sessionManager.getSession()) === null || _a === void 0 ? void 0 : _a.token, this.messageQueue, this.messageDB);
172
+ await clanObj.loadChannels();
173
+ this.clans.set(e.clan_id, clanObj);
542
174
  }
543
- const channel = await this.channels.fetch(channel_id).catch((err) => {
544
- console.warn("Fetch channel failed", err);
545
- return null;
546
- });
547
- if (!message_id || !channel)
548
- return;
549
- const messageRaw = {
550
- id: message_id,
551
- clan_id: clan_id,
552
- channel_id: channel_id,
553
- sender_id: sender_id,
554
- content,
555
- reactions,
556
- mentions,
557
- attachments,
558
- references,
559
- create_time_seconds,
560
- topic_id,
175
+ }
176
+ else {
177
+ const userRaw = {
178
+ id: e.user.user_id,
179
+ username: e.user.username,
180
+ clan_nick: "",
181
+ clan_avatar: "",
182
+ avartar: e.user.avatar,
183
+ display_name: e.user.display_name,
184
+ dmChannelId: "",
561
185
  };
562
- const message = new Message_1.Message(messageRaw, channel, this.socketManager, this.messageQueue);
563
- channel.messages.set(message_id, message);
564
- try {
565
- this.messageDB.saveMessage(e);
186
+ const clan = this.clans.get(e.clan_id);
187
+ if (clan) {
188
+ const user = new User_1.User(userRaw, clan, this.messageQueue, this.socketManager, this.channelManager);
189
+ clan.users.set(e.user.user_id, user);
566
190
  }
567
- catch (err) {
568
- console.warn("Failed to save message", err);
191
+ const clanDm = this.clans.get("0");
192
+ if (clanDm) {
193
+ const user = new User_1.User(userRaw, clanDm, this.messageQueue, this.socketManager, this.channelManager);
194
+ clanDm.users.set(e.user.user_id, user);
569
195
  }
570
196
  }
571
- catch (error) {
572
- console.log("Error initChannelMessageCache");
197
+ }
198
+ async _onUserChannelAddedInternal(e) {
199
+ var _a;
200
+ const socket = this.socketManager.getSocket();
201
+ if ((_a = e === null || e === void 0 ? void 0 : e.users) === null || _a === void 0 ? void 0 : _a.some((user) => user.user_id == this.clientId)) {
202
+ await socket.joinChat(e.clan_id, e.channel_desc.channel_id, e.channel_desc.type, !e.channel_desc.channel_private);
203
+ }
204
+ }
205
+ async _onTokenSendInternal(e) {
206
+ if (e.sender_id === this.clientId) {
207
+ const clan = this.clans.get("0");
208
+ const receiver = await (clan === null || clan === void 0 ? void 0 : clan.users.fetch(e.receiver_id));
209
+ await (receiver === null || receiver === void 0 ? void 0 : receiver.sendDM({
210
+ t: `Funds Transferred: ${(+e.amount).toLocaleString()}₫ | ${e.note || "Transfer funds"}`,
211
+ }, constants_1.TypeMessage.SendToken));
573
212
  }
574
213
  }
575
- async _initUserClanCache(e) {
214
+ async _onNotificationsInternal(e) {
576
215
  var _a;
577
- const { clan_id, sender_id, username, clan_nick, clan_avatar, avatar, display_name, } = e;
578
- const clan = this.clans.get(clan_id !== null && clan_id !== void 0 ? clan_id : "0");
579
- if (clan) {
580
- const userCache = clan.users.get(sender_id);
581
- const clanDm = this.clans.get("0");
582
- const allDmChannels = this.channelManager.getAllDmChannels();
583
- if (!userCache && sender_id !== this.clientId && allDmChannels) {
584
- const userIds = Object.keys(allDmChannels !== null && allDmChannels !== void 0 ? allDmChannels : {}) || [];
585
- userIds.forEach((id) => {
586
- var _a, _b, _c;
587
- if (!id)
588
- return;
589
- const user = new User_1.User({ id, dmChannelId: (_a = allDmChannels === null || allDmChannels === void 0 ? void 0 : allDmChannels[id]) !== null && _a !== void 0 ? _a : "" }, clan, this.messageQueue, this.socketManager, this.channelManager);
590
- const userDM = (_b = clanDm === null || clanDm === void 0 ? void 0 : clanDm.users) === null || _b === void 0 ? void 0 : _b.get(id);
591
- if (!userDM) {
592
- (_c = clanDm === null || clanDm === void 0 ? void 0 : clanDm.users) === null || _c === void 0 ? void 0 : _c.set(id, user);
593
- }
594
- const userClan = clan.users.get(id);
595
- if (!userClan) {
596
- clan.users.set(id, user);
597
- }
598
- });
216
+ const notifications = e.notifications;
217
+ if (notifications && notifications.length) {
218
+ for (const noti of notifications) {
219
+ const content = JSON.parse((_a = noti === null || noti === void 0 ? void 0 : noti.content) !== null && _a !== void 0 ? _a : "{}");
220
+ if (noti.code === -2) {
221
+ const session = this.sessionManager.getSession();
222
+ await this.apiClient.requestFriend(session.token, content.username, noti.sender_id);
223
+ }
599
224
  }
600
- const userRaw = {
601
- id: sender_id,
602
- username: username,
603
- clan_nick: clan_nick,
604
- clan_avatar: clan_avatar,
605
- avartar: avatar,
606
- display_name: display_name,
607
- dmChannelId: (_a = allDmChannels === null || allDmChannels === void 0 ? void 0 : allDmChannels[sender_id]) !== null && _a !== void 0 ? _a : "",
608
- };
609
- const user = new User_1.User(userRaw, clan, this.messageQueue, this.socketManager, this.channelManager);
610
- clan.users.set(sender_id, user);
611
- clanDm === null || clanDm === void 0 ? void 0 : clanDm.users.set(sender_id, user);
612
225
  }
613
226
  }
614
- _updateCacheChannel(e) {
615
- const clan = this.clans.get(e.clan_id);
616
- if (!clan)
617
- return;
618
- const channelObj = new TextChannel_1.TextChannel(Object.assign(Object.assign({}, e), { type: e.channel_type, channel_private: e.channel_private ? 1 : 0 }), clan, this.socketManager, this.messageQueue, this.messageDB);
619
- this.channels.set(e.channel_id, channelObj);
620
- clan.channels.set(e.channel_id, channelObj);
621
- this.socketManager.getSocket().joinChat;
622
- }
623
227
  }
624
228
  exports.MezonClient = MezonClient;
625
229
  //# sourceMappingURL=MezonClient.js.map