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

@@ -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<IInsert> {
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<AuthRaw>({
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<AuthRaw> {
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',

View File

@@ -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<IInsert> {
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<StoreConf>('STORE');
if (store.CHATS) {
this.logger.verbose('saving chats to store');
data.forEach((chat) => {
this.writeStore<ChatRaw>({
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<ChatRaw[]> {
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,

View File

@@ -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<IInsert> {
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<StoreConf>('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<IInsert> {
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<StoreConf>('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<ContactRaw[]> {
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 [];

View File

@@ -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<IInsert> {
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<StoreConf>('STORE');
if (store.MESSAGES) {
data.forEach((msg) =>
this.writeStore<MessageRaw>({
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);

View File

@@ -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<IInsert> {
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<StoreConf>('STORE');
if (store.MESSAGE_UP) {
this.logger.verbose('saving message up to store');
data.forEach((update) => {
this.writeStore<MessageUpdateRaw>({
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;

View File

@@ -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>('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<Auth>('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')}`);
}
}

View File

@@ -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<IInsert> {
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<WebhookRaw>({
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<WebhookRaw> {
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',