Skip to content

Conversation

@clairton
Copy link
Owner

@clairton clairton commented Feb 13, 2025

Summary by CodeRabbit

  • Documentation

    • Updated media sending instructions to indicate a required authorization header and updated resource link.
  • New Features

    • Enhanced media transmission to ensure secure message delivery.
    • Expanded contact management capabilities for more reliable sender details and improved message history.
    • Refined message processing with better validation and error feedback for a smoother messaging experience.

@coderabbitai
Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

The changes update the documentation and core messaging services. The README now specifies that media messages require an authorization header and references an updated image link. In the code, the messaging history event now accepts and processes a contacts array, and the message metadata extraction fetches additional contact details. Multiple data store modules have been enhanced to support contact management through new setContact and getContact methods. A minor check in the message listener now explicitly ensures the existence of a message key ID, and the transformer improves sender name derivation and error handling.

Changes

File(s) Summary
README.md Updated media sending docs to add the authorization header requirement and changed the image link from favicon-dark.png to favicon.png.
src/services/data_store.ts, src/services/data_store_file.ts, src/services/data_store_redis.ts, src/services/redis.ts Added contact management methods (setContact, getContact), updated imports to include Contact, and modified event listeners in the file store to persist contact data.
src/services/client_baileys.ts Enhanced the messaging history event by introducing a contacts parameter and updating getMessageMetadata to retrieve contact details for user messages.
src/services/listener_baileys.ts Improved the sendOne method by refining the message key check to confirm the existence of key.id before proceeding.
src/services/transformer.ts Modified fromBaileysMessageContent to derive profileName from contact fields and enhanced error handling for message stub type errors.

Sequence Diagram(s)

sequenceDiagram
    participant MHE as Messaging History Event
    participant Client as ClientBaileys
    participant DS as DataStore/Redis
    participant Trans as Transformer
    participant Listener as ListenerBaileys

    MHE->>Client: Trigger messaging-history.set (messages, contacts)
    Client->>DS: Process contacts using setContact
    DS-->>Client: Acknowledge contact storage
    Client->>Client: Update message metadata via getContact
    Listener->>Client: Invoke sendOne with validated key.id
    Trans->>DS: Retrieve contact details for sender info
    DS-->>Trans: Return contact information
Loading

Poem

I'm a little rabbit, hopping through the code,
Discovering new contacts on every winding road.
Messages scurry in with a header so neat,
And each data store now makes the flow complete.
Bugs vanish like shadows beneath my eager feet.
🐰✨

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.

src/services/data_store.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

TypeError: prettier.resolveConfig.sync is not a function
Occurred while linting /src/services/data_store.ts:1
Rule: "prettier/prettier"
at Program (/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js:138:40)
at ruleErrorHandler (/node_modules/eslint/lib/linter/linter.js:1076:28)
at /node_modules/eslint/lib/linter/safe-emitter.js:45:58
at Array.forEach ()
at Object.emit (/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (/node_modules/eslint/lib/linter/node-event-generator.js:340:14)
at CodePathAnalyzer.enterNode (/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:803:23)
at /node_modules/eslint/lib/linter/linter.js:1111:32

src/services/listener_baileys.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

TypeError: prettier.resolveConfig.sync is not a function
Occurred while linting /src/services/listener_baileys.ts:1
Rule: "prettier/prettier"
at Program (/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js:138:40)
at ruleErrorHandler (/node_modules/eslint/lib/linter/linter.js:1076:28)
at /node_modules/eslint/lib/linter/safe-emitter.js:45:58
at Array.forEach ()
at Object.emit (/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (/node_modules/eslint/lib/linter/node-event-generator.js:340:14)
at CodePathAnalyzer.enterNode (/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:803:23)
at /node_modules/eslint/lib/linter/linter.js:1111:32

src/services/data_store_file.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

TypeError: prettier.resolveConfig.sync is not a function
Occurred while linting /src/services/data_store_file.ts:1
Rule: "prettier/prettier"
at Program (/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js:138:40)
at ruleErrorHandler (/node_modules/eslint/lib/linter/linter.js:1076:28)
at /node_modules/eslint/lib/linter/safe-emitter.js:45:58
at Array.forEach ()
at Object.emit (/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (/node_modules/eslint/lib/linter/node-event-generator.js:340:14)
at CodePathAnalyzer.enterNode (/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:803:23)
at /node_modules/eslint/lib/linter/linter.js:1111:32

  • 4 others
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
src/services/listener_baileys.ts (1)

92-94: Use optional chaining for safer key access.

The condition can be simplified using optional chaining, which is safer and more concise.

Apply this diff:

-if (i.key && i.key.id) {
+if (i.key?.id) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 92-92: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

src/services/data_store_redis.ts (1)

71-85: Add error handling for contact operations.

The contact management methods should handle potential errors when converting IDs or accessing undefined properties.

Apply this diff:

 store.setContact = async (contact: Partial<Contact>) => {
+  if (!contact.id && !contact.lid) {
+    throw new Error('Contact ID or LID is required')
+  }
   const id =  jidToPhoneNumber(contact.id || contact.lid)
   const newData: Partial<Contact> = {}
   if (contact.name) {
     newData.name = contact.name
   }
   if (contact.verifiedName) {
     newData.verifiedName = contact.verifiedName
   }
   return setContact(phone, id, newData)
 }
 store.getContact = async (id: string) => {
+  if (!id) {
+    throw new Error('Contact ID is required')
+  }
   const newId =  jidToPhoneNumber(id)
   return getContact(phone, newId)
 }
src/services/data_store_file.ts (2)

111-118: Add type safety to contacts event handler.

The event handler could benefit from explicit type annotations and error handling.

Apply this diff:

-ev.on('contacts.upsert', async (contacts: Contact[]) => {
+ev.on('contacts.upsert', async (contacts: readonly Contact[]) => {
   logger.debug('contacts.upsert %s', phone, JSON.stringify(contacts))
   const { saveProfilePicture } = mediaStore
-  await Promise.all(contacts.map(async (c) => {
+  await Promise.all(contacts.map(async (c: Contact) => {
+    try {
       await dataStore.setContact(c)
       return saveProfilePicture(c)
+    } catch (error) {
+      logger.error('Failed to process contact:', error)
+    }
     })
   )
 })

129-143: Improve type safety in contact management methods.

The contact management methods could benefit from stronger type checking and error handling.

Apply this diff:

 dataStore.setContact = async (contact: Partial<Contact>) => {
+  if (!contact.id && !contact.lid) {
+    throw new Error('Contact ID or LID is required')
+  }
   const id =  jidToPhoneNumber(contact.id || contact.lid)
   const newData: Partial<Contact> = {}
   if (contact.name) {
     newData.name = contact.name
   }
   if (contact.verifiedName) {
     newData.verifiedName = contact.verifiedName
   }
+  if (!dataStore.contacts) {
+    dataStore.contacts = {}
+  }
   dataStore.contacts[id]  = { ...(dataStore.contacts[id] || {}), ...newData }
 }
 dataStore.getContact = async (id: string) => {
+  if (!id) {
+    throw new Error('Contact ID is required')
+  }
   const newId =  jidToPhoneNumber(id)
+  if (!dataStore.contacts) {
+    return undefined
+  }
   return dataStore.contacts[newId]
 }
src/services/redis.ts (1)

235-239: Consider adding TTL for contact data.

The setContact function correctly merges existing and new contact data. However, consider adding a TTL to prevent stale contact data from persisting indefinitely.

Apply this diff to add TTL:

-  await client.set(key, JSON.stringify({ ...currentContact, ...(contact || {} )}))
+  await client.set(key, JSON.stringify({ ...currentContact, ...(contact || {} )}), { EX: DATA_TTL })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e60d2c2 and e786bd3.

📒 Files selected for processing (8)
  • README.md (1 hunks)
  • src/services/client_baileys.ts (3 hunks)
  • src/services/data_store.ts (2 hunks)
  • src/services/data_store_file.ts (1 hunks)
  • src/services/data_store_redis.ts (3 hunks)
  • src/services/listener_baileys.ts (1 hunks)
  • src/services/redis.ts (3 hunks)
  • src/services/transformer.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/services/listener_baileys.ts

[error] 92-92: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (7)
src/services/data_store.ts (1)

1-1: LGTM! Contact management methods added.

The addition of setContact and getContact methods to the DataStore type enhances contact management capabilities.

Also applies to: 32-33

src/services/redis.ts (2)

142-144: LGTM! Key generation follows the established pattern.

The contactKey function follows the same pattern as other key generation functions in the file, maintaining consistency.


229-233: LGTM! Contact retrieval with proper type safety.

The getContact function correctly handles type safety with the Contact type and properly handles undefined cases.

src/services/client_baileys.ts (2)

308-324: LGTM! Enhanced messaging history with contact processing.

The messaging history event handler now correctly processes contacts array and stores contact information. The implementation properly handles:

  • Contact ID extraction with fallback
  • Image URL storage
  • Contact data storage

641-652: LGTM! Improved message metadata with contact information.

The message metadata enhancement correctly adds contact name and business name information for outgoing messages.

src/services/transformer.ts (1)

467-467: LGTM! Improved sender name resolution.

The sender name resolution now correctly prioritizes business name and contact name over the phone number, providing more meaningful identification.

README.md (1)

156-162: LGTM! Documentation improvements for media messages.

The changes correctly:

  • Add the required authorization header for media messages
  • Update the example image link to a valid resource

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants