Merge branch 'develop' into feat/labels

This commit is contained in:
Judson Cairo 2024-02-08 13:10:23 -03:00
commit 6d3779eb83
9 changed files with 73 additions and 41 deletions

View File

@ -4,8 +4,6 @@ import path from 'path';
import { ConfigService, Language } from '../config/env.config';
// export class i18n {
// constructor(private readonly configService: ConfigService) {
const languages = ['en', 'pt-BR'];
const translationsPath = path.join(__dirname, 'translations');
const configService: ConfigService = new ConfigService();
@ -31,6 +29,4 @@ i18next.init({
escapeValue: false,
},
});
// }
// }
export default i18next;

View File

@ -21,7 +21,6 @@ const logger = new Logger('Validate');
export abstract class RouterBroker {
constructor() {}
public routerPath(path: string, param = true) {
// const route = param ? '/:instanceName/' + path : '/' + path;
let route = '/' + path;
param ? (route += '/:instanceName') : null;
@ -56,10 +55,6 @@ export abstract class RouterBroker {
message = stack.replace('instance.', '');
}
return message;
// return {
// property: property.replace('instance.', ''),
// message,
// };
});
logger.error(message);
throw new BadRequestException(message);

View File

@ -1,7 +1,4 @@
// import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
// import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
import { SettingsService } from '../services/settings.service';

View File

@ -1,4 +1,4 @@
import { readFileSync } from 'fs';
import { opendirSync, readFileSync } from 'fs';
import { join } from 'path';
import { Auth, ConfigService } from '../../config/env.config';
@ -64,6 +64,37 @@ export class AuthRepository extends Repository {
}
}
public async list(): Promise<AuthRaw[]> {
try {
if (this.dbSettings.ENABLED) {
this.logger.verbose('listing auth in db');
return await this.authModel.find();
}
this.logger.verbose('listing auth in store');
const auths: AuthRaw[] = [];
const openDir = opendirSync(join(AUTH_DIR, this.auth.TYPE), {
encoding: 'utf-8',
});
for await (const dirent of openDir) {
if (dirent.isFile()) {
auths.push(
JSON.parse(
readFileSync(join(AUTH_DIR, this.auth.TYPE, dirent.name), {
encoding: 'utf-8',
}),
),
);
}
}
return auths;
} catch (error) {
return [];
}
}
public async findInstanceNameById(instanceId: string): Promise<string | null> {
try {
this.logger.verbose('finding auth by instanceId');

View File

@ -5,7 +5,6 @@ import { chatwootSchema, instanceNameSchema } from '../../validate/validate.sche
import { RouterBroker } from '../abstract/abstract.router';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
// import { ChatwootService } from '../services/chatwoot.service';
import { chatwootController } from '../whatsapp.module';
import { HttpStatus } from './index.router';

View File

@ -5,7 +5,6 @@ import { instanceNameSchema, settingsSchema } from '../../validate/validate.sche
import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
// import { SettingsService } from '../services/settings.service';
import { settingsController } from '../whatsapp.module';
import { HttpStatus } from './index.router';

View File

@ -51,11 +51,6 @@ export class ChatwootService {
this.cache.set(cacheKey, provider);
return provider;
// try {
// } catch (error) {
// this.logger.error('provider not found');
// return null;
// }
}
private async clientCw(instance: InstanceDto) {
@ -389,10 +384,6 @@ export class ChatwootService {
q: query,
});
} else {
// contact = await client.contacts.filter({
// accountId: this.provider.account_id,
// payload: this.getFilterPayload(query),
// });
// hotfix for: https://github.com/EvolutionAPI/evolution-api/pull/382. waiting fix: https://github.com/figurolatam/chatwoot-sdk/pull/7
contact = await chatwootRequest(this.getClientCwConfig(), {
method: 'POST',
@ -1194,7 +1185,6 @@ export class ChatwootService {
if (state !== 'open') {
if (state === 'close') {
this.logger.verbose('request cleaning up instance: ' + instance.instanceName);
// await this.waMonitor.cleaningUp(instance.instanceName);
}
this.logger.verbose('connect to whatsapp');
const number = command.split(':')[1];

View File

@ -2,23 +2,20 @@ import { execSync } from 'child_process';
import EventEmitter2 from 'eventemitter2';
import { opendirSync, readdirSync, rmSync } from 'fs';
import { Db } from 'mongodb';
import { Collection } from 'mongoose';
import { join } from 'path';
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import { NotFoundException } from '../../exceptions';
import { dbserver } from '../../libs/db.connect';
import { RedisCache } from '../../libs/redis.client';
import {
AuthModel,
ChamaaiModel,
// ChatModel,
ChatwootModel,
ContactModel,
LabelModel,
// ContactModel,
// MessageModel,
// MessageUpModel,
ProxyModel,
RabbitmqModel,
SettingsModel,
@ -42,7 +39,6 @@ export class WAMonitoringService {
this.removeInstance();
this.noConnection();
// this.delInstanceFiles();
Object.assign(this.db, configService.get<Database>('DATABASE'));
Object.assign(this.redis, configService.get<Redis>('REDIS'));
@ -57,8 +53,6 @@ export class WAMonitoringService {
private dbInstance: Db;
private dbStore = dbserver;
private readonly logger = new Logger(WAMonitoringService.name);
public readonly waInstances: Record<string, WAStartupService> = {};
@ -328,11 +322,6 @@ export class WAMonitoringService {
this.logger.verbose('cleaning store database instance: ' + instanceName);
// await ChatModel.deleteMany({ owner: instanceName });
// await ContactModel.deleteMany({ owner: instanceName });
// await MessageUpModel.deleteMany({ owner: instanceName });
// await MessageModel.deleteMany({ owner: instanceName });
await AuthModel.deleteMany({ _id: instanceName });
await WebhookModel.deleteMany({ _id: instanceName });
await ChatwootModel.deleteMany({ _id: instanceName });
@ -343,6 +332,7 @@ export class WAMonitoringService {
await WebsocketModel.deleteMany({ _id: instanceName });
await SettingsModel.deleteMany({ _id: instanceName });
await LabelModel.deleteMany({ owner: instanceName });
await ContactModel.deleteMany({ owner: instanceName });
return;
}
@ -396,7 +386,7 @@ export class WAMonitoringService {
this.logger.verbose('Database enabled');
await this.repository.dbServer.connect();
const collections: any[] = await this.dbInstance.collections();
await this.deleteTempInstances(collections);
if (collections.length > 0) {
this.logger.verbose('Reading collections and setting instances');
await Promise.all(collections.map((coll) => this.setInstance(coll.namespace.replace(/^[\w-]+\./, ''))));
@ -485,4 +475,22 @@ export class WAMonitoringService {
}
});
}
private async deleteTempInstances(collections: Collection<Document>[]) {
this.logger.verbose('Cleaning up temp instances');
const auths = await this.repository.auth.list();
if (auths.length === 0) {
this.logger.verbose('No temp instances found');
return;
}
let tempInstances = 0;
auths.forEach((auth) => {
if (collections.find((coll) => coll.namespace.replace(/^[\w-]+\./, '') === auth._id)) {
return;
}
tempInstances++;
this.eventEmitter.emit('remove.instance', auth._id, 'inner');
});
this.logger.verbose('Temp instances removed: ' + tempInstances);
}
}

View File

@ -1660,7 +1660,7 @@ export class WAStartupService {
);
this.logger.verbose('Verifying if contacts exists in database to insert');
const contactsRaw: ContactRaw[] = [];
let contactsRaw: ContactRaw[] = [];
for (const contact of contacts) {
if (contactsRepository.has(contact.id)) {
@ -1670,7 +1670,7 @@ export class WAStartupService {
contactsRaw.push({
id: contact.id,
pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0],
profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl,
profilePictureUrl: null,
owner: this.instance.name,
});
}
@ -1685,6 +1685,23 @@ export class WAStartupService {
this.chatwootService.addHistoryContacts({ instanceName: this.instance.name }, contactsRaw);
chatwootImport.importHistoryContacts({ instanceName: this.instance.name }, this.localChatwoot);
}
// Update profile pictures
contactsRaw = [];
for await (const contact of contacts) {
contactsRaw.push({
id: contact.id,
pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0],
profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl,
owner: this.instance.name,
});
}
this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE');
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
this.logger.verbose('Updating contacts in database');
this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
} catch (error) {
this.logger.error(error);
}