Skip to content

Commit 6d3779e

Browse files
committed
Merge branch 'develop' into feat/labels
2 parents c7bed04 + b0e956c commit 6d3779e

File tree

9 files changed

+73
-41
lines changed

9 files changed

+73
-41
lines changed

src/utils/i18n.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import path from 'path';
44

55
import { ConfigService, Language } from '../config/env.config';
66

7-
// export class i18n {
8-
// constructor(private readonly configService: ConfigService) {
97
const languages = ['en', 'pt-BR'];
108
const translationsPath = path.join(__dirname, 'translations');
119
const configService: ConfigService = new ConfigService();
@@ -31,6 +29,4 @@ i18next.init({
3129
escapeValue: false,
3230
},
3331
});
34-
// }
35-
// }
3632
export default i18next;

src/whatsapp/abstract/abstract.router.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ const logger = new Logger('Validate');
2121
export abstract class RouterBroker {
2222
constructor() {}
2323
public routerPath(path: string, param = true) {
24-
// const route = param ? '/:instanceName/' + path : '/' + path;
2524
let route = '/' + path;
2625
param ? (route += '/:instanceName') : null;
2726

@@ -56,10 +55,6 @@ export abstract class RouterBroker {
5655
message = stack.replace('instance.', '');
5756
}
5857
return message;
59-
// return {
60-
// property: property.replace('instance.', ''),
61-
// message,
62-
// };
6358
});
6459
logger.error(message);
6560
throw new BadRequestException(message);

src/whatsapp/controllers/settings.controller.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
// import { isURL } from 'class-validator';
2-
31
import { Logger } from '../../config/logger.config';
4-
// import { BadRequestException } from '../../exceptions';
52
import { InstanceDto } from '../dto/instance.dto';
63
import { SettingsDto } from '../dto/settings.dto';
74
import { SettingsService } from '../services/settings.service';

src/whatsapp/repository/auth.repository.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { readFileSync } from 'fs';
1+
import { opendirSync, readFileSync } from 'fs';
22
import { join } from 'path';
33

44
import { Auth, ConfigService } from '../../config/env.config';
@@ -64,6 +64,37 @@ export class AuthRepository extends Repository {
6464
}
6565
}
6666

67+
public async list(): Promise<AuthRaw[]> {
68+
try {
69+
if (this.dbSettings.ENABLED) {
70+
this.logger.verbose('listing auth in db');
71+
return await this.authModel.find();
72+
}
73+
74+
this.logger.verbose('listing auth in store');
75+
76+
const auths: AuthRaw[] = [];
77+
const openDir = opendirSync(join(AUTH_DIR, this.auth.TYPE), {
78+
encoding: 'utf-8',
79+
});
80+
for await (const dirent of openDir) {
81+
if (dirent.isFile()) {
82+
auths.push(
83+
JSON.parse(
84+
readFileSync(join(AUTH_DIR, this.auth.TYPE, dirent.name), {
85+
encoding: 'utf-8',
86+
}),
87+
),
88+
);
89+
}
90+
}
91+
92+
return auths;
93+
} catch (error) {
94+
return [];
95+
}
96+
}
97+
6798
public async findInstanceNameById(instanceId: string): Promise<string | null> {
6899
try {
69100
this.logger.verbose('finding auth by instanceId');

src/whatsapp/routers/chatwoot.router.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { chatwootSchema, instanceNameSchema } from '../../validate/validate.sche
55
import { RouterBroker } from '../abstract/abstract.router';
66
import { ChatwootDto } from '../dto/chatwoot.dto';
77
import { InstanceDto } from '../dto/instance.dto';
8-
// import { ChatwootService } from '../services/chatwoot.service';
98
import { chatwootController } from '../whatsapp.module';
109
import { HttpStatus } from './index.router';
1110

src/whatsapp/routers/settings.router.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { instanceNameSchema, settingsSchema } from '../../validate/validate.sche
55
import { RouterBroker } from '../abstract/abstract.router';
66
import { InstanceDto } from '../dto/instance.dto';
77
import { SettingsDto } from '../dto/settings.dto';
8-
// import { SettingsService } from '../services/settings.service';
98
import { settingsController } from '../whatsapp.module';
109
import { HttpStatus } from './index.router';
1110

src/whatsapp/services/chatwoot.service.ts

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,6 @@ export class ChatwootService {
5151
this.cache.set(cacheKey, provider);
5252

5353
return provider;
54-
// try {
55-
// } catch (error) {
56-
// this.logger.error('provider not found');
57-
// return null;
58-
// }
5954
}
6055

6156
private async clientCw(instance: InstanceDto) {
@@ -389,10 +384,6 @@ export class ChatwootService {
389384
q: query,
390385
});
391386
} else {
392-
// contact = await client.contacts.filter({
393-
// accountId: this.provider.account_id,
394-
// payload: this.getFilterPayload(query),
395-
// });
396387
// hotfix for: https://github.com/EvolutionAPI/evolution-api/pull/382. waiting fix: https://github.com/figurolatam/chatwoot-sdk/pull/7
397388
contact = await chatwootRequest(this.getClientCwConfig(), {
398389
method: 'POST',
@@ -1194,7 +1185,6 @@ export class ChatwootService {
11941185
if (state !== 'open') {
11951186
if (state === 'close') {
11961187
this.logger.verbose('request cleaning up instance: ' + instance.instanceName);
1197-
// await this.waMonitor.cleaningUp(instance.instanceName);
11981188
}
11991189
this.logger.verbose('connect to whatsapp');
12001190
const number = command.split(':')[1];

src/whatsapp/services/monitor.service.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,20 @@ import { execSync } from 'child_process';
22
import EventEmitter2 from 'eventemitter2';
33
import { opendirSync, readdirSync, rmSync } from 'fs';
44
import { Db } from 'mongodb';
5+
import { Collection } from 'mongoose';
56
import { join } from 'path';
67

78
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
89
import { Logger } from '../../config/logger.config';
910
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
1011
import { NotFoundException } from '../../exceptions';
11-
import { dbserver } from '../../libs/db.connect';
1212
import { RedisCache } from '../../libs/redis.client';
1313
import {
1414
AuthModel,
1515
ChamaaiModel,
16-
// ChatModel,
1716
ChatwootModel,
17+
ContactModel,
1818
LabelModel,
19-
// ContactModel,
20-
// MessageModel,
21-
// MessageUpModel,
2219
ProxyModel,
2320
RabbitmqModel,
2421
SettingsModel,
@@ -42,7 +39,6 @@ export class WAMonitoringService {
4239

4340
this.removeInstance();
4441
this.noConnection();
45-
// this.delInstanceFiles();
4642

4743
Object.assign(this.db, configService.get<Database>('DATABASE'));
4844
Object.assign(this.redis, configService.get<Redis>('REDIS'));
@@ -57,8 +53,6 @@ export class WAMonitoringService {
5753

5854
private dbInstance: Db;
5955

60-
private dbStore = dbserver;
61-
6256
private readonly logger = new Logger(WAMonitoringService.name);
6357
public readonly waInstances: Record<string, WAStartupService> = {};
6458

@@ -328,11 +322,6 @@ export class WAMonitoringService {
328322

329323
this.logger.verbose('cleaning store database instance: ' + instanceName);
330324

331-
// await ChatModel.deleteMany({ owner: instanceName });
332-
// await ContactModel.deleteMany({ owner: instanceName });
333-
// await MessageUpModel.deleteMany({ owner: instanceName });
334-
// await MessageModel.deleteMany({ owner: instanceName });
335-
336325
await AuthModel.deleteMany({ _id: instanceName });
337326
await WebhookModel.deleteMany({ _id: instanceName });
338327
await ChatwootModel.deleteMany({ _id: instanceName });
@@ -343,6 +332,7 @@ export class WAMonitoringService {
343332
await WebsocketModel.deleteMany({ _id: instanceName });
344333
await SettingsModel.deleteMany({ _id: instanceName });
345334
await LabelModel.deleteMany({ owner: instanceName });
335+
await ContactModel.deleteMany({ owner: instanceName });
346336

347337
return;
348338
}
@@ -396,7 +386,7 @@ export class WAMonitoringService {
396386
this.logger.verbose('Database enabled');
397387
await this.repository.dbServer.connect();
398388
const collections: any[] = await this.dbInstance.collections();
399-
389+
await this.deleteTempInstances(collections);
400390
if (collections.length > 0) {
401391
this.logger.verbose('Reading collections and setting instances');
402392
await Promise.all(collections.map((coll) => this.setInstance(coll.namespace.replace(/^[\w-]+\./, ''))));
@@ -485,4 +475,22 @@ export class WAMonitoringService {
485475
}
486476
});
487477
}
478+
479+
private async deleteTempInstances(collections: Collection<Document>[]) {
480+
this.logger.verbose('Cleaning up temp instances');
481+
const auths = await this.repository.auth.list();
482+
if (auths.length === 0) {
483+
this.logger.verbose('No temp instances found');
484+
return;
485+
}
486+
let tempInstances = 0;
487+
auths.forEach((auth) => {
488+
if (collections.find((coll) => coll.namespace.replace(/^[\w-]+\./, '') === auth._id)) {
489+
return;
490+
}
491+
tempInstances++;
492+
this.eventEmitter.emit('remove.instance', auth._id, 'inner');
493+
});
494+
this.logger.verbose('Temp instances removed: ' + tempInstances);
495+
}
488496
}

src/whatsapp/services/whatsapp.service.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1660,7 +1660,7 @@ export class WAStartupService {
16601660
);
16611661

16621662
this.logger.verbose('Verifying if contacts exists in database to insert');
1663-
const contactsRaw: ContactRaw[] = [];
1663+
let contactsRaw: ContactRaw[] = [];
16641664

16651665
for (const contact of contacts) {
16661666
if (contactsRepository.has(contact.id)) {
@@ -1670,7 +1670,7 @@ export class WAStartupService {
16701670
contactsRaw.push({
16711671
id: contact.id,
16721672
pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0],
1673-
profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl,
1673+
profilePictureUrl: null,
16741674
owner: this.instance.name,
16751675
});
16761676
}
@@ -1685,6 +1685,23 @@ export class WAStartupService {
16851685
this.chatwootService.addHistoryContacts({ instanceName: this.instance.name }, contactsRaw);
16861686
chatwootImport.importHistoryContacts({ instanceName: this.instance.name }, this.localChatwoot);
16871687
}
1688+
1689+
// Update profile pictures
1690+
contactsRaw = [];
1691+
for await (const contact of contacts) {
1692+
contactsRaw.push({
1693+
id: contact.id,
1694+
pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0],
1695+
profilePictureUrl: (await this.profilePicture(contact.id)).profilePictureUrl,
1696+
owner: this.instance.name,
1697+
});
1698+
}
1699+
1700+
this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE');
1701+
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
1702+
1703+
this.logger.verbose('Updating contacts in database');
1704+
this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
16881705
} catch (error) {
16891706
this.logger.error(error);
16901707
}

0 commit comments

Comments
 (0)