Skip to content

fix(newsletter): parse metadata and fetch-messages responses#2620

Open
vinikjkkj wants to merge 1 commit into
masterfrom
fix/newsletter-metadata-and-fetch
Open

fix(newsletter): parse metadata and fetch-messages responses#2620
vinikjkkj wants to merge 1 commit into
masterfrom
fix/newsletter-metadata-and-fetch

Conversation

@vinikjkkj

@vinikjkkj vinikjkkj commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

newsletterMetadata: transform the raw server response into the flat NewsletterMetadata shape instead of casting it, and fall back to image/preview when picture is absent (preview-only responses for non-followers). Fixes #2204.

newsletterFetchMessages: send the WA-Web-shaped query (<iq to='s.whatsapp.net' xmlns='newsletter'><messages type='jid' jid count/></iq>) instead of <message_updates> addressed to the channel jid, which timed out, then parse the <messages> response into messages carrying reactions, pollVotes, views/forwards/responses counts, edit timestamps, media rcat, and the decoded plaintext proto.Message. Fixes #2555.

Mex.ts: remove the duplicated NewsletterCreateResponse interface.

All changes were validated end-to-end against live WhatsApp. newsletterMetadata and newsletterFetchMessages were verified on a real public channel: metadata returns the flat shape with the channel picture (resolved from preview), and fetch returns real messages with decoded proto.Message content, reactions, and forwards counts (both previously timed out or returned null).

Summary by CodeRabbit

  • Refactor
    • Improved newsletter metadata parsing with stronger validation and safer fallbacks for optional fields.
  • Bug Fixes
    • Message fetching and decoding now reliably return parsed messages, including reactions, poll counts, media categories, and edit/original timestamps.
  • Chores
    • Newsletter create response no longer includes the viewer role field in viewer metadata.

@whiskeysockets-bot

whiskeysockets-bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Thanks for opening this pull request and contributing to the project!

The next step is for the maintainers to review your changes. If everything looks good, it will be approved and merged into the main branch.

In the meantime, anyone in the community is encouraged to test this pull request and provide feedback.

✅ How to confirm it works

If you’ve tested this PR, please comment below with:

Tested and working ✅

This helps us speed up the review and merge process.

📦 To test this PR locally:

# NPM
npm install @whiskeysockets/baileys@WhiskeySockets/Baileys#fix/newsletter-metadata-and-fetch

# Yarn (v2+)
yarn add @whiskeysockets/baileys@WhiskeySockets/Baileys#fix/newsletter-metadata-and-fetch

# PNPM
pnpm add @whiskeysockets/baileys@WhiskeySockets/Baileys#fix/newsletter-metadata-and-fetch

If you encounter any issues or have feedback, feel free to comment as well.

@coderabbitai

coderabbitai Bot commented Jun 5, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ff334a59-77a8-464e-b56e-c701a0747061

📥 Commits

Reviewing files that changed from the base of the PR and between cc4c345 and 5f1f118.

📒 Files selected for processing (2)
  • src/Socket/newsletter.ts
  • src/Types/Mex.ts
💤 Files with no reviewable changes (1)
  • src/Types/Mex.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Socket/newsletter.ts

📝 Walkthrough

Walkthrough

Newsletter parsing now decodes protobuf message payloads and robustly parses binary-node fields; newsletterFetchMessages issues a messages IQ (type: 'jid') to S_WHATSAPP_NET and returns parsed message nodes. The NewsletterCreateResponse.viewer_metadata type no longer includes role.

Changes

Newsletter Socket Message and Metadata Parsing

Layer / File(s) Summary
Imports and metadata parsing
src/Socket/newsletter.ts
Imports add BinaryNode, binary helpers, S_WHATSAPP_NET, and proto. parseNewsletterMetadata normalizes the raw query result into a single node, validates node.id, and extracts optional fields (name, description, creation/update times, subscriber count, picture, verification, mute state) with safe fallback handling.
Message parsing and fetch endpoint
src/Socket/newsletter.ts
parseFetchedNewsletterMessage decodes plaintext messages via proto.Message.decode, extracts reaction and poll vote counts from binary-node children with integer conversion and zero defaults, and conditionally parses media rcat and edit/original timestamps. newsletterFetchMessages requests messages (with type: 'jid' and pagination before/after) under the newsletter IQ namespace to S_WHATSAPP_NET, returning parsed message nodes.

Newsletter Response Type Update

Layer / File(s) Summary
Response contract change
src/Types/Mex.ts
NewsletterCreateResponse.viewer_metadata removes the role: NewsletterViewRole field from the interface.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

testing needed

Suggested reviewers

  • purpshell

Poem

🐰 I hopped through nodes both old and new,
Decoded bytes where plaintext grew,
Switched the fetch to messages fair,
Trimmed a role with tidy care,
Parsers sing — a rabbit's cue!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the primary changes: updating newsletter metadata and fetch-messages response parsing logic.
Linked Issues check ✅ Passed The PR directly addresses both linked issues #2204 and #2555 by updating metadata parsing with proper structure/types and fixing fetch-messages with correct IQ query and response parsing.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: newsletter metadata/fetch-messages parsing in src/Socket/newsletter.ts and removing duplicated type in src/Types/Mex.ts.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@vinikjkkj vinikjkkj force-pushed the fix/newsletter-metadata-and-fetch branch from 34d3250 to cc4c345 Compare June 5, 2026 03:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Socket/newsletter.ts (1)

1-8: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix import sorting and use type-only import for BinaryNode.

The pipeline flagged an import sorting violation. Additionally, BinaryNode is only used as a type annotation (line 58), so it should use import type to satisfy the verbatimModuleSyntax strict mode requirement.

📦 Proposed fix
-import type { NewsletterCreateResponse, SocketConfig, WAMediaUpload } from '../Types'
-import type { NewsletterMetadata, NewsletterUpdate } from '../Types'
+import type { NewsletterCreateResponse, NewsletterMetadata, NewsletterUpdate, SocketConfig, WAMediaUpload } from '../Types'
 import { QueryIds, XWAPaths } from '../Types'
 import { generateProfilePicture } from '../Utils/messages-media'
-import { type BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET } from '../WABinary'
+import type { BinaryNode } from '../WABinary'
+import { getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET } from '../WABinary'
+import { proto } from '../../WAProto/index.js'
 import { makeGroupsSocket } from './groups'
 import { executeWMexQuery as genericExecuteWMexQuery } from './mex'
-import { proto } from '../../WAProto/index.js'

As per coding guidelines, type-only imports must use import type or inline type prefix for verbatimModuleSyntax strict mode.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Socket/newsletter.ts` around lines 1 - 8, Update the import block to
satisfy import-sorting and verbatimModuleSyntax: make BinaryNode a type-only
import by changing its import to "import type { BinaryNode } from '../WABinary'"
(leave getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET as value
imports), and reorder the import statements so type-only imports (e.g.,
NewsletterCreateResponse, SocketConfig, WAMediaUpload, NewsletterMetadata,
NewsletterUpdate, QueryIds, XWAPaths, BinaryNode) are grouped/placed
appropriately before/after value imports according to the repo's sorting rule so
ESLint import-sorting no longer flags the file; ensure unique symbols
referenced: BinaryNode, getBinaryNodeChild, getBinaryNodeChildren,
S_WHATSAPP_NET, generateProfilePicture, makeGroupsSocket,
genericExecuteWMexQuery, proto.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Socket/newsletter.ts`:
- Line 34: Replace the unsafe cast to any by casting result to Record<string,
unknown> for better type safety: change the declaration of raw (the variable
assigned from result in newsletter.ts) from using Record<string, any> to
Record<string, unknown>, and ensure subsequent property accesses on raw continue
to use optional chaining/nullish coalescing as already implemented.
- Line 97: parseFetchedNewsletterMessage currently calls
proto.Message.decode(plaintextContent) directly which can throw on malformed
protobufs and abort newsletterFetchMessages; wrap the decode call in a try/catch
inside parseFetchedNewsletterMessage (or the object construction that sets the
message field) and on error set message: undefined (or return a structured error
object) so a single bad payload won’t break the whole fetch; specifically catch
around proto.Message.decode(plaintextContent) and handle the failure path
consistently with other decode sites in this file.

---

Outside diff comments:
In `@src/Socket/newsletter.ts`:
- Around line 1-8: Update the import block to satisfy import-sorting and
verbatimModuleSyntax: make BinaryNode a type-only import by changing its import
to "import type { BinaryNode } from '../WABinary'" (leave getBinaryNodeChild,
getBinaryNodeChildren, S_WHATSAPP_NET as value imports), and reorder the import
statements so type-only imports (e.g., NewsletterCreateResponse, SocketConfig,
WAMediaUpload, NewsletterMetadata, NewsletterUpdate, QueryIds, XWAPaths,
BinaryNode) are grouped/placed appropriately before/after value imports
according to the repo's sorting rule so ESLint import-sorting no longer flags
the file; ensure unique symbols referenced: BinaryNode, getBinaryNodeChild,
getBinaryNodeChildren, S_WHATSAPP_NET, generateProfilePicture, makeGroupsSocket,
genericExecuteWMexQuery, proto.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 756cce53-e343-4683-8e6c-05ad850dd43b

📥 Commits

Reviewing files that changed from the base of the PR and between 78e7e4e and 34d3250.

📒 Files selected for processing (2)
  • src/Socket/newsletter.ts
  • src/Types/Mex.ts
💤 Files with no reviewable changes (1)
  • src/Types/Mex.ts

Comment thread src/Socket/newsletter.ts Outdated
Comment thread src/Socket/newsletter.ts Outdated

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread src/Socket/newsletter.ts Outdated
`newsletterMetadata`: transform the raw server response into the flat `NewsletterMetadata` shape instead of casting it, and fall back to `image`/`preview` when `picture` is absent (preview-only responses for non-followers). Fixes #2204.

`newsletterFetchMessages`: send the WA-Web-shaped query (`<iq to='s.whatsapp.net' xmlns='newsletter'><messages type='jid' jid count/></iq>`) instead of `<message_updates>` addressed to the channel jid, which timed out, then parse the `<messages>` response into messages carrying `reactions`, `pollVotes`, views/forwards/responses counts, edit timestamps, media `rcat`, and the decoded plaintext `proto.Message`. Fixes #2555.

`Mex.ts`: remove the duplicated `NewsletterCreateResponse` interface.

All changes were validated end-to-end against live WhatsApp. `newsletterMetadata` and `newsletterFetchMessages` were verified on a real public channel (~109k subscribers): metadata returns the flat shape with the channel picture (resolved from `preview`), and fetch returns real messages with decoded `proto.Message` content, `reactions`, and `forwards` counts (both previously timed out or returned `null`).
@vinikjkkj vinikjkkj force-pushed the fix/newsletter-metadata-and-fetch branch from cc4c345 to 5f1f118 Compare June 5, 2026 04:30

@jlucaso1 jlucaso1 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice work

rsalcara added a commit to rsalcara/InfiniteAPI that referenced this pull request Jun 6, 2026
…Sockets#2620 port) (#503)

fix(newsletter): parse metadata and fetch-messages responses (WhiskeySockets#2620 port) (#503)
rsalcara added a commit to rsalcara/InfiniteAPI that referenced this pull request Jun 6, 2026
…a picture fallback

PR #508 review caught an ambiguity in the picture-fallback chain inherited
from upstream PR WhiskeySockets#2620 (#503 port). The original chain only looked inside
`thread_metadata`:

    const pic = thread.picture ?? thread.image ?? thread.preview

but the in-code comment noted that for preview-only responses (non-followed
channel via invite) the server returns `image` / `preview` SIBLINGS of
`thread_metadata` rather than children of it. The chain was missing the
sibling case, so the picture came back undefined for that flow.

Extend the fallback to also try `node.image` and `node.preview`. Additive and
defensive — `undefined ?? undefined` short-circuits cleanly when the server
returns the followed-channel shape (which has worked since #503 merged).

Also refine the comment so the chain is unambiguous on the next read.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
rsalcara added a commit to rsalcara/InfiniteAPI that referenced this pull request Jun 6, 2026
…a picture fallback

PR #508 review caught an ambiguity in the picture-fallback chain inherited
from upstream PR WhiskeySockets#2620 (#503 port). The original chain only looked inside
`thread_metadata`:

    const pic = thread.picture ?? thread.image ?? thread.preview

but the in-code comment noted that for preview-only responses (non-followed
channel via invite) the server returns `image` / `preview` SIBLINGS of
`thread_metadata` rather than children of it. The chain was missing the
sibling case, so the picture came back undefined for that flow.

Extend the fallback to also try `node.image` and `node.preview`. Additive and
defensive — `undefined ?? undefined` short-circuits cleanly when the server
returns the followed-channel shape (which has worked since #503 merged).

Also refine the comment so the chain is unambiguous on the next read.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Backlog

3 participants