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

View File

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

View File

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