Skip to content

Adicionando rota de download de midia em base64 ou buffer #4

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 1 commit into
base: develop
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions src/api/controllers/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ArchiveChatDto,
BlockUserDto,
DeleteMessage,
DownloadMediaMessageDto,
getBase64FromMediaMessageDto,
MarkChatUnreadDto,
NumberDto,
Expand Down Expand Up @@ -82,6 +83,10 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data);
}

public async downloadMediaMessage({ instanceName }: InstanceDto, data: DownloadMediaMessageDto) {
return await this.waMonitor.waInstances[instanceName].downloadMediaMessage(data);
}

public async fetchBusinessProfile({ instanceName }: InstanceDto, data: ProfilePictureDto) {
return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(data.number);
}
Expand Down
9 changes: 9 additions & 0 deletions src/api/dto/chat.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
DownloadableMessage,
MediaType,
proto,
WAPresence,
WAPrivacyGroupAddValue,
Expand Down Expand Up @@ -94,6 +96,13 @@ export class PrivacySettingDto {
groupadd: WAPrivacyGroupAddValue;
}

export class DownloadMediaMessageDto {
downloadableMessage: DownloadableMessage;
type: MediaType;
timeout?: number;
returnType?: 'base64' | 'buffer' = 'buffer';
}

export class DeleteMessage {
id: string;
fromMe: boolean;
Expand Down
25 changes: 25 additions & 0 deletions src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ArchiveChatDto,
BlockUserDto,
DeleteMessage,
DownloadMediaMessageDto,
getBase64FromMediaMessageDto,
LastMessage,
MarkChatUnreadDto,
Expand Down Expand Up @@ -77,6 +78,7 @@ import { Instance } from '@prisma/client';
import { createJid } from '@utils/createJid';
import { makeProxyAgent } from '@utils/makeProxyAgent';
import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache';
import { readStreamWithTimeout } from '@utils/readStreamWithTimeout';
import { status } from '@utils/renderStatus';
import useMultiFileAuthStatePrisma from '@utils/use-multi-file-auth-state-prisma';
import { AuthStateProvider } from '@utils/use-multi-file-auth-state-provider-files';
Expand All @@ -92,6 +94,7 @@ import makeWASocket, {
Contact,
delay,
DisconnectReason,
downloadContentFromMessage,
downloadMediaMessage,
fetchLatestBaileysVersion,
generateWAMessageFromContent,
Expand Down Expand Up @@ -3133,6 +3136,28 @@ export class BaileysStartupService extends ChannelStartupService {
}
}

public async downloadMediaMessage(downloadMedia: DownloadMediaMessageDto) {
try {
const media = await downloadContentFromMessage(
{
...downloadMedia.downloadableMessage,
},
downloadMedia.type,
);

const buffer = await readStreamWithTimeout(media, downloadMedia.timeout);

if (downloadMedia.returnType === 'base64') {
const base64Data = buffer.toString('base64');
return base64Data;
}

return buffer;
} catch (error) {
throw new InternalServerErrorException('Error downloading media message', error.toString());
}
}

public async fetchBusinessProfile(number: string): Promise<NumberBusiness> {
try {
const jid = number ? createJid(number) : this.instance.wuid;
Expand Down
12 changes: 12 additions & 0 deletions src/api/routes/chat.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ArchiveChatDto,
BlockUserDto,
DeleteMessage,
DownloadMediaMessageDto,
getBase64FromMediaMessageDto,
MarkChatUnreadDto,
NumberDto,
Expand All @@ -24,6 +25,7 @@ import {
blockUserSchema,
contactValidateSchema,
deleteMessageSchema,
downloadMediaMessageSchema,
markChatUnreadSchema,
messageUpSchema,
messageValidateSchema,
Expand Down Expand Up @@ -267,6 +269,16 @@ export class ChatRouter extends RouterBroker {
});

return res.status(HttpStatus.CREATED).json(response);
})
.post(this.routerPath('downloadMediaMessage'), ...guards, async (req, res) => {
const response = await this.dataValidate<DownloadMediaMessageDto>({
request: req,
schema: downloadMediaMessageSchema,
ClassRef: DownloadMediaMessageDto,
execute: (instance, data) => chatController.downloadMediaMessage(instance, data),
});

return res.status(HttpStatus.OK).json(response);
});
}

Expand Down
22 changes: 22 additions & 0 deletions src/utils/readStreamWithTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { promisify } from 'util';

export async function readStreamWithTimeout(stream: any, timeout: number = 30_000) {
const setTimeoutPromise = promisify(setTimeout);

let buffer = Buffer.from([]);
const chunks = [];
const timer: any = setTimeoutPromise(timeout).then(() => {
stream.destroy(new Error('Stream timeout'));
});

try {
for await (const chunk of stream) {
chunks.push(chunk);
}
buffer = Buffer.concat(chunks);
} finally {
clearTimeout(timer);
}

return buffer;
}
20 changes: 20 additions & 0 deletions src/validate/chat.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,26 @@ export const privacySettingsSchema: JSONSchema7 = {
...isNotEmpty('readreceipts', 'profile', 'status', 'online', 'last', 'groupadd'),
};

export const downloadMediaMessageSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
downloadableMessage: {
type: 'object',
properties: {
url: { type: 'string' },
mediaKey: { type: 'string' },
directPath: { type: 'string' },
},
...isNotEmpty('url', 'mediaKey', 'directPath'),
},
type: { type: 'string', enum: ['image', 'video', 'audio', 'document', 'sticker', 'ptt'] },
timeout: { type: 'number', default: 30_000 },
returnType: { type: 'string', enum: ['base64', 'buffer'], default: 'buffer' },
},
...isNotEmpty('downloadableMessage', 'type'),
};

export const profileNameSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
Expand Down