@rosyn/whats 0.1.4 → 0.1.5

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.
@@ -10,7 +10,7 @@ import pb from "protobufjs/minimal.js";
10
10
  import { RosynWhatsClient } from "../client/index.js";
11
11
  import { downloadContentFromMessage, encryptWaMedia, toBuffer } from "../media/index.js";
12
12
  import { proto } from "../proto/index.js";
13
- import { DisconnectReason, generateMessageIDV2, jidDecode, jidNormalizedUser } from "../protocol/jid.js";
13
+ import { DisconnectReason, generateMessageIDV2, isJidBroadcast, isJidGroup, isJidNewsletter, isLidUser, jidDecode, jidNormalizedUser, } from "../protocol/jid.js";
14
14
  const pbkdf2Async = promisify(pbkdf2);
15
15
  import { decodeWABinaryNode, encodeWABinaryNode } from "../protocol/wabin.js";
16
16
  import { jidToSignalAddress, SignalProtocolManager, toSignalPub33, unpadRandomMax16, writeRandomPadMax16, } from "../signal/protocol.js";
@@ -379,9 +379,13 @@ export function makeWASocket(config = {}) {
379
379
  return "2:" + hash.slice(0, 6);
380
380
  };
381
381
  const lidToPnMap = new Map();
382
+ const pnToLidMap = new Map();
382
383
  const rememberLidPn = (lid, pn) => {
383
384
  if (lid && pn && lid.endsWith("@lid") && pn.endsWith("@s.whatsapp.net")) {
384
- lidToPnMap.set(jidNormalizedUser(lid), jidNormalizedUser(pn));
385
+ const normLid = jidNormalizedUser(lid);
386
+ const normPn = jidNormalizedUser(pn);
387
+ lidToPnMap.set(normLid, normPn);
388
+ pnToLidMap.set(normPn, normLid);
385
389
  }
386
390
  };
387
391
  const resolvePnJid = (jid) => {
@@ -391,6 +395,219 @@ export function makeWASocket(config = {}) {
391
395
  return jid;
392
396
  return lidToPnMap.get(jidNormalizedUser(jid)) ?? jid;
393
397
  };
398
+ const walkContextInfo = (obj, onContext) => {
399
+ if (!obj || typeof obj !== "object" || Array.isArray(obj) || obj instanceof Uint8Array)
400
+ return;
401
+ const rec = obj;
402
+ if (rec.contextInfo && typeof rec.contextInfo === "object") {
403
+ onContext(rec.contextInfo, rec);
404
+ if (rec.contextInfo.quotedMessage && typeof rec.contextInfo.quotedMessage === "object") {
405
+ walkContextInfo(rec.contextInfo.quotedMessage, onContext);
406
+ }
407
+ }
408
+ for (const k of Object.keys(rec)) {
409
+ if (k === "contextInfo")
410
+ continue;
411
+ const v = rec[k];
412
+ if (v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Uint8Array)) {
413
+ walkContextInfo(v, onContext);
414
+ }
415
+ }
416
+ };
417
+ const hasUnresolvedContextLids = (msg) => {
418
+ let found = false;
419
+ walkContextInfo(msg, (ctx) => {
420
+ if (found)
421
+ return;
422
+ if (typeof ctx.participant === "string" && ctx.participant.endsWith("@lid") && !lidToPnMap.has(jidNormalizedUser(ctx.participant))) {
423
+ found = true;
424
+ return;
425
+ }
426
+ if (Array.isArray(ctx.mentionedJid)) {
427
+ for (const jid of ctx.mentionedJid) {
428
+ if (typeof jid === "string" && jid.endsWith("@lid") && !lidToPnMap.has(jidNormalizedUser(jid))) {
429
+ found = true;
430
+ return;
431
+ }
432
+ }
433
+ }
434
+ });
435
+ return found;
436
+ };
437
+ const resolveContextInfoLids = (msg) => {
438
+ walkContextInfo(msg, (ctx, parent) => {
439
+ if (typeof ctx.participant === "string" && ctx.participant.endsWith("@lid")) {
440
+ ctx.participant = resolvePnJid(ctx.participant);
441
+ }
442
+ if (Array.isArray(ctx.mentionedJid)) {
443
+ const replacements = [];
444
+ ctx.mentionedJid = ctx.mentionedJid.map((jid) => {
445
+ if (typeof jid === "string" && jid.endsWith("@lid")) {
446
+ const resolved = resolvePnJid(jid);
447
+ if (resolved !== jid && resolved.endsWith("@s.whatsapp.net")) {
448
+ const lidUser = jidDecode(jid)?.user;
449
+ const pnUser = jidDecode(resolved)?.user;
450
+ if (lidUser && pnUser)
451
+ replacements.push([lidUser, pnUser]);
452
+ }
453
+ return resolved;
454
+ }
455
+ return jid;
456
+ });
457
+ if (replacements.length > 0) {
458
+ for (const field of ["text", "caption", "conversation"]) {
459
+ if (typeof parent[field] === "string") {
460
+ let updated = parent[field];
461
+ for (const [lidUser, pnUser] of replacements) {
462
+ updated = updated.replaceAll(`@${lidUser}`, `@${pnUser}`);
463
+ }
464
+ parent[field] = updated;
465
+ }
466
+ }
467
+ }
468
+ }
469
+ });
470
+ };
471
+ const pickIncomingExpirationSeconds = (msg) => {
472
+ if (!msg || typeof msg !== "object")
473
+ return undefined;
474
+ const inner = msg.ephemeralMessage?.message ??
475
+ msg.viewOnceMessage?.message ??
476
+ msg.viewOnceMessageV2?.message ??
477
+ msg.viewOnceMessageV2Extension?.message ??
478
+ msg.documentWithCaptionMessage?.message ??
479
+ msg.editedMessage?.message ??
480
+ msg;
481
+ for (const key of Object.keys(inner)) {
482
+ const val = inner[key];
483
+ if (val && typeof val === "object" && !Array.isArray(val) && !(val instanceof Uint8Array)) {
484
+ const exp = val.contextInfo?.expiration;
485
+ if (exp !== undefined && exp !== null)
486
+ return Number(exp);
487
+ }
488
+ }
489
+ return undefined;
490
+ };
491
+ const findChild = (node, tag) => Array.isArray(node.content) ? node.content.find((c) => c.tag === tag) : undefined;
492
+ const hasChild = (node, tag) => Boolean(findChild(node, tag));
493
+ const getNodeText = (node) => {
494
+ if (!node)
495
+ return undefined;
496
+ if (typeof node.content === "string")
497
+ return node.content;
498
+ if (node.content instanceof Uint8Array)
499
+ return Buffer.from(node.content).toString("utf8");
500
+ return undefined;
501
+ };
502
+ const INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom");
503
+ const attachDeepInspect = (obj, seen = new WeakSet()) => {
504
+ if (!obj || typeof obj !== "object" || obj instanceof Uint8Array || ArrayBuffer.isView(obj))
505
+ return;
506
+ if (seen.has(obj))
507
+ return;
508
+ seen.add(obj);
509
+ if (Array.isArray(obj)) {
510
+ for (const item of obj)
511
+ attachDeepInspect(item, seen);
512
+ return;
513
+ }
514
+ const rec = obj;
515
+ if (!Object.prototype.hasOwnProperty.call(rec, INSPECT_CUSTOM)) {
516
+ Object.defineProperty(rec, INSPECT_CUSTOM, {
517
+ enumerable: false,
518
+ configurable: true,
519
+ value(_depth, opts, inspectFn) {
520
+ return inspectFn({ ...this }, { ...opts, depth: null, maxArrayLength: null });
521
+ },
522
+ });
523
+ }
524
+ for (const k of Object.keys(rec)) {
525
+ attachDeepInspect(rec[k], seen);
526
+ }
527
+ };
528
+ const parseGroupMetadataNode = (grp, fallbackJid) => {
529
+ const attrs = grp.attrs ?? {};
530
+ const rawId = attrs.id ?? attrs.jid ?? fallbackJid ?? "";
531
+ const id = rawId && !rawId.includes("@") ? `${rawId}@g.us` : rawId;
532
+ const subject = attrs.subject ?? "";
533
+ const addressingMode = attrs.addressing_mode;
534
+ const descNode = findChild(grp, "description");
535
+ const desc = descNode ? getNodeText(findChild(descNode, "body")) : undefined;
536
+ const ephemeralNode = findChild(grp, "ephemeral");
537
+ const ephemeralDuration = ephemeralNode?.attrs?.expiration
538
+ ? Number(ephemeralNode.attrs.expiration) || undefined
539
+ : undefined;
540
+ const parentNode = findChild(grp, "parent");
541
+ const linkedParentNode = findChild(grp, "linked_parent");
542
+ const membershipNode = findChild(grp, "membership_approval_mode");
543
+ const groupJoinNode = membershipNode ? findChild(membershipNode, "group_join") : undefined;
544
+ const memberAddModeNode = findChild(grp, "member_add_mode");
545
+ const memberLinkModeNode = findChild(grp, "member_link_mode");
546
+ const participants = [];
547
+ if (Array.isArray(grp.content)) {
548
+ for (const c of grp.content) {
549
+ if (c.tag === "participant" && c.attrs?.jid) {
550
+ rememberLidPn(c.attrs.jid, c.attrs.phone_number);
551
+ const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? jidNormalizedUser(c.attrs.jid) : undefined);
552
+ const pnVal = c.attrs.phone_number
553
+ ? jidNormalizedUser(c.attrs.phone_number)
554
+ : c.attrs.jid.endsWith("@s.whatsapp.net")
555
+ ? jidNormalizedUser(c.attrs.jid)
556
+ : undefined;
557
+ rememberLidPn(lidVal, pnVal);
558
+ const pnId = pnVal ?? resolvePnJid(c.attrs.jid);
559
+ const admin = c.attrs.type;
560
+ participants.push({
561
+ id: pnId,
562
+ ...(pnVal ? { phoneNumber: pnVal } : {}),
563
+ ...(lidVal ? { lid: lidVal } : {}),
564
+ admin,
565
+ isAdmin: admin === "admin" || admin === "superadmin",
566
+ isSuperAdmin: admin === "superadmin",
567
+ ...(c.attrs.display_name ? { displayName: c.attrs.display_name } : {}),
568
+ ...(c.attrs.username ? { username: c.attrs.username } : {}),
569
+ });
570
+ }
571
+ }
572
+ }
573
+ const meta = {
574
+ id,
575
+ subject,
576
+ ...(attrs.s_o || attrs.subject_owner ? { subjectOwner: attrs.s_o ?? attrs.subject_owner } : {}),
577
+ ...(attrs.s_o_pn ? { subjectOwnerPhoneNumber: attrs.s_o_pn } : {}),
578
+ ...(attrs.s_o_username ? { subjectOwnerUsername: attrs.s_o_username } : {}),
579
+ ...(attrs.s_t ? { subjectTime: Number(attrs.s_t) } : {}),
580
+ ...(attrs.creation ? { creation: Number(attrs.creation) } : {}),
581
+ ...(attrs.creator || attrs.owner ? { owner: attrs.creator ?? attrs.owner } : {}),
582
+ ...(attrs.creator_pn ? { ownerPhoneNumber: attrs.creator_pn } : {}),
583
+ ...(attrs.creator_username ? { ownerUsername: attrs.creator_username } : {}),
584
+ ...(attrs.creator_country_code ? { ownerCountryCode: attrs.creator_country_code } : {}),
585
+ size: attrs.size ? Number(attrs.size) : participants.length,
586
+ addressingMode,
587
+ ...(desc !== undefined ? { desc } : {}),
588
+ ...(descNode?.attrs?.id ? { descId: descNode.attrs.id } : {}),
589
+ ...(descNode?.attrs?.participant ? { descOwner: descNode.attrs.participant } : {}),
590
+ ...(descNode?.attrs?.t ? { descTime: Number(descNode.attrs.t) } : {}),
591
+ restrict: hasChild(grp, "locked"),
592
+ announce: hasChild(grp, "announcement"),
593
+ isCommunity: parentNode !== undefined,
594
+ isCommunityAnnounce: hasChild(grp, "default_sub_group"),
595
+ joinApprovalMode: groupJoinNode?.attrs?.state === "on",
596
+ ...(memberAddModeNode ? { memberAddMode: getNodeText(memberAddModeNode) } : {}),
597
+ ...(memberLinkModeNode ? { memberLinkMode: getNodeText(memberLinkModeNode) } : {}),
598
+ ...(ephemeralDuration ? { ephemeralDuration } : {}),
599
+ ...(linkedParentNode?.attrs?.jid || parentNode?.attrs?.jid
600
+ ? { linkedParent: linkedParentNode?.attrs?.jid ?? parentNode?.attrs?.jid }
601
+ : {}),
602
+ noFrequentlyForwarded: hasChild(grp, "no_frequently_forwarded"),
603
+ incognito: hasChild(grp, "incognito"),
604
+ support: hasChild(grp, "support"),
605
+ suspended: hasChild(grp, "suspended"),
606
+ participants,
607
+ };
608
+ attachDeepInspect(meta);
609
+ return meta;
610
+ };
394
611
  rememberLidPn(authCreds.me?.lid, authCreds.me?.id);
395
612
  let msgTagCounter = 1;
396
613
  const nextTag = () => `${Math.floor(Date.now() / 1000)}.${msgTagCounter++}`;
@@ -422,7 +639,8 @@ export function makeWASocket(config = {}) {
422
639
  const p = pendingQueries.get(node.attrs.id);
423
640
  pendingQueries.delete(node.attrs.id);
424
641
  if (node.attrs.type === "error") {
425
- p.reject(new Error(`WA IQ error on ${node.attrs.id}`));
642
+ const errNode = Array.isArray(node.content) ? node.content.find((c) => c.tag === "error") : undefined;
643
+ p.reject(new Error(`WA IQ error on ${node.attrs.id}${errNode?.attrs?.code ? ` (${errNode.attrs.code})` : ""}`));
426
644
  }
427
645
  else {
428
646
  p.resolve(node);
@@ -960,7 +1178,7 @@ export function makeWASocket(config = {}) {
960
1178
  return { stanzaType: "media", mediatype: m.audioMessage.ptt ? "ptt" : "audio" };
961
1179
  if (m.documentMessage)
962
1180
  return { stanzaType: "media", mediatype: "document" };
963
- if (m.stickerMessage)
1181
+ if (m.stickerMessage || m.lottieStickerMessage || m.audioStickerMessage)
964
1182
  return { stanzaType: "media", mediatype: "sticker" };
965
1183
  return { stanzaType: "text" };
966
1184
  };
@@ -1058,16 +1276,22 @@ export function makeWASocket(config = {}) {
1058
1276
  const from = node.attrs.from;
1059
1277
  const participant = node.attrs.participant;
1060
1278
  const recipient = node.attrs.recipient;
1061
- const isGroup = from.endsWith("@g.us");
1062
- const chatId = isGroup || from === "status@broadcast" ? from : recipient || from;
1063
- const author = isGroup || from === "status@broadcast" ? participant || from : from;
1279
+ const isGroup = isJidGroup(from);
1280
+ const isBroadcast = from === "status@broadcast" || isJidBroadcast(from);
1281
+ const isNewsletter = isJidNewsletter(from);
1282
+ const chatId = isGroup || isBroadcast ? from : recipient || from;
1283
+ const author = isGroup || isBroadcast ? participant || from : from;
1064
1284
  rememberLidPn(participant, node.attrs.participant_pn);
1285
+ rememberLidPn(node.attrs.participant_lid, participant);
1065
1286
  rememberLidPn(from, node.attrs.sender_pn);
1287
+ rememberLidPn(node.attrs.sender_lid, from);
1066
1288
  rememberLidPn(authCreds.me?.lid, authCreds.me?.id);
1067
1289
  const meId = authCreds.me?.id ?? sock.user?.id;
1068
1290
  const meLid = authCreds.me?.lid ?? sock.user?.lid;
1069
1291
  const fromMe = Boolean((meId && jidDecode(author)?.user === jidDecode(meId)?.user) ||
1070
1292
  (meLid && jidDecode(author)?.user === jidDecode(meLid)?.user));
1293
+ const isSelfSentDirect = fromMe && !isGroup && !isBroadcast;
1294
+ const senderDevice = jidDecode(author)?.device ?? 0;
1071
1295
  const ackAttrs = {
1072
1296
  to: from,
1073
1297
  id: msgId,
@@ -1100,8 +1324,9 @@ export function makeWASocket(config = {}) {
1100
1324
  else {
1101
1325
  continue;
1102
1326
  }
1103
- let decoded = proto.Message.decode(plainBuf);
1104
- decoded = decoded.deviceSentMessage?.message ?? decoded;
1327
+ const rawDecoded = proto.Message.decode(plainBuf);
1328
+ const destinationJid = rawDecoded.deviceSentMessage?.destinationJid ?? undefined;
1329
+ const decoded = rawDecoded.deviceSentMessage?.message ?? rawDecoded;
1105
1330
  const skdm = decoded.senderKeyDistributionMessage ?? decoded.fastRatchetKeySenderKeyDistributionMessage;
1106
1331
  if (skdm?.axolotlSenderKeyDistributionMessage) {
1107
1332
  const gId = skdm.groupId ?? chatId;
@@ -1112,25 +1337,79 @@ export function makeWASocket(config = {}) {
1112
1337
  k !== "messageContextInfo");
1113
1338
  if (hasDisplayContent) {
1114
1339
  if (isGroup &&
1115
- participant?.endsWith("@lid") &&
1116
- !node.attrs.participant_pn &&
1117
- !lidToPnMap.has(jidNormalizedUser(participant))) {
1340
+ ((participant?.endsWith("@lid") &&
1341
+ !node.attrs.participant_pn &&
1342
+ !lidToPnMap.has(jidNormalizedUser(participant))) ||
1343
+ hasUnresolvedContextLids(decoded))) {
1118
1344
  await sock.groupMetadata(chatId).catch(() => undefined);
1119
1345
  }
1346
+ resolveContextInfoLids(decoded);
1347
+ attachDeepInspect(decoded);
1348
+ const effectiveChatId = isSelfSentDirect ? (recipient ?? destinationJid ?? chatId) : chatId;
1349
+ const resolvedRemoteJid = !isGroup && !isBroadcast ? resolvePnJid(effectiveChatId) : effectiveChatId;
1350
+ let remoteJidAlt;
1351
+ if (!isGroup && !isBroadcast) {
1352
+ if (isLidUser(resolvedRemoteJid)) {
1353
+ const pn = isSelfSentDirect
1354
+ ? node.attrs.peer_recipient_pn
1355
+ : node.attrs.sender_pn;
1356
+ remoteJidAlt = pn ? jidNormalizedUser(pn) : undefined;
1357
+ }
1358
+ else {
1359
+ const lid = isSelfSentDirect
1360
+ ? node.attrs.peer_recipient_lid ??
1361
+ (isLidUser(effectiveChatId) ? effectiveChatId : pnToLidMap.get(jidNormalizedUser(resolvedRemoteJid)))
1362
+ : node.attrs.sender_lid ??
1363
+ (isLidUser(effectiveChatId) ? effectiveChatId : pnToLidMap.get(jidNormalizedUser(resolvedRemoteJid)));
1364
+ remoteJidAlt = lid ? jidNormalizedUser(lid) : undefined;
1365
+ }
1366
+ }
1367
+ const resolvedParticipant = participant
1368
+ ? jidNormalizedUser(resolvePnJid(node.attrs.participant_pn || participant))
1369
+ : undefined;
1370
+ let participantAlt;
1371
+ if ((isGroup || isBroadcast) && resolvedParticipant) {
1372
+ if (isLidUser(resolvedParticipant)) {
1373
+ participantAlt = node.attrs.participant_pn
1374
+ ? jidNormalizedUser(node.attrs.participant_pn)
1375
+ : undefined;
1376
+ }
1377
+ else {
1378
+ const lid = node.attrs.participant_lid ??
1379
+ (isLidUser(participant) ? participant : pnToLidMap.get(resolvedParticipant));
1380
+ participantAlt = lid ? jidNormalizedUser(lid) : undefined;
1381
+ }
1382
+ }
1383
+ const senderUsername = !isSelfSentDirect
1384
+ ? (node.attrs.participant_username ?? node.attrs.username)?.replace(/^@/, "")
1385
+ : undefined;
1386
+ const recipientUsername = (node.attrs.recipient_username ?? node.attrs.peer_recipient_username)?.replace(/^@/, "");
1387
+ const recipientAlt = node.attrs.peer_recipient_pn ?? node.attrs.peer_recipient_lid;
1388
+ const expirationSeconds = pickIncomingExpirationSeconds(decoded);
1120
1389
  ev.emit("messages.upsert", {
1121
1390
  type: "notify",
1122
1391
  messages: [
1123
1392
  {
1124
1393
  key: {
1125
- remoteJid: !isGroup && chatId !== "status@broadcast" ? resolvePnJid(chatId) : chatId,
1126
- remoteJidAlt: !isGroup
1127
- ? node.attrs.sender_pn || node.attrs.sender_lid || node.attrs.peer_recipient_pn
1128
- : undefined,
1394
+ remoteJid: resolvedRemoteJid,
1395
+ ...(remoteJidAlt ? { remoteJidAlt } : {}),
1129
1396
  fromMe,
1130
1397
  id: msgId,
1131
- participant: participant ? resolvePnJid(node.attrs.participant_pn || participant) : undefined,
1132
- participantAlt: isGroup ? node.attrs.participant_pn || node.attrs.participant_lid : undefined,
1398
+ isGroup,
1399
+ isBroadcast,
1400
+ isNewsletter,
1401
+ senderDevice,
1402
+ ...(resolvedParticipant ? { participant: resolvedParticipant } : {}),
1403
+ ...(participantAlt ? { participantAlt } : {}),
1404
+ ...(senderUsername ? { senderUsername } : {}),
1405
+ ...(recipient ? { recipientJid: jidNormalizedUser(recipient) } : {}),
1406
+ ...(recipientAlt ? { recipientAlt: jidNormalizedUser(recipientAlt) } : {}),
1407
+ ...(recipientUsername ? { recipientUsername } : {}),
1133
1408
  },
1409
+ ...(resolvedParticipant ? { participant: resolvedParticipant } : {}),
1410
+ ...(isBroadcast ? { broadcast: true } : {}),
1411
+ ...(expirationSeconds !== undefined ? { expirationSeconds } : {}),
1412
+ ...(node.attrs.verified_name ? { verifiedBizName: node.attrs.verified_name } : {}),
1134
1413
  message: decoded,
1135
1414
  messageTimestamp: Number(node.attrs.t || Math.floor(Date.now() / 1000)),
1136
1415
  pushName: node.attrs.notify,
@@ -1348,7 +1627,24 @@ export function makeWASocket(config = {}) {
1348
1627
  };
1349
1628
  }
1350
1629
  if (c?.rawMessage && typeof c.rawMessage === "object") {
1351
- return c.rawMessage;
1630
+ const raw = c.rawMessage;
1631
+ if (raw.audioStickerMessage) {
1632
+ const futureProof = raw.audioStickerMessage;
1633
+ const outerMessage = futureProof.message ?? futureProof;
1634
+ const original = outerMessage.message ?? outerMessage;
1635
+ const originalMessage = original.stickerMessage ? original : { stickerMessage: original };
1636
+ const sticker = originalMessage.stickerMessage;
1637
+ const stickerBytes = sticker?.buffer ?? sticker?.data;
1638
+ const stickerMedia = stickerBytes instanceof Uint8Array
1639
+ ? { ...sticker, __rawBytes: stickerBytes }
1640
+ : sticker;
1641
+ return {
1642
+ audioStickerMessage: { message: originalMessage },
1643
+ messageContextInfo: raw.messageContextInfo,
1644
+ __audioStickerMedia: stickerMedia,
1645
+ };
1646
+ }
1647
+ return { ...raw };
1352
1648
  }
1353
1649
  if (c?.stickerPackMessage)
1354
1650
  return { stickerPackMessage: c.stickerPackMessage };
@@ -1660,6 +1956,30 @@ export function makeWASocket(config = {}) {
1660
1956
  return { conversation: text };
1661
1957
  };
1662
1958
  const waMsg = await buildOutgoingWAMessage(content);
1959
+ if (waMsg.audioStickerMessage?.message) {
1960
+ const envelope = waMsg.audioStickerMessage.message;
1961
+ const outerMessage = envelope.message ?? envelope;
1962
+ const inner = outerMessage.message ?? outerMessage;
1963
+ const sticker = envelope.stickerMessage ?? inner.stickerMessage;
1964
+ const audioMessage = sticker?.audioMessage;
1965
+ if (!sticker || !audioMessage) {
1966
+ throw new Error("Audio sticker payload must contain StickerMessage.audioMessage");
1967
+ }
1968
+ const stickerMedia = waMsg.__audioStickerMedia;
1969
+ const stickerBytes = stickerMedia?.__rawBytes;
1970
+ if (!sticker.url && !sticker.directPath && stickerBytes instanceof Uint8Array && stickerBytes.length > 0) {
1971
+ const uploaded = await uploadWaMedia(stickerBytes, "sticker", "/mms/image", sticker.mediaKey);
1972
+ Object.assign(sticker, uploaded);
1973
+ }
1974
+ delete waMsg.__audioStickerMedia;
1975
+ if (!sticker.url && !sticker.directPath) {
1976
+ throw new Error("Audio sticker needs sticker bytes or uploaded StickerMessage URL/directPath before relay");
1977
+ }
1978
+ if (!audioMessage.url && !audioMessage.directPath) {
1979
+ throw new Error("Audio sticker needs uploaded AudioMessage URL/directPath before relay");
1980
+ }
1981
+ waMsg.audioStickerMessage = { message: { stickerMessage: sticker } };
1982
+ }
1663
1983
  const quotedRaw = options?.quoted;
1664
1984
  const mentionedJid = Array.isArray(content?.mentions)
1665
1985
  ? content.mentions
@@ -1719,23 +2039,25 @@ export function makeWASocket(config = {}) {
1719
2039
  ? "button"
1720
2040
  : isStickerPack
1721
2041
  ? "sticker_pack"
1722
- : waMsg.imageMessage
1723
- ? "image"
1724
- : waMsg.videoMessage
1725
- ? waMsg.videoMessage.gifPlayback
1726
- ? "gif"
1727
- : "video"
1728
- : waMsg.ptvMessage
1729
- ? "ptv"
1730
- : waMsg.audioMessage
1731
- ? waMsg.audioMessage.ptt
1732
- ? "ptt"
1733
- : "audio"
1734
- : waMsg.documentMessage
1735
- ? "document"
1736
- : waMsg.stickerMessage
1737
- ? "sticker"
1738
- : undefined;
2042
+ : waMsg.audioStickerMessage || waMsg.lottieStickerMessage
2043
+ ? "sticker"
2044
+ : waMsg.imageMessage
2045
+ ? "image"
2046
+ : waMsg.videoMessage
2047
+ ? waMsg.videoMessage.gifPlayback
2048
+ ? "gif"
2049
+ : "video"
2050
+ : waMsg.ptvMessage
2051
+ ? "ptv"
2052
+ : waMsg.audioMessage
2053
+ ? waMsg.audioMessage.ptt
2054
+ ? "ptt"
2055
+ : "audio"
2056
+ : waMsg.documentMessage
2057
+ ? "document"
2058
+ : waMsg.stickerMessage
2059
+ ? "sticker"
2060
+ : undefined;
1739
2061
  const stanzaType = encMediatype ? "media" : "text";
1740
2062
  const deleteEditAttr = content?.delete && typeof content.delete === "object"
1741
2063
  ? jid.endsWith("@g.us") && !content.delete.fromMe
@@ -1886,27 +2208,57 @@ export function makeWASocket(config = {}) {
1886
2208
  ? String(content.edit.id ?? msgId)
1887
2209
  : msgId;
1888
2210
  const nlEditAttr = isNlDelete ? "8" : isNlEdit ? "3" : deleteEditAttr;
1889
- const nlPlaintext = isNlDelete
1890
- ? Buffer.alloc(0)
1891
- : isNlEdit && waMsg.protocolMessage?.editedMessage
1892
- ? proto.Message.encode(waMsg.protocolMessage.editedMessage)
1893
- : proto.Message.encode(waMsg);
1894
- transport.sendEncrypted(encodeWABinaryNode({
1895
- tag: "message",
1896
- attrs: {
1897
- id: nlMsgId,
1898
- to: jid,
1899
- type: stanzaType,
1900
- ...(nlEditAttr ? { edit: nlEditAttr } : {}),
1901
- },
1902
- content: [
1903
- {
1904
- tag: "plaintext",
1905
- attrs: !isNlDelete && encMediatype ? { mediatype: encMediatype } : {},
1906
- content: nlPlaintext,
2211
+ const nlSticker = waMsg.audioStickerMessage?.message?.stickerMessage;
2212
+ if (nlSticker && !isNlDelete && !isNlEdit) {
2213
+ const { audioMessage: nlAudio, ...plainSticker } = nlSticker;
2214
+ transport.sendEncrypted(encodeWABinaryNode({
2215
+ tag: "message",
2216
+ attrs: { id: nlMsgId, to: jid, type: "media" },
2217
+ content: [
2218
+ {
2219
+ tag: "plaintext",
2220
+ attrs: { mediatype: "sticker" },
2221
+ content: proto.Message.encode({ stickerMessage: plainSticker }),
2222
+ },
2223
+ ],
2224
+ }));
2225
+ if (nlAudio && (nlAudio.url || nlAudio.directPath)) {
2226
+ transport.sendEncrypted(encodeWABinaryNode({
2227
+ tag: "message",
2228
+ attrs: { id: generateMessageIDV2(meJid), to: jid, type: "media" },
2229
+ content: [
2230
+ {
2231
+ tag: "plaintext",
2232
+ attrs: { mediatype: nlAudio.ptt ? "ptt" : "audio" },
2233
+ content: proto.Message.encode({ audioMessage: nlAudio }),
2234
+ },
2235
+ ],
2236
+ }));
2237
+ }
2238
+ }
2239
+ else {
2240
+ const nlPlaintext = isNlDelete
2241
+ ? Buffer.alloc(0)
2242
+ : isNlEdit && waMsg.protocolMessage?.editedMessage
2243
+ ? proto.Message.encode(waMsg.protocolMessage.editedMessage)
2244
+ : proto.Message.encode(waMsg);
2245
+ transport.sendEncrypted(encodeWABinaryNode({
2246
+ tag: "message",
2247
+ attrs: {
2248
+ id: nlMsgId,
2249
+ to: jid,
2250
+ type: stanzaType,
2251
+ ...(nlEditAttr ? { edit: nlEditAttr } : {}),
1907
2252
  },
1908
- ],
1909
- }));
2253
+ content: [
2254
+ {
2255
+ tag: "plaintext",
2256
+ attrs: !isNlDelete && encMediatype ? { mediatype: encMediatype } : {},
2257
+ content: nlPlaintext,
2258
+ },
2259
+ ],
2260
+ }));
2261
+ }
1910
2262
  }
1911
2263
  else if (jid.endsWith("@g.us")) {
1912
2264
  const meta = await sock.groupMetadata(jid);
@@ -2102,7 +2454,6 @@ export function makeWASocket(config = {}) {
2102
2454
  return { auth: mc?.attrs?.auth ?? "", hosts };
2103
2455
  },
2104
2456
  async waUploadToServer(stream, opts = {}) {
2105
- const buf = stream instanceof Uint8Array ? stream : await toBuffer(stream);
2106
2457
  const mType = opts.mediaType ?? "document";
2107
2458
  const pathMap = {
2108
2459
  image: "/mms/image",
@@ -2112,15 +2463,26 @@ export function makeWASocket(config = {}) {
2112
2463
  sticker: "/mms/image",
2113
2464
  document: "/mms/document",
2114
2465
  };
2115
- const enc = encryptWaMedia(buf, mType);
2466
+ let encData;
2467
+ let fileEncSha256B64;
2468
+ if (opts.encData && opts.fileEncSha256B64) {
2469
+ encData = opts.encData;
2470
+ fileEncSha256B64 = opts.fileEncSha256B64;
2471
+ }
2472
+ else {
2473
+ const buf = stream instanceof Uint8Array ? stream : await toBuffer(stream);
2474
+ const enc = encryptWaMedia(buf, mType);
2475
+ encData = enc.encData;
2476
+ fileEncSha256B64 = enc.fileEncSha256.toString("base64");
2477
+ }
2116
2478
  const mc = await sock.refreshMediaConn();
2117
2479
  const host = mc.hosts[0]?.hostname ?? "mmg.whatsapp.net";
2118
- const token = Buffer.from(enc.fileEncSha256).toString("base64url");
2480
+ const token = Buffer.from(fileEncSha256B64, "base64").toString("base64url");
2119
2481
  const upUrl = `https://${host}${pathMap[mType] ?? "/mms/document"}/${token}?auth=${encodeURIComponent(mc.auth)}&token=${token}`;
2120
2482
  const res = await fetch(upUrl, {
2121
2483
  method: "POST",
2122
2484
  headers: { "Content-Type": "application/octet-stream", Origin: "https://web.whatsapp.com" },
2123
- body: new Uint8Array(enc.encData),
2485
+ body: new Uint8Array(encData),
2124
2486
  });
2125
2487
  if (!res.ok)
2126
2488
  throw new Error(`Media upload failed (${res.status})`);
@@ -2193,33 +2555,8 @@ export function makeWASocket(config = {}) {
2193
2555
  },
2194
2556
  async groupMetadata(jid) {
2195
2557
  const cached = groupCache.get(jid);
2196
- if (cached && cached.participants.length > 0)
2558
+ if (cached && cached.participants?.length > 0)
2197
2559
  return { id: jid, ...cached };
2198
- const parseGroupNode = (grp) => {
2199
- const subject = grp.attrs?.subject ?? "";
2200
- const addressingMode = grp.attrs?.addressing_mode;
2201
- let ephemeralDuration;
2202
- const participants = [];
2203
- if (Array.isArray(grp.content)) {
2204
- for (const c of grp.content) {
2205
- if (c.tag === "ephemeral" && c.attrs?.expiration) {
2206
- ephemeralDuration = Number(c.attrs.expiration) || undefined;
2207
- }
2208
- if (c.tag === "participant" && c.attrs?.jid) {
2209
- rememberLidPn(c.attrs.jid, c.attrs.phone_number);
2210
- const pnId = c.attrs.phone_number ? jidNormalizedUser(c.attrs.phone_number) : resolvePnJid(c.attrs.jid);
2211
- const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? c.attrs.jid : undefined);
2212
- participants.push({
2213
- id: pnId,
2214
- ...(c.attrs.phone_number ? { phoneNumber: c.attrs.phone_number } : {}),
2215
- ...(lidVal ? { lid: lidVal } : {}),
2216
- admin: c.attrs.type,
2217
- });
2218
- }
2219
- }
2220
- }
2221
- return { subject, addressingMode, ...(ephemeralDuration ? { ephemeralDuration } : {}), participants };
2222
- };
2223
2560
  try {
2224
2561
  const res = await sendQuery({
2225
2562
  tag: "iq",
@@ -2228,11 +2565,11 @@ export function makeWASocket(config = {}) {
2228
2565
  });
2229
2566
  const grp = Array.isArray(res.content) ? res.content.find((c) => c.tag === "group") : undefined;
2230
2567
  if (grp) {
2231
- const parsed = parseGroupNode(grp);
2568
+ const parsed = parseGroupMetadataNode(grp, jid);
2232
2569
  if (parsed.participants.length > 0 || parsed.subject) {
2233
2570
  groupCache.set(jid, parsed);
2234
2571
  }
2235
- return { id: jid, ...parsed };
2572
+ return parsed;
2236
2573
  }
2237
2574
  }
2238
2575
  catch {
@@ -2254,11 +2591,11 @@ export function makeWASocket(config = {}) {
2254
2591
  if (Array.isArray(groupsNode?.content)) {
2255
2592
  for (const g of groupsNode.content) {
2256
2593
  if (g.tag === "group" && (g.attrs?.id === jid || g.attrs?.id === targetId)) {
2257
- const parsed = parseGroupNode(g);
2594
+ const parsed = parseGroupMetadataNode(g, jid);
2258
2595
  if (parsed.participants.length > 0 || parsed.subject) {
2259
2596
  groupCache.set(jid, parsed);
2260
2597
  }
2261
- return { id: jid, ...parsed };
2598
+ return parsed;
2262
2599
  }
2263
2600
  }
2264
2601
  }
@@ -2377,24 +2714,8 @@ export function makeWASocket(config = {}) {
2377
2714
  if (g.tag !== "group" || !g.attrs?.id)
2378
2715
  continue;
2379
2716
  const gid = g.attrs.id.includes("@") ? g.attrs.id : `${g.attrs.id}@g.us`;
2380
- const participants = [];
2381
- if (Array.isArray(g.content)) {
2382
- for (const c of g.content) {
2383
- if (c.tag === "participant" && c.attrs?.jid) {
2384
- rememberLidPn(c.attrs.jid, c.attrs.phone_number);
2385
- const pnId = c.attrs.phone_number ? jidNormalizedUser(c.attrs.phone_number) : resolvePnJid(c.attrs.jid);
2386
- const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? c.attrs.jid : undefined);
2387
- participants.push({
2388
- id: pnId,
2389
- ...(c.attrs.phone_number ? { phoneNumber: c.attrs.phone_number } : {}),
2390
- ...(lidVal ? { lid: lidVal } : {}),
2391
- admin: c.attrs.type,
2392
- });
2393
- }
2394
- }
2395
- }
2396
- const meta = { id: gid, subject: g.attrs.subject ?? "", addressingMode: g.attrs.addressing_mode, participants };
2397
- groupCache.set(gid, { subject: meta.subject, addressingMode: meta.addressingMode, participants });
2717
+ const meta = parseGroupMetadataNode(g, gid);
2718
+ groupCache.set(gid, meta);
2398
2719
  out[gid] = meta;
2399
2720
  }
2400
2721
  }
@@ -2561,6 +2882,7 @@ export function normalizeMessageContent(content) {
2561
2882
  "pollCreationOptionImageMessage",
2562
2883
  "pollCreationMessageV4",
2563
2884
  "botForwardedMessage",
2885
+ "audioStickerMessage",
2564
2886
  ];
2565
2887
  let cur = content;
2566
2888
  for (let depth = 0; depth < 5; depth++) {
@@ -2610,18 +2932,56 @@ export async function downloadMediaMessage(msg, type = "buffer", _options, _ctx)
2610
2932
  const stream = await downloadContentFromMessage(inner[mediaKey], mediaType);
2611
2933
  return type === "stream" ? stream : await toBuffer(stream);
2612
2934
  }
2613
- export async function prepareWAMessageMedia(media, _options) {
2935
+ export async function prepareWAMessageMedia(media, options) {
2936
+ const defaultMime = {
2937
+ image: "image/jpeg",
2938
+ video: "video/mp4",
2939
+ audio: "audio/mpeg",
2940
+ document: "application/octet-stream",
2941
+ sticker: "image/webp",
2942
+ };
2614
2943
  for (const kind of ["image", "video", "audio", "document", "sticker"]) {
2615
- if (media[kind]) {
2616
- const buf = Buffer.isBuffer(media[kind]) ? media[kind] : Buffer.from(media[kind]);
2617
- const enc = encryptWaMedia(buf, kind);
2944
+ const raw = media[kind];
2945
+ if (raw) {
2946
+ let buf;
2947
+ if (Buffer.isBuffer(raw))
2948
+ buf = raw;
2949
+ else if (raw instanceof Uint8Array)
2950
+ buf = Buffer.from(raw);
2951
+ else if (typeof raw === "object" && typeof raw.url === "string") {
2952
+ const res = await fetch(raw.url);
2953
+ buf = Buffer.from(await res.arrayBuffer());
2954
+ }
2955
+ else {
2956
+ buf = Buffer.from(raw);
2957
+ }
2958
+ const encType = kind === "audio" && media.ptt ? "ptt" : kind;
2959
+ const enc = encryptWaMedia(buf, encType);
2960
+ let uploaded;
2961
+ if (typeof options?.upload === "function") {
2962
+ uploaded = await options.upload(Buffer.from(enc.encData), {
2963
+ mediaType: encType,
2964
+ fileEncSha256B64: enc.fileEncSha256.toString("base64"),
2965
+ encData: enc.encData,
2966
+ });
2967
+ }
2618
2968
  return {
2619
2969
  [`${kind}Message`]: {
2970
+ ...(uploaded?.mediaUrl || uploaded?.url ? { url: uploaded.mediaUrl || uploaded.url } : {}),
2971
+ ...(uploaded?.directPath || uploaded?.direct_path
2972
+ ? { directPath: uploaded.directPath || uploaded.direct_path }
2973
+ : {}),
2620
2974
  mediaKey: enc.mediaKey,
2621
2975
  fileSha256: enc.fileSha256,
2622
2976
  fileEncSha256: enc.fileEncSha256,
2623
2977
  fileLength: buf.length,
2624
- mimetype: media.mimetype,
2978
+ mediaKeyTimestamp: Math.floor(Date.now() / 1000),
2979
+ mimetype: media.mimetype ?? (kind === "audio" && media.ptt ? "audio/ogg; codecs=opus" : defaultMime[kind]),
2980
+ ...(typeof media.ptt === "boolean" ? { ptt: media.ptt } : {}),
2981
+ ...(typeof media.seconds === "number" ? { seconds: media.seconds } : {}),
2982
+ ...(typeof media.isAnimated === "boolean" ? { isAnimated: media.isAnimated } : {}),
2983
+ ...(typeof media.caption === "string" ? { caption: media.caption } : {}),
2984
+ ...(typeof media.fileName === "string" ? { fileName: media.fileName } : {}),
2625
2985
  },
2626
2986
  };
2627
2987
  }