Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 4 additions & 4 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ services:
api:
container_name: evolution_api_${ENVIROMNENT}
build: .
#image: evoapicloud/evolution-api:latest
image: adaptweb/evolution-api:1.2.1
restart: always
depends_on:
- redis
Expand All @@ -24,11 +24,11 @@ services:
- evolution-net
container_name: redis_${ENVIROMNENT}
command: >
redis-server --port 6379 --appendonly yes
redis-server --port 11235 --appendonly yes
volumes:
- evolution_redis:/data
ports:
- ${REDIS_PORT}:6379
- ${REDIS_PORT}:11235

postgres:
container_name: postgres_${ENVIROMNENT}
Expand All @@ -38,7 +38,7 @@ services:
command: ["postgres", "-c", "max_connections=1000", "-c", "listen_addresses=*"]
restart: always
ports:
- ${DATABASE_PORT}:5432
- ${DATABASE_PORT}:11234
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=pass
Expand Down
1 change: 0 additions & 1 deletion src/api/controllers/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export class ChatController {
}

public async fetchProfilePicture({ instanceName }: InstanceDto, data: NumberDto) {
console.dir("Fetching profile picture...");
return await this.waMonitor.waInstances[instanceName].profilePicture(data.number);
}

Expand Down
23 changes: 23 additions & 0 deletions src/api/controllers/health.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { WAMonitoringService } from '@api/services/monitor.service';

import { UnauthorizedException } from '../../exceptions';

Check failure on line 3 in src/api/controllers/health.controller.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

'UnauthorizedException' is defined but never used
import { PrismaRepository } from '../repository/repository.service';

export class HealthController {
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly prismaRepository: PrismaRepository,
) {}

public async checkHealth() {
const instancesByKey = await this.prismaRepository.instance.findMany();

if (instancesByKey.length > 0) {
const names = instancesByKey.map((instance) => instance.name);

return this.waMonitor.instanceInfo(names);
} else {
return [];
}
}
}
59 changes: 40 additions & 19 deletions src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
Contact,
delay,
DisconnectReason,
downloadContentFromMessage,
downloadMediaMessage,
fetchLatestBaileysVersion,
generateWAMessageFromContent,
Expand Down Expand Up @@ -382,7 +383,7 @@
qrcodeTerminal.generate(qr, { small: true }, (qrcode) =>
this.logger.log(
`\n{ instance: ${this.instance.name} pairingCode: ${this.instance.qrcode.pairingCode}, qrcodeCount: ${this.instance.qrcode.count} }\n` +
qrcode,

Check failure on line 386 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
),
);

Expand Down Expand Up @@ -1023,14 +1024,14 @@

const messagesRepository: Set<string> = new Set(
chatwootImport.getRepositoryMessagesCache(instance) ??
(

Check failure on line 1027 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
await this.prismaRepository.message.findMany({

Check failure on line 1028 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
select: { key: true },

Check failure on line 1029 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
where: { instanceId: this.instanceId },

Check failure on line 1030 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
})

Check failure on line 1031 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
).map((message) => {

Check failure on line 1032 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Replace `··········` with `············`
const key = message.key as {

Check failure on line 1033 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
id: string;

Check failure on line 1034 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
};

return key.id;
Expand Down Expand Up @@ -1248,6 +1249,7 @@
received?.message?.imageMessage ||
received?.message?.videoMessage ||
received?.message?.stickerMessage ||
received?.message?.lottieStickerMessage ||
received?.message?.documentMessage ||
received?.message?.documentWithCaptionMessage ||
received?.message?.ptvMessage ||
Expand Down Expand Up @@ -1362,27 +1364,49 @@
}
}
}

if (this.localWebhook.enabled) {
if (isMedia && this.localWebhook.webhookBase64) {
if (1/* this.localWebhook.enabled */) {
if (1/* isMedia && this.localWebhook.webhookBase64 */) {
try {
const buffer = await downloadMediaMessage(
{ key: received.key, message: received?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);
let buffer : Buffer = null;
console.dir({received}, {depth: null});
if ((received.message.stickerMessage && received.message.stickerMessage.url === 'https://web.whatsapp.net')
|| (received.message.lottieStickerMessage && received.message.lottieStickerMessage.message.stickerMessage.url)) { /*Fixing broken URLs from sticker messages*/
const newUrl = `https://mmg.whatsapp.net${received.message.lottieStickerMessage ? received.message.lottieStickerMessage.message.stickerMessage.directPath : received.message.stickerMessage.directPath }`;

const stream = await downloadContentFromMessage(
{
mediaKey: received.message?.stickerMessage?.mediaKey || received.message.lottieStickerMessage?.message?.stickerMessage?.mediaKey,
directPath: received.message?.stickerMessage?.directPath || received.message.lottieStickerMessage?.message?.stickerMessage?.directPath,
url: newUrl
},
'sticker',
{},
)
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
buffer = Buffer.concat(chunks);
messageRaw.message.url = newUrl;
} else {
buffer = await downloadMediaMessage(
{ key: received.key, message: received?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);
}
messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined;
} catch (error) {
this.logger.error(['Error converting media to base64', error?.message]);
}
}
}

console.dir({webhookMessage: messageRaw}, {depth: null})
this.logger.log(messageRaw);

this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
Expand Down Expand Up @@ -1508,13 +1532,11 @@
},
});


if (!findMessage) {
continue;
}

if (update.message === null && update.status === undefined) {

const deletedMessage = {
id: findMessage.id,
instanceId: this.instanceId,
Expand All @@ -1526,7 +1548,7 @@
pushName: findMessage.pushName,
participant: findMessage.participant,
message: findMessage.message,
}
};

this.sendDataWebhook(Events.MESSAGES_DELETE, deletedMessage);

Expand Down Expand Up @@ -1756,7 +1778,7 @@
}

if (events['messages.upsert']) {
const payload = events['messages.upsert'];
const payload = events['messages.upsert']
this.messageHandle['messages.upsert'](payload, settings);
}

Expand Down Expand Up @@ -1880,12 +1902,10 @@
}

public async profilePicture(number: string) {
console.dir(`converting jid:${number}`);
const jid = createJid(number);

try {
const profilePictureUrl = await this.client.profilePictureUrl(jid, 'image');
console.dir({ profilePictureUrl });

return {
wuid: jid,
Expand Down Expand Up @@ -2280,7 +2300,8 @@
messageSent?.message?.documentMessage ||
messageSent?.message?.documentWithCaptionMessage ||
messageSent?.message?.ptvMessage ||
messageSent?.message?.audioMessage;
messageSent?.message?.audioMessage ||
messageSent?.message?.lottieStickerMessage;

if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) {
this.chatwootService.eventWhatsapp(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1597,6 +1597,7 @@ export class ChatwootService {
'audioMessage',
'videoMessage',
'stickerMessage',
'lottieStickerMessage',
'viewOnceMessageV2',
];

Expand Down Expand Up @@ -1651,6 +1652,7 @@ export class ChatwootService {
extendedTextMessage: msg.extendedTextMessage?.text,
messageContextInfo: msg.messageContextInfo?.stanzaId,
stickerMessage: undefined,
lottieStickerMessage: undefined,
documentMessage: msg.documentMessage?.caption,
documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
audioMessage: msg.audioMessage?.caption,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,7 @@ class ChatwootImport {
videoMessage: msg.message.videoMessage,
audioMessage: msg.message.audioMessage,
stickerMessage: msg.message.stickerMessage,
lottieStickerMessage: msg.message.lottieStickerMessage,
templateMessage: msg.message.templateMessage?.hydratedTemplate?.hydratedContentText,
};
const typeKey = Object.keys(types).find((key) => types[key] !== undefined);
Expand Down Expand Up @@ -531,6 +532,9 @@ class ChatwootImport {
case 'stickerMessage':
return '_<Sticker Message>_';

case 'lottieStickerMessage':
return '_<lottieStickerMessage>_';

default:
return '';
}
Expand Down
18 changes: 18 additions & 0 deletions src/api/routes/health.router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { RequestHandler, Router } from "express";
import { RouterBroker } from "../abstract/abstract.router";
import { HttpStatus } from "./index.router";
import { healthController } from "@api/server.module";


export class HealthRouter extends RouterBroker {
constructor() {
super();
this.router
.get(this.routerPath('healthz', false), async (req, res) => {
await healthController.checkHealth();
return res.status(HttpStatus.OK).json({msg: 'healthy'});
})
}

public readonly router: Router = Router();
}
4 changes: 4 additions & 0 deletions src/api/routes/index.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { MessageRouter } from './sendMessage.router';
import { SettingsRouter } from './settings.router';
import { TemplateRouter } from './template.router';
import { ViewsRouter } from './view.router';
import { HealthRouter} from './health.router';

enum HttpStatus {
OK = 200,
Expand Down Expand Up @@ -57,6 +58,8 @@ router.get('/assets/*', (req, res) => {
}
});

console.dir(new HealthRouter().router, { depth: null });

router
.use((req, res, next) => telemetry.collectTelemetry(req, res, next))

Expand All @@ -79,6 +82,7 @@ router
facebookUserToken: process.env.FACEBOOK_USER_TOKEN,
});
})
.use('', new HealthRouter().router)
.use('/instance', new InstanceRouter(configService, ...guards).router)
.use('/message', new MessageRouter(...guards).router)
.use('/call', new CallRouter(...guards).router)
Expand Down
4 changes: 4 additions & 0 deletions src/api/server.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { WAMonitoringService } from './services/monitor.service';
import { ProxyService } from './services/proxy.service';
import { SettingsService } from './services/settings.service';
import { TemplateService } from './services/template.service';
import { HealthController } from './controllers/health.controller';

const logger = new Logger('WA MODULE');

Expand Down Expand Up @@ -107,6 +108,9 @@ export const eventManager = new EventManager(prismaRepository, waMonitor);
export const chatbotController = new ChatbotController(prismaRepository, waMonitor);
export const channelController = new ChannelController(prismaRepository, waMonitor);

//Health check
export const healthController = new HealthController(waMonitor, prismaRepository);

// channels
export const evolutionController = new EvolutionController(prismaRepository, waMonitor);
export const metaController = new MetaController(prismaRepository, waMonitor);
Expand Down
5 changes: 5 additions & 0 deletions src/api/services/channel.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,11 @@ export class ChannelStartupService {
cleanedMessage.message.stickerMessage = {};
}

// Limpa LottieStickerMessage
if(cleanedMessage.message.lottieStickerMessage) {
cleanedMessage.message.lottieStickerMessage = {};
}

// Limpa documentMessage
if (cleanedMessage.message.documentMessage) {
cleanedMessage.message.documentMessage = {
Expand Down
1 change: 1 addition & 0 deletions src/api/types/wa.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ export const TypeMediaMessage = [
'audioMessage',
'videoMessage',
'stickerMessage',
'lottieStickerMessage',
'ptvMessage',
];

Expand Down