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