@pontalabs/baileys 1.0.11 → 1.1.0

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 (119) hide show
  1. package/README.md +96 -85
  2. package/lib/Defaults/connection.js +39 -0
  3. package/lib/Defaults/constants.js +50 -0
  4. package/lib/Defaults/history.js +13 -0
  5. package/lib/Defaults/index.js +36 -151
  6. package/lib/Defaults/media.js +43 -0
  7. package/lib/Defaults/phonenumber-mcc.json +221 -221
  8. package/lib/Defaults/prefix.js +12 -0
  9. package/lib/Defaults/vialeys-version.json +7 -0
  10. package/lib/Signal/Group/ciphertext-message.js +10 -15
  11. package/lib/Signal/Group/group-session-builder.js +34 -60
  12. package/lib/Signal/Group/group_cipher.js +69 -76
  13. package/lib/Signal/Group/index.js +41 -60
  14. package/lib/Signal/Group/keyhelper.js +12 -57
  15. package/lib/Signal/Group/sender-chain-key.js +20 -33
  16. package/lib/Signal/Group/sender-key-distribution-message.js +43 -48
  17. package/lib/Signal/Group/sender-key-message.js +58 -53
  18. package/lib/Signal/Group/sender-key-name.js +21 -31
  19. package/lib/Signal/Group/sender-key-record.js +21 -34
  20. package/lib/Signal/Group/sender-key-state.js +59 -106
  21. package/lib/Signal/Group/sender-message-key.js +16 -21
  22. package/lib/Signal/libsignal.js +282 -203
  23. package/lib/Signal/lid-mapping.js +164 -184
  24. package/lib/Socket/Client/index.js +31 -22
  25. package/lib/Socket/Client/types.js +9 -15
  26. package/lib/Socket/Client/websocket.js +42 -37
  27. package/lib/Socket/business.js +212 -336
  28. package/lib/Socket/chats.js +696 -940
  29. package/lib/Socket/community.js +454 -369
  30. package/lib/Socket/groups.js +278 -280
  31. package/lib/Socket/index.js +9 -21
  32. package/lib/Socket/messages-recv.js +1027 -1570
  33. package/lib/Socket/messages-send.js +1180 -1136
  34. package/lib/Socket/mex.js +59 -0
  35. package/lib/Socket/newsletter.js +193 -251
  36. package/lib/Socket/socket.js +758 -898
  37. package/lib/Store/index.js +35 -24
  38. package/lib/Store/make-cache-manager-store.js +53 -66
  39. package/lib/Store/make-in-memory-store.js +319 -325
  40. package/lib/Store/make-ordered-dictionary.js +49 -57
  41. package/lib/Store/object-repository.js +10 -15
  42. package/lib/Types/Auth.js +2 -3
  43. package/lib/Types/Bussines.js +2 -3
  44. package/lib/Types/Call.js +2 -3
  45. package/lib/Types/Chat.js +10 -9
  46. package/lib/Types/Contact.js +2 -3
  47. package/lib/Types/Events.js +2 -3
  48. package/lib/Types/GroupMetadata.js +2 -3
  49. package/lib/Types/Label.js +6 -12
  50. package/lib/Types/LabelAssociation.js +4 -13
  51. package/lib/Types/Message.js +10 -18
  52. package/lib/Types/MexUpdates.js +15 -18
  53. package/lib/Types/Newsletter.js +26 -34
  54. package/lib/Types/Product.js +2 -3
  55. package/lib/Types/Signal.js +2 -3
  56. package/lib/Types/Socket.js +2 -3
  57. package/lib/Types/State.js +8 -13
  58. package/lib/Types/USync.js +2 -3
  59. package/lib/Types/index.js +49 -40
  60. package/lib/Utils/auth-utils.js +190 -495
  61. package/lib/Utils/browser-utils.js +29 -0
  62. package/lib/Utils/business.js +177 -199
  63. package/lib/Utils/chat-utils.js +711 -624
  64. package/lib/Utils/crypto.js +116 -161
  65. package/lib/Utils/decode-wa-message.js +225 -321
  66. package/lib/Utils/event-buffer.js +363 -405
  67. package/lib/Utils/generics.js +318 -472
  68. package/lib/Utils/history.js +72 -76
  69. package/lib/Utils/index.js +49 -41
  70. package/lib/Utils/link-preview.js +59 -103
  71. package/lib/Utils/logger.js +4 -7
  72. package/lib/Utils/lt-hash.js +29 -42
  73. package/lib/Utils/make-mutex.js +26 -42
  74. package/lib/Utils/message-retry-manager.js +134 -160
  75. package/lib/Utils/messages-media.js +665 -731
  76. package/lib/Utils/messages.js +518 -1
  77. package/lib/Utils/noise-handler.js +127 -125
  78. package/lib/Utils/pre-key-manager.js +86 -0
  79. package/lib/Utils/process-message.js +739 -351
  80. package/lib/Utils/signal.js +146 -129
  81. package/lib/Utils/use-multi-file-auth-state.js +68 -135
  82. package/lib/Utils/validate-connection.js +183 -142
  83. package/lib/Utils/vialeys-event-stream.js +41 -0
  84. package/lib/WABinary/constants.js +1281 -1289
  85. package/lib/WABinary/decode.js +145 -200
  86. package/lib/WABinary/encode.js +149 -202
  87. package/lib/WABinary/generic-utils.js +79 -97
  88. package/lib/WABinary/index.js +36 -25
  89. package/lib/WABinary/jid-utils.js +91 -123
  90. package/lib/WABinary/types.js +2 -3
  91. package/lib/WAM/BinaryInfo.js +8 -13
  92. package/lib/WAM/constants.js +16584 -11464
  93. package/lib/WAM/encode.js +117 -133
  94. package/lib/WAM/index.js +34 -23
  95. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -69
  96. package/lib/WAUSync/Protocols/USyncContactProtocol.js +11 -25
  97. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +32 -44
  98. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +13 -23
  99. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -38
  100. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +17 -31
  101. package/lib/WAUSync/Protocols/index.js +37 -26
  102. package/lib/WAUSync/USyncQuery.js +66 -66
  103. package/lib/WAUSync/USyncUser.js +13 -18
  104. package/lib/WAUSync/index.js +34 -23
  105. package/lib/index.js +95 -28
  106. package/package.json +2 -1
  107. package/lib/Defaults/baileys-version.json +0 -3
  108. package/lib/Signal/Group/queue-job.d.ts +0 -1
  109. package/lib/Signal/Group/queue-job.js +0 -57
  110. package/lib/Socket/usync.d.ts +0 -37
  111. package/lib/Socket/usync.js +0 -83
  112. package/lib/Utils/baileys-event-stream.d.ts +0 -18
  113. package/lib/Utils/baileys-event-stream.js +0 -70
  114. package/lib/Utils/signal-housekeeping.d.ts +0 -19
  115. package/lib/Utils/signal-housekeeping.js +0 -73
  116. package/lib/Utils/use-mongo-file-auth-state.d.ts +0 -6
  117. package/lib/Utils/use-mongo-file-auth-state.js +0 -84
  118. package/lib/Utils/use-single-file-auth-state.d.ts +0 -13
  119. package/lib/Utils/use-single-file-auth-state.js +0 -80
@@ -1,429 +1,423 @@
1
- "use strict"
2
-
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod }
5
- }
6
-
7
- Object.defineProperty(exports, "__esModule", { value: true })
8
-
9
- const WAProto_1 = require("../../WAProto")
10
- const Defaults_1 = require("../Defaults")
11
- const LabelAssociation_1 = require("../Types/LabelAssociation")
12
- const Utils_1 = require("../Utils")
13
- const WABinary_1 = require("../WABinary")
14
- const Store_1 = require("./make-ordered-dictionary")
15
- const object_repository_1 = require("./object-repository")
16
-
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { proto: proto } = require("../../WAProto");
4
+ const { DEFAULT_CONNECTION_CONFIG: DEFAULT_CONNECTION_CONFIG } = require("../Defaults/connection");
5
+ const { LabelAssociationType: LabelAssociationType } = require("../Types/LabelAssociation");
6
+ const {
7
+ md5: md5,
8
+ toNumber: toNumber,
9
+ updateMessageWithReceipt: updateMessageWithReceipt,
10
+ updateMessageWithReaction: updateMessageWithReaction,
11
+ } = require("../Utils");
12
+ const { jidDecode: jidDecode, jidNormalizedUser: jidNormalizedUser } = require("../WABinary");
13
+ const { makeOrderedDictionary: makeOrderedDictionary } = require("./make-ordered-dictionary");
14
+ const { ObjectRepository: ObjectRepository } = require("./object-repository");
17
15
  const waChatKey = (pin) => ({
18
- key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
19
- compare: (k1, k2) => k2.localeCompare(k1)
20
- })
21
-
22
- const waMessageID = (m) => m.key.id || ''
23
-
16
+ key: (c) =>
17
+ (pin ? (c.pinned ? "1" : "0") : "") +
18
+ (c.archived ? "0" : "1") +
19
+ (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, "0") : "") +
20
+ c.id,
21
+ compare: (k1, k2) => k2.localeCompare(k1),
22
+ });
23
+ const waMessageID = (m) => m.key.id || "";
24
24
  const waLabelAssociationKey = {
25
- key: (la) => (la.type === LabelAssociation_1.LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
26
- compare: (k1, k2) => k2.localeCompare(k1)
27
- }
28
-
29
- const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
30
-
25
+ key: (la) =>
26
+ la.type === LabelAssociationType.Chat
27
+ ? la.chatId + la.labelId
28
+ : la.chatId + la.messageId + la.labelId,
29
+ compare: (k1, k2) => k2.localeCompare(k1),
30
+ };
31
+ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
31
32
  const makeInMemoryStore = (config) => {
32
- const socket = config.socket
33
- const chatKey = config.chatKey || waChatKey(true)
34
- const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
35
- const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
36
- const KeyedDB = require('@adiwajshing/keyed-db').default
37
- const chats = new KeyedDB(chatKey, c => c.id)
38
- const messages = {}
39
- const contacts = {}
40
- const groupMetadata = {}
41
- const presences = {}
42
- const state = { connection: 'close' }
43
- const labels = new object_repository_1.ObjectRepository()
44
- const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
33
+ const socket = config.socket;
34
+ const chatKey = config.chatKey || waChatKey(true);
35
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
36
+ const logger =
37
+ config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: "in-mem-store" });
38
+ const KeyedDB = require("@adiwajshing/keyed-db").default;
39
+ const chats = new KeyedDB(chatKey, (c) => c.id);
40
+ const messages = {};
41
+ const contacts = {};
42
+ const groupMetadata = {};
43
+ const presences = {};
44
+ const state = { connection: "close" };
45
+ const labels = new ObjectRepository();
46
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
45
47
  const assertMessageList = (jid) => {
46
48
  if (!messages[jid]) {
47
- messages[jid] = makeMessagesDictionary()
49
+ messages[jid] = makeMessagesDictionary();
48
50
  }
49
- return messages[jid]
50
- }
51
+ return messages[jid];
52
+ };
51
53
  const contactsUpsert = (newContacts) => {
52
- const oldContacts = new Set(Object.keys(contacts))
54
+ const oldContacts = new Set(Object.keys(contacts));
53
55
  for (const contact of newContacts) {
54
- oldContacts.delete(contact.id)
55
- contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact)
56
+ oldContacts.delete(contact.id);
57
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
56
58
  }
57
- return oldContacts
58
- }
59
+ return oldContacts;
60
+ };
59
61
  const labelsUpsert = (newLabels) => {
60
62
  for (const label of newLabels) {
61
- labels.upsertById(label.id, label)
63
+ labels.upsertById(label.id, label);
62
64
  }
63
- }
64
- /**
65
- * binds to a BaileysEventEmitter.
66
- * It listens to all events and constructs a state that you can query accurate data from.
67
- * Eg. can use the store to fetch chats, contacts, messages etc.
68
- * @param ev typically the event emitter from the socket connection
69
- */
65
+ };
70
66
  const bind = (ev) => {
71
- ev.on('connection.update', update => {
72
- Object.assign(state, update)
73
- })
74
- ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
75
- if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
76
- return // FOR NOW,
77
- //TODO: HANDLE
78
- }
79
- if (isLatest) {
80
- chats.clear()
81
- for (const id in messages) {
82
- delete messages[id]
67
+ ev.on("connection.update", (update) => {
68
+ Object.assign(state, update);
69
+ });
70
+ ev.on(
71
+ "messaging-history.set",
72
+ ({
73
+ chats: newChats,
74
+ contacts: newContacts,
75
+ messages: newMessages,
76
+ isLatest: isLatest,
77
+ syncType: syncType,
78
+ }) => {
79
+ if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) {
80
+ return;
83
81
  }
84
- }
85
- const chatsAdded = chats.insertIfAbsent(...newChats).length
86
- logger.debug({ chatsAdded }, 'synced chats')
87
- const oldContacts = contactsUpsert(newContacts)
88
- if (isLatest) {
89
- for (const jid of oldContacts) {
90
- delete contacts[jid]
82
+ if (isLatest) {
83
+ chats.clear();
84
+ for (const id in messages) {
85
+ delete messages[id];
86
+ }
91
87
  }
88
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
89
+ logger.debug({ chatsAdded: chatsAdded }, "synced chats");
90
+ const oldContacts = contactsUpsert(newContacts);
91
+ if (isLatest) {
92
+ for (const jid of oldContacts) {
93
+ delete contacts[jid];
94
+ }
95
+ }
96
+ logger.debug(
97
+ {
98
+ deletedContacts: isLatest ? oldContacts.size : 0,
99
+ newContacts: newContacts,
100
+ },
101
+ "synced contacts"
102
+ );
103
+ for (const msg of newMessages) {
104
+ const jid = msg.key.remoteJid;
105
+ const list = assertMessageList(jid);
106
+ list.upsert(msg, "prepend");
107
+ }
108
+ logger.debug({ messages: newMessages.length }, "synced messages");
92
109
  }
93
- logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts')
94
- for (const msg of newMessages) {
95
- const jid = msg.key.remoteJid
96
- const list = assertMessageList(jid)
97
- list.upsert(msg, 'prepend')
98
- }
99
- logger.debug({ messages: newMessages.length }, 'synced messages')
100
- })
101
- ev.on('contacts.upsert', contacts => {
102
- contactsUpsert(contacts)
103
- })
104
- ev.on('contacts.update', async (updates) => {
110
+ );
111
+ ev.on("contacts.upsert", (contacts) => {
112
+ contactsUpsert(contacts);
113
+ });
114
+ ev.on("contacts.update", async (updates) => {
105
115
  for (const update of updates) {
106
- let contact
116
+ let contact;
107
117
  if (contacts[update.id]) {
108
- contact = contacts[update.id]
109
- }
110
- else {
111
- const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
112
- const { user } = WABinary_1.jidDecode(contactId)
113
- return [contactId, (await Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)]
114
- }))
115
- contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''] // find contact by attrs.hash, when user is not saved as a contact
118
+ contact = contacts[update.id];
119
+ } else {
120
+ const contactHashes = await Promise.all(
121
+ Object.keys(contacts).map(async (contactId) => {
122
+ const { user: user } = jidDecode(contactId);
123
+ return [
124
+ contactId,
125
+ (await md5(Buffer.from(user + "WA_ADD_NOTIF", "utf8")))
126
+ .toString("base64")
127
+ .slice(0, 3),
128
+ ];
129
+ })
130
+ );
131
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ""];
116
132
  }
117
133
  if (contact) {
118
- if (update.imgUrl === 'changed') {
119
- contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined
120
- }
121
- else if (update.imgUrl === 'removed') {
122
- delete contact.imgUrl
134
+ if (update.imgUrl === "changed") {
135
+ contact.imgUrl = socket
136
+ ? await socket.profilePictureUrl(contact.id)
137
+ : undefined;
138
+ } else if (update.imgUrl === "removed") {
139
+ delete contact.imgUrl;
123
140
  }
141
+ } else {
142
+ return logger.debug({ update: update }, "got update for non-existant contact");
124
143
  }
125
- else {
126
- return logger.debug({ update }, 'got update for non-existant contact')
127
- }
128
- Object.assign(contacts[contact.id], contact)
144
+ Object.assign(contacts[contact.id], contact);
129
145
  }
130
- })
131
- ev.on('chats.upsert', newChats => {
132
- chats.upsert(...newChats)
133
- })
134
- ev.on('chats.update', updates => {
146
+ });
147
+ ev.on("chats.upsert", (newChats) => {
148
+ chats.upsert(...newChats);
149
+ });
150
+ ev.on("chats.update", (updates) => {
135
151
  for (let update of updates) {
136
- const result = chats.update(update.id, chat => {
152
+ const result = chats.update(update.id, (chat) => {
137
153
  if (update.unreadCount > 0) {
138
- update = { ...update }
139
- update.unreadCount = (chat.unreadCount || 0) + update.unreadCount
154
+ update = { ...update };
155
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
140
156
  }
141
- Object.assign(chat, update)
142
- })
157
+ Object.assign(chat, update);
158
+ });
143
159
  if (!result) {
144
- logger.debug({ update }, 'got update for non-existant chat')
160
+ logger.debug({ update: update }, "got update for non-existant chat");
145
161
  }
146
162
  }
147
- })
148
- ev.on('labels.edit', (label) => {
163
+ });
164
+ ev.on("labels.edit", (label) => {
149
165
  if (label.deleted) {
150
- return labels.deleteById(label.id)
166
+ return labels.deleteById(label.id);
151
167
  }
152
- // WhatsApp can store only up to 20 labels
153
168
  if (labels.count() < 20) {
154
- return labels.upsertById(label.id, label)
169
+ return labels.upsertById(label.id, label);
155
170
  }
156
- logger.error('Labels count exceed')
157
- })
158
- ev.on('labels.association', ({ type, association }) => {
171
+ logger.error("Labels count exceed");
172
+ });
173
+ ev.on("labels.association", ({ type: type, association: association }) => {
159
174
  switch (type) {
160
- case 'add':
161
- labelAssociations.upsert(association)
162
- break
163
- case 'remove':
164
- labelAssociations.delete(association)
165
- break
175
+ case "add":
176
+ labelAssociations.upsert(association);
177
+ break;
178
+ case "remove":
179
+ labelAssociations.delete(association);
180
+ break;
166
181
  default:
167
- console.error(`unknown operation type [${type}]`)
182
+ console.error(`unknown operation type [${type}]`);
168
183
  }
169
- })
170
- ev.on('presence.update', ({ id, presences: update }) => {
171
- presences[id] = presences[id] || {}
172
- Object.assign(presences[id], update)
173
- })
174
- ev.on('chats.delete', deletions => {
184
+ });
185
+ ev.on("presence.update", ({ id: id, presences: update }) => {
186
+ presences[id] = presences[id] || {};
187
+ Object.assign(presences[id], update);
188
+ });
189
+ ev.on("chats.delete", (deletions) => {
175
190
  for (const item of deletions) {
176
191
  if (chats.get(item)) {
177
- chats.deleteById(item)
192
+ chats.deleteById(item);
178
193
  }
179
194
  }
180
- })
181
- ev.on('messages.upsert', ({ messages: newMessages, type }) => {
195
+ });
196
+ ev.on("messages.upsert", ({ messages: newMessages, type: type }) => {
182
197
  switch (type) {
183
- case 'append':
184
- case 'notify':
198
+ case "append":
199
+ case "notify":
185
200
  for (const msg of newMessages) {
186
- const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
187
- const list = assertMessageList(jid)
188
- list.upsert(msg, 'append')
189
- if (type === 'notify' && !chats.get(jid)) {
190
- ev.emit('chats.upsert', [
201
+ const jid = jidNormalizedUser(msg.key.remoteJid);
202
+ const list = assertMessageList(jid);
203
+ list.upsert(msg, "append");
204
+ if (type === "notify" && !chats.get(jid)) {
205
+ ev.emit("chats.upsert", [
191
206
  {
192
207
  id: jid,
193
- conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
194
- unreadCount: 1
195
- }
196
- ])
208
+ conversationTimestamp: toNumber(msg.messageTimestamp),
209
+ unreadCount: 1,
210
+ },
211
+ ]);
197
212
  }
198
213
  }
199
- break
214
+ break;
200
215
  }
201
- })
202
- ev.on('messages.update', updates => {
203
- for (const { update, key } of updates) {
204
- const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid))
216
+ });
217
+ ev.on("messages.update", (updates) => {
218
+ for (const { update: update, key: key } of updates) {
219
+ const list = assertMessageList(jidNormalizedUser(key.remoteJid));
205
220
  if (update?.status) {
206
- const listStatus = list.get(key.id)?.status
221
+ const listStatus = list.get(key.id)?.status;
207
222
  if (listStatus && update?.status <= listStatus) {
208
- logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
209
- delete update.status
210
- logger.debug({ update }, 'new update object')
223
+ logger.debug(
224
+ { update: update, storedStatus: listStatus },
225
+ "status stored newer then update"
226
+ );
227
+ delete update.status;
228
+ logger.debug({ update: update }, "new update object");
211
229
  }
212
230
  }
213
- const result = list.updateAssign(key.id, update)
231
+ const result = list.updateAssign(key.id, update);
214
232
  if (!result) {
215
- logger.debug({ update }, 'got update for non-existent message')
233
+ logger.debug({ update: update }, "got update for non-existent message");
216
234
  }
217
235
  }
218
- })
219
- ev.on('messages.delete', item => {
220
- if ('all' in item) {
221
- const list = messages[item.jid]
222
- list?.clear()
223
- }
224
- else {
225
- const jid = item.keys[0].remoteJid
226
- const list = messages[jid]
236
+ });
237
+ ev.on("messages.delete", (item) => {
238
+ if ("all" in item) {
239
+ const list = messages[item.jid];
240
+ list?.clear();
241
+ } else {
242
+ const jid = item.keys[0].remoteJid;
243
+ const list = messages[jid];
227
244
  if (list) {
228
- const idSet = new Set(item.keys.map(k => k.id))
229
- list.filter(m => !idSet.has(m.key.id))
245
+ const idSet = new Set(item.keys.map((k) => k.id));
246
+ list.filter((m) => !idSet.has(m.key.id));
230
247
  }
231
248
  }
232
- })
233
- ev.on('groups.update', updates => {
249
+ });
250
+ ev.on("groups.update", (updates) => {
234
251
  for (const update of updates) {
235
- const id = update.id
252
+ const id = update.id;
236
253
  if (groupMetadata[id]) {
237
- Object.assign(groupMetadata[id], update)
238
- }
239
- else {
240
- logger.debug({ update }, 'got update for non-existant group metadata')
254
+ Object.assign(groupMetadata[id], update);
255
+ } else {
256
+ logger.debug({ update: update }, "got update for non-existant group metadata");
241
257
  }
242
258
  }
243
- })
244
- ev.on('group-participants.update', ({ id, participants, action }) => {
245
- const metadata = groupMetadata[id]
246
- if (metadata) {
247
- switch (action) {
248
- case 'add':
249
- metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })))
250
- break
251
- case 'demote':
252
- case 'promote':
253
- for (const participant of metadata.participants) {
254
- if (participants.includes(participant.id)) {
255
- participant.isAdmin = action === 'promote'
259
+ });
260
+ ev.on(
261
+ "group-participants.update",
262
+ ({ id: id, participants: participants, action: action }) => {
263
+ const metadata = groupMetadata[id];
264
+ if (metadata) {
265
+ switch (action) {
266
+ case "add":
267
+ metadata.participants.push(
268
+ ...participants.map((id) => ({
269
+ id: id,
270
+ isAdmin: false,
271
+ isSuperAdmin: false,
272
+ }))
273
+ );
274
+ break;
275
+ case "demote":
276
+ case "promote":
277
+ for (const participant of metadata.participants) {
278
+ if (participants.includes(participant.id)) {
279
+ participant.isAdmin = action === "promote";
280
+ }
256
281
  }
257
- }
258
- break
259
- case 'remove':
260
- metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
261
- break
282
+ break;
283
+ case "remove":
284
+ metadata.participants = metadata.participants.filter(
285
+ (p) => !participants.includes(p.id)
286
+ );
287
+ break;
288
+ }
262
289
  }
263
290
  }
264
- })
265
- ev.on('message-receipt.update', updates => {
266
- for (const { key, receipt } of updates) {
267
- const obj = messages[key.remoteJid]
268
- const msg = obj?.get(key.id)
291
+ );
292
+ ev.on("message-receipt.update", (updates) => {
293
+ for (const { key: key, receipt: receipt } of updates) {
294
+ const obj = messages[key.remoteJid];
295
+ const msg = obj?.get(key.id);
269
296
  if (msg) {
270
- Utils_1.updateMessageWithReceipt(msg, receipt)
297
+ updateMessageWithReceipt(msg, receipt);
271
298
  }
272
299
  }
273
- })
274
- ev.on('messages.reaction', (reactions) => {
275
- for (const { key, reaction } of reactions) {
276
- const obj = messages[key.remoteJid]
277
- const msg = obj?.get(key.id)
300
+ });
301
+ ev.on("messages.reaction", (reactions) => {
302
+ for (const { key: key, reaction: reaction } of reactions) {
303
+ const obj = messages[key.remoteJid];
304
+ const msg = obj?.get(key.id);
278
305
  if (msg) {
279
- Utils_1.updateMessageWithReaction(msg, reaction)
306
+ updateMessageWithReaction(msg, reaction);
280
307
  }
281
308
  }
282
- })
283
- }
309
+ });
310
+ };
284
311
  const toJSON = () => ({
285
- chats,
286
- contacts,
287
- messages,
288
- labels,
289
- labelAssociations
290
- })
312
+ chats: chats,
313
+ contacts: contacts,
314
+ messages: messages,
315
+ labels: labels,
316
+ labelAssociations: labelAssociations,
317
+ });
291
318
  const fromJSON = (json) => {
292
- chats.upsert(...json.chats)
293
- labelAssociations.upsert(...json.labelAssociations || [])
294
- contactsUpsert(Object.values(json.contacts))
295
- labelsUpsert(Object.values(json.labels || {}))
319
+ chats.upsert(...json.chats);
320
+ labelAssociations.upsert(...(json.labelAssociations || []));
321
+ contactsUpsert(Object.values(json.contacts));
322
+ labelsUpsert(Object.values(json.labels || {}));
296
323
  for (const jid in json.messages) {
297
- const list = assertMessageList(jid)
324
+ const list = assertMessageList(jid);
298
325
  for (const msg of json.messages[jid]) {
299
- list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append')
326
+ list.upsert(proto.WebMessageInfo.fromObject(msg), "append");
300
327
  }
301
328
  }
302
- }
329
+ };
303
330
  return {
304
- chats,
305
- contacts,
306
- messages,
307
- groupMetadata,
308
- state,
309
- presences,
310
- labels,
311
- labelAssociations,
312
- bind,
313
- /** loads messages from the store, if not found -- uses the legacy connection */
331
+ chats: chats,
332
+ contacts: contacts,
333
+ messages: messages,
334
+ groupMetadata: groupMetadata,
335
+ state: state,
336
+ presences: presences,
337
+ labels: labels,
338
+ labelAssociations: labelAssociations,
339
+ bind: bind,
314
340
  loadMessages: async (jid, count, cursor) => {
315
- const list = assertMessageList(jid)
316
- const mode = !cursor || 'before' in cursor ? 'before' : 'after'
317
- const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
318
- const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
319
- let messages
320
- if (list && mode === 'before' && (!cursorKey || cursorValue)) {
341
+ const list = assertMessageList(jid);
342
+ const mode = !cursor || "before" in cursor ? "before" : "after";
343
+ const cursorKey = !!cursor
344
+ ? "before" in cursor
345
+ ? cursor.before
346
+ : cursor.after
347
+ : undefined;
348
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
349
+ let messages;
350
+ if (list && mode === "before" && (!cursorKey || cursorValue)) {
321
351
  if (cursorValue) {
322
- const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
323
- messages = list.array.slice(0, msgIdx)
324
- }
325
- else {
326
- messages = list.array
352
+ const msgIdx = list.array.findIndex((m) => m.key.id === cursorKey?.id);
353
+ messages = list.array.slice(0, msgIdx);
354
+ } else {
355
+ messages = list.array;
327
356
  }
328
- const diff = count - messages.length
357
+ const diff = count - messages.length;
329
358
  if (diff < 0) {
330
- messages = messages.slice(-count) // get the last X messages
359
+ messages = messages.slice(-count);
331
360
  }
361
+ } else {
362
+ messages = [];
332
363
  }
333
- else {
334
- messages = []
335
- }
336
- return messages
337
- },
338
- /**
339
- * Get all available labels for profile
340
- *
341
- * Keep in mind that the list is formed from predefined tags and tags
342
- * that were "caught" during their editing.
343
- */
344
- getLabels: () => {
345
- return labels
346
- },
347
- /**
348
- * Get labels for chat
349
- *
350
- * @returns Label IDs
351
- **/
352
- getChatLabels: (chatId) => {
353
- return labelAssociations.filter((la) => la.chatId === chatId).all()
364
+ return messages;
354
365
  },
355
- /**
356
- * Get labels for message
357
- *
358
- * @returns Label IDs
359
- **/
366
+ getLabels: () => labels,
367
+ getChatLabels: (chatId) => labelAssociations.filter((la) => la.chatId === chatId).all(),
360
368
  getMessageLabels: (messageId) => {
361
- const associations = labelAssociations
362
- .filter((la) => la.messageId === messageId)
363
- .all()
364
- return associations.map(({ labelId }) => labelId)
369
+ const associations = labelAssociations.filter((la) => la.messageId === messageId).all();
370
+ return associations.map(({ labelId: labelId }) => labelId);
365
371
  },
366
- loadMessage: async (jid, id) => messages[jid]?.get(id),
372
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
367
373
  mostRecentMessage: async (jid) => {
368
- const message = messages[jid]?.array.slice(-1)[0]
369
- return message
374
+ const message = messages[jid]?.array.slice(-1)[0];
375
+ return message;
370
376
  },
371
- fetchImageUrl: async (jid, sock) => {
372
- const contact = contacts[jid]
377
+ fetchImageUrl: async (jid, conn) => {
378
+ const contact = contacts[jid];
373
379
  if (!contact) {
374
- return sock?.profilePictureUrl(jid)
380
+ return conn?.profilePictureUrl(jid);
375
381
  }
376
- if (typeof contact.imgUrl === 'undefined') {
377
- contact.imgUrl = await sock?.profilePictureUrl(jid)
382
+ if (typeof contact.imgUrl === "undefined") {
383
+ contact.imgUrl = await conn?.profilePictureUrl(jid);
378
384
  }
379
- return contact.imgUrl
385
+ return contact.imgUrl;
380
386
  },
381
- fetchGroupMetadata: async (jid, sock) => {
387
+ fetchGroupMetadata: async (jid, conn) => {
382
388
  if (!groupMetadata[jid]) {
383
- const metadata = await sock?.groupMetadata(jid)
389
+ const metadata = await conn?.groupMetadata(jid);
384
390
  if (metadata) {
385
- groupMetadata[jid] = metadata
391
+ groupMetadata[jid] = metadata;
386
392
  }
387
393
  }
388
- return groupMetadata[jid]
394
+ return groupMetadata[jid];
389
395
  },
390
- // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
391
- // if(!groupMetadata[jid]) {
392
- // const metadata = await sock?.getBroadcastListInfo(jid)
393
- // if(metadata) {
394
- // groupMetadata[jid] = metadata
395
- // }
396
- // }
397
- // return groupMetadata[jid]
398
- // },
399
- fetchMessageReceipts: async ({ remoteJid, id }) => {
400
- const list = messages[remoteJid]
401
- const msg = list?.get(id)
402
- return msg?.userReceipt
396
+ fetchMessageReceipts: async ({ remoteJid: remoteJid, id: id }) => {
397
+ const list = messages[remoteJid];
398
+ const msg = list?.get(id);
399
+ return msg?.userReceipt;
403
400
  },
404
- toJSON,
405
- fromJSON,
401
+ toJSON: toJSON,
402
+ fromJSON: fromJSON,
406
403
  writeToFile: (path) => {
407
- // require fs here so that in case "fs" is not available -- the app does not crash
408
- const { writeFileSync } = require('fs')
409
- writeFileSync(path, JSON.stringify(toJSON()))
404
+ const { writeFileSync: writeFileSync } = require("fs");
405
+ writeFileSync(path, JSON.stringify(toJSON()));
410
406
  },
411
407
  readFromFile: (path) => {
412
- // require fs here so that in case "fs" is not available -- the app does not crash
413
- const { readFileSync, existsSync } = require('fs')
408
+ const { readFileSync: readFileSync, existsSync: existsSync } = require("fs");
414
409
  if (existsSync(path)) {
415
- logger.debug({ path }, 'reading from file')
416
- const jsonStr = readFileSync(path, { encoding: 'utf-8' })
417
- const json = JSON.parse(jsonStr)
418
- fromJSON(json)
410
+ logger.debug({ path: path }, "reading from file");
411
+ const jsonStr = readFileSync(path, { encoding: "utf-8" });
412
+ const json = JSON.parse(jsonStr);
413
+ fromJSON(json);
419
414
  }
420
- }
421
- }
422
- }
423
-
415
+ },
416
+ };
417
+ };
424
418
  module.exports = {
425
- waChatKey,
426
- waMessageID,
427
- waLabelAssociationKey,
428
- makeInMemoryStore
429
- }
419
+ waChatKey: waChatKey,
420
+ waMessageID: waMessageID,
421
+ waLabelAssociationKey: waLabelAssociationKey,
422
+ makeInMemoryStore: makeInMemoryStore,
423
+ };