@skyzopedia/baileys-mod 3.0.2

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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/WAProto.proto +5311 -0
  3. package/WAProto/index.js +94091 -0
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/KeyDB/BinarySearch.js +20 -0
  6. package/lib/KeyDB/KeyedDB.js +167 -0
  7. package/lib/KeyDB/index.js +4 -0
  8. package/lib/Signal/Group/ciphertext-message.js +13 -0
  9. package/lib/Signal/Group/group-session-builder.js +32 -0
  10. package/lib/Signal/Group/group_cipher.js +84 -0
  11. package/lib/Signal/Group/index.js +13 -0
  12. package/lib/Signal/Group/keyhelper.js +20 -0
  13. package/lib/Signal/Group/sender-chain-key.js +28 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  15. package/lib/Signal/Group/sender-key-message.js +68 -0
  16. package/lib/Signal/Group/sender-key-name.js +52 -0
  17. package/lib/Signal/Group/sender-key-record.js +43 -0
  18. package/lib/Signal/Group/sender-key-state.js +86 -0
  19. package/lib/Signal/Group/sender-message-key.js +28 -0
  20. package/lib/Signal/libsignal.js +324 -0
  21. package/lib/Signal/lid-mapping.js +155 -0
  22. package/lib/Socket/Client/index.js +4 -0
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +52 -0
  25. package/lib/Socket/business.js +377 -0
  26. package/lib/Socket/chats.js +881 -0
  27. package/lib/Socket/communities.js +413 -0
  28. package/lib/Socket/groups.js +312 -0
  29. package/lib/Socket/index.js +16 -0
  30. package/lib/Socket/messages-recv.js +1163 -0
  31. package/lib/Socket/messages-send.js +1082 -0
  32. package/lib/Socket/mex.js +45 -0
  33. package/lib/Socket/newsletter.js +259 -0
  34. package/lib/Socket/socket.js +781 -0
  35. package/lib/Store/index.js +6 -0
  36. package/lib/Store/make-cache-manager-store.js +75 -0
  37. package/lib/Store/make-in-memory-store.js +290 -0
  38. package/lib/Store/make-ordered-dictionary.js +79 -0
  39. package/lib/Store/object-repository.js +25 -0
  40. package/lib/Types/Auth.js +3 -0
  41. package/lib/Types/Bussines.js +3 -0
  42. package/lib/Types/Call.js +3 -0
  43. package/lib/Types/Chat.js +9 -0
  44. package/lib/Types/Contact.js +3 -0
  45. package/lib/Types/Events.js +3 -0
  46. package/lib/Types/GroupMetadata.js +3 -0
  47. package/lib/Types/Label.js +25 -0
  48. package/lib/Types/LabelAssociation.js +7 -0
  49. package/lib/Types/Message.js +12 -0
  50. package/lib/Types/Newsletter.js +33 -0
  51. package/lib/Types/Newsletter.js.bak +33 -0
  52. package/lib/Types/Product.js +3 -0
  53. package/lib/Types/Signal.js +3 -0
  54. package/lib/Types/Socket.js +4 -0
  55. package/lib/Types/State.js +11 -0
  56. package/lib/Types/USync.js +3 -0
  57. package/lib/Types/index.js +28 -0
  58. package/lib/Utils/auth-utils.js +219 -0
  59. package/lib/Utils/baileys-event-stream.js +44 -0
  60. package/lib/Utils/browser-utils.js +17 -0
  61. package/lib/Utils/business.js +233 -0
  62. package/lib/Utils/chat-utils.js +752 -0
  63. package/lib/Utils/crypto.js +130 -0
  64. package/lib/Utils/decode-wa-message.js +267 -0
  65. package/lib/Utils/event-buffer.js +528 -0
  66. package/lib/Utils/generics.js +355 -0
  67. package/lib/Utils/history.js +87 -0
  68. package/lib/Utils/index.js +21 -0
  69. package/lib/Utils/link-preview.js +81 -0
  70. package/lib/Utils/logger.js +5 -0
  71. package/lib/Utils/lt-hash.js +45 -0
  72. package/lib/Utils/make-mutex.js +36 -0
  73. package/lib/Utils/message-retry-manager.js +113 -0
  74. package/lib/Utils/messages-media.js +601 -0
  75. package/lib/Utils/messages.js +776 -0
  76. package/lib/Utils/noise-handler.js +144 -0
  77. package/lib/Utils/pre-key-manager.js +85 -0
  78. package/lib/Utils/process-message.js +341 -0
  79. package/lib/Utils/signal.js +161 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  81. package/lib/Utils/validate-connection.js +200 -0
  82. package/lib/WABinary/constants.js +1303 -0
  83. package/lib/WABinary/decode.js +240 -0
  84. package/lib/WABinary/encode.js +218 -0
  85. package/lib/WABinary/generic-utils.js +113 -0
  86. package/lib/WABinary/index.js +7 -0
  87. package/lib/WABinary/jid-utils.js +93 -0
  88. package/lib/WABinary/types.js +3 -0
  89. package/lib/WAM/BinaryInfo.js +11 -0
  90. package/lib/WAM/constants.js +22853 -0
  91. package/lib/WAM/encode.js +154 -0
  92. package/lib/WAM/index.js +5 -0
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  99. package/lib/WAUSync/Protocols/index.js +6 -0
  100. package/lib/WAUSync/USyncQuery.js +90 -0
  101. package/lib/WAUSync/USyncUser.js +24 -0
  102. package/lib/WAUSync/index.js +5 -0
  103. package/lib/index.js +15 -0
  104. package/package.json +102 -0
@@ -0,0 +1,1082 @@
1
+ //=======================================================//
2
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from "../Utils/index.js";
3
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from "../WABinary/index.js";
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from "../Defaults/index.js";
5
+ import { USyncQuery, USyncUser } from "../WAUSync/index.js";
6
+ import { makeKeyedMutex } from "../Utils/make-mutex.js";
7
+ import { makeNewsletterSocket } from "./newsletter.js";
8
+ import { getUrlInfo } from "../Utils/link-preview.js";
9
+ import { proto } from "../../WAProto/index.js";
10
+ import NodeCache from "@cacheable/node-cache";
11
+ import { Boom } from "@hapi/boom";
12
+ import crypto from "crypto";
13
+ //=======================================================//
14
+ export const makeMessagesSocket = (config) => {
15
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
16
+ const sock = makeNewsletterSocket(config);
17
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
18
+ const userDevicesCache = config.userDevicesCache ||
19
+ new NodeCache({
20
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
21
+ useClones: false
22
+ });
23
+ const peerSessionsCache = new NodeCache({
24
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
25
+ useClones: false
26
+ });
27
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
28
+ const encryptionMutex = makeKeyedMutex();
29
+ let mediaConn;
30
+ const refreshMediaConn = async (forceGet = false) => {
31
+ const media = await mediaConn;
32
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
33
+ mediaConn = (async () => {
34
+ const result = await query({
35
+ tag: "iq",
36
+ attrs: {
37
+ type: "set",
38
+ xmlns: "w:m",
39
+ to: S_WHATSAPP_NET
40
+ },
41
+ content: [{ tag: "media_conn", attrs: {} }]
42
+ });
43
+ const mediaConnNode = getBinaryNodeChild(result, "media_conn");
44
+ const node = {
45
+ hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs }) => ({
46
+ hostname: attrs.hostname,
47
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
48
+ })),
49
+ auth: mediaConnNode.attrs.auth,
50
+ ttl: +mediaConnNode.attrs.ttl,
51
+ fetchDate: new Date()
52
+ };
53
+ logger.debug("fetched media conn");
54
+ return node;
55
+ })();
56
+ }
57
+ return mediaConn;
58
+ };
59
+ const sendReceipt = async (jid, participant, messageIds, type) => {
60
+ if (!messageIds || messageIds.length === 0) {
61
+ throw new Boom("missing ids in receipt");
62
+ }
63
+ const node = {
64
+ tag: "receipt",
65
+ attrs: {
66
+ id: messageIds[0]
67
+ }
68
+ };
69
+ const isReadReceipt = type === "read" || type === "read-self";
70
+ if (isReadReceipt) {
71
+ node.attrs.t = unixTimestampSeconds().toString();
72
+ }
73
+ if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
74
+ node.attrs.recipient = jid;
75
+ node.attrs.to = participant;
76
+ }
77
+ else {
78
+ node.attrs.to = jid;
79
+ if (participant) {
80
+ node.attrs.participant = participant;
81
+ }
82
+ }
83
+ if (type) {
84
+ node.attrs.type = type;
85
+ }
86
+ const remainingMessageIds = messageIds.slice(1);
87
+ if (remainingMessageIds.length) {
88
+ node.content = [
89
+ {
90
+ tag: "list",
91
+ attrs: {},
92
+ content: remainingMessageIds.map(id => ({
93
+ tag: "item",
94
+ attrs: { id }
95
+ }))
96
+ }
97
+ ];
98
+ }
99
+ logger.debug({ attrs: node.attrs, messageIds }, "sending receipt for messages");
100
+ await sendNode(node);
101
+ };
102
+ const sendReceipts = async (keys, type) => {
103
+ const recps = aggregateMessageKeysNotFromMe(keys);
104
+ for (const { jid, participant, messageIds } of recps) {
105
+ await sendReceipt(jid, participant, messageIds, type);
106
+ }
107
+ };
108
+ const readMessages = async (keys) => {
109
+ const privacySettings = await fetchPrivacySettings();
110
+ const readType = privacySettings.readreceipts === "all" ? "read" : "read-self";
111
+ await sendReceipts(keys, readType);
112
+ };
113
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
114
+ const deviceResults = [];
115
+ if (!useCache) {
116
+ logger.debug("not using cache for devices");
117
+ }
118
+ const toFetch = [];
119
+ const jidsWithUser = jids
120
+ .map(jid => {
121
+ const decoded = jidDecode(jid);
122
+ const user = decoded?.user;
123
+ const device = decoded?.device;
124
+ const isExplicitDevice = typeof device === "number" && device >= 0;
125
+ if (isExplicitDevice && user) {
126
+ deviceResults.push({
127
+ user,
128
+ device,
129
+ jid
130
+ });
131
+ return null;
132
+ }
133
+ jid = jidNormalizedUser(jid);
134
+ return { jid, user };
135
+ })
136
+ .filter(jid => jid !== null);
137
+ let mgetDevices;
138
+ if (useCache && userDevicesCache.mget) {
139
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
140
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
141
+ }
142
+ for (const { jid, user } of jidsWithUser) {
143
+ if (useCache) {
144
+ const devices = mgetDevices?.[user] ||
145
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
146
+ if (devices) {
147
+ const devicesWithJid = devices.map(d => ({
148
+ ...d,
149
+ jid: jidEncode(d.user, d.server, d.device)
150
+ }));
151
+ deviceResults.push(...devicesWithJid);
152
+ logger.trace({ user }, "using cache for devices");
153
+ }
154
+ else {
155
+ toFetch.push(jid);
156
+ }
157
+ }
158
+ else {
159
+ toFetch.push(jid);
160
+ }
161
+ }
162
+ if (!toFetch.length) {
163
+ return deviceResults;
164
+ }
165
+ const requestedLidUsers = new Set();
166
+ for (const jid of toFetch) {
167
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
168
+ const user = jidDecode(jid)?.user;
169
+ if (user)
170
+ requestedLidUsers.add(user);
171
+ }
172
+ }
173
+ const query = new USyncQuery().withContext("message").withDeviceProtocol().withLIDProtocol();
174
+ for (const jid of toFetch) {
175
+ query.withUser(new USyncUser().withId(jid));
176
+ }
177
+ const result = await sock.executeUSyncQuery(query);
178
+ if (result) {
179
+ const lidResults = result.list.filter(a => !!a.lid);
180
+ if (lidResults.length > 0) {
181
+ logger.trace("Storing LID maps from device call");
182
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
183
+ }
184
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
185
+ const deviceMap = {};
186
+ for (const item of extracted) {
187
+ deviceMap[item.user] = deviceMap[item.user] || [];
188
+ deviceMap[item.user]?.push(item);
189
+ }
190
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
191
+ const isLidUser = requestedLidUsers.has(user);
192
+ for (const item of userDevices) {
193
+ const finalJid = isLidUser
194
+ ? jidEncode(user, item.server, item.device)
195
+ : jidEncode(item.user, item.server, item.device);
196
+ deviceResults.push({
197
+ ...item,
198
+ jid: finalJid
199
+ });
200
+ logger.debug({
201
+ user: item.user,
202
+ device: item.device,
203
+ finalJid,
204
+ usedLid: isLidUser
205
+ }, "Processed device with LID priority");
206
+ }
207
+ }
208
+ if (userDevicesCache.mset) {
209
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
210
+ }
211
+ else {
212
+ for (const key in deviceMap) {
213
+ if (deviceMap[key])
214
+ await userDevicesCache.set(key, deviceMap[key]);
215
+ }
216
+ }
217
+ const userDeviceUpdates = {};
218
+ for (const [userId, devices] of Object.entries(deviceMap)) {
219
+ if (devices && devices.length > 0) {
220
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || "0");
221
+ }
222
+ }
223
+ if (Object.keys(userDeviceUpdates).length > 0) {
224
+ try {
225
+ await authState.keys.set({ "device-list": userDeviceUpdates });
226
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, "stored user device lists for bulk migration");
227
+ }
228
+ catch (error) {
229
+ logger.warn({ error }, "failed to store user device lists");
230
+ }
231
+ }
232
+ }
233
+ return deviceResults;
234
+ };
235
+ const assertSessions = async (jids) => {
236
+ let didFetchNewSession = false;
237
+ const uniqueJids = [...new Set(jids)];
238
+ const jidsRequiringFetch = [];
239
+ logger.debug({ jids }, "assertSessions call with jids");
240
+ for (const jid of uniqueJids) {
241
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
242
+ const cachedSession = peerSessionsCache.get(signalId);
243
+ if (cachedSession !== undefined) {
244
+ if (cachedSession) {
245
+ continue;
246
+ }
247
+ }
248
+ else {
249
+ const sessionValidation = await signalRepository.validateSession(jid);
250
+ const hasSession = sessionValidation.exists;
251
+ peerSessionsCache.set(signalId, hasSession);
252
+ if (hasSession) {
253
+ continue;
254
+ }
255
+ }
256
+ jidsRequiringFetch.push(jid);
257
+ }
258
+ if (jidsRequiringFetch.length) {
259
+ const wireJids = [
260
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
261
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
262
+ ];
263
+ logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
264
+ const result = await query({
265
+ tag: "iq",
266
+ attrs: {
267
+ xmlns: "encrypt",
268
+ type: "get",
269
+ to: S_WHATSAPP_NET
270
+ },
271
+ content: [
272
+ {
273
+ tag: "key",
274
+ attrs: {},
275
+ content: wireJids.map(jid => ({
276
+ tag: "user",
277
+ attrs: { jid }
278
+ }))
279
+ }
280
+ ]
281
+ });
282
+ await parseAndInjectE2ESessions(result, signalRepository);
283
+ didFetchNewSession = true;
284
+ for (const wireJid of wireJids) {
285
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
286
+ peerSessionsCache.set(signalId, true);
287
+ }
288
+ }
289
+ return didFetchNewSession;
290
+ };
291
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
292
+ if (!authState.creds.me?.id) {
293
+ throw new Boom("Not authenticated");
294
+ }
295
+ const protocolMessage = {
296
+ protocolMessage: {
297
+ peerDataOperationRequestMessage: pdoMessage,
298
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
299
+ }
300
+ };
301
+ const meJid = jidNormalizedUser(authState.creds.me.id);
302
+ const msgId = await relayMessage(meJid, protocolMessage, {
303
+ additionalAttributes: {
304
+ category: "peer",
305
+ push_priority: "high_force"
306
+ },
307
+ additionalNodes: [
308
+ {
309
+ tag: "meta",
310
+ attrs: { appdata: "default" }
311
+ }
312
+ ]
313
+ });
314
+ return msgId;
315
+ };
316
+ const offerCall = async (toJid, isVideo = false) => {
317
+ const callId = crypto
318
+ .randomBytes(16)
319
+ .toString("hex")
320
+ .toUpperCase()
321
+ .substring(0, 64);
322
+ const offerContent = [];
323
+ offerContent.push({
324
+ tag: "audio",
325
+ attrs: { enc: "opus", rate: "16000" },
326
+ content: undefined,
327
+ });
328
+ offerContent.push({
329
+ tag: "audio",
330
+ attrs: { enc: "opus", rate: "8000" },
331
+ content: undefined,
332
+ });
333
+ if (isVideo) {
334
+ offerContent.push({
335
+ tag: "video",
336
+ attrs: {
337
+ enc: "vp8",
338
+ dec: "vp8",
339
+ orientation: "0",
340
+ screen_width: "1920",
341
+ screen_height: "1080",
342
+ device_orientation: "0",
343
+ },
344
+ content: undefined,
345
+ });
346
+ }
347
+ offerContent.push({
348
+ tag: "net",
349
+ attrs: { medium: "3" },
350
+ content: undefined,
351
+ });
352
+ offerContent.push({
353
+ tag: "capability",
354
+ attrs: { ver: "1" },
355
+ content: new Uint8Array([1, 4, 255, 131, 207, 4]),
356
+ });
357
+ offerContent.push({
358
+ tag: "encopt",
359
+ attrs: { keygen: "2" },
360
+ content: undefined,
361
+ });
362
+ const encKey = crypto.randomBytes(32);
363
+ const rawDevices = await getUSyncDevices([toJid], true, false);
364
+ const devices = rawDevices.map(({ user, device }) =>
365
+ jidEncode(user, "s.whatsapp.net", device)
366
+ );
367
+ await assertSessions(devices, true);
368
+ const { nodes: destinations, shouldIncludeDeviceIdentity } =
369
+ await createParticipantNodes(
370
+ devices,
371
+ { call: { callKey: new Uint8Array(encKey) } },
372
+ { count: "0" }
373
+ );
374
+ offerContent.push({ tag: "destination", attrs: {}, content: destinations });
375
+ if (shouldIncludeDeviceIdentity) {
376
+ offerContent.push({
377
+ tag: "device-identity",
378
+ attrs: {},
379
+ content: encodeSignedDeviceIdentity(
380
+ authState.creds.account,
381
+ true
382
+ ),
383
+ });
384
+ }
385
+ const stanza = {
386
+ tag: "call",
387
+ attrs: {
388
+ id: generateMessageIDV2(),
389
+ to: toJid,
390
+ },
391
+ content: [
392
+ {
393
+ tag: "offer",
394
+ attrs: {
395
+ "call-id": callId,
396
+ "call-creator": authState.creds.me.id,
397
+ },
398
+ content: offerContent,
399
+ },
400
+ ],
401
+ };
402
+ await query(stanza);
403
+ return {
404
+ id: callId,
405
+ to: toJid,
406
+ };
407
+ };
408
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
409
+ if (!recipientJids.length) {
410
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
411
+ }
412
+ const patched = await patchMessageBeforeSending(message, recipientJids);
413
+ const patchedMessages = Array.isArray(patched)
414
+ ? patched
415
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
416
+ let shouldIncludeDeviceIdentity = false;
417
+ const meId = authState.creds.me.id;
418
+ const meLid = authState.creds.me?.lid;
419
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
420
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
421
+ if (!jid)
422
+ return null;
423
+ let msgToEncrypt = patchedMessage;
424
+ if (dsmMessage) {
425
+ const { user: targetUser } = jidDecode(jid);
426
+ const { user: ownPnUser } = jidDecode(meId);
427
+ const ownLidUser = meLidUser;
428
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
429
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
430
+ if (isOwnUser && !isExactSenderDevice) {
431
+ msgToEncrypt = dsmMessage;
432
+ logger.debug({ jid, targetUser }, "Using DSM for own device");
433
+ }
434
+ }
435
+ const bytes = encodeWAMessage(msgToEncrypt);
436
+ const mutexKey = jid;
437
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
438
+ const { type, ciphertext } = await signalRepository.encryptMessage({
439
+ jid,
440
+ data: bytes
441
+ });
442
+ if (type === "pkmsg") {
443
+ shouldIncludeDeviceIdentity = true;
444
+ }
445
+ return {
446
+ tag: "to",
447
+ attrs: { jid },
448
+ content: [
449
+ {
450
+ tag: "enc",
451
+ attrs: {
452
+ v: "2",
453
+ type,
454
+ ...(extraAttrs || {})
455
+ },
456
+ content: ciphertext
457
+ }
458
+ ]
459
+ };
460
+ });
461
+ return node;
462
+ });
463
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
464
+ return { nodes, shouldIncludeDeviceIdentity };
465
+ };
466
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
467
+ const meId = authState.creds.me.id;
468
+ const meLid = authState.creds.me?.lid;
469
+ const isRetryResend = Boolean(participant?.jid);
470
+ let shouldIncludeDeviceIdentity = isRetryResend;
471
+ const statusJid = "status@broadcast";
472
+ const { user, server } = jidDecode(jid);
473
+ const isGroup = server === "g.us";
474
+ const isStatus = jid === statusJid;
475
+ const isLid = server === "lid";
476
+ const isNewsletter = server === "newsletter";
477
+ const finalJid = jid;
478
+ msgId = msgId || generateMessageIDV2(meId);
479
+ useUserDevicesCache = useUserDevicesCache !== false;
480
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
481
+ const participants = [];
482
+ const destinationJid = !isStatus ? finalJid : statusJid;
483
+ const binaryNodeContent = [];
484
+ const devices = [];
485
+ const meMsg = {
486
+ deviceSentMessage: {
487
+ destinationJid,
488
+ message
489
+ },
490
+ messageContextInfo: message.messageContextInfo
491
+ };
492
+ const extraAttrs = {};
493
+ if (participant) {
494
+ if (!isGroup && !isStatus) {
495
+ additionalAttributes = { ...additionalAttributes, device_fanout: "false" };
496
+ }
497
+ const { user, device } = jidDecode(participant.jid);
498
+ devices.push({
499
+ user,
500
+ device,
501
+ jid: participant.jid
502
+ });
503
+ }
504
+ await authState.keys.transaction(async () => {
505
+ const mediaType = getMediaType(message);
506
+ if (mediaType) {
507
+ extraAttrs["mediatype"] = mediaType;
508
+ }
509
+ if (isNewsletter) {
510
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
511
+ const bytes = encodeNewsletterMessage(patched);
512
+ binaryNodeContent.push({
513
+ tag: "plaintext",
514
+ attrs: {},
515
+ content: bytes
516
+ });
517
+ const stanza = {
518
+ tag: "message",
519
+ attrs: {
520
+ to: jid,
521
+ id: msgId,
522
+ type: getMessageType(message),
523
+ ...(additionalAttributes || {})
524
+ },
525
+ content: binaryNodeContent
526
+ };
527
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
528
+ await sendNode(stanza);
529
+ return;
530
+ }
531
+ if (normalizeMessageContent(message)?.pinInChatMessage) {
532
+ extraAttrs["decrypt-fail"] = "hide";
533
+ }
534
+ if (isGroup || isStatus) {
535
+ const [groupData, senderKeyMap] = await Promise.all([
536
+ (async () => {
537
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
538
+ if (groupData && Array.isArray(groupData?.participants)) {
539
+ logger.trace({ jid, participants: groupData.participants.length }, "using cached group metadata");
540
+ }
541
+ else if (!isStatus) {
542
+ groupData = await groupMetadata(jid);
543
+ }
544
+ return groupData;
545
+ })(),
546
+ (async () => {
547
+ if (!participant && !isStatus) {
548
+ const result = await authState.keys.get("sender-key-memory", [jid]);
549
+ return result[jid] || {};
550
+ }
551
+ return {};
552
+ })()
553
+ ]);
554
+ if (!participant) {
555
+ const participantsList = [];
556
+ if (isStatus) {
557
+ if (statusJidList?.length)
558
+ participantsList.push(...statusJidList);
559
+ }
560
+ else {
561
+ let groupAddressingMode = "lid";
562
+ if (groupData) {
563
+ participantsList.push(...groupData.participants.map(p => p.id));
564
+ groupAddressingMode = groupData?.addressingMode || groupAddressingMode;
565
+ }
566
+ additionalAttributes = {
567
+ ...additionalAttributes,
568
+ addressing_mode: groupAddressingMode
569
+ };
570
+ }
571
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
572
+ devices.push(...additionalDevices);
573
+ }
574
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
575
+ additionalAttributes = {
576
+ ...additionalAttributes,
577
+ expiration: groupData.ephemeralDuration.toString()
578
+ };
579
+ }
580
+ const patched = await patchMessageBeforeSending(message);
581
+ if (Array.isArray(patched)) {
582
+ throw new Boom("Per-jid patching is not supported in groups");
583
+ }
584
+ const bytes = encodeWAMessage(patched);
585
+ const groupAddressingMode = additionalAttributes?.["addressing_mode"] || groupData?.addressingMode || "lid";
586
+ const groupSenderIdentity = groupAddressingMode === "lid" && meLid ? meLid : meId;
587
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
588
+ group: destinationJid,
589
+ data: bytes,
590
+ meId: groupSenderIdentity
591
+ });
592
+ const senderKeyRecipients = [];
593
+ for (const device of devices) {
594
+ const deviceJid = device.jid;
595
+ const hasKey = !!senderKeyMap[deviceJid];
596
+ if ((!hasKey || !!participant) &&
597
+ !isHostedLidUser(deviceJid) &&
598
+ !isHostedPnUser(deviceJid) &&
599
+ device.device !== 99) {
600
+ senderKeyRecipients.push(deviceJid);
601
+ senderKeyMap[deviceJid] = true;
602
+ }
603
+ }
604
+ if (senderKeyRecipients.length) {
605
+ logger.debug({ senderKeyJids: senderKeyRecipients }, "sending new sender key");
606
+ const senderKeyMsg = {
607
+ senderKeyDistributionMessage: {
608
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
609
+ groupId: destinationJid
610
+ }
611
+ };
612
+ const senderKeySessionTargets = senderKeyRecipients;
613
+ await assertSessions(senderKeySessionTargets);
614
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
615
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
616
+ participants.push(...result.nodes);
617
+ }
618
+ if (isRetryResend) {
619
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
620
+ data: bytes,
621
+ jid: participant?.jid
622
+ });
623
+ binaryNodeContent.push({
624
+ tag: "enc",
625
+ attrs: {
626
+ v: "2",
627
+ type,
628
+ count: participant.count.toString()
629
+ },
630
+ content: encryptedContent
631
+ });
632
+ }
633
+ else {
634
+ binaryNodeContent.push({
635
+ tag: "enc",
636
+ attrs: { v: "2", type: "skmsg", ...extraAttrs },
637
+ content: ciphertext
638
+ });
639
+ await authState.keys.set({ "sender-key-memory": { [jid]: senderKeyMap } });
640
+ }
641
+ }
642
+ else {
643
+ let ownId = meId;
644
+ if (isLid && meLid) {
645
+ ownId = meLid;
646
+ logger.debug({ to: jid, ownId }, "Using LID identity for @lid conversation");
647
+ }
648
+ else {
649
+ logger.debug({ to: jid, ownId }, "Using PN identity for @s.whatsapp.net conversation");
650
+ }
651
+ const { user: ownUser } = jidDecode(ownId);
652
+ if (!participant) {
653
+ const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
654
+ devices.push({
655
+ user,
656
+ device: 0,
657
+ jid: jidEncode(user, targetUserServer, 0)
658
+ });
659
+ if (user !== ownUser) {
660
+ const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
661
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
662
+ devices.push({
663
+ user: ownUserForAddressing,
664
+ device: 0,
665
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
666
+ });
667
+ }
668
+ if (additionalAttributes?.["category"] !== "peer") {
669
+ devices.length = 0;
670
+ const senderIdentity = isLid && meLid
671
+ ? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
672
+ : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
673
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
674
+ devices.push(...sessionDevices);
675
+ logger.debug({
676
+ deviceCount: devices.length,
677
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
678
+ }, "Device enumeration complete with unified addressing");
679
+ }
680
+ }
681
+ const allRecipients = [];
682
+ const meRecipients = [];
683
+ const otherRecipients = [];
684
+ const { user: mePnUser } = jidDecode(meId);
685
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
686
+ for (const { user, jid } of devices) {
687
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
688
+ if (isExactSenderDevice) {
689
+ logger.debug({ jid, meId, meLid }, "Skipping exact sender device (whatsmeow pattern)");
690
+ continue;
691
+ }
692
+ const isMe = user === mePnUser || user === meLidUser;
693
+ if (isMe) {
694
+ meRecipients.push(jid);
695
+ }
696
+ else {
697
+ otherRecipients.push(jid);
698
+ }
699
+ allRecipients.push(jid);
700
+ }
701
+ await assertSessions(allRecipients);
702
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
703
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
704
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
705
+ ]);
706
+ participants.push(...meNodes);
707
+ participants.push(...otherNodes);
708
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
709
+ extraAttrs["phash"] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
710
+ }
711
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
712
+ }
713
+ if (participants.length) {
714
+ if (additionalAttributes?.["category"] === "peer") {
715
+ const peerNode = participants[0]?.content?.[0];
716
+ if (peerNode) {
717
+ binaryNodeContent.push(peerNode);
718
+ }
719
+ }
720
+ else {
721
+ binaryNodeContent.push({
722
+ tag: "participants",
723
+ attrs: {},
724
+ content: participants
725
+ });
726
+ }
727
+ }
728
+ const stanza = {
729
+ tag: "message",
730
+ attrs: {
731
+ id: msgId,
732
+ to: destinationJid,
733
+ type: getMessageType(message),
734
+ ...(additionalAttributes || {})
735
+ },
736
+ content: binaryNodeContent
737
+ };
738
+ if (participant) {
739
+ if (isJidGroup(destinationJid)) {
740
+ stanza.attrs.to = destinationJid;
741
+ stanza.attrs.participant = participant.lid;
742
+ }
743
+ else if (areJidsSameUser(participant.lid, meId)) {
744
+ stanza.attrs.to = participant.lid;
745
+ stanza.attrs.recipient = destinationJid;
746
+ }
747
+ else {
748
+ stanza.attrs.to = participant.lid;
749
+ }
750
+ }
751
+ else {
752
+ stanza.attrs.to = destinationJid;
753
+ }
754
+
755
+ if (shouldIncludeDeviceIdentity) {
756
+ stanza.content.push({
757
+ tag: "device-identity",
758
+ attrs: {},
759
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
760
+ });
761
+ logger.debug({ destinationJid }, "adding device identity");
762
+ }
763
+
764
+ if (additionalNodes && additionalNodes.length > 0) {
765
+ stanza.content.push(...additionalNodes);
766
+ }
767
+ else {
768
+ if ((isJidGroup(destinationJid) || isLidUser(destinationJid)) &&
769
+ (message?.viewOnceMessage ? message?.viewOnceMessage :
770
+ (message?.viewOnceMessageV2 ? message?.viewOnceMessageV2 :
771
+ (message?.viewOnceMessageV2Extension ? message?.viewOnceMessageV2Extension :
772
+ (message?.ephemeralMessage ? message?.ephemeralMessage :
773
+ (message?.templateMessage ? message?.templateMessage :
774
+ (message?.interactiveMessage ? message?.interactiveMessage :
775
+ message?.buttonsMessage))))))) {
776
+ stanza.content.push({
777
+ tag: "biz",
778
+ attrs: {},
779
+ content: [{
780
+ tag: "interactive",
781
+ attrs: {
782
+ type: "native_flow",
783
+ v: "1"
784
+ },
785
+ content: [{
786
+ tag: "native_flow",
787
+ attrs: { name: "quick_reply" }
788
+ }]
789
+ }]
790
+ });
791
+ }
792
+ }
793
+ const buttonType = getButtonType(message);
794
+ if (buttonType) {
795
+ stanza.content.push({
796
+ tag: "biz",
797
+ attrs: {},
798
+ content: [
799
+ {
800
+ tag: buttonType,
801
+ attrs: getButtonArgs(message),
802
+ }
803
+ ]
804
+ });
805
+ logger.debug({ jid }, "adding business node");
806
+ }
807
+
808
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
809
+ await sendNode(stanza);
810
+ });
811
+ return msgId;
812
+ };
813
+ const getMessageType = (message) => {
814
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
815
+ return "poll";
816
+ }
817
+ if (message.eventMessage) {
818
+ return "event";
819
+ }
820
+ if (getMediaType(message) !== "") {
821
+ return "media";
822
+ }
823
+ return "text";
824
+ };
825
+ const getMediaType = (message) => {
826
+ if (message.imageMessage) {
827
+ return "image";
828
+ }
829
+ else if (message.videoMessage) {
830
+ return message.videoMessage.gifPlayback ? "gif" : "video";
831
+ }
832
+ else if (message.audioMessage) {
833
+ return message.audioMessage.ptt ? "ptt" : "audio";
834
+ }
835
+ else if (message.contactMessage) {
836
+ return "vcard";
837
+ }
838
+ else if (message.documentMessage) {
839
+ return "document";
840
+ }
841
+ else if (message.contactsArrayMessage) {
842
+ return "contact_array";
843
+ }
844
+ else if (message.liveLocationMessage) {
845
+ return "livelocation";
846
+ }
847
+ else if (message.stickerMessage) {
848
+ return "sticker";
849
+ }
850
+ else if (message.listMessage) {
851
+ return "list";
852
+ }
853
+ else if (message.listResponseMessage) {
854
+ return "list_response";
855
+ }
856
+ else if (message.buttonsResponseMessage) {
857
+ return "buttons_response";
858
+ }
859
+ else if (message.orderMessage) {
860
+ return "order";
861
+ }
862
+ else if (message.productMessage) {
863
+ return "product";
864
+ }
865
+ else if (message.interactiveResponseMessage) {
866
+ return "native_flow_response";
867
+ }
868
+ else if (message.groupInviteMessage) {
869
+ return "url";
870
+ }
871
+ return "";
872
+ };
873
+ const getButtonType = (message) => {
874
+ if (message.buttonsMessage) {
875
+ return "buttons";
876
+ }
877
+ else if (message.buttonsResponseMessage) {
878
+ return "buttons_response";
879
+ }
880
+ else if (message.interactiveResponseMessage) {
881
+ return "interactive_response";
882
+ }
883
+ else if (message.listMessage) {
884
+ return "list";
885
+ }
886
+ else if (message.listResponseMessage) {
887
+ return "list_response";
888
+ }
889
+ };
890
+ const getButtonArgs = (message) => {
891
+ if (message.templateMessage) {
892
+ return {};
893
+ }
894
+ else if (message.listMessage) {
895
+ const type = message.listMessage.listType;
896
+ if (!type) {
897
+ throw new Boom("Expected list type inside message");
898
+ }
899
+ return { v: "2", type: proto.ListMessage.ListType[type].toLowerCase() };
900
+ }
901
+ else {
902
+ return {};
903
+ }
904
+ };
905
+ const getPrivacyTokens = async (jids) => {
906
+ const t = unixTimestampSeconds().toString();
907
+ const result = await query({
908
+ tag: "iq",
909
+ attrs: {
910
+ to: S_WHATSAPP_NET,
911
+ type: "set",
912
+ xmlns: "privacy"
913
+ },
914
+ content: [
915
+ {
916
+ tag: "tokens",
917
+ attrs: {},
918
+ content: jids.map(jid => ({
919
+ tag: "token",
920
+ attrs: {
921
+ jid: jidNormalizedUser(jid),
922
+ t,
923
+ type: "trusted_contact"
924
+ }
925
+ }))
926
+ }
927
+ ]
928
+ });
929
+ return result;
930
+ };
931
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
932
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
933
+ return {
934
+ ...sock,
935
+ offerCall,
936
+ getButtonType,
937
+ getButtonArgs,
938
+ getPrivacyTokens,
939
+ assertSessions,
940
+ relayMessage,
941
+ sendReceipt,
942
+ sendReceipts,
943
+ readMessages,
944
+ refreshMediaConn,
945
+ waUploadToServer,
946
+ fetchPrivacySettings,
947
+ sendPeerDataOperationMessage,
948
+ createParticipantNodes,
949
+ getUSyncDevices,
950
+ messageRetryManager,
951
+ updateMediaMessage: async (message) => {
952
+ const content = assertMediaContent(message.message);
953
+ const mediaKey = content.mediaKey;
954
+ const meId = authState.creds.me.id;
955
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
956
+ let error = undefined;
957
+ await Promise.all([
958
+ sendNode(node),
959
+ waitForMsgMediaUpdate(async (update) => {
960
+ const result = update.find(c => c.key.id === message.key.id);
961
+ if (result) {
962
+ if (result.error) {
963
+ error = result.error;
964
+ }
965
+ else {
966
+ try {
967
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
968
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
969
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
970
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
971
+ data: media,
972
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
973
+ });
974
+ }
975
+ content.directPath = media.directPath;
976
+ content.url = getUrlFromDirectPath(content.directPath);
977
+ logger.debug({ directPath: media.directPath, key: result.key }, "media update successful");
978
+ }
979
+ catch (err) {
980
+ error = err;
981
+ }
982
+ }
983
+ return true;
984
+ }
985
+ })
986
+ ]);
987
+ if (error) {
988
+ throw error;
989
+ }
990
+ ev.emit("messages.update", [{ key: message.key, update: { message: message.message } }]);
991
+ return message;
992
+ },
993
+ sendMessage: async (jid, content, options = {}) => {
994
+ const userJid = authState.creds.me.id;
995
+ if (typeof content === "object" &&
996
+ "disappearingMessagesInChat" in content &&
997
+ typeof content["disappearingMessagesInChat"] !== "undefined" &&
998
+ isJidGroup(jid)) {
999
+ const { disappearingMessagesInChat } = content;
1000
+ const value = typeof disappearingMessagesInChat === "boolean"
1001
+ ? disappearingMessagesInChat
1002
+ ? WA_DEFAULT_EPHEMERAL
1003
+ : 0
1004
+ : disappearingMessagesInChat;
1005
+ await groupToggleEphemeral(jid, value);
1006
+ }
1007
+ else {
1008
+ const fullMsg = await generateWAMessage(jid, content, {
1009
+ logger,
1010
+ userJid,
1011
+ getUrlInfo: text => getUrlInfo(text, {
1012
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1013
+ fetchOpts: {
1014
+ timeout: 3000,
1015
+ ...(httpRequestOptions || {})
1016
+ },
1017
+ logger,
1018
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1019
+ }),
1020
+ getProfilePicUrl: sock.profilePictureUrl,
1021
+ getCallLink: sock.createCallLink,
1022
+ upload: waUploadToServer,
1023
+ mediaCache: config.mediaCache,
1024
+ options: config.options,
1025
+ messageId: generateMessageIDV2(sock.user?.id),
1026
+ ...options
1027
+ });
1028
+ const isEventMsg = "event" in content && !!content.event;
1029
+ const isDeleteMsg = "delete" in content && !!content.delete;
1030
+ const isEditMsg = "edit" in content && !!content.edit;
1031
+ const isPinMsg = "pin" in content && !!content.pin;
1032
+ const isPollMessage = "poll" in content && !!content.poll;
1033
+ const additionalAttributes = {};
1034
+ const additionalNodes = [];
1035
+ if (isDeleteMsg) {
1036
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1037
+ additionalAttributes.edit = "8";
1038
+ }
1039
+ else {
1040
+ additionalAttributes.edit = "7";
1041
+ }
1042
+ }
1043
+ else if (isEditMsg) {
1044
+ additionalAttributes.edit = "1";
1045
+ }
1046
+ else if (isPinMsg) {
1047
+ additionalAttributes.edit = "2";
1048
+ }
1049
+ else if (isPollMessage) {
1050
+ additionalNodes.push({
1051
+ tag: "meta",
1052
+ attrs: {
1053
+ polltype: "creation"
1054
+ }
1055
+ });
1056
+ }
1057
+ else if (isEventMsg) {
1058
+ additionalNodes.push({
1059
+ tag: "meta",
1060
+ attrs: {
1061
+ event_type: "creation"
1062
+ }
1063
+ });
1064
+ }
1065
+ await relayMessage(jid, fullMsg.message, {
1066
+ messageId: fullMsg.key.id,
1067
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1068
+ additionalAttributes,
1069
+ statusJidList: options.statusJidList,
1070
+ additionalNodes
1071
+ });
1072
+ if (config.emitOwnEvents) {
1073
+ process.nextTick(() => {
1074
+ processingMutex.mutex(() => upsertMessage(fullMsg, "append"));
1075
+ });
1076
+ }
1077
+ return fullMsg;
1078
+ }
1079
+ }
1080
+ };
1081
+ };
1082
+ //=======================================================//