mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-07-14 01:41:24 -06:00
feat: Added verbose logs
This commit is contained in:
parent
d66b751c2e
commit
f23ebf1e99
@ -7,6 +7,7 @@
|
||||
* Added organization name in vcard
|
||||
* Added email in vcard
|
||||
* Added url in vcard
|
||||
* Added verbose logs
|
||||
|
||||
### Fixed
|
||||
|
||||
|
@ -2,16 +2,20 @@ import mongoose from 'mongoose';
|
||||
import { configService, Database } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
const logger = new Logger('Db Connection');
|
||||
const logger = new Logger('MongoDB');
|
||||
|
||||
const db = configService.get<Database>('DATABASE');
|
||||
export const dbserver = (() => {
|
||||
if (db.ENABLED) {
|
||||
logger.verbose('connecting');
|
||||
const dbs = mongoose.createConnection(db.CONNECTION.URI, {
|
||||
dbName: db.CONNECTION.DB_PREFIX_NAME + '-whatsapp-api',
|
||||
});
|
||||
logger.verbose('connected in ' + db.CONNECTION.URI);
|
||||
logger.info('ON - dbName: ' + dbs['$dbName']);
|
||||
|
||||
process.on('beforeExit', () => {
|
||||
logger.verbose('instance destroyed');
|
||||
dbserver.destroy(true, (error) => logger.error(error));
|
||||
});
|
||||
|
||||
|
@ -43,8 +43,12 @@ export class AuthService {
|
||||
{ expiresIn: jwtOpts.EXPIRIN_IN, encoding: 'utf8', subject: 'g-t' },
|
||||
);
|
||||
|
||||
this.logger.verbose('JWT token created: ' + token);
|
||||
|
||||
const auth = await this.repository.auth.create({ jwt: token }, instance.instanceName);
|
||||
|
||||
this.logger.verbose('JWT token saved in database');
|
||||
|
||||
if (auth['error']) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.jwt',
|
||||
@ -59,8 +63,14 @@ export class AuthService {
|
||||
private async apikey(instance: InstanceDto, token?: string) {
|
||||
const apikey = token ? token : v4().toUpperCase();
|
||||
|
||||
this.logger.verbose(
|
||||
token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey,
|
||||
);
|
||||
|
||||
const auth = await this.repository.auth.create({ apikey }, instance.instanceName);
|
||||
|
||||
this.logger.verbose('APIKEY saved in database');
|
||||
|
||||
if (auth['error']) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.apikey',
|
||||
@ -75,54 +85,77 @@ export class AuthService {
|
||||
public async checkDuplicateToken(token: string) {
|
||||
const instances = await this.waMonitor.instanceInfo();
|
||||
|
||||
this.logger.verbose('checking duplicate token');
|
||||
|
||||
const instance = instances.find((instance) => instance.instance.apikey === token);
|
||||
|
||||
if (instance) {
|
||||
throw new BadRequestException('Token already exists');
|
||||
}
|
||||
|
||||
this.logger.verbose('available token');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async generateHash(instance: InstanceDto, token?: string) {
|
||||
const options = this.configService.get<Auth>('AUTHENTICATION');
|
||||
|
||||
this.logger.verbose(
|
||||
'generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName,
|
||||
);
|
||||
|
||||
return (await this[options.TYPE](instance, token)) as
|
||||
| { jwt: string }
|
||||
| { apikey: string };
|
||||
}
|
||||
|
||||
public async refreshToken({ oldToken }: OldToken) {
|
||||
this.logger.verbose('refreshing token');
|
||||
|
||||
if (!isJWT(oldToken)) {
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtOpts = this.configService.get<Auth>('AUTHENTICATION').JWT;
|
||||
|
||||
this.logger.verbose('checking oldToken');
|
||||
|
||||
const decode = verify(oldToken, jwtOpts.SECRET, {
|
||||
ignoreExpiration: true,
|
||||
}) as Pick<JwtPayload, 'apiName' | 'instanceName' | 'tokenId'>;
|
||||
|
||||
this.logger.verbose('checking token in database');
|
||||
|
||||
const tokenStore = await this.repository.auth.find(decode.instanceName);
|
||||
|
||||
const decodeTokenStore = verify(tokenStore.jwt, jwtOpts.SECRET, {
|
||||
ignoreExpiration: true,
|
||||
}) as Pick<JwtPayload, 'apiName' | 'instanceName' | 'tokenId'>;
|
||||
|
||||
this.logger.verbose('checking tokenId');
|
||||
|
||||
if (decode.tokenId !== decodeTokenStore.tokenId) {
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
|
||||
this.logger.verbose('generating new token');
|
||||
|
||||
const token = {
|
||||
jwt: (await this.jwt({ instanceName: decode.instanceName })).jwt,
|
||||
instanceName: decode.instanceName,
|
||||
};
|
||||
|
||||
try {
|
||||
this.logger.verbose('checking webhook');
|
||||
const webhook = await this.repository.webhook.find(decode.instanceName);
|
||||
if (
|
||||
webhook?.enabled &&
|
||||
this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN
|
||||
) {
|
||||
this.logger.verbose('sending webhook');
|
||||
|
||||
const httpService = axios.create({ baseURL: webhook.url });
|
||||
await httpService.post(
|
||||
'',
|
||||
@ -138,6 +171,8 @@ export class AuthService {
|
||||
this.logger.error(error);
|
||||
}
|
||||
|
||||
this.logger.verbose('token refreshed');
|
||||
|
||||
return token;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
|
@ -24,6 +24,8 @@ export class WAMonitoringService {
|
||||
private readonly repository: RepositoryBroker,
|
||||
private readonly cache: RedisCache,
|
||||
) {
|
||||
this.logger.verbose('instance created');
|
||||
|
||||
this.removeInstance();
|
||||
this.noConnection();
|
||||
this.delInstanceFiles();
|
||||
@ -47,6 +49,10 @@ export class WAMonitoringService {
|
||||
public delInstanceTime(instance: string) {
|
||||
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
|
||||
if (typeof time === 'number' && time > 0) {
|
||||
this.logger.verbose(
|
||||
`Instance "${instance}" don't have connection, will be removed in ${time} minutes`,
|
||||
);
|
||||
|
||||
setTimeout(async () => {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
|
||||
@ -66,6 +72,7 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
public async instanceInfo(instanceName?: string) {
|
||||
this.logger.verbose('get instance info');
|
||||
if (instanceName && !this.waInstances[instanceName]) {
|
||||
throw new NotFoundException(`Instance "${instanceName}" not found`);
|
||||
}
|
||||
@ -74,9 +81,14 @@ export class WAMonitoringService {
|
||||
|
||||
for await (const [key, value] of Object.entries(this.waInstances)) {
|
||||
if (value) {
|
||||
this.logger.verbose('get instance info: ' + key);
|
||||
if (value.connectionStatus.state === 'open') {
|
||||
this.logger.verbose('instance: ' + key + ' - connectionStatus: open');
|
||||
let apikey: string;
|
||||
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
|
||||
this.logger.verbose(
|
||||
'instance: ' + key + ' - hash exposed in fetch instances',
|
||||
);
|
||||
const tokenStore = await this.repository.auth.find(key);
|
||||
apikey = tokenStore.apikey || 'Apikey not found';
|
||||
|
||||
@ -91,6 +103,9 @@ export class WAMonitoringService {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
this.logger.verbose(
|
||||
'instance: ' + key + ' - hash not exposed in fetch instances',
|
||||
);
|
||||
instances.push({
|
||||
instance: {
|
||||
instanceName: key,
|
||||
@ -102,8 +117,14 @@ export class WAMonitoringService {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
this.logger.verbose(
|
||||
'instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state,
|
||||
);
|
||||
let apikey: string;
|
||||
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
|
||||
this.logger.verbose(
|
||||
'instance: ' + key + ' - hash exposed in fetch instances',
|
||||
);
|
||||
const tokenStore = await this.repository.auth.find(key);
|
||||
apikey = tokenStore.apikey || 'Apikey not found';
|
||||
|
||||
@ -115,6 +136,9 @@ export class WAMonitoringService {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
this.logger.verbose(
|
||||
'instance: ' + key + ' - hash not exposed in fetch instances',
|
||||
);
|
||||
instances.push({
|
||||
instance: {
|
||||
instanceName: key,
|
||||
@ -126,10 +150,13 @@ export class WAMonitoringService {
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.verbose('return instance info: ' + instances.length);
|
||||
|
||||
return instances.find((i) => i.instance.instanceName === instanceName) ?? instances;
|
||||
}
|
||||
|
||||
private delInstanceFiles() {
|
||||
this.logger.verbose('cron to delete instance files started');
|
||||
setInterval(async () => {
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
const collections = await this.dbInstance.collections();
|
||||
@ -141,6 +168,7 @@ export class WAMonitoringService {
|
||||
{ _id: { $regex: /^session-.*/ } },
|
||||
],
|
||||
});
|
||||
this.logger.verbose('instance files deleted: ' + name);
|
||||
});
|
||||
} else if (this.redis.ENABLED) {
|
||||
} else {
|
||||
@ -158,6 +186,7 @@ export class WAMonitoringService {
|
||||
});
|
||||
}
|
||||
});
|
||||
this.logger.verbose('instance files deleted: ' + dirent.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -165,7 +194,9 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
public async cleaningUp(instanceName: string) {
|
||||
this.logger.verbose('cleaning up instance: ' + instanceName);
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
this.logger.verbose('cleaning up instance in database: ' + instanceName);
|
||||
await this.repository.dbServer.connect();
|
||||
const collections: any[] = await this.dbInstance.collections();
|
||||
if (collections.length > 0) {
|
||||
@ -175,14 +206,18 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
if (this.redis.ENABLED) {
|
||||
this.logger.verbose('cleaning up instance in redis: ' + instanceName);
|
||||
this.cache.reference = instanceName;
|
||||
await this.cache.delAll();
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.verbose('cleaning up instance in files: ' + instanceName);
|
||||
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
public async loadInstance() {
|
||||
this.logger.verbose('load instances');
|
||||
const set = async (name: string) => {
|
||||
const instance = new WAStartupService(
|
||||
this.configService,
|
||||
@ -191,38 +226,50 @@ export class WAMonitoringService {
|
||||
this.cache,
|
||||
);
|
||||
instance.instanceName = name;
|
||||
this.logger.verbose('instance loaded: ' + name);
|
||||
|
||||
await instance.connectToWhatsapp();
|
||||
this.logger.verbose('connectToWhatsapp: ' + name);
|
||||
|
||||
this.waInstances[name] = instance;
|
||||
};
|
||||
|
||||
try {
|
||||
if (this.redis.ENABLED) {
|
||||
this.logger.verbose('redis enabled');
|
||||
await this.cache.connect(this.redis as Redis);
|
||||
const keys = await this.cache.instanceKeys();
|
||||
if (keys?.length > 0) {
|
||||
this.logger.verbose('reading instance keys and setting instances');
|
||||
keys.forEach(async (k) => await set(k.split(':')[1]));
|
||||
} else {
|
||||
this.logger.verbose('no instance keys found');
|
||||
initInstance();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
this.logger.verbose('database enabled');
|
||||
await this.repository.dbServer.connect();
|
||||
const collections: any[] = await this.dbInstance.collections();
|
||||
if (collections.length > 0) {
|
||||
this.logger.verbose('reading collections and setting instances');
|
||||
collections.forEach(
|
||||
async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')),
|
||||
);
|
||||
} else {
|
||||
this.logger.verbose('no collections found');
|
||||
initInstance();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.verbose('store in files enabled');
|
||||
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
|
||||
for await (const dirent of dir) {
|
||||
if (dirent.isDirectory()) {
|
||||
this.logger.verbose('reading instance files and setting instances');
|
||||
const files = readdirSync(join(INSTANCE_DIR, dirent.name), {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
@ -233,6 +280,7 @@ export class WAMonitoringService {
|
||||
|
||||
await set(dirent.name);
|
||||
} else {
|
||||
this.logger.verbose('no instance files found');
|
||||
initInstance();
|
||||
}
|
||||
}
|
||||
@ -243,18 +291,23 @@ export class WAMonitoringService {
|
||||
|
||||
private removeInstance() {
|
||||
this.eventEmitter.on('remove.instance', async (instanceName: string) => {
|
||||
this.logger.verbose('remove instance: ' + instanceName);
|
||||
try {
|
||||
this.logger.verbose('instance: ' + instanceName + ' - removing from memory');
|
||||
this.waInstances[instanceName] = undefined;
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
this.logger.verbose('request cleaning up instance: ' + instanceName);
|
||||
this.cleaningUp(instanceName);
|
||||
} finally {
|
||||
this.logger.warn(`Instance "${instanceName}" - REMOVED`);
|
||||
}
|
||||
});
|
||||
this.eventEmitter.on('logout.instance', async (instanceName: string) => {
|
||||
this.logger.verbose('logout instance: ' + instanceName);
|
||||
try {
|
||||
this.logger.verbose('request cleaning up instance: ' + instanceName);
|
||||
this.cleaningUp(instanceName);
|
||||
} finally {
|
||||
this.logger.warn(`Instance "${instanceName}" - LOGOUT`);
|
||||
@ -263,9 +316,13 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
private noConnection() {
|
||||
this.logger.verbose('checking instances without connection');
|
||||
this.eventEmitter.on('no.connection', async (instanceName) => {
|
||||
try {
|
||||
this.logger.verbose('instance: ' + instanceName + ' - removing from memory');
|
||||
this.waInstances[instanceName] = undefined;
|
||||
|
||||
this.logger.verbose('request cleaning up instance: ' + instanceName);
|
||||
this.cleaningUp(instanceName);
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
|
@ -1,11 +1,15 @@
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { WebhookDto } from '../dto/webhook.dto';
|
||||
import { WAMonitoringService } from './monitor.service';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
|
||||
export class WebhookService {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
|
||||
private readonly logger = new Logger(WebhookService.name);
|
||||
|
||||
public create(instance: InstanceDto, data: WebhookDto) {
|
||||
this.logger.verbose('create webhook: ' + instance.instanceName);
|
||||
this.waMonitor.waInstances[instance.instanceName].setWebhook(data);
|
||||
|
||||
return { webhook: { ...instance, webhook: data } };
|
||||
@ -13,6 +17,7 @@ export class WebhookService {
|
||||
|
||||
public async find(instance: InstanceDto): Promise<WebhookDto> {
|
||||
try {
|
||||
this.logger.verbose('find webhook: ' + instance.instanceName);
|
||||
return await this.waMonitor.waInstances[instance.instanceName].findWebhook();
|
||||
} catch (error) {
|
||||
return { enabled: null, url: '' };
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -85,6 +85,7 @@ export async function initInstance() {
|
||||
|
||||
const mode = configService.get<Auth>('AUTHENTICATION').INSTANCE.MODE;
|
||||
|
||||
logger.verbose('Sending data webhook for event: ' + Events.APPLICATION_STARTUP);
|
||||
instance.sendDataWebhook(
|
||||
Events.APPLICATION_STARTUP,
|
||||
{
|
||||
@ -95,9 +96,14 @@ export async function initInstance() {
|
||||
);
|
||||
|
||||
if (mode === 'container') {
|
||||
logger.verbose('Application startup in container mode');
|
||||
|
||||
const instanceName = configService.get<Auth>('AUTHENTICATION').INSTANCE.NAME;
|
||||
logger.verbose('Instance name: ' + instanceName);
|
||||
|
||||
const instanceWebhook =
|
||||
configService.get<Auth>('AUTHENTICATION').INSTANCE.WEBHOOK_URL;
|
||||
logger.verbose('Instance webhook: ' + instanceWebhook);
|
||||
|
||||
instance.instanceName = instanceName;
|
||||
|
||||
@ -106,13 +112,17 @@ export async function initInstance() {
|
||||
|
||||
const hash = await authService.generateHash({
|
||||
instanceName: instance.instanceName,
|
||||
token: configService.get<Auth>('AUTHENTICATION').API_KEY.KEY,
|
||||
});
|
||||
logger.verbose('Hash generated: ' + hash);
|
||||
|
||||
if (instanceWebhook) {
|
||||
logger.verbose('Creating webhook for instance: ' + instanceName);
|
||||
try {
|
||||
webhookService.create(instance, { enabled: true, url: instanceWebhook });
|
||||
logger.verbose('Webhook created');
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
logger.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
@ -130,7 +140,7 @@ export async function initInstance() {
|
||||
return await this.connectionState({ instanceName });
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
logger.log(error);
|
||||
}
|
||||
|
||||
const result = {
|
||||
|
Loading…
Reference in New Issue
Block a user