@skyzopedia/baileys-mod 5.0.8 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/WAProto/index.js +133384 -57814
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.d.ts +53 -0
  5. package/lib/Defaults/index.js +141 -117
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +14 -12
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +42 -10
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +87 -75
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +52 -17
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +33 -27
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +63 -62
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +66 -65
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +44 -45
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +49 -39
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +93 -80
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/lib/Signal/Group/sender-message-key.js +28 -27
  33. package/lib/Signal/libsignal.d.ts +3 -0
  34. package/lib/Signal/libsignal.js +163 -313
  35. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  36. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +19 -4
  39. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  40. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  41. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  42. package/lib/Socket/Client/web-socket-client.js +62 -0
  43. package/lib/Socket/business.d.ts +171 -0
  44. package/lib/Socket/business.js +242 -359
  45. package/lib/Socket/chats.d.ts +267 -0
  46. package/lib/Socket/chats.js +935 -846
  47. package/lib/Socket/dugong.d.ts +254 -0
  48. package/lib/Socket/dugong.js +484 -0
  49. package/lib/Socket/groups.d.ts +115 -0
  50. package/lib/Socket/groups.js +309 -304
  51. package/lib/Socket/index.d.ts +173 -0
  52. package/lib/Socket/index.js +10 -15
  53. package/lib/Socket/messages-recv.d.ts +161 -0
  54. package/lib/Socket/messages-recv.js +1054 -1107
  55. package/lib/Socket/messages-send.d.ts +149 -0
  56. package/lib/Socket/messages-send.js +447 -706
  57. package/lib/Socket/newsletter.d.ts +134 -0
  58. package/lib/Socket/newsletter.js +314 -199
  59. package/lib/Socket/registration.d.ts +267 -0
  60. package/lib/Socket/registration.js +166 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +650 -777
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +70 -0
  65. package/lib/Store/index.d.ts +3 -0
  66. package/lib/Store/index.js +10 -6
  67. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  68. package/lib/Store/make-cache-manager-store.js +81 -73
  69. package/lib/Store/make-in-memory-store.d.ts +118 -0
  70. package/lib/Store/make-in-memory-store.js +423 -286
  71. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  72. package/lib/Store/make-ordered-dictionary.js +79 -77
  73. package/lib/Store/object-repository.d.ts +10 -0
  74. package/lib/Store/object-repository.js +26 -24
  75. package/lib/Types/Auth.d.ts +110 -0
  76. package/lib/Types/Auth.js +2 -3
  77. package/lib/Types/Call.d.ts +13 -0
  78. package/lib/Types/Call.js +2 -3
  79. package/lib/Types/Chat.d.ts +102 -0
  80. package/lib/Types/Chat.js +4 -9
  81. package/lib/Types/Contact.d.ts +19 -0
  82. package/lib/Types/Contact.js +2 -3
  83. package/lib/Types/Events.d.ts +157 -0
  84. package/lib/Types/Events.js +2 -3
  85. package/lib/Types/GroupMetadata.d.ts +55 -0
  86. package/lib/Types/GroupMetadata.js +2 -3
  87. package/lib/Types/Label.d.ts +35 -0
  88. package/lib/Types/Label.js +26 -24
  89. package/lib/Types/LabelAssociation.d.ts +29 -0
  90. package/lib/Types/LabelAssociation.js +8 -6
  91. package/lib/Types/Message.d.ts +273 -0
  92. package/lib/Types/Message.js +9 -12
  93. package/lib/Types/Newsletter.d.ts +103 -0
  94. package/lib/Types/Newsletter.js +38 -33
  95. package/lib/Types/Product.d.ts +78 -0
  96. package/lib/Types/Product.js +2 -3
  97. package/lib/Types/Signal.d.ts +57 -0
  98. package/lib/Types/Signal.js +2 -3
  99. package/lib/Types/Socket.d.ts +111 -0
  100. package/lib/Types/Socket.js +2 -4
  101. package/lib/Types/State.d.ts +27 -0
  102. package/lib/Types/State.js +2 -11
  103. package/lib/Types/USync.d.ts +25 -0
  104. package/lib/Types/USync.js +2 -3
  105. package/lib/Types/index.d.ts +57 -0
  106. package/lib/Types/index.js +41 -27
  107. package/lib/Utils/auth-utils.d.ts +18 -0
  108. package/lib/Utils/auth-utils.js +198 -211
  109. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  110. package/lib/Utils/baileys-event-stream.js +61 -42
  111. package/lib/Utils/business.d.ts +22 -0
  112. package/lib/Utils/business.js +214 -213
  113. package/lib/Utils/chat-utils.d.ts +71 -0
  114. package/lib/Utils/chat-utils.js +687 -710
  115. package/lib/Utils/crypto.d.ts +41 -0
  116. package/lib/Utils/crypto.js +133 -112
  117. package/lib/Utils/decode-wa-message.d.ts +19 -0
  118. package/lib/Utils/decode-wa-message.js +183 -252
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +496 -510
  121. package/lib/Utils/generics.d.ts +92 -0
  122. package/lib/Utils/generics.js +387 -319
  123. package/lib/Utils/history.d.ts +15 -0
  124. package/lib/Utils/history.js +92 -83
  125. package/lib/Utils/index.d.ts +17 -0
  126. package/lib/Utils/index.js +33 -21
  127. package/lib/Utils/link-preview.d.ts +21 -0
  128. package/lib/Utils/link-preview.js +83 -71
  129. package/lib/Utils/logger.d.ts +4 -0
  130. package/lib/Utils/logger.js +7 -5
  131. package/lib/Utils/lt-hash.d.ts +12 -0
  132. package/lib/Utils/lt-hash.js +46 -40
  133. package/lib/Utils/make-mutex.d.ts +7 -0
  134. package/lib/Utils/make-mutex.js +41 -34
  135. package/lib/Utils/messages-media.d.ts +116 -0
  136. package/lib/Utils/messages-media.js +768 -550
  137. package/lib/Utils/messages.d.ts +77 -0
  138. package/lib/Utils/messages.js +263 -362
  139. package/lib/Utils/noise-handler.d.ts +21 -0
  140. package/lib/Utils/noise-handler.js +149 -138
  141. package/lib/Utils/process-message.d.ts +41 -0
  142. package/lib/Utils/process-message.js +303 -323
  143. package/lib/Utils/signal.d.ts +32 -0
  144. package/lib/Utils/signal.js +141 -149
  145. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +103 -95
  147. package/lib/Utils/validate-connection.d.ts +11 -0
  148. package/lib/Utils/validate-connection.js +220 -183
  149. package/lib/WABinary/constants.d.ts +30 -0
  150. package/lib/WABinary/constants.js +35 -1298
  151. package/lib/WABinary/decode.d.ts +7 -0
  152. package/lib/WABinary/decode.js +249 -237
  153. package/lib/WABinary/encode.d.ts +3 -0
  154. package/lib/WABinary/encode.js +260 -213
  155. package/lib/WABinary/generic-utils.d.ts +17 -0
  156. package/lib/WABinary/generic-utils.js +65 -56
  157. package/lib/WABinary/index.d.ts +5 -0
  158. package/lib/WABinary/index.js +21 -7
  159. package/lib/WABinary/jid-utils.d.ts +31 -0
  160. package/lib/WABinary/jid-utils.js +58 -89
  161. package/lib/WABinary/types.d.ts +18 -0
  162. package/lib/WABinary/types.js +2 -3
  163. package/lib/WAM/BinaryInfo.d.ts +17 -0
  164. package/lib/WAM/BinaryInfo.js +12 -10
  165. package/lib/WAM/constants.d.ts +38 -0
  166. package/lib/WAM/constants.js +15348 -22851
  167. package/lib/WAM/encode.d.ts +3 -0
  168. package/lib/WAM/encode.js +136 -135
  169. package/lib/WAM/index.d.ts +3 -0
  170. package/lib/WAM/index.js +19 -5
  171. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  172. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -28
  173. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -49
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  176. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +28 -27
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  178. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -36
  179. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  180. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  181. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  182. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +20 -26
  183. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  184. package/lib/WAUSync/Protocols/index.js +20 -6
  185. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  186. package/lib/WAUSync/USyncQuery.js +85 -86
  187. package/lib/WAUSync/USyncUser.d.ts +12 -0
  188. package/lib/WAUSync/USyncUser.js +25 -23
  189. package/lib/WAUSync/index.d.ts +3 -0
  190. package/lib/WAUSync/index.js +19 -5
  191. package/lib/index.d.ts +12 -0
  192. package/lib/index.js +36 -24
  193. package/package.json +106 -98
  194. package/LICENSE +0 -21
  195. package/WAProto/WAProto.proto +0 -5311
  196. package/lib/KeyDB/BinarySearch.js +0 -20
  197. package/lib/KeyDB/KeyedDB.js +0 -167
  198. package/lib/KeyDB/index.js +0 -4
  199. package/lib/Signal/lid-mapping.js +0 -155
  200. package/lib/Socket/Client/types.js +0 -13
  201. package/lib/Socket/Client/websocket.js +0 -52
  202. package/lib/Socket/Client/websocket.js.bak +0 -53
  203. package/lib/Socket/communities.js +0 -413
  204. package/lib/Socket/mex.js +0 -45
  205. package/lib/Types/Bussines.js +0 -3
  206. package/lib/Types/Newsletter.js.bak +0 -33
  207. package/lib/Utils/browser-utils.js +0 -25
  208. package/lib/Utils/message-retry-manager.js +0 -113
  209. package/lib/Utils/messages.js.bak +0 -907
  210. package/lib/Utils/pre-key-manager.js +0 -85
@@ -1,92 +1,68 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { Boom } from '@hapi/boom';
3
- import { proto } from '../../WAProto/index.js';
4
- import crypto from "crypto";
5
- const randomBytes = crypto.randomBytes(32).toString("hex");
6
- import {
7
- DEFAULT_CACHE_TTLS,
8
- WA_DEFAULT_EPHEMERAL
9
- } from '../Defaults/index.js';
10
- import {
11
- aggregateMessageKeysNotFromMe,
12
- assertMediaContent,
13
- bindWaitForEvent,
14
- decryptMediaRetryData,
15
- encodeNewsletterMessage,
16
- encodeSignedDeviceIdentity,
17
- encodeWAMessage,
18
- encryptMediaRetryRequest,
19
- extractDeviceJids,
20
- generateMessageIDV2,
21
- generateParticipantHashV2,
22
- generateWAMessage,
23
- getStatusCodeForMediaRetry,
24
- getUrlFromDirectPath,
25
- getWAUploadToServer,
26
- MessageRetryManager,
27
- normalizeMessageContent,
28
- parseAndInjectE2ESessions,
29
- unixTimestampSeconds,
30
- generateWAMessageFromContent
31
- } from '../Utils/index.js';
32
- import {
33
- areJidsSameUser,
34
- getBinaryNodeChild,
35
- getBinaryNodeChildren,
36
- getAdditionalNode,
37
- getBinaryNodeFilter,
38
- isHostedLidUser,
39
- isHostedPnUser,
40
- isJidGroup,
41
- isLidUser,
42
- isPnUser,
43
- jidDecode,
44
- jidEncode,
45
- isJidNewsletter,
46
- jidNormalizedUser,
47
- S_WHATSAPP_NET
48
- } from '../WABinary/index.js';
49
- import { getUrlInfo } from '../Utils/link-preview.js';
50
- import { makeKeyedMutex } from '../Utils/make-mutex.js';
51
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
52
- import { makeNewsletterSocket } from './newsletter.js';
53
- export const makeMessagesSocket = (config) => {
54
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
55
- const sock = makeNewsletterSocket(config);
56
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
57
- const userDevicesCache = config.userDevicesCache ||
58
- new NodeCache({
59
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
60
- useClones: false
61
- });
62
- const peerSessionsCache = new NodeCache({
63
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const axios_1 = require("axios")
12
+ const Types_1 = require("../Types")
13
+ const Utils_1 = require("../Utils");
14
+ const link_preview_1 = require("../Utils/link-preview");
15
+ const WABinary_1 = require("../WABinary");
16
+ const newsletter_1 = require("./newsletter");
17
+ const WAUSync_1 = require("../WAUSync")
18
+ const kikyy = require('./dugong');
19
+ var ListType = WAProto_1.proto.Message.ListMessage.ListType;
20
+ const makeMessagesSocket = (config) => {
21
+ const {
22
+ logger,
23
+ linkPreviewImageThumbnailWidth,
24
+ generateHighQualityLinkPreview,
25
+ options: axiosOptions,
26
+ patchMessageBeforeSending
27
+ } = config;
28
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
29
+ const {
30
+ ev,
31
+ authState,
32
+ processingMutex,
33
+ signalRepository,
34
+ upsertMessage,
35
+ query,
36
+ fetchPrivacySettings,
37
+ generateMessageTag,
38
+ sendNode,
39
+ groupMetadata,
40
+ groupToggleEphemeral,
41
+ executeUSyncQuery
42
+ } = sock;
43
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
44
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
64
45
  useClones: false
65
46
  });
66
- // Initialize message retry manager if enabled
67
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
68
- // Prevent race conditions in Signal session encryption by user
69
- const encryptionMutex = makeKeyedMutex();
70
47
  let mediaConn;
71
48
  const refreshMediaConn = async (forceGet = false) => {
72
49
  const media = await mediaConn;
73
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
50
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
74
51
  mediaConn = (async () => {
75
52
  const result = await query({
76
53
  tag: 'iq',
77
54
  attrs: {
78
55
  type: 'set',
79
56
  xmlns: 'w:m',
80
- to: S_WHATSAPP_NET
57
+ to: WABinary_1.S_WHATSAPP_NET,
81
58
  },
82
59
  content: [{ tag: 'media_conn', attrs: {} }]
83
60
  });
84
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
85
- // TODO: explore full length of data that whatsapp provides
61
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
86
62
  const node = {
87
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
63
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
88
64
  hostname: attrs.hostname,
89
- maxContentLengthBytes: +attrs.maxContentLengthBytes
65
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
90
66
  })),
91
67
  auth: mediaConnNode.attrs.auth,
92
68
  ttl: +mediaConnNode.attrs.ttl,
@@ -103,20 +79,17 @@ export const makeMessagesSocket = (config) => {
103
79
  * used for receipts of phone call, read, delivery etc.
104
80
  * */
105
81
  const sendReceipt = async (jid, participant, messageIds, type) => {
106
- if (!messageIds || messageIds.length === 0) {
107
- throw new Boom('missing ids in receipt');
108
- }
109
82
  const node = {
110
83
  tag: 'receipt',
111
84
  attrs: {
112
- id: messageIds[0]
113
- }
85
+ id: messageIds[0],
86
+ },
114
87
  };
115
88
  const isReadReceipt = type === 'read' || type === 'read-self';
116
89
  if (isReadReceipt) {
117
- node.attrs.t = unixTimestampSeconds().toString();
90
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
118
91
  }
119
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
92
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
120
93
  node.attrs.recipient = jid;
121
94
  node.attrs.to = participant;
122
95
  }
@@ -127,7 +100,7 @@ export const makeMessagesSocket = (config) => {
127
100
  }
128
101
  }
129
102
  if (type) {
130
- node.attrs.type = type;
103
+ node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
131
104
  }
132
105
  const remainingMessageIds = messageIds.slice(1);
133
106
  if (remainingMessageIds.length) {
@@ -147,7 +120,7 @@ export const makeMessagesSocket = (config) => {
147
120
  };
148
121
  /** Correctly bulk send receipts to multiple chats, participants */
149
122
  const sendReceipts = async (keys, type) => {
150
- const recps = aggregateMessageKeysNotFromMe(keys);
123
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
151
124
  for (const { jid, participant, messageIds } of recps) {
152
125
  await sendReceipt(jid, participant, messageIds, type);
153
126
  }
@@ -161,349 +134,207 @@ export const makeMessagesSocket = (config) => {
161
134
  };
162
135
  /** Fetch all the devices we've to send a message to */
163
136
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
164
- const deviceResults = [];
137
+ const deviceResults = []
138
+
165
139
  if (!useCache) {
166
- logger.debug('not using cache for devices');
167
- }
168
- const toFetch = [];
169
- const jidsWithUser = jids
170
- .map(jid => {
171
- const decoded = jidDecode(jid);
172
- const user = decoded?.user;
173
- const device = decoded?.device;
174
- const isExplicitDevice = typeof device === 'number' && device >= 0;
175
- if (isExplicitDevice && user) {
176
- deviceResults.push({
177
- user,
178
- device,
179
- jid
180
- });
181
- return null;
182
- }
183
- jid = jidNormalizedUser(jid);
184
- return { jid, user };
185
- })
186
- .filter(jid => jid !== null);
187
- let mgetDevices;
188
- if (useCache && userDevicesCache.mget) {
189
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
190
- mgetDevices = await userDevicesCache.mget(usersToFetch);
140
+ logger.debug('not using cache for devices')
191
141
  }
192
- for (const { jid, user } of jidsWithUser) {
142
+
143
+ const toFetch = []
144
+
145
+ jids = Array.from(new Set(jids))
146
+
147
+ for (let jid of jids) {
148
+ const user = WABinary_1.jidDecode(jid)?.user
149
+
150
+ jid = WABinary_1.jidNormalizedUser(jid)
151
+
193
152
  if (useCache) {
194
- const devices = mgetDevices?.[user] ||
195
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
153
+ const devices = userDevicesCache.get(user)
154
+
196
155
  if (devices) {
197
- const devicesWithJid = devices.map(d => ({
198
- ...d,
199
- jid: jidEncode(d.user, d.server, d.device)
200
- }));
201
- deviceResults.push(...devicesWithJid);
202
- logger.trace({ user }, 'using cache for devices');
156
+ deviceResults.push(...devices)
157
+ logger.trace({ user }, 'using cache for devices')
203
158
  }
159
+
204
160
  else {
205
- toFetch.push(jid);
161
+ toFetch.push(jid)
206
162
  }
207
163
  }
164
+
208
165
  else {
209
- toFetch.push(jid);
166
+ toFetch.push(jid)
210
167
  }
211
168
  }
169
+
212
170
  if (!toFetch.length) {
213
- return deviceResults;
214
- }
215
- const requestedLidUsers = new Set();
216
- for (const jid of toFetch) {
217
- if (isLidUser(jid) || isHostedLidUser(jid)) {
218
- const user = jidDecode(jid)?.user;
219
- if (user)
220
- requestedLidUsers.add(user);
221
- }
171
+ return deviceResults
222
172
  }
223
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
173
+
174
+ const query = new WAUSync_1.USyncQuery()
175
+ .withContext('message')
176
+ .withDeviceProtocol()
177
+
224
178
  for (const jid of toFetch) {
225
- query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
179
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
226
180
  }
227
- const result = await sock.executeUSyncQuery(query);
181
+
182
+ const result = await executeUSyncQuery(query)
183
+
228
184
  if (result) {
229
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
230
- const lidResults = result.list.filter(a => !!a.lid);
231
- if (lidResults.length > 0) {
232
- logger.trace('Storing LID maps from device call');
233
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
234
- }
235
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
236
- const deviceMap = {};
185
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
186
+ const deviceMap = {}
187
+
237
188
  for (const item of extracted) {
238
- deviceMap[item.user] = deviceMap[item.user] || [];
239
- deviceMap[item.user]?.push(item);
189
+ deviceMap[item.user] = deviceMap[item.user] || []
190
+ deviceMap[item.user].push(item)
191
+ deviceResults.push(item)
240
192
  }
241
- // Process each user's devices as a group for bulk LID migration
242
- for (const [user, userDevices] of Object.entries(deviceMap)) {
243
- const isLidUser = requestedLidUsers.has(user);
244
- // Process all devices for this user
245
- for (const item of userDevices) {
246
- const finalJid = isLidUser
247
- ? jidEncode(user, item.server, item.device)
248
- : jidEncode(item.user, item.server, item.device);
249
- deviceResults.push({
250
- ...item,
251
- jid: finalJid
252
- });
253
- logger.debug({
254
- user: item.user,
255
- device: item.device,
256
- finalJid,
257
- usedLid: isLidUser
258
- }, 'Processed device with LID priority');
259
- }
260
- }
261
- if (userDevicesCache.mset) {
262
- // if the cache supports mset, we can set all devices in one go
263
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
264
- }
265
- else {
266
- for (const key in deviceMap) {
267
- if (deviceMap[key])
268
- await userDevicesCache.set(key, deviceMap[key]);
269
- }
270
- }
271
- const userDeviceUpdates = {};
272
- for (const [userId, devices] of Object.entries(deviceMap)) {
273
- if (devices && devices.length > 0) {
274
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
275
- }
276
- }
277
- if (Object.keys(userDeviceUpdates).length > 0) {
278
- try {
279
- await authState.keys.set({ 'device-list': userDeviceUpdates });
280
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
281
- }
282
- catch (error) {
283
- logger.warn({ error }, 'failed to store user device lists');
284
- }
193
+
194
+ for (const key in deviceMap) {
195
+ userDevicesCache.set(key, deviceMap[key])
285
196
  }
286
197
  }
287
- return deviceResults;
288
- };
289
- const assertSessions = async (jids) => {
198
+
199
+ return deviceResults
200
+ }
201
+ const assertSessions = async (jids, force) => {
290
202
  let didFetchNewSession = false;
291
- const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
292
- const jidsRequiringFetch = [];
293
- logger.debug({ jids }, 'assertSessions call with jids');
294
- // Check peerSessionsCache and validate sessions using libsignal loadSession
295
- for (const jid of uniqueJids) {
296
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
297
- const cachedSession = peerSessionsCache.get(signalId);
298
- if (cachedSession !== undefined) {
299
- if (cachedSession) {
300
- continue; // Session exists in cache
301
- }
302
- }
303
- else {
304
- const sessionValidation = await signalRepository.validateSession(jid);
305
- const hasSession = sessionValidation.exists;
306
- peerSessionsCache.set(signalId, hasSession);
307
- if (hasSession) {
308
- continue;
203
+ let jidsRequiringFetch = [];
204
+ if (force) {
205
+ jidsRequiringFetch = jids;
206
+ }
207
+ else {
208
+ const addrs = jids.map(jid => (signalRepository
209
+ .jidToSignalProtocolAddress(jid)));
210
+ const sessions = await authState.keys.get('session', addrs);
211
+ for (const jid of jids) {
212
+ const signalId = signalRepository
213
+ .jidToSignalProtocolAddress(jid);
214
+ if (!sessions[signalId]) {
215
+ jidsRequiringFetch.push(jid);
309
216
  }
310
217
  }
311
- jidsRequiringFetch.push(jid);
312
218
  }
313
219
  if (jidsRequiringFetch.length) {
314
- // LID if mapped, otherwise original
315
- const wireJids = [
316
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
317
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
318
- ];
319
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
220
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
320
221
  const result = await query({
321
222
  tag: 'iq',
322
223
  attrs: {
323
224
  xmlns: 'encrypt',
324
225
  type: 'get',
325
- to: S_WHATSAPP_NET
226
+ to: WABinary_1.S_WHATSAPP_NET,
326
227
  },
327
228
  content: [
328
229
  {
329
230
  tag: 'key',
330
231
  attrs: {},
331
- content: wireJids.map(jid => ({
232
+ content: jidsRequiringFetch.map(jid => ({
332
233
  tag: 'user',
333
- attrs: { jid }
234
+ attrs: { jid },
334
235
  }))
335
236
  }
336
237
  ]
337
238
  });
338
- await parseAndInjectE2ESessions(result, signalRepository);
239
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
339
240
  didFetchNewSession = true;
340
- // Cache fetched sessions using wire JIDs
341
- for (const wireJid of wireJids) {
342
- const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
343
- peerSessionsCache.set(signalId, true);
344
- }
345
241
  }
346
242
  return didFetchNewSession;
347
243
  };
244
+
245
+
348
246
  const sendPeerDataOperationMessage = async (pdoMessage) => {
349
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
350
247
  if (!authState.creds.me?.id) {
351
- throw new Boom('Not authenticated');
248
+ throw new boom_1.Boom('Not authenticated')
352
249
  }
250
+
353
251
  const protocolMessage = {
354
252
  protocolMessage: {
355
253
  peerDataOperationRequestMessage: pdoMessage,
356
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
254
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
357
255
  }
358
256
  };
359
- const meJid = jidNormalizedUser(authState.creds.me.id);
257
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
360
258
  const msgId = await relayMessage(meJid, protocolMessage, {
361
259
  additionalAttributes: {
362
260
  category: 'peer',
363
- push_priority: 'high_force'
261
+ // eslint-disable-next-line camelcase
262
+ push_priority: 'high_force',
364
263
  },
365
- additionalNodes: [
366
- {
367
- tag: 'meta',
368
- attrs: { appdata: 'default' }
369
- }
370
- ]
371
264
  });
372
265
  return msgId;
373
266
  };
374
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
375
- if (!recipientJids.length) {
376
- return { nodes: [], shouldIncludeDeviceIdentity: false };
377
- }
378
- const patched = await patchMessageBeforeSending(message, recipientJids);
379
- const patchedMessages = Array.isArray(patched)
380
- ? patched
381
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
267
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
268
+ const patched = await patchMessageBeforeSending(message, jids);
269
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
382
270
  let shouldIncludeDeviceIdentity = false;
383
- const meId = authState.creds.me.id;
384
- const meLid = authState.creds.me?.lid;
385
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
386
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
387
- if (!jid)
388
- return null;
389
- let msgToEncrypt = patchedMessage;
390
- if (dsmMessage) {
391
- const { user: targetUser } = jidDecode(jid);
392
- const { user: ownPnUser } = jidDecode(meId);
393
- const ownLidUser = meLidUser;
394
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
395
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
396
- if (isOwnUser && !isExactSenderDevice) {
397
- msgToEncrypt = dsmMessage;
398
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
399
- }
400
- }
401
- const bytes = encodeWAMessage(msgToEncrypt);
402
- const mutexKey = jid;
403
- const node = await encryptionMutex.mutex(mutexKey, async () => {
404
- const { type, ciphertext } = await signalRepository.encryptMessage({
405
- jid,
406
- data: bytes
407
- });
408
- if (type === 'pkmsg') {
409
- shouldIncludeDeviceIdentity = true;
410
- }
411
- return {
412
- tag: 'to',
413
- attrs: { jid },
414
- content: [
415
- {
416
- tag: 'enc',
417
- attrs: {
418
- v: '2',
419
- type,
420
- ...(extraAttrs || {})
421
- },
422
- content: ciphertext
423
- }
424
- ]
425
- };
426
- });
271
+ const nodes = await Promise.all(jids.map(async (jid) => {
272
+ const { type, ciphertext } = await signalRepository
273
+ .encryptMessage({ jid, data: bytes });
274
+ if (type === 'pkmsg') {
275
+ shouldIncludeDeviceIdentity = true;
276
+ }
277
+ const node = {
278
+ tag: 'to',
279
+ attrs: { jid },
280
+ content: [{
281
+ tag: 'enc',
282
+ attrs: {
283
+ v: '2',
284
+ type,
285
+ ...extraAttrs || {}
286
+ },
287
+ content: ciphertext
288
+ }]
289
+ };
427
290
  return node;
428
- });
429
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
291
+ }));
430
292
  return { nodes, shouldIncludeDeviceIdentity };
431
- };
432
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
433
- // let shouldIncludeDeviceIdentity = false;
434
- let didPushAdditional = false
293
+ }; //apela
294
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = false }) => {
435
295
  const meId = authState.creds.me.id;
436
- const meLid = authState.creds.me?.lid;
437
- const isRetryResend = Boolean(participant?.jid);
438
- let shouldIncludeDeviceIdentity = isRetryResend;
296
+ let shouldIncludeDeviceIdentity = false;
297
+ let didPushAdditional = false
298
+ const { user, server } = WABinary_1.jidDecode(jid);
439
299
  const statusJid = 'status@broadcast';
440
- const { user, server } = jidDecode(jid);
441
300
  const isGroup = server === 'g.us';
442
301
  const isStatus = jid === statusJid;
443
302
  const isLid = server === 'lid';
444
- const isNewsletter = server === 'newsletter';
445
303
  const isPrivate = server === 's.whatsapp.net'
446
- const finalJid = jid;
447
- msgId = msgId || generateMessageIDV2(meId);
304
+ const isNewsletter = server === 'newsletter';
305
+ msgId = msgId || (0, Utils_1.generateMessageID)();
448
306
  useUserDevicesCache = useUserDevicesCache !== false;
449
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
307
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
450
308
  const participants = [];
451
- const destinationJid = !isStatus ? finalJid : statusJid;
309
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
452
310
  const binaryNodeContent = [];
453
311
  const devices = [];
454
312
  const meMsg = {
455
313
  deviceSentMessage: {
456
314
  destinationJid,
457
315
  message
458
- },
459
- messageContextInfo: message.messageContextInfo
316
+ }
460
317
  };
461
- const extraAttrs = {};
462
- const messages = normalizeMessageContent(message)
318
+ const extraAttrs = {}
319
+ const messages = Utils_1.normalizeMessageContent(message)
463
320
  const buttonType = getButtonType(messages);
464
321
  if (participant) {
322
+ // when the retry request is not for a group
323
+ // only send to the specific device that asked for a retry
324
+ // otherwise the message is sent out to every device that should be a recipient
465
325
  if (!isGroup && !isStatus) {
466
- additionalAttributes = {
467
- ...additionalAttributes,
468
- device_fanout: 'false'
469
- };
326
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
470
327
  }
471
- const { user, device } = jidDecode(participant.jid);
472
- devices.push({
473
- user,
474
- device,
475
- jid: participant.jid
476
- });
328
+ const { user, device } = WABinary_1.jidDecode(participant.jid);
329
+ devices.push({ user, device });
477
330
  }
478
331
  await authState.keys.transaction(async () => {
479
- const mediaType = getMediaType(message);
332
+ const mediaType = getMediaType(messages);
333
+
480
334
  if (mediaType) {
481
- extraAttrs['mediatype'] = mediaType;
335
+ extraAttrs['mediatype'] = mediaType
482
336
  }
483
337
 
484
- if (isNewsletter) {
485
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
486
- const bytes = encodeNewsletterMessage(patched);
487
- binaryNodeContent.push({
488
- tag: "plaintext",
489
- attrs: mediaType ? { mediatype: mediaType } : {},
490
- content: bytes
491
- });
492
- const stanza = {
493
- tag: "message",
494
- attrs: {
495
- to: jid,
496
- id: msgId,
497
- type: getTypeMessage(message),
498
- ...(additionalAttributes || {})
499
- },
500
- content: binaryNodeContent
501
- };
502
- logger.debug({ msgId }, `sending newsletter message to ${jid}`);
503
- await sendNode(stanza);
504
- return;
505
- }
506
-
507
338
  if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
508
339
  extraAttrs['decrypt-fail'] = 'hide'
509
340
  }
@@ -515,228 +346,185 @@ export const makeMessagesSocket = (config) => {
515
346
  if (isGroup || isStatus) {
516
347
  const [groupData, senderKeyMap] = await Promise.all([
517
348
  (async () => {
518
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
519
- if (groupData && Array.isArray(groupData?.participants)) {
520
- logger.trace({
521
- jid,
522
- participants: groupData.participants.length
523
- }, 'using cached group metadata');
349
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
350
+ if (groupData) {
351
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
524
352
  }
353
+
525
354
  else if (!isStatus) {
526
- groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
355
+ groupData = await groupMetadata(jid)
527
356
  }
357
+
528
358
  return groupData;
529
359
  })(),
530
360
  (async () => {
531
361
  if (!participant && !isStatus) {
532
- // what if sender memory is less accurate than the cached metadata
533
- // on participant change in group, we should do sender memory manipulation
534
- const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
535
- return result[jid] || {};
362
+ const result = await authState.keys.get('sender-key-memory', [jid])
363
+ return result[jid] || {}
536
364
  }
537
- return {};
538
- })()
365
+
366
+ return {}
367
+
368
+ })()
539
369
  ]);
540
370
  if (!participant) {
541
- const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
371
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
372
+
542
373
  if (isStatus && statusJidList) {
543
- participantsList.push(...statusJidList);
374
+ participantsList.push(...statusJidList)
544
375
  }
545
- // if (!isStatus) {
546
- // additionalAttributes = {
547
- // ...additionalAttributes,
548
- // addressing_mode: groupData?.addressingMode || 'pn'
549
- // };
550
- // }
551
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
552
- devices.push(...additionalDevices);
553
- }
554
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
555
- additionalAttributes = {
556
- ...additionalAttributes,
557
- expiration: groupData.ephemeralDuration.toString()
558
- };
559
- }
560
- const patched = await patchMessageBeforeSending(message);
561
- if (Array.isArray(patched)) {
562
- throw new Boom('Per-jid patching is not supported in groups');
376
+
377
+ // if (!isStatus) {
378
+ // const expiration = await getEphemeralGroup(jid)
379
+ // additionalAttributes = {
380
+ // ...additionalAttributes,
381
+ // addressing_mode: 'pn',
382
+ // ...expiration ? { expiration: expiration.toString() } : null
383
+ // }
384
+ // }
385
+
386
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
387
+ devices.push(...additionalDevices)
563
388
  }
564
- const bytes = encodeWAMessage(patched);
565
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
566
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
389
+
390
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
391
+ const bytes = Utils_1.encodeWAMessage(patched);
392
+
567
393
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
568
394
  group: destinationJid,
569
395
  data: bytes,
570
- meId: groupSenderIdentity
396
+ meId,
571
397
  });
572
- const senderKeyRecipients = [];
573
- for (const device of devices) {
574
- const deviceJid = device.jid;
575
- const hasKey = !!senderKeyMap[deviceJid];
576
- if ((!hasKey || !!participant) &&
577
- !isHostedLidUser(deviceJid) &&
578
- !isHostedPnUser(deviceJid) &&
579
- device.device !== 99) {
580
- //todo: revamp all this logic
581
- // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
582
- senderKeyRecipients.push(deviceJid);
583
- senderKeyMap[deviceJid] = true;
398
+ const senderKeyJids = [];
399
+
400
+ for (const { user, device } of devices) {
401
+ const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
402
+ if (!senderKeyMap[jid] || !!participant) {
403
+ senderKeyJids.push(jid);
404
+ // store that this person has had the sender keys sent to them
405
+ senderKeyMap[jid] = true;
584
406
  }
585
407
  }
586
- if (senderKeyRecipients.length) {
587
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
408
+ // if there are some participants with whom the session has not been established
409
+ // if there are, we re-send the senderkey
410
+ if (senderKeyJids.length) {
411
+ logger.debug({ senderKeyJids }, 'sending new sender key');
588
412
  const senderKeyMsg = {
589
413
  senderKeyDistributionMessage: {
590
414
  axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
591
415
  groupId: destinationJid
592
416
  }
593
417
  };
594
- const senderKeySessionTargets = senderKeyRecipients;
595
- await assertSessions(senderKeySessionTargets);
596
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
418
+ await assertSessions(senderKeyJids, false);
419
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
597
420
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
598
421
  participants.push(...result.nodes);
599
422
  }
600
- if (isRetryResend) {
601
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
602
- data: bytes,
603
- jid: participant?.jid
604
- });
605
- binaryNodeContent.push({
606
- tag: 'enc',
607
- attrs: {
608
- v: '2',
609
- type,
610
- count: participant.count.toString()
611
- },
612
- content: encryptedContent
613
- });
423
+ binaryNodeContent.push({
424
+ tag: 'enc',
425
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
426
+ content: ciphertext
427
+ });
428
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
429
+ }
430
+ else if (isNewsletter) {
431
+ // Message edit
432
+ if (message.protocolMessage?.editedMessage) {
433
+ msgId = message.protocolMessage.key?.id
434
+ message = message.protocolMessage.editedMessage
614
435
  }
615
- else {
616
- binaryNodeContent.push({
617
- tag: 'enc',
618
- attrs: {
619
- v: '2',
620
- type: 'skmsg',
621
- ...extraAttrs
622
- },
623
- content: ciphertext
624
- });
625
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
436
+
437
+ // Message delete
438
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
439
+ msgId = message.protocolMessage.key?.id
440
+ message = {}
626
441
  }
442
+
443
+ const patched = await patchMessageBeforeSending(message, [])
444
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
445
+
446
+ binaryNodeContent.push({
447
+ tag: 'plaintext',
448
+ attrs: extraAttrs ? extraAttrs : {},
449
+ content: bytes
450
+ })
627
451
  }
628
452
  else {
629
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
630
- // TODO: investigate if this is true
631
- let ownId = meId;
632
- if (isLid && meLid) {
633
- ownId = meLid;
634
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
635
- }
636
- else {
637
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
638
- }
639
- const { user: ownUser } = jidDecode(ownId);
453
+ const { user: meUser } = WABinary_1.jidDecode(meId);
640
454
  if (!participant) {
641
- const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
642
- devices.push({
643
- user,
644
- device: 0,
645
- jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
646
- });
647
- if (user !== ownUser) {
648
- const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
649
- const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
650
- devices.push({
651
- user: ownUserForAddressing,
652
- device: 0,
653
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
654
- });
455
+ devices.push({ user })
456
+ if (user !== meUser) {
457
+ devices.push({ user: meUser })
655
458
  }
459
+
656
460
  if (additionalAttributes?.['category'] !== 'peer') {
657
- // Clear placeholders and enumerate actual devices
658
- devices.length = 0;
659
- // Use conversation-appropriate sender identity
660
- const senderIdentity = isLid && meLid
661
- ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
662
- : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
663
- // Enumerate devices for sender and target with consistent addressing
664
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
665
- devices.push(...sessionDevices);
666
- logger.debug({
667
- deviceCount: devices.length,
668
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
669
- }, 'Device enumeration complete with unified addressing');
461
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
462
+
463
+ devices.push(...additionalDevices)
670
464
  }
671
465
  }
672
- const allRecipients = [];
673
- const meRecipients = [];
674
- const otherRecipients = [];
675
- const { user: mePnUser } = jidDecode(meId);
676
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
677
- for (const { user, jid } of devices) {
678
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
679
- if (isExactSenderDevice) {
680
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
681
- continue;
682
- }
683
- // Check if this is our device (could match either PN or LID user)
684
- const isMe = user === mePnUser || user === meLidUser;
466
+ const allJids = [];
467
+ const meJids = [];
468
+ const otherJids = [];
469
+ for (const { user, device } of devices) {
470
+ const isMe = user === meUser
471
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
472
+
685
473
  if (isMe) {
686
- meRecipients.push(jid);
474
+ meJids.push(jid)
687
475
  }
476
+
688
477
  else {
689
- otherRecipients.push(jid);
478
+ otherJids.push(jid)
690
479
  }
691
- allRecipients.push(jid);
480
+
481
+ allJids.push(jid)
692
482
  }
693
- await assertSessions(allRecipients);
483
+ await assertSessions(allJids, false);
694
484
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
695
- // For own devices: use DSM if available (1:1 chats only)
696
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
697
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
698
- ]);
485
+ createParticipantNodes(meJids, meMsg, extraAttrs),
486
+ createParticipantNodes(otherJids, message, extraAttrs)
487
+ ])
699
488
  participants.push(...meNodes);
700
489
  participants.push(...otherNodes);
701
- /* if (meRecipients.length > 0 || otherRecipients.length > 0) {
702
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
703
- }*/
704
490
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
705
491
  }
706
492
  if (participants.length) {
707
493
  if (additionalAttributes?.['category'] === 'peer') {
708
- const peerNode = participants[0]?.content?.[0];
494
+ const peerNode = participants[0]?.content?.[0]
495
+
709
496
  if (peerNode) {
710
- binaryNodeContent.push(peerNode); // push only enc
497
+ binaryNodeContent.push(peerNode) // push only enc
711
498
  }
712
499
  }
500
+
713
501
  else {
714
502
  binaryNodeContent.push({
715
503
  tag: 'participants',
716
504
  attrs: {},
717
505
  content: participants
718
- });
506
+ })
719
507
  }
720
508
  }
509
+
721
510
  const stanza = {
722
511
  tag: 'message',
723
512
  attrs: {
724
513
  id: msgId,
725
- to: destinationJid,
726
- type: getTypeMessage(messages),
514
+ type: getTypeMessage(messages),
727
515
  ...(additionalAttributes || {})
728
516
  },
729
517
  content: binaryNodeContent
730
- };
518
+ }
731
519
  // if the participant to send to is explicitly specified (generally retry recp)
732
520
  // ensure the message is only sent to that person
733
521
  // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
734
522
  if (participant) {
735
- if (isJidGroup(destinationJid)) {
523
+ if (WABinary_1.isJidGroup(destinationJid)) {
736
524
  stanza.attrs.to = destinationJid;
737
525
  stanza.attrs.participant = participant.jid;
738
526
  }
739
- else if (areJidsSameUser(participant.jid, meId)) {
527
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
740
528
  stanza.attrs.to = participant.jid;
741
529
  stanza.attrs.recipient = destinationJid;
742
530
  }
@@ -748,14 +536,14 @@ export const makeMessagesSocket = (config) => {
748
536
  stanza.attrs.to = destinationJid;
749
537
  }
750
538
  if (shouldIncludeDeviceIdentity) {
751
- ;
752
539
  stanza.content.push({
753
540
  tag: 'device-identity',
754
541
  attrs: {},
755
- content: encodeSignedDeviceIdentity(authState.creds.account, true)
542
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
756
543
  });
757
544
  logger.debug({ jid }, 'adding device identity');
758
545
  }
546
+
759
547
  if (AI && isPrivate) {
760
548
  const botNode = {
761
549
  tag: 'bot',
@@ -764,7 +552,7 @@ export const makeMessagesSocket = (config) => {
764
552
  }
765
553
  }
766
554
 
767
- const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
555
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
768
556
 
769
557
  if (filteredBizBot) {
770
558
  stanza.content.push(...additionalNodes)
@@ -776,9 +564,9 @@ export const makeMessagesSocket = (config) => {
776
564
  }
777
565
  }
778
566
 
779
- if(buttonType && !isStatus) {
780
- const content = getAdditionalNode(buttonType)
781
- const filteredNode = getBinaryNodeFilter(additionalNodes)
567
+ if(!isNewsletter && buttonType && !isStatus) {
568
+ const content = WABinary_1.getAdditionalNode(buttonType)
569
+ const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
782
570
 
783
571
  if (filteredNode) {
784
572
  didPushAdditional = true
@@ -793,44 +581,42 @@ export const makeMessagesSocket = (config) => {
793
581
  if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
794
582
  stanza.content.push(...additionalNodes);
795
583
  }
584
+
796
585
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
797
586
  await sendNode(stanza);
798
- // Add message to retry cache if enabled
799
- if (messageRetryManager && !participant) {
800
- messageRetryManager.addRecentMessage(destinationJid, msgId, message);
801
- }
802
- }, meId);
803
- return msgId;
587
+ });
588
+
589
+ message = Types_1.WAProto.Message.fromObject(message)
590
+
591
+ const messageJSON = {
592
+ key: {
593
+ remoteJid: jid,
594
+ fromMe: true,
595
+ id: msgId
596
+ },
597
+ message: message,
598
+ messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
599
+ messageStubParameters: [],
600
+ participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
601
+ status: Types_1.WAMessageStatus.PENDING
602
+ }
603
+
604
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON)
605
+ // return msgId;
804
606
  };
805
607
  const getTypeMessage = (msg) => {
806
- if (msg.viewOnceMessage) {
807
- return getTypeMessage(msg.viewOnceMessage.message);
808
- }
809
- else if (msg.viewOnceMessageV2) {
810
- return getTypeMessage(msg.viewOnceMessageV2.message);
811
- }
812
- else if (msg.viewOnceMessageV2Extension) {
813
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
814
- }
815
- else if (msg.ephemeralMessage) {
816
- return getTypeMessage(msg.ephemeralMessage.message);
817
- }
818
- else if (msg.documentWithCaptionMessage) {
819
- return getTypeMessage(msg.documentWithCaptionMessage.message);
820
- }
821
- else if (msg.reactionMessage) {
822
- return 'reaction';
823
- }
824
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
825
- return 'poll';
826
- }
827
- else if (getMediaType(msg)) {
828
- return 'media';
829
- }
608
+ const message = Utils_1.normalizeMessageContent(msg)
609
+ if (message.reactionMessage) {
610
+ return 'reaction'
611
+ }
612
+ else if (getMediaType(message)) {
613
+ return 'media'
614
+ }
830
615
  else {
831
- return 'text';
616
+ return 'text'
832
617
  }
833
- };
618
+ }
619
+
834
620
  const getMediaType = (message) => {
835
621
  if (message.imageMessage) {
836
622
  return 'image'
@@ -880,7 +666,8 @@ export const makeMessagesSocket = (config) => {
880
666
  else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
881
667
  return 'productlink'
882
668
  }
883
- }
669
+ }
670
+
884
671
  const getButtonType = (message) => {
885
672
  if (message.listMessage) {
886
673
  return 'list'
@@ -911,11 +698,11 @@ export const makeMessagesSocket = (config) => {
911
698
  }
912
699
  }
913
700
  const getPrivacyTokens = async (jids) => {
914
- const t = unixTimestampSeconds().toString();
701
+ const t = Utils_1.unixTimestampSeconds().toString();
915
702
  const result = await query({
916
703
  tag: 'iq',
917
704
  attrs: {
918
- to: S_WHATSAPP_NET,
705
+ to: WABinary_1.S_WHATSAPP_NET,
919
706
  type: 'set',
920
707
  xmlns: 'privacy'
921
708
  },
@@ -926,7 +713,7 @@ export const makeMessagesSocket = (config) => {
926
713
  content: jids.map(jid => ({
927
714
  tag: 'token',
928
715
  attrs: {
929
- jid: jidNormalizedUser(jid),
716
+ jid: WABinary_1.jidNormalizedUser(jid),
930
717
  t,
931
718
  type: 'trusted_contact'
932
719
  }
@@ -935,9 +722,10 @@ export const makeMessagesSocket = (config) => {
935
722
  ]
936
723
  });
937
724
  return result;
938
- };
939
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
940
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
725
+ }
726
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
727
+ const rahmi = new kikyy(Utils_1, waUploadToServer, relayMessage);
728
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
941
729
  return {
942
730
  ...sock,
943
731
  getPrivacyTokens,
@@ -945,23 +733,23 @@ export const makeMessagesSocket = (config) => {
945
733
  relayMessage,
946
734
  sendReceipt,
947
735
  sendReceipts,
736
+ rahmi,
948
737
  readMessages,
949
738
  refreshMediaConn,
739
+ getUSyncDevices,
740
+ createParticipantNodes,
950
741
  waUploadToServer,
951
- fetchPrivacySettings,
952
742
  sendPeerDataOperationMessage,
953
- createParticipantNodes,
954
- getUSyncDevices,
955
- messageRetryManager,
743
+ fetchPrivacySettings,
956
744
  updateMediaMessage: async (message) => {
957
- const content = assertMediaContent(message.message);
745
+ const content = (0, Utils_1.assertMediaContent)(message.message);
958
746
  const mediaKey = content.mediaKey;
959
747
  const meId = authState.creds.me.id;
960
- const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
748
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
961
749
  let error = undefined;
962
750
  await Promise.all([
963
751
  sendNode(node),
964
- waitForMsgMediaUpdate(async (update) => {
752
+ waitForMsgMediaUpdate(update => {
965
753
  const result = update.find(c => c.key.id === message.key.id);
966
754
  if (result) {
967
755
  if (result.error) {
@@ -969,16 +757,13 @@ export const makeMessagesSocket = (config) => {
969
757
  }
970
758
  else {
971
759
  try {
972
- const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
973
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
974
- const resultStr = proto.MediaRetryNotification.ResultType[media.result];
975
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
976
- data: media,
977
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
978
- });
760
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
761
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
762
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
763
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
979
764
  }
980
765
  content.directPath = media.directPath;
981
- content.url = getUrlFromDirectPath(content.directPath);
766
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
982
767
  logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
983
768
  }
984
769
  catch (err) {
@@ -992,177 +777,133 @@ export const makeMessagesSocket = (config) => {
992
777
  if (error) {
993
778
  throw error;
994
779
  }
995
- ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
780
+ ev.emit('messages.update', [
781
+ {
782
+ key: message.key,
783
+ update: {
784
+ message: message.message
785
+ }
786
+ }
787
+ ]);
996
788
  return message;
997
789
  },
998
790
  sendMessage: async (jid, content, options = {}) => {
999
791
  const userJid = authState.creds.me.id;
1000
- if (typeof content === 'object' &&
1001
- 'disappearingMessagesInChat' in content &&
1002
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1003
- isJidGroup(jid)) {
1004
- const { disappearingMessagesInChat } = content;
1005
- const value = typeof disappearingMessagesInChat === 'boolean'
1006
- ? disappearingMessagesInChat
1007
- ? WA_DEFAULT_EPHEMERAL
1008
- : 0
1009
- : disappearingMessagesInChat;
1010
- await groupToggleEphemeral(jid, value);
792
+ delete options.ephemeralExpiration
793
+ const { filter = false, quoted } = options;
794
+ const getParticipantAttr = () => filter ? { participant: { jid } } : {};
795
+ const messageType = rahmi.detectType(content);
796
+ if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
797
+ typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
798
+ const { disappearingMessagesInChat } = content
799
+
800
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
801
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
802
+ disappearingMessagesInChat
803
+
804
+ await groupToggleEphemeral(jid, value)
1011
805
  }
1012
- else if (typeof content === 'object' && 'album' in content && content.album) {
1013
- const { album, caption } = content;
1014
- if (caption && !album[0].caption) {
1015
- album[0].caption = caption;
1016
- }
1017
- let mediaHandle;
1018
- let mediaMsg;
1019
- const albumMsg = await generateWAMessageFromContent(jid, {
1020
- albumMessage: {
1021
- expectedImageCount: album.filter(item => 'image' in item).length,
1022
- expectedVideoCount: album.filter(item => 'video' in item).length
1023
- }
1024
- }, { userJid, ...options });
1025
- await relayMessage(jid, albumMsg.message, {
1026
- messageId: albumMsg.key.id
1027
- });
1028
- for (const i in album) {
1029
- const media = album[i];
1030
- if ('image' in media) {
1031
- mediaMsg = await generateWAMessage(jid, {
1032
- image: media.image,
1033
- ...(media.caption ? { caption: media.caption } : {}),
1034
- ...options
1035
- }, {
1036
- userJid,
1037
- upload: async (readStream, opts) => {
1038
- const up = await waUploadToServer(readStream, { ...opts, newsletter: isJidNewsletter(jid) });
1039
- mediaHandle = up.handle;
1040
- return up;
1041
- },
1042
- ...options,
806
+
807
+ else {
808
+ let mediaHandle
809
+
810
+
811
+ if (messageType) {
812
+ switch(messageType) {
813
+ case 'PAYMENT':
814
+ const paymentContent = await rahmi.handlePayment(content, quoted);
815
+ return await relayMessage(jid, paymentContent, {
816
+ messageId: Utils_1.generateMessageID(),
817
+ ...getParticipantAttr()
1043
818
  });
1044
- }
1045
- else if ('video' in media) {
1046
- mediaMsg = await generateWAMessage(jid, {
1047
- video: media.video,
1048
- ...(media.caption ? { caption: media.caption } : {}),
1049
- ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
1050
- ...options
1051
- }, {
1052
- userJid,
1053
- upload: async (readStream, opts) => {
1054
- const up = await waUploadToServer(readStream, { ...opts, newsletter: isJidNewsletter(jid) });
1055
- mediaHandle = up.handle;
1056
- return up;
1057
- },
1058
- ...options,
819
+
820
+ case 'PRODUCT':
821
+ const productContent = await rahmi.handleProduct(content, jid, quoted);
822
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
823
+ return await relayMessage(jid, productMsg.message, {
824
+ messageId: productMsg.key.id,
825
+ ...getParticipantAttr()
1059
826
  });
1060
- }
1061
- if (mediaMsg) {
1062
- mediaMsg.message.messageContextInfo = {
1063
- messageSecret: randomBytes,
1064
- messageAssociation: {
1065
- associationType: 1,
1066
- parentMessageKey: albumMsg.key
1067
- }
1068
- };
1069
- }
1070
- await relayMessage(jid, mediaMsg.message, {
1071
- messageId: mediaMsg.key.id
1072
- });
1073
- await new Promise(resolve => setTimeout(resolve, 800));
1074
- }
1075
- return albumMsg;
1076
- }
1077
- else {
1078
- const fullMsg = await generateWAMessage(jid, content, {
1079
- logger,
1080
- userJid,
1081
- getUrlInfo: text => getUrlInfo(text, {
1082
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1083
- fetchOpts: {
1084
- timeout: 3000,
1085
- ...(httpRequestOptions || {})
1086
- },
1087
- logger,
1088
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1089
- }),
1090
- //TODO: CACHE
1091
- getProfilePicUrl: sock.profilePictureUrl,
1092
- getCallLink: sock.createCallLink,
1093
- upload: async (readStream, opts) => {
1094
- const up = await waUploadToServer(readStream, {
1095
- ...opts,
1096
- newsletter: isJidNewsletter(jid)
827
+
828
+ case 'INTERACTIVE':
829
+ const interactiveContent = await rahmi.handleInteractive(content, jid, quoted);
830
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
831
+ return await relayMessage(jid, interactiveMsg.message, {
832
+ messageId: interactiveMsg.key.id,
833
+ ...getParticipantAttr()
1097
834
  });
1098
- return up;
835
+ case 'ALBUM':
836
+ return await rahmi.handleAlbum(content, jid, quoted)
837
+ case 'EVENT':
838
+ return await rahmi.handleEvent(content, jid, quoted)
839
+ case 'POLL_RESULT':
840
+ return await rahmi.handlePollResult(content, jid, quoted)
841
+ case 'GROUP_STORY':
842
+ return await rahmi.handleGroupStory(content, jid, quoted)
843
+ }
844
+ }
845
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
846
+ logger,
847
+ userJid,
848
+ quoted,
849
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
850
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
851
+ fetchOpts: {
852
+ timeout: 3000,
853
+ ...axiosOptions || {}
1099
854
  },
1100
- mediaCache: config.mediaCache,
1101
- options: config.options,
1102
- messageId: generateMessageIDV2(sock.user?.id),
1103
- ...options
1104
- });
1105
- const isAiMsg = 'ai' in content && !!content.ai;
1106
- const isEventMsg = 'event' in content && !!content.event;
1107
- const isDeleteMsg = 'delete' in content && !!content.delete;
1108
- const isEditMsg = 'edit' in content && !!content.edit;
1109
- const isPinMsg = 'pin' in content && !!content.pin;
1110
- const isPollMessage = 'poll' in content && !!content.poll;
1111
- const additionalAttributes = {};
1112
- const additionalNodes = [];
1113
- // required for delete
1114
- if (isDeleteMsg) {
1115
- // if the chat is a group, and I am not the author, then delete the message as an admin
1116
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1117
- additionalAttributes.edit = '8';
1118
- }
1119
- else {
1120
- additionalAttributes.edit = '7';
1121
- }
1122
- }
1123
- else if (isEditMsg) {
1124
- additionalAttributes.edit = '1';
1125
- }
1126
- else if (isAiMsg) {
1127
- additionalNodes.push({
855
+ logger,
856
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
857
+ }),
858
+ upload: async (readStream, opts) => {
859
+ const up = await waUploadToServer(readStream, {
860
+ ...opts,
861
+ newsletter: WABinary_1.isJidNewsLetter(jid)
862
+ });
863
+ return up;
864
+ },
865
+ mediaCache: config.mediaCache,
866
+ options: config.options,
867
+ ...options
868
+ });
869
+
870
+ const isDeleteMsg = 'delete' in content && !!content.delete;
871
+ const isEditMsg = 'edit' in content && !!content.edit;
872
+ const isAiMsg = 'ai' in content && !!content.ai;
873
+
874
+ const additionalAttributes = {};
875
+ const additionalNodes = [];
876
+
877
+ if (isDeleteMsg) {
878
+ const fromMe = content.delete?.fromMe;
879
+ const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
880
+ additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
881
+ } else if (isEditMsg) {
882
+ additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
883
+ } else if (isAiMsg) {
884
+ additionalNodes.push({
1128
885
  attrs: {
1129
886
  biz_bot: '1'
1130
887
  }, tag: "bot"
1131
888
  });
1132
- }
1133
- else if (isPinMsg) {
1134
- additionalAttributes.edit = '2';
1135
- }
1136
- else if (isPollMessage) {
1137
- additionalNodes.push({
1138
- tag: 'meta',
1139
- attrs: {
1140
- polltype: 'creation'
1141
- }
1142
- });
1143
- }
1144
- else if (isEventMsg) {
1145
- additionalNodes.push({
1146
- tag: 'meta',
1147
- attrs: {
1148
- event_type: 'creation'
1149
- }
1150
- });
1151
- }
1152
- await relayMessage(jid, fullMsg.message, {
1153
- messageId: fullMsg.key.id,
1154
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1155
- additionalAttributes,
1156
- statusJidList: options.statusJidList,
1157
- additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes
889
+ }
890
+
891
+ await relayMessage(jid, fullMsg.message, {
892
+ messageId: fullMsg.key.id,
893
+ cachedGroupMetadata: options.cachedGroupMetadata,
894
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
895
+ additionalAttributes,
896
+ statusJidList: options.statusJidList
897
+ });
898
+
899
+ if (config.emitOwnEvents) {
900
+ process.nextTick(() => {
901
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1158
902
  });
1159
- if (config.emitOwnEvents) {
1160
- process.nextTick(() => {
1161
- processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1162
- });
1163
- }
1164
- return fullMsg;
903
+ }
904
+ return fullMsg;
1165
905
  }
1166
906
  }
1167
- };
1168
- };
907
+ }
908
+ };
909
+ exports.makeMessagesSocket = makeMessagesSocket;