fix: Adjust in store files

This commit is contained in:
Davidson Gomes 2023-07-07 15:55:33 -03:00
parent 5bd7dd3022
commit a7be7c3e19
10 changed files with 75 additions and 21 deletions

View File

@ -7,6 +7,7 @@
### Fixed ### Fixed
* Adjusted set in webhook to go empty when enabled false * Adjusted set in webhook to go empty when enabled false
* Adjust in store files
# 1.1.3 (2023-07-06 11:43) # 1.1.3 (2023-07-06 11:43)

View File

@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "1.1.3", "version": "1.1.4",
"description": "Rest api for communication with WhatsApp", "description": "Rest api for communication with WhatsApp",
"main": "./dist/src/main.js", "main": "./dist/src/main.js",
"scripts": { "scripts": {

View File

@ -4,3 +4,4 @@ export const ROOT_DIR = process.cwd();
export const INSTANCE_DIR = join(ROOT_DIR, 'instances'); export const INSTANCE_DIR = join(ROOT_DIR, 'instances');
export const SRC_DIR = join(ROOT_DIR, 'src'); export const SRC_DIR = join(ROOT_DIR, 'src');
export const AUTH_DIR = join(ROOT_DIR, 'store', 'auth'); export const AUTH_DIR = join(ROOT_DIR, 'store', 'auth');
export const STORE_DIR = join(ROOT_DIR, 'store');

View File

@ -6,7 +6,7 @@ import { ROOT_DIR } from '../../config/path.config';
export type IInsert = { insertCount: number }; export type IInsert = { insertCount: number };
export interface IRepository { export interface IRepository {
insert(data: any, saveDb?: boolean): Promise<IInsert>; insert(data: any, instanceName: string, saveDb?: boolean): Promise<IInsert>;
find(query: any): Promise<any>; find(query: any): Promise<any>;
delete(query: any, force?: boolean): Promise<any>; delete(query: any, force?: boolean): Promise<any>;
@ -45,7 +45,7 @@ export abstract class Repository implements IRepository {
} }
}; };
public insert(data: any, saveDb = false): Promise<IInsert> { public insert(data: any, instanceName: string, saveDb = false): Promise<IInsert> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
public find(query: any): Promise<any> { public find(query: any): Promise<any> {

View File

@ -16,7 +16,11 @@ export class ChatRepository extends Repository {
super(configService); super(configService);
} }
public async insert(data: ChatRaw[], saveDb = false): Promise<IInsert> { public async insert(
data: ChatRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
if (data.length === 0) { if (data.length === 0) {
return; return;
} }
@ -32,7 +36,7 @@ export class ChatRepository extends Repository {
if (store.CHATS) { if (store.CHATS) {
data.forEach((chat) => { data.forEach((chat) => {
this.writeStore<ChatRaw>({ this.writeStore<ChatRaw>({
path: join(this.storePath, 'chats', chat.owner), path: join(this.storePath, 'chats', instanceName),
fileName: chat.id, fileName: chat.id,
data: chat, data: chat,
}); });

View File

@ -16,7 +16,11 @@ export class ContactRepository extends Repository {
super(configService); super(configService);
} }
public async insert(data: ContactRaw[], saveDb = false): Promise<IInsert> { public async insert(
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
if (data.length === 0) { if (data.length === 0) {
return; return;
} }
@ -32,7 +36,7 @@ export class ContactRepository extends Repository {
if (store.CONTACTS) { if (store.CONTACTS) {
data.forEach((contact) => { data.forEach((contact) => {
this.writeStore({ this.writeStore({
path: join(this.storePath, 'contacts', contact.owner), path: join(this.storePath, 'contacts', instanceName),
fileName: contact.id, fileName: contact.id,
data: contact, data: contact,
}); });

View File

@ -17,7 +17,11 @@ export class MessageRepository extends Repository {
super(configService); super(configService);
} }
public async insert(data: MessageRaw[], saveDb = false): Promise<IInsert> { public async insert(
data: MessageRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
if (!Array.isArray(data) || data.length === 0) { if (!Array.isArray(data) || data.length === 0) {
return; return;
} }
@ -52,7 +56,7 @@ export class MessageRepository extends Repository {
if (store.MESSAGES) { if (store.MESSAGES) {
data.forEach((msg) => data.forEach((msg) =>
this.writeStore<MessageRaw>({ this.writeStore<MessageRaw>({
path: join(this.storePath, 'messages', msg.owner), path: join(this.storePath, 'messages', instanceName),
fileName: msg.key.id, fileName: msg.key.id,
data: msg, data: msg,
}), }),

View File

@ -17,7 +17,11 @@ export class MessageUpRepository extends Repository {
super(configService); super(configService);
} }
public async insert(data: MessageUpdateRaw[], saveDb?: boolean): Promise<IInsert> { public async insert(
data: MessageUpdateRaw[],
instanceName: string,
saveDb?: boolean,
): Promise<IInsert> {
if (data.length === 0) { if (data.length === 0) {
return; return;
} }
@ -33,7 +37,7 @@ export class MessageUpRepository extends Repository {
if (store.MESSAGE_UP) { if (store.MESSAGE_UP) {
data.forEach((update) => { data.forEach((update) => {
this.writeStore<MessageUpdateRaw>({ this.writeStore<MessageUpdateRaw>({
path: join(this.storePath, 'message-up', update.owner), path: join(this.storePath, 'message-up', instanceName),
fileName: update.id, fileName: update.id,
data: update, data: update,
}); });

View File

@ -1,6 +1,6 @@
import { opendirSync, readdirSync, rmSync } from 'fs'; import { opendirSync, readdirSync, rmSync } from 'fs';
import { WAStartupService } from './whatsapp.service'; import { WAStartupService } from './whatsapp.service';
import { INSTANCE_DIR } from '../../config/path.config'; import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import EventEmitter2 from 'eventemitter2'; import EventEmitter2 from 'eventemitter2';
import { join } from 'path'; import { join } from 'path';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
@ -16,6 +16,7 @@ import { NotFoundException } from '../../exceptions';
import { Db } from 'mongodb'; import { Db } from 'mongodb';
import { initInstance } from '../whatsapp.module'; import { initInstance } from '../whatsapp.module';
import { RedisCache } from '../../db/redis.client'; import { RedisCache } from '../../db/redis.client';
import { execSync } from 'child_process';
export class WAMonitoringService { export class WAMonitoringService {
constructor( constructor(
@ -216,7 +217,23 @@ export class WAMonitoringService {
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true }); rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
} }
public async clearStoreFiles(instanceName: string) {} public async cleaningStoreFiles(instanceName: string) {
this.logger.verbose('cleaning store files instance: ' + instanceName);
if (!this.db.ENABLED) {
const instance = this.waInstances[instanceName];
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
execSync(`rm -rf ${join(STORE_DIR, 'chats', instanceName)}`);
execSync(`rm -rf ${join(STORE_DIR, 'contacts', instanceName)}`);
execSync(`rm -rf ${join(STORE_DIR, 'message-up', instanceName)}`);
execSync(`rm -rf ${join(STORE_DIR, 'messages', instanceName)}`);
execSync(`rm -rf ${join(STORE_DIR, 'auth', 'apikey', instanceName + '.json')}`);
execSync(`rm -rf ${join(STORE_DIR, 'webhook', instanceName + '.json')}`);
}
}
public async loadInstance() { public async loadInstance() {
this.logger.verbose('load instances'); this.logger.verbose('load instances');
@ -302,7 +319,7 @@ export class WAMonitoringService {
try { try {
this.logger.verbose('request cleaning up instance: ' + instanceName); this.logger.verbose('request cleaning up instance: ' + instanceName);
this.cleaningUp(instanceName); this.cleaningUp(instanceName);
this.clearStoreFiles(instanceName); this.cleaningStoreFiles(instanceName);
} finally { } finally {
this.logger.warn(`Instance "${instanceName}" - REMOVED`); this.logger.warn(`Instance "${instanceName}" - REMOVED`);
} }

View File

@ -30,6 +30,7 @@ import makeWASocket, {
WAMessageUpdate, WAMessageUpdate,
WASocket, WASocket,
getAggregateVotesInPollMessage, getAggregateVotesInPollMessage,
Browsers,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import { import {
Auth, Auth,
@ -554,14 +555,14 @@ export class WAStartupService {
`rm -rf ${join( `rm -rf ${join(
this.storePath, this.storePath,
key.toLowerCase().replace('_', '-'), key.toLowerCase().replace('_', '-'),
this.instance.wuid, this.instance.name,
)}/*.json`, )}/*.json`,
); );
this.logger.verbose( this.logger.verbose(
`Cleaned ${join( `Cleaned ${join(
this.storePath, this.storePath,
key.toLowerCase().replace('_', '-'), key.toLowerCase().replace('_', '-'),
this.instance.wuid, this.instance.name,
)}/*.json`, )}/*.json`,
); );
} }
@ -601,7 +602,8 @@ export class WAStartupService {
const { version } = await fetchLatestBaileysVersion(); const { version } = await fetchLatestBaileysVersion();
this.logger.verbose('Baileys version: ' + version); this.logger.verbose('Baileys version: ' + version);
const session = this.configService.get<ConfigSessionPhone>('CONFIG_SESSION_PHONE'); const session = this.configService.get<ConfigSessionPhone>('CONFIG_SESSION_PHONE');
const browser: WABrowserDescription = [session.CLIENT, session.NAME, release()]; // const browser: WABrowserDescription = [session.CLIENT, session.NAME, release()];
const browser: WABrowserDescription = Browsers.appropriate(session.CLIENT);
this.logger.verbose('Browser: ' + JSON.stringify(browser)); this.logger.verbose('Browser: ' + JSON.stringify(browser));
const socketConfig: UserFacingSocketConfig = { const socketConfig: UserFacingSocketConfig = {
@ -692,7 +694,11 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CHATS_UPSERT, chatsRaw); await this.sendDataWebhook(Events.CHATS_UPSERT, chatsRaw);
this.logger.verbose('Inserting chats in database'); this.logger.verbose('Inserting chats in database');
await this.repository.chat.insert(chatsRaw, database.SAVE_DATA.CHATS); await this.repository.chat.insert(
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
}, },
'chats.update': async ( 'chats.update': async (
@ -757,7 +763,11 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw); await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
this.logger.verbose('Inserting contacts in database'); this.logger.verbose('Inserting contacts in database');
await this.repository.contact.insert(contactsRaw, database.SAVE_DATA.CONTACTS); await this.repository.contact.insert(
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
}, },
'contacts.update': async (contacts: Partial<Contact>[]) => { 'contacts.update': async (contacts: Partial<Contact>[]) => {
@ -808,7 +818,11 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CHATS_SET, chatsRaw); await this.sendDataWebhook(Events.CHATS_SET, chatsRaw);
this.logger.verbose('Inserting chats in database'); this.logger.verbose('Inserting chats in database');
await this.repository.chat.insert(chatsRaw, database.SAVE_DATA.CHATS); await this.repository.chat.insert(
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
} }
const messagesRaw: MessageRaw[] = []; const messagesRaw: MessageRaw[] = [];
@ -890,7 +904,11 @@ export class WAStartupService {
await this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); await this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
this.logger.verbose('Inserting message in database'); this.logger.verbose('Inserting message in database');
await this.repository.message.insert([messageRaw], database.SAVE_DATA.NEW_MESSAGE); await this.repository.message.insert(
[messageRaw],
this.instance.name,
database.SAVE_DATA.NEW_MESSAGE,
);
}, },
'messages.update': async (args: WAMessageUpdate[], database: Database) => { 'messages.update': async (args: WAMessageUpdate[], database: Database) => {
@ -934,6 +952,7 @@ export class WAStartupService {
this.logger.verbose('Inserting message in database'); this.logger.verbose('Inserting message in database');
await this.repository.messageUpdate.insert( await this.repository.messageUpdate.insert(
[message], [message],
this.instance.name,
database.SAVE_DATA.MESSAGE_UPDATE, database.SAVE_DATA.MESSAGE_UPDATE,
); );
} }