evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

fix: normalize fileName property to handle case-insensitivity

Open enzowilliam opened this issue 8 months ago • 4 comments

Summary

  • Fixes the inconsistency in the /message/sendMedia/{instance} endpoint where the fileName property was case-sensitive
  • For images, only filename (lowercase) worked
  • For documents/videos, only fileName (camelCase) worked
  • Now both fileName and filename are accepted for all media types

Changes

Added property normalization at the beginning of the mediaMessage method in all three channel services:

  • src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
  • src/api/integrations/channel/evolution/evolution.channel.service.ts
  • src/api/integrations/channel/meta/whatsapp.business.service.ts

The fix normalizes filename to fileName by using:

fileName: data.fileName || (data as any).filename,

Test plan

  • [ ] Send image with fileName property - should work
  • [ ] Send image with filename property - should work
  • [ ] Send document with fileName property - should work
  • [ ] Send document with filename property - should work
  • [ ] Send video with fileName property - should work
  • [ ] Send video with filename property - should work

Closes #2459

🤖 Generated with Claude Code

Summary by Sourcery

Normalize media message filename handling across channels and refine group mention options for message schemas and WhatsApp integration.

Bug Fixes:

  • Allow both fileName and filename properties when sending media messages across WhatsApp, Evolution, and Meta channel services.
  • Ensure mentionsEveryOne only applies when explicitly set to true in WhatsApp Baileys group messaging.

Enhancements:

  • Rename message schema property from everyOne to mentionsEveryOne for clearer and more consistent API semantics across all message types.

enzowilliam avatar Mar 11 '26 19:03 enzowilliam

Reviewer's Guide

Normalizes the SendMedia DTO so both fileName and filename are accepted across all WhatsApp channel integrations, and renames the everyOne mention flag to mentionsEveryOne consistently in message validation schemas and Baileys service logic.

Sequence diagram for sendMedia filename normalization

sequenceDiagram
  actor Client
  participant Api as MessageApi
  participant Chan as ChannelService
  participant WA as WhatsappProvider

  Client->>Api: POST /message/sendMedia/{instance}\nbody { fileName or filename }
  Api->>Chan: mediaMessage(data, file, isIntegration)

  alt data.fileName is defined
    Chan->>Chan: Build mediaData with fileName = data.fileName
  else data.fileName is undefined and data.filename is defined
    Chan->>Chan: Build mediaData with fileName = data.filename
  end

  Chan->>Chan: if file provided\nset mediaData.media = file buffer base64
  Chan->>WA: Send normalized mediaData
  WA-->>Chan: Provider response
  Chan-->>Api: Normalized send result
  Api-->>Client: HTTP response

Class diagram for updated message mention schemas

classDiagram
  class TextMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class MediaMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class PtvMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class AudioMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class StickerMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class LocationMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class PollMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class ListMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }
  class ButtonsMessageSchema {
    +boolean mentionsEveryOne
    +array mentioned
  }

  TextMessageSchema <|-- MediaMessageSchema
  TextMessageSchema <|-- PtvMessageSchema
  TextMessageSchema <|-- AudioMessageSchema
  TextMessageSchema <|-- StickerMessageSchema
  TextMessageSchema <|-- LocationMessageSchema
  TextMessageSchema <|-- PollMessageSchema
  TextMessageSchema <|-- ListMessageSchema
  TextMessageSchema <|-- ButtonsMessageSchema

Flow diagram for mentionsEveryOne handling in Baileys service

flowchart TD
  A[Start building mentions list] --> B{options.mentionsEveryOne === true}
  B -->|yes| C[Set mentions to all group participants ids]
  B -->|no| D{options.mentioned has items}
  D -->|yes| E[Map each mentioned value to participant id]
  D -->|no| F[Leave mentions empty]
  C --> G[Continue sending message]
  E --> G[Continue sending message]
  F --> G[Continue sending message]

File-Level Changes

Change Details Files
Normalize media filename input to support both fileName and filename for all media types in all WhatsApp channel services.
  • Change mediaMessage construction to spread incoming data while overriding/setting fileName
  • Derive fileName from either existing data.fileName or legacy lowercase data.filename
  • Ensure file attachment buffer is still converted to base64 and assigned to media
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/integrations/channel/evolution/evolution.channel.service.ts
src/api/integrations/channel/meta/whatsapp.business.service.ts
Rename the broadcast-mention boolean flag from everyOne to mentionsEveryOne across message validation schemas and tighten its usage in Baileys service.
  • Update JSON schemas for all message types to use mentionsEveryOne instead of everyOne
  • Keep mentionsEveryOne typed as a boolean enum [true, false] in schemas
  • Require options.mentionsEveryOne to be strictly true before auto-mentioning all group participants
src/validate/message.schema.ts
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Assessment against linked issues

Issue Objective Addressed Explanation
https://github.com/EvolutionAPI/evolution-api/issues/2459 Fix the /message/sendMedia/{instance} endpoint so that the file name field behaves consistently across all media types (image, video, document), eliminating the bug where images only worked with filename and documents/videos only with fileName. ✅
https://github.com/EvolutionAPI/evolution-api/issues/2459 Standardize on a single canonical property name (fileName) in the public API contract and documentation, fully aligning the documented payload with the actual implementation. ❌ The PR changes only backend service code to normalize filename to fileName in mediaMessage methods; it does not modify any API documentation or schemas related to the documented contract, so alignment of docs/contract with the new behavior is not covered here.

Possibly linked issues

  • #2459: PR normalizes filename to fileName in mediaMessage, resolving the documented inconsistency for all media types
  • #2459: PR normalizes filename/fileName in mediaMessage, fixing the sendMedia error seen on WhatsApp Cloud API instances.

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

  • Contact our support team for questions or feedback.
  • Visit our documentation for detailed guides and information.
  • Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.

sourcery-ai[bot] avatar Mar 11 '26 19:03 sourcery-ai[bot]

Hi! As part of our PR triage, we noticed the Check Code Quality workflow has not run on this PR (it requires maintainer approval for first-time external contributors, which we've now enabled).

To trigger CI:

  • Push any commit to your branch (a rebase against develop is ideal — base was adjusted on our side from main to develop)
  • Or close + reopen this PR

Once CI runs and is green I'll re-review for merge. Thanks!

DavidsonGomes avatar May 06 '26 18:05 DavidsonGomes

O fix de normalização de fileName/filename está bom — endereça um problema real de case-insensitivity vindo de clientes diferentes.

Bloqueador antes do merge:

  • [ ] Breaking change não declarado — a renomeação everyOne → mentionsEveryOne em 9 schemas (textMessage, mediaMessage, ptv, audio, sticker, location, poll, list, buttons) quebra abruptamente clientes que enviam everyOne: true. Sem alias nem migration path.

    Por favor aceitar ambos no schema (como enum ou oneOf) por pelo menos uma release, logar deprecation warning ao receber everyOne, e marcar a remoção para uma versão futura.

    Alternativa: mover a renomeação para PR separado marcado como BREAKING + entrada de CHANGELOG.

Nits (não-bloqueantes):

  • [ ] Cast (data as any).filename aparece em 3 services — considerar mover a normalização para um helper compartilhado em src/utils/ ou direto no DTO
  • [ ] O strict check mentionsEveryOne === true é o ideal, mas combine com o ponto acima (aceitar alias) para evitar breaking change silencioso

DavidsonGomes avatar May 17 '26 22:05 DavidsonGomes

Olá @enzowilliam, obrigado pelo fix. O core (normalizeFileName) está correto e endereça uma inconsistência real reportada em #2459. Antes de mergear, três pontos:

Bloqueantes

  1. Scope creep entre título e diff. O título da PR é sobre fileName, mas metade do diff é deprecation do everyOne em favor de mentionsEveryOne (adicionado em 9 schemas: text, media, ptv, audio, sticker, location, poll, list, buttons). Por favor:

    • Opção A: split em duas PRs — uma para fileName, outra para deprecation do everyOne
    • Opção B: atualize o título para algo como fix: normalize fileName + deprecate everyOne in favor of mentionsEveryOne

    Sem isso, reviewers podem aprovar achando que é só o fileName e perder a segunda mudança.

  2. Sem testes. normalizeFileName é uma função pura — testar é trivial:

    expect(normalizeFileName({ filename: 'a.pdf' })).toEqual({ filename: 'a.pdf', fileName: 'a.pdf' });
    expect(normalizeFileName({ fileName: 'a.pdf' })).toEqual({ fileName: 'a.pdf' });
    expect(normalizeFileName(null)).toBeNull();
    

    Adicione pelo menos um Jest test para a função.

Inconsistência interna da PR

  1. resolveMentionsEveryOne usa warnOnce para alertar uso do nome legado, mas normalizeFileName normaliza silenciosamente filename → fileName. Por consistência, adicione warnOnce também no fileName — usuários precisam aprender que devem migrar.

  2. Edge case não coberto: se o caller mandar ambos fileName e filename, qual vence? Olhando o código, fileName vence silenciosamente sem warning. Documente ou avise.

Após o split (ou rename do título) + teste mínimo, mergeio. Obrigado!

DavidsonGomes avatar May 19 '26 14:05 DavidsonGomes

🟢 👍

Mira a develop e está consistente: centraliza a normalização num util (normalizeSendMessageOptions) e aplica normalizeFileName nos 3 channels (aceita o alias filename), além de tratar o alias depreciado everyOne→mentionsEveryOne com aviso e schema/DTO atualizados. Aditivo, sem mexer em estrutura. Pode seguir.

@dpaes

NeritonDias avatar Jun 26 '26 02:06 NeritonDias