gifted-baileys 1.5.6 → 1.5.7

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 (252) hide show
  1. package/README.md +9 -0
  2. package/WAProto/WAProto.proto +969 -88
  3. package/WAProto/index.d.ts +13199 -1260
  4. package/WAProto/index.js +124901 -74525
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.d.ts +284 -0
  7. package/{src → lib}/Defaults/index.js +7 -14
  8. package/lib/Signal/libsignal.d.ts +3 -0
  9. package/lib/Signal/libsignal.js +161 -0
  10. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  11. package/lib/Socket/Client/index.d.ts +2 -0
  12. package/{src → lib}/Socket/Client/index.js +2 -3
  13. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  14. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  15. package/lib/Socket/Client/types.d.ts +17 -0
  16. package/lib/Socket/Client/types.js +13 -0
  17. package/lib/Socket/Client/websocket.d.ts +12 -0
  18. package/lib/Socket/Client/websocket.js +62 -0
  19. package/lib/Socket/business.d.ts +170 -0
  20. package/{src → lib}/Socket/business.js +28 -33
  21. package/lib/Socket/chats.d.ts +81 -0
  22. package/{src → lib}/Socket/chats.js +174 -176
  23. package/lib/Socket/groups.d.ts +115 -0
  24. package/{src → lib}/Socket/groups.js +80 -68
  25. package/lib/Socket/index.d.ts +172 -0
  26. package/{src → lib}/Socket/index.js +4 -1
  27. package/lib/Socket/messages-recv.d.ts +158 -0
  28. package/{src → lib}/Socket/messages-recv.js +378 -211
  29. package/lib/Socket/messages-send.d.ts +155 -0
  30. package/{src → lib}/Socket/messages-send.js +452 -177
  31. package/lib/Socket/newsletter.d.ts +132 -0
  32. package/{src → lib}/Socket/newsletter.js +107 -98
  33. package/lib/Socket/registration.d.ts +264 -0
  34. package/{src → lib}/Socket/registration.js +56 -48
  35. package/lib/Socket/socket.d.ts +44 -0
  36. package/{src → lib}/Socket/socket.js +77 -77
  37. package/lib/Socket/usync.d.ts +37 -0
  38. package/lib/Socket/usync.js +70 -0
  39. package/lib/Store/index.d.ts +3 -0
  40. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  41. package/{src → lib}/Store/make-cache-manager-store.js +25 -34
  42. package/lib/Store/make-in-memory-store.d.ts +118 -0
  43. package/{src → lib}/Store/make-in-memory-store.js +36 -32
  44. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  45. package/lib/Store/object-repository.d.ts +10 -0
  46. package/{src → lib}/Store/object-repository.js +1 -1
  47. package/lib/Types/Auth.d.ts +109 -0
  48. package/lib/Types/Call.d.ts +13 -0
  49. package/lib/Types/Chat.d.ts +107 -0
  50. package/{src/Types/Contact.ts → lib/Types/Contact.d.ts} +8 -9
  51. package/lib/Types/Events.d.ts +172 -0
  52. package/lib/Types/GroupMetadata.d.ts +56 -0
  53. package/lib/Types/Label.d.ts +46 -0
  54. package/{src/Types/LabelAssociation.ts → lib/Types/LabelAssociation.d.ts} +16 -22
  55. package/lib/Types/Message.d.ts +433 -0
  56. package/lib/Types/Newsletter.d.ts +92 -0
  57. package/lib/Types/Product.d.ts +78 -0
  58. package/lib/Types/Signal.d.ts +57 -0
  59. package/{src/Types/Socket.ts → lib/Types/Socket.d.ts} +61 -68
  60. package/lib/Types/State.d.ts +27 -0
  61. package/lib/Types/USync.d.ts +25 -0
  62. package/lib/Types/index.d.ts +66 -0
  63. package/lib/Utils/auth-utils.d.ts +18 -0
  64. package/{src → lib}/Utils/auth-utils.js +73 -90
  65. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  66. package/lib/Utils/baileys-event-stream.js +63 -0
  67. package/lib/Utils/business.d.ts +22 -0
  68. package/{src → lib}/Utils/business.js +15 -43
  69. package/lib/Utils/chat-utils.d.ts +70 -0
  70. package/{src → lib}/Utils/chat-utils.js +87 -94
  71. package/lib/Utils/crypto.d.ts +40 -0
  72. package/{src → lib}/Utils/crypto.js +4 -2
  73. package/lib/Utils/decode-wa-message.d.ts +36 -0
  74. package/lib/Utils/decode-wa-message.js +226 -0
  75. package/lib/Utils/event-buffer.d.ts +35 -0
  76. package/{src → lib}/Utils/event-buffer.js +4 -13
  77. package/lib/Utils/generics.d.ts +88 -0
  78. package/{src → lib}/Utils/generics.js +67 -86
  79. package/lib/Utils/history.d.ts +19 -0
  80. package/{src → lib}/Utils/history.js +13 -39
  81. package/lib/Utils/index.d.ts +17 -0
  82. package/lib/Utils/link-preview.d.ts +21 -0
  83. package/{src → lib}/Utils/link-preview.js +17 -54
  84. package/lib/Utils/logger.d.ts +2 -0
  85. package/lib/Utils/lt-hash.d.ts +12 -0
  86. package/lib/Utils/make-mutex.d.ts +7 -0
  87. package/{src → lib}/Utils/make-mutex.js +4 -13
  88. package/lib/Utils/messages-media.d.ts +113 -0
  89. package/{src → lib}/Utils/messages-media.js +193 -255
  90. package/lib/Utils/messages.d.ts +77 -0
  91. package/{src → lib}/Utils/messages.js +588 -118
  92. package/lib/Utils/noise-handler.d.ts +20 -0
  93. package/lib/Utils/process-message.d.ts +41 -0
  94. package/{src → lib}/Utils/process-message.js +27 -30
  95. package/lib/Utils/signal.d.ts +33 -0
  96. package/{src → lib}/Utils/signal.js +25 -42
  97. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  98. package/{src → lib}/Utils/use-multi-file-auth-state.js +27 -28
  99. package/lib/Utils/validate-connection.d.ts +11 -0
  100. package/{src → lib}/Utils/validate-connection.js +40 -9
  101. package/lib/WABinary/constants.d.ts +27 -0
  102. package/lib/WABinary/decode.d.ts +6 -0
  103. package/lib/WABinary/encode.d.ts +2 -0
  104. package/{src → lib}/WABinary/encode.js +16 -10
  105. package/lib/WABinary/generic-utils.d.ts +14 -0
  106. package/lib/WABinary/index.d.ts +5 -0
  107. package/lib/WABinary/jid-utils.d.ts +31 -0
  108. package/lib/WABinary/types.d.ts +18 -0
  109. package/lib/WABinary/types.js +2 -0
  110. package/lib/WAM/BinaryInfo.d.ts +8 -0
  111. package/lib/WAM/constants.d.ts +38 -0
  112. package/lib/WAM/encode.d.ts +2 -0
  113. package/lib/WAM/index.d.ts +3 -0
  114. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  115. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  116. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  117. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  118. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  119. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  120. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  121. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  122. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  123. package/lib/WAUSync/Protocols/index.js +20 -0
  124. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  125. package/lib/WAUSync/USyncQuery.js +79 -0
  126. package/lib/WAUSync/USyncUser.d.ts +10 -0
  127. package/lib/WAUSync/USyncUser.js +22 -0
  128. package/lib/WAUSync/index.d.ts +3 -0
  129. package/lib/WAUSync/index.js +19 -0
  130. package/{src → lib}/index.js +1 -0
  131. package/package.json +26 -8
  132. package/LICENSE +0 -21
  133. package/src/Defaults/baileys-version.json +0 -3
  134. package/src/Defaults/index.ts +0 -131
  135. package/src/README.md +0 -1
  136. package/src/Signal/libsignal.js +0 -180
  137. package/src/Signal/libsignal.ts +0 -141
  138. package/src/Socket/Client/abstract-socket-client.ts +0 -19
  139. package/src/Socket/Client/index.ts +0 -3
  140. package/src/Socket/Client/mobile-socket-client.js +0 -78
  141. package/src/Socket/Client/mobile-socket-client.ts +0 -66
  142. package/src/Socket/Client/web-socket-client.js +0 -75
  143. package/src/Socket/Client/web-socket-client.ts +0 -57
  144. package/src/Socket/business.ts +0 -281
  145. package/src/Socket/chats.ts +0 -1030
  146. package/src/Socket/groups.ts +0 -356
  147. package/src/Socket/index.ts +0 -13
  148. package/src/Socket/messages-recv.ts +0 -985
  149. package/src/Socket/messages-send.ts +0 -871
  150. package/src/Socket/newsletter.ts +0 -282
  151. package/src/Socket/registration.ts +0 -250
  152. package/src/Socket/socket.ts +0 -777
  153. package/src/Store/index.ts +0 -3
  154. package/src/Store/make-cache-manager-store.ts +0 -100
  155. package/src/Store/make-in-memory-store.ts +0 -475
  156. package/src/Store/make-ordered-dictionary.ts +0 -86
  157. package/src/Store/object-repository.ts +0 -32
  158. package/src/Tests/test.app-state-sync.js +0 -204
  159. package/src/Tests/test.app-state-sync.ts +0 -207
  160. package/src/Tests/test.event-buffer.js +0 -270
  161. package/src/Tests/test.event-buffer.ts +0 -319
  162. package/src/Tests/test.key-store.js +0 -76
  163. package/src/Tests/test.key-store.ts +0 -92
  164. package/src/Tests/test.libsignal.js +0 -141
  165. package/src/Tests/test.libsignal.ts +0 -186
  166. package/src/Tests/test.media-download.js +0 -93
  167. package/src/Tests/test.media-download.ts +0 -76
  168. package/src/Tests/test.messages.js +0 -33
  169. package/src/Tests/test.messages.ts +0 -37
  170. package/src/Tests/utils.js +0 -34
  171. package/src/Tests/utils.ts +0 -36
  172. package/src/Types/Auth.ts +0 -113
  173. package/src/Types/Call.ts +0 -15
  174. package/src/Types/Chat.ts +0 -106
  175. package/src/Types/Events.ts +0 -93
  176. package/src/Types/GroupMetadata.ts +0 -53
  177. package/src/Types/Label.ts +0 -36
  178. package/src/Types/Message.ts +0 -288
  179. package/src/Types/Newsletter.ts +0 -98
  180. package/src/Types/Product.ts +0 -85
  181. package/src/Types/Signal.ts +0 -68
  182. package/src/Types/State.ts +0 -29
  183. package/src/Types/index.ts +0 -59
  184. package/src/Utils/auth-utils.ts +0 -222
  185. package/src/Utils/baileys-event-stream.js +0 -92
  186. package/src/Utils/baileys-event-stream.ts +0 -66
  187. package/src/Utils/business.ts +0 -275
  188. package/src/Utils/chat-utils.ts +0 -860
  189. package/src/Utils/crypto.ts +0 -131
  190. package/src/Utils/decode-wa-message.js +0 -211
  191. package/src/Utils/decode-wa-message.ts +0 -228
  192. package/src/Utils/event-buffer.ts +0 -613
  193. package/src/Utils/generics.ts +0 -434
  194. package/src/Utils/history.ts +0 -112
  195. package/src/Utils/index.ts +0 -17
  196. package/src/Utils/link-preview.ts +0 -122
  197. package/src/Utils/logger.ts +0 -3
  198. package/src/Utils/lt-hash.ts +0 -61
  199. package/src/Utils/make-mutex.ts +0 -44
  200. package/src/Utils/messages-media.ts +0 -847
  201. package/src/Utils/messages.ts +0 -956
  202. package/src/Utils/noise-handler.ts +0 -197
  203. package/src/Utils/process-message.ts +0 -414
  204. package/src/Utils/signal.ts +0 -177
  205. package/src/Utils/use-multi-file-auth-state.ts +0 -90
  206. package/src/Utils/validate-connection.ts +0 -238
  207. package/src/WABinary/constants.ts +0 -42
  208. package/src/WABinary/decode.ts +0 -265
  209. package/src/WABinary/encode.ts +0 -236
  210. package/src/WABinary/generic-utils.ts +0 -121
  211. package/src/WABinary/index.ts +0 -5
  212. package/src/WABinary/jid-utils.ts +0 -68
  213. package/src/WABinary/types.ts +0 -17
  214. package/src/WAM/BinaryInfo.ts +0 -12
  215. package/src/WAM/constants.ts +0 -15382
  216. package/src/WAM/encode.ts +0 -174
  217. package/src/WAM/index.ts +0 -3
  218. package/src/gifted +0 -1
  219. package/src/index.ts +0 -13
  220. /package/{src → lib}/Defaults/phonenumber-mcc.json +0 -0
  221. /package/{src → lib}/Socket/Client/abstract-socket-client.js +0 -0
  222. /package/{src → lib}/Store/index.js +0 -0
  223. /package/{src → lib}/Store/make-ordered-dictionary.js +0 -0
  224. /package/{src → lib}/Types/Auth.js +0 -0
  225. /package/{src → lib}/Types/Call.js +0 -0
  226. /package/{src → lib}/Types/Chat.js +0 -0
  227. /package/{src → lib}/Types/Contact.js +0 -0
  228. /package/{src → lib}/Types/Events.js +0 -0
  229. /package/{src → lib}/Types/GroupMetadata.js +0 -0
  230. /package/{src → lib}/Types/Label.js +0 -0
  231. /package/{src → lib}/Types/LabelAssociation.js +0 -0
  232. /package/{src → lib}/Types/Message.js +0 -0
  233. /package/{src → lib}/Types/Newsletter.js +0 -0
  234. /package/{src → lib}/Types/Product.js +0 -0
  235. /package/{src → lib}/Types/Signal.js +0 -0
  236. /package/{src → lib}/Types/Socket.js +0 -0
  237. /package/{src → lib}/Types/State.js +0 -0
  238. /package/{src/WABinary/types.js → lib/Types/USync.js} +0 -0
  239. /package/{src → lib}/Types/index.js +0 -0
  240. /package/{src → lib}/Utils/index.js +0 -0
  241. /package/{src → lib}/Utils/logger.js +0 -0
  242. /package/{src → lib}/Utils/lt-hash.js +0 -0
  243. /package/{src → lib}/Utils/noise-handler.js +0 -0
  244. /package/{src → lib}/WABinary/constants.js +0 -0
  245. /package/{src → lib}/WABinary/decode.js +0 -0
  246. /package/{src → lib}/WABinary/generic-utils.js +0 -0
  247. /package/{src → lib}/WABinary/index.js +0 -0
  248. /package/{src → lib}/WABinary/jid-utils.js +0 -0
  249. /package/{src → lib}/WAM/BinaryInfo.js +0 -0
  250. /package/{src → lib}/WAM/constants.js +0 -0
  251. /package/{src → lib}/WAM/encode.js +0 -0
  252. /package/{src → lib}/WAM/index.js +0 -0
@@ -1,613 +0,0 @@
1
- import EventEmitter from 'events'
2
- import { Logger } from 'pino'
3
- import { proto } from '../../WAProto'
4
- import { BaileysEvent, BaileysEventEmitter, BaileysEventMap, BufferedEventData, Chat, ChatUpdate, Contact, WAMessage, WAMessageStatus } from '../Types'
5
- import { trimUndefined } from './generics'
6
- import { updateMessageWithReaction, updateMessageWithReceipt } from './messages'
7
- import { isRealMessage, shouldIncrementChatUnread } from './process-message'
8
-
9
- const BUFFERABLE_EVENT = [
10
- 'messaging-history.set',
11
- 'chats.upsert',
12
- 'chats.update',
13
- 'chats.delete',
14
- 'contacts.upsert',
15
- 'contacts.update',
16
- 'messages.upsert',
17
- 'messages.update',
18
- 'messages.delete',
19
- 'messages.reaction',
20
- 'message-receipt.update',
21
- 'groups.update',
22
- ] as const
23
-
24
- type BufferableEvent = typeof BUFFERABLE_EVENT[number]
25
-
26
- /**
27
- * A map that contains a list of all events that have been triggered
28
- *
29
- * Note, this can contain different type of events
30
- * this can make processing events extremely efficient -- since everything
31
- * can be done in a single transaction
32
- */
33
- type BaileysEventData = Partial<BaileysEventMap>
34
-
35
- const BUFFERABLE_EVENT_SET = new Set<BaileysEvent>(BUFFERABLE_EVENT)
36
-
37
- type BaileysBufferableEventEmitter = BaileysEventEmitter & {
38
- /** Use to process events in a batch */
39
- process(handler: (events: BaileysEventData) => void | Promise<void>): (() => void)
40
- /**
41
- * starts buffering events, call flush() to release them
42
- * */
43
- buffer(): void
44
- /** buffers all events till the promise completes */
45
- createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>)
46
- /**
47
- * flushes all buffered events
48
- * @param force if true, will flush all data regardless of any pending buffers
49
- * @returns returns true if the flush actually happened, otherwise false
50
- */
51
- flush(force?: boolean): boolean
52
- /** is there an ongoing buffer */
53
- isBuffering(): boolean
54
- }
55
-
56
- /**
57
- * The event buffer logically consolidates different events into a single event
58
- * making the data processing more efficient.
59
- * @param ev the baileys event emitter
60
- */
61
- export const makeEventBuffer = (logger: Logger): BaileysBufferableEventEmitter => {
62
- const ev = new EventEmitter()
63
- const historyCache = new Set<string>()
64
-
65
- let data = makeBufferData()
66
- let buffersInProgress = 0
67
-
68
- // take the generic event and fire it as a baileys event
69
- ev.on('event', (map: BaileysEventData) => {
70
- for(const event in map) {
71
- ev.emit(event, map[event])
72
- }
73
- })
74
-
75
- function buffer() {
76
- buffersInProgress += 1
77
- }
78
-
79
- function flush(force = false) {
80
- // no buffer going on
81
- if(!buffersInProgress) {
82
- return false
83
- }
84
-
85
- if(!force) {
86
- // reduce the number of buffers in progress
87
- buffersInProgress -= 1
88
- // if there are still some buffers going on
89
- // then we don't flush now
90
- if(buffersInProgress) {
91
- return false
92
- }
93
- }
94
-
95
- const newData = makeBufferData()
96
- const chatUpdates = Object.values(data.chatUpdates)
97
- // gather the remaining conditional events so we re-queue them
98
- let conditionalChatUpdatesLeft = 0
99
- for(const update of chatUpdates) {
100
- if(update.conditional) {
101
- conditionalChatUpdatesLeft += 1
102
- newData.chatUpdates[update.id!] = update
103
- delete data.chatUpdates[update.id!]
104
- }
105
- }
106
-
107
- const consolidatedData = consolidateEvents(data)
108
- if(Object.keys(consolidatedData).length) {
109
- ev.emit('event', consolidatedData)
110
- }
111
-
112
- data = newData
113
-
114
- logger.trace(
115
- { conditionalChatUpdatesLeft },
116
- 'released buffered events'
117
- )
118
-
119
- return true
120
- }
121
-
122
- return {
123
- process(handler) {
124
- const listener = (map: BaileysEventData) => {
125
- handler(map)
126
- }
127
-
128
- ev.on('event', listener)
129
- return () => {
130
- ev.off('event', listener)
131
- }
132
- },
133
- emit<T extends BaileysEvent>(event: BaileysEvent, evData: BaileysEventMap[T]) {
134
- if(buffersInProgress && BUFFERABLE_EVENT_SET.has(event)) {
135
- append(data, historyCache, event as any, evData, logger)
136
- return true
137
- }
138
-
139
- return ev.emit('event', { [event]: evData })
140
- },
141
- isBuffering() {
142
- return buffersInProgress > 0
143
- },
144
- buffer,
145
- flush,
146
- createBufferedFunction(work) {
147
- return async(...args) => {
148
- buffer()
149
- try {
150
- const result = await work(...args)
151
- return result
152
- } finally {
153
- flush()
154
- }
155
- }
156
- },
157
- on: (...args) => ev.on(...args),
158
- off: (...args) => ev.off(...args),
159
- removeAllListeners: (...args) => ev.removeAllListeners(...args),
160
- }
161
- }
162
-
163
- const makeBufferData = (): BufferedEventData => {
164
- return {
165
- historySets: {
166
- chats: { },
167
- messages: { },
168
- contacts: { },
169
- isLatest: false,
170
- empty: true
171
- },
172
- chatUpserts: { },
173
- chatUpdates: { },
174
- chatDeletes: new Set(),
175
- contactUpserts: { },
176
- contactUpdates: { },
177
- messageUpserts: { },
178
- messageUpdates: { },
179
- messageReactions: { },
180
- messageDeletes: { },
181
- messageReceipts: { },
182
- groupUpdates: { }
183
- }
184
- }
185
-
186
- function append<E extends BufferableEvent>(
187
- data: BufferedEventData,
188
- historyCache: Set<string>,
189
- event: E,
190
- eventData: any,
191
- logger: Logger
192
- ) {
193
- switch (event) {
194
- case 'messaging-history.set':
195
- for(const chat of eventData.chats as Chat[]) {
196
- const existingChat = data.historySets.chats[chat.id]
197
- if(existingChat) {
198
- existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
199
- }
200
-
201
- if(!existingChat && !historyCache.has(chat.id)) {
202
- data.historySets.chats[chat.id] = chat
203
- historyCache.add(chat.id)
204
-
205
- absorbingChatUpdate(chat)
206
- }
207
- }
208
-
209
- for(const contact of eventData.contacts as Contact[]) {
210
- const existingContact = data.historySets.contacts[contact.id]
211
- if(existingContact) {
212
- Object.assign(existingContact, trimUndefined(contact))
213
- } else {
214
- const historyContactId = `c:${contact.id}`
215
- const hasAnyName = contact.notify || contact.name || contact.verifiedName
216
- if(!historyCache.has(historyContactId) || hasAnyName) {
217
- data.historySets.contacts[contact.id] = contact
218
- historyCache.add(historyContactId)
219
- }
220
- }
221
- }
222
-
223
- for(const message of eventData.messages as WAMessage[]) {
224
- const key = stringifyMessageKey(message.key)
225
- const existingMsg = data.historySets.messages[key]
226
- if(!existingMsg && !historyCache.has(key)) {
227
- data.historySets.messages[key] = message
228
- historyCache.add(key)
229
- }
230
- }
231
-
232
- data.historySets.empty = false
233
- data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest
234
-
235
- break
236
- case 'chats.upsert':
237
- for(const chat of eventData as Chat[]) {
238
- let upsert = data.chatUpserts[chat.id]
239
- if(!upsert) {
240
- upsert = data.historySets[chat.id]
241
- if(upsert) {
242
- logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set')
243
- }
244
- }
245
-
246
- if(upsert) {
247
- upsert = concatChats(upsert, chat)
248
- } else {
249
- upsert = chat
250
- data.chatUpserts[chat.id] = upsert
251
- }
252
-
253
- absorbingChatUpdate(upsert)
254
-
255
- if(data.chatDeletes.has(chat.id)) {
256
- data.chatDeletes.delete(chat.id)
257
- }
258
- }
259
-
260
- break
261
- case 'chats.update':
262
- for(const update of eventData as ChatUpdate[]) {
263
- const chatId = update.id!
264
- const conditionMatches = update.conditional ? update.conditional(data) : true
265
- if(conditionMatches) {
266
- delete update.conditional
267
-
268
- // if there is an existing upsert, merge the update into it
269
- const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
270
- if(upsert) {
271
- concatChats(upsert, update)
272
- } else {
273
- // merge the update into the existing update
274
- const chatUpdate = data.chatUpdates[chatId] || { }
275
- data.chatUpdates[chatId] = concatChats(chatUpdate, update)
276
- }
277
- } else if(conditionMatches === undefined) {
278
- // condition yet to be fulfilled
279
- data.chatUpdates[chatId] = update
280
- }
281
- // otherwise -- condition not met, update is invalid
282
-
283
- // if the chat has been updated
284
- // ignore any existing chat delete
285
- if(data.chatDeletes.has(chatId)) {
286
- data.chatDeletes.delete(chatId)
287
- }
288
- }
289
-
290
- break
291
- case 'chats.delete':
292
- for(const chatId of eventData as string[]) {
293
- if(!data.chatDeletes.has(chatId)) {
294
- data.chatDeletes.add(chatId)
295
- }
296
-
297
- // remove any prior updates & upserts
298
- if(data.chatUpdates[chatId]) {
299
- delete data.chatUpdates[chatId]
300
- }
301
-
302
- if(data.chatUpserts[chatId]) {
303
- delete data.chatUpserts[chatId]
304
-
305
- }
306
-
307
- if(data.historySets.chats[chatId]) {
308
- delete data.historySets.chats[chatId]
309
- }
310
- }
311
-
312
- break
313
- case 'contacts.upsert':
314
- for(const contact of eventData as Contact[]) {
315
- let upsert = data.contactUpserts[contact.id]
316
- if(!upsert) {
317
- upsert = data.historySets.contacts[contact.id]
318
- if(upsert) {
319
- logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set')
320
- }
321
- }
322
-
323
- if(upsert) {
324
- upsert = Object.assign(upsert, trimUndefined(contact))
325
- } else {
326
- upsert = contact
327
- data.contactUpserts[contact.id] = upsert
328
- }
329
-
330
- if(data.contactUpdates[contact.id]) {
331
- upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact))
332
- delete data.contactUpdates[contact.id]
333
- }
334
- }
335
-
336
- break
337
- case 'contacts.update':
338
- const contactUpdates = eventData as BaileysEventMap['contacts.update']
339
- for(const update of contactUpdates) {
340
- const id = update.id!
341
- // merge into prior upsert
342
- const upsert = data.historySets.contacts[id] || data.contactUpserts[id]
343
- if(upsert) {
344
- Object.assign(upsert, update)
345
- } else {
346
- // merge into prior update
347
- const contactUpdate = data.contactUpdates[id] || { }
348
- data.contactUpdates[id] = Object.assign(contactUpdate, update)
349
- }
350
- }
351
-
352
- break
353
- case 'messages.upsert':
354
- const { messages, type } = eventData as BaileysEventMap['messages.upsert']
355
- for(const message of messages) {
356
- const key = stringifyMessageKey(message.key)
357
- let existing = data.messageUpserts[key]?.message
358
- if(!existing) {
359
- existing = data.historySets.messages[key]
360
- if(existing) {
361
- logger.debug({ messageId: key }, 'absorbed message upsert in message set')
362
- }
363
- }
364
-
365
- if(existing) {
366
- message.messageTimestamp = existing.messageTimestamp
367
- }
368
-
369
- if(data.messageUpdates[key]) {
370
- logger.debug('absorbed prior message update in message upsert')
371
- Object.assign(message, data.messageUpdates[key].update)
372
- delete data.messageUpdates[key]
373
- }
374
-
375
- if(data.historySets.messages[key]) {
376
- data.historySets.messages[key] = message
377
- } else {
378
- data.messageUpserts[key] = {
379
- message,
380
- type: type === 'notify' || data.messageUpserts[key]?.type === 'notify'
381
- ? 'notify'
382
- : type
383
- }
384
- }
385
- }
386
-
387
- break
388
- case 'messages.update':
389
- const msgUpdates = eventData as BaileysEventMap['messages.update']
390
- for(const { key, update } of msgUpdates) {
391
- const keyStr = stringifyMessageKey(key)
392
- const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
393
- if(existing) {
394
- Object.assign(existing, update)
395
- // if the message was received & read by us
396
- // the chat counter must have been incremented
397
- // so we need to decrement it
398
- if(update.status === WAMessageStatus.READ && !key.fromMe) {
399
- decrementChatReadCounterIfMsgDidUnread(existing)
400
- }
401
- } else {
402
- const msgUpdate = data.messageUpdates[keyStr] || { key, update: { } }
403
- Object.assign(msgUpdate.update, update)
404
- data.messageUpdates[keyStr] = msgUpdate
405
- }
406
- }
407
-
408
- break
409
- case 'messages.delete':
410
- const deleteData = eventData as BaileysEventMap['messages.delete']
411
- if('keys' in deleteData) {
412
- const { keys } = deleteData
413
- for(const key of keys) {
414
- const keyStr = stringifyMessageKey(key)
415
- if(!data.messageDeletes[keyStr]) {
416
- data.messageDeletes[keyStr] = key
417
-
418
- }
419
-
420
- if(data.messageUpserts[keyStr]) {
421
- delete data.messageUpserts[keyStr]
422
- }
423
-
424
- if(data.messageUpdates[keyStr]) {
425
- delete data.messageUpdates[keyStr]
426
- }
427
- }
428
- } else {
429
- // TODO: add support
430
- }
431
-
432
- break
433
- case 'messages.reaction':
434
- const reactions = eventData as BaileysEventMap['messages.reaction']
435
- for(const { key, reaction } of reactions) {
436
- const keyStr = stringifyMessageKey(key)
437
- const existing = data.messageUpserts[keyStr]
438
- if(existing) {
439
- updateMessageWithReaction(existing.message, reaction)
440
- } else {
441
- data.messageReactions[keyStr] = data.messageReactions[keyStr]
442
- || { key, reactions: [] }
443
- updateMessageWithReaction(data.messageReactions[keyStr], reaction)
444
- }
445
- }
446
-
447
- break
448
- case 'message-receipt.update':
449
- const receipts = eventData as BaileysEventMap['message-receipt.update']
450
- for(const { key, receipt } of receipts) {
451
- const keyStr = stringifyMessageKey(key)
452
- const existing = data.messageUpserts[keyStr]
453
- if(existing) {
454
- updateMessageWithReceipt(existing.message, receipt)
455
- } else {
456
- data.messageReceipts[keyStr] = data.messageReceipts[keyStr]
457
- || { key, userReceipt: [] }
458
- updateMessageWithReceipt(data.messageReceipts[keyStr], receipt)
459
- }
460
- }
461
-
462
- break
463
- case 'groups.update':
464
- const groupUpdates = eventData as BaileysEventMap['groups.update']
465
- for(const update of groupUpdates) {
466
- const id = update.id!
467
- const groupUpdate = data.groupUpdates[id] || { }
468
- if(!data.groupUpdates[id]) {
469
- data.groupUpdates[id] = Object.assign(groupUpdate, update)
470
-
471
- }
472
- }
473
-
474
- break
475
- default:
476
- throw new Error(`"${event}" cannot be buffered`)
477
- }
478
-
479
- function absorbingChatUpdate(existing: Chat) {
480
- const chatId = existing.id
481
- const update = data.chatUpdates[chatId]
482
- if(update) {
483
- const conditionMatches = update.conditional ? update.conditional(data) : true
484
- if(conditionMatches) {
485
- delete update.conditional
486
- logger.debug({ chatId }, 'absorbed chat update in existing chat')
487
- Object.assign(existing, concatChats(update as Chat, existing))
488
- delete data.chatUpdates[chatId]
489
- } else if(conditionMatches === false) {
490
- logger.debug({ chatId }, 'chat update condition fail, removing')
491
- delete data.chatUpdates[chatId]
492
- }
493
- }
494
- }
495
-
496
- function decrementChatReadCounterIfMsgDidUnread(message: WAMessage) {
497
- // decrement chat unread counter
498
- // if the message has already been marked read by us
499
- const chatId = message.key.remoteJid!
500
- const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
501
- if(
502
- isRealMessage(message, '')
503
- && shouldIncrementChatUnread(message)
504
- && typeof chat?.unreadCount === 'number'
505
- && chat.unreadCount > 0
506
- ) {
507
- logger.debug({ chatId: chat.id }, 'decrementing chat counter')
508
- chat.unreadCount -= 1
509
- if(chat.unreadCount === 0) {
510
- delete chat.unreadCount
511
- }
512
- }
513
- }
514
- }
515
-
516
- function consolidateEvents(data: BufferedEventData) {
517
- const map: BaileysEventData = { }
518
-
519
- if(!data.historySets.empty) {
520
- map['messaging-history.set'] = {
521
- chats: Object.values(data.historySets.chats),
522
- messages: Object.values(data.historySets.messages),
523
- contacts: Object.values(data.historySets.contacts),
524
- isLatest: data.historySets.isLatest
525
- }
526
- }
527
-
528
- const chatUpsertList = Object.values(data.chatUpserts)
529
- if(chatUpsertList.length) {
530
- map['chats.upsert'] = chatUpsertList
531
- }
532
-
533
- const chatUpdateList = Object.values(data.chatUpdates)
534
- if(chatUpdateList.length) {
535
- map['chats.update'] = chatUpdateList
536
- }
537
-
538
- const chatDeleteList = Array.from(data.chatDeletes)
539
- if(chatDeleteList.length) {
540
- map['chats.delete'] = chatDeleteList
541
- }
542
-
543
- const messageUpsertList = Object.values(data.messageUpserts)
544
- if(messageUpsertList.length) {
545
- const type = messageUpsertList[0].type
546
- map['messages.upsert'] = {
547
- messages: messageUpsertList.map(m => m.message),
548
- type
549
- }
550
- }
551
-
552
- const messageUpdateList = Object.values(data.messageUpdates)
553
- if(messageUpdateList.length) {
554
- map['messages.update'] = messageUpdateList
555
- }
556
-
557
- const messageDeleteList = Object.values(data.messageDeletes)
558
- if(messageDeleteList.length) {
559
- map['messages.delete'] = { keys: messageDeleteList }
560
- }
561
-
562
- const messageReactionList = Object.values(data.messageReactions).flatMap(
563
- ({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction }))
564
- )
565
- if(messageReactionList.length) {
566
- map['messages.reaction'] = messageReactionList
567
- }
568
-
569
- const messageReceiptList = Object.values(data.messageReceipts).flatMap(
570
- ({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt }))
571
- )
572
- if(messageReceiptList.length) {
573
- map['message-receipt.update'] = messageReceiptList
574
- }
575
-
576
- const contactUpsertList = Object.values(data.contactUpserts)
577
- if(contactUpsertList.length) {
578
- map['contacts.upsert'] = contactUpsertList
579
- }
580
-
581
- const contactUpdateList = Object.values(data.contactUpdates)
582
- if(contactUpdateList.length) {
583
- map['contacts.update'] = contactUpdateList
584
- }
585
-
586
- const groupUpdateList = Object.values(data.groupUpdates)
587
- if(groupUpdateList.length) {
588
- map['groups.update'] = groupUpdateList
589
- }
590
-
591
- return map
592
- }
593
-
594
- function concatChats<C extends Partial<Chat>>(a: C, b: Partial<Chat>) {
595
- if(b.unreadCount === null) {
596
- // neutralize unread counter
597
- if(a.unreadCount! < 0) {
598
- a.unreadCount = undefined
599
- b.unreadCount = undefined
600
- }
601
- }
602
-
603
- if(typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
604
- b = { ...b }
605
- if(b.unreadCount! >= 0) {
606
- b.unreadCount = Math.max(b.unreadCount!, 0) + Math.max(a.unreadCount, 0)
607
- }
608
- }
609
-
610
- return Object.assign(a, b)
611
- }
612
-
613
- const stringifyMessageKey = (key: proto.IMessageKey) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`