dcodeindra-baileyspro 2.3.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 (286) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2534 -0
  3. package/WAProto/Adv/Adv.d.ts +518 -0
  4. package/WAProto/Adv/Adv.js +1734 -0
  5. package/WAProto/Adv/Adv.proto +36 -0
  6. package/WAProto/BotMetadata/BotMetadata.d.ts +5745 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +16291 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +463 -0
  9. package/WAProto/Cert/Cert.d.ts +497 -0
  10. package/WAProto/Cert/Cert.js +1503 -0
  11. package/WAProto/Cert/Cert.proto +28 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +391 -0
  13. package/WAProto/ChatLockSettings/ChatLockSettings.js +1155 -0
  14. package/WAProto/ChatLockSettings/ChatLockSettings.proto +7 -0
  15. package/WAProto/CompanionReg/CompanionReg.d.ts +1055 -0
  16. package/WAProto/CompanionReg/CompanionReg.js +3532 -0
  17. package/WAProto/CompanionReg/CompanionReg.proto +89 -0
  18. package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +187 -0
  19. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +520 -0
  20. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +14 -0
  21. package/WAProto/E2E/E2E.d.ts +28417 -0
  22. package/WAProto/E2E/E2E.js +98438 -0
  23. package/WAProto/E2E/E2E.proto +2289 -0
  24. package/WAProto/Ephemeral/Ephemeral.d.ts +95 -0
  25. package/WAProto/Ephemeral/Ephemeral.js +269 -0
  26. package/WAProto/Ephemeral/Ephemeral.proto +6 -0
  27. package/WAProto/HistorySync/HistorySync.d.ts +40728 -0
  28. package/WAProto/HistorySync/HistorySync.js +142980 -0
  29. package/WAProto/HistorySync/HistorySync.proto +207 -0
  30. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +189 -0
  31. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +585 -0
  32. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +11 -0
  33. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +461 -0
  34. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +1559 -0
  35. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +37 -0
  36. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +29294 -0
  37. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +101732 -0
  38. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +76 -0
  39. package/WAProto/MmsRetry/MmsRetry.d.ts +200 -0
  40. package/WAProto/MmsRetry/MmsRetry.js +586 -0
  41. package/WAProto/MmsRetry/MmsRetry.proto +17 -0
  42. package/WAProto/Protocol/Protocol.d.ts +218 -0
  43. package/WAProto/Protocol/Protocol.js +701 -0
  44. package/WAProto/Protocol/Protocol.proto +20 -0
  45. package/WAProto/Reporting/Reporting.d.ts +301 -0
  46. package/WAProto/Reporting/Reporting.js +989 -0
  47. package/WAProto/Reporting/Reporting.proto +19 -0
  48. package/WAProto/ServerSync/ServerSync.d.ts +1050 -0
  49. package/WAProto/ServerSync/ServerSync.js +3176 -0
  50. package/WAProto/ServerSync/ServerSync.proto +59 -0
  51. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +1507 -0
  52. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +4756 -0
  53. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +88 -0
  54. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +617 -0
  55. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1940 -0
  56. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +38 -0
  57. package/WAProto/StatusAttributions/StatusAttributions.d.ts +636 -0
  58. package/WAProto/StatusAttributions/StatusAttributions.js +2037 -0
  59. package/WAProto/StatusAttributions/StatusAttributions.proto +61 -0
  60. package/WAProto/SyncAction/SyncAction.d.ts +7227 -0
  61. package/WAProto/SyncAction/SyncAction.js +22271 -0
  62. package/WAProto/SyncAction/SyncAction.proto +423 -0
  63. package/WAProto/UserPassword/UserPassword.d.ts +298 -0
  64. package/WAProto/UserPassword/UserPassword.js +898 -0
  65. package/WAProto/UserPassword/UserPassword.proto +27 -0
  66. package/WAProto/VnameCert/VnameCert.d.ts +658 -0
  67. package/WAProto/VnameCert/VnameCert.js +2225 -0
  68. package/WAProto/VnameCert/VnameCert.proto +60 -0
  69. package/WAProto/Wa6/Wa6.d.ts +1613 -0
  70. package/WAProto/Wa6/Wa6.js +6299 -0
  71. package/WAProto/Wa6/Wa6.proto +229 -0
  72. package/WAProto/Web/Web.d.ts +31718 -0
  73. package/WAProto/Web/Web.js +113402 -0
  74. package/WAProto/Web/Web.proto +545 -0
  75. package/WAProto/index.d.ts +49 -0
  76. package/WAProto/index.js +28 -0
  77. package/WASignalGroup/GroupProtocol.js +1771 -0
  78. package/WASignalGroup/ciphertext_message.js +10 -0
  79. package/WASignalGroup/group_cipher.js +103 -0
  80. package/WASignalGroup/group_session_builder.js +39 -0
  81. package/WASignalGroup/index.js +5 -0
  82. package/WASignalGroup/keyhelper.js +17 -0
  83. package/WASignalGroup/protobufs.js +2 -0
  84. package/WASignalGroup/queue_job.js +64 -0
  85. package/WASignalGroup/sender_chain_key.js +38 -0
  86. package/WASignalGroup/sender_key_distribution_message.js +68 -0
  87. package/WASignalGroup/sender_key_message.js +79 -0
  88. package/WASignalGroup/sender_key_name.js +59 -0
  89. package/WASignalGroup/sender_key_record.js +47 -0
  90. package/WASignalGroup/sender_key_state.js +110 -0
  91. package/WASignalGroup/sender_message_key.js +30 -0
  92. package/check-node-version.js +10 -0
  93. package/lib/Defaults/baileys-version.json +3 -0
  94. package/lib/Defaults/index.d.ts +51 -0
  95. package/lib/Defaults/index.js +108 -0
  96. package/lib/Defaults/phonenumber-mcc.json +223 -0
  97. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  98. package/lib/Signal/Group/ciphertext-message.js +19 -0
  99. package/lib/Signal/Group/group-session-builder.d.ts +17 -0
  100. package/lib/Signal/Group/group-session-builder.js +72 -0
  101. package/lib/Signal/Group/group_cipher.d.ts +19 -0
  102. package/lib/Signal/Group/group_cipher.js +99 -0
  103. package/lib/Signal/Group/index.d.ts +11 -0
  104. package/lib/Signal/Group/index.js +61 -0
  105. package/lib/Signal/Group/keyhelper.d.ts +16 -0
  106. package/lib/Signal/Group/keyhelper.js +66 -0
  107. package/lib/Signal/Group/queue-job.d.ts +1 -0
  108. package/lib/Signal/Group/queue-job.js +64 -0
  109. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  110. package/lib/Signal/Group/sender-chain-key.js +39 -0
  111. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  112. package/lib/Signal/Group/sender-key-distribution-message.js +71 -0
  113. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  114. package/lib/Signal/Group/sender-key-message.js +73 -0
  115. package/lib/Signal/Group/sender-key-name.d.ts +19 -0
  116. package/lib/Signal/Group/sender-key-name.js +59 -0
  117. package/lib/Signal/Group/sender-key-record.d.ts +32 -0
  118. package/lib/Signal/Group/sender-key-record.js +53 -0
  119. package/lib/Signal/Group/sender-key-record.ts +77 -0
  120. package/lib/Signal/Group/sender-key-state.d.ts +44 -0
  121. package/lib/Signal/Group/sender-key-state.js +104 -0
  122. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  123. package/lib/Signal/Group/sender-message-key.js +33 -0
  124. package/lib/Signal/libsignal.d.ts +3 -0
  125. package/lib/Signal/libsignal.js +153 -0
  126. package/lib/Socket/Client/index.d.ts +2 -0
  127. package/lib/Socket/Client/index.js +18 -0
  128. package/lib/Socket/Client/types.d.ts +15 -0
  129. package/lib/Socket/Client/types.js +14 -0
  130. package/lib/Socket/Client/websocket.d.ts +12 -0
  131. package/lib/Socket/Client/websocket.js +57 -0
  132. package/lib/Socket/business.d.ts +181 -0
  133. package/lib/Socket/business.js +259 -0
  134. package/lib/Socket/chats.d.ts +95 -0
  135. package/lib/Socket/chats.js +906 -0
  136. package/lib/Socket/community.d.ts +131 -0
  137. package/lib/Socket/community.js +369 -0
  138. package/lib/Socket/groups.d.ts +122 -0
  139. package/lib/Socket/groups.js +360 -0
  140. package/lib/Socket/index.d.ts +183 -0
  141. package/lib/Socket/index.js +10 -0
  142. package/lib/Socket/messages-recv.d.ts +170 -0
  143. package/lib/Socket/messages-recv.js +1074 -0
  144. package/lib/Socket/messages-send.d.ts +161 -0
  145. package/lib/Socket/messages-send.js +982 -0
  146. package/lib/Socket/newsletter.d.ts +140 -0
  147. package/lib/Socket/newsletter.js +242 -0
  148. package/lib/Socket/socket.d.ts +43 -0
  149. package/lib/Socket/socket.js +749 -0
  150. package/lib/Socket/usync.d.ts +36 -0
  151. package/lib/Socket/usync.js +71 -0
  152. package/lib/Store/index.d.ts +4 -0
  153. package/lib/Store/index.js +20 -0
  154. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  155. package/lib/Store/make-cache-manager-store.js +77 -0
  156. package/lib/Store/make-in-memory-store.d.ts +117 -0
  157. package/lib/Store/make-in-memory-store.js +420 -0
  158. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  159. package/lib/Store/make-ordered-dictionary.js +83 -0
  160. package/lib/Store/object-repository.d.ts +10 -0
  161. package/lib/Store/object-repository.js +28 -0
  162. package/lib/Types/Auth.d.ts +103 -0
  163. package/lib/Types/Auth.js +2 -0
  164. package/lib/Types/Call.d.ts +13 -0
  165. package/lib/Types/Call.js +2 -0
  166. package/lib/Types/Chat.d.ts +115 -0
  167. package/lib/Types/Chat.js +6 -0
  168. package/lib/Types/Contact.d.ts +35 -0
  169. package/lib/Types/Contact.js +2 -0
  170. package/lib/Types/Events.d.ts +208 -0
  171. package/lib/Types/Events.js +2 -0
  172. package/lib/Types/GroupMetadata.d.ts +81 -0
  173. package/lib/Types/GroupMetadata.js +2 -0
  174. package/lib/Types/Label.d.ts +46 -0
  175. package/lib/Types/Label.js +28 -0
  176. package/lib/Types/LabelAssociation.d.ts +29 -0
  177. package/lib/Types/LabelAssociation.js +10 -0
  178. package/lib/Types/Message.d.ts +480 -0
  179. package/lib/Types/Message.js +9 -0
  180. package/lib/Types/MexUpdates.d.ts +9 -0
  181. package/lib/Types/MexUpdates.js +18 -0
  182. package/lib/Types/Newsletter.d.ts +92 -0
  183. package/lib/Types/Newsletter.js +33 -0
  184. package/lib/Types/Product.d.ts +78 -0
  185. package/lib/Types/Product.js +2 -0
  186. package/lib/Types/Signal.d.ts +57 -0
  187. package/lib/Types/Signal.js +2 -0
  188. package/lib/Types/Socket.d.ts +116 -0
  189. package/lib/Types/Socket.js +2 -0
  190. package/lib/Types/State.d.ts +27 -0
  191. package/lib/Types/State.js +2 -0
  192. package/lib/Types/USync.d.ts +25 -0
  193. package/lib/Types/USync.js +2 -0
  194. package/lib/Types/index.d.ts +70 -0
  195. package/lib/Types/index.js +42 -0
  196. package/lib/Utils/auth-utils.d.ts +18 -0
  197. package/lib/Utils/auth-utils.js +198 -0
  198. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  199. package/lib/Utils/baileys-event-stream.js +64 -0
  200. package/lib/Utils/business.d.ts +22 -0
  201. package/lib/Utils/business.js +243 -0
  202. package/lib/Utils/chat-utils.d.ts +72 -0
  203. package/lib/Utils/chat-utils.js +762 -0
  204. package/lib/Utils/crypto.d.ts +40 -0
  205. package/lib/Utils/crypto.js +150 -0
  206. package/lib/Utils/decode-wa-message.d.ts +252 -0
  207. package/lib/Utils/decode-wa-message.js +232 -0
  208. package/lib/Utils/event-buffer.d.ts +35 -0
  209. package/lib/Utils/event-buffer.js +539 -0
  210. package/lib/Utils/generics.d.ts +96 -0
  211. package/lib/Utils/generics.js +553 -0
  212. package/lib/Utils/history.d.ts +29 -0
  213. package/lib/Utils/history.js +109 -0
  214. package/lib/Utils/index.d.ts +19 -0
  215. package/lib/Utils/index.js +35 -0
  216. package/lib/Utils/link-preview.d.ts +21 -0
  217. package/lib/Utils/link-preview.js +112 -0
  218. package/lib/Utils/logger.d.ts +11 -0
  219. package/lib/Utils/logger.js +7 -0
  220. package/lib/Utils/lt-hash.d.ts +12 -0
  221. package/lib/Utils/lt-hash.js +53 -0
  222. package/lib/Utils/make-mutex.d.ts +7 -0
  223. package/lib/Utils/make-mutex.js +45 -0
  224. package/lib/Utils/messages-media.d.ts +104 -0
  225. package/lib/Utils/messages-media.js +751 -0
  226. package/lib/Utils/messages.d.ts +80 -0
  227. package/lib/Utils/messages.js +1741 -0
  228. package/lib/Utils/noise-handler.d.ts +19 -0
  229. package/lib/Utils/noise-handler.js +150 -0
  230. package/lib/Utils/process-message.d.ts +41 -0
  231. package/lib/Utils/process-message.js +391 -0
  232. package/lib/Utils/signal.d.ts +33 -0
  233. package/lib/Utils/signal.js +154 -0
  234. package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -0
  235. package/lib/Utils/use-mongo-file-auth-state.js +75 -0
  236. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  237. package/lib/Utils/use-multi-file-auth-state.js +123 -0
  238. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  239. package/lib/Utils/use-single-file-auth-state.js +75 -0
  240. package/lib/Utils/validate-connection.d.ts +10 -0
  241. package/lib/Utils/validate-connection.js +174 -0
  242. package/lib/WABinary/constants.d.ts +27 -0
  243. package/lib/WABinary/constants.js +45 -0
  244. package/lib/WABinary/decode.d.ts +6 -0
  245. package/lib/WABinary/decode.js +255 -0
  246. package/lib/WABinary/encode.d.ts +2 -0
  247. package/lib/WABinary/encode.js +243 -0
  248. package/lib/WABinary/generic-utils.d.ts +16 -0
  249. package/lib/WABinary/generic-utils.js +125 -0
  250. package/lib/WABinary/index.d.ts +5 -0
  251. package/lib/WABinary/index.js +21 -0
  252. package/lib/WABinary/jid-utils.d.ts +34 -0
  253. package/lib/WABinary/jid-utils.js +73 -0
  254. package/lib/WABinary/types.d.ts +18 -0
  255. package/lib/WABinary/types.js +2 -0
  256. package/lib/WAM/BinaryInfo.d.ts +16 -0
  257. package/lib/WAM/BinaryInfo.js +14 -0
  258. package/lib/WAM/constants.d.ts +39 -0
  259. package/lib/WAM/constants.js +15362 -0
  260. package/lib/WAM/encode.d.ts +2 -0
  261. package/lib/WAM/encode.js +156 -0
  262. package/lib/WAM/index.d.ts +3 -0
  263. package/lib/WAM/index.js +19 -0
  264. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +25 -0
  265. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +60 -0
  266. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  267. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  268. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  269. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +58 -0
  270. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  271. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  272. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +8 -0
  273. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +26 -0
  274. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  275. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  276. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  277. package/lib/WAUSync/Protocols/index.js +22 -0
  278. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  279. package/lib/WAUSync/USyncQuery.js +88 -0
  280. package/lib/WAUSync/USyncUser.d.ts +12 -0
  281. package/lib/WAUSync/USyncUser.js +27 -0
  282. package/lib/WAUSync/index.d.ts +3 -0
  283. package/lib/WAUSync/index.js +19 -0
  284. package/lib/index.d.ts +13 -0
  285. package/lib/index.js +45 -0
  286. package/package.json +63 -0
@@ -0,0 +1,420 @@
1
+ "use strict"
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod }
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true })
6
+ const WAProto_1 = require("../../WAProto")
7
+ const Defaults_1 = require("../Defaults")
8
+ const LabelAssociation_1 = require("../Types/LabelAssociation")
9
+ const Utils_1 = require("../Utils")
10
+ const WABinary_1 = require("../WABinary")
11
+ const Store_1 = require("./make-ordered-dictionary")
12
+ const object_repository_1 = require("./object-repository")
13
+ const waChatKey = (pin) => ({
14
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
15
+ compare: (k1, k2) => k2.localeCompare(k1)
16
+ })
17
+ const waMessageID = (m) => m.key.id || ''
18
+ const waLabelAssociationKey = {
19
+ key: (la) => (la.type === LabelAssociation_1.LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
20
+ compare: (k1, k2) => k2.localeCompare(k1)
21
+ }
22
+ const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
23
+ const makeInMemoryStore = (config) => {
24
+ const socket = config.socket
25
+ const chatKey = config.chatKey || waChatKey(true)
26
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
27
+ const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
28
+ const KeyedDB = require('@adiwajshing/keyed-db').default
29
+ const chats = new KeyedDB(chatKey, c => c.id)
30
+ const messages = {}
31
+ const contacts = {}
32
+ const groupMetadata = {}
33
+ const presences = {}
34
+ const state = { connection: 'close' }
35
+ const labels = new object_repository_1.ObjectRepository()
36
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
37
+ const assertMessageList = (jid) => {
38
+ if (!messages[jid]) {
39
+ messages[jid] = makeMessagesDictionary()
40
+ }
41
+ return messages[jid]
42
+ }
43
+ const contactsUpsert = (newContacts) => {
44
+ const oldContacts = new Set(Object.keys(contacts))
45
+ for (const contact of newContacts) {
46
+ oldContacts.delete(contact.id)
47
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact)
48
+ }
49
+ return oldContacts
50
+ }
51
+ const labelsUpsert = (newLabels) => {
52
+ for (const label of newLabels) {
53
+ labels.upsertById(label.id, label)
54
+ }
55
+ }
56
+ /**
57
+ * binds to a BaileysEventEmitter.
58
+ * It listens to all events and constructs a state that you can query accurate data from.
59
+ * Eg. can use the store to fetch chats, contacts, messages etc.
60
+ * @param ev typically the event emitter from the socket connection
61
+ */
62
+ const bind = (ev) => {
63
+ ev.on('connection.update', update => {
64
+ Object.assign(state, update)
65
+ })
66
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
67
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
68
+ return // FOR NOW,
69
+ //TODO: HANDLE
70
+ }
71
+ if (isLatest) {
72
+ chats.clear()
73
+ for (const id in messages) {
74
+ delete messages[id]
75
+ }
76
+ }
77
+ const chatsAdded = chats.insertIfAbsent(...newChats).length
78
+ logger.debug({ chatsAdded }, 'synced chats')
79
+ const oldContacts = contactsUpsert(newContacts)
80
+ if (isLatest) {
81
+ for (const jid of oldContacts) {
82
+ delete contacts[jid]
83
+ }
84
+ }
85
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts')
86
+ for (const msg of newMessages) {
87
+ const jid = msg.key.remoteJid
88
+ const list = assertMessageList(jid)
89
+ list.upsert(msg, 'prepend')
90
+ }
91
+ logger.debug({ messages: newMessages.length }, 'synced messages')
92
+ })
93
+ ev.on('contacts.upsert', contacts => {
94
+ contactsUpsert(contacts)
95
+ })
96
+ ev.on('contacts.update', async (updates) => {
97
+ for (const update of updates) {
98
+ let contact
99
+ if (contacts[update.id]) {
100
+ contact = contacts[update.id]
101
+ }
102
+ else {
103
+ const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
104
+ const { user } = WABinary_1.jidDecode(contactId)
105
+ return [contactId, (await Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)]
106
+ }))
107
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''] // find contact by attrs.hash, when user is not saved as a contact
108
+ }
109
+ if (contact) {
110
+ if (update.imgUrl === 'changed') {
111
+ contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined
112
+ }
113
+ else if (update.imgUrl === 'removed') {
114
+ delete contact.imgUrl
115
+ }
116
+ }
117
+ else {
118
+ return logger.debug({ update }, 'got update for non-existant contact')
119
+ }
120
+ Object.assign(contacts[contact.id], contact)
121
+ }
122
+ })
123
+ ev.on('chats.upsert', newChats => {
124
+ chats.upsert(...newChats)
125
+ })
126
+ ev.on('chats.update', updates => {
127
+ for (let update of updates) {
128
+ const result = chats.update(update.id, chat => {
129
+ if (update.unreadCount > 0) {
130
+ update = { ...update }
131
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount
132
+ }
133
+ Object.assign(chat, update)
134
+ })
135
+ if (!result) {
136
+ logger.debug({ update }, 'got update for non-existant chat')
137
+ }
138
+ }
139
+ })
140
+ ev.on('labels.edit', (label) => {
141
+ if (label.deleted) {
142
+ return labels.deleteById(label.id)
143
+ }
144
+ // WhatsApp can store only up to 20 labels
145
+ if (labels.count() < 20) {
146
+ return labels.upsertById(label.id, label)
147
+ }
148
+ logger.error('Labels count exceed')
149
+ })
150
+ ev.on('labels.association', ({ type, association }) => {
151
+ switch (type) {
152
+ case 'add':
153
+ labelAssociations.upsert(association)
154
+ break
155
+ case 'remove':
156
+ labelAssociations.delete(association)
157
+ break
158
+ default:
159
+ console.error(`unknown operation type [${type}]`)
160
+ }
161
+ })
162
+ ev.on('presence.update', ({ id, presences: update }) => {
163
+ presences[id] = presences[id] || {}
164
+ Object.assign(presences[id], update)
165
+ })
166
+ ev.on('chats.delete', deletions => {
167
+ for (const item of deletions) {
168
+ if (chats.get(item)) {
169
+ chats.deleteById(item)
170
+ }
171
+ }
172
+ })
173
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
174
+ switch (type) {
175
+ case 'append':
176
+ case 'notify':
177
+ for (const msg of newMessages) {
178
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
179
+ const list = assertMessageList(jid)
180
+ list.upsert(msg, 'append')
181
+ if (type === 'notify' && !chats.get(jid)) {
182
+ ev.emit('chats.upsert', [
183
+ {
184
+ id: jid,
185
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
186
+ unreadCount: 1
187
+ }
188
+ ])
189
+ }
190
+ }
191
+ break
192
+ }
193
+ })
194
+ ev.on('messages.update', updates => {
195
+ for (const { update, key } of updates) {
196
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid))
197
+ if (update?.status) {
198
+ const listStatus = list.get(key.id)?.status
199
+ if (listStatus && update?.status <= listStatus) {
200
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
201
+ delete update.status
202
+ logger.debug({ update }, 'new update object')
203
+ }
204
+ }
205
+ const result = list.updateAssign(key.id, update)
206
+ if (!result) {
207
+ logger.debug({ update }, 'got update for non-existent message')
208
+ }
209
+ }
210
+ })
211
+ ev.on('messages.delete', item => {
212
+ if ('all' in item) {
213
+ const list = messages[item.jid]
214
+ list?.clear()
215
+ }
216
+ else {
217
+ const jid = item.keys[0].remoteJid
218
+ const list = messages[jid]
219
+ if (list) {
220
+ const idSet = new Set(item.keys.map(k => k.id))
221
+ list.filter(m => !idSet.has(m.key.id))
222
+ }
223
+ }
224
+ })
225
+ ev.on('groups.update', updates => {
226
+ for (const update of updates) {
227
+ const id = update.id
228
+ if (groupMetadata[id]) {
229
+ Object.assign(groupMetadata[id], update)
230
+ }
231
+ else {
232
+ logger.debug({ update }, 'got update for non-existant group metadata')
233
+ }
234
+ }
235
+ })
236
+ ev.on('group-participants.update', ({ id, participants, action }) => {
237
+ const metadata = groupMetadata[id]
238
+ if (metadata) {
239
+ switch (action) {
240
+ case 'add':
241
+ metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })))
242
+ break
243
+ case 'demote':
244
+ case 'promote':
245
+ for (const participant of metadata.participants) {
246
+ if (participants.includes(participant.id)) {
247
+ participant.isAdmin = action === 'promote'
248
+ }
249
+ }
250
+ break
251
+ case 'remove':
252
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
253
+ break
254
+ }
255
+ }
256
+ })
257
+ ev.on('message-receipt.update', updates => {
258
+ for (const { key, receipt } of updates) {
259
+ const obj = messages[key.remoteJid]
260
+ const msg = obj?.get(key.id)
261
+ if (msg) {
262
+ Utils_1.updateMessageWithReceipt(msg, receipt)
263
+ }
264
+ }
265
+ })
266
+ ev.on('messages.reaction', (reactions) => {
267
+ for (const { key, reaction } of reactions) {
268
+ const obj = messages[key.remoteJid]
269
+ const msg = obj?.get(key.id)
270
+ if (msg) {
271
+ Utils_1.updateMessageWithReaction(msg, reaction)
272
+ }
273
+ }
274
+ })
275
+ }
276
+ const toJSON = () => ({
277
+ chats,
278
+ contacts,
279
+ messages,
280
+ labels,
281
+ labelAssociations
282
+ })
283
+ const fromJSON = (json) => {
284
+ chats.upsert(...json.chats)
285
+ labelAssociations.upsert(...json.labelAssociations || [])
286
+ contactsUpsert(Object.values(json.contacts))
287
+ labelsUpsert(Object.values(json.labels || {}))
288
+ for (const jid in json.messages) {
289
+ const list = assertMessageList(jid)
290
+ for (const msg of json.messages[jid]) {
291
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append')
292
+ }
293
+ }
294
+ }
295
+ return {
296
+ chats,
297
+ contacts,
298
+ messages,
299
+ groupMetadata,
300
+ state,
301
+ presences,
302
+ labels,
303
+ labelAssociations,
304
+ bind,
305
+ /** loads messages from the store, if not found -- uses the legacy connection */
306
+ loadMessages: async (jid, count, cursor) => {
307
+ const list = assertMessageList(jid)
308
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after'
309
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
310
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
311
+ let messages
312
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
313
+ if (cursorValue) {
314
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
315
+ messages = list.array.slice(0, msgIdx)
316
+ }
317
+ else {
318
+ messages = list.array
319
+ }
320
+ const diff = count - messages.length
321
+ if (diff < 0) {
322
+ messages = messages.slice(-count) // get the last X messages
323
+ }
324
+ }
325
+ else {
326
+ messages = []
327
+ }
328
+ return messages
329
+ },
330
+ /**
331
+ * Get all available labels for profile
332
+ *
333
+ * Keep in mind that the list is formed from predefined tags and tags
334
+ * that were "caught" during their editing.
335
+ */
336
+ getLabels: () => {
337
+ return labels
338
+ },
339
+ /**
340
+ * Get labels for chat
341
+ *
342
+ * @returns Label IDs
343
+ **/
344
+ getChatLabels: (chatId) => {
345
+ return labelAssociations.filter((la) => la.chatId === chatId).all()
346
+ },
347
+ /**
348
+ * Get labels for message
349
+ *
350
+ * @returns Label IDs
351
+ **/
352
+ getMessageLabels: (messageId) => {
353
+ const associations = labelAssociations
354
+ .filter((la) => la.messageId === messageId)
355
+ .all()
356
+ return associations.map(({ labelId }) => labelId)
357
+ },
358
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
359
+ mostRecentMessage: async (jid) => {
360
+ const message = messages[jid]?.array.slice(-1)[0]
361
+ return message
362
+ },
363
+ fetchImageUrl: async (jid, sock) => {
364
+ const contact = contacts[jid]
365
+ if (!contact) {
366
+ return sock?.profilePictureUrl(jid)
367
+ }
368
+ if (typeof contact.imgUrl === 'undefined') {
369
+ contact.imgUrl = await sock?.profilePictureUrl(jid)
370
+ }
371
+ return contact.imgUrl
372
+ },
373
+ fetchGroupMetadata: async (jid, sock) => {
374
+ if (!groupMetadata[jid]) {
375
+ const metadata = await sock?.groupMetadata(jid)
376
+ if (metadata) {
377
+ groupMetadata[jid] = metadata
378
+ }
379
+ }
380
+ return groupMetadata[jid]
381
+ },
382
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
383
+ // if(!groupMetadata[jid]) {
384
+ // const metadata = await sock?.getBroadcastListInfo(jid)
385
+ // if(metadata) {
386
+ // groupMetadata[jid] = metadata
387
+ // }
388
+ // }
389
+ // return groupMetadata[jid]
390
+ // },
391
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
392
+ const list = messages[remoteJid]
393
+ const msg = list?.get(id)
394
+ return msg?.userReceipt
395
+ },
396
+ toJSON,
397
+ fromJSON,
398
+ writeToFile: (path) => {
399
+ // require fs here so that in case "fs" is not available -- the app does not crash
400
+ const { writeFileSync } = require('fs')
401
+ writeFileSync(path, JSON.stringify(toJSON()))
402
+ },
403
+ readFromFile: (path) => {
404
+ // require fs here so that in case "fs" is not available -- the app does not crash
405
+ const { readFileSync, existsSync } = require('fs')
406
+ if (existsSync(path)) {
407
+ logger.debug({ path }, 'reading from file')
408
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' })
409
+ const json = JSON.parse(jsonStr)
410
+ fromJSON(json)
411
+ }
412
+ }
413
+ }
414
+ }
415
+ module.exports = {
416
+ waChatKey,
417
+ waMessageID,
418
+ waLabelAssociationKey,
419
+ makeInMemoryStore
420
+ }
@@ -0,0 +1,12 @@
1
+ export declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
2
+ array: T[]
3
+ get: (id: string) => T | undefined
4
+ upsert: (item: T, mode: 'append' | 'prepend') => void
5
+ update: (item: T) => boolean
6
+ remove: (item: T) => boolean
7
+ updateAssign: (id: string, update: Partial<T>) => boolean
8
+ clear: () => void
9
+ filter: (contain: (item: T) => boolean) => void
10
+ toJSON: () => T[]
11
+ fromJSON: (newItems: T[]) => void
12
+ }
@@ -0,0 +1,83 @@
1
+ "use strict"
2
+ Object.defineProperty(exports, "__esModule", { value: true })
3
+ function makeOrderedDictionary(idGetter) {
4
+ const array = []
5
+ const dict = {}
6
+ const get = (id) => dict[id]
7
+ const update = (item) => {
8
+ const id = idGetter(item)
9
+ const idx = array.findIndex(i => idGetter(i) === id)
10
+ if (idx >= 0) {
11
+ array[idx] = item
12
+ dict[id] = item
13
+ }
14
+ return false
15
+ }
16
+ const upsert = (item, mode) => {
17
+ const id = idGetter(item)
18
+ if (get(id)) {
19
+ update(item)
20
+ }
21
+ else {
22
+ if (mode === 'append') {
23
+ array.push(item)
24
+ }
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
+ }
70
+ else {
71
+ i += 1
72
+ }
73
+ }
74
+ },
75
+ toJSON: () => array,
76
+ fromJSON: (newItems) => {
77
+ array.splice(0, array.length, ...newItems)
78
+ }
79
+ }
80
+ }
81
+ module.exports = {
82
+ makeOrderedDictionary
83
+ }
@@ -0,0 +1,10 @@
1
+ export declare class ObjectRepository<T extends object> {
2
+ readonly entityMap: Map<string, T>
3
+ constructor(entities?: Record<string, T>)
4
+ findById(id: string): T | undefined
5
+ findAll(): T[]
6
+ upsertById(id: string, entity: T): Map<string, T>
7
+ deleteById(id: string): boolean
8
+ count(): number
9
+ toJSON(): T[]
10
+ }
@@ -0,0 +1,28 @@
1
+ "use strict"
2
+ Object.defineProperty(exports, "__esModule", { value: true })
3
+ class ObjectRepository {
4
+ constructor(entities = {}) {
5
+ this.entityMap = new Map(Object.entries(entities))
6
+ }
7
+ findById(id) {
8
+ return this.entityMap.get(id)
9
+ }
10
+ findAll() {
11
+ return Array.from(this.entityMap.values())
12
+ }
13
+ upsertById(id, entity) {
14
+ return this.entityMap.set(id, { ...entity })
15
+ }
16
+ deleteById(id) {
17
+ return this.entityMap.delete(id)
18
+ }
19
+ count() {
20
+ return this.entityMap.size
21
+ }
22
+ toJSON() {
23
+ return this.findAll()
24
+ }
25
+ }
26
+ module.exports = {
27
+ ObjectRepository
28
+ }
@@ -0,0 +1,103 @@
1
+ import type { proto } from '../../WAProto'
2
+ import type { Contact } from './Contact'
3
+ import type { MinimalMessage } from './Message'
4
+ export type KeyPair = {
5
+ public: Uint8Array
6
+ private: Uint8Array
7
+ }
8
+ export type SignedKeyPair = {
9
+ keyPair: KeyPair
10
+ signature: Uint8Array
11
+ keyId: number
12
+ timestampS?: number
13
+ }
14
+ export type ProtocolAddress = {
15
+ name: string
16
+ deviceId: number
17
+ }
18
+ export type SignalIdentity = {
19
+ identifier: ProtocolAddress
20
+ identifierKey: Uint8Array
21
+ }
22
+ export type LTHashState = {
23
+ version: number
24
+ hash: Buffer
25
+ indexValueMap: {
26
+ [indexMacBase64: string]: {
27
+ valueMac: Uint8Array | Buffer
28
+ }
29
+ }
30
+ }
31
+ export type SignalCreds = {
32
+ readonly signedIdentityKey: KeyPair
33
+ readonly signedPreKey: SignedKeyPair
34
+ readonly registrationId: number
35
+ }
36
+ export type AccountSettings = {
37
+ /** unarchive chats when a new message is received */
38
+ unarchiveChats: boolean
39
+ /** the default mode to start new conversations with */
40
+ defaultDisappearingMode?: Pick<proto.IConversation, 'ephemeralExpiration' | 'ephemeralSettingTimestamp'>
41
+ }
42
+ export type AuthenticationCreds = SignalCreds & {
43
+ readonly noiseKey: KeyPair
44
+ readonly pairingEphemeralKeyPair: KeyPair
45
+ advSecretKey: string
46
+ me?: Contact
47
+ account?: proto.IADVSignedDeviceIdentity
48
+ signalIdentities?: SignalIdentity[]
49
+ myAppStateKeyId?: string
50
+ firstUnuploadedPreKeyId: number
51
+ nextPreKeyId: number
52
+ lastAccountSyncTimestamp?: number
53
+ platform?: string
54
+ processedHistoryMessages: MinimalMessage[]
55
+ /** number of times history & app state has been synced */
56
+ accountSyncCounter: number
57
+ accountSettings: AccountSettings
58
+ registered: boolean
59
+ pairingCode: string | undefined
60
+ lastPropHash: string | undefined
61
+ routingInfo: Buffer | undefined
62
+ }
63
+ export type SignalDataTypeMap = {
64
+ 'pre-key': KeyPair
65
+ 'session': Uint8Array
66
+ 'sender-key': Uint8Array
67
+ 'sender-key-memory': {
68
+ [jid: string]: boolean
69
+ }
70
+ 'app-state-sync-key': proto.Message.IAppStateSyncKeyData
71
+ 'app-state-sync-version': LTHashState
72
+ }
73
+ export type SignalDataSet = {
74
+ [T in keyof SignalDataTypeMap]?: {
75
+ [id: string]: SignalDataTypeMap[T] | null
76
+ }
77
+ }
78
+ type Awaitable<T> = T | Promise<T>
79
+ export type SignalKeyStore = {
80
+ get<T extends keyof SignalDataTypeMap>(type: T, ids: string[]): Awaitable<{
81
+ [id: string]: SignalDataTypeMap[T]
82
+ }>
83
+ set(data: SignalDataSet): Awaitable<void>
84
+ /** clear all the data in the store */
85
+ clear?(): Awaitable<void>
86
+ }
87
+ export type SignalKeyStoreWithTransaction = SignalKeyStore & {
88
+ isInTransaction: () => boolean
89
+ transaction<T>(exec: () => Promise<T>): Promise<T>
90
+ }
91
+ export type TransactionCapabilityOptions = {
92
+ maxCommitRetries: number
93
+ delayBetweenTriesMs: number
94
+ }
95
+ export type SignalAuthState = {
96
+ creds: SignalCreds
97
+ keys: SignalKeyStore | SignalKeyStoreWithTransaction
98
+ }
99
+ export type AuthenticationState = {
100
+ creds: AuthenticationCreds
101
+ keys: SignalKeyStore
102
+ }
103
+ export {}
@@ -0,0 +1,2 @@
1
+ "use strict"
2
+ Object.defineProperty(exports, "__esModule", { value: true })
@@ -0,0 +1,13 @@
1
+ export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate'
2
+ export type WACallEvent = {
3
+ chatId: string
4
+ from: string
5
+ isGroup?: boolean
6
+ groupJid?: string
7
+ id: string
8
+ date: Date
9
+ isVideo?: boolean
10
+ status: WACallUpdateType
11
+ offline: boolean
12
+ latencyMs?: number
13
+ }
@@ -0,0 +1,2 @@
1
+ "use strict"
2
+ Object.defineProperty(exports, "__esModule", { value: true })