@badzz88/baileys 8.4.7 → 8.4.9

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 (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +347 -6
  4. package/WAProto/fix-import.js +38 -0
  5. package/WAProto/fix-imports.js +86 -85
  6. package/WAProto/index.d.ts +4913 -25
  7. package/WAProto/index.js +14074 -98
  8. package/package.json +50 -90
  9. package/src/Defaults/index.js +201 -0
  10. package/src/Defaults/phonenumber-mcc.json +223 -0
  11. package/src/Signal/Group/ciphertext-message.js +15 -0
  12. package/src/Signal/Group/group-session-builder.js +92 -0
  13. package/src/Signal/Group/group_cipher.js +89 -0
  14. package/src/Signal/Group/index.js +136 -0
  15. package/src/Signal/Group/keyhelper.js +73 -0
  16. package/src/Signal/Group/sender-chain-key.js +32 -0
  17. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/src/Signal/Group/sender-key-message.js +69 -0
  19. package/src/Signal/Group/sender-key-name.js +50 -0
  20. package/src/Signal/Group/sender-key-record.js +44 -0
  21. package/src/Signal/Group/sender-key-state.js +97 -0
  22. package/src/Signal/Group/sender-message-key.js +30 -0
  23. package/src/Signal/libsignal.js +470 -0
  24. package/src/Signal/lid-mapping.js +262 -0
  25. package/src/Socket/Client/index.js +30 -0
  26. package/src/Socket/Client/types.js +13 -0
  27. package/src/Socket/Client/websocket.js +62 -0
  28. package/src/Socket/aigroups.js +240 -0
  29. package/src/Socket/business.js +422 -0
  30. package/src/Socket/chats.js +2374 -0
  31. package/src/Socket/communities.js +580 -0
  32. package/src/Socket/graphql.js +915 -0
  33. package/src/Socket/groups.js +812 -0
  34. package/src/Socket/index.js +37 -0
  35. package/src/Socket/interactive-handler.js +579 -0
  36. package/src/Socket/interop.js +566 -0
  37. package/src/Socket/managed-account.js +214 -0
  38. package/src/Socket/messages-recv.js +3012 -0
  39. package/src/Socket/messages-send.js +2163 -0
  40. package/{lib → src}/Socket/mex.js +11 -5
  41. package/src/Socket/newsletter.js +1057 -0
  42. package/src/Socket/privacy.js +452 -0
  43. package/src/Socket/registration.js +434 -0
  44. package/src/Socket/socket.js +1079 -0
  45. package/src/Socket/text-router.js +67 -0
  46. package/src/Socket/username.js +234 -0
  47. package/src/Store/index.js +36 -0
  48. package/src/Store/make-cache-manager-store.js +90 -0
  49. package/src/Store/make-in-memory-store.js +506 -0
  50. package/src/Store/make-ordered-dictionary.js +81 -0
  51. package/src/Store/object-repository.js +29 -0
  52. package/src/Types/Auth.js +38 -0
  53. package/src/Types/Bussines.js +2 -0
  54. package/src/Types/Call.js +2 -0
  55. package/src/Types/Chat.js +4 -0
  56. package/src/Types/Contact.js +2 -0
  57. package/src/Types/Events.js +2 -0
  58. package/src/Types/GroupMetadata.js +2 -0
  59. package/src/Types/Label.js +27 -0
  60. package/src/Types/LabelAssociation.js +9 -0
  61. package/src/Types/Message.js +95 -0
  62. package/src/Types/Newsletter.js +152 -0
  63. package/src/Types/Product.js +2 -0
  64. package/src/Types/Signal.js +2 -0
  65. package/src/Types/Socket.js +2 -0
  66. package/src/Types/State.js +70 -0
  67. package/src/Types/USync.js +2 -0
  68. package/src/Types/index.js +54 -0
  69. package/src/Utils/auth-utils.js +306 -0
  70. package/src/Utils/browser-utils.js +114 -0
  71. package/src/Utils/business.js +247 -0
  72. package/src/Utils/chat-utils.js +1272 -0
  73. package/src/Utils/consumer-application.js +107 -0
  74. package/src/Utils/crypto.js +125 -0
  75. package/src/Utils/decode-wa-message.js +808 -0
  76. package/src/Utils/event-buffer.js +586 -0
  77. package/src/Utils/generics.js +640 -0
  78. package/src/Utils/group-history.js +60 -0
  79. package/src/Utils/history.js +244 -0
  80. package/src/Utils/identity-change-handler.js +52 -0
  81. package/src/Utils/index.js +53 -0
  82. package/src/Utils/jid-display-normalization.js +218 -0
  83. package/src/Utils/link-preview.js +143 -0
  84. package/src/Utils/logger.js +9 -0
  85. package/src/Utils/lt-hash.js +10 -0
  86. package/src/Utils/make-mutex.js +36 -0
  87. package/src/Utils/message-composer.js +479 -0
  88. package/src/Utils/message-inspect.js +400 -0
  89. package/src/Utils/message-retry-manager.js +231 -0
  90. package/src/Utils/messages-media.js +943 -0
  91. package/src/Utils/messages.js +2490 -0
  92. package/src/Utils/meta-ai-msmsg.js +133 -0
  93. package/src/Utils/noise-handler.js +194 -0
  94. package/src/Utils/offline-node-processor.js +42 -0
  95. package/src/Utils/pre-key-manager.js +107 -0
  96. package/src/Utils/process-message.js +1047 -0
  97. package/src/Utils/reporting-utils.js +262 -0
  98. package/src/Utils/signal.js +192 -0
  99. package/src/Utils/stanza-ack.js +74 -0
  100. package/src/Utils/sync-action-utils.js +54 -0
  101. package/src/Utils/tc-token-utils.js +161 -0
  102. package/src/Utils/use-multi-file-auth-state.js +121 -0
  103. package/src/Utils/validate-connection.js +248 -0
  104. package/src/Utils/voip-rekey.js +22 -0
  105. package/src/WABinary/constants.js +1304 -0
  106. package/src/WABinary/decode.js +377 -0
  107. package/src/WABinary/encode.js +58 -0
  108. package/src/WABinary/generic-utils.js +148 -0
  109. package/src/WABinary/index.js +33 -0
  110. package/src/WABinary/jid-utils.js +374 -0
  111. package/src/WABinary/types.js +2 -0
  112. package/src/WAM/BinaryInfo.js +13 -0
  113. package/src/WAM/constants.js +39486 -0
  114. package/src/WAM/encode.js +142 -0
  115. package/src/WAM/index.js +31 -0
  116. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  117. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  118. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  119. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  120. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  121. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  122. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  123. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  124. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  125. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  126. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  127. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  128. package/src/WAUSync/Protocols/index.js +40 -0
  129. package/src/WAUSync/USyncBackoff.js +31 -0
  130. package/src/WAUSync/USyncQuery.js +204 -0
  131. package/src/WAUSync/USyncUser.js +58 -0
  132. package/src/WAUSync/index.js +32 -0
  133. package/src/antiban.js +4726 -0
  134. package/{lib → src}/index.js +48 -15
  135. package/lib/Defaults/index.js +0 -130
  136. package/lib/Signal/Group/ciphertext-message.js +0 -12
  137. package/lib/Signal/Group/group-session-builder.js +0 -30
  138. package/lib/Signal/Group/group_cipher.js +0 -82
  139. package/lib/Signal/Group/index.js +0 -12
  140. package/lib/Signal/Group/keyhelper.js +0 -18
  141. package/lib/Signal/Group/sender-chain-key.js +0 -26
  142. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  143. package/lib/Signal/Group/sender-key-message.js +0 -66
  144. package/lib/Signal/Group/sender-key-name.js +0 -48
  145. package/lib/Signal/Group/sender-key-record.js +0 -41
  146. package/lib/Signal/Group/sender-key-state.js +0 -84
  147. package/lib/Signal/Group/sender-message-key.js +0 -26
  148. package/lib/Signal/libsignal.js +0 -431
  149. package/lib/Signal/lid-mapping.js +0 -277
  150. package/lib/Socket/Client/index.js +0 -3
  151. package/lib/Socket/Client/types.js +0 -11
  152. package/lib/Socket/Client/websocket.js +0 -54
  153. package/lib/Socket/business.js +0 -379
  154. package/lib/Socket/chats.js +0 -1193
  155. package/lib/Socket/communities.js +0 -431
  156. package/lib/Socket/groups.js +0 -374
  157. package/lib/Socket/index.js +0 -12
  158. package/lib/Socket/luxu.js +0 -386
  159. package/lib/Socket/messages-recv.js +0 -1916
  160. package/lib/Socket/messages-send.js +0 -1453
  161. package/lib/Socket/newsletter.js +0 -251
  162. package/lib/Socket/socket.js +0 -980
  163. package/lib/Socket/username.js +0 -146
  164. package/lib/Store/index.js +0 -10
  165. package/lib/Store/keyed-db.js +0 -108
  166. package/lib/Store/make-cache-manager-store.js +0 -85
  167. package/lib/Store/make-in-memory-store.js +0 -198
  168. package/lib/Store/make-ordered-dictionary.js +0 -75
  169. package/lib/Store/object-repository.js +0 -32
  170. package/lib/Types/Auth.js +0 -2
  171. package/lib/Types/Bussines.js +0 -2
  172. package/lib/Types/Call.js +0 -2
  173. package/lib/Types/Chat.js +0 -8
  174. package/lib/Types/Contact.js +0 -2
  175. package/lib/Types/Events.js +0 -2
  176. package/lib/Types/GroupMetadata.js +0 -2
  177. package/lib/Types/Label.js +0 -25
  178. package/lib/Types/LabelAssociation.js +0 -7
  179. package/lib/Types/Message.js +0 -11
  180. package/lib/Types/Mex.js +0 -37
  181. package/lib/Types/Product.js +0 -2
  182. package/lib/Types/Signal.js +0 -2
  183. package/lib/Types/Socket.js +0 -3
  184. package/lib/Types/State.js +0 -56
  185. package/lib/Types/USync.js +0 -2
  186. package/lib/Types/index.js +0 -26
  187. package/lib/Utils/auth-utils.js +0 -302
  188. package/lib/Utils/browser-utils.js +0 -49
  189. package/lib/Utils/business.js +0 -231
  190. package/lib/Utils/chat-utils.js +0 -872
  191. package/lib/Utils/companion-reg-client-utils.js +0 -35
  192. package/lib/Utils/crypto.js +0 -118
  193. package/lib/Utils/decode-wa-message.js +0 -350
  194. package/lib/Utils/event-buffer.js +0 -622
  195. package/lib/Utils/generics.js +0 -403
  196. package/lib/Utils/history.js +0 -134
  197. package/lib/Utils/identity-change-handler.js +0 -50
  198. package/lib/Utils/index.js +0 -23
  199. package/lib/Utils/link-preview.js +0 -85
  200. package/lib/Utils/logger.js +0 -3
  201. package/lib/Utils/lt-hash.js +0 -8
  202. package/lib/Utils/make-mutex.js +0 -33
  203. package/lib/Utils/message-composer.js +0 -273
  204. package/lib/Utils/message-retry-manager.js +0 -265
  205. package/lib/Utils/messages-media.js +0 -788
  206. package/lib/Utils/messages.js +0 -1260
  207. package/lib/Utils/noise-handler.js +0 -201
  208. package/lib/Utils/offline-node-processor.js +0 -40
  209. package/lib/Utils/pre-key-manager.js +0 -106
  210. package/lib/Utils/process-message.js +0 -630
  211. package/lib/Utils/reporting-utils.js +0 -258
  212. package/lib/Utils/signal.js +0 -201
  213. package/lib/Utils/stanza-ack.js +0 -38
  214. package/lib/Utils/sync-action-utils.js +0 -49
  215. package/lib/Utils/tc-token-utils.js +0 -163
  216. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  217. package/lib/Utils/validate-connection.js +0 -203
  218. package/lib/WABinary/constants.js +0 -1301
  219. package/lib/WABinary/decode.js +0 -262
  220. package/lib/WABinary/encode.js +0 -220
  221. package/lib/WABinary/generic-utils.js +0 -204
  222. package/lib/WABinary/index.js +0 -6
  223. package/lib/WABinary/jid-utils.js +0 -98
  224. package/lib/WABinary/types.js +0 -2
  225. package/lib/WAM/BinaryInfo.js +0 -10
  226. package/lib/WAM/constants.js +0 -22853
  227. package/lib/WAM/encode.js +0 -150
  228. package/lib/WAM/index.js +0 -4
  229. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  230. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  231. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  232. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  233. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  234. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  235. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  236. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  237. package/lib/WAUSync/Protocols/index.js +0 -6
  238. package/lib/WAUSync/USyncQuery.js +0 -98
  239. package/lib/WAUSync/USyncUser.js +0 -31
  240. package/lib/WAUSync/index.js +0 -4
@@ -0,0 +1,506 @@
1
+ 'use strict'
2
+
3
+ var __importDefault =
4
+ (this && this.__importDefault) ||
5
+ function (mod) {
6
+ return mod && mod.__esModule ? mod : { default: mod }
7
+ }
8
+
9
+ Object.defineProperty(exports, '__esModule', { value: true })
10
+
11
+ const WAProto_1 = require('../../WAProto')
12
+ const Defaults_1 = require('../Defaults')
13
+ const LabelAssociation_1 = require('../Types/LabelAssociation')
14
+ const Utils_1 = require('../Utils')
15
+ const WABinary_1 = require('../WABinary')
16
+ const Store_1 = require('./make-ordered-dictionary')
17
+ const object_repository_1 = require('./object-repository')
18
+
19
+ const waChatKey = pin => ({
20
+ key: c =>
21
+ (pin ? (c.pinned ? '1' : '0') : '') +
22
+ (c.archived ? '0' : '1') +
23
+ (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') +
24
+ c.id,
25
+ compare: (k1, k2) => k2.localeCompare(k1)
26
+ })
27
+
28
+ const waMessageID = m => m.key.id || ''
29
+
30
+ const waLabelAssociationKey = {
31
+ key: la =>
32
+ la.type === LabelAssociation_1.LabelAssociationType.Chat
33
+ ? la.chatId + la.labelId
34
+ : la.chatId + la.messageId + la.labelId,
35
+ compare: (k1, k2) => k2.localeCompare(k1)
36
+ }
37
+
38
+ const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
39
+
40
+ const makeInMemoryStore = config => {
41
+ const socket = config.socket
42
+ const chatKey = config.chatKey || waChatKey(true)
43
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
44
+ const logger =
45
+ config.logger ||
46
+ Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
47
+ stream: 'in-mem-store'
48
+ })
49
+ const KeyedDB = require('@adiwajshing/keyed-db').default
50
+ const chats = new KeyedDB(chatKey, c => c.id)
51
+ const messages = {}
52
+ const contacts = {}
53
+ const groupMetadata = {}
54
+ const presences = {}
55
+ const state = { connection: 'close' }
56
+ const labels = new object_repository_1.ObjectRepository()
57
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
58
+ const assertMessageList = jid => {
59
+ if (!messages[jid]) {
60
+ messages[jid] = makeMessagesDictionary()
61
+ }
62
+ return messages[jid]
63
+ }
64
+ const contactsUpsert = newContacts => {
65
+ const oldContacts = new Set(Object.keys(contacts))
66
+ for (const contact of newContacts) {
67
+ oldContacts.delete(contact.id)
68
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact)
69
+ }
70
+ return oldContacts
71
+ }
72
+ const labelsUpsert = newLabels => {
73
+ for (const label of newLabels) {
74
+ labels.upsertById(label.id, label)
75
+ }
76
+ }
77
+ /**
78
+ * binds to a BaileysEventEmitter.
79
+ * It listens to all events and constructs a state that you can query accurate data from.
80
+ * Eg. can use the store to fetch chats, contacts, messages etc.
81
+ * @param ev typically the event emitter from the socket connection
82
+ */
83
+ const bind = ev => {
84
+ ev.on('connection.update', update => {
85
+ Object.assign(state, update)
86
+ })
87
+ ev.on(
88
+ 'messaging-history.set',
89
+ ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
90
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
91
+ // ON_DEMAND syncs are chunk-based and need cursor tracking — skip for now
92
+ return
93
+ }
94
+ if (isLatest) {
95
+ chats.clear()
96
+ for (const id in messages) {
97
+ delete messages[id]
98
+ }
99
+ }
100
+ const chatsAdded = chats.insertIfAbsent(...newChats).length
101
+ logger.debug({ chatsAdded }, 'synced chats')
102
+ const oldContacts = contactsUpsert(newContacts)
103
+ if (isLatest) {
104
+ for (const jid of oldContacts) {
105
+ delete contacts[jid]
106
+ }
107
+ }
108
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts')
109
+ for (const msg of newMessages) {
110
+ const jid = msg.key.remoteJid
111
+ const list = assertMessageList(jid)
112
+ list.upsert(msg, 'prepend')
113
+ }
114
+ logger.debug({ messages: newMessages.length }, 'synced messages')
115
+ }
116
+ )
117
+ ev.on('contacts.upsert', contacts => {
118
+ contactsUpsert(contacts)
119
+ })
120
+ ev.on('contacts.update', async updates => {
121
+ for (const update of updates) {
122
+ let contact
123
+ if (contacts[update.id]) {
124
+ contact = contacts[update.id]
125
+ } else {
126
+ const contactHashes = await Promise.all(
127
+ Object.keys(contacts).map(async contactId => {
128
+ const { user } = WABinary_1.jidDecode(contactId)
129
+ return [
130
+ contactId,
131
+ (await Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)
132
+ ]
133
+ })
134
+ )
135
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''] // find contact by attrs.hash, when user is not saved as a contact
136
+ }
137
+ if (contact) {
138
+ if (update.imgUrl === 'changed') {
139
+ contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined
140
+ } else if (update.imgUrl === 'removed') {
141
+ delete contact.imgUrl
142
+ }
143
+ } else {
144
+ return logger.debug({ update }, 'got update for non-existant contact')
145
+ }
146
+ Object.assign(contacts[contact.id], contact)
147
+ }
148
+ })
149
+ ev.on('chats.upsert', newChats => {
150
+ chats.upsert(...newChats)
151
+ })
152
+ ev.on('chats.update', updates => {
153
+ for (let update of updates) {
154
+ const result = chats.update(update.id, chat => {
155
+ if (update.unreadCount > 0) {
156
+ update = { ...update }
157
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount
158
+ }
159
+ Object.assign(chat, update)
160
+ })
161
+ if (!result) {
162
+ logger.debug({ update }, 'got update for non-existant chat')
163
+ }
164
+ }
165
+ })
166
+ ev.on('labels.edit', label => {
167
+ if (label.deleted) {
168
+ return labels.deleteById(label.id)
169
+ }
170
+ // WhatsApp can store only up to 20 labels
171
+ if (labels.count() < 20) {
172
+ return labels.upsertById(label.id, label)
173
+ }
174
+ logger.error('Labels count exceed')
175
+ })
176
+ ev.on('labels.association', ({ type, association }) => {
177
+ switch (type) {
178
+ case 'add':
179
+ labelAssociations.upsert(association)
180
+ break
181
+ case 'remove':
182
+ labelAssociations.delete(association)
183
+ break
184
+ default:
185
+ logger.error({ type }, 'unknown label association operation type')
186
+ }
187
+ })
188
+ ev.on('presence.update', ({ id, presences: update }) => {
189
+ presences[id] = presences[id] || {}
190
+ Object.assign(presences[id], update)
191
+ })
192
+ ev.on('chats.delete', deletions => {
193
+ for (const item of deletions) {
194
+ if (chats.get(item)) {
195
+ chats.deleteById(item)
196
+ }
197
+ }
198
+ })
199
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
200
+ switch (type) {
201
+ case 'append':
202
+ case 'notify':
203
+ for (const msg of newMessages) {
204
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
205
+ const list = assertMessageList(jid)
206
+ list.upsert(msg, 'append')
207
+ if (type === 'notify' && !chats.get(jid)) {
208
+ ev.emit('chats.upsert', [
209
+ {
210
+ id: jid,
211
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
212
+ unreadCount: 1
213
+ }
214
+ ])
215
+ }
216
+ }
217
+ break
218
+ }
219
+ })
220
+ ev.on('messages.update', updates => {
221
+ for (const { update, key } of updates) {
222
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid))
223
+ if (update?.status) {
224
+ const listStatus = list.get(key.id)?.status
225
+ if (listStatus && update?.status <= listStatus) {
226
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
227
+ delete update.status
228
+ logger.debug({ update }, 'new update object')
229
+ }
230
+ }
231
+ const result = list.updateAssign(key.id, update)
232
+ if (!result) {
233
+ logger.debug({ update }, 'got update for non-existent message')
234
+ }
235
+ }
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]
244
+ if (list) {
245
+ const idSet = new Set(item.keys.map(k => k.id))
246
+ list.filter(m => !idSet.has(m.key.id))
247
+ }
248
+ }
249
+ })
250
+ ev.on('groups.update', updates => {
251
+ for (const update of updates) {
252
+ const id = update.id
253
+ if (groupMetadata[id]) {
254
+ Object.assign(groupMetadata[id], update)
255
+ } else {
256
+ logger.debug({ update }, 'got update for non-existant group metadata')
257
+ }
258
+ }
259
+ })
260
+ ev.on('group-participants.update', ({ id, participants, action }) => {
261
+ const metadata = groupMetadata[id]
262
+ if (metadata) {
263
+ switch (action) {
264
+ case 'add':
265
+ metadata.participants.push(
266
+ ...participants.map(id => ({
267
+ id,
268
+ isAdmin: false,
269
+ isSuperAdmin: false
270
+ }))
271
+ )
272
+ break
273
+ case 'demote':
274
+ case 'promote':
275
+ for (const participant of metadata.participants) {
276
+ if (participants.includes(participant.id)) {
277
+ participant.isAdmin = action === 'promote'
278
+ }
279
+ }
280
+ break
281
+ case 'remove':
282
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
283
+ break
284
+ }
285
+ }
286
+ })
287
+ ev.on('message-receipt.update', updates => {
288
+ for (const { key, receipt } of updates) {
289
+ const obj = messages[key.remoteJid]
290
+ const msg = obj?.get(key.id)
291
+ if (msg) {
292
+ Utils_1.updateMessageWithReceipt(msg, receipt)
293
+ }
294
+ }
295
+ })
296
+ ev.on('messages.reaction', reactions => {
297
+ for (const { key, reaction } of reactions) {
298
+ const obj = messages[key.remoteJid]
299
+ const msg = obj?.get(key.id)
300
+ if (msg) {
301
+ Utils_1.updateMessageWithReaction(msg, reaction)
302
+ }
303
+ }
304
+ })
305
+ ev.on('settings.update', ({ setting, value }) => {
306
+ state.settings = state.settings || {}
307
+ state.settings[setting] = value
308
+ })
309
+ ev.on('labels.reorder', ({ labelIds }) => {
310
+ let order = 0
311
+ for (const id of labelIds) {
312
+ const label = labels.findById(id)
313
+ if (label) {
314
+ labels.upsertById(id, { ...label, order: order++ })
315
+ }
316
+ order++
317
+ }
318
+ })
319
+ ev.on('call.scheduled', ({ messageKey, scheduledCall, chatId }) => {
320
+ state.scheduledCalls = state.scheduledCalls || {}
321
+ state.scheduledCalls[messageKey.id] = { key: messageKey, scheduledCall, chatId }
322
+ })
323
+ ev.on('call.schedule-cancelled', ({ messageKey, editedCallKey }) => {
324
+ if (state.scheduledCalls?.[editedCallKey?.id]) {
325
+ delete state.scheduledCalls[editedCallKey.id]
326
+ }
327
+ })
328
+ ev.on('payment.split', ({ messageKey, splitPayment }) => {
329
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(messageKey.remoteJid))
330
+ const msg = list?.get(messageKey.id)
331
+ if (msg) {
332
+ msg.splitPayment = splitPayment
333
+ }
334
+ })
335
+ ev.on('message.comment', ({ commentKey, comment, targetKey }) => {
336
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(targetKey.remoteJid))
337
+ const msg = list?.get(targetKey.id)
338
+ if (msg) {
339
+ msg.commentCount = (msg.commentCount || 0) + 1
340
+ }
341
+ })
342
+ ev.on('poll.add-option', ({ pollKey, addedOption }) => {
343
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(pollKey.remoteJid))
344
+ const msg = list?.get(pollKey.id)
345
+ if (msg?.message) {
346
+ const poll =
347
+ msg.message.pollCreationMessage ||
348
+ msg.message.pollCreationMessageV3 ||
349
+ msg.message.pollCreationMessageV5 ||
350
+ msg.message.pollCreationMessageV6
351
+ if (poll && addedOption) {
352
+ poll.options = [...(poll.options || []), addedOption]
353
+ }
354
+ }
355
+ })
356
+ ev.on('chats.lock', ({ id, locked }) => {
357
+ const result = chats.update(id, chat => {
358
+ chat.locked = locked
359
+ })
360
+ if (!result) logger.debug({ id }, 'got chats.lock for non-existent chat')
361
+ })
362
+ ev.on('messaging-history.status', ({ syncType, status }) => {
363
+ state.historySyncStatus = state.historySyncStatus || {}
364
+ state.historySyncStatus[syncType] = status
365
+ })
366
+ }
367
+ const toJSON = () => ({
368
+ chats,
369
+ contacts,
370
+ messages,
371
+ labels,
372
+ labelAssociations
373
+ })
374
+ const fromJSON = json => {
375
+ chats.upsert(...json.chats)
376
+ labelAssociations.upsert(...(json.labelAssociations || []))
377
+ contactsUpsert(Object.values(json.contacts))
378
+ labelsUpsert(Object.values(json.labels || {}))
379
+ for (const jid in json.messages) {
380
+ const list = assertMessageList(jid)
381
+ for (const msg of json.messages[jid]) {
382
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append')
383
+ }
384
+ }
385
+ }
386
+ return {
387
+ chats,
388
+ contacts,
389
+ messages,
390
+ groupMetadata,
391
+ state,
392
+ presences,
393
+ labels,
394
+ labelAssociations,
395
+ bind,
396
+ /** loads messages from the store, if not found -- uses the legacy connection */
397
+ loadMessages: async (jid, count, cursor) => {
398
+ const list = assertMessageList(jid)
399
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after'
400
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
401
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
402
+ let messages
403
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
404
+ if (cursorValue) {
405
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
406
+ messages = list.array.slice(0, msgIdx)
407
+ } else {
408
+ messages = list.array
409
+ }
410
+ const diff = count - messages.length
411
+ if (diff < 0) {
412
+ messages = messages.slice(-count) // get the last X messages
413
+ }
414
+ } else {
415
+ messages = []
416
+ }
417
+ return messages
418
+ },
419
+ /**
420
+ * Get all available labels for profile
421
+ *
422
+ * Keep in mind that the list is formed from predefined tags and tags
423
+ * that were "caught" during their editing.
424
+ */
425
+ getLabels: () => {
426
+ return labels
427
+ },
428
+ /**
429
+ * Get labels for chat
430
+ *
431
+ * @returns Label IDs
432
+ **/
433
+ getChatLabels: chatId => {
434
+ return labelAssociations.filter(la => la.chatId === chatId).all()
435
+ },
436
+ /**
437
+ * Get labels for message
438
+ *
439
+ * @returns Label IDs
440
+ **/
441
+ getMessageLabels: messageId => {
442
+ const associations = labelAssociations.filter(la => la.messageId === messageId).all()
443
+ return associations.map(({ labelId }) => labelId)
444
+ },
445
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
446
+ mostRecentMessage: async jid => {
447
+ const message = messages[jid]?.array.slice(-1)[0]
448
+ return message
449
+ },
450
+ fetchImageUrl: async (jid, suki) => {
451
+ const contact = contacts[jid]
452
+ if (!contact) {
453
+ return suki?.profilePictureUrl(jid)
454
+ }
455
+ if (contact.imgUrl === undefined) {
456
+ contact.imgUrl = await suki?.profilePictureUrl(jid)
457
+ }
458
+ return contact.imgUrl
459
+ },
460
+ fetchGroupMetadata: async (jid, suki) => {
461
+ if (!groupMetadata[jid]) {
462
+ const metadata = await suki?.groupMetadata(jid)
463
+ if (metadata) {
464
+ groupMetadata[jid] = metadata
465
+ }
466
+ }
467
+ return groupMetadata[jid]
468
+ },
469
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
470
+ // if(!groupMetadata[jid]) {
471
+ // const metadata = await sock?.getBroadcastListInfo(jid)
472
+ // if(metadata) {
473
+ // groupMetadata[jid] = metadata
474
+ // }
475
+ // }
476
+ // return groupMetadata[jid]
477
+ // },
478
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
479
+ const list = messages[remoteJid]
480
+ const msg = list?.get(id)
481
+ return msg?.userReceipt
482
+ },
483
+ toJSON,
484
+ fromJSON,
485
+ writeToFile: path => {
486
+ // require fs here so that in case "fs" is not available -- the app does not crash
487
+ const { writeFileSync } = require('fs')
488
+ writeFileSync(path, JSON.stringify(toJSON()))
489
+ },
490
+ readFromFile: path => {
491
+ // require fs here so that in case "fs" is not available -- the app does not crash
492
+ const { readFileSync, existsSync } = require('fs')
493
+ if (existsSync(path)) {
494
+ logger.debug({ path }, 'reading from file')
495
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' })
496
+ const json = JSON.parse(jsonStr)
497
+ fromJSON(json)
498
+ }
499
+ }
500
+ }
501
+ }
502
+
503
+ exports.waChatKey = waChatKey
504
+ exports.waMessageID = waMessageID
505
+ exports.waLabelAssociationKey = waLabelAssociationKey
506
+ exports.makeInMemoryStore = makeInMemoryStore
@@ -0,0 +1,81 @@
1
+ 'use strict'
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true })
4
+
5
+ function makeOrderedDictionary(idGetter) {
6
+ const array = []
7
+ const dict = {}
8
+ const get = id => dict[id]
9
+ const update = item => {
10
+ const id = idGetter(item)
11
+ const idx = array.findIndex(i => idGetter(i) === id)
12
+ if (idx >= 0) {
13
+ array[idx] = item
14
+ dict[id] = item
15
+ }
16
+ return false
17
+ }
18
+ const upsert = (item, mode) => {
19
+ const id = idGetter(item)
20
+ if (get(id)) {
21
+ update(item)
22
+ } else {
23
+ if (mode === 'append') {
24
+ array.push(item)
25
+ } else {
26
+ array.splice(0, 0, item)
27
+ }
28
+ dict[id] = item
29
+ }
30
+ }
31
+ const remove = item => {
32
+ const id = idGetter(item)
33
+ const idx = array.findIndex(i => idGetter(i) === id)
34
+ if (idx >= 0) {
35
+ array.splice(idx, 1)
36
+ delete dict[id]
37
+ return true
38
+ }
39
+ return false
40
+ }
41
+ return {
42
+ array,
43
+ get,
44
+ upsert,
45
+ update,
46
+ remove,
47
+ updateAssign: (id, update) => {
48
+ const item = get(id)
49
+ if (item) {
50
+ Object.assign(item, update)
51
+ delete dict[id]
52
+ dict[idGetter(item)] = item
53
+ return true
54
+ }
55
+ return false
56
+ },
57
+ clear: () => {
58
+ array.splice(0, array.length)
59
+ for (const key of Object.keys(dict)) {
60
+ delete dict[key]
61
+ }
62
+ },
63
+ filter: contain => {
64
+ let i = 0
65
+ while (i < array.length) {
66
+ if (!contain(array[i])) {
67
+ delete dict[idGetter(array[i])]
68
+ array.splice(i, 1)
69
+ } else {
70
+ i += 1
71
+ }
72
+ }
73
+ },
74
+ toJSON: () => array,
75
+ fromJSON: newItems => {
76
+ array.splice(0, array.length, ...newItems)
77
+ }
78
+ }
79
+ }
80
+
81
+ exports.makeOrderedDictionary = makeOrderedDictionary
@@ -0,0 +1,29 @@
1
+ 'use strict'
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true })
4
+
5
+ class ObjectRepository {
6
+ constructor(entities = {}) {
7
+ this.entityMap = new Map(Object.entries(entities))
8
+ }
9
+ findById(id) {
10
+ return this.entityMap.get(id)
11
+ }
12
+ findAll() {
13
+ return Array.from(this.entityMap.values())
14
+ }
15
+ upsertById(id, entity) {
16
+ return this.entityMap.set(id, { ...entity })
17
+ }
18
+ deleteById(id) {
19
+ return this.entityMap.delete(id)
20
+ }
21
+ count() {
22
+ return this.entityMap.size
23
+ }
24
+ toJSON() {
25
+ return this.findAll()
26
+ }
27
+ }
28
+
29
+ exports.ObjectRepository = ObjectRepository
@@ -0,0 +1,38 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+
4
+ // Factory functions for creating auth-related objects
5
+ function createKeyPair(publicKey, privateKey) {
6
+ return {
7
+ public: publicKey,
8
+ private: privateKey
9
+ }
10
+ }
11
+
12
+ function createSignedKeyPair(keyPair, signature, keyId, timestampS) {
13
+ return {
14
+ keyPair,
15
+ signature,
16
+ keyId,
17
+ timestampS
18
+ }
19
+ }
20
+
21
+ // Export type definitions (for documentation purposes)
22
+ exports.SignalDataTypeMap = {
23
+ 'pre-key': 'KeyPair',
24
+ session: 'Uint8Array',
25
+ 'sender-key': 'Uint8Array',
26
+ 'sender-key-memory': 'object',
27
+ 'app-state-sync-key': 'proto.Message.IAppStateSyncKeyData',
28
+ 'app-state-sync-version': 'LTHashState',
29
+ 'lid-mapping': 'string',
30
+ 'device-list': 'Array',
31
+ tctoken: 'object'
32
+ }
33
+ exports.SignalDataSet = undefined
34
+ exports.Awaitable = undefined
35
+
36
+ // Export the factory functions
37
+ exports.createKeyPair = createKeyPair
38
+ exports.createSignedKeyPair = createSignedKeyPair
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
@@ -0,0 +1,4 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.ALL_WA_PATCH_NAMES = void 0
4
+ exports.ALL_WA_PATCH_NAMES = ['critical_block', 'critical_unblock_low', 'regular_high', 'regular_low', 'regular']
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })