fix: Changed owner of the jid for instanceName

This commit is contained in:
Davidson Gomes 2023-07-08 07:47:06 -03:00
parent eca4285ea8
commit 048bea376d
9 changed files with 284 additions and 62 deletions

View File

@ -11,6 +11,7 @@
* Adjusted set in webhook to go empty when enabled false * Adjusted set in webhook to go empty when enabled false
* Adjust in store files * Adjust in store files
* Fixed the problem when do not save contacts when receive messages * 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) # 1.1.3 (2023-07-06 11:43)

View File

@ -4,7 +4,7 @@ import { IInsert, Repository } from '../abstract/abstract.repository';
import { IAuthModel, AuthRaw } from '../models'; import { IAuthModel, AuthRaw } from '../models';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { AUTH_DIR } from '../../config/path.config'; import { AUTH_DIR } from '../../config/path.config';
import { InstanceDto } from '../dto/instance.dto'; import { Logger } from '../../config/logger.config';
export class AuthRepository extends Repository { export class AuthRepository extends Repository {
constructor( constructor(
@ -16,24 +16,35 @@ export class AuthRepository extends Repository {
} }
private readonly auth: Auth; private readonly auth: Auth;
private readonly logger = new Logger('AuthRepository');
public async create(data: AuthRaw, instance: string): Promise<IInsert> { public async create(data: AuthRaw, instance: string): Promise<IInsert> {
try { try {
this.logger.verbose('creating auth');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving auth to db');
const insert = await this.authModel.replaceOne( const insert = await this.authModel.replaceOne(
{ _id: instance }, { _id: instance },
{ ...data }, { ...data },
{ upsert: true }, { upsert: true },
); );
this.logger.verbose('auth saved to db: ' + insert.modifiedCount + ' auth');
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
} }
this.logger.verbose('saving auth to store');
this.writeStore<AuthRaw>({ this.writeStore<AuthRaw>({
path: join(AUTH_DIR, this.auth.TYPE), path: join(AUTH_DIR, this.auth.TYPE),
fileName: instance, fileName: instance,
data, 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 }; return { insertCount: 1 };
} catch (error) { } catch (error) {
return { error } as any; return { error } as any;
@ -42,10 +53,14 @@ export class AuthRepository extends Repository {
public async find(instance: string): Promise<AuthRaw> { public async find(instance: string): Promise<AuthRaw> {
try { try {
this.logger.verbose('finding auth');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('finding auth in db');
return await this.authModel.findOne({ _id: instance }); return await this.authModel.findOne({ _id: instance });
} }
this.logger.verbose('finding auth in store');
return JSON.parse( return JSON.parse(
readFileSync(join(AUTH_DIR, this.auth.TYPE, instance + '.json'), { readFileSync(join(AUTH_DIR, this.auth.TYPE, instance + '.json'), {
encoding: 'utf-8', encoding: 'utf-8',

View File

@ -3,6 +3,7 @@ import { ConfigService, StoreConf } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository'; import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync, rmSync } from 'fs'; import { opendirSync, readFileSync, rmSync } from 'fs';
import { ChatRaw, IChatModel } from '../models'; import { ChatRaw, IChatModel } from '../models';
import { Logger } from '../../config/logger.config';
export class ChatQuery { export class ChatQuery {
where: ChatRaw; where: ChatRaw;
@ -16,35 +17,54 @@ export class ChatRepository extends Repository {
super(configService); super(configService);
} }
private readonly logger = new Logger('ChatRepository');
public async insert( public async insert(
data: ChatRaw[], data: ChatRaw[],
instanceName: string, instanceName: string,
saveDb = false, saveDb = false,
): Promise<IInsert> { ): Promise<IInsert> {
this.logger.verbose('inserting chats');
if (data.length === 0) { if (data.length === 0) {
this.logger.verbose('no chats to insert');
return; return;
} }
try { try {
this.logger.verbose('saving chats to store');
if (this.dbSettings.ENABLED && saveDb) { if (this.dbSettings.ENABLED && saveDb) {
this.logger.verbose('saving chats to db');
const insert = await this.chatModel.insertMany([...data]); const insert = await this.chatModel.insertMany([...data]);
this.logger.verbose('chats saved to db: ' + insert.length + ' chats');
return { insertCount: insert.length }; return { insertCount: insert.length };
} }
this.logger.verbose('saving chats to store');
const store = this.configService.get<StoreConf>('STORE'); const store = this.configService.get<StoreConf>('STORE');
if (store.CHATS) { if (store.CHATS) {
this.logger.verbose('saving chats to store');
data.forEach((chat) => { data.forEach((chat) => {
this.writeStore<ChatRaw>({ this.writeStore<ChatRaw>({
path: join(this.storePath, 'chats', instanceName), path: join(this.storePath, 'chats', instanceName),
fileName: chat.id, fileName: chat.id,
data: chat, 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 }; return { insertCount: data.length };
} }
this.logger.verbose('chats not saved to store');
return { insertCount: 0 }; return { insertCount: 0 };
} catch (error) { } catch (error) {
return error; return error;
@ -55,10 +75,14 @@ export class ChatRepository extends Repository {
public async find(query: ChatQuery): Promise<ChatRaw[]> { public async find(query: ChatQuery): Promise<ChatRaw[]> {
try { try {
this.logger.verbose('finding chats');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('finding chats in db');
return await this.chatModel.find({ owner: query.where.owner }); return await this.chatModel.find({ owner: query.where.owner });
} }
this.logger.verbose('finding chats in store');
const chats: ChatRaw[] = []; const chats: ChatRaw[] = [];
const openDir = opendirSync(join(this.storePath, 'chats', query.where.owner)); const openDir = opendirSync(join(this.storePath, 'chats', query.where.owner));
for await (const dirent of openDir) { 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; return chats;
} catch (error) { } catch (error) {
return []; return [];
@ -82,10 +107,13 @@ export class ChatRepository extends Repository {
public async delete(query: ChatQuery) { public async delete(query: ChatQuery) {
try { try {
this.logger.verbose('deleting chats');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('deleting chats in db');
return await this.chatModel.deleteOne({ ...query.where }); 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'), { rmSync(join(this.storePath, 'chats', query.where.owner, query.where.id + '.josn'), {
force: true, force: true,
recursive: true, recursive: true,

View File

@ -3,6 +3,7 @@ import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config'; import { ConfigService, StoreConf } from '../../config/env.config';
import { ContactRaw, IContactModel } from '../models'; import { ContactRaw, IContactModel } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository'; import { IInsert, Repository } from '../abstract/abstract.repository';
import { Logger } from '../../config/logger.config';
export class ContactQuery { export class ContactQuery {
where: ContactRaw; where: ContactRaw;
@ -16,35 +17,55 @@ export class ContactRepository extends Repository {
super(configService); super(configService);
} }
private readonly logger = new Logger('ContactRepository');
public async insert( public async insert(
data: ContactRaw[], data: ContactRaw[],
instanceName: string, instanceName: string,
saveDb = false, saveDb = false,
): Promise<IInsert> { ): Promise<IInsert> {
this.logger.verbose('inserting contacts');
if (data.length === 0) { if (data.length === 0) {
this.logger.verbose('no contacts to insert');
return; return;
} }
try { try {
if (this.dbSettings.ENABLED && saveDb) { if (this.dbSettings.ENABLED && saveDb) {
this.logger.verbose('saving contacts to db');
const insert = await this.contactModel.insertMany([...data]); const insert = await this.contactModel.insertMany([...data]);
this.logger.verbose('contacts saved to db: ' + insert.length + ' contacts');
return { insertCount: insert.length }; return { insertCount: insert.length };
} }
this.logger.verbose('saving contacts to store');
const store = this.configService.get<StoreConf>('STORE'); const store = this.configService.get<StoreConf>('STORE');
if (store.CONTACTS) { if (store.CONTACTS) {
this.logger.verbose('saving contacts to store');
data.forEach((contact) => { data.forEach((contact) => {
this.writeStore({ this.writeStore({
path: join(this.storePath, 'contacts', instanceName), path: join(this.storePath, 'contacts', instanceName),
fileName: contact.id, fileName: contact.id,
data: contact, 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 }; return { insertCount: data.length };
} }
this.logger.verbose('contacts not saved');
return { insertCount: 0 }; return { insertCount: 0 };
} catch (error) { } catch (error) {
return error; return error;
@ -54,31 +75,63 @@ export class ContactRepository extends Repository {
} }
public async update( public async update(
data: ContactRaw, data: ContactRaw[],
instanceName: string, instanceName: string,
saveDb = false, saveDb = false,
): Promise<IInsert> { ): Promise<IInsert> {
try { try {
if (this.dbSettings.ENABLED && saveDb) { this.logger.verbose('updating contacts');
const contact = await this.contactModel.findOneAndUpdate(
{ id: data.id }, if (data.length === 0) {
{ ...data }, this.logger.verbose('no contacts to update');
); return;
return { insertCount: contact ? 1 : 0 };
} }
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<StoreConf>('STORE'); const store = this.configService.get<StoreConf>('STORE');
if (store.CONTACTS) { if (store.CONTACTS) {
this.logger.verbose('updating contacts in store');
data.forEach((contact) => {
this.writeStore({ this.writeStore({
path: join(this.storePath, 'contacts', instanceName), path: join(this.storePath, 'contacts', instanceName),
fileName: data.id, fileName: contact.id,
data, 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 }; return { insertCount: 0 };
} catch (error) { } catch (error) {
return error; return error;
@ -89,11 +142,16 @@ export class ContactRepository extends Repository {
public async find(query: ContactQuery): Promise<ContactRaw[]> { public async find(query: ContactQuery): Promise<ContactRaw[]> {
try { try {
this.logger.verbose('finding contacts');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('finding contacts in db');
return await this.contactModel.find({ ...query.where }); return await this.contactModel.find({ ...query.where });
} }
this.logger.verbose('finding contacts in store');
const contacts: ContactRaw[] = []; const contacts: ContactRaw[] = [];
if (query?.where?.id) { if (query?.where?.id) {
this.logger.verbose('finding contacts in store by id');
contacts.push( contacts.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(
@ -108,6 +166,8 @@ export class ContactRepository extends Repository {
), ),
); );
} else { } else {
this.logger.verbose('finding contacts in store by owner');
const openDir = opendirSync(join(this.storePath, 'contacts', query.where.owner), { const openDir = opendirSync(join(this.storePath, 'contacts', query.where.owner), {
encoding: 'utf-8', encoding: 'utf-8',
}); });
@ -124,6 +184,8 @@ export class ContactRepository extends Repository {
} }
} }
} }
this.logger.verbose('contacts found in store: ' + contacts.length + ' contacts');
return contacts; return contacts;
} catch (error) { } catch (error) {
return []; return [];

View File

@ -3,6 +3,7 @@ import { join } from 'path';
import { IMessageModel, MessageRaw } from '../models'; import { IMessageModel, MessageRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository'; import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { Logger } from '../../config/logger.config';
export class MessageQuery { export class MessageQuery {
where: MessageRaw; where: MessageRaw;
@ -17,17 +18,23 @@ export class MessageRepository extends Repository {
super(configService); super(configService);
} }
private readonly logger = new Logger('MessageRepository');
public async insert( public async insert(
data: MessageRaw[], data: MessageRaw[],
instanceName: string, instanceName: string,
saveDb = false, saveDb = false,
): Promise<IInsert> { ): Promise<IInsert> {
this.logger.verbose('inserting messages');
if (!Array.isArray(data) || data.length === 0) { if (!Array.isArray(data) || data.length === 0) {
this.logger.verbose('no messages to insert');
return; return;
} }
try { try {
if (this.dbSettings.ENABLED && saveDb) { if (this.dbSettings.ENABLED && saveDb) {
this.logger.verbose('saving messages to db');
const cleanedData = data.map((obj) => { const cleanedData = data.map((obj) => {
const cleanedObj = { ...obj }; const cleanedObj = { ...obj };
if ('extendedTextMessage' in obj.message) { if ('extendedTextMessage' in obj.message) {
@ -48,23 +55,37 @@ export class MessageRepository extends Repository {
}); });
const insert = await this.messageModel.insertMany([...cleanedData]); const insert = await this.messageModel.insertMany([...cleanedData]);
this.logger.verbose('messages saved to db: ' + insert.length + ' messages');
return { insertCount: insert.length }; return { insertCount: insert.length };
} }
this.logger.verbose('saving messages to store');
const store = this.configService.get<StoreConf>('STORE'); const store = this.configService.get<StoreConf>('STORE');
if (store.MESSAGES) { if (store.MESSAGES) {
data.forEach((msg) => this.logger.verbose('saving messages to store');
this.writeStore<MessageRaw>({
path: join(this.storePath, 'messages', instanceName),
fileName: msg.key.id,
data: msg,
}),
);
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 }; return { insertCount: data.length };
} }
this.logger.verbose('messages not saved to store');
return { insertCount: 0 }; return { insertCount: 0 };
} catch (error) { } catch (error) {
console.log('ERROR: ', error); console.log('ERROR: ', error);
@ -76,21 +97,26 @@ export class MessageRepository extends Repository {
public async find(query: MessageQuery) { public async find(query: MessageQuery) {
try { try {
this.logger.verbose('finding messages');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('finding messages in db');
if (query?.where?.key) { if (query?.where?.key) {
for (const [k, v] of Object.entries(query.where.key)) { for (const [k, v] of Object.entries(query.where.key)) {
query.where['key.' + k] = v; query.where['key.' + k] = v;
} }
delete query?.where?.key; delete query?.where?.key;
} }
return await this.messageModel return await this.messageModel
.find({ ...query.where }) .find({ ...query.where })
.sort({ messageTimestamp: -1 }) .sort({ messageTimestamp: -1 })
.limit(query?.limit ?? 0); .limit(query?.limit ?? 0);
} }
this.logger.verbose('finding messages in store');
const messages: MessageRaw[] = []; const messages: MessageRaw[] = [];
if (query?.where?.key?.id) { if (query?.where?.key?.id) {
this.logger.verbose('finding messages in store by id');
messages.push( messages.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(
@ -105,6 +131,7 @@ export class MessageRepository extends Repository {
), ),
); );
} else { } else {
this.logger.verbose('finding messages in store by owner');
const openDir = opendirSync(join(this.storePath, 'messages', query.where.owner), { const openDir = opendirSync(join(this.storePath, 'messages', query.where.owner), {
encoding: 'utf-8', encoding: 'utf-8',
}); });
@ -123,6 +150,7 @@ export class MessageRepository extends Repository {
} }
} }
this.logger.verbose('messages found in store: ' + messages.length + ' messages');
return messages return messages
.sort((x, y) => { .sort((x, y) => {
return (y.messageTimestamp as number) - (x.messageTimestamp as number); return (y.messageTimestamp as number) - (x.messageTimestamp as number);

View File

@ -3,6 +3,7 @@ import { IMessageUpModel, MessageUpdateRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository'; import { IInsert, Repository } from '../abstract/abstract.repository';
import { join } from 'path'; import { join } from 'path';
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { Logger } from '../../config/logger.config';
export class MessageUpQuery { export class MessageUpQuery {
where: MessageUpdateRaw; where: MessageUpdateRaw;
@ -17,35 +18,54 @@ export class MessageUpRepository extends Repository {
super(configService); super(configService);
} }
private readonly logger = new Logger('MessageUpRepository');
public async insert( public async insert(
data: MessageUpdateRaw[], data: MessageUpdateRaw[],
instanceName: string, instanceName: string,
saveDb?: boolean, saveDb?: boolean,
): Promise<IInsert> { ): Promise<IInsert> {
this.logger.verbose('inserting message up');
if (data.length === 0) { if (data.length === 0) {
this.logger.verbose('no message up to insert');
return; return;
} }
try { try {
if (this.dbSettings.ENABLED && saveDb) { if (this.dbSettings.ENABLED && saveDb) {
this.logger.verbose('saving message up to db');
const insert = await this.messageUpModel.insertMany([...data]); const insert = await this.messageUpModel.insertMany([...data]);
this.logger.verbose('message up saved to db: ' + insert.length + ' message up');
return { insertCount: insert.length }; return { insertCount: insert.length };
} }
this.logger.verbose('saving message up to store');
const store = this.configService.get<StoreConf>('STORE'); const store = this.configService.get<StoreConf>('STORE');
if (store.MESSAGE_UP) { if (store.MESSAGE_UP) {
this.logger.verbose('saving message up to store');
data.forEach((update) => { data.forEach((update) => {
this.writeStore<MessageUpdateRaw>({ this.writeStore<MessageUpdateRaw>({
path: join(this.storePath, 'message-up', instanceName), path: join(this.storePath, 'message-up', instanceName),
fileName: update.id, fileName: update.id,
data: update, 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 }; return { insertCount: data.length };
} }
this.logger.verbose('message up not saved to store');
return { insertCount: 0 }; return { insertCount: 0 };
} catch (error) { } catch (error) {
return error; return error;
@ -54,15 +74,21 @@ export class MessageUpRepository extends Repository {
public async find(query: MessageUpQuery) { public async find(query: MessageUpQuery) {
try { try {
this.logger.verbose('finding message up');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('finding message up in db');
return await this.messageUpModel return await this.messageUpModel
.find({ ...query.where }) .find({ ...query.where })
.sort({ datetime: -1 }) .sort({ datetime: -1 })
.limit(query?.limit ?? 0); .limit(query?.limit ?? 0);
} }
this.logger.verbose('finding message up in store');
const messageUpdate: MessageUpdateRaw[] = []; const messageUpdate: MessageUpdateRaw[] = [];
if (query?.where?.id) { if (query?.where?.id) {
this.logger.verbose('finding message up in store by id');
messageUpdate.push( messageUpdate.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(
@ -77,6 +103,8 @@ export class MessageUpRepository extends Repository {
), ),
); );
} else { } else {
this.logger.verbose('finding message up in store by owner');
const openDir = opendirSync( const openDir = opendirSync(
join(this.storePath, 'message-up', query.where.owner), join(this.storePath, 'message-up', query.where.owner),
{ encoding: 'utf-8' }, { 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 return messageUpdate
.sort((x, y) => { .sort((x, y) => {
return y.datetime - x.datetime; return y.datetime - x.datetime;

View File

@ -8,6 +8,7 @@ import { AuthRepository } from './auth.repository';
import { Auth, ConfigService, Database } from '../../config/env.config'; import { Auth, ConfigService, Database } from '../../config/env.config';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import { join } from 'path'; import { join } from 'path';
import { Logger } from '../../config/logger.config';
export class RepositoryBroker { export class RepositoryBroker {
constructor( constructor(
@ -20,19 +21,26 @@ export class RepositoryBroker {
private configService: ConfigService, private configService: ConfigService,
dbServer?: MongoClient, dbServer?: MongoClient,
) { ) {
this.logger.verbose('initializing repository broker');
this.dbClient = dbServer; this.dbClient = dbServer;
this.__init_repo_without_db__(); this.__init_repo_without_db__();
} }
private dbClient?: MongoClient; private dbClient?: MongoClient;
private readonly logger = new Logger('RepositoryBroker');
public get dbServer() { public get dbServer() {
return this.dbClient; return this.dbClient;
} }
private __init_repo_without_db__() { private __init_repo_without_db__() {
this.logger.verbose('initializing repository without db');
if (!this.configService.get<Database>('DATABASE').ENABLED) { if (!this.configService.get<Database>('DATABASE').ENABLED) {
this.logger.verbose('database is disabled');
const storePath = join(process.cwd(), 'store'); const storePath = join(process.cwd(), 'store');
this.logger.verbose('creating store path: ' + storePath);
execSync( execSync(
`mkdir -p ${join( `mkdir -p ${join(
storePath, storePath,
@ -40,10 +48,20 @@ export class RepositoryBroker {
this.configService.get<Auth>('AUTHENTICATION').TYPE, this.configService.get<Auth>('AUTHENTICATION').TYPE,
)}`, )}`,
); );
this.logger.verbose('creating chats path: ' + join(storePath, 'chats'));
execSync(`mkdir -p ${join(storePath, 'chats')}`); execSync(`mkdir -p ${join(storePath, 'chats')}`);
this.logger.verbose('creating contacts path: ' + join(storePath, 'contacts'));
execSync(`mkdir -p ${join(storePath, 'contacts')}`); execSync(`mkdir -p ${join(storePath, 'contacts')}`);
this.logger.verbose('creating messages path: ' + join(storePath, 'messages'));
execSync(`mkdir -p ${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')}`); execSync(`mkdir -p ${join(storePath, 'message-up')}`);
this.logger.verbose('creating webhook path: ' + join(storePath, 'webhook'));
execSync(`mkdir -p ${join(storePath, 'webhook')}`); execSync(`mkdir -p ${join(storePath, 'webhook')}`);
} }
} }

View File

@ -3,6 +3,7 @@ import { ConfigService } from '../../config/env.config';
import { join } from 'path'; import { join } from 'path';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { IWebhookModel, WebhookRaw } from '../models'; import { IWebhookModel, WebhookRaw } from '../models';
import { Logger } from '../../config/logger.config';
export class WebhookRepository extends Repository { export class WebhookRepository extends Repository {
constructor( constructor(
@ -12,23 +13,39 @@ export class WebhookRepository extends Repository {
super(configService); super(configService);
} }
private readonly logger = new Logger('WebhookRepository');
public async create(data: WebhookRaw, instance: string): Promise<IInsert> { public async create(data: WebhookRaw, instance: string): Promise<IInsert> {
try { try {
this.logger.verbose('creating webhook');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving webhook to db');
const insert = await this.webhookModel.replaceOne( const insert = await this.webhookModel.replaceOne(
{ _id: instance }, { _id: instance },
{ ...data }, { ...data },
{ upsert: true }, { upsert: true },
); );
this.logger.verbose('webhook saved to db: ' + insert.modifiedCount + ' webhook');
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
} }
this.logger.verbose('saving webhook to store');
this.writeStore<WebhookRaw>({ this.writeStore<WebhookRaw>({
path: join(this.storePath, 'webhook'), path: join(this.storePath, 'webhook'),
fileName: instance, fileName: instance,
data, data,
}); });
this.logger.verbose(
'webhook saved to store in path: ' +
join(this.storePath, 'webhook') +
'/' +
instance,
);
this.logger.verbose('webhook created');
return { insertCount: 1 }; return { insertCount: 1 };
} catch (error) { } catch (error) {
return error; return error;
@ -37,10 +54,13 @@ export class WebhookRepository extends Repository {
public async find(instance: string): Promise<WebhookRaw> { public async find(instance: string): Promise<WebhookRaw> {
try { try {
this.logger.verbose('finding webhook');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('finding webhook in db');
return await this.webhookModel.findOne({ _id: instance }); return await this.webhookModel.findOne({ _id: instance });
} }
this.logger.verbose('finding webhook in store');
return JSON.parse( return JSON.parse(
readFileSync(join(this.storePath, 'webhook', instance + '.json'), { readFileSync(join(this.storePath, 'webhook', instance + '.json'), {
encoding: 'utf-8', encoding: 'utf-8',

View File

@ -509,7 +509,7 @@ export class WAStartupService {
this.logger.verbose('Getting message with key: ' + JSON.stringify(key)); this.logger.verbose('Getting message with key: ' + JSON.stringify(key));
try { try {
const webMessageInfo = (await this.repository.message.find({ 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[]; })) as unknown as proto.IWebMessageInfo[];
if (full) { if (full) {
this.logger.verbose('Returning full message'); this.logger.verbose('Returning full message');
@ -677,7 +677,7 @@ export class WAStartupService {
this.logger.verbose('Finding chats in database'); this.logger.verbose('Finding chats in database');
const chatsRepository = await this.repository.chat.find({ 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'); this.logger.verbose('Verifying if chats exists in database to insert');
@ -726,7 +726,7 @@ export class WAStartupService {
chats.forEach( chats.forEach(
async (chat) => async (chat) =>
await this.repository.chat.delete({ 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'); this.logger.verbose('Finding contacts in database');
const contactsRepository = await this.repository.contact.find({ 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'); this.logger.verbose('Verifying if contacts exists in database to insert');
@ -755,7 +755,7 @@ export class WAStartupService {
id: contact.id, id: contact.id,
pushName: contact?.name || contact?.verifiedName, pushName: contact?.name || contact?.verifiedName,
profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl, 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, id: contact.id,
pushName: contact?.name ?? contact?.verifiedName, pushName: contact?.name ?? contact?.verifiedName,
profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl, 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'); this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE');
await this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw); 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) => { const chatsRaw: ChatRaw[] = chats.map((chat) => {
return { return {
id: chat.id, id: chat.id,
owner: this.instance.wuid, owner: this.instance.name,
lastMsgTimestamp: chat.lastMessageRecvTimestamp, lastMsgTimestamp: chat.lastMessageRecvTimestamp,
}; };
}); });
@ -839,7 +834,7 @@ export class WAStartupService {
const messagesRaw: MessageRaw[] = []; const messagesRaw: MessageRaw[] = [];
const messagesRepository = await this.repository.message.find({ 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)) { for await (const [, m] of Object.entries(messages)) {
if (!m.message) { if (!m.message) {
@ -847,7 +842,7 @@ export class WAStartupService {
} }
if ( if (
messagesRepository.find( 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; continue;
@ -864,7 +859,7 @@ export class WAStartupService {
message: { ...m.message }, message: { ...m.message },
messageType: getContentType(m.message), messageType: getContentType(m.message),
messageTimestamp: m.messageTimestamp as number, messageTimestamp: m.messageTimestamp as number,
owner: this.instance.wuid, owner: this.instance.name,
}); });
} }
@ -906,7 +901,7 @@ export class WAStartupService {
message: { ...received.message }, message: { ...received.message },
messageType: getContentType(received.message), messageType: getContentType(received.message),
messageTimestamp: received.messageTimestamp as number, messageTimestamp: received.messageTimestamp as number,
owner: this.instance.wuid, owner: this.instance.name,
source: getDevice(received.key.id), source: getDevice(received.key.id),
}; };
@ -924,9 +919,22 @@ export class WAStartupService {
this.logger.verbose('Verifying contact from message'); this.logger.verbose('Verifying contact from message');
const contact = await this.repository.contact.find({ 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) { if (contact?.length) {
this.logger.verbose('Contact found in database'); this.logger.verbose('Contact found in database');
const contactRaw: ContactRaw = { const contactRaw: ContactRaw = {
@ -934,7 +942,7 @@ export class WAStartupService {
pushName: contact[0].pushName, pushName: contact[0].pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)) profilePictureUrl: (await this.profilePicture(received.key.remoteJid))
.profilePictureUrl, .profilePictureUrl,
owner: this.instance.wuid, owner: this.instance.name,
}; };
this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE'); 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'); this.logger.verbose('Updating contact in database');
await this.repository.contact.update( await this.repository.contact.update(
contactRaw, [contactRaw],
this.instance.name, this.instance.name,
database.SAVE_DATA.CONTACTS, database.SAVE_DATA.CONTACTS,
); );
@ -950,13 +958,6 @@ export class WAStartupService {
} }
this.logger.verbose('Contact not found in database'); 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'); this.logger.verbose('Sending data to webhook in event CONTACTS_UPSERT');
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
@ -1000,7 +1001,7 @@ export class WAStartupService {
...key, ...key,
status: status[update.status], status: status[update.status],
datetime: Date.now(), datetime: Date.now(),
owner: this.instance.wuid, owner: this.instance.name,
pollUpdates, pollUpdates,
}; };
@ -1436,6 +1437,8 @@ export class WAStartupService {
} }
private async formatStatusMessage(status: StatusMessage) { private async formatStatusMessage(status: StatusMessage) {
this.logger.verbose('Formatting status message');
if (!status.type) { if (!status.type) {
throw new BadRequestException('Type is required'); throw new BadRequestException('Type is required');
} }
@ -1445,17 +1448,23 @@ export class WAStartupService {
} }
if (status.allContacts) { 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({ const contacts = await this.repository.contact.find({
where: { owner: this.instance.wuid }, where: { owner: this.instance.name },
}); });
if (!contacts.length) { if (!contacts.length) {
throw new BadRequestException('Contacts not found'); throw new BadRequestException('Contacts not found');
} }
this.logger.verbose('Getting contacts with push name');
status.statusJidList = contacts status.statusJidList = contacts
.filter((contact) => contact.pushName) .filter((contact) => contact.pushName)
.map((contact) => contact.id); .map((contact) => contact.id);
this.logger.verbose(status.statusJidList);
} }
if (!status.statusJidList?.length && !status.allContacts) { if (!status.statusJidList?.length && !status.allContacts) {
@ -1463,6 +1472,8 @@ export class WAStartupService {
} }
if (status.type === 'text') { if (status.type === 'text') {
this.logger.verbose('Type defined as text');
if (!status.backgroundColor) { if (!status.backgroundColor) {
throw new BadRequestException('Background color is required'); throw new BadRequestException('Background color is required');
} }
@ -1483,6 +1494,8 @@ export class WAStartupService {
}; };
} }
if (status.type === 'image') { if (status.type === 'image') {
this.logger.verbose('Type defined as image');
return { return {
content: { content: {
image: { image: {
@ -1496,6 +1509,8 @@ export class WAStartupService {
}; };
} }
if (status.type === 'video') { if (status.type === 'video') {
this.logger.verbose('Type defined as video');
return { return {
content: { content: {
video: { video: {
@ -1509,8 +1524,12 @@ export class WAStartupService {
}; };
} }
if (status.type === 'audio') { 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'); const convert = await this.processAudio(status.content, 'status@broadcast');
if (typeof convert === 'string') { if (typeof convert === 'string') {
this.logger.verbose('Audio processed');
const audio = fs.readFileSync(convert).toString('base64'); const audio = fs.readFileSync(convert).toString('base64');
const result = { const result = {
@ -2097,11 +2116,11 @@ export class WAStartupService {
public async fetchContacts(query: ContactQuery) { public async fetchContacts(query: ContactQuery) {
this.logger.verbose('Fetching contacts'); this.logger.verbose('Fetching contacts');
if (query?.where) { if (query?.where) {
query.where.owner = this.instance.wuid; query.where.owner = this.instance.name;
} else { } else {
query = { query = {
where: { where: {
owner: this.instance.wuid, owner: this.instance.name,
}, },
}; };
} }
@ -2111,11 +2130,11 @@ export class WAStartupService {
public async fetchMessages(query: MessageQuery) { public async fetchMessages(query: MessageQuery) {
this.logger.verbose('Fetching messages'); this.logger.verbose('Fetching messages');
if (query?.where) { if (query?.where) {
query.where.owner = this.instance.wuid; query.where.owner = this.instance.name;
} else { } else {
query = { query = {
where: { where: {
owner: this.instance.wuid, owner: this.instance.name,
}, },
limit: query?.limit, limit: query?.limit,
}; };
@ -2126,11 +2145,11 @@ export class WAStartupService {
public async fetchStatusMessage(query: MessageUpQuery) { public async fetchStatusMessage(query: MessageUpQuery) {
this.logger.verbose('Fetching status messages'); this.logger.verbose('Fetching status messages');
if (query?.where) { if (query?.where) {
query.where.owner = this.instance.wuid; query.where.owner = this.instance.name;
} else { } else {
query = { query = {
where: { where: {
owner: this.instance.wuid, owner: this.instance.name,
}, },
limit: query?.limit, limit: query?.limit,
}; };
@ -2140,7 +2159,7 @@ export class WAStartupService {
public async fetchChats() { public async fetchChats() {
this.logger.verbose('Fetching chats'); 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() { public async fetchPrivacySettings() {