Removing code that writes in db

This commit is contained in:
Gabriel Rodrigues 2025-03-26 07:18:02 -03:00
parent e96acd7766
commit 1c6b29fbf5
4 changed files with 433 additions and 430 deletions

View File

@ -437,3 +437,6 @@ export class InstanceController {
} }
} }
} }
curl --location --request POST 'http://localhost:8080/instance/restart/IWA-67e38885218ad5f643d422bd' \
--header 'apikey: 429683C4C977415CAAFCCE10F7D57E11'

View File

@ -198,15 +198,15 @@ export class EvolutionStartupService extends ChannelStartupService {
} }
} }
await this.prismaRepository.message.create({ // await this.prismaRepository.message.create({
data: messageRaw, // data: messageRaw,
}); // });
await this.updateContact({ // await this.updateContact({
remoteJid: messageRaw.key.remoteJid, // remoteJid: messageRaw.key.remoteJid,
pushName: messageRaw.pushName, // pushName: messageRaw.pushName,
profilePicUrl: received.profilePicUrl, // profilePicUrl: received.profilePicUrl,
}); // });
} }
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
@ -517,10 +517,10 @@ export class EvolutionStartupService extends ChannelStartupService {
msg: messageRaw, msg: messageRaw,
pushName: messageRaw.pushName, pushName: messageRaw.pushName,
}); });
//
await this.prismaRepository.message.create({ // await this.prismaRepository.message.create({
data: messageRaw, // data: messageRaw,
}); // });
return messageRaw; return messageRaw;
} catch (error) { } catch (error) {

View File

@ -360,19 +360,19 @@ export class BusinessStartupService extends ChannelStartupService {
'Content-Type': mimetype, 'Content-Type': mimetype,
}); });
const createdMessage = await this.prismaRepository.message.create({ // const createdMessage = await this.prismaRepository.message.create({
data: messageRaw, // data: messageRaw,
}); // });
//
await this.prismaRepository.media.create({ // await this.prismaRepository.media.create({
data: { // data: {
messageId: createdMessage.id, // messageId: createdMessage.id,
instanceId: this.instanceId, // instanceId: this.instanceId,
type: mediaType, // type: mediaType,
fileName: fullName, // fileName: fullName,
mimetype, // mimetype,
}, // },
}); // });
const mediaUrl = await s3Service.getObjectUrl(fullName); const mediaUrl = await s3Service.getObjectUrl(fullName);
@ -511,11 +511,11 @@ export class BusinessStartupService extends ChannelStartupService {
} }
} }
if (!this.isMediaMessage(received?.messages[0])) { // if (!this.isMediaMessage(received?.messages[0])) {
await this.prismaRepository.message.create({ // await this.prismaRepository.message.create({
data: messageRaw, // data: messageRaw,
}); // });
} // }
const contact = await this.prismaRepository.contact.findFirst({ const contact = await this.prismaRepository.contact.findFirst({
where: { instanceId: this.instanceId, remoteJid: key.remoteJid }, where: { instanceId: this.instanceId, remoteJid: key.remoteJid },
@ -944,9 +944,9 @@ export class BusinessStartupService extends ChannelStartupService {
pushName: messageRaw.pushName, pushName: messageRaw.pushName,
}); });
await this.prismaRepository.message.create({ // await this.prismaRepository.message.create({
data: messageRaw, // data: messageRaw,
}); // });
return messageRaw; return messageRaw;
} catch (error) { } catch (error) {

View File

@ -651,10 +651,10 @@ export class BaileysStartupService extends ChannelStartupService {
...browserOptions, ...browserOptions,
markOnlineOnConnect: this.localSettings.alwaysOnline, markOnlineOnConnect: this.localSettings.alwaysOnline,
retryRequestDelayMs: 350, retryRequestDelayMs: 350,
maxMsgRetryCount: 4, maxMsgRetryCount: 10,
fireInitQueries: true, fireInitQueries: true,
connectTimeoutMs: 30_000, connectTimeoutMs: 30_000,
keepAliveIntervalMs: 30_000, keepAliveIntervalMs: 60 * 60 * 1000, //1 hour
qrTimeout: 45_000, qrTimeout: 45_000,
emitOwnEvents: false, emitOwnEvents: false,
shouldIgnoreJid: (jid) => { shouldIgnoreJid: (jid) => {
@ -664,7 +664,7 @@ export class BaileysStartupService extends ChannelStartupService {
return isGroupJid || isBroadcast || isNewsletter; return isGroupJid || isBroadcast || isNewsletter;
}, },
syncFullHistory: this.localSettings.syncFullHistory, syncFullHistory: this.localSettings.syncFullHistory,
shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => { shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => {
return this.historySyncNotification(msg); return this.historySyncNotification(msg);
}, },
@ -944,12 +944,12 @@ export class BaileysStartupService extends ChannelStartupService {
private readonly messageHandle = { private readonly messageHandle = {
'messaging-history.set': async ({ 'messaging-history.set': async ({
messages, // messages,
chats, // chats,
contacts, // contacts,
isLatest, // isLatest,
progress, // progress,
syncType, // syncType,
}: { }: {
chats: Chat[]; chats: Chat[];
contacts: Contact[]; contacts: Contact[];
@ -958,143 +958,143 @@ export class BaileysStartupService extends ChannelStartupService {
progress?: number; progress?: number;
syncType?: proto.HistorySync.HistorySyncType; syncType?: proto.HistorySync.HistorySyncType;
}) => { }) => {
try { // try {
if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) { // if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) {
console.log('received on-demand history sync, messages=', messages); // console.log('received on-demand history sync, messages=', messages);
} // }
console.log( // console.log(
`recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`, // `recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`,
); // );
//
const instance: InstanceDto = { instanceName: this.instance.name }; // const instance: InstanceDto = { instanceName: this.instance.name };
//
let timestampLimitToImport = null; // let timestampLimitToImport = null;
//
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) { // if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
const daysLimitToImport = this.localChatwoot?.enabled ? this.localChatwoot.daysLimitImportMessages : 1000; // const daysLimitToImport = this.localChatwoot?.enabled ? this.localChatwoot.daysLimitImportMessages : 1000;
//
const date = new Date(); // const date = new Date();
timestampLimitToImport = new Date(date.setDate(date.getDate() - daysLimitToImport)).getTime() / 1000; // timestampLimitToImport = new Date(date.setDate(date.getDate() - daysLimitToImport)).getTime() / 1000;
//
const maxBatchTimestamp = Math.max(...messages.map((message) => message.messageTimestamp as number)); // const maxBatchTimestamp = Math.max(...messages.map((message) => message.messageTimestamp as number));
//
const processBatch = maxBatchTimestamp >= timestampLimitToImport; // const processBatch = maxBatchTimestamp >= timestampLimitToImport;
//
if (!processBatch) { // if (!processBatch) {
return; // return;
} // }
} // }
//
const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = []; // const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = [];
const chatsRepository = new Set( // const chatsRepository = new Set(
( // (
await this.prismaRepository.chat.findMany({ // await this.prismaRepository.chat.findMany({
where: { instanceId: this.instanceId }, // where: { instanceId: this.instanceId },
}) // })
).map((chat) => chat.remoteJid), // ).map((chat) => chat.remoteJid),
); // );
//
for (const chat of chats) { // for (const chat of chats) {
if (chatsRepository?.has(chat.id)) { // if (chatsRepository?.has(chat.id)) {
continue; // continue;
} // }
//
chatsRaw.push({ // chatsRaw.push({
remoteJid: chat.id, // remoteJid: chat.id,
instanceId: this.instanceId, // instanceId: this.instanceId,
name: chat.name, // name: chat.name,
}); // });
} // }
//
this.sendDataWebhook(Events.CHATS_SET, chatsRaw); // this.sendDataWebhook(Events.CHATS_SET, chatsRaw);
//
if (this.configService.get<Database>('DATABASE').SAVE_DATA.HISTORIC) { // if (this.configService.get<Database>('DATABASE').SAVE_DATA.HISTORIC) {
await this.prismaRepository.chat.createMany({ // await this.prismaRepository.chat.createMany({
data: chatsRaw, // data: chatsRaw,
skipDuplicates: true, // skipDuplicates: true,
}); // });
} // }
//
const messagesRaw: any[] = []; // const messagesRaw: any[] = [];
//
const messagesRepository: Set<string> = new Set( // const messagesRepository: Set<string> = new Set(
chatwootImport.getRepositoryMessagesCache(instance) ?? // chatwootImport.getRepositoryMessagesCache(instance) ??
( // (
await this.prismaRepository.message.findMany({ // await this.prismaRepository.message.findMany({
select: { key: true }, // select: { key: true },
where: { instanceId: this.instanceId }, // where: { instanceId: this.instanceId },
}) // })
).map((message) => { // ).map((message) => {
const key = message.key as { // const key = message.key as {
id: string; // id: string;
}; // };
//
return key.id; // return key.id;
}), // }),
); // );
//
if (chatwootImport.getRepositoryMessagesCache(instance) === null) { // if (chatwootImport.getRepositoryMessagesCache(instance) === null) {
chatwootImport.setRepositoryMessagesCache(instance, messagesRepository); // chatwootImport.setRepositoryMessagesCache(instance, messagesRepository);
} // }
//
for (const m of messages) { // for (const m of messages) {
if (!m.message || !m.key || !m.messageTimestamp) { // if (!m.message || !m.key || !m.messageTimestamp) {
continue; // continue;
} // }
//
if (Long.isLong(m?.messageTimestamp)) { // if (Long.isLong(m?.messageTimestamp)) {
m.messageTimestamp = m.messageTimestamp?.toNumber(); // m.messageTimestamp = m.messageTimestamp?.toNumber();
} // }
//
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) { // if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
if (m.messageTimestamp <= timestampLimitToImport) { // if (m.messageTimestamp <= timestampLimitToImport) {
continue; // continue;
} // }
} // }
//
if (messagesRepository?.has(m.key.id)) { // if (messagesRepository?.has(m.key.id)) {
continue; // continue;
} // }
//
messagesRaw.push(this.prepareMessage(m)); // messagesRaw.push(this.prepareMessage(m));
} // }
//
this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]); // this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]);
//
if (this.configService.get<Database>('DATABASE').SAVE_DATA.HISTORIC) { // if (this.configService.get<Database>('DATABASE').SAVE_DATA.HISTORIC) {
await this.prismaRepository.message.createMany({ // await this.prismaRepository.message.createMany({
data: messagesRaw, // data: messagesRaw,
skipDuplicates: true, // skipDuplicates: true,
}); // });
} // }
//
if ( // if (
this.configService.get<Chatwoot>('CHATWOOT').ENABLED && // this.configService.get<Chatwoot>('CHATWOOT').ENABLED &&
this.localChatwoot?.enabled && // this.localChatwoot?.enabled &&
this.localChatwoot.importMessages && // this.localChatwoot.importMessages &&
messagesRaw.length > 0 // messagesRaw.length > 0
) { // ) {
this.chatwootService.addHistoryMessages( // this.chatwootService.addHistoryMessages(
instance, // instance,
messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)), // messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)),
); // );
} // }
//
await this.contactHandle['contacts.upsert']( // await this.contactHandle['contacts.upsert'](
contacts // contacts
.filter((c) => !!c.notify || !!c.name) // .filter((c) => !!c.notify || !!c.name)
.map((c) => ({ // .map((c) => ({
id: c.id, // id: c.id,
name: c.name ?? c.notify, // name: c.name ?? c.notify,
})), // })),
); // );
//
contacts = undefined; // contacts = undefined;
messages = undefined; // messages = undefined;
chats = undefined; // chats = undefined;
} catch (error) { // } catch (error) {
this.logger.error(error); // this.logger.error(error);
} // }
}, },
'messages.upsert': async ( 'messages.upsert': async (
@ -1122,26 +1122,26 @@ export class BaileysStartupService extends ChannelStartupService {
console.log('Message received from phone, id=', requestId, received); console.log('Message received from phone, id=', requestId, received);
} }
if (text == 'onDemandHistSync') { // if (text == 'onDemandHistSync') {
const messageId = await this.client.fetchMessageHistory(50, received.key, received.messageTimestamp!); // const messageId = await this.client.fetchMessageHistory(50, received.key, received.messageTimestamp!);
console.log('requested on-demand sync, id=', messageId); // console.log('requested on-demand sync, id=', messageId);
} // }
} }
if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { // if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) {
const editedMessage = // const editedMessage =
received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; // received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage;
if (editedMessage) { // if (editedMessage) {
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) // if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled)
this.chatwootService.eventWhatsapp( // this.chatwootService.eventWhatsapp(
'messages.edit', // 'messages.edit',
{ instanceName: this.instance.name, instanceId: this.instance.id }, // { instanceName: this.instance.name, instanceId: this.instance.id },
editedMessage, // editedMessage,
); // );
//
await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage); // await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage);
} // }
} // }
if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') { if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') {
this.logger.info(`Recovering message lost messageId: ${received.key.id}`); this.logger.info(`Recovering message lost messageId: ${received.key.id}`);
@ -1174,32 +1174,32 @@ export class BaileysStartupService extends ChannelStartupService {
received.messageTimestamp = received.messageTimestamp?.toNumber(); received.messageTimestamp = received.messageTimestamp?.toNumber();
} }
if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) { // if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) {
continue; // continue;
} // }
const existingChat = await this.prismaRepository.chat.findFirst({ // const existingChat = await this.prismaRepository.chat.findFirst({
where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid }, // where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid },
select: { id: true, name: true }, // select: { id: true, name: true },
}); // });
if ( // if (
existingChat && // existingChat &&
received.pushName && // received.pushName &&
existingChat.name !== received.pushName && // existingChat.name !== received.pushName &&
received.pushName.trim().length > 0 // received.pushName.trim().length > 0
) { // ) {
this.sendDataWebhook(Events.CHATS_UPSERT, [{ ...existingChat, name: received.pushName }]); // this.sendDataWebhook(Events.CHATS_UPSERT, [{ ...existingChat, name: received.pushName }]);
if (this.configService.get<Database>('DATABASE').SAVE_DATA.CHATS) { // if (this.configService.get<Database>('DATABASE').SAVE_DATA.CHATS) {
try { // try {
await this.prismaRepository.chat.update({ // await this.prismaRepository.chat.update({
where: { id: existingChat.id }, // where: { id: existingChat.id },
data: { name: received.pushName }, // data: { name: received.pushName },
}); // });
} catch (error) { // } catch (error) {
console.log(`Chat insert record ignored: ${received.key.remoteJid} - ${this.instanceId}`); // console.log(`Chat insert record ignored: ${received.key.remoteJid} - ${this.instanceId}`);
} // }
} // }
} // }
const messageRaw = this.prepareMessage(received); const messageRaw = this.prepareMessage(received);
@ -1220,107 +1220,107 @@ export class BaileysStartupService extends ChannelStartupService {
await this.client.readMessages([received.key]); await this.client.readMessages([received.key]);
} }
if ( // if (
this.configService.get<Chatwoot>('CHATWOOT').ENABLED && // this.configService.get<Chatwoot>('CHATWOOT').ENABLED &&
this.localChatwoot?.enabled && // this.localChatwoot?.enabled &&
!received.key.id.includes('@broadcast') // !received.key.id.includes('@broadcast')
) { // ) {
const chatwootSentMessage = await this.chatwootService.eventWhatsapp( // const chatwootSentMessage = await this.chatwootService.eventWhatsapp(
Events.MESSAGES_UPSERT, // Events.MESSAGES_UPSERT,
{ instanceName: this.instance.name, instanceId: this.instance.id }, // { instanceName: this.instance.name, instanceId: this.instance.id },
messageRaw, // messageRaw,
); // );
//
// if (chatwootSentMessage?.id) {
// messageRaw.chatwootMessageId = chatwootSentMessage.id;
// messageRaw.chatwootInboxId = chatwootSentMessage.inbox_id;
// messageRaw.chatwootConversationId = chatwootSentMessage.conversation_id;
// }
// }
if (chatwootSentMessage?.id) { // if (this.configService.get<Openai>('OPENAI').ENABLED && received?.message?.audioMessage) {
messageRaw.chatwootMessageId = chatwootSentMessage.id; // const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({
messageRaw.chatwootInboxId = chatwootSentMessage.inbox_id; // where: {
messageRaw.chatwootConversationId = chatwootSentMessage.conversation_id; // instanceId: this.instanceId,
} // },
} // include: {
// OpenaiCreds: true,
// },
// });
//
// if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) {
// messageRaw.message.speechToText = await this.openaiService.speechToText(
// openAiDefaultSettings.OpenaiCreds,
// received,
// this.client.updateMediaMessage,
// );
// }
// }
if (this.configService.get<Openai>('OPENAI').ENABLED && received?.message?.audioMessage) { // if (this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ // const msg = await this.prismaRepository.message.create({
where: { // data: messageRaw,
instanceId: this.instanceId, // });
}, //
include: { // if (received.key.fromMe === false) {
OpenaiCreds: true, // if (msg.status === status[3]) {
}, // this.logger.log(`Update not read messages ${received.key.remoteJid}`);
}); //
// await this.updateChatUnreadMessages(received.key.remoteJid);
if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { // } else if (msg.status === status[4]) {
messageRaw.message.speechToText = await this.openaiService.speechToText( // this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`);
openAiDefaultSettings.OpenaiCreds, //
received, // await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp);
this.client.updateMediaMessage, // }
); // } else {
} // // is send message by me
} // this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`);
//
if (this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) { // await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp);
const msg = await this.prismaRepository.message.create({ // }
data: messageRaw, //
}); // if (isMedia) {
// if (this.configService.get<S3>('S3').ENABLE) {
if (received.key.fromMe === false) { // try {
if (msg.status === status[3]) { // const message: any = received;
this.logger.log(`Update not read messages ${received.key.remoteJid}`); // const media = await this.getBase64FromMediaMessage(
// {
await this.updateChatUnreadMessages(received.key.remoteJid); // message,
} else if (msg.status === status[4]) { // },
this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); // true,
// );
await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); //
} // const { buffer, mediaType, fileName, size } = media;
} else { // const mimetype = mimeTypes.lookup(fileName).toString();
// is send message by me // const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName);
this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); // await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, {
// 'Content-Type': mimetype,
await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); // });
} //
// await this.prismaRepository.media.create({
if (isMedia) { // data: {
if (this.configService.get<S3>('S3').ENABLE) { // messageId: msg.id,
try { // instanceId: this.instanceId,
const message: any = received; // type: mediaType,
const media = await this.getBase64FromMediaMessage( // fileName: fullName,
{ // mimetype,
message, // },
}, // });
true, //
); // const mediaUrl = await s3Service.getObjectUrl(fullName);
//
const { buffer, mediaType, fileName, size } = media; // messageRaw.message.mediaUrl = mediaUrl;
const mimetype = mimeTypes.lookup(fileName).toString(); //
const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); // await this.prismaRepository.message.update({
await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { // where: { id: msg.id },
'Content-Type': mimetype, // data: messageRaw,
}); // });
// } catch (error) {
await this.prismaRepository.media.create({ // this.logger.error(['Error on upload file to minio', error?.message, error?.stack]);
data: { // }
messageId: msg.id, // }
instanceId: this.instanceId, // }
type: mediaType, // }
fileName: fullName,
mimetype,
},
});
const mediaUrl = await s3Service.getObjectUrl(fullName);
messageRaw.message.mediaUrl = mediaUrl;
await this.prismaRepository.message.update({
where: { id: msg.id },
data: messageRaw,
});
} catch (error) {
this.logger.error(['Error on upload file to minio', error?.message, error?.stack]);
}
}
}
}
if (this.localWebhook.enabled) { if (this.localWebhook.enabled) {
if (isMedia && this.localWebhook.webhookBase64) { if (isMedia && this.localWebhook.webhookBase64) {
@ -1346,66 +1346,66 @@ export class BaileysStartupService extends ChannelStartupService {
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
await chatbotController.emit({ // await chatbotController.emit({
instance: { instanceName: this.instance.name, instanceId: this.instanceId }, // instance: { instanceName: this.instance.name, instanceId: this.instanceId },
remoteJid: messageRaw.key.remoteJid, // remoteJid: messageRaw.key.remoteJid,
msg: messageRaw, // msg: messageRaw,
pushName: messageRaw.pushName, // pushName: messageRaw.pushName,
}); // });
//
// const contact = await this.prismaRepository.contact.findFirst({
// where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId },
// });
//
// const contactRaw: { remoteJid: string; pushName: string; profilePicUrl?: string; instanceId: string } = {
// remoteJid: received.key.remoteJid,
// pushName: received.key.fromMe ? '' : received.key.fromMe == null ? '' : received.pushName,
// profilePicUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
// instanceId: this.instanceId,
// };
const contact = await this.prismaRepository.contact.findFirst({ // if (contactRaw.remoteJid === 'status@broadcast') {
where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId }, // continue;
}); // }
const contactRaw: { remoteJid: string; pushName: string; profilePicUrl?: string; instanceId: string } = { // if (contact) {
remoteJid: received.key.remoteJid, // this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw);
pushName: received.key.fromMe ? '' : received.key.fromMe == null ? '' : received.pushName, //
profilePicUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl, // if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) {
instanceId: this.instanceId, // await this.chatwootService.eventWhatsapp(
}; // Events.CONTACTS_UPDATE,
// { instanceName: this.instance.name, instanceId: this.instanceId },
// contactRaw,
// );
// }
//
// if (this.configService.get<Database>('DATABASE').SAVE_DATA.CONTACTS)
// await this.prismaRepository.contact.upsert({
// where: { remoteJid_instanceId: { remoteJid: contactRaw.remoteJid, instanceId: contactRaw.instanceId } },
// create: contactRaw,
// update: contactRaw,
// });
//
// continue;
// }
if (contactRaw.remoteJid === 'status@broadcast') { // this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
continue;
}
if (contact) { // if (this.configService.get<Database>('DATABASE').SAVE_DATA.CONTACTS)
this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); // await this.prismaRepository.contact.upsert({
// where: {
// remoteJid_instanceId: {
// remoteJid: contactRaw.remoteJid,
// instanceId: contactRaw.instanceId,
// },
// },
// update: contactRaw,
// create: contactRaw,
// });
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { // if (contactRaw.remoteJid.includes('@s.whatsapp')) {
await this.chatwootService.eventWhatsapp( // await saveOnWhatsappCache([{ remoteJid: contactRaw.remoteJid }]);
Events.CONTACTS_UPDATE, // }
{ instanceName: this.instance.name, instanceId: this.instanceId },
contactRaw,
);
}
if (this.configService.get<Database>('DATABASE').SAVE_DATA.CONTACTS)
await this.prismaRepository.contact.upsert({
where: { remoteJid_instanceId: { remoteJid: contactRaw.remoteJid, instanceId: contactRaw.instanceId } },
create: contactRaw,
update: contactRaw,
});
continue;
}
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
if (this.configService.get<Database>('DATABASE').SAVE_DATA.CONTACTS)
await this.prismaRepository.contact.upsert({
where: {
remoteJid_instanceId: {
remoteJid: contactRaw.remoteJid,
instanceId: contactRaw.instanceId,
},
},
update: contactRaw,
create: contactRaw,
});
if (contactRaw.remoteJid.includes('@s.whatsapp')) {
await saveOnWhatsappCache([{ remoteJid: contactRaw.remoteJid }]);
}
} }
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
@ -2241,60 +2241,60 @@ export class BaileysStartupService extends ChannelStartupService {
} }
} }
if (this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) { // if (this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
const msg = await this.prismaRepository.message.create({ // const msg = await this.prismaRepository.message.create({
data: messageRaw, // data: messageRaw,
}); // });
//
if (isMedia && this.configService.get<S3>('S3').ENABLE) { // if (isMedia && this.configService.get<S3>('S3').ENABLE) {
try { // try {
const message: any = messageRaw; // const message: any = messageRaw;
const media = await this.getBase64FromMediaMessage( // const media = await this.getBase64FromMediaMessage(
{ // {
message, // message,
}, // },
true, // true,
); // );
//
const { buffer, mediaType, fileName, size } = media; // const { buffer, mediaType, fileName, size } = media;
//
const mimetype = mimeTypes.lookup(fileName).toString(); // const mimetype = mimeTypes.lookup(fileName).toString();
//
const fullName = join( // const fullName = join(
`${this.instance.id}`, // `${this.instance.id}`,
messageRaw.key.remoteJid, // messageRaw.key.remoteJid,
`${messageRaw.key.id}`, // `${messageRaw.key.id}`,
mediaType, // mediaType,
fileName, // fileName,
); // );
//
await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { // await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, {
'Content-Type': mimetype, // 'Content-Type': mimetype,
}); // });
//
await this.prismaRepository.media.create({ // await this.prismaRepository.media.create({
data: { // data: {
messageId: msg.id, // messageId: msg.id,
instanceId: this.instanceId, // instanceId: this.instanceId,
type: mediaType, // type: mediaType,
fileName: fullName, // fileName: fullName,
mimetype, // mimetype,
}, // },
}); // });
//
const mediaUrl = await s3Service.getObjectUrl(fullName); // const mediaUrl = await s3Service.getObjectUrl(fullName);
//
messageRaw.message.mediaUrl = mediaUrl; // messageRaw.message.mediaUrl = mediaUrl;
//
await this.prismaRepository.message.update({ // await this.prismaRepository.message.update({
where: { id: msg.id }, // where: { id: msg.id },
data: messageRaw, // data: messageRaw,
}); // });
} catch (error) { // } catch (error) {
this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); // this.logger.error(['Error on upload file to minio', error?.message, error?.stack]);
} // }
} // }
} // }
if (this.localWebhook.enabled) { if (this.localWebhook.enabled) {
if (isMedia && this.localWebhook.webhookBase64) { if (isMedia && this.localWebhook.webhookBase64) {