@xbibzlibrary/whatsbibz 1.3.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 (260) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +22 -0
  3. package/LICENSE.upstream +21 -0
  4. package/README.md +280 -0
  5. package/VERIFIKASI-IDENTITAS-2026-09-03.md +138 -0
  6. package/WAProto/GenerateStatics.sh +3 -0
  7. package/WAProto/WAProto.proto +6035 -0
  8. package/WAProto/fix-imports.js +81 -0
  9. package/WAProto/index.d.ts +15314 -0
  10. package/WAProto/index.js +132326 -0
  11. package/assets/logo/README.md +21 -0
  12. package/assets/logo/png/banner-1200x360.png +0 -0
  13. package/assets/logo/png/icon-1024.png +0 -0
  14. package/assets/logo/png/icon-128.png +0 -0
  15. package/assets/logo/png/icon-16.png +0 -0
  16. package/assets/logo/png/icon-24.png +0 -0
  17. package/assets/logo/png/icon-256.png +0 -0
  18. package/assets/logo/png/icon-32.png +0 -0
  19. package/assets/logo/png/icon-48.png +0 -0
  20. package/assets/logo/png/icon-512.png +0 -0
  21. package/assets/logo/png/icon-64.png +0 -0
  22. package/assets/logo/png/mark-512.png +0 -0
  23. package/assets/logo/preview.png +0 -0
  24. package/assets/logo/whatsbibz.ico +0 -0
  25. package/lib/BibzWhats/client.d.ts +95 -0
  26. package/lib/BibzWhats/client.js +501 -0
  27. package/lib/BibzWhats/device-identity.d.ts +60 -0
  28. package/lib/BibzWhats/device-identity.js +234 -0
  29. package/lib/BibzWhats/extract.d.ts +29 -0
  30. package/lib/BibzWhats/extract.js +115 -0
  31. package/lib/BibzWhats/index.d.ts +7 -0
  32. package/lib/BibzWhats/index.js +8 -0
  33. package/lib/BibzWhats/jid.d.ts +22 -0
  34. package/lib/BibzWhats/jid.js +98 -0
  35. package/lib/BibzWhats/pairing.d.ts +35 -0
  36. package/lib/BibzWhats/pairing.js +186 -0
  37. package/lib/BibzWhats/send.d.ts +9 -0
  38. package/lib/BibzWhats/send.js +107 -0
  39. package/lib/BibzWhats/version.d.ts +6 -0
  40. package/lib/BibzWhats/version.js +7 -0
  41. package/lib/Defaults/index.d.ts +73 -0
  42. package/lib/Defaults/index.js +141 -0
  43. package/lib/Modded/message_builder.d.ts +15 -0
  44. package/lib/Modded/message_builder.js +2330 -0
  45. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  46. package/lib/Signal/Group/ciphertext-message.js +11 -0
  47. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  48. package/lib/Signal/Group/group-session-builder.js +29 -0
  49. package/lib/Signal/Group/group_cipher.d.ts +16 -0
  50. package/lib/Signal/Group/group_cipher.js +81 -0
  51. package/lib/Signal/Group/index.d.ts +11 -0
  52. package/lib/Signal/Group/index.js +11 -0
  53. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  54. package/lib/Signal/Group/keyhelper.js +17 -0
  55. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  56. package/lib/Signal/Group/sender-chain-key.js +25 -0
  57. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  58. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  59. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  60. package/lib/Signal/Group/sender-key-message.js +65 -0
  61. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  62. package/lib/Signal/Group/sender-key-name.js +47 -0
  63. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  64. package/lib/Signal/Group/sender-key-record.js +40 -0
  65. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  66. package/lib/Signal/Group/sender-key-state.js +83 -0
  67. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  68. package/lib/Signal/Group/sender-message-key.js +25 -0
  69. package/lib/Signal/libsignal.d.ts +4 -0
  70. package/lib/Signal/libsignal.js +406 -0
  71. package/lib/Signal/lid-mapping.d.ts +18 -0
  72. package/lib/Signal/lid-mapping.js +276 -0
  73. package/lib/Socket/Client/index.d.ts +2 -0
  74. package/lib/Socket/Client/index.js +2 -0
  75. package/lib/Socket/Client/types.d.ts +15 -0
  76. package/lib/Socket/Client/types.js +10 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -0
  78. package/lib/Socket/Client/websocket.js +53 -0
  79. package/lib/Socket/business.d.ts +537 -0
  80. package/lib/Socket/business.js +421 -0
  81. package/lib/Socket/chats.d.ts +110 -0
  82. package/lib/Socket/chats.js +1006 -0
  83. package/lib/Socket/communities.d.ts +646 -0
  84. package/lib/Socket/communities.js +430 -0
  85. package/lib/Socket/engine.d.ts +129 -0
  86. package/lib/Socket/engine.js +767 -0
  87. package/lib/Socket/groups.d.ts +149 -0
  88. package/lib/Socket/groups.js +326 -0
  89. package/lib/Socket/index.d.ts +637 -0
  90. package/lib/Socket/index.js +14 -0
  91. package/lib/Socket/messages-recv.d.ts +239 -0
  92. package/lib/Socket/messages-recv.js +1307 -0
  93. package/lib/Socket/messages-send.d.ts +580 -0
  94. package/lib/Socket/messages-send.js +1639 -0
  95. package/lib/Socket/mex.d.ts +2 -0
  96. package/lib/Socket/mex.js +47 -0
  97. package/lib/Socket/newsletter.d.ts +176 -0
  98. package/lib/Socket/newsletter.js +456 -0
  99. package/lib/Socket/socket.d.ts +56 -0
  100. package/lib/Socket/socket.js +998 -0
  101. package/lib/Types/Auth.d.ts +115 -0
  102. package/lib/Types/Auth.js +1 -0
  103. package/lib/Types/Bussines.d.ts +36 -0
  104. package/lib/Types/Bussines.js +1 -0
  105. package/lib/Types/Call.d.ts +14 -0
  106. package/lib/Types/Call.js +1 -0
  107. package/lib/Types/Chat.d.ts +124 -0
  108. package/lib/Types/Chat.js +7 -0
  109. package/lib/Types/Contact.d.ts +23 -0
  110. package/lib/Types/Contact.js +1 -0
  111. package/lib/Types/Events.d.ts +241 -0
  112. package/lib/Types/Events.js +1 -0
  113. package/lib/Types/GroupMetadata.d.ts +67 -0
  114. package/lib/Types/GroupMetadata.js +1 -0
  115. package/lib/Types/Label.d.ts +46 -0
  116. package/lib/Types/Label.js +24 -0
  117. package/lib/Types/LabelAssociation.d.ts +29 -0
  118. package/lib/Types/LabelAssociation.js +6 -0
  119. package/lib/Types/Message.d.ts +427 -0
  120. package/lib/Types/Message.js +10 -0
  121. package/lib/Types/Newsletter.d.ts +134 -0
  122. package/lib/Types/Newsletter.js +30 -0
  123. package/lib/Types/Product.d.ts +78 -0
  124. package/lib/Types/Product.js +1 -0
  125. package/lib/Types/Signal.d.ts +77 -0
  126. package/lib/Types/Signal.js +1 -0
  127. package/lib/Types/Socket.d.ts +173 -0
  128. package/lib/Types/Socket.js +2 -0
  129. package/lib/Types/State.d.ts +38 -0
  130. package/lib/Types/State.js +12 -0
  131. package/lib/Types/USync.d.ts +25 -0
  132. package/lib/Types/USync.js +1 -0
  133. package/lib/Types/index.d.ts +75 -0
  134. package/lib/Types/index.js +32 -0
  135. package/lib/Utils/auth-utils.d.ts +18 -0
  136. package/lib/Utils/auth-utils.js +289 -0
  137. package/lib/Utils/browser-utils.d.ts +3 -0
  138. package/lib/Utils/browser-utils.js +47 -0
  139. package/lib/Utils/business.d.ts +22 -0
  140. package/lib/Utils/business.js +230 -0
  141. package/lib/Utils/chat-utils.d.ts +69 -0
  142. package/lib/Utils/chat-utils.js +811 -0
  143. package/lib/Utils/companion-reg-client-utils.d.ts +20 -0
  144. package/lib/Utils/companion-reg-client-utils.js +66 -0
  145. package/lib/Utils/crypto.d.ts +41 -0
  146. package/lib/Utils/crypto.js +117 -0
  147. package/lib/Utils/decode-wa-message.d.ts +47 -0
  148. package/lib/Utils/decode-wa-message.js +282 -0
  149. package/lib/Utils/event-buffer.d.ts +35 -0
  150. package/lib/Utils/event-buffer.js +590 -0
  151. package/lib/Utils/generics.d.ts +90 -0
  152. package/lib/Utils/generics.js +384 -0
  153. package/lib/Utils/history.d.ts +21 -0
  154. package/lib/Utils/history.js +130 -0
  155. package/lib/Utils/identity-change-handler.d.ts +36 -0
  156. package/lib/Utils/identity-change-handler.js +48 -0
  157. package/lib/Utils/index.d.ts +25 -0
  158. package/lib/Utils/index.js +24 -0
  159. package/lib/Utils/link-preview.d.ts +20 -0
  160. package/lib/Utils/link-preview.js +84 -0
  161. package/lib/Utils/logger.d.ts +12 -0
  162. package/lib/Utils/logger.js +2 -0
  163. package/lib/Utils/lt-hash.d.ts +10 -0
  164. package/lib/Utils/lt-hash.js +7 -0
  165. package/lib/Utils/make-mutex.d.ts +8 -0
  166. package/lib/Utils/make-mutex.js +32 -0
  167. package/lib/Utils/message-retry-manager.d.ts +109 -0
  168. package/lib/Utils/message-retry-manager.js +224 -0
  169. package/lib/Utils/messages-media.d.ts +129 -0
  170. package/lib/Utils/messages-media.js +784 -0
  171. package/lib/Utils/messages.d.ts +90 -0
  172. package/lib/Utils/messages.js +1240 -0
  173. package/lib/Utils/noise-handler.d.ts +19 -0
  174. package/lib/Utils/noise-handler.js +200 -0
  175. package/lib/Utils/offline-node-processor.d.ts +16 -0
  176. package/lib/Utils/offline-node-processor.js +39 -0
  177. package/lib/Utils/platform-identity.d.ts +14 -0
  178. package/lib/Utils/platform-identity.js +148 -0
  179. package/lib/Utils/pre-key-manager.d.ts +27 -0
  180. package/lib/Utils/pre-key-manager.js +105 -0
  181. package/lib/Utils/process-message.d.ts +59 -0
  182. package/lib/Utils/process-message.js +544 -0
  183. package/lib/Utils/reporting-utils.d.ts +10 -0
  184. package/lib/Utils/reporting-utils.js +257 -0
  185. package/lib/Utils/rich-messages.d.ts +276 -0
  186. package/lib/Utils/rich-messages.js +1143 -0
  187. package/lib/Utils/signal.d.ts +33 -0
  188. package/lib/Utils/signal.js +158 -0
  189. package/lib/Utils/stanza-ack.d.ts +10 -0
  190. package/lib/Utils/stanza-ack.js +37 -0
  191. package/lib/Utils/sticker-pack.d.ts +10 -0
  192. package/lib/Utils/sticker-pack.js +111 -0
  193. package/lib/Utils/sync-action-utils.d.ts +18 -0
  194. package/lib/Utils/sync-action-utils.js +47 -0
  195. package/lib/Utils/tc-token-utils.d.ts +8 -0
  196. package/lib/Utils/tc-token-utils.js +45 -0
  197. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  198. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  199. package/lib/Utils/validate-connection.d.ts +10 -0
  200. package/lib/Utils/validate-connection.js +222 -0
  201. package/lib/VoIP/audio-feeder.d.ts +15 -0
  202. package/lib/VoIP/audio-feeder.js +136 -0
  203. package/lib/VoIP/index.d.ts +12 -0
  204. package/lib/VoIP/index.js +282 -0
  205. package/lib/VoIP/relay-transport.d.ts +43 -0
  206. package/lib/VoIP/relay-transport.js +559 -0
  207. package/lib/VoIP/signaling.js +603 -0
  208. package/lib/VoIP/types.d.ts +69 -0
  209. package/lib/VoIP/types.js +17 -0
  210. package/lib/VoIP/wasm-engine.d.ts +103 -0
  211. package/lib/VoIP/wasm-engine.js +1214 -0
  212. package/lib/VoIP/worker-bootstrap.js +1042 -0
  213. package/lib/WABinary/constants.d.ts +27 -0
  214. package/lib/WABinary/constants.js +1300 -0
  215. package/lib/WABinary/decode.d.ts +6 -0
  216. package/lib/WABinary/decode.js +261 -0
  217. package/lib/WABinary/encode.d.ts +2 -0
  218. package/lib/WABinary/encode.js +219 -0
  219. package/lib/WABinary/generic-utils.d.ts +16 -0
  220. package/lib/WABinary/generic-utils.js +190 -0
  221. package/lib/WABinary/index.d.ts +5 -0
  222. package/lib/WABinary/index.js +5 -0
  223. package/lib/WABinary/jid-utils.d.ts +47 -0
  224. package/lib/WABinary/jid-utils.js +95 -0
  225. package/lib/WABinary/types.d.ts +18 -0
  226. package/lib/WABinary/types.js +1 -0
  227. package/lib/WAM/BinaryInfo.d.ts +8 -0
  228. package/lib/WAM/BinaryInfo.js +9 -0
  229. package/lib/WAM/constants.d.ts +39 -0
  230. package/lib/WAM/constants.js +22852 -0
  231. package/lib/WAM/encode.d.ts +2 -0
  232. package/lib/WAM/encode.js +149 -0
  233. package/lib/WAM/index.d.ts +3 -0
  234. package/lib/WAM/index.js +3 -0
  235. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  236. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  237. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  238. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  239. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  240. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  242. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  243. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  244. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  245. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +9 -0
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  247. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  248. package/lib/WAUSync/Protocols/index.js +4 -0
  249. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  250. package/lib/WAUSync/USyncQuery.js +93 -0
  251. package/lib/WAUSync/USyncUser.d.ts +12 -0
  252. package/lib/WAUSync/USyncUser.js +22 -0
  253. package/lib/WAUSync/index.d.ts +3 -0
  254. package/lib/WAUSync/index.js +3 -0
  255. package/lib/assets/wasm/loader.js +5 -0
  256. package/lib/assets/wasm/whatsapp.wasm +0 -0
  257. package/lib/assets/wasm/worker-modules.js +273 -0
  258. package/lib/index.d.ts +21 -0
  259. package/lib/index.js +22 -0
  260. package/package.json +111 -0
@@ -0,0 +1,1639 @@
1
+ import NodeCache from "@cacheable/node-cache";
2
+ import { Boom } from "@hapi/boom";
3
+ import { proto } from "../../WAProto/index.js";
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from "../Defaults/index.js";
5
+ import {
6
+ aggregateMessageKeysNotFromMe,
7
+ assertMediaContent,
8
+ bindWaitForEvent,
9
+ decryptMediaRetryData,
10
+ encodeNewsletterMessage,
11
+ encodeSignedDeviceIdentity,
12
+ encodeWAMessage,
13
+ encryptMediaRetryRequest,
14
+ extractDeviceJids,
15
+ generateMessageIDV2,
16
+ generateParticipantHashV2,
17
+ generateWAMessage,
18
+ generateWAMessageFromContent,
19
+ getStatusCodeForMediaRetry,
20
+ getUrlFromDirectPath,
21
+ getWAUploadToServer,
22
+ MessageRetryManager,
23
+ normalizeMessageContent,
24
+ prepareWAMessageMedia,
25
+ parseAndInjectE2ESessions,
26
+ unixTimestampSeconds,
27
+ } from "../Utils/index.js";
28
+ import {
29
+ generateTableContent,
30
+ generateTableContentV2,
31
+ generateListContent,
32
+ generateCodeBlockContent,
33
+ generateCodeBlockContentV2,
34
+ generateLinkContent,
35
+ generateLinkContentV2,
36
+ generateRichMessageContent,
37
+ generateLatexContent,
38
+ generateLatexImageContent,
39
+ generateLatexInlineImageContent,
40
+ generateUnifiedResponseContent,
41
+ captureUnifiedResponse,
42
+ } from "../Utils/rich-messages.js";
43
+ import { getUrlInfo } from "../Utils/link-preview.js";
44
+ import { makeKeyedMutex } from "../Utils/make-mutex.js";
45
+ import {
46
+ getMessageReportingToken,
47
+ shouldIncludeReportingToken,
48
+ } from "../Utils/reporting-utils.js";
49
+ import {
50
+ areJidsSameUser,
51
+ getAdditionalNode,
52
+ getBinaryNodeChild,
53
+ getBinaryNodeChildren,
54
+ isHostedLidUser,
55
+ isHostedPnUser,
56
+ isJidGroup,
57
+ isJidNewsletter,
58
+ isLidUser,
59
+ isPnUser,
60
+ jidDecode,
61
+ jidEncode,
62
+ jidNormalizedUser,
63
+ S_WHATSAPP_NET,
64
+ } from "../WABinary/index.js";
65
+ import { USyncQuery, USyncUser } from "../WAUSync/index.js";
66
+ import { BibzWhatsEngine } from "./engine.js";
67
+ import { makeNewsletterSocket } from "./newsletter.js";
68
+ import { isTcTokenExpired } from "../Utils/tc-token-utils.js";
69
+ const NATIVE_FLOW_BUTTON_MAP = {
70
+ review_and_pay: "order_details",
71
+ review_order: "order_status",
72
+ payment_info: "payment_info",
73
+ payment_status: "payment_status",
74
+ payment_method: "payment_method",
75
+ };
76
+ const getButtonType = (message) => {
77
+ const msg = normalizeMessageContent(message) || message;
78
+ if (msg?.buttonsMessage || msg?.listMessage)
79
+ return msg.listMessage ? "list" : "buttons";
80
+ const vm = msg?.viewOnceMessage?.message || msg?.viewOnceMessageV2?.message;
81
+ const im = vm?.interactiveMessage || msg?.interactiveMessage;
82
+ if (!im?.nativeFlowMessage) return null;
83
+ const btnName = im.nativeFlowMessage?.buttons?.[0]?.name;
84
+ if (btnName && NATIVE_FLOW_BUTTON_MAP[btnName])
85
+ return NATIVE_FLOW_BUTTON_MAP[btnName];
86
+ return "interactive";
87
+ };
88
+ const normalizeRecipientJid = (input) => {
89
+ if (!input || typeof input !== "string") return "";
90
+ const trimmed = input.trim();
91
+ if (
92
+ trimmed.endsWith("@s.whatsapp.net") ||
93
+ trimmed.endsWith("@lid") ||
94
+ trimmed.endsWith("@g.us") ||
95
+ trimmed.endsWith("@broadcast")
96
+ ) {
97
+ return trimmed;
98
+ }
99
+ const cleanNumber = trimmed.replace(/\D/g, "");
100
+ return cleanNumber ? `${cleanNumber}@s.whatsapp.net` : "";
101
+ };
102
+ const normalizeRecipientList = (list) => {
103
+ if (!list) return [];
104
+ const arr = Array.isArray(list) ? list : [list];
105
+ return arr.map(normalizeRecipientJid).filter(Boolean);
106
+ };
107
+ export const makeMessagesSocket = (config) => {
108
+ const {
109
+ logger,
110
+ linkPreviewImageThumbnailWidth,
111
+ generateHighQualityLinkPreview,
112
+ options: httpRequestOptions,
113
+ patchMessageBeforeSending,
114
+ cachedGroupMetadata,
115
+ enableRecentMessageCache,
116
+ maxMsgRetryCount,
117
+ } = config;
118
+ const sock = makeNewsletterSocket(config);
119
+ const {
120
+ ev,
121
+ authState,
122
+ messageMutex,
123
+ signalRepository,
124
+ upsertMessage,
125
+ query,
126
+ fetchPrivacySettings,
127
+ sendNode,
128
+ groupMetadata,
129
+ groupToggleEphemeral,
130
+ } = sock;
131
+ const userDevicesCache =
132
+ config.userDevicesCache ||
133
+ new NodeCache({
134
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
135
+ useClones: false,
136
+ });
137
+ const peerSessionsCache = new NodeCache({
138
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
139
+ useClones: false,
140
+ });
141
+ // Initialize message retry manager if enabled
142
+ const messageRetryManager = enableRecentMessageCache
143
+ ? new MessageRetryManager(logger, maxMsgRetryCount)
144
+ : null;
145
+ // Prevent race conditions in Signal session encryption by user
146
+ const encryptionMutex = makeKeyedMutex();
147
+ let mediaConn;
148
+ const refreshMediaConn = async (forceGet = false) => {
149
+ const media = await mediaConn;
150
+ if (
151
+ !media ||
152
+ forceGet ||
153
+ new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000
154
+ ) {
155
+ mediaConn = (async () => {
156
+ const result = await query({
157
+ tag: "iq",
158
+ attrs: {
159
+ type: "set",
160
+ xmlns: "w:m",
161
+ to: S_WHATSAPP_NET,
162
+ },
163
+ content: [{ tag: "media_conn", attrs: {} }],
164
+ });
165
+ const mediaConnNode = getBinaryNodeChild(result, "media_conn");
166
+ // TODO: explore full length of data that whatsapp provides
167
+ const node = {
168
+ hosts: getBinaryNodeChildren(mediaConnNode, "host").map(
169
+ ({ attrs }) => ({
170
+ hostname: attrs.hostname,
171
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
172
+ }),
173
+ ),
174
+ auth: mediaConnNode.attrs.auth,
175
+ ttl: +mediaConnNode.attrs.ttl,
176
+ fetchDate: new Date(),
177
+ };
178
+ logger.debug("fetched media conn");
179
+ return node;
180
+ })();
181
+ }
182
+ return mediaConn;
183
+ };
184
+ /**
185
+ * generic send receipt function
186
+ * used for receipts of phone call, read, delivery etc.
187
+ * */
188
+ const sendReceipt = async (jid, participant, messageIds, type) => {
189
+ if (!messageIds || messageIds.length === 0) {
190
+ throw new Boom("missing ids in receipt");
191
+ }
192
+ const node = {
193
+ tag: "receipt",
194
+ attrs: {
195
+ id: messageIds[0],
196
+ },
197
+ };
198
+ const isReadReceipt = type === "read" || type === "read-self";
199
+ if (isReadReceipt) {
200
+ node.attrs.t = unixTimestampSeconds().toString();
201
+ }
202
+ if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
203
+ node.attrs.recipient = jid;
204
+ node.attrs.to = participant;
205
+ } else {
206
+ node.attrs.to = jid;
207
+ if (participant) {
208
+ node.attrs.participant = participant;
209
+ }
210
+ }
211
+ if (type) {
212
+ node.attrs.type = type;
213
+ }
214
+ const remainingMessageIds = messageIds.slice(1);
215
+ if (remainingMessageIds.length) {
216
+ node.content = [
217
+ {
218
+ tag: "list",
219
+ attrs: {},
220
+ content: remainingMessageIds.map((id) => ({
221
+ tag: "item",
222
+ attrs: { id },
223
+ })),
224
+ },
225
+ ];
226
+ }
227
+ logger.debug(
228
+ { attrs: node.attrs, messageIds },
229
+ "sending receipt for messages",
230
+ );
231
+ await sendNode(node);
232
+ };
233
+ /** Correctly bulk send receipts to multiple chats, participants */
234
+ const sendReceipts = async (keys, type) => {
235
+ const recps = aggregateMessageKeysNotFromMe(keys);
236
+ for (const { jid, participant, messageIds } of recps) {
237
+ await sendReceipt(jid, participant, messageIds, type);
238
+ }
239
+ };
240
+ /** Bulk read messages. Keys can be from different chats & participants */
241
+ const readMessages = async (keys) => {
242
+ const privacySettings = await fetchPrivacySettings();
243
+ // based on privacy settings, we have to change the read type
244
+ const readType =
245
+ privacySettings.readreceipts === "all" ? "read" : "read-self";
246
+ await sendReceipts(keys, readType);
247
+ };
248
+ /** Fetch all the devices we've to send a message to */
249
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
250
+ const deviceResults = [];
251
+ if (!useCache) {
252
+ logger.debug("not using cache for devices");
253
+ }
254
+ const toFetch = [];
255
+ const jidsWithUser = jids
256
+ .map((jid) => {
257
+ const decoded = jidDecode(jid);
258
+ const user = decoded?.user;
259
+ const device = decoded?.device;
260
+ const isExplicitDevice = typeof device === "number" && device >= 0;
261
+ if (isExplicitDevice && user) {
262
+ deviceResults.push({
263
+ user,
264
+ device,
265
+ jid,
266
+ });
267
+ return null;
268
+ }
269
+ jid = jidNormalizedUser(jid);
270
+ return { jid, user };
271
+ })
272
+ .filter((jid) => jid !== null);
273
+ let mgetDevices;
274
+ if (useCache && userDevicesCache.mget) {
275
+ const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
276
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
277
+ }
278
+ for (const { jid, user } of jidsWithUser) {
279
+ if (useCache) {
280
+ const devices =
281
+ mgetDevices?.[user] ||
282
+ (userDevicesCache.mget
283
+ ? undefined
284
+ : await userDevicesCache.get(user));
285
+ if (devices) {
286
+ const devicesWithJid = devices.map((d) => ({
287
+ ...d,
288
+ jid: jidEncode(d.user, d.server, d.device),
289
+ }));
290
+ deviceResults.push(...devicesWithJid);
291
+ logger.trace({ user }, "using cache for devices");
292
+ } else {
293
+ toFetch.push(jid);
294
+ }
295
+ } else {
296
+ toFetch.push(jid);
297
+ }
298
+ }
299
+ if (!toFetch.length) {
300
+ return deviceResults;
301
+ }
302
+ const requestedLidUsers = new Set();
303
+ for (const jid of toFetch) {
304
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
305
+ const user = jidDecode(jid)?.user;
306
+ if (user) requestedLidUsers.add(user);
307
+ }
308
+ }
309
+ const query = new USyncQuery()
310
+ .withContext("message")
311
+ .withDeviceProtocol()
312
+ .withLIDProtocol();
313
+ for (const jid of toFetch) {
314
+ 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
315
+ }
316
+ const result = await sock.executeUSyncQuery(query);
317
+ if (result) {
318
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
319
+ const lidResults = result.list.filter((a) => !!a.lid);
320
+ if (lidResults.length > 0) {
321
+ logger.trace("Storing LID maps from device call");
322
+ await signalRepository.lidMapping.storeLIDPNMappings(
323
+ lidResults.map((a) => ({ lid: a.lid, pn: a.id })),
324
+ );
325
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
326
+ try {
327
+ const lids = lidResults.map((a) => a.lid);
328
+ if (lids.length) {
329
+ await assertSessions(lids, true);
330
+ }
331
+ } catch (e) {
332
+ logger.warn(
333
+ { e, count: lidResults.length },
334
+ "failed to assert sessions for newly mapped LIDs",
335
+ );
336
+ }
337
+ }
338
+ const extracted = extractDeviceJids(
339
+ result?.list,
340
+ authState.creds.me.id,
341
+ authState.creds.me.lid,
342
+ ignoreZeroDevices,
343
+ );
344
+ const deviceMap = {};
345
+ for (const item of extracted) {
346
+ deviceMap[item.user] = deviceMap[item.user] || [];
347
+ deviceMap[item.user]?.push(item);
348
+ }
349
+ // Process each user's devices as a group for bulk LID migration
350
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
351
+ const isLidUser = requestedLidUsers.has(user);
352
+ // Process all devices for this user
353
+ for (const item of userDevices) {
354
+ const finalJid = isLidUser
355
+ ? jidEncode(user, item.server, item.device)
356
+ : jidEncode(item.user, item.server, item.device);
357
+ deviceResults.push({
358
+ ...item,
359
+ jid: finalJid,
360
+ });
361
+ logger.debug(
362
+ {
363
+ user: item.user,
364
+ device: item.device,
365
+ finalJid,
366
+ usedLid: isLidUser,
367
+ },
368
+ "Processed device with LID priority",
369
+ );
370
+ }
371
+ }
372
+ if (userDevicesCache.mset) {
373
+ // if the cache supports mset, we can set all devices in one go
374
+ await userDevicesCache.mset(
375
+ Object.entries(deviceMap).map(([key, value]) => ({ key, value })),
376
+ );
377
+ } else {
378
+ for (const key in deviceMap) {
379
+ if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
380
+ }
381
+ }
382
+ const userDeviceUpdates = {};
383
+ for (const [userId, devices] of Object.entries(deviceMap)) {
384
+ if (devices && devices.length > 0) {
385
+ userDeviceUpdates[userId] = devices.map(
386
+ (d) => d.device?.toString() || "0",
387
+ );
388
+ }
389
+ }
390
+ if (Object.keys(userDeviceUpdates).length > 0) {
391
+ try {
392
+ await authState.keys.set({ "device-list": userDeviceUpdates });
393
+ logger.debug(
394
+ { userCount: Object.keys(userDeviceUpdates).length },
395
+ "stored user device lists for bulk migration",
396
+ );
397
+ } catch (error) {
398
+ logger.warn({ error }, "failed to store user device lists");
399
+ }
400
+ }
401
+ }
402
+ return deviceResults;
403
+ };
404
+ /**
405
+ * Update Member Label
406
+ */
407
+ const updateMemberLabel = (jid, memberLabel) => {
408
+ return relayMessage(
409
+ jid,
410
+ {
411
+ protocolMessage: {
412
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
413
+ memberLabel: {
414
+ label: memberLabel?.slice(0, 30),
415
+ labelTimestamp: unixTimestampSeconds(),
416
+ },
417
+ },
418
+ },
419
+ {
420
+ additionalNodes: [
421
+ {
422
+ tag: "meta",
423
+ attrs: {
424
+ tag_reason: "user_update",
425
+ appdata: "member_tag",
426
+ },
427
+ content: undefined,
428
+ },
429
+ ],
430
+ },
431
+ );
432
+ };
433
+ const assertSessions = async (jids, force) => {
434
+ let didFetchNewSession = false;
435
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
436
+ const jidsRequiringFetch = [];
437
+ logger.debug({ jids }, "assertSessions call with jids");
438
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
439
+ for (const jid of uniqueJids) {
440
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
441
+ const cachedSession = peerSessionsCache.get(signalId);
442
+ if (cachedSession !== undefined) {
443
+ if (cachedSession && !force) {
444
+ continue; // Session exists in cache
445
+ }
446
+ } else {
447
+ const sessionValidation = await signalRepository.validateSession(jid);
448
+ const hasSession = sessionValidation.exists;
449
+ peerSessionsCache.set(signalId, hasSession);
450
+ if (hasSession && !force) {
451
+ continue;
452
+ }
453
+ }
454
+ jidsRequiringFetch.push(jid);
455
+ }
456
+ if (jidsRequiringFetch.length) {
457
+ // LID if mapped, otherwise original
458
+ const wireJids = [
459
+ ...jidsRequiringFetch.filter(
460
+ (jid) => !!isLidUser(jid) || !!isHostedLidUser(jid),
461
+ ),
462
+ ...(
463
+ (await signalRepository.lidMapping.getLIDsForPNs(
464
+ jidsRequiringFetch.filter(
465
+ (jid) => !!isPnUser(jid) || !!isHostedPnUser(jid),
466
+ ),
467
+ )) || []
468
+ ).map((a) => a.lid),
469
+ ];
470
+ logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
471
+ const result = await query({
472
+ tag: "iq",
473
+ attrs: {
474
+ xmlns: "encrypt",
475
+ type: "get",
476
+ to: S_WHATSAPP_NET,
477
+ },
478
+ content: [
479
+ {
480
+ tag: "key",
481
+ attrs: {},
482
+ content: wireJids.map((jid) => {
483
+ const attrs = { jid };
484
+ if (force) attrs.reason = "identity";
485
+ return { tag: "user", attrs };
486
+ }),
487
+ },
488
+ ],
489
+ });
490
+ await parseAndInjectE2ESessions(result, signalRepository);
491
+ didFetchNewSession = true;
492
+ // Cache fetched sessions using wire JIDs
493
+ for (const wireJid of wireJids) {
494
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
495
+ peerSessionsCache.set(signalId, true);
496
+ }
497
+ }
498
+ return didFetchNewSession;
499
+ };
500
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
501
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
502
+ if (!authState.creds.me?.id) {
503
+ throw new Boom("Not authenticated");
504
+ }
505
+ const protocolMessage = {
506
+ protocolMessage: {
507
+ peerDataOperationRequestMessage: pdoMessage,
508
+ type: proto.Message.ProtocolMessage.Type
509
+ .PEER_DATA_OPERATION_REQUEST_MESSAGE,
510
+ },
511
+ };
512
+ const meJid = jidNormalizedUser(authState.creds.me.id);
513
+ const msgId = await relayMessage(meJid, protocolMessage, {
514
+ additionalAttributes: {
515
+ category: "peer",
516
+ push_priority: "high_force",
517
+ },
518
+ additionalNodes: [
519
+ {
520
+ tag: "meta",
521
+ attrs: { appdata: "default" },
522
+ },
523
+ ],
524
+ });
525
+ return msgId;
526
+ };
527
+ const createParticipantNodes = async (
528
+ recipientJids,
529
+ message,
530
+ extraAttrs,
531
+ dsmMessage,
532
+ ) => {
533
+ if (!recipientJids.length) {
534
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
535
+ }
536
+ const patched = await patchMessageBeforeSending(message, recipientJids);
537
+ const patchedMessages = Array.isArray(patched)
538
+ ? patched
539
+ : recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
540
+ let shouldIncludeDeviceIdentity = false;
541
+ const meId = authState.creds.me.id;
542
+ const meLid = authState.creds.me?.lid;
543
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
544
+ const encryptionPromises = patchedMessages.map(
545
+ async ({ recipientJid: jid, message: patchedMessage }) => {
546
+ try {
547
+ if (!jid) return null;
548
+ let msgToEncrypt = patchedMessage;
549
+ if (dsmMessage) {
550
+ const { user: targetUser } = jidDecode(jid);
551
+ const { user: ownPnUser } = jidDecode(meId);
552
+ const ownLidUser = meLidUser;
553
+ const isOwnUser =
554
+ targetUser === ownPnUser ||
555
+ (ownLidUser && targetUser === ownLidUser);
556
+ const isExactSenderDevice =
557
+ jid === meId || (meLid && jid === meLid);
558
+ if (isOwnUser && !isExactSenderDevice) {
559
+ msgToEncrypt = dsmMessage;
560
+ logger.debug({ jid, targetUser }, "Using DSM for own device");
561
+ }
562
+ }
563
+ const bytes = encodeWAMessage(msgToEncrypt);
564
+ const mutexKey = jid;
565
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
566
+ const { type, ciphertext } = await signalRepository.encryptMessage({
567
+ jid,
568
+ data: bytes,
569
+ });
570
+ if (type === "pkmsg") {
571
+ shouldIncludeDeviceIdentity = true;
572
+ }
573
+ return {
574
+ tag: "to",
575
+ attrs: { jid },
576
+ content: [
577
+ {
578
+ tag: "enc",
579
+ attrs: { v: "2", type, ...(extraAttrs || {}) },
580
+ content: ciphertext,
581
+ },
582
+ ],
583
+ };
584
+ });
585
+ return node;
586
+ } catch (err) {
587
+ logger.error({ jid, err }, "Failed to encrypt for recipient");
588
+ return null;
589
+ }
590
+ },
591
+ );
592
+ const nodes = (await Promise.all(encryptionPromises)).filter(
593
+ (node) => node !== null,
594
+ );
595
+ if (recipientJids.length > 0 && nodes.length === 0) {
596
+ throw new Boom("All encryptions failed", { statusCode: 500 });
597
+ }
598
+ return { nodes, shouldIncludeDeviceIdentity };
599
+ };
600
+ const relayMessage = async (
601
+ jid,
602
+ message,
603
+ {
604
+ messageId: msgId,
605
+ participant,
606
+ additionalAttributes,
607
+ additionalNodes,
608
+ useUserDevicesCache,
609
+ useCachedGroupMetadata,
610
+ statusJidList,
611
+ recipientOverrides,
612
+ specificRecipient,
613
+ specificRecipients,
614
+ },
615
+ ) => {
616
+ const meId = authState.creds.me.id;
617
+ const meLid = authState.creds.me?.lid;
618
+ const isRetryResend = Boolean(participant?.jid);
619
+ let shouldIncludeDeviceIdentity = isRetryResend;
620
+ const statusJid = "status@broadcast";
621
+ const { user, server } = jidDecode(jid);
622
+ const isGroup = server === "g.us";
623
+ const isStatus = jid === statusJid;
624
+ const isLid = server === "lid";
625
+ const isNewsletter = server === "newsletter";
626
+ const isGroupOrStatus = isGroup || isStatus;
627
+ const finalJid = jid;
628
+ msgId = msgId || generateMessageIDV2(meId);
629
+ useUserDevicesCache = useUserDevicesCache !== false;
630
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
631
+ const participants = [];
632
+ const destinationJid = !isStatus ? finalJid : statusJid;
633
+ const binaryNodeContent = [];
634
+ const devices = [];
635
+ let reportingMessage;
636
+ const meMsg = {
637
+ deviceSentMessage: {
638
+ destinationJid,
639
+ message,
640
+ },
641
+ messageContextInfo: message.messageContextInfo,
642
+ };
643
+ const extraAttrs = {};
644
+ if (participant) {
645
+ if (!isGroup && !isStatus) {
646
+ additionalAttributes = {
647
+ ...additionalAttributes,
648
+ device_fanout: "false",
649
+ };
650
+ }
651
+ const { user, device } = jidDecode(participant.jid);
652
+ devices.push({
653
+ user,
654
+ device,
655
+ jid: participant.jid,
656
+ });
657
+ }
658
+ await authState.keys.transaction(async () => {
659
+ const mediaType = getMediaType(
660
+ normalizeMessageContent(message) || message,
661
+ );
662
+ if (mediaType) {
663
+ extraAttrs["mediatype"] = mediaType;
664
+ }
665
+ if (isNewsletter) {
666
+ const patched = patchMessageBeforeSending
667
+ ? await patchMessageBeforeSending(message, [])
668
+ : message;
669
+ const bytes = encodeNewsletterMessage(patched);
670
+ binaryNodeContent.push({
671
+ tag: "plaintext",
672
+ attrs: extraAttrs || {},
673
+ content: bytes,
674
+ });
675
+ const stanza = {
676
+ tag: "message",
677
+ attrs: {
678
+ to: jid,
679
+ id: msgId,
680
+ type: getMessageType(message),
681
+ ...(additionalAttributes || {}),
682
+ },
683
+ content: binaryNodeContent,
684
+ };
685
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
686
+ await sendNode(stanza);
687
+ return;
688
+ }
689
+ if (
690
+ normalizeMessageContent(message)?.pinInChatMessage ||
691
+ normalizeMessageContent(message)?.reactionMessage
692
+ ) {
693
+ extraAttrs["decrypt-fail"] = "hide"; // todo: expand for reactions and other types
694
+ }
695
+ if (isGroupOrStatus && !isRetryResend) {
696
+ const [groupData, senderKeyMap] = await Promise.all([
697
+ (async () => {
698
+ let groupData =
699
+ useCachedGroupMetadata && cachedGroupMetadata
700
+ ? await cachedGroupMetadata(jid)
701
+ : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
702
+ if (groupData && Array.isArray(groupData?.participants)) {
703
+ logger.trace(
704
+ { jid, participants: groupData.participants.length },
705
+ "using cached group metadata",
706
+ );
707
+ } else if (!isStatus) {
708
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
709
+ }
710
+ return groupData;
711
+ })(),
712
+ (async () => {
713
+ if (!participant && !isStatus) {
714
+ // what if sender memory is less accurate than the cached metadata
715
+ // on participant change in group, we should do sender memory manipulation
716
+ const result = await authState.keys.get("sender-key-memory", [
717
+ jid,
718
+ ]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
719
+ return result[jid] || {};
720
+ }
721
+ return {};
722
+ })(),
723
+ ]);
724
+ let participantsList = groupData
725
+ ? groupData.participants.map((p) => p.id)
726
+ : [];
727
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
728
+ additionalAttributes = {
729
+ ...additionalAttributes,
730
+ expiration: groupData.ephemeralDuration.toString(),
731
+ };
732
+ }
733
+ if (isStatus) {
734
+ const rawStatusOverrides = normalizeRecipientList(
735
+ statusJidList || recipientOverrides || specificRecipients || (specificRecipient ? [specificRecipient] : undefined),
736
+ );
737
+ if (rawStatusOverrides.length > 0) {
738
+ participantsList = [...rawStatusOverrides];
739
+ }
740
+ }
741
+ if (isGroup) {
742
+ additionalAttributes = {
743
+ ...additionalAttributes,
744
+ addressing_mode: groupData?.addressingMode || "lid",
745
+ };
746
+ }
747
+ const additionalDevices = await getUSyncDevices(
748
+ participantsList,
749
+ !!useUserDevicesCache,
750
+ false,
751
+ );
752
+ devices.push(...additionalDevices);
753
+ const patched = await patchMessageBeforeSending(message);
754
+ if (Array.isArray(patched)) {
755
+ throw new Boom("Per-jid patching is not supported in groups");
756
+ }
757
+ const bytes = encodeWAMessage(patched);
758
+ reportingMessage = patched;
759
+ const groupAddressingMode =
760
+ additionalAttributes?.["addressing_mode"] ||
761
+ groupData?.addressingMode ||
762
+ "lid";
763
+ const groupSenderIdentity =
764
+ groupAddressingMode === "lid" && meLid ? meLid : meId;
765
+ const { ciphertext, senderKeyDistributionMessage } =
766
+ await signalRepository.encryptGroupMessage({
767
+ group: destinationJid,
768
+ data: bytes,
769
+ meId: groupSenderIdentity,
770
+ });
771
+ const forceDistribute = isStatus;
772
+ const senderKeyRecipients = [];
773
+ for (const device of devices) {
774
+ const deviceJid = device.jid;
775
+ const hasKey = !forceDistribute && !!senderKeyMap[deviceJid];
776
+ if (
777
+ (!hasKey || !!participant || forceDistribute) &&
778
+ !isHostedLidUser(deviceJid) &&
779
+ !isHostedPnUser(deviceJid) &&
780
+ device.device !== 99
781
+ ) {
782
+ senderKeyRecipients.push(deviceJid);
783
+ if (!forceDistribute) {
784
+ senderKeyMap[deviceJid] = true;
785
+ }
786
+ }
787
+ }
788
+ if (senderKeyRecipients.length) {
789
+ logger.debug(
790
+ { senderKeyJids: senderKeyRecipients },
791
+ "sending new sender key",
792
+ );
793
+ const senderKeyMsg = {
794
+ senderKeyDistributionMessage: {
795
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
796
+ groupId: destinationJid,
797
+ },
798
+ };
799
+ const senderKeySessionTargets = senderKeyRecipients;
800
+ await assertSessions(senderKeySessionTargets);
801
+ const result = await createParticipantNodes(
802
+ senderKeyRecipients,
803
+ senderKeyMsg,
804
+ extraAttrs,
805
+ );
806
+ shouldIncludeDeviceIdentity =
807
+ shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
808
+ participants.push(...result.nodes);
809
+ }
810
+ binaryNodeContent.push({
811
+ tag: "enc",
812
+ attrs: { v: "2", type: "skmsg", ...extraAttrs },
813
+ content: ciphertext,
814
+ });
815
+ if (!isStatus) {
816
+ await authState.keys.set({
817
+ "sender-key-memory": { [jid]: senderKeyMap },
818
+ });
819
+ }
820
+ } else {
821
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
822
+ // TODO: investigate if this is true
823
+ let ownId = meId;
824
+ if (isLid && meLid) {
825
+ ownId = meLid;
826
+ logger.debug(
827
+ { to: jid, ownId },
828
+ "Using LID identity for @lid conversation",
829
+ );
830
+ } else {
831
+ logger.debug(
832
+ { to: jid, ownId },
833
+ "Using PN identity for @s.whatsapp.net conversation",
834
+ );
835
+ }
836
+ const { user: ownUser } = jidDecode(ownId);
837
+ if (!participant) {
838
+ const patchedForReporting = await patchMessageBeforeSending(message, [
839
+ jid,
840
+ ]);
841
+ reportingMessage = Array.isArray(patchedForReporting)
842
+ ? patchedForReporting.find((item) => item.recipientJid === jid) ||
843
+ patchedForReporting[0]
844
+ : patchedForReporting;
845
+ }
846
+ if (!isRetryResend) {
847
+ const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
848
+ devices.push({
849
+ user,
850
+ device: 0,
851
+ jid: jidEncode(user, targetUserServer, 0), // rajeh, todo: this entire logic is convoluted and weird.
852
+ });
853
+ if (user !== ownUser) {
854
+ const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
855
+ const ownUserForAddressing =
856
+ isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
857
+ devices.push({
858
+ user: ownUserForAddressing,
859
+ device: 0,
860
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0),
861
+ });
862
+ }
863
+ if (additionalAttributes?.["category"] !== "peer") {
864
+ devices.length = 0;
865
+ const senderIdentity =
866
+ isLid && meLid
867
+ ? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
868
+ : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
869
+ const rawOverrides = normalizeRecipientList(
870
+ recipientOverrides ||
871
+ specificRecipients ||
872
+ (specificRecipient ? [specificRecipient] : undefined),
873
+ );
874
+ const targetsToFetch =
875
+ rawOverrides.length > 0
876
+ ? [senderIdentity, ...rawOverrides]
877
+ : [senderIdentity, jid];
878
+ const sessionDevices = await getUSyncDevices(
879
+ [...new Set(targetsToFetch)],
880
+ true,
881
+ false,
882
+ );
883
+ devices.push(...sessionDevices);
884
+ logger.debug(
885
+ {
886
+ deviceCount: devices.length,
887
+ devices: devices.map(
888
+ (d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`,
889
+ ),
890
+ },
891
+ "Device enumeration complete with unified addressing",
892
+ );
893
+ }
894
+ }
895
+ const allRecipients = [];
896
+ const meRecipients = [];
897
+ const otherRecipients = [];
898
+ const { user: mePnUser } = jidDecode(meId);
899
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
900
+ for (const { user, jid } of devices) {
901
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
902
+ if (isExactSenderDevice) {
903
+ logger.debug(
904
+ { jid, meId, meLid },
905
+ "Skipping exact sender device (whatsmeow pattern)",
906
+ );
907
+ continue;
908
+ }
909
+ // Check if this is our device (could match either PN or LID user)
910
+ const isMe = user === mePnUser || user === meLidUser;
911
+ if (isMe) {
912
+ meRecipients.push(jid);
913
+ } else {
914
+ otherRecipients.push(jid);
915
+ }
916
+ allRecipients.push(jid);
917
+ }
918
+ await assertSessions(allRecipients);
919
+ const [
920
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
921
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },
922
+ ] = await Promise.all([
923
+ // For own devices: use DSM if available (1:1 chats only)
924
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
925
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg),
926
+ ]);
927
+ participants.push(...meNodes);
928
+ participants.push(...otherNodes);
929
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
930
+ extraAttrs["phash"] = generateParticipantHashV2([
931
+ ...meRecipients,
932
+ ...otherRecipients,
933
+ ]);
934
+ }
935
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
936
+ }
937
+ if (isRetryResend) {
938
+ const isParticipantLid = isLidUser(participant.jid);
939
+ const isMe = areJidsSameUser(
940
+ participant.jid,
941
+ isParticipantLid ? meLid : meId,
942
+ );
943
+ const encodedMessageToSend = isMe
944
+ ? encodeWAMessage({
945
+ deviceSentMessage: {
946
+ destinationJid,
947
+ message,
948
+ },
949
+ })
950
+ : encodeWAMessage(message);
951
+ const { type, ciphertext: encryptedContent } =
952
+ await signalRepository.encryptMessage({
953
+ data: encodedMessageToSend,
954
+ jid: participant.jid,
955
+ });
956
+ binaryNodeContent.push({
957
+ tag: "enc",
958
+ attrs: {
959
+ v: "2",
960
+ type,
961
+ count: participant.count.toString(),
962
+ },
963
+ content: encryptedContent,
964
+ });
965
+ }
966
+ if (participants.length) {
967
+ if (additionalAttributes?.["category"] === "peer") {
968
+ const peerNode = participants[0]?.content?.[0];
969
+ if (peerNode) {
970
+ binaryNodeContent.push(peerNode); // push only enc
971
+ }
972
+ } else {
973
+ binaryNodeContent.push({
974
+ tag: "participants",
975
+ attrs: {},
976
+ content: participants,
977
+ });
978
+ }
979
+ }
980
+ const stanza = {
981
+ tag: "message",
982
+ attrs: {
983
+ id: msgId,
984
+ to: destinationJid,
985
+ type: getMessageType(message),
986
+ ...(additionalAttributes || {}),
987
+ },
988
+ content: binaryNodeContent,
989
+ };
990
+ // if the participant to send to is explicitly specified (generally retry recp)
991
+ // ensure the message is only sent to that person
992
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
993
+ if (participant) {
994
+ if (isJidGroup(destinationJid)) {
995
+ stanza.attrs.to = destinationJid;
996
+ stanza.attrs.participant = participant.jid;
997
+ } else if (areJidsSameUser(participant.jid, meId)) {
998
+ stanza.attrs.to = participant.jid;
999
+ stanza.attrs.recipient = destinationJid;
1000
+ } else {
1001
+ stanza.attrs.to = participant.jid;
1002
+ }
1003
+ } else {
1004
+ stanza.attrs.to = destinationJid;
1005
+ }
1006
+ if (shouldIncludeDeviceIdentity) {
1007
+ stanza.content.push({
1008
+ tag: "device-identity",
1009
+ attrs: {},
1010
+ content: encodeSignedDeviceIdentity(authState.creds.account, true),
1011
+ });
1012
+ logger.debug({ jid }, "adding device identity");
1013
+ }
1014
+ if (
1015
+ !isNewsletter &&
1016
+ !isRetryResend &&
1017
+ reportingMessage?.messageContextInfo?.messageSecret &&
1018
+ shouldIncludeReportingToken(reportingMessage)
1019
+ ) {
1020
+ try {
1021
+ const encoded = encodeWAMessage(reportingMessage);
1022
+ const reportingKey = {
1023
+ id: msgId,
1024
+ fromMe: true,
1025
+ remoteJid: destinationJid,
1026
+ participant: participant?.jid,
1027
+ };
1028
+ const reportingNode = await getMessageReportingToken(
1029
+ encoded,
1030
+ reportingMessage,
1031
+ reportingKey,
1032
+ );
1033
+ if (reportingNode) {
1034
+ stanza.content.push(reportingNode);
1035
+ logger.trace({ jid }, "added reporting token to message");
1036
+ }
1037
+ } catch (error) {
1038
+ logger.warn(
1039
+ { jid, trace: error?.stack },
1040
+ "failed to attach reporting token",
1041
+ );
1042
+ }
1043
+ }
1044
+ const contactTcTokenData =
1045
+ !isGroup && !isRetryResend && !isStatus
1046
+ ? await authState.keys.get("tctoken", [destinationJid])
1047
+ : {};
1048
+ const tcTokenEntry = contactTcTokenData[destinationJid];
1049
+ const tcTokenBuffer = tcTokenEntry?.token;
1050
+ // BibzWhats (upstream rc11+): token tanpa timestamp / kedaluwarsa (~28 hari) tidak dikirim
1051
+ if (tcTokenBuffer?.length && tcTokenEntry?.timestamp !== undefined && !isTcTokenExpired(tcTokenEntry.timestamp)) {
1052
+ stanza.content.push({
1053
+ tag: "tctoken",
1054
+ attrs: {},
1055
+ content: tcTokenBuffer,
1056
+ });
1057
+ }
1058
+ if (additionalNodes && additionalNodes.length > 0) {
1059
+ stanza.content.push(...additionalNodes);
1060
+ }
1061
+ const buttonType = getButtonType(message);
1062
+ if (buttonType && !isNewsletter && !isStatus) {
1063
+ const hasBizNode = stanza.content.some((node) => typeof node === "object" && node && node.tag === "biz");
1064
+ if (!hasBizNode) {
1065
+ const bizNodes = getAdditionalNode(buttonType);
1066
+ stanza.content.push(...bizNodes);
1067
+ }
1068
+ }
1069
+ logger.debug(
1070
+ { msgId },
1071
+ `sending message to ${participants.length} devices`,
1072
+ );
1073
+ await sendNode(stanza);
1074
+ // Add message to retry cache if enabled
1075
+ if (messageRetryManager && !participant) {
1076
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1077
+ }
1078
+ }, meId);
1079
+ return msgId;
1080
+ };
1081
+ const getMessageType = (message) => {
1082
+ const normalizedMessage = normalizeMessageContent(message);
1083
+ if (!normalizedMessage) return "text";
1084
+ if (
1085
+ normalizedMessage.reactionMessage ||
1086
+ normalizedMessage.encReactionMessage
1087
+ ) {
1088
+ return "reaction";
1089
+ }
1090
+ if (
1091
+ normalizedMessage.pollCreationMessage ||
1092
+ normalizedMessage.pollCreationMessageV2 ||
1093
+ normalizedMessage.pollCreationMessageV3 ||
1094
+ normalizedMessage.pollUpdateMessage
1095
+ ) {
1096
+ return "poll";
1097
+ }
1098
+ if (normalizedMessage.eventMessage) {
1099
+ return "event";
1100
+ }
1101
+ if (getMediaType(normalizedMessage) !== "") {
1102
+ return "media";
1103
+ }
1104
+ return "text";
1105
+ };
1106
+ const getMediaType = (message) => {
1107
+ if (message.imageMessage) {
1108
+ return "image";
1109
+ } else if (message.videoMessage) {
1110
+ return message.videoMessage.gifPlayback ? "gif" : "video";
1111
+ } else if (message.audioMessage) {
1112
+ return message.audioMessage.ptt ? "ptt" : "audio";
1113
+ } else if (message.contactMessage) {
1114
+ return "vcard";
1115
+ } else if (message.documentMessage) {
1116
+ return "document";
1117
+ } else if (message.contactsArrayMessage) {
1118
+ return "contact_array";
1119
+ } else if (message.liveLocationMessage) {
1120
+ return "livelocation";
1121
+ } else if (message.stickerMessage) {
1122
+ return message.stickerMessage.isLottie
1123
+ ? "1p_sticker"
1124
+ : message.stickerMessage.isAvatar
1125
+ ? "avatar_sticker"
1126
+ : "sticker";
1127
+ } else if (message.listMessage) {
1128
+ return "list";
1129
+ } else if (message.listResponseMessage) {
1130
+ return "list_response";
1131
+ } else if (message.buttonsResponseMessage) {
1132
+ return "buttons_response";
1133
+ } else if (message.orderMessage) {
1134
+ return "order";
1135
+ } else if (message.productMessage) {
1136
+ return "product";
1137
+ } else if (message.interactiveResponseMessage) {
1138
+ return "native_flow_response";
1139
+ } else if (message.groupInviteMessage) {
1140
+ return "url";
1141
+ }
1142
+ return "";
1143
+ };
1144
+ const getPrivacyTokens = async (jids) => {
1145
+ const t = unixTimestampSeconds().toString();
1146
+ const result = await query({
1147
+ tag: "iq",
1148
+ attrs: {
1149
+ to: S_WHATSAPP_NET,
1150
+ type: "set",
1151
+ xmlns: "privacy",
1152
+ },
1153
+ content: [
1154
+ {
1155
+ tag: "tokens",
1156
+ attrs: {},
1157
+ content: jids.map((jid) => ({
1158
+ tag: "token",
1159
+ attrs: {
1160
+ jid: jidNormalizedUser(jid),
1161
+ t,
1162
+ type: "trusted_contact",
1163
+ },
1164
+ })),
1165
+ },
1166
+ ],
1167
+ });
1168
+ return result;
1169
+ };
1170
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1171
+ const bibz = new BibzWhatsEngine(waUploadToServer, relayMessage, config, sock);
1172
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
1173
+ return {
1174
+ ...sock,
1175
+ getPrivacyTokens,
1176
+ assertSessions,
1177
+ relayMessage,
1178
+ sendReceipt,
1179
+ sendReceipts,
1180
+ bibz,
1181
+ /** alias kompatibilitas ourin-baileys */
1182
+ ourin: bibz,
1183
+ readMessages,
1184
+ refreshMediaConn,
1185
+ waUploadToServer,
1186
+ fetchPrivacySettings,
1187
+ sendPeerDataOperationMessage,
1188
+ createParticipantNodes,
1189
+ getUSyncDevices,
1190
+ messageRetryManager,
1191
+ updateMemberLabel,
1192
+ updateMediaMessage: async (message) => {
1193
+ const content = assertMediaContent(message.message);
1194
+ const mediaKey = content.mediaKey;
1195
+ const meId = authState.creds.me.id;
1196
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1197
+ let error = undefined;
1198
+ await Promise.all([
1199
+ sendNode(node),
1200
+ waitForMsgMediaUpdate(async (update) => {
1201
+ const result = update.find((c) => c.key.id === message.key.id);
1202
+ if (result) {
1203
+ if (result.error) {
1204
+ error = result.error;
1205
+ } else {
1206
+ try {
1207
+ const media = decryptMediaRetryData(
1208
+ result.media,
1209
+ mediaKey,
1210
+ result.key.id,
1211
+ );
1212
+ if (
1213
+ media.result !==
1214
+ proto.MediaRetryNotification.ResultType.SUCCESS
1215
+ ) {
1216
+ const resultStr =
1217
+ proto.MediaRetryNotification.ResultType[media.result];
1218
+ throw new Boom(
1219
+ `Media re-upload failed by device (${resultStr})`,
1220
+ {
1221
+ data: media,
1222
+ statusCode:
1223
+ getStatusCodeForMediaRetry(media.result) || 404,
1224
+ },
1225
+ );
1226
+ }
1227
+ content.directPath = media.directPath;
1228
+ content.url = getUrlFromDirectPath(content.directPath);
1229
+ logger.debug(
1230
+ { directPath: media.directPath, key: result.key },
1231
+ "media update successful",
1232
+ );
1233
+ } catch (err) {
1234
+ error = err;
1235
+ }
1236
+ }
1237
+ return true;
1238
+ }
1239
+ }),
1240
+ ]);
1241
+ if (error) {
1242
+ throw error;
1243
+ }
1244
+ ev.emit("messages.update", [
1245
+ { key: message.key, update: { message: message.message } },
1246
+ ]);
1247
+ return message;
1248
+ },
1249
+ sendStatusMention: async (content, jids = []) => {
1250
+ return await bibz.sendStatusWhatsApp(content, jids);
1251
+ },
1252
+ swgc: async (jid, content, options = {}) => {
1253
+ if (!isJidGroup(jid)) {
1254
+ throw new Boom("JID must be a group", { statusCode: 400 });
1255
+ }
1256
+ const storyContent = { groupStatusMessage: content };
1257
+ return await bibz.handleGroupStory(storyContent, jid, null);
1258
+ },
1259
+ sendPreview: async (jid, preview, options = {}) => {
1260
+ const extContent = {
1261
+ text: preview.caption || preview.text || "",
1262
+ matchedText: preview.matchedText || preview.url || "",
1263
+ previewType: preview.previewType ?? 0,
1264
+ };
1265
+ if (preview.title) extContent.title = preview.title;
1266
+ if (preview.description) extContent.description = preview.description;
1267
+ if (preview.inviteLinkGroupTypeV2)
1268
+ extContent.inviteLinkGroupTypeV2 = preview.inviteLinkGroupTypeV2;
1269
+ if (preview.image) {
1270
+ let imgBuf = preview.image;
1271
+ if (typeof imgBuf === "string" && imgBuf.startsWith("http")) {
1272
+ try {
1273
+ const resp = await fetch(imgBuf);
1274
+ imgBuf = Buffer.from(await resp.arrayBuffer());
1275
+ } catch {}
1276
+ }
1277
+ if (Buffer.isBuffer(imgBuf)) {
1278
+ try {
1279
+ const { imageMessage } = await prepareWAMessageMedia(
1280
+ { image: imgBuf },
1281
+ { upload: waUploadToServer, mediaTypeOverride: "thumbnail-link" },
1282
+ );
1283
+ if (imageMessage) {
1284
+ extContent.jpegThumbnail = imageMessage.jpegThumbnail;
1285
+ if (imageMessage.directPath)
1286
+ extContent.thumbnailDirectPath = imageMessage.directPath;
1287
+ if (imageMessage.mediaKey)
1288
+ extContent.mediaKey = imageMessage.mediaKey;
1289
+ if (imageMessage.mediaKeyTimestamp)
1290
+ extContent.mediaKeyTimestamp = imageMessage.mediaKeyTimestamp;
1291
+ if (imageMessage.fileSha256)
1292
+ extContent.thumbnailSha256 = imageMessage.fileSha256;
1293
+ if (imageMessage.fileEncSha256)
1294
+ extContent.thumbnailEncSha256 = imageMessage.fileEncSha256;
1295
+ if (imageMessage.width)
1296
+ extContent.thumbnailWidth = imageMessage.width;
1297
+ if (imageMessage.height)
1298
+ extContent.thumbnailHeight = imageMessage.height;
1299
+ }
1300
+ } catch {
1301
+ extContent.jpegThumbnail = imgBuf;
1302
+ }
1303
+ } else {
1304
+ extContent.jpegThumbnail = imgBuf;
1305
+ }
1306
+ } else if (preview.jpegThumbnail) {
1307
+ extContent.jpegThumbnail = preview.jpegThumbnail;
1308
+ }
1309
+ if (preview.thumbnailHeight)
1310
+ extContent.thumbnailHeight = preview.thumbnailHeight;
1311
+ if (preview.thumbnailWidth)
1312
+ extContent.thumbnailWidth = preview.thumbnailWidth;
1313
+ if (options.quoted) {
1314
+ const participant = options.quoted.key.fromMe
1315
+ ? authState.creds.me.id
1316
+ : options.quoted.participant ||
1317
+ options.quoted.key.participant ||
1318
+ options.quoted.key.remoteJid;
1319
+ extContent.contextInfo = {
1320
+ stanzaId: options.quoted.key.id,
1321
+ participant,
1322
+ quotedMessage: options.quoted.message,
1323
+ };
1324
+ }
1325
+ if (options.contextInfo) {
1326
+ extContent.contextInfo = {
1327
+ ...extContent.contextInfo,
1328
+ ...options.contextInfo,
1329
+ };
1330
+ }
1331
+ const messageId = generateMessageIDV2(sock.user?.id);
1332
+ await relayMessage(
1333
+ jid,
1334
+ { extendedTextMessage: extContent },
1335
+ { messageId },
1336
+ );
1337
+ return messageId;
1338
+ },
1339
+ // BibzWhats: tabel teks siap kirim
1340
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1341
+ const { message, messageId } = generateTableContent(
1342
+ title,
1343
+ headers,
1344
+ rows,
1345
+ quoted,
1346
+ options,
1347
+ );
1348
+ await relayMessage(jid, message, { messageId });
1349
+ return { message, messageId };
1350
+ },
1351
+ sendTableV2: async (jid, table, quoted, options = {}) => {
1352
+ const { message, messageId } = generateTableContentV2(
1353
+ table,
1354
+ quoted,
1355
+ options,
1356
+ );
1357
+ await relayMessage(jid, message, { messageId });
1358
+ return { message, messageId };
1359
+ },
1360
+ sendList: async (jid, title, items, quoted, options = {}) => {
1361
+ const { message, messageId } = generateListContent(
1362
+ title,
1363
+ items,
1364
+ quoted,
1365
+ options,
1366
+ );
1367
+ await relayMessage(jid, message, { messageId });
1368
+ return { message, messageId };
1369
+ },
1370
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1371
+ const { message, messageId } = generateCodeBlockContent(
1372
+ code,
1373
+ quoted,
1374
+ options,
1375
+ );
1376
+ await relayMessage(jid, message, { messageId });
1377
+ return { message, messageId };
1378
+ },
1379
+ sendCodeBlockV2: async (jid, code, quoted, options = {}) => {
1380
+ const { message, messageId } = generateCodeBlockContentV2(
1381
+ code,
1382
+ quoted,
1383
+ options,
1384
+ );
1385
+ await relayMessage(jid, message, { messageId });
1386
+ return { message, messageId };
1387
+ },
1388
+ sendLink: async (jid, text, links, quoted, options = {}) => {
1389
+ const { message, messageId } = generateLinkContent(
1390
+ text,
1391
+ links,
1392
+ quoted,
1393
+ options,
1394
+ );
1395
+ await relayMessage(jid, message, { messageId });
1396
+ return { message, messageId };
1397
+ },
1398
+ sendLinkV2: async (jid, text, links, quoted, options = {}) => {
1399
+ const { message, messageId } = generateLinkContentV2(
1400
+ text,
1401
+ links,
1402
+ quoted,
1403
+ options,
1404
+ );
1405
+ await relayMessage(jid, message, { messageId });
1406
+ return { message, messageId };
1407
+ },
1408
+ sendLatex: async (jid, quoted, options) => {
1409
+ const { message, messageId } = generateLatexContent(quoted, options);
1410
+ await relayMessage(jid, message, { messageId });
1411
+ return { message, messageId };
1412
+ },
1413
+ sendLatexImage: async (
1414
+ jid,
1415
+ quoted,
1416
+ options,
1417
+ renderLatexToPng,
1418
+ uploadFn,
1419
+ ) => {
1420
+ const { message, messageId } = await generateLatexImageContent(
1421
+ quoted,
1422
+ options,
1423
+ uploadFn,
1424
+ renderLatexToPng,
1425
+ );
1426
+ await relayMessage(jid, message, { messageId });
1427
+ return { message, messageId };
1428
+ },
1429
+ sendLatexInlineImage: async (
1430
+ jid,
1431
+ quoted,
1432
+ options,
1433
+ renderLatexToPng,
1434
+ uploadFn,
1435
+ ) => {
1436
+ const { message, messageId } = await generateLatexInlineImageContent(
1437
+ quoted,
1438
+ options,
1439
+ uploadFn,
1440
+ renderLatexToPng,
1441
+ );
1442
+ await relayMessage(jid, message, { messageId });
1443
+ return { message, messageId };
1444
+ },
1445
+ captureUnifiedResponse,
1446
+ sendUnifiedResponse: async (jid, quoted, captured) => {
1447
+ const { message, messageId } = generateUnifiedResponseContent(
1448
+ quoted,
1449
+ captured,
1450
+ );
1451
+ await relayMessage(jid, message, { messageId });
1452
+ return { message, messageId };
1453
+ },
1454
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1455
+ const { message, messageId } = generateRichMessageContent(
1456
+ submessages,
1457
+ quoted,
1458
+ );
1459
+ await relayMessage(jid, message, { messageId });
1460
+ return { message, messageId };
1461
+ },
1462
+ sendMessage: async (jid, content, options = {}) => {
1463
+ const userJid = authState.creds.me.id;
1464
+ const { quoted } = options;
1465
+ const messageType = bibz.detectType(content);
1466
+ if (
1467
+ typeof content === "object" &&
1468
+ "disappearingMessagesInChat" in content &&
1469
+ typeof content["disappearingMessagesInChat"] !== "undefined" &&
1470
+ isJidGroup(jid)
1471
+ ) {
1472
+ const { disappearingMessagesInChat } = content;
1473
+ const value =
1474
+ typeof disappearingMessagesInChat === "boolean"
1475
+ ? disappearingMessagesInChat
1476
+ ? WA_DEFAULT_EPHEMERAL
1477
+ : 0
1478
+ : disappearingMessagesInChat;
1479
+ await groupToggleEphemeral(jid, value);
1480
+ } else if (messageType) {
1481
+ switch (messageType) {
1482
+ case "PAYMENT": {
1483
+ const paymentContent = await bibz.handlePayment(content, quoted);
1484
+ return await relayMessage(jid, paymentContent, {
1485
+ messageId: generateMessageIDV2(userJid),
1486
+ });
1487
+ }
1488
+ case "PRODUCT": {
1489
+ const productContent = await bibz.handleProduct(
1490
+ content,
1491
+ jid,
1492
+ quoted,
1493
+ );
1494
+ const productMsg = await generateWAMessageFromContent(
1495
+ jid,
1496
+ productContent,
1497
+ { quoted, userJid },
1498
+ );
1499
+ return await relayMessage(jid, productMsg.message, {
1500
+ messageId: productMsg.key.id,
1501
+ });
1502
+ }
1503
+ case "CAROUSEL": {
1504
+ const carouselContent = await bibz.handleCarousel(
1505
+ content,
1506
+ jid,
1507
+ quoted,
1508
+ );
1509
+ const carouselMsg = await generateWAMessageFromContent(
1510
+ jid,
1511
+ carouselContent,
1512
+ { quoted, userJid },
1513
+ );
1514
+ return await relayMessage(jid, carouselMsg.message, {
1515
+ messageId: carouselMsg.key.id,
1516
+ });
1517
+ }
1518
+ case "INTERACTIVE": {
1519
+ const interactiveContent = await bibz.handleInteractive(
1520
+ content,
1521
+ jid,
1522
+ quoted,
1523
+ );
1524
+ const interactiveMsg = await generateWAMessageFromContent(
1525
+ jid,
1526
+ interactiveContent,
1527
+ { quoted, userJid },
1528
+ );
1529
+ return await relayMessage(jid, interactiveMsg.message, {
1530
+ messageId: interactiveMsg.key.id,
1531
+ });
1532
+ }
1533
+ case "INTERACTIVE_BUTTONS": {
1534
+ const ibContent = await bibz.handleInteractiveButtons(
1535
+ content,
1536
+ jid,
1537
+ quoted,
1538
+ );
1539
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, {
1540
+ quoted,
1541
+ userJid,
1542
+ });
1543
+ return await relayMessage(jid, ibMsg.message, {
1544
+ messageId: ibMsg.key.id,
1545
+ });
1546
+ }
1547
+ case "ALBUM":
1548
+ return await bibz.handleAlbum(content, jid, quoted);
1549
+ case "EVENT":
1550
+ return await bibz.handleEvent(content, jid, quoted);
1551
+ case "POLL_RESULT":
1552
+ return await bibz.handlePollResult(content, jid, quoted);
1553
+ case "GROUP_STORY":
1554
+ return await bibz.handleGroupStory(content, jid, quoted, options);
1555
+ }
1556
+ } else {
1557
+ let mediaHandle;
1558
+ const fullMsg = await generateWAMessage(jid, content, {
1559
+ logger,
1560
+ userJid,
1561
+ getUrlInfo: (text) =>
1562
+ getUrlInfo(text, {
1563
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1564
+ fetchOpts: {
1565
+ timeout: 3000,
1566
+ ...(httpRequestOptions || {}),
1567
+ },
1568
+ logger,
1569
+ uploadImage: generateHighQualityLinkPreview
1570
+ ? waUploadToServer
1571
+ : undefined,
1572
+ }),
1573
+ getProfilePicUrl: sock.profilePictureUrl,
1574
+ getCallLink: sock.createCallLink,
1575
+ upload: async (readStream, opts) => {
1576
+ const up = await waUploadToServer(readStream, {
1577
+ ...opts,
1578
+ newsletter: isJidNewsletter(jid),
1579
+ });
1580
+ return up;
1581
+ },
1582
+ mediaCache: config.mediaCache,
1583
+ options: config.options,
1584
+ messageId: generateMessageIDV2(sock.user?.id),
1585
+ ...options,
1586
+ });
1587
+ const isEventMsg = "event" in content && !!content.event;
1588
+ const isDeleteMsg = "delete" in content && !!content.delete;
1589
+ const isEditMsg = "edit" in content && !!content.edit;
1590
+ const isPinMsg = "pin" in content && !!content.pin;
1591
+ const isPollMessage = "poll" in content && !!content.poll;
1592
+ const isAiMsg = "ai" in content && !!content.ai;
1593
+ const additionalAttributes = {};
1594
+ const additionalNodes = [];
1595
+ if (isDeleteMsg) {
1596
+ const fromMe = content.delete?.fromMe;
1597
+ const isGroup = isJidGroup(content.delete?.remoteJid);
1598
+ additionalAttributes.edit =
1599
+ (isGroup && !fromMe) || isJidNewsletter(jid) ? "8" : "7";
1600
+ } else if (isEditMsg) {
1601
+ additionalAttributes.edit = isJidNewsletter(jid) ? "3" : "1";
1602
+ } else if (isPinMsg) {
1603
+ additionalAttributes.edit = "2";
1604
+ } else if (isPollMessage) {
1605
+ additionalNodes.push({
1606
+ tag: "meta",
1607
+ attrs: { polltype: "creation" },
1608
+ });
1609
+ } else if (isEventMsg) {
1610
+ additionalNodes.push({
1611
+ tag: "meta",
1612
+ attrs: { event_type: "creation" },
1613
+ });
1614
+ } else if (isAiMsg) {
1615
+ additionalNodes.push({
1616
+ tag: "bot",
1617
+ attrs: { biz_bot: "1" },
1618
+ });
1619
+ }
1620
+ await relayMessage(jid, fullMsg.message, {
1621
+ messageId: fullMsg.key.id,
1622
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1623
+ additionalAttributes,
1624
+ statusJidList: options.statusJidList,
1625
+ recipientOverrides: options.recipientOverrides,
1626
+ specificRecipient: options.specificRecipient,
1627
+ specificRecipients: options.specificRecipients,
1628
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
1629
+ });
1630
+ if (config.emitOwnEvents) {
1631
+ process.nextTick(async () => {
1632
+ await messageMutex.mutex(() => upsertMessage(fullMsg, "append"));
1633
+ });
1634
+ }
1635
+ return fullMsg;
1636
+ }
1637
+ },
1638
+ };
1639
+ };