8000 fix: try to disconnect baileys before destroy inbox by CayoPOliveira · Pull Request #29 · fazer-ai/chatwoot · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix: try to disconnect baileys before destroy inbox #29

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 community.

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 24, 2025

Pull Request Template

Description

Please include a summary of the change and issue(s) fixed. Also, mention relevant motivation, context, and any dependencies that this change requires.
Fixes # (issue)

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality not to work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration.

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented on my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

This change is Reviewable

Summary by CodeRabbit

  • Bug Fixes

    • Improved channel cleanup to ensure proper disconnection for WhatsApp channels using the Baileys provider upon deletion.
  • Tests

    • Added tests to verify disconnection behavior for WhatsApp channels with the Baileys provider and ensured deletion proceeds smoothly even if disconnection fails.

@CayoPOliveira CayoPOliveira added enhancement New feature or request review needed labels Apr 24, 2025
@CayoPOliveira CayoPOliveira requested a review from Copilot April 24, 2025 20:40
@CayoPOliveira CayoPOliveira self-assigned this Apr 24, 2025
Copy link
coderabbitai bot commented Apr 24, 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

A before_destroy callback was added to the Channel::Whatsapp model that triggers disconnect_channel_provider only if the channel's provider is 'baileys'. This introduces conditional cleanup logic specifically for Baileys provider channels before destruction. Corresponding tests were added to verify that the callback behaves correctly for both Baileys and other providers, and that the channel is destroyed properly even if the disconnect request fails.

Changes

File(s) Change Summary
app/models/channel/whatsapp.rb Added a before_destroy callback that conditionally calls disconnect_channel_provider if provider is 'baileys'.
spec/models/channel/whatsapp_spec.rb Added tests for the conditional callback behavior on destruction, including success and failure of disconnect requests.

Suggested labels

approved for merge

Poem

In the warren where channels hop and play,
Baileys now gets a special say—
Before it’s gone, a call is made,
To disconnect, as rules are laid.
Tests ensure the cleanup’s neat,
Even if the server skips a beat!
🐇✨


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
🪧 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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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
@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 introduces a disconnection callback to ensure that a channel provider using the "baileys" integration is disconnected before the channel is destroyed. The key changes include:

  • Adding a before_destroy callback in the Whatsapp channel model for baileys providers.
  • Defining a helper method (baileys_provider?) to conditionally trigger the callback.
  • Adding tests to verify callback behavior for both baileys and non-baileys providers.

Reviewed Changes

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

File Description
spec/models/channel/whatsapp_spec.rb Adds tests for the disconnect callback based on provider type.
app/models/channel/whatsapp.rb Introduces a before_destroy callback and a helper method for baeleys providers.
Comments suppressed due to low confidence (1)

spec/models/channel/whatsapp_spec.rb:72

  • [nitpick] Consider renaming the locally defined 'channel' variable to avoid shadowing the let(:channel) declaration for improved clarity.
channel = create(:channel_whatsapp, provider: 'whatsapp_cloud', validate_provider_config: false, sync_templates: false)

Copy link
Member
@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.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on @CayoPOliveira)


app/models/channel/whatsapp.rb line 40 at r1 (raw file):

  after_create :sync_templates

  before_destroy :disconnect_channel_provider, if: :baileys_provider?

Helper method is not needed here, due to low complexity for condition.

Suggestion:

  before_destroy :disconnect_channel_provider, if: -> { provider == 'baileys' }

spec/models/channel/whatsapp_spec.rb line 93 at r1 (raw file):

      end
    end
  end

Carefully note on all suggested changes.

For some context:

  1. ActiveRecord objects have a .destroyed? method
  2. expect(object).to be_something is shorthand for expect(object.something?).to be(true)

Suggestion:

  describe 'callbacks' do
    describe '#disconnect_channel_provider' do
      context 'when provider is baileys' do
        let(:channel) { create(:channel_whatsapp, provider: 'baileys', validate_provider_config: false, sync_templates: false) }
        let(:disconnect_url) { "#{channel.provider_config['provider_url']}/connections/#{channel.phone_number}" }

        it 'destroys the channel on successful disconnect' do
          stub_request(:delete, disconnect_url).to_return(status: 200)

          channel.destroy!

          expect(channel).to be_destroyed
        end

        it 'destroys the channel on failure to disconnect' do
          stub_request(:delete, disconnect_url).to_return(status: 404, body: 'error message')

          channel.destroy!

          expect(channel).to be_destroyed
        end
      end

      context 'when provider is not baileys' do
        let(:channel) { create(:channel_whatsapp, provider: 'whatsapp_cloud', validate_provider_config: false, sync_templates: false) }

        it 'does not invoke callback' do
          expect(channel).not_to receive(:disconnect_channel_provider)

          channel.destroy!
        end
      end
    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.

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

Reviewable status: all files reviewed, 1 unresolved discussion (waiting on @gabrieljablonski)


spec/models/channel/whatsapp_spec.rb line 93 at r1 (raw file):

Previously, gabrieljablonski (Gabriel Jablonski) wrote…

Carefully note on all suggested changes.

For some context:

  1. ActiveRecord objects have a .destroyed? method
  2. expect(object).to be_something is shorthand for expect(object.something?).to be(true)

Done.

@gabrieljablonski gabrieljablonski changed the base branch from fazer-ai/main to feat/process-baileys-images-in-message-upsert April 25, 2025 19:32
Copy link
Member
@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) +(approved for merge)

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

@gabrieljablonski gabrieljablonski merged commit 4e86e88 into feat/process-baileys-images-in-message-upsert Apr 25, 2025
2 checks passed
@gabrieljablonski gabrieljablonski deleted the fix/disconnect-baileys-before-destroy-inbox branch April 25, 2025 19:35
gabrieljablonski added a commit that referenced this pull request Apr 25, 2025
…dle unsupported messages (#26)

* fix: return not_found status for missing messages in WhatsApp webhook

* feat: enhance message handling to support image attachments

* chore: Handle incoming whatsapp baileys service attachments and implement specs for images and videos

* fix: add file_content_type method to incoming baileys messages

* chore: specs for stickers, audio and files

* fix: handle media attachment errors

* chore: convert file_content_type to string when attaching media

* fix: add handling for attachment not found error in incoming message service

* chore: refactor file_content_type method and simplify filename method

* chore: update media attachment tests

* feat: baileys unsupported message alert (#27)

* feat: create alert message for unsupported message types

* chore: fail message when try send not supported type in baileys

* chore: add tests for unsupported message handling in Baileys service

* chore: correct spelling

* chore: NIT in spec name

* chore: remove unnecessary message reload in unsupported message type test

* feat: baileys support to send attachments (#28)

* feat: enhance message sending logic with support for attachments and interactive messages

* fix: update message format to use messageContent for text messages

* feat: attachment message sending

* fix: use strict encoding for attachment file download

* chore: streamline message sending logic and remove unused error classes

* chore: remove type from message sending logic

* chore: update message sending specs

* chore: raise MessageNotSentError instead of updating message status to failed

* chore: change baileys contact name preferences (#30)

* refactor: improve contact name handling and extraction from JID

* test: enhance message handling to update contact names based on pushName and verifiedBizName

* chore: update contact name condition to match phone number from JID

* chore: correct method name typo

* chore: correct variable names for phone number consistency in tests

* chore: update message payload structure and improve error handling in send_message

* test: re-add testing for error handling

* feat: enhance contact name handling and add self-message detection

* fix: ensure presence check for verified business name in contact name retrieval

* test: improve specs

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>
Co-authored-by: Gabriel Jablonski <gabriel@fazer.ai>

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>
Co-authored-by: Gabriel Jablonski <gabriel@fazer.ai>

* fix: try to disconnect baileys before destroy inbox (#29)

* fix: ensure proper disconnection of Baileys provider on channel destruction

* test: add callback tests for disconnecting channel provider in Whatsapp spec

* refactor: simplify condition for disconnecting Baileys provider on channel destruction

* refactor: enhance disconnect_channel_provider specs for Baileys provider

* test: verify channel destruction does not call disconnect_channel_provider

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>
Co-authored-by: Gabriel Jablonski <gabriel@fazer.ai>
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