@vinzsocket/baileys 2.8.10 → 2.8.30

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 (83) hide show
  1. package/lib/Defaults/index.js +75 -73
  2. package/lib/Signal/Group/ciphertext-message.js +9 -9
  3. package/lib/Signal/Group/group-session-builder.js +21 -21
  4. package/lib/Signal/Group/group_cipher.js +79 -81
  5. package/lib/Signal/Group/index.js +2 -2
  6. package/lib/Signal/Group/keyhelper.js +9 -9
  7. package/lib/Signal/Group/queue-job.js +43 -46
  8. package/lib/Signal/Group/sender-chain-key.js +24 -25
  9. package/lib/Signal/Group/sender-key-distribution-message.js +50 -58
  10. package/lib/Signal/Group/sender-key-message.js +55 -60
  11. package/lib/Signal/Group/sender-key-name.js +38 -39
  12. package/lib/Signal/Group/sender-key-record.js +39 -41
  13. package/lib/Signal/Group/sender-key-state.js +85 -89
  14. package/lib/Signal/Group/sender-message-key.js +22 -22
  15. package/lib/Signal/libsignal.js +387 -292
  16. package/lib/Signal/lid-mapping.js +98 -93
  17. package/lib/Socket/Client/types.js +6 -6
  18. package/lib/Socket/Client/websocket.js +44 -44
  19. package/lib/Socket/business.js +350 -365
  20. package/lib/Socket/chats.js +1019 -914
  21. package/lib/Socket/communities.js +454 -376
  22. package/lib/Socket/groups.js +378 -310
  23. package/lib/Socket/index.js +11 -11
  24. package/lib/Socket/messages-recv.js +1355 -1182
  25. package/lib/Socket/messages-send.js +1224 -1081
  26. package/lib/Socket/mex.js +40 -34
  27. package/lib/Socket/newsletter.js +212 -169
  28. package/lib/Socket/socket.js +896 -757
  29. package/lib/Store/index.js +1 -1
  30. package/lib/Store/make-cache-manager-store.js +75 -79
  31. package/lib/Store/make-in-memory-store.js +450 -389
  32. package/lib/Store/make-ordered-dictionary.js +73 -76
  33. package/lib/Store/object-repository.js +24 -22
  34. package/lib/Types/Chat.js +1 -7
  35. package/lib/Types/Label.js +20 -20
  36. package/lib/Types/LabelAssociation.js +2 -2
  37. package/lib/Types/Message.js +2 -2
  38. package/lib/Types/Newsletter.js +24 -24
  39. package/lib/Types/Socket.js +1 -1
  40. package/lib/Types/State.js +8 -8
  41. package/lib/Types/index.js +10 -10
  42. package/lib/Utils/auth-utils.js +408 -401
  43. package/lib/Utils/baileys-event-stream.js +44 -35
  44. package/lib/Utils/business.js +200 -197
  45. package/lib/Utils/chat-utils.js +775 -708
  46. package/lib/Utils/crypto.js +97 -85
  47. package/lib/Utils/decode-wa-message.js +240 -227
  48. package/lib/Utils/event-buffer.js +547 -518
  49. package/lib/Utils/extended-messages.js +250 -203
  50. package/lib/Utils/generics.js +300 -289
  51. package/lib/Utils/history.js +76 -69
  52. package/lib/Utils/lid-resolver.js +47 -42
  53. package/lib/Utils/link-preview.js +75 -65
  54. package/lib/Utils/logger.js +3 -1
  55. package/lib/Utils/lt-hash.js +38 -34
  56. package/lib/Utils/make-mutex.js +32 -34
  57. package/lib/Utils/mention.js +79 -86
  58. package/lib/Utils/message-retry-manager.js +148 -136
  59. package/lib/Utils/messages-media.js +652 -562
  60. package/lib/Utils/messages.js +753 -707
  61. package/lib/Utils/noise-handler.js +156 -135
  62. package/lib/Utils/process-message.js +404 -341
  63. package/lib/Utils/signal.js +180 -118
  64. package/lib/Utils/use-multi-file-auth-state.js +87 -91
  65. package/lib/Utils/validate-connection.js +167 -142
  66. package/lib/WABinary/constants.js +28 -1293
  67. package/lib/WABinary/decode.js +220 -218
  68. package/lib/WABinary/encode.js +199 -201
  69. package/lib/WABinary/generic-utils.js +80 -77
  70. package/lib/WABinary/jid-utils.js +41 -35
  71. package/lib/WAM/BinaryInfo.js +7 -7
  72. package/lib/WAM/constants.js +1 -15241
  73. package/lib/WAM/encode.js +124 -131
  74. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  75. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +51 -47
  76. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -22
  77. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -32
  78. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -19
  79. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -43
  80. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +17 -17
  81. package/lib/WAUSync/USyncQuery.js +82 -84
  82. package/lib/WAUSync/USyncUser.js +20 -20
  83. package/package.json +4 -2
@@ -5,66 +5,57 @@ import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUse
5
5
  import { aesDecryptGCM, hmacSign } from './crypto.js';
6
6
  import { toNumber } from './generics.js';
7
7
  import { downloadAndProcessHistorySyncNotification } from './history.js';
8
- const REAL_MSG_STUB_TYPES = new Set([
9
- WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
10
- WAMessageStubType.CALL_MISSED_GROUP_VOICE,
11
- WAMessageStubType.CALL_MISSED_VIDEO,
12
- WAMessageStubType.CALL_MISSED_VOICE
13
- ]);
8
+ const REAL_MSG_STUB_TYPES = new Set([WAMessageStubType.CALL_MISSED_GROUP_VIDEO, WAMessageStubType.CALL_MISSED_GROUP_VOICE, WAMessageStubType.CALL_MISSED_VIDEO, WAMessageStubType.CALL_MISSED_VOICE]);
14
9
  const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
15
10
  /** Cleans a received message to further processing */
16
11
  export const cleanMessage = (message, meId) => {
17
- // ensure remoteJid and participant doesn't have device or agent in it
18
- message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
19
- message.key.participant = message.key.participant ? jidNormalizedUser(message.key.participant) : undefined;
20
- const content = normalizeMessageContent(message.message);
21
- // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
22
- if (content?.reactionMessage) {
23
- normaliseKey(content.reactionMessage.key);
24
- }
25
- if (content?.pollUpdateMessage) {
26
- normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
27
- }
28
- function normaliseKey(msgKey) {
29
- // if the reaction is from another user
30
- // we've to correctly map the key to this user's perspective
31
- if (!message.key.fromMe) {
32
- // if the sender believed the message being reacted to is not from them
33
- // we've to correct the key to be from them, or some other participant
34
- msgKey.fromMe = !msgKey.fromMe
35
- ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId)
36
- : // if the message being reacted to, was from them
37
- // fromMe automatically becomes false
38
- false;
39
- // set the remoteJid to being the same as the chat the message came from
40
- msgKey.remoteJid = message.key.remoteJid;
41
- // set participant of the message
42
- msgKey.participant = msgKey.participant || message.key.participant;
43
- }
12
+ // ensure remoteJid and participant doesn't have device or agent in it
13
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
14
+ message.key.participant = message.key.participant ? jidNormalizedUser(message.key.participant) : undefined;
15
+ const content = normalizeMessageContent(message.message);
16
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
17
+ if (content?.reactionMessage) {
18
+ normaliseKey(content.reactionMessage.key);
19
+ }
20
+ if (content?.pollUpdateMessage) {
21
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
22
+ }
23
+ function normaliseKey(msgKey) {
24
+ // if the reaction is from another user
25
+ // we've to correctly map the key to this user's perspective
26
+ if (!message.key.fromMe) {
27
+ // if the sender believed the message being reacted to is not from them
28
+ // we've to correct the key to be from them, or some other participant
29
+ msgKey.fromMe = !msgKey.fromMe ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) :
30
+ // if the message being reacted to, was from them
31
+ // fromMe automatically becomes false
32
+ false;
33
+ // set the remoteJid to being the same as the chat the message came from
34
+ msgKey.remoteJid = message.key.remoteJid;
35
+ // set participant of the message
36
+ msgKey.participant = msgKey.participant || message.key.participant;
44
37
  }
38
+ }
45
39
  };
46
40
  export const isRealMessage = (message, meId) => {
47
- const normalizedContent = normalizeMessageContent(message.message);
48
- const hasSomeContent = !!getContentType(normalizedContent);
49
- return ((!!normalizedContent ||
50
- REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
51
- (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType) &&
52
- message.messageStubParameters?.some(p => areJidsSameUser(meId, p)))) &&
53
- hasSomeContent &&
54
- !normalizedContent?.protocolMessage &&
55
- !normalizedContent?.reactionMessage &&
56
- !normalizedContent?.pollUpdateMessage);
41
+ const normalizedContent = normalizeMessageContent(message.message);
42
+ const hasSomeContent = !!getContentType(normalizedContent);
43
+ return (!!normalizedContent || REAL_MSG_STUB_TYPES.has(message.messageStubType) || REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType) && message.messageStubParameters?.some(p => areJidsSameUser(meId, p))) && hasSomeContent && !normalizedContent?.protocolMessage && !normalizedContent?.reactionMessage && !normalizedContent?.pollUpdateMessage;
57
44
  };
58
- export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
45
+ export const shouldIncrementChatUnread = message => !message.key.fromMe && !message.messageStubType;
59
46
  /**
60
47
  * Get the ID of the chat from the given key.
61
48
  * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
62
49
  */
63
- export const getChatId = ({ remoteJid, participant, fromMe }) => {
64
- if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
65
- return participant;
66
- }
67
- return remoteJid;
50
+ export const getChatId = ({
51
+ remoteJid,
52
+ participant,
53
+ fromMe
54
+ }) => {
55
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
56
+ return participant;
57
+ }
58
+ return remoteJid;
68
59
  };
69
60
  /**
70
61
  * Decrypt a poll vote
@@ -72,308 +63,380 @@ export const getChatId = ({ remoteJid, participant, fromMe }) => {
72
63
  * @param ctx additional info about the poll required for decryption
73
64
  * @returns list of SHA256 options
74
65
  */
75
- export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
76
- const sign = Buffer.concat([
77
- toBinary(pollMsgId),
78
- toBinary(pollCreatorJid),
79
- toBinary(voterJid),
80
- toBinary('Poll Vote'),
81
- new Uint8Array([1])
82
- ]);
83
- const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
84
- const decKey = hmacSign(sign, key0, 'sha256');
85
- const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
86
- const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
87
- return proto.Message.PollVoteMessage.decode(decrypted);
88
- function toBinary(txt) {
89
- return Buffer.from(txt);
90
- }
66
+ export function decryptPollVote({
67
+ encPayload,
68
+ encIv
69
+ }, {
70
+ pollCreatorJid,
71
+ pollMsgId,
72
+ pollEncKey,
73
+ voterJid
74
+ }) {
75
+ const sign = Buffer.concat([toBinary(pollMsgId), toBinary(pollCreatorJid), toBinary(voterJid), toBinary('Poll Vote'), new Uint8Array([1])]);
76
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
77
+ const decKey = hmacSign(sign, key0, 'sha256');
78
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
79
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
80
+ return proto.Message.PollVoteMessage.decode(decrypted);
81
+ function toBinary(txt) {
82
+ return Buffer.from(txt);
83
+ }
91
84
  }
92
- const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options }) => {
93
- const meId = creds.me.id;
94
- const { accountSettings } = creds;
95
- const chat = { id: jidNormalizedUser(getChatId(message.key)) };
96
- const isRealMsg = isRealMessage(message, meId);
97
- if (isRealMsg) {
98
- chat.messages = [{ message }];
99
- chat.conversationTimestamp = toNumber(message.messageTimestamp);
100
- // only increment unread count if not CIPHERTEXT and from another person
101
- if (shouldIncrementChatUnread(message)) {
102
- chat.unreadCount = (chat.unreadCount || 0) + 1;
103
- }
85
+ const processMessage = async (message, {
86
+ shouldProcessHistoryMsg,
87
+ placeholderResendCache,
88
+ ev,
89
+ creds,
90
+ signalRepository,
91
+ keyStore,
92
+ logger,
93
+ options
94
+ }) => {
95
+ const meId = creds.me.id;
96
+ const {
97
+ accountSettings
98
+ } = creds;
99
+ const chat = {
100
+ id: jidNormalizedUser(getChatId(message.key))
101
+ };
102
+ const isRealMsg = isRealMessage(message, meId);
103
+ if (isRealMsg) {
104
+ chat.messages = [{
105
+ message
106
+ }];
107
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
108
+ // only increment unread count if not CIPHERTEXT and from another person
109
+ if (shouldIncrementChatUnread(message)) {
110
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
104
111
  }
105
- const content = normalizeMessageContent(message.message);
106
- // unarchive chat if it's a real message, or someone reacted to our message
107
- // and we've the unarchive chats setting on
108
- if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
109
- chat.archived = false;
110
- chat.readOnly = false;
111
- }
112
- const protocolMsg = content?.protocolMessage;
113
- if (protocolMsg) {
114
- switch (protocolMsg.type) {
115
- case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
116
- const histNotification = protocolMsg.historySyncNotification;
117
- const process = shouldProcessHistoryMsg;
118
- const isLatest = !creds.processedHistoryMessages?.length;
119
- logger?.info({
120
- histNotification,
121
- process,
122
- id: message.key.id,
123
- isLatest
124
- }, 'got history notification');
125
- if (process) {
126
- if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
127
- ev.emit('creds.update', {
128
- processedHistoryMessages: [
129
- ...(creds.processedHistoryMessages || []),
130
- { key: message.key, messageTimestamp: message.messageTimestamp }
131
- ]
132
- });
133
- }
134
- const data = await downloadAndProcessHistorySyncNotification(histNotification, options);
135
- ev.emit('messaging-history.set', {
136
- ...data,
137
- isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
138
- peerDataRequestSessionId: histNotification.peerDataRequestSessionId
139
- });
140
- }
141
- break;
142
- case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
143
- const keys = protocolMsg.appStateSyncKeyShare.keys;
144
- if (keys?.length) {
145
- let newAppStateSyncKeyId = '';
146
- await keyStore.transaction(async () => {
147
- const newKeys = [];
148
- for (const { keyData, keyId } of keys) {
149
- const strKeyId = Buffer.from(keyId.keyId).toString('base64');
150
- newKeys.push(strKeyId);
151
- await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
152
- newAppStateSyncKeyId = strKeyId;
153
- }
154
- logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
155
- }, meId);
156
- ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
157
- }
158
- else {
159
- logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
160
- }
161
- break;
162
- case proto.Message.ProtocolMessage.Type.REVOKE:
163
- ev.emit('messages.update', [
164
- {
165
- key: {
166
- ...message.key,
167
- id: protocolMsg.key.id
168
- },
169
- update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
170
- }
171
- ]);
172
- break;
173
- case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
174
- Object.assign(chat, {
175
- ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
176
- ephemeralExpiration: protocolMsg.ephemeralExpiration || null
177
- });
178
- break;
179
- case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
180
- const response = protocolMsg.peerDataOperationRequestResponseMessage;
181
- if (response) {
182
- placeholderResendCache?.del(response.stanzaId);
183
- // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
184
- const { peerDataOperationResult } = response;
185
- for (const result of peerDataOperationResult) {
186
- const { placeholderMessageResendResponse: retryResponse } = result;
187
- //eslint-disable-next-line max-depth
188
- if (retryResponse) {
189
- const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
190
- // wait till another upsert event is available, don't want it to be part of the PDO response message
191
- setTimeout(() => {
192
- ev.emit('messages.upsert', {
193
- messages: [webMessageInfo],
194
- type: 'notify',
195
- requestId: response.stanzaId
196
- });
197
- }, 500);
198
- }
199
- }
200
- }
201
- break;
202
- case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
203
- ev.emit('messages.update', [
204
- {
205
- // flip the sender / fromMe properties because they're in the perspective of the sender
206
- key: { ...message.key, id: protocolMsg.key?.id },
207
- update: {
208
- message: {
209
- editedMessage: {
210
- message: protocolMsg.editedMessage
211
- }
212
- },
213
- messageTimestamp: protocolMsg.timestampMs
214
- ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
215
- : message.messageTimestamp
216
- }
217
- }
218
- ]);
219
- break;
220
- case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
221
- const lidMappingStore = signalRepository.getLIDMappingStore();
222
- const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
223
- const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
224
- logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
225
- const pairs = [];
226
- for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
227
- const lid = latestLid || assignedLid;
228
- pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
112
+ }
113
+ const content = normalizeMessageContent(message.message);
114
+ // unarchive chat if it's a real message, or someone reacted to our message
115
+ // and we've the unarchive chats setting on
116
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
117
+ chat.archived = false;
118
+ chat.readOnly = false;
119
+ }
120
+ const protocolMsg = content?.protocolMessage;
121
+ if (protocolMsg) {
122
+ switch (protocolMsg.type) {
123
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
124
+ const histNotification = protocolMsg.historySyncNotification;
125
+ const process = shouldProcessHistoryMsg;
126
+ const isLatest = !creds.processedHistoryMessages?.length;
127
+ logger?.info({
128
+ histNotification,
129
+ process,
130
+ id: message.key.id,
131
+ isLatest
132
+ }, 'got history notification');
133
+ if (process) {
134
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
135
+ ev.emit('creds.update', {
136
+ processedHistoryMessages: [...(creds.processedHistoryMessages || []), {
137
+ key: message.key,
138
+ messageTimestamp: message.messageTimestamp
139
+ }]
140
+ });
141
+ }
142
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options);
143
+ ev.emit('messaging-history.set', {
144
+ ...data,
145
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
146
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
147
+ });
148
+ }
149
+ break;
150
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
151
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
152
+ if (keys?.length) {
153
+ let newAppStateSyncKeyId = '';
154
+ await keyStore.transaction(async () => {
155
+ const newKeys = [];
156
+ for (const {
157
+ keyData,
158
+ keyId
159
+ } of keys) {
160
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
161
+ newKeys.push(strKeyId);
162
+ await keyStore.set({
163
+ 'app-state-sync-key': {
164
+ [strKeyId]: keyData
229
165
  }
230
- await lidMappingStore.storeLIDPNMappings(pairs);
166
+ });
167
+ newAppStateSyncKeyId = strKeyId;
168
+ }
169
+ logger?.info({
170
+ newAppStateSyncKeyId,
171
+ newKeys
172
+ }, 'injecting new app state sync keys');
173
+ }, meId);
174
+ ev.emit('creds.update', {
175
+ myAppStateKeyId: newAppStateSyncKeyId
176
+ });
177
+ } else {
178
+ logger?.info({
179
+ protocolMsg
180
+ }, 'recv app state sync with 0 keys');
231
181
  }
232
- }
233
- else if (content?.reactionMessage) {
234
- const reaction = {
235
- ...content.reactionMessage,
182
+ break;
183
+ case proto.Message.ProtocolMessage.Type.REVOKE:
184
+ ev.emit('messages.update', [{
185
+ key: {
186
+ ...message.key,
187
+ id: protocolMsg.key.id
188
+ },
189
+ update: {
190
+ message: null,
191
+ messageStubType: WAMessageStubType.REVOKE,
236
192
  key: message.key
237
- };
238
- ev.emit('messages.reaction', [
239
- {
240
- reaction,
241
- key: content.reactionMessage?.key
193
+ }
194
+ }]);
195
+ break;
196
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
197
+ Object.assign(chat, {
198
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
199
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
200
+ });
201
+ break;
202
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
203
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
204
+ if (response) {
205
+ placeholderResendCache?.del(response.stanzaId);
206
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
207
+ const {
208
+ peerDataOperationResult
209
+ } = response;
210
+ for (const result of peerDataOperationResult) {
211
+ const {
212
+ placeholderMessageResendResponse: retryResponse
213
+ } = result;
214
+ //eslint-disable-next-line max-depth
215
+ if (retryResponse) {
216
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
217
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
218
+ setTimeout(() => {
219
+ ev.emit('messages.upsert', {
220
+ messages: [webMessageInfo],
221
+ type: 'notify',
222
+ requestId: response.stanzaId
223
+ });
224
+ }, 500);
242
225
  }
243
- ]);
226
+ }
227
+ }
228
+ break;
229
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
230
+ ev.emit('messages.update', [{
231
+ // flip the sender / fromMe properties because they're in the perspective of the sender
232
+ key: {
233
+ ...message.key,
234
+ id: protocolMsg.key?.id
235
+ },
236
+ update: {
237
+ message: {
238
+ editedMessage: {
239
+ message: protocolMsg.editedMessage
240
+ }
241
+ },
242
+ messageTimestamp: protocolMsg.timestampMs ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000) : message.messageTimestamp
243
+ }
244
+ }]);
245
+ break;
246
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
247
+ const lidMappingStore = signalRepository.getLIDMappingStore();
248
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
249
+ const {
250
+ pnToLidMappings,
251
+ chatDbMigrationTimestamp
252
+ } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
253
+ logger?.debug({
254
+ pnToLidMappings,
255
+ chatDbMigrationTimestamp
256
+ }, 'got lid mappings and chat db migration timestamp');
257
+ const pairs = [];
258
+ for (const {
259
+ pn,
260
+ latestLid,
261
+ assignedLid
262
+ } of pnToLidMappings) {
263
+ const lid = latestLid || assignedLid;
264
+ pairs.push({
265
+ lid: `${lid}@lid`,
266
+ pn: `${pn}@s.whatsapp.net`
267
+ });
268
+ }
269
+ await lidMappingStore.storeLIDPNMappings(pairs);
244
270
  }
245
- else if (message.messageStubType) {
246
- const jid = message.key?.remoteJid;
247
- //let actor = whatsappID (message.participant)
248
- let participants;
249
- const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action });
250
- const emitGroupUpdate = (update) => {
251
- ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }]);
252
- };
253
- const emitGroupRequestJoin = (participant, action, method) => {
254
- ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
255
- };
256
- const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid));
257
- switch (message.messageStubType) {
258
- case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
259
- participants = message.messageStubParameters || [];
260
- emitParticipantsUpdate('modify');
261
- break;
262
- case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
263
- case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
264
- participants = message.messageStubParameters || [];
265
- emitParticipantsUpdate('remove');
266
- // mark the chat read only if you left the group
267
- if (participantsIncludesMe()) {
268
- chat.readOnly = true;
269
- }
270
- break;
271
- case WAMessageStubType.GROUP_PARTICIPANT_ADD:
272
- case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
273
- case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
274
- participants = message.messageStubParameters || [];
275
- if (participantsIncludesMe()) {
276
- chat.readOnly = false;
277
- }
278
- emitParticipantsUpdate('add');
279
- break;
280
- case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
281
- participants = message.messageStubParameters || [];
282
- emitParticipantsUpdate('demote');
283
- break;
284
- case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
285
- participants = message.messageStubParameters || [];
286
- emitParticipantsUpdate('promote');
287
- break;
288
- case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
289
- const announceValue = message.messageStubParameters?.[0];
290
- emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
291
- break;
292
- case WAMessageStubType.GROUP_CHANGE_RESTRICT:
293
- const restrictValue = message.messageStubParameters?.[0];
294
- emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
295
- break;
296
- case WAMessageStubType.GROUP_CHANGE_SUBJECT:
297
- const name = message.messageStubParameters?.[0];
298
- chat.name = name;
299
- emitGroupUpdate({ subject: name });
300
- break;
301
- case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
302
- const description = message.messageStubParameters?.[0];
303
- chat.description = description;
304
- emitGroupUpdate({ desc: description });
305
- break;
306
- case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
307
- const code = message.messageStubParameters?.[0];
308
- emitGroupUpdate({ inviteCode: code });
309
- break;
310
- case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
311
- const memberAddValue = message.messageStubParameters?.[0];
312
- emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
313
- break;
314
- case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
315
- const approvalMode = message.messageStubParameters?.[0];
316
- emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
317
- break;
318
- case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
319
- const participant = message.messageStubParameters?.[0];
320
- const action = message.messageStubParameters?.[1];
321
- const method = message.messageStubParameters?.[2];
322
- emitGroupRequestJoin(participant, action, method);
323
- break;
271
+ } else if (content?.reactionMessage) {
272
+ const reaction = {
273
+ ...content.reactionMessage,
274
+ key: message.key
275
+ };
276
+ ev.emit('messages.reaction', [{
277
+ reaction,
278
+ key: content.reactionMessage?.key
279
+ }]);
280
+ } else if (message.messageStubType) {
281
+ const jid = message.key?.remoteJid;
282
+ //let actor = whatsappID (message.participant)
283
+ let participants;
284
+ const emitParticipantsUpdate = action => ev.emit('group-participants.update', {
285
+ id: jid,
286
+ author: message.participant,
287
+ participants,
288
+ action
289
+ });
290
+ const emitGroupUpdate = update => {
291
+ ev.emit('groups.update', [{
292
+ id: jid,
293
+ ...update,
294
+ author: message.participant ?? undefined
295
+ }]);
296
+ };
297
+ const emitGroupRequestJoin = (participant, action, method) => {
298
+ ev.emit('group.join-request', {
299
+ id: jid,
300
+ author: message.participant,
301
+ participant,
302
+ action,
303
+ method: method
304
+ });
305
+ };
306
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid));
307
+ switch (message.messageStubType) {
308
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
309
+ participants = message.messageStubParameters || [];
310
+ emitParticipantsUpdate('modify');
311
+ break;
312
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
313
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
314
+ participants = message.messageStubParameters || [];
315
+ emitParticipantsUpdate('remove');
316
+ // mark the chat read only if you left the group
317
+ if (participantsIncludesMe()) {
318
+ chat.readOnly = true;
324
319
  }
325
- } /* else if(content?.pollUpdateMessage) {
326
- const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
327
- // we need to fetch the poll creation message to get the poll enc key
328
- // TODO: make standalone, remove getMessage reference
329
- // TODO: Remove entirely
330
- const pollMsg = await getMessage(creationMsgKey)
331
- if(pollMsg) {
332
- const meIdNormalised = jidNormalizedUser(meId)
333
- const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
334
- const voterJid = getKeyAuthor(message.key, meIdNormalised)
335
- const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
336
-
337
- try {
338
- const voteMsg = decryptPollVote(
339
- content.pollUpdateMessage.vote!,
340
- {
341
- pollEncKey,
342
- pollCreatorJid,
343
- pollMsgId: creationMsgKey.id!,
344
- voterJid,
345
- }
346
- )
347
- ev.emit('messages.update', [
348
- {
349
- key: creationMsgKey,
350
- update: {
351
- pollUpdates: [
352
- {
353
- pollUpdateMessageKey: message.key,
354
- vote: voteMsg,
355
- senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
356
- }
357
- ]
358
- }
359
- }
360
- ])
361
- } catch(err) {
362
- logger?.warn(
363
- { err, creationMsgKey },
364
- 'failed to decrypt poll vote'
365
- )
366
- }
367
- } else {
368
- logger?.warn(
369
- { creationMsgKey },
370
- 'poll creation message not found, cannot decrypt update'
371
- )
320
+ break;
321
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
322
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
323
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
324
+ participants = message.messageStubParameters || [];
325
+ if (participantsIncludesMe()) {
326
+ chat.readOnly = false;
372
327
  }
373
- } */
374
- if (Object.keys(chat).length > 1) {
375
- ev.emit('chats.update', [chat]);
328
+ emitParticipantsUpdate('add');
329
+ break;
330
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
331
+ participants = message.messageStubParameters || [];
332
+ emitParticipantsUpdate('demote');
333
+ break;
334
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
335
+ participants = message.messageStubParameters || [];
336
+ emitParticipantsUpdate('promote');
337
+ break;
338
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
339
+ const announceValue = message.messageStubParameters?.[0];
340
+ emitGroupUpdate({
341
+ announce: announceValue === 'true' || announceValue === 'on'
342
+ });
343
+ break;
344
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
345
+ const restrictValue = message.messageStubParameters?.[0];
346
+ emitGroupUpdate({
347
+ restrict: restrictValue === 'true' || restrictValue === 'on'
348
+ });
349
+ break;
350
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
351
+ const name = message.messageStubParameters?.[0];
352
+ chat.name = name;
353
+ emitGroupUpdate({
354
+ subject: name
355
+ });
356
+ break;
357
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
358
+ const description = message.messageStubParameters?.[0];
359
+ chat.description = description;
360
+ emitGroupUpdate({
361
+ desc: description
362
+ });
363
+ break;
364
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
365
+ const code = message.messageStubParameters?.[0];
366
+ emitGroupUpdate({
367
+ inviteCode: code
368
+ });
369
+ break;
370
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
371
+ const memberAddValue = message.messageStubParameters?.[0];
372
+ emitGroupUpdate({
373
+ memberAddMode: memberAddValue === 'all_member_add'
374
+ });
375
+ break;
376
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
377
+ const approvalMode = message.messageStubParameters?.[0];
378
+ emitGroupUpdate({
379
+ joinApprovalMode: approvalMode === 'on'
380
+ });
381
+ break;
382
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
383
+ const participant = message.messageStubParameters?.[0];
384
+ const action = message.messageStubParameters?.[1];
385
+ const method = message.messageStubParameters?.[2];
386
+ emitGroupRequestJoin(participant, action, method);
387
+ break;
376
388
  }
389
+ } /* else if(content?.pollUpdateMessage) {
390
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
391
+ // we need to fetch the poll creation message to get the poll enc key
392
+ // TODO: make standalone, remove getMessage reference
393
+ // TODO: Remove entirely
394
+ const pollMsg = await getMessage(creationMsgKey)
395
+ if(pollMsg) {
396
+ const meIdNormalised = jidNormalizedUser(meId)
397
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
398
+ const voterJid = getKeyAuthor(message.key, meIdNormalised)
399
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
400
+ try {
401
+ const voteMsg = decryptPollVote(
402
+ content.pollUpdateMessage.vote!,
403
+ {
404
+ pollEncKey,
405
+ pollCreatorJid,
406
+ pollMsgId: creationMsgKey.id!,
407
+ voterJid,
408
+ }
409
+ )
410
+ ev.emit('messages.update', [
411
+ {
412
+ key: creationMsgKey,
413
+ update: {
414
+ pollUpdates: [
415
+ {
416
+ pollUpdateMessageKey: message.key,
417
+ vote: voteMsg,
418
+ senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
419
+ }
420
+ ]
421
+ }
422
+ }
423
+ ])
424
+ } catch(err) {
425
+ logger?.warn(
426
+ { err, creationMsgKey },
427
+ 'failed to decrypt poll vote'
428
+ )
429
+ }
430
+ } else {
431
+ logger?.warn(
432
+ { creationMsgKey },
433
+ 'poll creation message not found, cannot decrypt update'
434
+ )
435
+ }
436
+ } */
437
+ if (Object.keys(chat).length > 1) {
438
+ ev.emit('chats.update', [chat]);
439
+ }
377
440
  };
378
441
  export default processMessage;
379
442
  //# sourceMappingURL=process-message.js.map