-
Notifications
You must be signed in to change notification settings - Fork 5.2k
fix(api): modifica fetchChats para trazer mensagens de contatos não salvos #1383
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
- Update Docker image repository to evoapicloud/evolution-api - Modify contact email to contato@evolution-api.com - Update Docker Compose, Dockerfile, and workflow files - Add Docker image badge to README - Include additional content creator in README - Implement message deduplication cache in Baileys service
…leys service - Refactor edited message detection logic - Prevent duplicate message processing for edited messages - Optimize message key caching mechanism
…{baseUrl}}/chat/fetchCatalogs' and '{{baseUrl}}/chat/fetchCollections'
Refactor edit and delete message functionality in BaileyStartupService
Feat: Adicionei suporte para obter o Catálogos de Produtos e as Coleções de Produtos para a versão 2.2.3
- Added NATS package to dependencies - Created Prisma schema models for NATS configuration - Implemented NATS controller, router, and event management - Updated instance controller and event manager to support NATS - Added NATS configuration options in environment configuration - Included NATS events in instance validation schema
…gos de produtos e Coleções evitando alterações desnecessárias em arquivos do repositório
Adicionado suporte para obter Catálogos e Coleções no WhatsApp Business
feat: notconvertsticket for animated stickers
Fix instance creation on v2.2.3
…-location feat: add message location support whatsapp meta
Fix audio send duplicate from chatwoot.
…twoot fix: chatwoot csat creating new conversation in another language
…#1234 Corrige problema na API relacionado à migration. Fixes EvolutionAPI#1234
Refactor Editing Message events and update message handler
…se-message fix: change mediaId optional chaining and list response message text obtain
…fix/missing-wavoipToken-mysql hotfix(migration): add missing wavoipToken column in MySQL schema
- Implement dynamic queue creation based on enabled events - Add method to list existing queues for an instance - Improve error handling and logging for SQS operations - Remove unused queue removal methods - Update set method to handle queue creation/deletion on event changes - Add comments for future feature of forced queue deletion
…avoipToken-create 🐛 Corrige problema na API relacionado à migration. Fixes EvolutionAPI#1234
✨ Feat: Remover a reação de uma mensagem.
fix: Refactor SQS controller to correct bug in sqs events by instance
…useless Fix: Expiration being useless on awaitUser false
- Create Nats table in PostgreSQL migration - Disable message recovery logic in Baileys service - Remove console log in instance creation route
- Add robust authentication mechanism for WebSocket connections - Implement API key validation for both instance-specific and global tokens - Improve connection request handling with detailed logging - Refactor WebSocket controller to support more secure connection validation
fix: adjusting cloud api send audio and video
Corrige validação de URL para permitir localhost e endereços IP
Add eventos referente a instancia que estavam faltando
Reviewer's Guide by SourceryThis pull request includes several bug fixes and new features. It fixes an issue where messages from unsaved contacts were not being fetched, implements message editing functionality, adds catalog and collection fetching for business accounts, implements SQS and NATS event queue management, enhances Websocket authentication and security, improves Webhook URL validation, fixes a bug where Typebot was not processing messages correctly, and adds support for location messages in Business API. Sequence diagram for fetching catalogsequenceDiagram
participant Client
participant BaileysService
participant WhatsApp
Client->>BaileysService: fetchCatalog(instanceName, data)
activate BaileysService
BaileysService->>WhatsApp: client.getCatalog(jid, limit, cursor)
activate WhatsApp
WhatsApp-->>BaileysService: Returns catalog data
deactivate WhatsApp
BaileysService-->>Client: Returns catalog data
deactivate BaileysService
Sequence diagram for fetching collectionssequenceDiagram
participant Client
participant BaileysService
participant WhatsApp
Client->>BaileysService: fetchCollections(instanceName, data)
activate BaileysService
BaileysService->>WhatsApp: client.getCollections(jid, limit)
activate WhatsApp
WhatsApp-->>BaileysService: Returns collections data
deactivate WhatsApp
BaileysService-->>Client: Returns collections data
deactivate BaileysService
Sequence diagram for SQS event creationsequenceDiagram
participant Client
participant SqsController
participant PrismaRepository
participant AWS SQS
Client->>SqsController: set(instanceName, data)
activate SqsController
SqsController->>SqsController: saveQueues(instanceName, events, enable)
activate SqsController
loop for each event in events
SqsController->>AWS SQS: createQueue(queueName)
activate AWS SQS
AWS SQS-->>SqsController: Returns QueueUrl
deactivate AWS SQS
end
SqsController->>PrismaRepository: upsert(payload)
activate PrismaRepository
PrismaRepository-->>SqsController: Returns Sqs data
deactivate PrismaRepository
SqsController-->>Client: Returns Sqs data
deactivate SqsController
deactivate SqsController
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @leandrosroc - I've reviewed your changes - here's some feedback:
Overall Comments:
- Consider adding a description of the purpose and usage of the
baileysCacheto improve readability. - The addition of NATS is a significant change; ensure that the configuration and usage are well-documented for operators.
Here's what I looked at during the review
- 🟡 General issues: 1 issue found
- 🟢 Security: all looks good
- 🟢 Testing: all looks good
- 🟡 Complexity: 2 issues found
- 🟢 Documentation: all looks good
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| cors: { | ||
| origin: this.cors, | ||
| cors: { origin: this.cors }, | ||
| allowRequest: async (req, callback) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (bug_risk): Review URL parsing in allowRequest callback.
The use of 'new URL(req.url || '', 'http://localhost')' works for many cases, but ensure that all incoming requests have a format that can be correctly parsed. It might be useful to have additional checks or to log malformed URLs to aid debugging.
Suggested implementation:
} catch (error) {
Logger.error('Malformed URL in allowRequest callback', { error, url: req.url });
return callback(new Error('Malformed URL'));
}Ensure that the Logger from '@config/logger.config' is properly configured and imported.
If other parts of your error handling strategy require modifications to accommodate the new error handling, please update them accordingly.
| const editedMessage = | ||
| received?.message?.protocolMessage || received?.message?.editedMessage?.message?.protocolMessage; | ||
|
|
||
| if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (complexity): Consider extracting the duplicate message caching and edited message handling logic into helper functions to improve readability and reduce nesting complexity within the code.
Consider breaking out repeated clustered logic into dedicated helper functions to improve readability and reduce nesting. For example, you can extract the duplicate message caching functionality and the edited message handling logic:
1. Cache Check Helper
Extract the cache check into a single helper:
// cacheHelpers.ts
export async function isCachedMessage(cache: CacheStore, key: string, logger: Logger): Promise<boolean> {
const cached = await cache.get(key);
if (cached) {
logger.info(`Message duplicated ignored: ${key}`);
return true;
}
await cache.set(key, true, 30 * 60);
return false;
}Then in your main code:
import { isCachedMessage } from './cacheHelpers';
const messageKey = `${this.instance.id}_${received.key.id}`;
if (await isCachedMessage(this.baileysCache, messageKey, this.logger) && !editedMessage) {
continue;
}2. Edited Message Handler
Consolidate the complicated edited message processing into a dedicated helper:
// messageHelpers.ts
export async function handleEditedMessage(
editedMessage: any,
chatwootService: any,
configService: any,
localChatwoot: any,
instance: any,
sendDataWebhook: Function,
prismaRepository: any,
getMessage: Function
) {
if (configService.get('CHATWOOT').ENABLED && localChatwoot?.enabled) {
chatwootService.eventWhatsapp('messages.edit', {
instanceName: instance.name,
instanceId: instance.id,
}, editedMessage);
}
await sendDataWebhook('MESSAGES_EDITED', editedMessage);
const oldMessage = await getMessage(editedMessage.key, true);
if (oldMessage?.id) {
await prismaRepository.message.update({
where: { id: oldMessage.id },
data: {
message: editedMessage.editedMessage,
messageTimestamp: Number(editedMessage.timestampMs),
status: 'EDITED',
},
});
await prismaRepository.messageUpdate.create({
data: {
fromMe: editedMessage.key.fromMe,
keyId: editedMessage.key.id,
remoteJid: editedMessage.key.remoteJid,
status: 'EDITED',
instanceId: instance.id,
messageId: oldMessage.id,
},
});
}
}And then simplify the main block:
const editedMessageValue = received?.message?.protocolMessage ||
received?.message?.editedMessage?.message?.protocolMessage;
if (received.message?.protocolMessage?.editedMessage ||
received.message?.editedMessage?.message) {
if (editedMessageValue) {
await handleEditedMessage(
editedMessageValue,
this.chatwootService,
this.configService,
this.localChatwoot,
this.instance,
this.sendDataWebhook.bind(this),
this.prismaRepository,
this.getMessage.bind(this)
);
}
}These steps refactor the nested logic into focused helper functions without reverting functionality, improving maintainability.
|
|
||
| public get channel(): SQS { | ||
| return this.sqs; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (complexity): Consider refactoring repeated patterns in helper methods into dedicated utility functions to reduce complexity and improve readability by reducing nested control flows and duplicated code.
The new helper methods are functionally solid but have complexity due to nested control flows. Consider refactoring the repeated patterns (like creating or extracting queue names and handling SQS commands) into dedicated utility functions. For example, extract the logic to build normalized queue names and abstract the try/catch for SQS commands.
Suggested Refactor:
-
Extract Queue Name Construction
// utils/sqsHelpers.ts export const getQueueName = (instanceName: string, event: string): string => { return `${instanceName}_${event.toLowerCase()}.fifo`; };
-
Abstract SQS Command Execution
// utils/sqsHelpers.ts import { SQS } from '@aws-sdk/client-sqs'; export const executeSqsCommand = async ( sqs: SQS, command: any, onSuccess: (data: any) => void, onError: (err: any) => void ): Promise<void> => { try { const data = await sqs.send(command); onSuccess(data); } catch (err: any) { onError(err); } };
-
Refactor
saveQueuesUsing the Helpersimport { getQueueName, executeSqsCommand } from '../utils/sqsHelpers'; import { CreateQueueCommand } from '@aws-sdk/client-sqs'; private async saveQueues(instanceName: string, events: string[], enable: boolean) { if (enable) { const eventsFound = await this.listQueuesByInstance(instanceName); for (const event of events) { const normalizedEvent = event.toLowerCase(); if (eventsFound.includes(normalizedEvent)) { this.logger.info(`Queue for event "${normalizedEvent}" already exists. Skipping creation.`); continue; } const queueName = getQueueName(instanceName, normalizedEvent); const createCommand = new CreateQueueCommand({ QueueName: queueName, Attributes: { FifoQueue: 'true' }, }); await executeSqsCommand( this.sqs, createCommand, (data) => this.logger.info(`Queue ${queueName} created: ${data.QueueUrl}`), (err) => this.logger.error(`Error creating queue ${queueName}: ${err.message}`) ); } } }
Applying similar patterns to initQueues and removeQueues will reduce nesting and duplicate code, hence lowering cognitive load while keeping the functionality intact.
fix(api): modifica fetchChats para trazer mensagens de contatos não salvos
Resolve issue #1376
Summary by Sourcery
Modify the fetchChats method to retrieve messages from unsaved contacts by changing the base query table and adjusting join conditions
Bug Fixes:
Enhancements: