@skycodee/baileys 8.0.4 → 8.0.6

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 (224) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +352 -520
  3. package/WAProto/index.js +558 -4154
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +13 -0
  10. package/lib/Signal/Group/group-session-builder.js +32 -0
  11. package/lib/Signal/Group/group_cipher.js +84 -0
  12. package/lib/Signal/Group/index.js +13 -0
  13. package/lib/Signal/Group/keyhelper.js +20 -0
  14. package/lib/Signal/Group/sender-chain-key.js +28 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-message.js +68 -0
  17. package/lib/Signal/Group/sender-key-name.js +52 -0
  18. package/lib/Signal/Group/sender-key-record.js +43 -0
  19. package/lib/Signal/Group/sender-key-state.js +86 -0
  20. package/lib/Signal/Group/sender-message-key.js +28 -0
  21. package/lib/Signal/libsignal.js +324 -0
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -0
  24. package/lib/Socket/Client/types.js +13 -0
  25. package/lib/Socket/Client/websocket.js +52 -0
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +377 -0
  28. package/lib/Socket/chats.js +885 -0
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +312 -0
  31. package/lib/Socket/index.js +16 -0
  32. package/lib/Socket/messages-recv.js +1163 -0
  33. package/lib/Socket/messages-send.js +1100 -0
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +247 -0
  36. package/lib/Socket/socket.js +820 -0
  37. package/lib/Store/index.js +6 -0
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +290 -0
  40. package/lib/Store/make-ordered-dictionary.js +79 -0
  41. package/lib/Store/object-repository.js +25 -0
  42. package/lib/Types/Auth.js +3 -0
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -0
  45. package/lib/Types/Chat.js +9 -0
  46. package/lib/Types/Contact.js +3 -0
  47. package/lib/Types/Events.js +3 -0
  48. package/lib/Types/GroupMetadata.js +3 -0
  49. package/lib/Types/Label.js +25 -0
  50. package/lib/Types/LabelAssociation.js +7 -0
  51. package/lib/Types/Message.js +12 -0
  52. package/lib/Types/Newsletter.js +33 -0
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -0
  55. package/lib/Types/Signal.js +3 -0
  56. package/lib/Types/Socket.js +4 -0
  57. package/lib/Types/State.js +11 -0
  58. package/lib/Types/USync.js +3 -0
  59. package/lib/Types/index.js +28 -0
  60. package/lib/Utils/auth-utils.js +219 -0
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +25 -0
  63. package/lib/Utils/business.js +233 -0
  64. package/lib/Utils/chat-utils.js +752 -0
  65. package/lib/Utils/crypto.js +130 -0
  66. package/lib/Utils/decode-wa-message.js +267 -0
  67. package/lib/Utils/event-buffer.js +528 -0
  68. package/lib/Utils/generics.js +355 -0
  69. package/lib/Utils/history.js +87 -0
  70. package/lib/Utils/index.js +21 -0
  71. package/lib/Utils/link-preview.js +81 -0
  72. package/lib/Utils/logger.js +5 -0
  73. package/lib/Utils/lt-hash.js +45 -0
  74. package/lib/Utils/make-mutex.js +36 -0
  75. package/lib/Utils/message-retry-manager.js +113 -0
  76. package/lib/Utils/messages-media.js +627 -0
  77. package/lib/Utils/messages.js +909 -0
  78. package/lib/Utils/noise-handler.js +144 -0
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +341 -0
  81. package/lib/Utils/signal.js +161 -0
  82. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  83. package/lib/Utils/validate-connection.js +200 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +240 -0
  86. package/lib/WABinary/encode.js +218 -0
  87. package/lib/WABinary/generic-utils.js +189 -0
  88. package/lib/WABinary/index.js +7 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +3 -0
  91. package/lib/WAM/BinaryInfo.js +11 -0
  92. package/lib/WAM/constants.js +22853 -0
  93. package/lib/WAM/encode.js +154 -0
  94. package/lib/WAM/index.js +5 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/index.js +6 -0
  102. package/lib/WAUSync/USyncQuery.js +90 -0
  103. package/lib/WAUSync/USyncUser.js +24 -0
  104. package/lib/WAUSync/index.js +5 -0
  105. package/lib/index.js +21 -0
  106. package/package.json +84 -57
  107. package/README.md +0 -1312
  108. package/WAProto/GenerateStatics.sh +0 -3
  109. package/WAProto/fix-imports.js +0 -81
  110. package/WAProto/index.d.ts +0 -14017
  111. package/engine-requirements.js +0 -10
  112. package/src/Defaults/baileys-version.json +0 -1
  113. package/src/Defaults/index.ts +0 -149
  114. package/src/Signal/Group/ciphertext-message.ts +0 -9
  115. package/src/Signal/Group/group-session-builder.ts +0 -56
  116. package/src/Signal/Group/group_cipher.ts +0 -117
  117. package/src/Signal/Group/index.ts +0 -11
  118. package/src/Signal/Group/keyhelper.ts +0 -28
  119. package/src/Signal/Group/sender-chain-key.ts +0 -34
  120. package/src/Signal/Group/sender-key-distribution-message.ts +0 -95
  121. package/src/Signal/Group/sender-key-message.ts +0 -96
  122. package/src/Signal/Group/sender-key-name.ts +0 -66
  123. package/src/Signal/Group/sender-key-record.ts +0 -69
  124. package/src/Signal/Group/sender-key-state.ts +0 -134
  125. package/src/Signal/Group/sender-message-key.ts +0 -36
  126. package/src/Signal/libsignal.ts +0 -521
  127. package/src/Signal/lid-mapping.ts +0 -328
  128. package/src/Socket/Client/index.ts +0 -2
  129. package/src/Socket/Client/types.ts +0 -22
  130. package/src/Socket/Client/websocket.ts +0 -63
  131. package/src/Socket/business.ts +0 -424
  132. package/src/Socket/chats.ts +0 -1272
  133. package/src/Socket/communities.ts +0 -477
  134. package/src/Socket/groups.ts +0 -361
  135. package/src/Socket/index.ts +0 -15
  136. package/src/Socket/messages-recv.ts +0 -1668
  137. package/src/Socket/messages-send.ts +0 -1296
  138. package/src/Socket/mex.ts +0 -58
  139. package/src/Socket/newsletter.ts +0 -229
  140. package/src/Socket/socket.ts +0 -1184
  141. package/src/Types/Auth.ts +0 -116
  142. package/src/Types/Bussines.ts +0 -20
  143. package/src/Types/Call.ts +0 -15
  144. package/src/Types/Chat.ts +0 -138
  145. package/src/Types/Contact.ts +0 -24
  146. package/src/Types/Events.ts +0 -159
  147. package/src/Types/GroupMetadata.ts +0 -70
  148. package/src/Types/Label.ts +0 -48
  149. package/src/Types/LabelAssociation.ts +0 -35
  150. package/src/Types/Message.ts +0 -380
  151. package/src/Types/Newsletter.ts +0 -98
  152. package/src/Types/Product.ts +0 -85
  153. package/src/Types/Signal.ts +0 -76
  154. package/src/Types/Socket.ts +0 -150
  155. package/src/Types/State.ts +0 -43
  156. package/src/Types/USync.ts +0 -27
  157. package/src/Types/globals.d.ts +0 -8
  158. package/src/Types/index.ts +0 -67
  159. package/src/Utils/auth-utils.ts +0 -368
  160. package/src/Utils/browser-utils.ts +0 -31
  161. package/src/Utils/business.ts +0 -286
  162. package/src/Utils/chat-utils.ts +0 -974
  163. package/src/Utils/crypto.ts +0 -147
  164. package/src/Utils/decode-wa-message.ts +0 -355
  165. package/src/Utils/event-buffer.ts +0 -692
  166. package/src/Utils/generics.ts +0 -474
  167. package/src/Utils/history.ts +0 -161
  168. package/src/Utils/identity-change-handler.ts +0 -83
  169. package/src/Utils/index.ts +0 -19
  170. package/src/Utils/link-preview.ts +0 -111
  171. package/src/Utils/logger.ts +0 -13
  172. package/src/Utils/lt-hash.ts +0 -8
  173. package/src/Utils/make-mutex.ts +0 -42
  174. package/src/Utils/message-retry-manager.ts +0 -295
  175. package/src/Utils/messages-media.ts +0 -984
  176. package/src/Utils/messages.ts +0 -1097
  177. package/src/Utils/noise-handler.ts +0 -268
  178. package/src/Utils/pre-key-manager.ts +0 -126
  179. package/src/Utils/process-message.ts +0 -670
  180. package/src/Utils/reporting-utils.ts +0 -344
  181. package/src/Utils/signal.ts +0 -214
  182. package/src/Utils/sync-action-utils.ts +0 -74
  183. package/src/Utils/tc-token-utils.ts +0 -34
  184. package/src/Utils/use-multi-file-auth-state.ts +0 -136
  185. package/src/Utils/validate-connection.ts +0 -253
  186. package/src/WABinary/constants.ts +0 -1305
  187. package/src/WABinary/decode.ts +0 -308
  188. package/src/WABinary/encode.ts +0 -258
  189. package/src/WABinary/generic-utils.ts +0 -141
  190. package/src/WABinary/index.ts +0 -5
  191. package/src/WABinary/jid-utils.ts +0 -128
  192. package/src/WABinary/types.ts +0 -17
  193. package/src/WAM/BinaryInfo.ts +0 -12
  194. package/src/WAM/constants.ts +0 -22889
  195. package/src/WAM/encode.ts +0 -169
  196. package/src/WAM/index.ts +0 -3
  197. package/src/WAUSync/Protocols/USyncContactProtocol.ts +0 -32
  198. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +0 -78
  199. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +0 -35
  200. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +0 -44
  201. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +0 -76
  202. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +0 -33
  203. package/src/WAUSync/Protocols/index.ts +0 -4
  204. package/src/WAUSync/USyncQuery.ts +0 -133
  205. package/src/WAUSync/USyncUser.ts +0 -32
  206. package/src/WAUSync/index.ts +0 -3
  207. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +0 -22
  208. package/src/__tests__/Signal/lid-mapping.test.ts +0 -47
  209. package/src/__tests__/Socket/identity-change-handling.test.ts +0 -207
  210. package/src/__tests__/TestUtils/session.ts +0 -47
  211. package/src/__tests__/Utils/generics.test.ts +0 -70
  212. package/src/__tests__/Utils/history.test.ts +0 -362
  213. package/src/__tests__/Utils/messages-media.test.ts +0 -405
  214. package/src/__tests__/Utils/noise-handler.test.ts +0 -339
  215. package/src/__tests__/Utils/process-message.test.ts +0 -138
  216. package/src/__tests__/Utils/process-sync-action.test.ts +0 -359
  217. package/src/__tests__/Utils/reporting-utils.test.ts +0 -160
  218. package/src/__tests__/Utils/signal.test.ts +0 -69
  219. package/src/__tests__/Utils/sync-action-utils.test.ts +0 -183
  220. package/src/__tests__/binary/connection-deadlock.test.ts +0 -54
  221. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +0 -60
  222. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +0 -644
  223. package/src/__tests__/proto-tojson-long.test.ts +0 -31
  224. package/src/index.ts +0 -13
@@ -1,974 +0,0 @@
1
- import { Boom } from '@hapi/boom'
2
- import { expandAppStateKeys } from 'whatsapp-rust-bridge'
3
- import { proto } from '../../WAProto/index.js'
4
- import type {
5
- BaileysEventEmitter,
6
- Chat,
7
- ChatModification,
8
- ChatMutation,
9
- ChatUpdate,
10
- Contact,
11
- InitialAppStateSyncOptions,
12
- LastMessageList,
13
- LTHashState,
14
- WAPatchCreate,
15
- WAPatchName
16
- } from '../Types'
17
- import {
18
- type ChatLabelAssociation,
19
- LabelAssociationType,
20
- type MessageLabelAssociation
21
- } from '../Types/LabelAssociation'
22
- import { type BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary'
23
- import { aesDecrypt, aesEncrypt, hmacSign } from './crypto'
24
- import { toNumber } from './generics'
25
- import type { ILogger } from './logger'
26
- import { LT_HASH_ANTI_TAMPERING } from './lt-hash'
27
- import { downloadContentFromMessage } from './messages-media'
28
- import { emitSyncActionResults, processContactAction } from './sync-action-utils'
29
-
30
- type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>
31
-
32
- export type ChatMutationMap = { [index: string]: ChatMutation }
33
-
34
- const mutationKeys = (keydata: Uint8Array) => {
35
- const keys = expandAppStateKeys(keydata)
36
- return {
37
- indexKey: keys.indexKey,
38
- valueEncryptionKey: keys.valueEncryptionKey,
39
- valueMacKey: keys.valueMacKey,
40
- snapshotMacKey: keys.snapshotMacKey,
41
- patchMacKey: keys.patchMacKey
42
- }
43
- }
44
-
45
- const generateMac = (
46
- operation: proto.SyncdMutation.SyncdOperation,
47
- data: Uint8Array,
48
- keyId: Uint8Array | string,
49
- key: Uint8Array
50
- ) => {
51
- const opByte = operation === proto.SyncdMutation.SyncdOperation.SET ? 0x01 : 0x02
52
- const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId
53
- const keyData = new Uint8Array(1 + keyIdBuffer.length)
54
- keyData[0] = opByte
55
- keyData.set(keyIdBuffer, 1)
56
-
57
- const last = new Uint8Array(8)
58
- last[7] = keyData.length
59
-
60
- const total = new Uint8Array(keyData.length + data.length + last.length)
61
- total.set(keyData, 0)
62
- total.set(data, keyData.length)
63
- total.set(last, keyData.length + data.length)
64
-
65
- const hmac = hmacSign(total, key, 'sha512')
66
- return hmac.subarray(0, 32)
67
- }
68
-
69
- const to64BitNetworkOrder = (e: number) => {
70
- const buff = Buffer.alloc(8)
71
- buff.writeUint32BE(e, 4)
72
- return buff
73
- }
74
-
75
- type Mac = { indexMac: Uint8Array; valueMac: Uint8Array; operation: proto.SyncdMutation.SyncdOperation }
76
-
77
- const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' | 'indexValueMap'>) => {
78
- indexValueMap = { ...indexValueMap }
79
- const addBuffs: Uint8Array[] = []
80
- const subBuffs: Uint8Array[] = []
81
-
82
- return {
83
- mix: ({ indexMac, valueMac, operation }: Mac) => {
84
- const indexMacBase64 = Buffer.from(indexMac).toString('base64')
85
- const prevOp = indexValueMap[indexMacBase64]
86
- if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
87
- if (!prevOp) {
88
- throw new Boom('tried remove, but no previous op', { data: { indexMac, valueMac } })
89
- }
90
-
91
- // remove from index value mac, since this mutation is erased
92
- delete indexValueMap[indexMacBase64]
93
- } else {
94
- addBuffs.push(valueMac)
95
- // add this index into the history map
96
- indexValueMap[indexMacBase64] = { valueMac }
97
- }
98
-
99
- if (prevOp) {
100
- subBuffs.push(prevOp.valueMac as Uint8Array)
101
- }
102
- },
103
- finish: () => {
104
- const result = LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs)
105
-
106
- return {
107
- hash: Buffer.from(result),
108
- indexValueMap
109
- }
110
- }
111
- }
112
- }
113
-
114
- const generateSnapshotMac = (lthash: Uint8Array, version: number, name: WAPatchName, key: Uint8Array) => {
115
- const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')])
116
- return hmacSign(total, key, 'sha256')
117
- }
118
-
119
- const generatePatchMac = (
120
- snapshotMac: Uint8Array,
121
- valueMacs: Uint8Array[],
122
- version: number,
123
- type: WAPatchName,
124
- key: Uint8Array
125
- ) => {
126
- const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')])
127
- return hmacSign(total, key)
128
- }
129
-
130
- export const newLTHashState = (): LTHashState => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} })
131
-
132
- export const encodeSyncdPatch = async (
133
- { type, index, syncAction, apiVersion, operation }: WAPatchCreate,
134
- myAppStateKeyId: string,
135
- state: LTHashState,
136
- getAppStateSyncKey: FetchAppStateSyncKey
137
- ) => {
138
- const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
139
- if (!key) {
140
- throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 })
141
- }
142
-
143
- const encKeyId = Buffer.from(myAppStateKeyId, 'base64')
144
-
145
- state = { ...state, indexValueMap: { ...state.indexValueMap } }
146
-
147
- const indexBuffer = Buffer.from(JSON.stringify(index))
148
- const dataProto = proto.SyncActionData.fromObject({
149
- index: indexBuffer,
150
- value: syncAction,
151
- padding: new Uint8Array(0),
152
- version: apiVersion
153
- })
154
- const encoded = proto.SyncActionData.encode(dataProto).finish()
155
-
156
- const keyValue = mutationKeys(key.keyData!)
157
-
158
- const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey)
159
- const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey)
160
- const indexMac = hmacSign(indexBuffer, keyValue.indexKey)
161
-
162
- // update LT hash
163
- const generator = makeLtHashGenerator(state)
164
- generator.mix({ indexMac, valueMac, operation })
165
- Object.assign(state, generator.finish())
166
-
167
- state.version += 1
168
-
169
- const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey)
170
-
171
- const patch: proto.ISyncdPatch = {
172
- patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
173
- snapshotMac: snapshotMac,
174
- keyId: { id: encKeyId },
175
- mutations: [
176
- {
177
- operation: operation,
178
- record: {
179
- index: {
180
- blob: indexMac
181
- },
182
- value: {
183
- blob: Buffer.concat([encValue, valueMac])
184
- },
185
- keyId: { id: encKeyId }
186
- }
187
- }
188
- ]
189
- }
190
-
191
- const base64Index = indexMac.toString('base64')
192
- state.indexValueMap[base64Index] = { valueMac }
193
-
194
- return { patch, state }
195
- }
196
-
197
- export const decodeSyncdMutations = async (
198
- msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[],
199
- initialState: LTHashState,
200
- getAppStateSyncKey: FetchAppStateSyncKey,
201
- onMutation: (mutation: ChatMutation) => void,
202
- validateMacs: boolean
203
- ) => {
204
- const ltGenerator = makeLtHashGenerator(initialState)
205
- const derivedKeyCache = new Map<string, ReturnType<typeof mutationKeys>>()
206
-
207
- // indexKey used to HMAC sign record.index.blob
208
- // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
209
- // the remaining record.value.blob[0:-32] is the mac, it the HMAC sign of key.keyId + decoded proto data + length of bytes in keyId
210
- for (const msgMutation of msgMutations) {
211
- // if it's a syncdmutation, get the operation property
212
- // otherwise, if it's only a record -- it'll be a SET mutation
213
- const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET
214
- const record =
215
- 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : (msgMutation as proto.ISyncdRecord)
216
-
217
- const key = await getKey(record.keyId!.id!)
218
- const content = record.value!.blob!
219
- const encContent = content.subarray(0, -32)
220
- const ogValueMac = content.subarray(-32)
221
- if (validateMacs) {
222
- const contentHmac = generateMac(operation!, encContent, record.keyId!.id!, key.valueMacKey)
223
- if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
224
- throw new Boom('HMAC content verification failed')
225
- }
226
- }
227
-
228
- const result = aesDecrypt(encContent, key.valueEncryptionKey)
229
- const syncAction = proto.SyncActionData.decode(result)
230
-
231
- if (validateMacs) {
232
- const hmac = hmacSign(syncAction.index!, key.indexKey)
233
- if (Buffer.compare(hmac, record.index!.blob!) !== 0) {
234
- throw new Boom('HMAC index verification failed')
235
- }
236
- }
237
-
238
- const indexStr = Buffer.from(syncAction.index!).toString()
239
- onMutation({ syncAction, index: JSON.parse(indexStr) })
240
-
241
- ltGenerator.mix({
242
- indexMac: record.index!.blob!,
243
- valueMac: ogValueMac,
244
- operation: operation!
245
- })
246
- }
247
-
248
- return ltGenerator.finish()
249
-
250
- async function getKey(keyId: Uint8Array) {
251
- const base64Key = Buffer.from(keyId).toString('base64')
252
-
253
- const cached = derivedKeyCache.get(base64Key)
254
- if (cached) {
255
- return cached
256
- }
257
-
258
- const keyEnc = await getAppStateSyncKey(base64Key)
259
- if (!keyEnc) {
260
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
261
- statusCode: 404,
262
- data: { msgMutations }
263
- })
264
- }
265
-
266
- const keys = mutationKeys(keyEnc.keyData!)
267
- derivedKeyCache.set(base64Key, keys)
268
- return keys
269
- }
270
- }
271
-
272
- export const decodeSyncdPatch = async (
273
- msg: proto.ISyncdPatch,
274
- name: WAPatchName,
275
- initialState: LTHashState,
276
- getAppStateSyncKey: FetchAppStateSyncKey,
277
- onMutation: (mutation: ChatMutation) => void,
278
- validateMacs: boolean
279
- ) => {
280
- if (validateMacs) {
281
- const base64Key = Buffer.from(msg.keyId!.id!).toString('base64')
282
- const mainKeyObj = await getAppStateSyncKey(base64Key)
283
- if (!mainKeyObj) {
284
- throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } })
285
- }
286
-
287
- const mainKey = mutationKeys(mainKeyObj.keyData!)
288
- const mutationmacs = msg.mutations!.map(mutation => mutation.record!.value!.blob!.slice(-32))
289
-
290
- const patchMac = generatePatchMac(
291
- msg.snapshotMac!,
292
- mutationmacs,
293
- toNumber(msg.version!.version),
294
- name,
295
- mainKey.patchMacKey
296
- )
297
- if (Buffer.compare(patchMac, msg.patchMac!) !== 0) {
298
- throw new Boom('Invalid patch mac')
299
- }
300
- }
301
-
302
- const result = await decodeSyncdMutations(msg.mutations!, initialState, getAppStateSyncKey, onMutation, validateMacs)
303
- return result
304
- }
305
-
306
- export const extractSyncdPatches = async (result: BinaryNode, options: RequestInit) => {
307
- const syncNode = getBinaryNodeChild(result, 'sync')
308
- const collectionNodes = getBinaryNodeChildren(syncNode, 'collection')
309
-
310
- const final = {} as {
311
- [T in WAPatchName]: { patches: proto.ISyncdPatch[]; hasMorePatches: boolean; snapshot?: proto.ISyncdSnapshot }
312
- }
313
- await Promise.all(
314
- collectionNodes.map(async collectionNode => {
315
- const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
316
-
317
- const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
318
- const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot')
319
-
320
- const syncds: proto.ISyncdPatch[] = []
321
- const name = collectionNode.attrs.name as WAPatchName
322
-
323
- const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
324
-
325
- let snapshot: proto.ISyncdSnapshot | undefined = undefined
326
- if (snapshotNode && !!snapshotNode.content) {
327
- if (!Buffer.isBuffer(snapshotNode)) {
328
- snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
329
- }
330
-
331
- const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content as Buffer)
332
- const data = await downloadExternalBlob(blobRef, options)
333
- snapshot = proto.SyncdSnapshot.decode(data)
334
- }
335
-
336
- for (let { content } of patches) {
337
- if (content) {
338
- if (!Buffer.isBuffer(content)) {
339
- content = Buffer.from(Object.values(content))
340
- }
341
-
342
- const syncd = proto.SyncdPatch.decode(content as Uint8Array)
343
- if (!syncd.version) {
344
- syncd.version = { version: +collectionNode.attrs.version! + 1 }
345
- }
346
-
347
- syncds.push(syncd)
348
- }
349
- }
350
-
351
- final[name] = { patches: syncds, hasMorePatches, snapshot }
352
- })
353
- )
354
-
355
- return final
356
- }
357
-
358
- export const downloadExternalBlob = async (blob: proto.IExternalBlobReference, options: RequestInit) => {
359
- const stream = await downloadContentFromMessage(blob, 'md-app-state', { options })
360
- const bufferArray: Buffer[] = []
361
- for await (const chunk of stream) {
362
- bufferArray.push(chunk)
363
- }
364
-
365
- return Buffer.concat(bufferArray)
366
- }
367
-
368
- export const downloadExternalPatch = async (blob: proto.IExternalBlobReference, options: RequestInit) => {
369
- const buffer = await downloadExternalBlob(blob, options)
370
- const syncData = proto.SyncdMutations.decode(buffer)
371
- return syncData
372
- }
373
-
374
- export const decodeSyncdSnapshot = async (
375
- name: WAPatchName,
376
- snapshot: proto.ISyncdSnapshot,
377
- getAppStateSyncKey: FetchAppStateSyncKey,
378
- minimumVersionNumber: number | undefined,
379
- validateMacs = true
380
- ) => {
381
- const newState = newLTHashState()
382
- newState.version = toNumber(snapshot.version!.version)
383
-
384
- const mutationMap: ChatMutationMap = {}
385
- const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber
386
-
387
- const { hash, indexValueMap } = await decodeSyncdMutations(
388
- snapshot.records!,
389
- newState,
390
- getAppStateSyncKey,
391
- areMutationsRequired
392
- ? mutation => {
393
- const index = mutation.syncAction.index?.toString()
394
- mutationMap[index!] = mutation
395
- }
396
- : () => {},
397
- validateMacs
398
- )
399
- newState.hash = hash
400
- newState.indexValueMap = indexValueMap
401
-
402
- if (validateMacs) {
403
- const base64Key = Buffer.from(snapshot.keyId!.id!).toString('base64')
404
- const keyEnc = await getAppStateSyncKey(base64Key)
405
- if (!keyEnc) {
406
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
407
- }
408
-
409
- const result = mutationKeys(keyEnc.keyData!)
410
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
411
- if (Buffer.compare(snapshot.mac!, computedSnapshotMac) !== 0) {
412
- throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`)
413
- }
414
- }
415
-
416
- return {
417
- state: newState,
418
- mutationMap
419
- }
420
- }
421
-
422
- export const decodePatches = async (
423
- name: WAPatchName,
424
- syncds: proto.ISyncdPatch[],
425
- initial: LTHashState,
426
- getAppStateSyncKey: FetchAppStateSyncKey,
427
- options: RequestInit,
428
- minimumVersionNumber?: number,
429
- logger?: ILogger,
430
- validateMacs = true
431
- ) => {
432
- const newState: LTHashState = {
433
- ...initial,
434
- indexValueMap: { ...initial.indexValueMap }
435
- }
436
-
437
- const mutationMap: ChatMutationMap = {}
438
-
439
- for (const syncd of syncds) {
440
- const { version, keyId, snapshotMac } = syncd
441
- if (syncd.externalMutations) {
442
- logger?.trace({ name, version }, 'downloading external patch')
443
- const ref = await downloadExternalPatch(syncd.externalMutations, options)
444
- logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch')
445
- syncd.mutations?.push(...ref.mutations)
446
- }
447
-
448
- const patchVersion = toNumber(version!.version)
449
-
450
- newState.version = patchVersion
451
- const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber
452
-
453
- const decodeResult = await decodeSyncdPatch(
454
- syncd,
455
- name,
456
- newState,
457
- getAppStateSyncKey,
458
- shouldMutate
459
- ? mutation => {
460
- const index = mutation.syncAction.index?.toString()
461
- mutationMap[index!] = mutation
462
- }
463
- : () => {},
464
- true
465
- )
466
-
467
- newState.hash = decodeResult.hash
468
- newState.indexValueMap = decodeResult.indexValueMap
469
-
470
- if (validateMacs) {
471
- const base64Key = Buffer.from(keyId!.id!).toString('base64')
472
- const keyEnc = await getAppStateSyncKey(base64Key)
473
- if (!keyEnc) {
474
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
475
- }
476
-
477
- const result = mutationKeys(keyEnc.keyData!)
478
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
479
- if (Buffer.compare(snapshotMac!, computedSnapshotMac) !== 0) {
480
- throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`)
481
- }
482
- }
483
-
484
- // clear memory used up by the mutations
485
- syncd.mutations = []
486
- }
487
-
488
- return { state: newState, mutationMap }
489
- }
490
-
491
- export const chatModificationToAppPatch = (mod: ChatModification, jid: string) => {
492
- const OP = proto.SyncdMutation.SyncdOperation
493
- const getMessageRange = (lastMessages: LastMessageList) => {
494
- let messageRange: proto.SyncActionValue.ISyncActionMessageRange
495
- if (Array.isArray(lastMessages)) {
496
- const lastMsg = lastMessages[lastMessages.length - 1]
497
- messageRange = {
498
- lastMessageTimestamp: lastMsg?.messageTimestamp,
499
- messages: lastMessages?.length
500
- ? lastMessages.map(m => {
501
- if (!m.key?.id || !m.key?.remoteJid) {
502
- throw new Boom('Incomplete key', { statusCode: 400, data: m })
503
- }
504
-
505
- if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
506
- throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m })
507
- }
508
-
509
- if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
510
- throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m })
511
- }
512
-
513
- if (m.key.participant) {
514
- m.key.participant = jidNormalizedUser(m.key.participant)
515
- }
516
-
517
- return m
518
- })
519
- : undefined
520
- }
521
- } else {
522
- messageRange = lastMessages
523
- }
524
-
525
- return messageRange
526
- }
527
-
528
- let patch: WAPatchCreate
529
- if ('mute' in mod) {
530
- patch = {
531
- syncAction: {
532
- muteAction: {
533
- muted: !!mod.mute,
534
- muteEndTimestamp: mod.mute || undefined
535
- }
536
- },
537
- index: ['mute', jid],
538
- type: 'regular_high',
539
- apiVersion: 2,
540
- operation: OP.SET
541
- }
542
- } else if ('archive' in mod) {
543
- patch = {
544
- syncAction: {
545
- archiveChatAction: {
546
- archived: !!mod.archive,
547
- messageRange: getMessageRange(mod.lastMessages)
548
- }
549
- },
550
- index: ['archive', jid],
551
- type: 'regular_low',
552
- apiVersion: 3,
553
- operation: OP.SET
554
- }
555
- } else if ('markRead' in mod) {
556
- patch = {
557
- syncAction: {
558
- markChatAsReadAction: {
559
- read: mod.markRead,
560
- messageRange: getMessageRange(mod.lastMessages)
561
- }
562
- },
563
- index: ['markChatAsRead', jid],
564
- type: 'regular_low',
565
- apiVersion: 3,
566
- operation: OP.SET
567
- }
568
- } else if ('deleteForMe' in mod) {
569
- const { timestamp, key, deleteMedia } = mod.deleteForMe
570
- patch = {
571
- syncAction: {
572
- deleteMessageForMeAction: {
573
- deleteMedia,
574
- messageTimestamp: timestamp
575
- }
576
- },
577
- index: ['deleteMessageForMe', jid, key.id!, key.fromMe ? '1' : '0', '0'],
578
- type: 'regular_high',
579
- apiVersion: 3,
580
- operation: OP.SET
581
- }
582
- } else if ('clear' in mod) {
583
- patch = {
584
- syncAction: {
585
- clearChatAction: {
586
- messageRange: getMessageRange(mod.lastMessages)
587
- }
588
- },
589
- index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
590
- type: 'regular_high',
591
- apiVersion: 6,
592
- operation: OP.SET
593
- }
594
- } else if ('pin' in mod) {
595
- patch = {
596
- syncAction: {
597
- pinAction: {
598
- pinned: !!mod.pin
599
- }
600
- },
601
- index: ['pin_v1', jid],
602
- type: 'regular_low',
603
- apiVersion: 5,
604
- operation: OP.SET
605
- }
606
- } else if ('contact' in mod) {
607
- patch = {
608
- syncAction: {
609
- contactAction: mod.contact || {}
610
- },
611
- index: ['contact', jid],
612
- type: 'critical_unblock_low',
613
- apiVersion: 2,
614
- operation: mod.contact ? OP.SET : OP.REMOVE
615
- }
616
- } else if ('disableLinkPreviews' in mod) {
617
- patch = {
618
- syncAction: {
619
- privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
620
- },
621
- index: ['setting_disableLinkPreviews'],
622
- type: 'regular',
623
- apiVersion: 8,
624
- operation: OP.SET
625
- }
626
- } else if ('star' in mod) {
627
- const key = mod.star.messages[0]!
628
- patch = {
629
- syncAction: {
630
- starAction: {
631
- starred: !!mod.star.star
632
- }
633
- },
634
- index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
635
- type: 'regular_low',
636
- apiVersion: 2,
637
- operation: OP.SET
638
- }
639
- } else if ('delete' in mod) {
640
- patch = {
641
- syncAction: {
642
- deleteChatAction: {
643
- messageRange: getMessageRange(mod.lastMessages)
644
- }
645
- },
646
- index: ['deleteChat', jid, '1'],
647
- type: 'regular_high',
648
- apiVersion: 6,
649
- operation: OP.SET
650
- }
651
- } else if ('pushNameSetting' in mod) {
652
- patch = {
653
- syncAction: {
654
- pushNameSetting: {
655
- name: mod.pushNameSetting
656
- }
657
- },
658
- index: ['setting_pushName'],
659
- type: 'critical_block',
660
- apiVersion: 1,
661
- operation: OP.SET
662
- }
663
- } else if ('quickReply' in mod) {
664
- patch = {
665
- syncAction: {
666
- quickReplyAction: {
667
- count: 0,
668
- deleted: mod.quickReply.deleted || false,
669
- keywords: [],
670
- message: mod.quickReply.message || '',
671
- shortcut: mod.quickReply.shortcut || ''
672
- }
673
- },
674
- index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
675
- type: 'regular',
676
- apiVersion: 2,
677
- operation: OP.SET
678
- }
679
- } else if ('addLabel' in mod) {
680
- patch = {
681
- syncAction: {
682
- labelEditAction: {
683
- name: mod.addLabel.name,
684
- color: mod.addLabel.color,
685
- predefinedId: mod.addLabel.predefinedId,
686
- deleted: mod.addLabel.deleted
687
- }
688
- },
689
- index: ['label_edit', mod.addLabel.id],
690
- type: 'regular',
691
- apiVersion: 3,
692
- operation: OP.SET
693
- }
694
- } else if ('addChatLabel' in mod) {
695
- patch = {
696
- syncAction: {
697
- labelAssociationAction: {
698
- labeled: true
699
- }
700
- },
701
- index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
702
- type: 'regular',
703
- apiVersion: 3,
704
- operation: OP.SET
705
- }
706
- } else if ('removeChatLabel' in mod) {
707
- patch = {
708
- syncAction: {
709
- labelAssociationAction: {
710
- labeled: false
711
- }
712
- },
713
- index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
714
- type: 'regular',
715
- apiVersion: 3,
716
- operation: OP.SET
717
- }
718
- } else if ('addMessageLabel' in mod) {
719
- patch = {
720
- syncAction: {
721
- labelAssociationAction: {
722
- labeled: true
723
- }
724
- },
725
- index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
726
- type: 'regular',
727
- apiVersion: 3,
728
- operation: OP.SET
729
- }
730
- } else if ('removeMessageLabel' in mod) {
731
- patch = {
732
- syncAction: {
733
- labelAssociationAction: {
734
- labeled: false
735
- }
736
- },
737
- index: [
738
- LabelAssociationType.Message,
739
- mod.removeMessageLabel.labelId,
740
- jid,
741
- mod.removeMessageLabel.messageId,
742
- '0',
743
- '0'
744
- ],
745
- type: 'regular',
746
- apiVersion: 3,
747
- operation: OP.SET
748
- }
749
- } else {
750
- throw new Boom('not supported')
751
- }
752
-
753
- patch.syncAction.timestamp = Date.now()
754
-
755
- return patch
756
- }
757
-
758
- export const processSyncAction = (
759
- syncAction: ChatMutation,
760
- ev: BaileysEventEmitter,
761
- me: Contact,
762
- initialSyncOpts?: InitialAppStateSyncOptions,
763
- logger?: ILogger
764
- ) => {
765
- const isInitialSync = !!initialSyncOpts
766
- const accountSettings = initialSyncOpts?.accountSettings
767
-
768
- logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action')
769
-
770
- const {
771
- syncAction: { value: action },
772
- index: [type, id, msgId, fromMe]
773
- } = syncAction
774
-
775
- if (action?.muteAction) {
776
- ev.emit('chats.update', [
777
- {
778
- id,
779
- muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
780
- conditional: getChatUpdateConditional(id!, undefined)
781
- }
782
- ])
783
- } else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
784
- // okay so we've to do some annoying computation here
785
- // when we're initially syncing the app state
786
- // there are a few cases we need to handle
787
- // 1. if the account unarchiveChats setting is true
788
- // a. if the chat is archived, and no further messages have been received -- simple, keep archived
789
- // b. if the chat was archived, and the user received messages from the other person afterwards
790
- // then the chat should be marked unarchved --
791
- // we compare the timestamp of latest message from the other person to determine this
792
- // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
793
- // it'll always take an app state action to mark in unarchived -- which we'll get anyway
794
- const archiveAction = action?.archiveChatAction
795
- const isArchived = archiveAction ? archiveAction.archived : type === 'archive'
796
- // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
797
- // // this only applies for the initial sync
798
- // if(isInitialSync && !isArchived) {
799
- // isArchived = false
800
- // }
801
-
802
- const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
803
- // logger?.debug({ chat: id, syncAction }, 'message range archive')
804
-
805
- ev.emit('chats.update', [
806
- {
807
- id,
808
- archived: isArchived,
809
- conditional: getChatUpdateConditional(id!, msgRange)
810
- }
811
- ])
812
- } else if (action?.markChatAsReadAction) {
813
- const markReadAction = action.markChatAsReadAction
814
- // basically we don't need to fire an "read" update if the chat is being marked as read
815
- // because the chat is read by default
816
- // this only applies for the initial sync
817
- const isNullUpdate = isInitialSync && markReadAction.read
818
-
819
- ev.emit('chats.update', [
820
- {
821
- id,
822
- unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
823
- conditional: getChatUpdateConditional(id!, markReadAction?.messageRange)
824
- }
825
- ])
826
- } else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
827
- ev.emit('messages.delete', {
828
- keys: [
829
- {
830
- remoteJid: id,
831
- id: msgId,
832
- fromMe: fromMe === '1'
833
- }
834
- ]
835
- })
836
- } else if (action?.contactAction) {
837
- const results = processContactAction(action.contactAction, id, logger)
838
- emitSyncActionResults(ev, results)
839
- } else if (action?.pushNameSetting) {
840
- const name = action?.pushNameSetting?.name
841
- if (name && me?.name !== name) {
842
- ev.emit('creds.update', { me: { ...me, name } })
843
- }
844
- } else if (action?.pinAction) {
845
- ev.emit('chats.update', [
846
- {
847
- id,
848
- pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
849
- conditional: getChatUpdateConditional(id!, undefined)
850
- }
851
- ])
852
- } else if (action?.unarchiveChatsSetting) {
853
- const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
854
- ev.emit('creds.update', { accountSettings: { unarchiveChats } })
855
-
856
- logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
857
- if (accountSettings) {
858
- accountSettings.unarchiveChats = unarchiveChats
859
- }
860
- } else if (action?.starAction || type === 'star') {
861
- let starred = action?.starAction?.starred
862
- if (typeof starred !== 'boolean') {
863
- starred = syncAction.index[syncAction.index.length - 1] === '1'
864
- }
865
-
866
- ev.emit('messages.update', [
867
- {
868
- key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
869
- update: { starred }
870
- }
871
- ])
872
- } else if (action?.deleteChatAction || type === 'deleteChat') {
873
- if (!isInitialSync) {
874
- ev.emit('chats.delete', [id!])
875
- }
876
- } else if (action?.labelEditAction) {
877
- const { name, color, deleted, predefinedId } = action.labelEditAction
878
-
879
- ev.emit('labels.edit', {
880
- id: id!,
881
- name: name!,
882
- color: color!,
883
- deleted: deleted!,
884
- predefinedId: predefinedId ? String(predefinedId) : undefined
885
- })
886
- } else if (action?.labelAssociationAction) {
887
- ev.emit('labels.association', {
888
- type: action.labelAssociationAction.labeled ? 'add' : 'remove',
889
- association:
890
- type === LabelAssociationType.Chat
891
- ? ({
892
- type: LabelAssociationType.Chat,
893
- chatId: syncAction.index[2],
894
- labelId: syncAction.index[1]
895
- } as ChatLabelAssociation)
896
- : ({
897
- type: LabelAssociationType.Message,
898
- chatId: syncAction.index[2],
899
- messageId: syncAction.index[3],
900
- labelId: syncAction.index[1]
901
- } as MessageLabelAssociation)
902
- })
903
- } else if (action?.localeSetting?.locale) {
904
- ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale })
905
- } else if (action?.timeFormatAction) {
906
- ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction })
907
- } else if (action?.pnForLidChatAction) {
908
- if (action.pnForLidChatAction.pnJid) {
909
- ev.emit('lid-mapping.update', { lid: id!, pn: action.pnForLidChatAction.pnJid })
910
- }
911
- } else if (action?.privacySettingRelayAllCalls) {
912
- ev.emit('settings.update', {
913
- setting: 'privacySettingRelayAllCalls',
914
- value: action.privacySettingRelayAllCalls
915
- })
916
- } else if (action?.statusPrivacy) {
917
- ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy })
918
- } else if (action?.lockChatAction) {
919
- ev.emit('chats.lock', { id: id!, locked: !!action.lockChatAction.locked })
920
- } else if (action?.privacySettingDisableLinkPreviewsAction) {
921
- ev.emit('settings.update', {
922
- setting: 'disableLinkPreviews',
923
- value: action.privacySettingDisableLinkPreviewsAction
924
- })
925
- } else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
926
- ev.emit('settings.update', {
927
- setting: 'notificationActivitySetting',
928
- value: action.notificationActivitySettingAction.notificationActivitySetting
929
- })
930
- } else if (action?.lidContactAction) {
931
- ev.emit('contacts.upsert', [
932
- {
933
- id: id!,
934
- name:
935
- action.lidContactAction.fullName ||
936
- action.lidContactAction.firstName ||
937
- action.lidContactAction.username ||
938
- undefined,
939
- lid: id!,
940
- phoneNumber: undefined
941
- }
942
- ])
943
- } else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
944
- ev.emit('settings.update', {
945
- setting: 'channelsPersonalisedRecommendation',
946
- value: action.privacySettingChannelsPersonalisedRecommendationAction
947
- })
948
- } else {
949
- logger?.debug({ syncAction, id }, 'unprocessable update')
950
- }
951
-
952
- function getChatUpdateConditional(
953
- id: string,
954
- msgRange: proto.SyncActionValue.ISyncActionMessageRange | null | undefined
955
- ): ChatUpdate['conditional'] {
956
- return isInitialSync
957
- ? data => {
958
- const chat = data.historySets.chats[id] || data.chatUpserts[id]
959
- if (chat) {
960
- return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
961
- }
962
- }
963
- : undefined
964
- }
965
-
966
- function isValidPatchBasedOnMessageRange(
967
- chat: Chat,
968
- msgRange: proto.SyncActionValue.ISyncActionMessageRange | null | undefined
969
- ) {
970
- const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
971
- const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
972
- return lastMsgTimestamp >= chatLastMsgTimestamp
973
- }
974
- }