mezon-sdk 2.8.28 → 2.8.30

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