Skip to content

Log webhook #7

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

Open
wants to merge 81 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
81 commits
Select commit Hold shift + click to select a range
d4b1af0
fix: getIdMedia and audioWhatsapp/ bug fix send media for meta
jhonsw1 Nov 1, 2024
6605c93
fix: status read in whatsapp business
jhonsw1 Nov 1, 2024
d22dacc
fix: receive sticker in connection for meta
jhonsw1 Nov 1, 2024
8a2199f
fix sending media in groups where the group number is greater than 23…
jhonsw1 Nov 1, 2024
807914b
fix messages loss
jhonsw1 Nov 1, 2024
fdd25e3
fix encrypted incoming messages
jhonsw1 Nov 1, 2024
614e9f7
fix message edited by whatsApp web
jhonsw1 Nov 1, 2024
d425e22
bug fix: message.map is not a function.. Only iterate over message.co…
jhonsw1 Nov 4, 2024
b5b2028
fix: Enter WhatsApp version individually
jhonsw1 Nov 4, 2024
8f61770
fix: removed create in database for messages cache
jhonsw1 Nov 5, 2024
cbe095a
fix: private groups
jhonsw1 Nov 5, 2024
a9f1b5a
Migration webVersion
Nov 5, 2024
e153b75
removed console.log
jhonsw1 Nov 5, 2024
2e3ba3a
Merge remote-tracking branch 'refs/remotes/origin/main-updates' into …
jhonsw1 Nov 5, 2024
7297e27
fix: blocked for status broadcast
jhonsw1 Nov 6, 2024
98064cc
Novo tratamento para mídias no webhook
Nov 11, 2024
0e5572f
Corrige recebimento de mensagens citadas
Nov 13, 2024
3d50534
Corrige resposta de status
Nov 14, 2024
bc2c96f
Altera versão da baileys
Nov 29, 2024
dc30002
fix: send audios with quoted messages
jhonsw1 Dec 4, 2024
d41cedf
Fixa versao 3.20 do node js alpine no dockerfile
lnmesquita1 Dec 14, 2024
114f879
Inclui groupInfo no webhook
Dec 17, 2024
3a28019
Merge branch 'main-updates' of https://github.com/lnmesquita1/evoluti…
Dec 17, 2024
ec6612a
Envio de mídias com mensagens citadas
Dec 26, 2024
01492cb
Remove inserção de contacts, chats e messages no evento messaging-his…
Jan 22, 2025
a85e3ab
Remove telemetry
Jan 22, 2025
15fc87b
Altera versão
Jan 22, 2025
b68b30f
Altera log, inclui opção de enviar buffer em mídias WABA e inclui fil…
Jan 23, 2025
d39c162
Corrige status
lnmesquita1 Jan 23, 2025
4a144ac
Merge main
Jan 24, 2025
4ae74fe
Merge main-updates from main-updates remote
Jan 24, 2025
d983921
Comenta listeners não utilizados
Jan 27, 2025
73594af
Remove log
Jan 27, 2025
4c14273
Update versão
Jan 27, 2025
998a4f0
fix: use cache on the findGroupInfos endpoint
jhonsw1 Jan 28, 2025
9d546aa
Inclui index remoteJid na tabela isOnWhatsapp
Jan 28, 2025
c56a0d3
Update da versão
Jan 28, 2025
07bd901
Merge pull request #1 from lnmesquita1/feature/IN-469
lnmesquita1 Jan 28, 2025
b0d0bc4
Comenta código desnecessário
Jan 29, 2025
11eb51d
Merge branch 'main-updates' of https://github.com/lnmesquita1/evoluti…
Jan 29, 2025
3fa1a5f
Altera lib da baileys
lnmesquita1 Jan 30, 2025
2b1060c
Remove codigo call nao usado
lnmesquita1 Jan 30, 2025
d642cdc
Update version
lnmesquita1 Jan 31, 2025
b8fd741
Update baileys version
lnmesquita1 Jan 31, 2025
c0fd917
Remove uniqueItems from mentioned validation
Feb 1, 2025
12d4c07
Envio de contatos no webhook messages.set
Feb 4, 2025
340a19a
Update versão
Feb 5, 2025
6ed2300
fix: Send ack update event to campaign messages
jhonsw1 Feb 10, 2025
39e6a4b
Merge pull request #2 from lnmesquita1/feature/IN-527
lnmesquita1 Feb 10, 2025
e6b637a
Update version
Feb 10, 2025
9e23c38
Update baileys
Feb 25, 2025
f21f93e
Remove persistencia de messageUpdate no waba e remove persistencia de…
Feb 25, 2025
b1e8a3e
fix sending media in groups where the group number is greater than 23…
jhonsw1 Feb 27, 2025
c6748f8
fix message edited by whatsApp web
jhonsw1 Feb 28, 2025
77c0d96
Merge pull request #3 from lnmesquita1/feature-547
lnmesquita1 Feb 28, 2025
775a504
Release
Feb 28, 2025
be0bfa4
Update baileys e altera userDevicesCache
Mar 25, 2025
3c723aa
Remove getMessage para evitar mensagem de 'Aguardando mensagem...'
Mar 25, 2025
3ba25d5
Ajusta edição de mensagens e remove codigo não usado
Mar 29, 2025
0460d72
Remove insert de mensagens
Apr 3, 2025
aa1c6df
Fork baileys
Apr 15, 2025
2273fbd
Update version
Apr 15, 2025
970ded7
KeepAlive undefined
Apr 15, 2025
0113243
Update node js no dockerfile
lnmesquita1 Apr 15, 2025
2b973a1
Codigo 408 para não reconectar
Apr 15, 2025
64efef6
keepAliveIntervalMs para 30_000
Apr 15, 2025
582cd91
Retorna versão da baileys
Apr 16, 2025
85b4136
Update dockerfile
Apr 16, 2025
bec40b3
Ajuste verificação de numeros
Apr 16, 2025
a9e27a0
Update
Apr 16, 2025
f4594ee
Cria endpoint para fazer count da instancias e remove verificação do …
Apr 18, 2025
fbc9337
Endpoint de instancia pelo nome
Apr 21, 2025
d6d246b
Update versão
Apr 21, 2025
d094595
Baileys pierre
Apr 22, 2025
dff9c8a
Corrige delete de mensagens
Apr 22, 2025
917e60b
Endpoint de download de mídias direto da baileys
Apr 28, 2025
7b6438a
Compatibilidade webhook meta V1
Apr 30, 2025
183c88d
Update versão
Apr 30, 2025
bd47e9b
Update lib
Apr 30, 2025
a62edbc
Update baileys
May 2, 2025
ab1d802
Log para identificar erros em webhook meta
jhonsw1 May 13, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:20-alpine AS builder
FROM node:20-alpine3.20 AS builder

RUN apk update && \
apk add git wget curl bash openssl
Expand Down Expand Up @@ -28,7 +28,7 @@ RUN ./Docker/scripts/generate_database.sh

RUN npm run build

FROM node:20-alpine AS final
FROM node:20-alpine3.20 AS final

RUN apk update && \
apk add tzdata bash openssl
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "evolution-api",
"version": "2.2.1",
"version": "2.2.29",
"description": "Rest api for communication with WhatsApp",
"main": "./dist/main.js",
"type": "commonjs",
Expand Down Expand Up @@ -57,7 +57,7 @@
"@sentry/node": "^8.47.0",
"amqplib": "^0.10.5",
"axios": "^1.7.9",
"baileys": "github:EvolutionAPI/Baileys",
"baileys": "github:WhiskeySockets/Baileys#master",
"class-validator": "^0.14.1",
"compression": "^1.7.5",
"cors": "^2.8.5",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Instance" ADD COLUMN "webVersion" VARCHAR(50);
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- CreateIndex
CREATE INDEX "IsOnWhatsapp_remoteJid_idx" ON "IsOnWhatsapp"("remoteJid");
2 changes: 2 additions & 0 deletions prisma/postgresql-schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ model Instance {
businessId String? @db.VarChar(100)
token String? @db.VarChar(255)
clientName String? @db.VarChar(100)
webVersion String? @db.VarChar(50)
disconnectionReasonCode Int? @db.Integer
disconnectionObject Json? @db.JsonB
disconnectionAt DateTime? @db.Timestamp
Expand Down Expand Up @@ -626,4 +627,5 @@ model IsOnWhatsapp {
jidOptions String
createdAt DateTime @default(now()) @db.Timestamp
updatedAt DateTime @updatedAt @db.Timestamp
@@index([remoteJid])
}
4 changes: 4 additions & 0 deletions src/api/abstract/abstract.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ export abstract class RouterBroker {
Object.assign(instance, body);
}

if (request.originalUrl.includes('/webhook/meta')) {
Object.assign(instance, body);
}

Object.assign(ref, body);

const v = schema ? validate(ref, schema) : { valid: true, errors: [] };
Expand Down
2 changes: 1 addition & 1 deletion src/api/controllers/group.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class GroupController {
}

public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) {
return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid);
return await this.waMonitor.waInstances[instance.instanceName].getGroupMetadataCache(groupJid.groupJid);
}

public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) {
Expand Down
29 changes: 28 additions & 1 deletion src/api/controllers/instance.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ export class InstanceController {
throw new BadRequestException('number is required');
}
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
webhookWaBusiness = `${urlServer}/webhook/meta`;
const webHookTest = this.configService.get<WaBusiness>('WA_BUSINESS').WEBHOOK_TEST;
webhookWaBusiness = `${webHookTest ? webHookTest : urlServer}/webhook/meta`;
Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Avoid unneeded ternary statements (simplify-ternary)

Suggested change
webhookWaBusiness = `${webHookTest ? webHookTest : urlServer}/webhook/meta`;
webhookWaBusiness = `${webHookTest || urlServer}/webhook/meta`;


ExplanationIt is possible to simplify certain ternary statements into either use of an || or !.
This makes the code easier to read, since there is no conditional logic.

accessTokenWaBusiness = this.configService.get<WaBusiness>('WA_BUSINESS').TOKEN_WEBHOOK;
}

Expand Down Expand Up @@ -285,6 +286,32 @@ export class InstanceController {
return this.waMonitor.instanceInfo(instanceNames);
}

public async getInstanceByName({ instanceName }: InstanceDto) {
const instanceByName = await this.prismaRepository.instance.findFirst({
where: {
name: instanceName,
},
});

if (!instanceByName) {
return null;
}

const response = {
id: instanceByName.id,
name: instanceByName.name,
ownerJid: instanceByName.ownerJid,
connectionStatus: instanceByName.connectionStatus,
profileName: instanceByName.profileName,
}
return response;
Comment on lines +300 to +307
Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const response = {
id: instanceByName.id,
name: instanceByName.name,
ownerJid: instanceByName.ownerJid,
connectionStatus: instanceByName.connectionStatus,
profileName: instanceByName.profileName,
}
return response;
return {
id: instanceByName.id,
name: instanceByName.name,
ownerJid: instanceByName.ownerJid,
connectionStatus: instanceByName.connectionStatus,
profileName: instanceByName.profileName,
};


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

}

public async countInstances() {
const count = await this.prismaRepository.instance.count();
return count;
Comment on lines +311 to +312
Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const count = await this.prismaRepository.instance.count();
return count;
return await this.prismaRepository.instance.count();


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

}

public async setPresence({ instanceName }: InstanceDto, data: SetPresenceDto) {
return await this.waMonitor.waInstances[instanceName].setPresence(data);
}
Expand Down
4 changes: 2 additions & 2 deletions src/api/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
return next();
}

if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances') || req.originalUrl.includes('/instance/instanceByName')) && !key) {
throw new ForbiddenException('Missing global api key', 'The global api key must be set');
}
const param = req.params as unknown as InstanceDto;
Expand All @@ -34,7 +34,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
return next();
}
} else {
if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) {
if ((req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances') || req.originalUrl.includes('/instance/instanceByName')) && db.SAVE_DATA.INSTANCE) {
const instanceByKey = await prismaRepository.instance.findFirst({
where: { token: key },
});
Expand Down
2 changes: 1 addition & 1 deletion src/api/guards/instance.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async function getInstance(instanceName: string) {
}

export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) {
if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) {
if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances') || req.originalUrl.includes('/instance/instanceByName')) {
return next();
}

Expand Down
56 changes: 28 additions & 28 deletions src/api/integrations/channel/evolution/evolution.channel.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,34 +179,34 @@ export class EvolutionStartupService extends ChannelStartupService {

this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);

const chat = await this.prismaRepository.chat.findFirst({
where: { instanceId: this.instanceId, remoteJid: data.remoteJid },
});

if (chat) {
const chatRaw: any = {
remoteJid: data.remoteJid,
instanceId: this.instanceId,
};

this.sendDataWebhook(Events.CHATS_UPDATE, chatRaw);

await this.prismaRepository.chat.updateMany({
where: { remoteJid: chat.remoteJid },
data: chatRaw,
});
}

const chatRaw: any = {
remoteJid: data.remoteJid,
instanceId: this.instanceId,
};

this.sendDataWebhook(Events.CHATS_UPSERT, chatRaw);

await this.prismaRepository.chat.create({
data: chatRaw,
});
// const chat = await this.prismaRepository.chat.findFirst({
// where: { instanceId: this.instanceId, remoteJid: data.remoteJid },
// });

// if (chat) {
// const chatRaw: any = {
// remoteJid: data.remoteJid,
// instanceId: this.instanceId,
// };

// this.sendDataWebhook(Events.CHATS_UPDATE, chatRaw);

// await this.prismaRepository.chat.updateMany({
// where: { remoteJid: chat.remoteJid },
// data: chatRaw,
// });
// }

// const chatRaw: any = {
// remoteJid: data.remoteJid,
// instanceId: this.instanceId,
// };

// this.sendDataWebhook(Events.CHATS_UPSERT, chatRaw);

// await this.prismaRepository.chat.create({
// data: chatRaw,
// });
}

protected async sendMessageWithTyping(number: string, message: any, options?: Options, file?: any) {
Expand Down
1 change: 1 addition & 0 deletions src/api/integrations/channel/meta/meta.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export class MetaController extends ChannelController implements ChannelControll
integrationEnabled: boolean;

public async receiveWebhook(data: any) {
this.logger.info("VALOR DE DATA META: " + JSON.stringify(data))
if (data.object === 'whatsapp_business_account') {
if (data.entry[0]?.changes[0]?.field === 'message_template_status_update') {
const template = await this.prismaRepository.template.findFirst({
Expand Down
11 changes: 11 additions & 0 deletions src/api/integrations/channel/meta/meta.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ export class MetaRouter extends RouterBroker {
const { body } = req;
const response = await metaController.receiveWebhook(body);

return res.status(200).json(response);
})
.get(this.routerPath('webhook/whatsapp', false), async (req, res) => {
if (req.query['hub.verify_token'] === configService.get<WaBusiness>('WA_BUSINESS').TOKEN_WEBHOOK)
res.send(req.query['hub.challenge']);
else res.send('Error, wrong validation token');
Comment on lines +22 to +24
Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

Suggested change
if (req.query['hub.verify_token'] === configService.get<WaBusiness>('WA_BUSINESS').TOKEN_WEBHOOK)
res.send(req.query['hub.challenge']);
else res.send('Error, wrong validation token');
if (req.query['hub.verify_token'] === configService.get<WaBusiness>('WA_BUSINESS').TOKEN_WEBHOOK) {
res.send(req.query['hub.challenge']);
} else res.send('Error, wrong validation token');


ExplanationIt is recommended to always use braces and create explicit statement blocks.

Using the allowed syntax to just write a single statement can lead to very confusing
situations, especially where subsequently a developer might add another statement
while forgetting to add the braces (meaning that this wouldn't be included in the condition).

})
.post(this.routerPath('webhook/whatsapp', false), async (req, res) => {
const { body } = req;
const response = await metaController.receiveWebhook(body);

return res.status(200).json(response);
});
}
Expand Down
Loading