@poucode/baileys 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +21 -2
  2. package/lib/Socket/chats.js +5 -0
  3. package/lib/Socket/graphql.js +716 -0
  4. package/lib/Socket/index.js +10 -2
  5. package/lib/Socket/interop.js +463 -0
  6. package/lib/Socket/luxu.js +1 -1
  7. package/lib/Socket/message-builder.js +475 -0
  8. package/lib/Socket/messages-send.js +29 -4
  9. package/lib/Socket/privacy.js +318 -0
  10. package/lib/Store/make-in-memory-store.js +47 -1
  11. package/lib/Utils/index.js +1 -0
  12. package/lib/Utils/messages-media.js +82 -0
  13. package/lib/Utils/messages.js +137 -3
  14. package/lib/Utils/sticker.js +133 -0
  15. package/lib/Utils/use-sqlite-auth-state.js +162 -0
  16. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  17. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -50
  18. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +56 -52
  19. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -25
  20. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  21. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  22. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  23. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -36
  24. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  25. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +26 -23
  26. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +52 -49
  27. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -27
  28. package/lib/WAUSync/Protocols/index.js +12 -5
  29. package/lib/WAUSync/USyncQuery.js +150 -96
  30. package/lib/WAUSync/USyncUser.js +55 -29
  31. package/lib/WAUSync/index.js +3 -3
  32. package/package.json +5 -3
@@ -0,0 +1,318 @@
1
+ import { executeWMexQuery } from './mex.js'
2
+
3
+ /**
4
+ * MEX query IDs for privacy, status/profile, account/auth, and misc operations.
5
+ * Source: assets/whatsapp-android-mex_client_persist_ids.json
6
+ */
7
+ const PRIVACY_MEX_IDS = {
8
+ // Privacy settings
9
+ GET_SETTINGS: '32774292262215380', // GetPrivacySettingsQuery
10
+ SET_SETTING: '26887749497493184', // SetPrivacySettingMutation
11
+ UPDATE_CONTACT_LIST: '26375158178762800', // UpdatePrivacyContactListMutation
12
+ GET_CONTACT_LIST: '25700444246275824', // GetPrivacyContactListQuery
13
+ // Status / profile
14
+ UPDATE_TEXT_STATUS: '25863197129975892', // UpdateTextStatus
15
+ GET_TEXT_STATUS_LIST: '25741205615468936', // GetTextStatusList
16
+ UPDATE_USER_STATUS: '7452341274886724', // UpdateUserStatus
17
+ FETCH_USER_PICTURE: '24983561624604410', // FetchUserPictureInfo
18
+ PROFILE_PICTURE_MUTATION: '24714239711610700', // ProfilePictureMutation
19
+ // Account / auth
20
+ ACCOUNT_LOGIN: '27298465499757130', // AccountLoginMutation
21
+ ACCOUNT_LOGOUT: '26863447609979190', // AccountLogoutMutation
22
+ MULTI_ACCOUNT_REVOKE: '25846242091639660', // MultiAccountRevokeAccount
23
+ ADD_MULTI_ACCOUNT_LINK: '25502812266025190', // AddMultiAccountLink
24
+ ADD_TRUSTED_DEVICE: '24522952587403290', // AddTrustedDeviceMutation
25
+ GET_TRUSTED_DEVICES: '25123358920671964', // GetTrustedDevicesQuery
26
+ UNTRUST_TRUSTED_DEVICE: '26574930682133620', // UntrustTrustedDeviceMutation
27
+ DELETE_TRUSTED_DEVICE: '33867503889559536', // DeleteTrustedDeviceMutation
28
+ // Misc
29
+ MOBILE_CONFIG_FETCH: '25676911271914596', // MobileConfigFetchQuery
30
+ NOTIFY_PUSH_NAME: '25900490552974544', // NotifyPushName
31
+ CONTACT_INTEGRITY: '25924358997169496', // ContactIntegrityQuery
32
+ BIZ_INTEGRITY: '25975613018777536', // BizIntegrityQuery
33
+ LINKED_PROFILES_SET: '25013968611531010', // LinkedProfilesSet
34
+ LINKED_PROFILES_REMOVE: '24537675509265524', // LinkedProfilesRemove
35
+ LINKED_PROFILES_UPDATE: '24876967165297616', // LinkedProfilesUpdate
36
+ MIGRATE_BLOCKLIST_LID: '25028600226770430', // MigrateBlocklistLid
37
+ QR_CODE_SCAN: '26287165600869744' // QRCodeScan
38
+ }
39
+
40
+ export const makePrivacySocket = sock => {
41
+ const { query, generateMessageTag } = sock
42
+
43
+ const mexQuery = (variables, queryId, dataPath) =>
44
+ executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag)
45
+
46
+ // ── Privacy Settings ────────────────────────────────────────────────────
47
+
48
+ /**
49
+ * Fetch all privacy settings via MEX.
50
+ */
51
+ const getPrivacySettings = (jid, features = null) => {
52
+ const users = [{ jid, ...(features ? { privacy_features: features } : {}) }]
53
+ return mexQuery({ users }, PRIVACY_MEX_IDS.GET_SETTINGS, 'xwa2_fetch_wa_users')
54
+ }
55
+
56
+ /**
57
+ * Set a privacy setting via MEX.
58
+ * Features: "LAST_SEEN", "ONLINE", "PROFILE_PHOTO", "STATUS", "READ_RECEIPTS", "GROUPS", "CALLS", "SCREENSHOT", "LIVE_LOCATION"
59
+ * Settings: "ALL", "CONTACTS", "CONTACT_BLACKLIST", "NONE"
60
+ */
61
+ const setPrivacySetting = (feature, setting) =>
62
+ mexQuery({ feature, setting }, PRIVACY_MEX_IDS.SET_SETTING, 'xwa2_privacy_feature_update')
63
+
64
+ /**
65
+ * Update the contact list for a privacy setting.
66
+ */
67
+ const updatePrivacyContactList = (feature, setting, jids) =>
68
+ mexQuery(
69
+ { feature, setting, contacts: jids.map(jid => ({ jid })) },
70
+ PRIVACY_MEX_IDS.UPDATE_CONTACT_LIST,
71
+ 'xwa2_privacy_contact_list_update'
72
+ )
73
+
74
+ /**
75
+ * Fetch the contact list for a privacy setting.
76
+ */
77
+ const getPrivacyContactList = (feature, setting) =>
78
+ mexQuery({ feature, setting }, PRIVACY_MEX_IDS.GET_CONTACT_LIST, 'xwa2_privacy_contact_list')
79
+
80
+ // ── Status / Profile ───────────────────────────────────────────────────
81
+
82
+ /**
83
+ * Update own text status About via MEX.
84
+ */
85
+ const updateTextStatus = (text, emoji = null) => {
86
+ const input = { text }
87
+ if (emoji) input.emoji = { content: emoji }
88
+ return mexQuery({ text_status_input: input }, PRIVACY_MEX_IDS.UPDATE_TEXT_STATUS, 'xwa2_text_status_update')
89
+ }
90
+
91
+ /**
92
+ * Fetch text statuses About for a list of JIDs via MEX.
93
+ */
94
+ const getTextStatusList = (jids, lastUpdateTime = null) => {
95
+ const input = jids.map(jid => ({ jid, last_update_time: lastUpdateTime }))
96
+ return mexQuery({ input }, PRIVACY_MEX_IDS.GET_TEXT_STATUS_LIST, 'xwa2_text_status_list')
97
+ }
98
+
99
+ /**
100
+ * Update own user status string via MEX.
101
+ */
102
+ const updateUserStatus = status =>
103
+ mexQuery({ status }, PRIVACY_MEX_IDS.UPDATE_USER_STATUS, 'xwa2_update_user_status')
104
+
105
+ /**
106
+ * Fetch picture info for a user via MEX.
107
+ */
108
+ const fetchUserPictureInfo = jid =>
109
+ mexQuery({ jid }, PRIVACY_MEX_IDS.FETCH_USER_PICTURE, 'xwa2_fetch_user_picture_info')
110
+
111
+ /**
112
+ * Set own profile picture via MEX.
113
+ */
114
+ const setProfilePictureMex = (imageBase64, type = 'image') =>
115
+ mexQuery(
116
+ { input: { image: imageBase64, type } },
117
+ PRIVACY_MEX_IDS.PROFILE_PICTURE_MUTATION,
118
+ 'xwa2_profile_picture_mutation'
119
+ )
120
+
121
+ // ── Account / Auth ─────────────────────────────────────────────────────
122
+
123
+ /**
124
+ * Mark account as logged-in via MEX.
125
+ */
126
+ const accountLogin = phoneNumber =>
127
+ mexQuery({ input: { phone_number: phoneNumber } }, PRIVACY_MEX_IDS.ACCOUNT_LOGIN, 'xwa2_account_login')
128
+
129
+ /**
130
+ * Mark account as logged-out via MEX.
131
+ */
132
+ const accountLogout = (phoneNumber, enabledBiometric = false) =>
133
+ mexQuery(
134
+ { input: { phone_number: phoneNumber, enabled_biometric: enabledBiometric } },
135
+ PRIVACY_MEX_IDS.ACCOUNT_LOGOUT,
136
+ 'xwa2_account_logout'
137
+ )
138
+
139
+ /**
140
+ * Add a multi-account link via MEX.
141
+ */
142
+ const addMultiAccountLink = phoneNumber =>
143
+ mexQuery(
144
+ { input: { phone_number: phoneNumber } },
145
+ PRIVACY_MEX_IDS.ADD_MULTI_ACCOUNT_LINK,
146
+ 'xwa2_add_multi_account_link'
147
+ )
148
+
149
+ /**
150
+ * Add a trusted device via MEX.
151
+ */
152
+ const addTrustedDevice = (deviceId, deviceName) =>
153
+ mexQuery({ device_id: deviceId, device_name: deviceName }, PRIVACY_MEX_IDS.ADD_TRUSTED_DEVICE, 'xwa2_add_trusted_device')
154
+
155
+ /**
156
+ * Fetch list of trusted devices for the account via MEX.
157
+ */
158
+ const getTrustedDevices = () => mexQuery({}, PRIVACY_MEX_IDS.GET_TRUSTED_DEVICES, 'xwa2_get_trusted_devices')
159
+
160
+ /**
161
+ * Untrust a trusted device via MEX.
162
+ */
163
+ const untrustTrustedDevice = (deviceId, reason = 'USER_INITIATED') =>
164
+ mexQuery(
165
+ { device_id: deviceId, reason },
166
+ PRIVACY_MEX_IDS.UNTRUST_TRUSTED_DEVICE,
167
+ 'xwa2_untrust_trusted_device'
168
+ )
169
+
170
+ /**
171
+ * Delete a trusted device entirely via MEX.
172
+ */
173
+ const deleteTrustedDevice = deviceId =>
174
+ mexQuery({ device_id: deviceId }, PRIVACY_MEX_IDS.DELETE_TRUSTED_DEVICE, 'xwa2_delete_trusted_device')
175
+
176
+ /**
177
+ * Revoke multi-account link for a secondary account via MEX.
178
+ */
179
+ const revokeMultiAccount = accountJid =>
180
+ mexQuery({ account_jid: accountJid }, PRIVACY_MEX_IDS.MULTI_ACCOUNT_REVOKE, 'xwa2_multi_account_revoke')
181
+
182
+ // ── Misc ───────────────────────────────────────────────────────────────
183
+
184
+ /**
185
+ * Fetch mobile config via MEX.
186
+ */
187
+ const fetchMobileConfig = (apiVersion = 0, epRefreshId = 0, flags = '') =>
188
+ mexQuery(
189
+ { api_version: apiVersion, ep_refresh_id: epRefreshId, flags },
190
+ PRIVACY_MEX_IDS.MOBILE_CONFIG_FETCH,
191
+ 'xwa2_mobile_config_fetch'
192
+ )
193
+
194
+ /**
195
+ * Notify group members of your push name via MEX.
196
+ */
197
+ const notifyPushName = (groupJid, participants) =>
198
+ mexQuery(
199
+ {
200
+ input: {
201
+ group_jid: groupJid,
202
+ participants: participants.map(({ jid, pushName }) => ({ jid, push_name: pushName }))
203
+ }
204
+ },
205
+ PRIVACY_MEX_IDS.NOTIFY_PUSH_NAME,
206
+ 'xwa2_notify_push_name'
207
+ )
208
+
209
+ /**
210
+ * Run a contact integrity check via MEX.
211
+ */
212
+ const contactIntegrityQuery = (jids, useCase = 'START_CHAT_CONTEXT') =>
213
+ mexQuery(
214
+ { users: jids.map(jid => ({ jid })), use_case: useCase },
215
+ PRIVACY_MEX_IDS.CONTACT_INTEGRITY,
216
+ 'xwa2_fetch_wa_users'
217
+ )
218
+
219
+ /**
220
+ * Run a business integrity check via MEX.
221
+ */
222
+ const bizIntegrityQuery = jids =>
223
+ mexQuery(
224
+ { users: jids.map(jid => ({ jid })) },
225
+ PRIVACY_MEX_IDS.BIZ_INTEGRITY,
226
+ 'xwa2_fetch_wa_users'
227
+ )
228
+
229
+ /**
230
+ * Set linked social profiles FB IG via MEX.
231
+ */
232
+ const linkedProfilesSet = profiles => {
233
+ const mapped = profiles.map(p => {
234
+ const entry = { type: p.type }
235
+ if (p.vid) entry.vid = p.vid
236
+ else if (p.username) entry.username = p.username
237
+ return entry
238
+ })
239
+ return mexQuery({ profiles: mapped }, PRIVACY_MEX_IDS.LINKED_PROFILES_SET, 'xwa2_linked_profiles_set')
240
+ }
241
+
242
+ /**
243
+ * Remove linked social profiles via MEX.
244
+ */
245
+ const linkedProfilesRemove = types =>
246
+ mexQuery(
247
+ { profiles: types.map(type => ({ type })) },
248
+ PRIVACY_MEX_IDS.LINKED_PROFILES_REMOVE,
249
+ 'xwa2_linked_profiles_remove'
250
+ )
251
+
252
+ /**
253
+ * Update linked social profile visibility settings via MEX.
254
+ */
255
+ const linkedProfilesUpdate = profiles =>
256
+ mexQuery(
257
+ { profiles: profiles.map(({ type, showOnProfile }) => ({ type, show_on_profile: showOnProfile })) },
258
+ PRIVACY_MEX_IDS.LINKED_PROFILES_UPDATE,
259
+ 'xwa2_linked_profiles_update'
260
+ )
261
+
262
+ /**
263
+ * Migrate blocklist to LID addressing via MEX.
264
+ */
265
+ const migrateBlocklistLid = (jids, dhash = '', dirtyAck = true) =>
266
+ mexQuery(
267
+ {
268
+ input: {
269
+ blocklist: jids.map(jid => ({ jid })),
270
+ dhash,
271
+ dirty_ack: dirtyAck
272
+ }
273
+ },
274
+ PRIVACY_MEX_IDS.MIGRATE_BLOCKLIST_LID,
275
+ 'xwa2_migrate_blocklist_lid'
276
+ )
277
+
278
+ /**
279
+ * Scan a QR code via MEX.
280
+ */
281
+ const qrCodeScan = qrData =>
282
+ mexQuery({ qr_data: qrData }, PRIVACY_MEX_IDS.QR_CODE_SCAN, 'xwa2_qr_code_scan')
283
+
284
+ return {
285
+ ...sock,
286
+ // Privacy
287
+ getPrivacySettings,
288
+ setPrivacySetting,
289
+ updatePrivacyContactList,
290
+ getPrivacyContactList,
291
+ // Status / profile
292
+ updateTextStatus,
293
+ getTextStatusList,
294
+ updateUserStatus,
295
+ fetchUserPictureInfo,
296
+ setProfilePictureMex,
297
+ // Account / auth
298
+ accountLogin,
299
+ accountLogout,
300
+ addMultiAccountLink,
301
+ addTrustedDevice,
302
+ getTrustedDevices,
303
+ untrustTrustedDevice,
304
+ deleteTrustedDevice,
305
+ revokeMultiAccount,
306
+ // Misc
307
+ fetchMobileConfig,
308
+ notifyPushName,
309
+ contactIntegrityQuery,
310
+ bizIntegrityQuery,
311
+ linkedProfilesSet,
312
+ linkedProfilesRemove,
313
+ linkedProfilesUpdate,
314
+ migrateBlocklistLid,
315
+ qrCodeScan,
316
+ PRIVACY_MEX_IDS
317
+ }
318
+ }
@@ -1,3 +1,4 @@
1
+ import fs from "fs";
1
2
  import * as WAProto_1 from "../../WAProto/index.js";
2
3
  import * as Defaults_1 from "../Defaults/index.js";
3
4
  import { LabelAssociationType } from "../Types/LabelAssociation.js";
@@ -181,6 +182,48 @@ export default function makeInMemoryStore(config) {
181
182
  const loadMessage = async (jid, id) => {
182
183
  return messages[jid]?.get(id)
183
184
  }
185
+
186
+ /**
187
+ * Persist the whole store to a JSON file on disk (synchronous, atomic write).
188
+ * Writes to a temp file first then renames, so a crash mid-write can't
189
+ * corrupt the existing store file.
190
+ */
191
+ const writeToFile = (path) => {
192
+ try {
193
+ const tmpPath = `${path}.tmp`;
194
+ fs.writeFileSync(tmpPath, JSON.stringify(toJSON()));
195
+ fs.renameSync(tmpPath, path);
196
+ } catch (err) {
197
+ logger.error({ err }, "failed to write store to file");
198
+ }
199
+ };
200
+
201
+ /**
202
+ * Load store state from a JSON file on disk, if it exists.
203
+ * Safe to call even if the file was never created yet.
204
+ */
205
+ const readFromFile = (path) => {
206
+ if (!fs.existsSync(path)) return;
207
+ try {
208
+ const jsonStr = fs.readFileSync(path, { encoding: "utf-8" });
209
+ const json = JSON.parse(jsonStr);
210
+ fromJSON(json);
211
+ } catch (err) {
212
+ logger.error({ err }, "failed to read store from file");
213
+ }
214
+ };
215
+
216
+ /**
217
+ * Convenience helper: load once from `path` (if present), then keep
218
+ * saving to the same file every `intervalMs` (default 10s).
219
+ * Returns a function to stop the auto-save interval.
220
+ */
221
+ const writeToFileInterval = (path, intervalMs = 10_000) => {
222
+ readFromFile(path);
223
+ const interval = setInterval(() => writeToFile(path), intervalMs);
224
+ return () => clearInterval(interval);
225
+ };
226
+
184
227
  return {
185
228
  chats,
186
229
  contacts,
@@ -193,6 +236,9 @@ export default function makeInMemoryStore(config) {
193
236
  bind,
194
237
  toJSON,
195
238
  fromJSON,
196
- loadMessage
239
+ loadMessage,
240
+ writeToFile,
241
+ readFromFile,
242
+ writeToFileInterval
197
243
  };
198
244
  }
@@ -11,6 +11,7 @@ export * from './chat-utils.js';
11
11
  export * from './lt-hash.js';
12
12
  export * from './auth-utils.js';
13
13
  export * from './use-multi-file-auth-state.js';
14
+ export * from './use-sqlite-auth-state.js';
14
15
  export * from './link-preview.js';
15
16
  export * from './event-buffer.js';
16
17
  export * from './process-message.js';
@@ -778,6 +778,88 @@ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
778
778
  const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
779
779
  return proto.MediaRetryNotification.decode(plaintext);
780
780
  };
781
+ const CRC_TABLE = (() => {
782
+ const table = new Uint32Array(256);
783
+ for (let n = 0; n < 256; n++) {
784
+ let c = n;
785
+ for (let k = 0; k < 8; k++) {
786
+ c = c & 1 ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
787
+ }
788
+ table[n] = c >>> 0;
789
+ }
790
+ return table;
791
+ })();
792
+ export const crc32 = (buf) => {
793
+ let crc = 0xffffffff;
794
+ for (let i = 0; i < buf.length; i++) {
795
+ crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
796
+ }
797
+ return (crc ^ 0xffffffff) >>> 0;
798
+ };
799
+ export const buildZipArchive = (files) => {
800
+ const localChunks = [];
801
+ const centralChunks = [];
802
+ let offset = 0;
803
+ for (const { name, data } of files) {
804
+ const nameBuf = Buffer.from(name, 'utf8');
805
+ const crc = crc32(data);
806
+ const dosTime = 0;
807
+ const dosDate = 0x21;
808
+ const localHeader = Buffer.alloc(30);
809
+ localHeader.writeUInt32LE(0x04034b50, 0);
810
+ localHeader.writeUInt16LE(20, 4);
811
+ localHeader.writeUInt16LE(0, 6);
812
+ localHeader.writeUInt16LE(0, 8);
813
+ localHeader.writeUInt16LE(dosTime, 10);
814
+ localHeader.writeUInt16LE(dosDate, 12);
815
+ localHeader.writeUInt32LE(crc, 14);
816
+ localHeader.writeUInt32LE(data.length, 18);
817
+ localHeader.writeUInt32LE(data.length, 22);
818
+ localHeader.writeUInt16LE(nameBuf.length, 26);
819
+ localHeader.writeUInt16LE(0, 28);
820
+ localChunks.push(localHeader, nameBuf, data);
821
+ const centralHeader = Buffer.alloc(46);
822
+ centralHeader.writeUInt32LE(0x02014b50, 0);
823
+ centralHeader.writeUInt16LE(20, 4);
824
+ centralHeader.writeUInt16LE(20, 6);
825
+ centralHeader.writeUInt16LE(0, 8);
826
+ centralHeader.writeUInt16LE(0, 10);
827
+ centralHeader.writeUInt16LE(dosTime, 12);
828
+ centralHeader.writeUInt16LE(dosDate, 14);
829
+ centralHeader.writeUInt32LE(crc, 16);
830
+ centralHeader.writeUInt32LE(data.length, 20);
831
+ centralHeader.writeUInt32LE(data.length, 24);
832
+ centralHeader.writeUInt16LE(nameBuf.length, 28);
833
+ centralHeader.writeUInt16LE(0, 30);
834
+ centralHeader.writeUInt16LE(0, 32);
835
+ centralHeader.writeUInt16LE(0, 34);
836
+ centralHeader.writeUInt16LE(0, 36);
837
+ centralHeader.writeUInt32LE(0, 38);
838
+ centralHeader.writeUInt32LE(offset, 42);
839
+ centralChunks.push(centralHeader, nameBuf);
840
+ offset += localHeader.length + nameBuf.length + data.length;
841
+ }
842
+ const centralDirStart = offset;
843
+ const centralDirBuf = Buffer.concat(centralChunks);
844
+ const eocd = Buffer.alloc(22);
845
+ eocd.writeUInt32LE(0x06054b50, 0);
846
+ eocd.writeUInt16LE(0, 4);
847
+ eocd.writeUInt16LE(0, 6);
848
+ eocd.writeUInt16LE(files.length, 8);
849
+ eocd.writeUInt16LE(files.length, 10);
850
+ eocd.writeUInt32LE(centralDirBuf.length, 12);
851
+ eocd.writeUInt32LE(centralDirStart, 16);
852
+ eocd.writeUInt16LE(0, 20);
853
+ return Buffer.concat([...localChunks, centralDirBuf, eocd]);
854
+ };
855
+ export const resolveStickerBuffer = async (item, opts) => {
856
+ if (Buffer.isBuffer(item)) {
857
+ return item;
858
+ }
859
+ const media = typeof item === 'string' ? { url: item } : item;
860
+ const { stream } = await getStream(media, opts);
861
+ return toBuffer(stream);
862
+ };
781
863
  export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
782
864
  const MEDIA_RETRY_STATUS_MAP = {
783
865
  [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
@@ -8,7 +8,8 @@ import { WAMessageStatus, WAProto } from '../Types/index.js';
8
8
  import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
9
  import { sha256 } from './crypto.js';
10
10
  import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
- import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
11
+ import { buildZipArchive, downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData, resolveStickerBuffer } from './messages-media.js';
12
+ import { makeSticker, convertToTrayIcon, isLikelyVideoBuffer } from './sticker.js';
12
13
  import { shouldIncludeReportingToken } from './reporting-utils.js';
13
14
  const MIMETYPE_MAP = {
14
15
  image: 'image/jpeg',
@@ -18,6 +19,34 @@ const MIMETYPE_MAP = {
18
19
  sticker: 'image/webp',
19
20
  'product-catalog-image': 'image/jpeg'
20
21
  };
22
+ const RAW_PROTO_MESSAGE_KEYS = [
23
+ 'conversation', 'senderKeyDistributionMessage', 'imageMessage', 'contactMessage', 'locationMessage',
24
+ 'extendedTextMessage', 'documentMessage', 'audioMessage', 'videoMessage', 'call', 'chat', 'protocolMessage',
25
+ 'contactsArrayMessage', 'highlyStructuredMessage', 'fastRatchetKeySenderKeyDistributionMessage',
26
+ 'sendPaymentMessage', 'liveLocationMessage', 'requestPaymentMessage', 'declinePaymentRequestMessage',
27
+ 'cancelPaymentRequestMessage', 'templateMessage', 'stickerMessage', 'groupInviteMessage',
28
+ 'templateButtonReplyMessage', 'productMessage', 'deviceSentMessage', 'messageContextInfo', 'listMessage',
29
+ 'viewOnceMessage', 'orderMessage', 'listResponseMessage', 'ephemeralMessage', 'invoiceMessage',
30
+ 'buttonsMessage', 'buttonsResponseMessage', 'paymentInviteMessage', 'interactiveMessage', 'reactionMessage',
31
+ 'stickerSyncRmrMessage', 'interactiveResponseMessage', 'pollCreationMessage', 'pollUpdateMessage',
32
+ 'keepInChatMessage', 'documentWithCaptionMessage', 'requestPhoneNumberMessage', 'viewOnceMessageV2',
33
+ 'encReactionMessage', 'editedMessage', 'viewOnceMessageV2Extension', 'pollCreationMessageV2',
34
+ 'scheduledCallCreationMessage', 'groupMentionedMessage', 'pinInChatMessage', 'pollCreationMessageV3',
35
+ 'scheduledCallEditMessage', 'ptvMessage', 'botInvokeMessage', 'callLogMesssage', 'messageHistoryBundle',
36
+ 'encCommentMessage', 'bcallMessage', 'lottieStickerMessage', 'eventMessage', 'encEventResponseMessage',
37
+ 'commentMessage', 'newsletterAdminInviteMessage', 'placeholderMessage', 'secretEncryptedMessage',
38
+ 'albumMessage', 'eventCoverImage', 'stickerPackMessage', 'statusMentionMessage', 'pollResultSnapshotMessage',
39
+ 'pollCreationOptionImageMessage', 'associatedChildMessage', 'groupStatusMentionMessage',
40
+ 'pollCreationMessageV4', 'statusAddYours', 'groupStatusMessage', 'richResponseMessage',
41
+ 'statusNotificationMessage', 'limitSharingMessage', 'botTaskMessage', 'questionMessage',
42
+ 'messageHistoryNotice', 'groupStatusMessageV2', 'botForwardedMessage', 'statusQuestionAnswerMessage',
43
+ 'questionReplyMessage', 'questionResponseMessage', 'statusQuotedMessage', 'statusStickerInteractionMessage',
44
+ 'pollCreationMessageV5', 'newsletterFollowerInviteMessageV2', 'pollResultSnapshotMessageV3',
45
+ 'newsletterAdminProfileMessage', 'newsletterAdminProfileMessageV2', 'spoilerMessage',
46
+ 'pollCreationMessageV6', 'conditionalRevealMessage', 'pollAddOptionMessage', 'eventInviteMessage',
47
+ 'groupRootKeyShare', 'paymentReminderMessage', 'splitPaymentMessage', 'newsletterAdminProfileStatusMessage',
48
+ 'rootSecretDistributeMessage'
49
+ ];
21
50
  const MessageTypeProto = {
22
51
  image: WAProto.Message.ImageMessage,
23
52
  video: WAProto.Message.VideoMessage,
@@ -852,8 +881,113 @@ export const generateWAMessageContent = async (message, options) => {
852
881
  }
853
882
  };
854
883
  }
884
+ else if (hasNonNullishProperty(message, 'stickerPacks')) {
885
+ const pack = message.stickerPacks;
886
+ const rawStickers = Array.isArray(pack.stickers) ? pack.stickers : [];
887
+ if (rawStickers.length === 0) {
888
+ throw new Boom('stickerPacks.stickers must have at least one sticker', { statusCode: 400 });
889
+ }
890
+ const packName = pack.name || 'Sticker Pack';
891
+ const publisher = pack.publisher || pack.author || '';
892
+ // each entry can be raw sticker media, or { image, animated, emojis, accessibilityLabel, quality }
893
+ const preparedStickers = await Promise.all(rawStickers.map(async (entry, i) => {
894
+ const isWrapped = entry && typeof entry === 'object' && !Buffer.isBuffer(entry) && 'image' in entry;
895
+ const rawBuffer = await resolveStickerBuffer(isWrapped ? entry.image : entry, options.options);
896
+ const animated = isWrapped ? !!entry.animated : false;
897
+ const emojis = (isWrapped && entry.emojis) || [];
898
+ const webp = await makeSticker(rawBuffer, {
899
+ pack: packName,
900
+ author: publisher,
901
+ emojis,
902
+ animated: animated || isLikelyVideoBuffer(rawBuffer),
903
+ quality: (isWrapped && entry.quality) || 60
904
+ });
905
+ return {
906
+ fileName: `sticker_${i}.webp`,
907
+ data: webp,
908
+ isAnimated: animated,
909
+ emojis,
910
+ accessibilityLabel: isWrapped ? entry.accessibilityLabel : undefined,
911
+ isLottie: false,
912
+ mimetype: 'image/webp'
913
+ };
914
+ }));
915
+ const trayIconFileName = 'tray.png';
916
+ const trayIconPng = await convertToTrayIcon(await resolveStickerBuffer(
917
+ (rawStickers[0] && typeof rawStickers[0] === 'object' && !Buffer.isBuffer(rawStickers[0]) && 'image' in rawStickers[0])
918
+ ? rawStickers[0].image
919
+ : rawStickers[0],
920
+ options.options
921
+ ));
922
+ const stickerPackId = pack.stickerPackId || randomUUID();
923
+ const zipEntries = [
924
+ ...preparedStickers.map(s => ({ name: s.fileName, data: s.data })),
925
+ { name: trayIconFileName, data: trayIconPng }
926
+ ];
927
+ const archive = buildZipArchive(zipEntries);
928
+ // reuse the normal, well-tested media upload path to encrypt+upload the archive,
929
+ // then repurpose the resulting media fields into the stickerPackMessage itself
930
+ const uploaded = await prepareWAMessageMedia({
931
+ document: archive,
932
+ mimetype: 'application/zip',
933
+ fileName: `${stickerPackId}.zip`
934
+ }, options);
935
+ const doc = uploaded.documentMessage;
936
+ m = {
937
+ stickerPackMessage: {
938
+ stickerPackId,
939
+ name: packName,
940
+ publisher,
941
+ packDescription: pack.description,
942
+ stickers: preparedStickers.map(s => ({
943
+ fileName: s.fileName,
944
+ isAnimated: s.isAnimated,
945
+ emojis: s.emojis,
946
+ accessibilityLabel: s.accessibilityLabel,
947
+ isLottie: s.isLottie,
948
+ mimetype: s.mimetype
949
+ })),
950
+ fileLength: doc.fileLength,
951
+ fileSha256: doc.fileSha256,
952
+ fileEncSha256: doc.fileEncSha256,
953
+ mediaKey: doc.mediaKey,
954
+ directPath: doc.directPath,
955
+ mediaKeyTimestamp: doc.mediaKeyTimestamp,
956
+ trayIconFileName,
957
+ stickerPackSize: archive.length,
958
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED
959
+ }
960
+ };
961
+ }
962
+ else if (hasNonNullishProperty(message, 'sticker') && (message.pack || message.author || message.isPrivate || message.premium || message.animated)) {
963
+ const rawBuffer = await resolveStickerBuffer(message.sticker, options.options);
964
+ const finalWebp = await makeSticker(rawBuffer, {
965
+ pack: message.pack || '',
966
+ author: message.author || '',
967
+ emojis: message.emojis || [],
968
+ isPrivate: !!message.isPrivate,
969
+ animated: !!message.animated,
970
+ quality: message.quality || 60
971
+ });
972
+ m = await prepareWAMessageMedia({ sticker: finalWebp }, options);
973
+ if (m.stickerMessage) {
974
+ if (message.premium) {
975
+ m.stickerMessage.premium = typeof message.premium === 'number' ? message.premium : 1;
976
+ }
977
+ if (message.isPrivate) {
978
+ m.stickerMessage.isAvatar = true;
979
+ }
980
+ }
981
+ }
855
982
  else {
856
- m = await prepareWAMessageMedia(message, options);
983
+ const rawProtoKey = RAW_PROTO_MESSAGE_KEYS.find(k => hasNonNullishProperty(message, k));
984
+ if (rawProtoKey) {
985
+ const built = proto.Message.fromObject({ [rawProtoKey]: message[rawProtoKey] });
986
+ m = { [rawProtoKey]: built[rawProtoKey] };
987
+ }
988
+ else {
989
+ m = await prepareWAMessageMedia(message, options);
990
+ }
857
991
  }
858
992
  if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
859
993
  m = { viewOnceMessage: { message: m } };
@@ -1256,4 +1390,4 @@ export const assertMediaContent = (content) => {
1256
1390
  throw new Boom('given message is not a media message', { statusCode: 400, data: content });
1257
1391
  }
1258
1392
  return mediaContent;
1259
- };
1393
+ };