Skip to content

feat(whatsapp): enhance message fetching and processing logic #1449

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

Merged

Conversation

gomessguii
Copy link
Contributor

@gomessguii gomessguii commented May 15, 2025

  • Added a new method fetchMessages to retrieve messages based on various query parameters.
  • Improved handling of pushName for messages, ensuring proper assignment based on participant information.
  • Refactored user devices cache initialization for better readability.
  • Cleaned up commented-out code related to message recovery.

Summary by Sourcery

Enhance WhatsApp message handling by adding a flexible fetchMessages API, improving pushName resolution, refining chat filtering rules, and tidying up related cache setup and dead code.

New Features:

  • Introduce fetchMessages method for paginated and filtered retrieval of messages.

Enhancements:

  • Assign missing pushName values based on participants or contact mappings.
  • Respect full history sync for group chats in shouldIgnoreJid logic.
  • Refactor userDevicesCache initialization for improved readability.
  • Remove commented-out message recovery logic to clean up codebase.

- Added a new method `fetchMessages` to retrieve messages based on various query parameters.
- Improved handling of `pushName` for messages, ensuring proper assignment based on participant information.
- Refactored user devices cache initialization for better readability.
- Cleaned up commented-out code related to message recovery.
Copy link
Contributor

sourcery-ai bot commented May 15, 2025

Reviewer's Guide

This PR enhances message retrieval and processing within BaileysStartupService by introducing a new fetchMessages method with Prisma-based filtering, pagination, and formatting, refines pushName assignment through a contacts map and fallback logic, streamlines cache initialization and ignore rules, and removes outdated recovery code.

Sequence Diagram for fetchMessages Method

sequenceDiagram
  participant Caller
  participant BSS as BaileysStartupService
  participant PR as PrismaRepository

  Caller->>BSS: fetchMessages(query)
  BSS->>BSS: Construct filterOptions from query
  BSS->>PR: message.count(filterOptions)
  PR-->>BSS: count
  BSS->>PR: message.findMany(filterOptions, pagination, selectFields)
  PR-->>BSS: rawMessages
  BSS->>BSS: Loop: Format each message (apply pushName logic)
  BSS-->>Caller: { total, pages, currentPage, records: formattedMessages }
Loading

Sequence Diagram for Enhanced pushName Assignment in Message Processing

sequenceDiagram
  participant BaileysSocket
  participant BSS as BaileysStartupService
  participant ContactsMap as contactsMap (internal)

  BaileysSocket->>BSS: Event: 'messages.upsert' (messagesUpdate)
  BSS->>BSS: Populate contactsMap from available contacts data
  loop For each message 'm' in messagesUpdate.messages
    alt If !m.pushName AND !m.key.fromMe
      BSS->>BSS: participantJid = m.participant || m.key.participant || m.key.remoteJid
      alt participantJid AND contactsMap.has(participantJid)
        BSS->>ContactsMap: get(participantJid)
        ContactsMap-->>BSS: contactInfo (with name)
        BSS->>BSS: m.pushName = contactInfo.name
      else if participantJid
        BSS->>BSS: m.pushName = participantJid.split('@')[0] (fallback)
      end
    end
    BSS->>BSS: preparedMessage = prepareMessage(m)
    note right of BSS: prepareMessage itself also contains updated pushName fallback logic
    BSS->>BSS: Further processing of preparedMessage (e.g., save, emit)
  end
Loading

Class Diagram for BaileysStartupService and fetchMessages Structures

classDiagram
  class BaileysStartupService {
    -authStateProvider: AuthStateProvider
    -msgRetryCounterCache: CacheStore
    -userDevicesCache: CacheStore
    +fetchMessages(query: Query_Message): Promise<FetchMessagesResponse>
    +prepareMessage(message: any): any
    #upsertMessage(messagesUpdate: any, messageType: any): Promise<void>
  }
  class Query_Message {
    +where: MessageWhereInput
    +offset: number
    +page: number
  }
  class MessageWhereInput {
    +id: string
    +source: string
    +messageType: string
    +messageTimestamp: TimestampFilter
    +key: KeyFilter
  }
  class KeyFilter {
    +id: string
    +fromMe: boolean
    +remoteJid: string
    +participants: string
  }
  class TimestampFilter {
    +gte: string
    +lte: string
  }
  class FetchMessagesResponse {
    +messages: PaginatedMessages
  }
  class PaginatedMessages {
    +total: number
    +pages: number
    +currentPage: number
    +records: object[]
  }

  BaileysStartupService ..> Query_Message : uses
  BaileysStartupService ..> FetchMessagesResponse : uses
  Query_Message *-- MessageWhereInput : contains
  MessageWhereInput *-- KeyFilter : contains
  MessageWhereInput *-- TimestampFilter : contains
  FetchMessagesResponse *-- PaginatedMessages : contains

  note for BaileysStartupService "New method fetchMessages added.\npushName logic enhanced in upsertMessage and prepareMessage."
Loading

File-Level Changes

Change Details Files
Implemented fetchMessages for advanced querying and response formatting
  • Added Prisma count and findMany calls with dynamic filters
  • Computed pagination (total, pages, currentPage)
  • Mapped and formatted each message with pushName fallback logic
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Enhanced pushName assignment for incoming messages
  • Built contactsMap from contacts to resolve names
  • Assigned missing m.pushName from contactsMap or extracted JID prefix
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Refined outgoing message mapping for pushName
  • Defaulted to 'Você' for sender when fromMe
  • Extracted participant or JID prefix when pushName is absent
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Refactored cache setup and ignore rules
  • Reformatted userDevicesCache initialization whitespace
  • Updated shouldIgnoreJid to consider syncFullHistory flag
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Removed obsolete commented-out message recovery code
  • Deleted code handling messageStubParameters and retryCache logic
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@DavidsonGomes DavidsonGomes merged commit a1cc504 into EvolutionAPI:develop May 15, 2025
1 check passed
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