diff --git a/CHANGELOG.md b/CHANGELOG.md index ca2885d0..41d3bb85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ * Adjusted set in webhook to go empty when enabled false * Adjust in store files * Fixed the problem when do not save contacts when receive messages +* Changed owner of the jid for instanceName # 1.1.3 (2023-07-06 11:43) diff --git a/src/whatsapp/repository/auth.repository.ts b/src/whatsapp/repository/auth.repository.ts index 4b6d4d00..c795737c 100644 --- a/src/whatsapp/repository/auth.repository.ts +++ b/src/whatsapp/repository/auth.repository.ts @@ -4,7 +4,7 @@ import { IInsert, Repository } from '../abstract/abstract.repository'; import { IAuthModel, AuthRaw } from '../models'; import { readFileSync } from 'fs'; import { AUTH_DIR } from '../../config/path.config'; -import { InstanceDto } from '../dto/instance.dto'; +import { Logger } from '../../config/logger.config'; export class AuthRepository extends Repository { constructor( @@ -16,24 +16,35 @@ export class AuthRepository extends Repository { } private readonly auth: Auth; + private readonly logger = new Logger('AuthRepository'); public async create(data: AuthRaw, instance: string): Promise { try { + this.logger.verbose('creating auth'); if (this.dbSettings.ENABLED) { + this.logger.verbose('saving auth to db'); const insert = await this.authModel.replaceOne( { _id: instance }, { ...data }, { upsert: true }, ); + + this.logger.verbose('auth saved to db: ' + insert.modifiedCount + ' auth'); return { insertCount: insert.modifiedCount }; } + this.logger.verbose('saving auth to store'); + this.writeStore({ path: join(AUTH_DIR, this.auth.TYPE), fileName: instance, data, }); + this.logger.verbose( + 'auth saved to store in path: ' + join(AUTH_DIR, this.auth.TYPE) + '/' + instance, + ); + this.logger.verbose('auth created'); return { insertCount: 1 }; } catch (error) { return { error } as any; @@ -42,10 +53,14 @@ export class AuthRepository extends Repository { public async find(instance: string): Promise { try { + this.logger.verbose('finding auth'); if (this.dbSettings.ENABLED) { + this.logger.verbose('finding auth in db'); return await this.authModel.findOne({ _id: instance }); } + this.logger.verbose('finding auth in store'); + return JSON.parse( readFileSync(join(AUTH_DIR, this.auth.TYPE, instance + '.json'), { encoding: 'utf-8', diff --git a/src/whatsapp/repository/chat.repository.ts b/src/whatsapp/repository/chat.repository.ts index f717ae2f..0f05760c 100644 --- a/src/whatsapp/repository/chat.repository.ts +++ b/src/whatsapp/repository/chat.repository.ts @@ -3,6 +3,7 @@ import { ConfigService, StoreConf } from '../../config/env.config'; import { IInsert, Repository } from '../abstract/abstract.repository'; import { opendirSync, readFileSync, rmSync } from 'fs'; import { ChatRaw, IChatModel } from '../models'; +import { Logger } from '../../config/logger.config'; export class ChatQuery { where: ChatRaw; @@ -16,35 +17,54 @@ export class ChatRepository extends Repository { super(configService); } + private readonly logger = new Logger('ChatRepository'); + public async insert( data: ChatRaw[], instanceName: string, saveDb = false, ): Promise { + this.logger.verbose('inserting chats'); if (data.length === 0) { + this.logger.verbose('no chats to insert'); return; } try { + this.logger.verbose('saving chats to store'); if (this.dbSettings.ENABLED && saveDb) { + this.logger.verbose('saving chats to db'); const insert = await this.chatModel.insertMany([...data]); + + this.logger.verbose('chats saved to db: ' + insert.length + ' chats'); return { insertCount: insert.length }; } + this.logger.verbose('saving chats to store'); + const store = this.configService.get('STORE'); if (store.CHATS) { + this.logger.verbose('saving chats to store'); data.forEach((chat) => { this.writeStore({ path: join(this.storePath, 'chats', instanceName), fileName: chat.id, data: chat, }); + this.logger.verbose( + 'chats saved to store in path: ' + + join(this.storePath, 'chats', instanceName) + + '/' + + chat.id, + ); }); + this.logger.verbose('chats saved to store'); return { insertCount: data.length }; } + this.logger.verbose('chats not saved to store'); return { insertCount: 0 }; } catch (error) { return error; @@ -55,10 +75,14 @@ export class ChatRepository extends Repository { public async find(query: ChatQuery): Promise { try { + this.logger.verbose('finding chats'); if (this.dbSettings.ENABLED) { + this.logger.verbose('finding chats in db'); return await this.chatModel.find({ owner: query.where.owner }); } + this.logger.verbose('finding chats in store'); + const chats: ChatRaw[] = []; const openDir = opendirSync(join(this.storePath, 'chats', query.where.owner)); for await (const dirent of openDir) { @@ -74,6 +98,7 @@ export class ChatRepository extends Repository { } } + this.logger.verbose('chats found in store: ' + chats.length + ' chats'); return chats; } catch (error) { return []; @@ -82,10 +107,13 @@ export class ChatRepository extends Repository { public async delete(query: ChatQuery) { try { + this.logger.verbose('deleting chats'); if (this.dbSettings.ENABLED) { + this.logger.verbose('deleting chats in db'); return await this.chatModel.deleteOne({ ...query.where }); } + this.logger.verbose('deleting chats in store'); rmSync(join(this.storePath, 'chats', query.where.owner, query.where.id + '.josn'), { force: true, recursive: true, diff --git a/src/whatsapp/repository/contact.repository.ts b/src/whatsapp/repository/contact.repository.ts index 67c51dff..648b5bf4 100644 --- a/src/whatsapp/repository/contact.repository.ts +++ b/src/whatsapp/repository/contact.repository.ts @@ -3,6 +3,7 @@ import { join } from 'path'; import { ConfigService, StoreConf } from '../../config/env.config'; import { ContactRaw, IContactModel } from '../models'; import { IInsert, Repository } from '../abstract/abstract.repository'; +import { Logger } from '../../config/logger.config'; export class ContactQuery { where: ContactRaw; @@ -16,35 +17,55 @@ export class ContactRepository extends Repository { super(configService); } + private readonly logger = new Logger('ContactRepository'); + public async insert( data: ContactRaw[], instanceName: string, saveDb = false, ): Promise { + this.logger.verbose('inserting contacts'); + if (data.length === 0) { + this.logger.verbose('no contacts to insert'); return; } try { if (this.dbSettings.ENABLED && saveDb) { + this.logger.verbose('saving contacts to db'); + const insert = await this.contactModel.insertMany([...data]); + + this.logger.verbose('contacts saved to db: ' + insert.length + ' contacts'); return { insertCount: insert.length }; } + this.logger.verbose('saving contacts to store'); + const store = this.configService.get('STORE'); if (store.CONTACTS) { + this.logger.verbose('saving contacts to store'); data.forEach((contact) => { this.writeStore({ path: join(this.storePath, 'contacts', instanceName), fileName: contact.id, data: contact, }); + this.logger.verbose( + 'contacts saved to store in path: ' + + join(this.storePath, 'contacts', instanceName) + + '/' + + contact.id, + ); }); + this.logger.verbose('contacts saved to store: ' + data.length + ' contacts'); return { insertCount: data.length }; } + this.logger.verbose('contacts not saved'); return { insertCount: 0 }; } catch (error) { return error; @@ -54,31 +75,63 @@ export class ContactRepository extends Repository { } public async update( - data: ContactRaw, + data: ContactRaw[], instanceName: string, saveDb = false, ): Promise { try { - if (this.dbSettings.ENABLED && saveDb) { - const contact = await this.contactModel.findOneAndUpdate( - { id: data.id }, - { ...data }, - ); - return { insertCount: contact ? 1 : 0 }; + this.logger.verbose('updating contacts'); + + if (data.length === 0) { + this.logger.verbose('no contacts to update'); + return; } + if (this.dbSettings.ENABLED && saveDb) { + this.logger.verbose('updating contacts in db'); + + const contacts = data.map((contact) => { + return { + updateOne: { + filter: { id: contact.id }, + update: { ...contact }, + upsert: true, + }, + }; + }); + + const { nModified } = await this.contactModel.bulkWrite(contacts); + + this.logger.verbose('contacts updated in db: ' + nModified + ' contacts'); + return { insertCount: nModified }; + } + + this.logger.verbose('updating contacts in store'); + const store = this.configService.get('STORE'); if (store.CONTACTS) { - this.writeStore({ - path: join(this.storePath, 'contacts', instanceName), - fileName: data.id, - data, + this.logger.verbose('updating contacts in store'); + data.forEach((contact) => { + this.writeStore({ + path: join(this.storePath, 'contacts', instanceName), + fileName: contact.id, + data: contact, + }); + this.logger.verbose( + 'contacts updated in store in path: ' + + join(this.storePath, 'contacts', instanceName) + + '/' + + contact.id, + ); }); - return { insertCount: 1 }; + this.logger.verbose('contacts updated in store: ' + data.length + ' contacts'); + + return { insertCount: data.length }; } + this.logger.verbose('contacts not updated'); return { insertCount: 0 }; } catch (error) { return error; @@ -89,11 +142,16 @@ export class ContactRepository extends Repository { public async find(query: ContactQuery): Promise { try { + this.logger.verbose('finding contacts'); if (this.dbSettings.ENABLED) { + this.logger.verbose('finding contacts in db'); return await this.contactModel.find({ ...query.where }); } + + this.logger.verbose('finding contacts in store'); const contacts: ContactRaw[] = []; if (query?.where?.id) { + this.logger.verbose('finding contacts in store by id'); contacts.push( JSON.parse( readFileSync( @@ -108,6 +166,8 @@ export class ContactRepository extends Repository { ), ); } else { + this.logger.verbose('finding contacts in store by owner'); + const openDir = opendirSync(join(this.storePath, 'contacts', query.where.owner), { encoding: 'utf-8', }); @@ -124,6 +184,8 @@ export class ContactRepository extends Repository { } } } + + this.logger.verbose('contacts found in store: ' + contacts.length + ' contacts'); return contacts; } catch (error) { return []; diff --git a/src/whatsapp/repository/message.repository.ts b/src/whatsapp/repository/message.repository.ts index 4da56e8a..dbfe01fc 100644 --- a/src/whatsapp/repository/message.repository.ts +++ b/src/whatsapp/repository/message.repository.ts @@ -3,6 +3,7 @@ import { join } from 'path'; import { IMessageModel, MessageRaw } from '../models'; import { IInsert, Repository } from '../abstract/abstract.repository'; import { opendirSync, readFileSync } from 'fs'; +import { Logger } from '../../config/logger.config'; export class MessageQuery { where: MessageRaw; @@ -17,17 +18,23 @@ export class MessageRepository extends Repository { super(configService); } + private readonly logger = new Logger('MessageRepository'); + public async insert( data: MessageRaw[], instanceName: string, saveDb = false, ): Promise { + this.logger.verbose('inserting messages'); + if (!Array.isArray(data) || data.length === 0) { + this.logger.verbose('no messages to insert'); return; } try { if (this.dbSettings.ENABLED && saveDb) { + this.logger.verbose('saving messages to db'); const cleanedData = data.map((obj) => { const cleanedObj = { ...obj }; if ('extendedTextMessage' in obj.message) { @@ -48,23 +55,37 @@ export class MessageRepository extends Repository { }); const insert = await this.messageModel.insertMany([...cleanedData]); + + this.logger.verbose('messages saved to db: ' + insert.length + ' messages'); return { insertCount: insert.length }; } + this.logger.verbose('saving messages to store'); + const store = this.configService.get('STORE'); if (store.MESSAGES) { - data.forEach((msg) => - this.writeStore({ - path: join(this.storePath, 'messages', instanceName), - fileName: msg.key.id, - data: msg, - }), - ); + this.logger.verbose('saving messages to store'); + data.forEach((message) => { + this.writeStore({ + path: join(this.storePath, 'messages', instanceName), + fileName: message.key.id, + data: message, + }); + this.logger.verbose( + 'messages saved to store in path: ' + + join(this.storePath, 'messages', instanceName) + + '/' + + message.key.id, + ); + }); + + this.logger.verbose('messages saved to store: ' + data.length + ' messages'); return { insertCount: data.length }; } + this.logger.verbose('messages not saved to store'); return { insertCount: 0 }; } catch (error) { console.log('ERROR: ', error); @@ -76,21 +97,26 @@ export class MessageRepository extends Repository { public async find(query: MessageQuery) { try { + this.logger.verbose('finding messages'); if (this.dbSettings.ENABLED) { + this.logger.verbose('finding messages in db'); if (query?.where?.key) { for (const [k, v] of Object.entries(query.where.key)) { query.where['key.' + k] = v; } delete query?.where?.key; } + return await this.messageModel .find({ ...query.where }) .sort({ messageTimestamp: -1 }) .limit(query?.limit ?? 0); } + this.logger.verbose('finding messages in store'); const messages: MessageRaw[] = []; if (query?.where?.key?.id) { + this.logger.verbose('finding messages in store by id'); messages.push( JSON.parse( readFileSync( @@ -105,6 +131,7 @@ export class MessageRepository extends Repository { ), ); } else { + this.logger.verbose('finding messages in store by owner'); const openDir = opendirSync(join(this.storePath, 'messages', query.where.owner), { encoding: 'utf-8', }); @@ -123,6 +150,7 @@ export class MessageRepository extends Repository { } } + this.logger.verbose('messages found in store: ' + messages.length + ' messages'); return messages .sort((x, y) => { return (y.messageTimestamp as number) - (x.messageTimestamp as number); diff --git a/src/whatsapp/repository/messageUp.repository.ts b/src/whatsapp/repository/messageUp.repository.ts index f9a42ee0..6a9f9cc4 100644 --- a/src/whatsapp/repository/messageUp.repository.ts +++ b/src/whatsapp/repository/messageUp.repository.ts @@ -3,6 +3,7 @@ import { IMessageUpModel, MessageUpdateRaw } from '../models'; import { IInsert, Repository } from '../abstract/abstract.repository'; import { join } from 'path'; import { opendirSync, readFileSync } from 'fs'; +import { Logger } from '../../config/logger.config'; export class MessageUpQuery { where: MessageUpdateRaw; @@ -17,35 +18,54 @@ export class MessageUpRepository extends Repository { super(configService); } + private readonly logger = new Logger('MessageUpRepository'); + public async insert( data: MessageUpdateRaw[], instanceName: string, saveDb?: boolean, ): Promise { + this.logger.verbose('inserting message up'); + if (data.length === 0) { + this.logger.verbose('no message up to insert'); return; } try { if (this.dbSettings.ENABLED && saveDb) { + this.logger.verbose('saving message up to db'); const insert = await this.messageUpModel.insertMany([...data]); + + this.logger.verbose('message up saved to db: ' + insert.length + ' message up'); return { insertCount: insert.length }; } + this.logger.verbose('saving message up to store'); + const store = this.configService.get('STORE'); if (store.MESSAGE_UP) { + this.logger.verbose('saving message up to store'); data.forEach((update) => { this.writeStore({ path: join(this.storePath, 'message-up', instanceName), fileName: update.id, data: update, }); + this.logger.verbose( + 'message up saved to store in path: ' + + join(this.storePath, 'message-up', instanceName) + + '/' + + update.id, + ); }); + this.logger.verbose('message up saved to store: ' + data.length + ' message up'); return { insertCount: data.length }; } + this.logger.verbose('message up not saved to store'); return { insertCount: 0 }; } catch (error) { return error; @@ -54,15 +74,21 @@ export class MessageUpRepository extends Repository { public async find(query: MessageUpQuery) { try { + this.logger.verbose('finding message up'); if (this.dbSettings.ENABLED) { + this.logger.verbose('finding message up in db'); return await this.messageUpModel .find({ ...query.where }) .sort({ datetime: -1 }) .limit(query?.limit ?? 0); } + this.logger.verbose('finding message up in store'); + const messageUpdate: MessageUpdateRaw[] = []; if (query?.where?.id) { + this.logger.verbose('finding message up in store by id'); + messageUpdate.push( JSON.parse( readFileSync( @@ -77,6 +103,8 @@ export class MessageUpRepository extends Repository { ), ); } else { + this.logger.verbose('finding message up in store by owner'); + const openDir = opendirSync( join(this.storePath, 'message-up', query.where.owner), { encoding: 'utf-8' }, @@ -96,6 +124,9 @@ export class MessageUpRepository extends Repository { } } + this.logger.verbose( + 'message up found in store: ' + messageUpdate.length + ' message up', + ); return messageUpdate .sort((x, y) => { return y.datetime - x.datetime; diff --git a/src/whatsapp/repository/repository.manager.ts b/src/whatsapp/repository/repository.manager.ts index eac7b18e..1e08213a 100644 --- a/src/whatsapp/repository/repository.manager.ts +++ b/src/whatsapp/repository/repository.manager.ts @@ -8,6 +8,7 @@ import { AuthRepository } from './auth.repository'; import { Auth, ConfigService, Database } from '../../config/env.config'; import { execSync } from 'child_process'; import { join } from 'path'; +import { Logger } from '../../config/logger.config'; export class RepositoryBroker { constructor( @@ -20,19 +21,26 @@ export class RepositoryBroker { private configService: ConfigService, dbServer?: MongoClient, ) { + this.logger.verbose('initializing repository broker'); this.dbClient = dbServer; this.__init_repo_without_db__(); } private dbClient?: MongoClient; + private readonly logger = new Logger('RepositoryBroker'); public get dbServer() { return this.dbClient; } private __init_repo_without_db__() { + this.logger.verbose('initializing repository without db'); if (!this.configService.get('DATABASE').ENABLED) { + this.logger.verbose('database is disabled'); + const storePath = join(process.cwd(), 'store'); + + this.logger.verbose('creating store path: ' + storePath); execSync( `mkdir -p ${join( storePath, @@ -40,10 +48,20 @@ export class RepositoryBroker { this.configService.get('AUTHENTICATION').TYPE, )}`, ); + + this.logger.verbose('creating chats path: ' + join(storePath, 'chats')); execSync(`mkdir -p ${join(storePath, 'chats')}`); + + this.logger.verbose('creating contacts path: ' + join(storePath, 'contacts')); execSync(`mkdir -p ${join(storePath, 'contacts')}`); + + this.logger.verbose('creating messages path: ' + join(storePath, 'messages')); execSync(`mkdir -p ${join(storePath, 'messages')}`); + + this.logger.verbose('creating message-up path: ' + join(storePath, 'message-up')); execSync(`mkdir -p ${join(storePath, 'message-up')}`); + + this.logger.verbose('creating webhook path: ' + join(storePath, 'webhook')); execSync(`mkdir -p ${join(storePath, 'webhook')}`); } } diff --git a/src/whatsapp/repository/webhook.repository.ts b/src/whatsapp/repository/webhook.repository.ts index 2a0c12a4..d9b34af1 100644 --- a/src/whatsapp/repository/webhook.repository.ts +++ b/src/whatsapp/repository/webhook.repository.ts @@ -3,6 +3,7 @@ import { ConfigService } from '../../config/env.config'; import { join } from 'path'; import { readFileSync } from 'fs'; import { IWebhookModel, WebhookRaw } from '../models'; +import { Logger } from '../../config/logger.config'; export class WebhookRepository extends Repository { constructor( @@ -12,23 +13,39 @@ export class WebhookRepository extends Repository { super(configService); } + private readonly logger = new Logger('WebhookRepository'); + public async create(data: WebhookRaw, instance: string): Promise { try { + this.logger.verbose('creating webhook'); if (this.dbSettings.ENABLED) { + this.logger.verbose('saving webhook to db'); const insert = await this.webhookModel.replaceOne( { _id: instance }, { ...data }, { upsert: true }, ); + + this.logger.verbose('webhook saved to db: ' + insert.modifiedCount + ' webhook'); return { insertCount: insert.modifiedCount }; } + this.logger.verbose('saving webhook to store'); + this.writeStore({ path: join(this.storePath, 'webhook'), fileName: instance, data, }); + this.logger.verbose( + 'webhook saved to store in path: ' + + join(this.storePath, 'webhook') + + '/' + + instance, + ); + + this.logger.verbose('webhook created'); return { insertCount: 1 }; } catch (error) { return error; @@ -37,10 +54,13 @@ export class WebhookRepository extends Repository { public async find(instance: string): Promise { try { + this.logger.verbose('finding webhook'); if (this.dbSettings.ENABLED) { + this.logger.verbose('finding webhook in db'); return await this.webhookModel.findOne({ _id: instance }); } + this.logger.verbose('finding webhook in store'); return JSON.parse( readFileSync(join(this.storePath, 'webhook', instance + '.json'), { encoding: 'utf-8', diff --git a/src/whatsapp/services/whatsapp.service.ts b/src/whatsapp/services/whatsapp.service.ts index 94efbc91..f86c29cc 100644 --- a/src/whatsapp/services/whatsapp.service.ts +++ b/src/whatsapp/services/whatsapp.service.ts @@ -509,7 +509,7 @@ export class WAStartupService { this.logger.verbose('Getting message with key: ' + JSON.stringify(key)); try { const webMessageInfo = (await this.repository.message.find({ - where: { owner: this.instance.wuid, key: { id: key.id } }, + where: { owner: this.instance.name, key: { id: key.id } }, })) as unknown as proto.IWebMessageInfo[]; if (full) { this.logger.verbose('Returning full message'); @@ -677,7 +677,7 @@ export class WAStartupService { this.logger.verbose('Finding chats in database'); const chatsRepository = await this.repository.chat.find({ - where: { owner: this.instance.wuid }, + where: { owner: this.instance.name }, }); this.logger.verbose('Verifying if chats exists in database to insert'); @@ -726,7 +726,7 @@ export class WAStartupService { chats.forEach( async (chat) => await this.repository.chat.delete({ - where: { owner: this.instance.wuid, id: chat }, + where: { owner: this.instance.name, id: chat }, }), ); @@ -741,7 +741,7 @@ export class WAStartupService { this.logger.verbose('Finding contacts in database'); const contactsRepository = await this.repository.contact.find({ - where: { owner: this.instance.wuid }, + where: { owner: this.instance.name }, }); this.logger.verbose('Verifying if contacts exists in database to insert'); @@ -755,7 +755,7 @@ export class WAStartupService { id: contact.id, pushName: contact?.name || contact?.verifiedName, profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl, - owner: this.instance.wuid, + owner: this.instance.name, }); } @@ -780,24 +780,19 @@ export class WAStartupService { id: contact.id, pushName: contact?.name ?? contact?.verifiedName, profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl, - owner: this.instance.wuid, + owner: this.instance.name, }); - - this.logger.verbose('Updating contacts in database'); - await this.repository.contact.update( - { - id: contact.id, - pushName: contact?.name ?? contact?.verifiedName, - profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl, - owner: this.instance.wuid, - }, - this.instance.name, - database.SAVE_DATA.CONTACTS, - ); } this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE'); await this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw); + + this.logger.verbose('Updating contacts in database'); + await this.repository.contact.update( + contactsRaw, + this.instance.name, + database.SAVE_DATA.CONTACTS, + ); }, }; @@ -821,7 +816,7 @@ export class WAStartupService { const chatsRaw: ChatRaw[] = chats.map((chat) => { return { id: chat.id, - owner: this.instance.wuid, + owner: this.instance.name, lastMsgTimestamp: chat.lastMessageRecvTimestamp, }; }); @@ -839,7 +834,7 @@ export class WAStartupService { const messagesRaw: MessageRaw[] = []; const messagesRepository = await this.repository.message.find({ - where: { owner: this.instance.wuid }, + where: { owner: this.instance.name }, }); for await (const [, m] of Object.entries(messages)) { if (!m.message) { @@ -847,7 +842,7 @@ export class WAStartupService { } if ( messagesRepository.find( - (mr) => mr.owner === this.instance.wuid && mr.key.id === m.key.id, + (mr) => mr.owner === this.instance.name && mr.key.id === m.key.id, ) ) { continue; @@ -864,7 +859,7 @@ export class WAStartupService { message: { ...m.message }, messageType: getContentType(m.message), messageTimestamp: m.messageTimestamp as number, - owner: this.instance.wuid, + owner: this.instance.name, }); } @@ -906,7 +901,7 @@ export class WAStartupService { message: { ...received.message }, messageType: getContentType(received.message), messageTimestamp: received.messageTimestamp as number, - owner: this.instance.wuid, + owner: this.instance.name, source: getDevice(received.key.id), }; @@ -924,9 +919,22 @@ export class WAStartupService { this.logger.verbose('Verifying contact from message'); const contact = await this.repository.contact.find({ - where: { owner: this.instance.wuid, id: received.key.remoteJid }, + where: { owner: this.instance.name, id: received.key.remoteJid }, }); + const contactRaw: ContactRaw = { + id: received.key.remoteJid, + pushName: received.pushName, + profilePictureUrl: (await this.profilePicture(received.key.remoteJid)) + .profilePictureUrl, + owner: this.instance.name, + }; + + if (contactRaw.id === 'status@broadcast') { + this.logger.verbose('Contact is status@broadcast'); + return; + } + if (contact?.length) { this.logger.verbose('Contact found in database'); const contactRaw: ContactRaw = { @@ -934,7 +942,7 @@ export class WAStartupService { pushName: contact[0].pushName, profilePictureUrl: (await this.profilePicture(received.key.remoteJid)) .profilePictureUrl, - owner: this.instance.wuid, + owner: this.instance.name, }; this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE'); @@ -942,7 +950,7 @@ export class WAStartupService { this.logger.verbose('Updating contact in database'); await this.repository.contact.update( - contactRaw, + [contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS, ); @@ -950,13 +958,6 @@ export class WAStartupService { } this.logger.verbose('Contact not found in database'); - const contactRaw: ContactRaw = { - id: received.key.remoteJid, - pushName: received.pushName, - profilePictureUrl: (await this.profilePicture(received.key.remoteJid)) - .profilePictureUrl, - owner: this.instance.wuid, - }; this.logger.verbose('Sending data to webhook in event CONTACTS_UPSERT'); await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); @@ -1000,7 +1001,7 @@ export class WAStartupService { ...key, status: status[update.status], datetime: Date.now(), - owner: this.instance.wuid, + owner: this.instance.name, pollUpdates, }; @@ -1436,6 +1437,8 @@ export class WAStartupService { } private async formatStatusMessage(status: StatusMessage) { + this.logger.verbose('Formatting status message'); + if (!status.type) { throw new BadRequestException('Type is required'); } @@ -1445,17 +1448,23 @@ export class WAStartupService { } if (status.allContacts) { + this.logger.verbose('All contacts defined as true'); + + this.logger.verbose('Getting contacts from database'); const contacts = await this.repository.contact.find({ - where: { owner: this.instance.wuid }, + where: { owner: this.instance.name }, }); if (!contacts.length) { throw new BadRequestException('Contacts not found'); } + this.logger.verbose('Getting contacts with push name'); status.statusJidList = contacts .filter((contact) => contact.pushName) .map((contact) => contact.id); + + this.logger.verbose(status.statusJidList); } if (!status.statusJidList?.length && !status.allContacts) { @@ -1463,6 +1472,8 @@ export class WAStartupService { } if (status.type === 'text') { + this.logger.verbose('Type defined as text'); + if (!status.backgroundColor) { throw new BadRequestException('Background color is required'); } @@ -1483,6 +1494,8 @@ export class WAStartupService { }; } if (status.type === 'image') { + this.logger.verbose('Type defined as image'); + return { content: { image: { @@ -1496,6 +1509,8 @@ export class WAStartupService { }; } if (status.type === 'video') { + this.logger.verbose('Type defined as video'); + return { content: { video: { @@ -1509,8 +1524,12 @@ export class WAStartupService { }; } if (status.type === 'audio') { + this.logger.verbose('Type defined as audio'); + + this.logger.verbose('Processing audio'); const convert = await this.processAudio(status.content, 'status@broadcast'); if (typeof convert === 'string') { + this.logger.verbose('Audio processed'); const audio = fs.readFileSync(convert).toString('base64'); const result = { @@ -2097,11 +2116,11 @@ export class WAStartupService { public async fetchContacts(query: ContactQuery) { this.logger.verbose('Fetching contacts'); if (query?.where) { - query.where.owner = this.instance.wuid; + query.where.owner = this.instance.name; } else { query = { where: { - owner: this.instance.wuid, + owner: this.instance.name, }, }; } @@ -2111,11 +2130,11 @@ export class WAStartupService { public async fetchMessages(query: MessageQuery) { this.logger.verbose('Fetching messages'); if (query?.where) { - query.where.owner = this.instance.wuid; + query.where.owner = this.instance.name; } else { query = { where: { - owner: this.instance.wuid, + owner: this.instance.name, }, limit: query?.limit, }; @@ -2126,11 +2145,11 @@ export class WAStartupService { public async fetchStatusMessage(query: MessageUpQuery) { this.logger.verbose('Fetching status messages'); if (query?.where) { - query.where.owner = this.instance.wuid; + query.where.owner = this.instance.name; } else { query = { where: { - owner: this.instance.wuid, + owner: this.instance.name, }, limit: query?.limit, }; @@ -2140,7 +2159,7 @@ export class WAStartupService { public async fetchChats() { this.logger.verbose('Fetching chats'); - return await this.repository.chat.find({ where: { owner: this.instance.wuid } }); + return await this.repository.chat.find({ where: { owner: this.instance.name } }); } public async fetchPrivacySettings() {