8000 chore: identify and permit only direct users jid types by CayoPOliveira · Pull Request #14 · fazer-ai/chatwoot · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

chore: identify and permit only direct users jid types #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the commu 8000 nity.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

CayoPOliveira
Copy link
Collaborator
@CayoPOliveira CayoPOliveira commented Apr 3, 2025

This change is Reviewable

Summary by CodeRabbit

  • New Features

    • Incoming messages are now filtered to display only those from valid user sources, ensuring a more focused conversation experience.
    • Enhanced processing of sender information improves how contact names and phone numbers appear.
  • Tests

    • New test scenarios have been added to confirm that non-user messages are correctly ignored, contributing to increased system reliability.

@CayoPOliveira CayoPOliveira added enhancement New feature or request review needed labels Apr 3, 2025
@CayoPOliveira CayoPOliveira self-assigned this Apr 3, 2025
@Copilot Copilot AI review requested due to automatic review settings April 3, 2025 04:41
Copy link
coderabbitai bot commented Apr 3, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update enhances the WhatsApp message processing service by introducing a new method to determine the type of JID from incoming messages. The service now processes only messages from user-type JIDs by adding an early return condition. It also refines the logic for extracting phone numbers and setting contact names, as well as simplifying the text message identification. Additionally, corresponding tests have been added and improved to cover non-user message scenarios.

Changes

File(s) Change Summary
app/services/whatsapp/incoming_message_baileys_service.rb Added jid_type method to categorize JIDs; modified handle_message to process only user messages; updated set_contact for phone number extraction using underscores; simplified text message check in message_type.
spec/services/whatsapp/incoming_message_baileys_service_spec.rb Introduced a new test context for non-user (broadcast) messages; enhanced tests with new assertions and improved variable usage.

Sequence Diagram(s)

sequenceDiagram
  participant M as Message
  participant S as IncomingMessageService
  participant C as Contact

  M->>S: Receive message with remoteJid
  S->>S: Evaluate jid_type(remoteJid)
  alt JID type is not 'user'
      S-->>M: Early return (skip processing)
  else JID type is 'user'
      S->>S: Extract & set contact using jid and updated logic
      S->>S: Process text message (simplified check)
  end
Loading

Possibly related PRs

Suggested labels

approved for merge

Suggested reviewers

  • gabrieljablonski

Poem

I’m a little rabbit, quick on my feet,
Hopping through code changes, oh so neat.
Messages now flow with a clearer tune,
User-checks and tests beneath the moon.
Hoppy coding vibes, let innovation bloom! 🐰✨


🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refines incoming message handling by allowing only direct user jid types while improving test coverage and contact name management.

  • Adds new tests to verify that non-user messages are ignored.
  • Updates jid parsing logic to correctly extract phone numbers and updates contacts when an incoming message has a new pushName.
  • Introduces a jid_type method to classify message sources.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
spec/services/whatsapp/incoming_message_baileys_service_spec.rb Adds tests for non-user jid types and validates contact name updates.
app/services/whatsapp/incoming_message_baileys_service.rb Restricts message processing to direct users, refines jid parsing, and updates contact names if needed.

@CayoPOliveira CayoPOliveira changed the base branch from fazer-ai/main to fix/contact-without-push-name April 3, 2025 12:19
Copy link
@gabrieljablonski gabrieljablonski left a comment

Choose a reason for hiding this comment

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

-(review needed) +(questions/changes requested)

Reviewed 2 of 2 files at r1, all commit messages.
Dismissed @copilot-pull-request-reviewer[bot] from a discussion.
Reviewable status: all files reviewed, 8 unresolved discussions (waiting on @broadcast and @CayoPOliveira)


spec/services/whatsapp/incoming_message_baileys_service_spec.rb line 195 at r2 (raw file):

        end

        it 'does not create a conversation or message' do

NIT

Suggestion:

        it 'does not create a conversation' do

spec/services/whatsapp/incoming_message_baileys_service_spec.rb line 197 at r2 (raw file):

        it 'does not create a conversation or message' do
          described_class.new(inbox: inbox, params: params).perform
          expect(inbox.conversations).to be_empty

NIT

Suggestion:

          described_class.new(inbox: inbox, params: params).perform

          expect(inbox.conversations).to be_empty

app/services/whatsapp/incoming_message_baileys_service.rb line 66 at r2 (raw file):

  def set_contact
    # NOTE: jid shape is `<user (like phone-number)>_<agent_id>:<device_id>@<server (like s.whatsapp.net)>`

NIT

Can be simplified.

Suggestion:

    # NOTE: jid shape is `<user>_<agent>:<device>@<server>`

app/services/whatsapp/incoming_message_baileys_service.rb line 67 at r2 (raw file):

  def set_contact
    # NOTE: jid shape is `<user (like phone-number)>_<agent_id>:<device_id>@<server (like s.whatsapp.net)>`
    # https://github.com/WhiskeySockets/Baileys/blob/d5dc75887493f25877028d43b81101e050a3695b/src/WABinary/jid-utils.ts#L21

NIT

Prefer using tagged branches when available vs specific commits (but never main/master since those change over time!)

v6.7.16 is the version we're currently using.

Suggestion:

    # https://github.com/WhiskeySockets/Baileys/blob/v6.7.16/src/WABinary/jid-utils.ts#L19

app/services/whatsapp/incoming_message_baileys_service.rb line 101 at r2 (raw file):

    return 'lid' if jid.include? '@lid'
    return 'broadcast' if jid.include? '@broadcast'
    return 'status' if jid.include? 'status@broadcast'

Have you found any other situations in which @broadcast is used other than for status@broadcast?


app/services/whatsapp/incoming_message_baileys_service.rb line 106 at r2 (raw file):

    'unknown'
  end

Avoid using "broad matches" (using include?) for stuff like this, better to be highly specific.

Suggestion:

  def jid_type # rubocop:disable Metrics/CyclomaticComplexity
    jid = @raw_message[:key][:remoteJid]
    server = jid.split('@').last

    case server
    when 's.whatsapp.net', 'c.us'
      'user'
    when 'g.us'
      'group'
    when 'lid'
      'lid'
    when 'broadcast'
      jid.start_with?('status@') ? 'status' : 'broadcast'
    when 'newsletter'
      'newsletter'
    when 'call'
      'call'
    else
      'unknown'
    end
  end

app/services/whatsapp/incoming_message_baileys_service.rb line 111 at r2 (raw file):

    msg = @raw_message[:message]

    return 'text' if msg.key?(:conversation) || msg.key?(:extendedTextMessage)

Are you sure this change is correct?

@CayoPOliveira CayoPOliveira force-pushed the chore/identify-and-ignore-status-updates branch from 70a7c97 to de63144 Compare April 3, 2025 21:55
Copy link
Collaborator Author
@CayoPOliveira CayoPOliveira left a comment

Choose a reason for hiding this comment

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

-(questions/changes requested) +(review needed)

Reviewable status: 0 of 2 files reviewed, 3 unresolved discussions (waiting on @gabrieljablonski)


app/services/whatsapp/incoming_message_baileys_service.rb line 101 at r2 (raw file):

Previously, gabrieljablonski (Gabriel Jablonski) wrote…

Have you found any other situations in which @broadcast is used other than for status@broadcast?

Not yet. I based myself on WhiskeySockets Baileys, which has the isJidBroadcast and isJidStatusBroadcast functions as separate ones, maybe there a reason for this.


app/services/whatsapp/incoming_message_baileys_service.rb line 106 at r2 (raw file):

Previously, gabrieljablonski (Gabriel Jablonski) wrote…

Avoid using "broad matches" (using include?) for stuff like this, better to be highly specific.

Done.


app/services/whatsapp/incoming_message_baileys_service.rb line 111 at r2 (raw file):

Previously, gabrieljablonski (Gabriel Jablonski) wrote…

Are you sure this change is correct?

My intention was to standardize the conditions with boolean values, I believe that this way works too, but I found a different previous solution

Copy link
Collaborator Author
@CayoPOliveira CayoPOliveira left a comment

Choose a reason for hiding this comment

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

Reviewed 2 of 2 files at r1.
Reviewable status: 0 of 2 files reviewed, 3 unresolved discussions (waiting on @gabrieljablonski)

Copy link
@gabrieljablonski gabrieljablonski left a comment

Choose a reason for hiding this comment

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

LGTM. Please check pending comments, no need to re-review.

-(review needed) +(approved for merge) +(questions/changes requested)

Reviewed 2 of 2 files at r3, all commit messages.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on @CayoPOliveira)


app/services/whatsapp/incoming_message_baileys_service.rb line 101 at r2 (raw file):

Previously, CayoPOliveira (Cayo P. R. Oliveira) wrote…

Not yet. I based myself on WhiskeySockets Baileys, which has the isJidBroadcast and isJidStatusBroadcast functions as separate ones, maybe there a reason for this.

Cool. Please add comment referencing that.


app/services/whatsapp/incoming_message_baileys_service.rb line 82 at r3 (raw file):

    @contact = contact_inbox.contact

    @contact.update(name: push_name) if @contact[:name] == phone_number_formatted && !@raw_message[:key][:fromMe]

NIT

Reminder to always favor update! over update, and object.field over object[:field] (when working with ActiveRecords)

Suggestion:

    @contact.update!(name: push_name) if @contact.name == phone_number_formatted && !@raw_message[:key][:fromMe]

Copy link
@gabrieljablonski gabrieljablonski left a comment

Choose a reason for hiding this comment

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

Reviewable status: all files reviewed, 2 unresolved discussions (waiting on @CayoPOliveira)


app/services/whatsapp/incoming_message_baileys_service.rb line 82 at r3 (raw file):

Previously, gabrieljablonski (Gabriel Jablonski) wrote…

NIT

Reminder to always favor update! over update, and object.field over object[:field] (when working with ActiveRecords)

About update! vs update, I'll add a Rubocop rule to warn about it. Still change it here though.

Copy link
Collaborator Author
@CayoPOliveira CayoPOliveira left a comment

Choose a reason for hiding this comment

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

-(questions/changes requested)

Reviewed all commit messages.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on @CayoPOliveira)

Copy link
Collaborator Author
@CayoPOliveira CayoPOliveira left a comment

Choose a reason for hiding this comment

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

Reviewed 1 of 2 files at r3.
Reviewable status: 1 of 2 files reviewed, all discussions resolved (waiting on @gabrieljablonski)

Copy link
@gabrieljablonski gabrieljablonski left a comment

Choose a reason for hiding this comment

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

Reviewed 1 of 1 files at r4, all commit messages.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on @CayoPOliveira)


app/services/whatsapp/incoming_message_baileys_service.rb line 116 at r4 (raw file):

      'unknown'
    end
  end

Suggestion:

    server = jid.split('@').last

    # NOTE: Based on Baileys internal functions
    # https://github.com/WhiskeySockets/Baileys/blob/v6.7.16/src/WABinary/jid-utils.ts#L48-L58
    case server
    when 's.whatsapp.net', 'c.us'
      'user'
    when 'g.us'
      'group'
    when 'lid'
      'lid'
    when 'broadcast'
      jid.start_with?('status@') ? 'status' : 'broadcast'
    when 'newsletter'
      'newsletter'
    when 'call'
      'call'
    else
      'unknown'
    end
  end

Copy link
Collaborator Author
@CayoPOliveira CayoPOliveira left a comment

Choose a reason for hiding this comment

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

Reviewed 1 of 1 files at r5, all commit messages.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on @CayoPOliveira)

@CayoPOliveira CayoPOliveira merged commit d101fe1 into fix/contact-without-push-name Apr 4, 2025
2 of 3 checks passed
@CayoPOliveira CayoPOliveira deleted the chore/identify-and-ignore-status-updates branch April 4, 2025 02:01
CayoPOliveira added a commit that referenced this pull request Apr 4, 2025
* fix: resolve bug for contact name when user stats a new conversation with a new contact

* chore: update specs to cover the bug resolution

* chore: correct variable name

* chore: simplify update contact name handling

* chore: ensure pushName is always a string and leave a comment to keep an eye if always pushName will be present

* fix: update contact name access

* chore: identify and permit only direct users jid types (#14)

* fix: add jid_type method to classify message sender types and prevent processing for non-user jids

* chore: update jid parsing to correctly extract phone number and improve message type detection

* chore: add spec to ensure no conversation is created for non-user messages

* chore: update jid shape comment

* chore: refactor jid_type method

* chore: update message_type logic for classify text messages when is a extendedTextMessage

* refactor: update spec that no conversation is created for non-user messages

* fix: use update! method for contact name update

* chore: add note on distinguishing broadcast and status JIDs in Baileys

* chore: add note on Baileys internal function for JID classification
gabrieljablonski pushed a commit that referenced this pull request Apr 4, 2025
* fix: resolve bug for contact name when user stats a new conversation with a new contact

* chore: update specs to cover the bug resolution

* chore: correct variable name

* chore: simplify update contact name handling

* chore: ensure pushName is always a string and leave a comment to keep an eye if always pushName will be present

* fix: update contact name access

* chore: identify and permit only direct users jid types (#14)

* fix: add jid_type method to classify message sender types and prevent processing for non-user jids

* chore: update jid parsing to correctly extract phone number and improve message type detection

* chore: add spec to ensure no conversation is created for non-user messages

* chore: update jid shape comment

* chore: refactor jid_type method

* chore: update message_type logic for classify text messages when is a extendedTextMessage

* refactor: update spec that no conversation is created for non-user messages

* fix: use update! method for contact name update

* chore: add note on distinguishing broadcast and status JIDs in Baileys

* chore: add note on Baileys internal function for JID classification
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
approved for merge enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0