feat: Show webhook_url for chatwoot

This commit is contained in:
Davidson Gomes 2023-07-13 11:19:48 -03:00
parent b4a9941452
commit eb83d89307
8 changed files with 83 additions and 26 deletions

View File

@ -4,7 +4,7 @@ import { join } from 'path';
import { SRC_DIR } from './path.config'; import { SRC_DIR } from './path.config';
import { isBooleanString } from 'class-validator'; import { isBooleanString } from 'class-validator';
export type HttpServer = { TYPE: 'http' | 'https'; PORT: number }; export type HttpServer = { TYPE: 'http' | 'https'; PORT: number; URL: string };
export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE'; export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE';
export type Cors = { export type Cors = {
@ -98,9 +98,9 @@ export type Instance = {
NAME: string; NAME: string;
WEBHOOK_URL: string; WEBHOOK_URL: string;
MODE: string; MODE: string;
CHATWOOT_ACCOUNT_ID: string; CHATWOOT_ACCOUNT_ID?: string;
CHATWOOT_TOKEN: string; CHATWOOT_TOKEN?: string;
CHATWOOT_URL: string; CHATWOOT_URL?: string;
}; };
export type Auth = { export type Auth = {
API_KEY: ApiKey; API_KEY: ApiKey;
@ -159,6 +159,7 @@ export class ConfigService {
if (process.env?.DOCKER_ENV === 'true') { if (process.env?.DOCKER_ENV === 'true') {
this.env.SERVER.TYPE = 'http'; this.env.SERVER.TYPE = 'http';
this.env.SERVER.PORT = 8080; this.env.SERVER.PORT = 8080;
this.env.SERVER.URL = `http://localhost:${this.env.SERVER.PORT}`;
} }
} }
@ -173,6 +174,7 @@ export class ConfigService {
SERVER: { SERVER: {
TYPE: process.env.SERVER_TYPE as 'http' | 'https', TYPE: process.env.SERVER_TYPE as 'http' | 'https',
PORT: Number.parseInt(process.env.SERVER_PORT), PORT: Number.parseInt(process.env.SERVER_PORT),
URL: process.env.SERVER_URL,
}, },
CORS: { CORS: {
ORIGIN: process.env.CORS_ORIGIN.split(','), ORIGIN: process.env.CORS_ORIGIN.split(','),
@ -278,9 +280,10 @@ export class ConfigService {
NAME: process.env.AUTHENTICATION_INSTANCE_NAME, NAME: process.env.AUTHENTICATION_INSTANCE_NAME,
WEBHOOK_URL: process.env.AUTHENTICATION_INSTANCE_WEBHOOK_URL, WEBHOOK_URL: process.env.AUTHENTICATION_INSTANCE_WEBHOOK_URL,
MODE: process.env.AUTHENTICATION_INSTANCE_MODE, MODE: process.env.AUTHENTICATION_INSTANCE_MODE,
CHATWOOT_ACCOUNT_ID: process.env.AUTHENTICATION_INSTANCE_CHATWOOT_ACCOUNT_ID, CHATWOOT_ACCOUNT_ID:
CHATWOOT_TOKEN: process.env.AUTHENTICATION_INSTANCE_CHATWOOT_TOKEN, process.env.AUTHENTICATION_INSTANCE_CHATWOOT_ACCOUNT_ID || '',
CHATWOOT_URL: process.env.AUTHENTICATION_INSTANCE_CHATWOOT_URL, CHATWOOT_TOKEN: process.env.AUTHENTICATION_INSTANCE_CHATWOOT_TOKEN || '',
CHATWOOT_URL: process.env.AUTHENTICATION_INSTANCE_CHATWOOT_URL || '',
}, },
}, },
}; };

View File

@ -8,6 +8,7 @@
SERVER: SERVER:
TYPE: http # https TYPE: http # https
PORT: 8080 # 443 PORT: 8080 # 443
URL: localhost
CORS: CORS:
ORIGIN: ORIGIN:

View File

@ -5,11 +5,15 @@ import { ChatwootDto } from '../dto/chatwoot.dto';
import { ChatwootService } from '../services/chatwoot.service'; import { ChatwootService } from '../services/chatwoot.service';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { waMonitor } from '../whatsapp.module'; import { waMonitor } from '../whatsapp.module';
import { ConfigService, HttpServer } from '../../config/env.config';
const logger = new Logger('ChatwootController'); const logger = new Logger('ChatwootController');
export class ChatwootController { export class ChatwootController {
constructor(private readonly chatwootService: ChatwootService) {} constructor(
private readonly chatwootService: ChatwootService,
private readonly configService: ConfigService,
) {}
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) { public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
logger.verbose( logger.verbose(
@ -46,9 +50,11 @@ export class ChatwootController {
const result = this.chatwootService.create(instance, data); const result = this.chatwootService.create(instance, data);
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const response = { const response = {
...result, ...result,
webhook_url: `/chatwoot/webhook/${instance.instanceName}`, webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
}; };
return response; return response;
@ -56,11 +62,13 @@ export class ChatwootController {
public async findChatwoot(instance: InstanceDto) { public async findChatwoot(instance: InstanceDto) {
logger.verbose('requested findChatwoot from ' + instance.instanceName + ' instance'); logger.verbose('requested findChatwoot from ' + instance.instanceName + ' instance');
const result = this.chatwootService.find(instance); const result = await this.chatwootService.find(instance);
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const response = { const response = {
...result, ...result,
webhook_url: `/chatwoot/webhook/${instance.instanceName}`, webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
}; };
return response; return response;

View File

@ -1,6 +1,6 @@
import { delay } from '@whiskeysockets/baileys'; import { delay } from '@whiskeysockets/baileys';
import EventEmitter2 from 'eventemitter2'; import EventEmitter2 from 'eventemitter2';
import { Auth, ConfigService } from '../../config/env.config'; import { Auth, ConfigService, HttpServer } from '../../config/env.config';
import { BadRequestException, InternalServerErrorException } from '../../exceptions'; import { BadRequestException, InternalServerErrorException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { RepositoryBroker } from '../repository/repository.manager'; import { RepositoryBroker } from '../repository/repository.manager';
@ -154,6 +154,8 @@ export class InstanceController {
this.logger.log(error); this.logger.log(error);
} }
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
return { return {
instance: { instance: {
instanceName: instance.instanceName, instanceName: instance.instanceName,
@ -167,7 +169,7 @@ export class InstanceController {
url: chatwoot_url, url: chatwoot_url,
sign_msg: chatwoot_sign_msg, sign_msg: chatwoot_sign_msg,
name_inbox: instance.instanceName, name_inbox: instance.instanceName,
webhook_url: `/chatwoot/webhook/${instance.instanceName}`, webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
}, },
}; };
} else { } else {
@ -288,6 +290,8 @@ export class InstanceController {
this.logger.log(error); this.logger.log(error);
} }
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
return { return {
instance: { instance: {
instanceName: instance.instanceName, instanceName: instance.instanceName,
@ -301,7 +305,7 @@ export class InstanceController {
url: chatwoot_url, url: chatwoot_url,
sign_msg: chatwoot_sign_msg, sign_msg: chatwoot_sign_msg,
name_inbox: instance.instanceName, name_inbox: instance.instanceName,
webhook_url: `/chatwoot/webhook/${instance.instanceName}`, webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
}, },
}; };
} }

View File

@ -42,22 +42,26 @@ export class ChatwootService {
} }
private async getProvider(instance: InstanceDto) { private async getProvider(instance: InstanceDto) {
const provider = await this.waMonitor.waInstances[ try {
instance.instanceName const provider = await this.waMonitor.waInstances[
].findChatwoot(); instance.instanceName
].findChatwoot();
if (!provider) { if (!provider) {
return null;
}
return provider;
} catch (error) {
return null; return null;
} }
return provider;
} }
private async clientCw(instance: InstanceDto) { private async clientCw(instance: InstanceDto) {
const provider = await this.getProvider(instance); const provider = await this.getProvider(instance);
if (!provider) { if (!provider) {
throw new Error('provider not found'); this.logger.error('provider not found');
} }
this.provider = provider; this.provider = provider;
@ -78,7 +82,7 @@ export class ChatwootService {
this.logger.verbose('create chatwoot: ' + instance.instanceName); this.logger.verbose('create chatwoot: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setChatwoot(data); this.waMonitor.waInstances[instance.instanceName].setChatwoot(data);
return { chatwoot: { ...instance, chatwoot: data } }; return data;
} }
public async find(instance: InstanceDto): Promise<ChatwootDto> { public async find(instance: InstanceDto): Promise<ChatwootDto> {
@ -583,6 +587,21 @@ export class ChatwootService {
} }
} }
if (body.message_type === 'template' && body.content_type === 'input_csat') {
const data: SendTextDto = {
number: chatId,
textMessage: {
text: body.content,
},
options: {
delay: 1200,
presence: 'composing',
},
};
await waInstance?.textMessage(data);
}
return { message: 'bot' }; return { message: 'bot' };
} catch (error) { } catch (error) {
console.log(error); console.log(error);

View File

@ -9,6 +9,7 @@ import {
ConfigService, ConfigService,
Database, Database,
DelInstance, DelInstance,
HttpServer,
Redis, Redis,
} from '../../config/env.config'; } from '../../config/env.config';
import { RepositoryBroker } from '../repository/repository.manager'; import { RepositoryBroker } from '../repository/repository.manager';
@ -83,6 +84,19 @@ export class WAMonitoringService {
for await (const [key, value] of Object.entries(this.waInstances)) { for await (const [key, value] of Object.entries(this.waInstances)) {
if (value) { if (value) {
this.logger.verbose('get instance info: ' + key); this.logger.verbose('get instance info: ' + key);
let chatwoot: any;
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const findChatwoot = await this.waInstances[key].findChatwoot();
if (findChatwoot.enabled) {
chatwoot = {
...findChatwoot,
webhook_url: `${urlServer}/chatwoot/webhook/${key}`,
};
}
if (value.connectionStatus.state === 'open') { if (value.connectionStatus.state === 'open') {
this.logger.verbose('instance: ' + key + ' - connectionStatus: open'); this.logger.verbose('instance: ' + key + ' - connectionStatus: open');
let apikey: string; let apikey: string;
@ -101,6 +115,7 @@ export class WAMonitoringService {
profilePictureUrl: value.profilePictureUrl, profilePictureUrl: value.profilePictureUrl,
status: (await value.getProfileStatus()) || '', status: (await value.getProfileStatus()) || '',
apikey, apikey,
chatwoot,
}, },
}); });
} else { } else {
@ -114,6 +129,7 @@ export class WAMonitoringService {
profileName: (await value.getProfileName()) || 'not loaded', profileName: (await value.getProfileName()) || 'not loaded',
profilePictureUrl: value.profilePictureUrl, profilePictureUrl: value.profilePictureUrl,
status: (await value.getProfileStatus()) || '', status: (await value.getProfileStatus()) || '',
chatwoot,
}, },
}); });
} }
@ -134,6 +150,7 @@ export class WAMonitoringService {
instanceName: key, instanceName: key,
status: value.connectionStatus.state, status: value.connectionStatus.state,
apikey, apikey,
chatwoot,
}, },
}); });
} else { } else {
@ -144,6 +161,7 @@ export class WAMonitoringService {
instance: { instance: {
instanceName: key, instanceName: key,
status: value.connectionStatus.state, status: value.connectionStatus.state,
chatwoot,
}, },
}); });
} }

View File

@ -30,7 +30,6 @@ import makeWASocket, {
WAMessageUpdate, WAMessageUpdate,
WASocket, WASocket,
getAggregateVotesInPollMessage, getAggregateVotesInPollMessage,
Browsers,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import { import {
Auth, Auth,
@ -38,6 +37,7 @@ import {
ConfigService, ConfigService,
ConfigSessionPhone, ConfigSessionPhone,
Database, Database,
HttpServer,
QrCode, QrCode,
Redis, Redis,
Webhook, Webhook,
@ -343,6 +343,7 @@ export class WAStartupService {
public async sendDataWebhook<T = any>(event: Events, data: T, local = true) { public async sendDataWebhook<T = any>(event: Events, data: T, local = true) {
const webhookGlobal = this.configService.get<Webhook>('WEBHOOK'); const webhookGlobal = this.configService.get<Webhook>('WEBHOOK');
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const webhookLocal = this.localWebhook.events; const webhookLocal = this.localWebhook.events;
const we = event.replace(/[\.-]/gm, '_').toUpperCase(); const we = event.replace(/[\.-]/gm, '_').toUpperCase();
const transformedWe = we.replace(/_/gm, '-').toLowerCase(); const transformedWe = we.replace(/_/gm, '-').toLowerCase();
@ -367,6 +368,7 @@ export class WAStartupService {
instance: this.instance.name, instance: this.instance.name,
data, data,
destination: this.localWebhook.url, destination: this.localWebhook.url,
urlServer,
}); });
} }
@ -378,6 +380,7 @@ export class WAStartupService {
instance: this.instance.name, instance: this.instance.name,
data, data,
destination: this.localWebhook.url, destination: this.localWebhook.url,
urlServer,
}); });
} }
} catch (error) { } catch (error) {
@ -425,6 +428,7 @@ export class WAStartupService {
instance: this.instance.name, instance: this.instance.name,
data, data,
destination: localUrl, destination: localUrl,
urlServer,
}); });
} }
@ -436,6 +440,7 @@ export class WAStartupService {
instance: this.instance.name, instance: this.instance.name,
data, data,
destination: localUrl, destination: localUrl,
urlServer,
}); });
} }
} catch (error) { } catch (error) {
@ -719,8 +724,7 @@ 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 = {

View File

@ -74,7 +74,7 @@ export const webhookController = new WebhookController(webhookService);
const chatwootService = new ChatwootService(waMonitor); const chatwootService = new ChatwootService(waMonitor);
export const chatwootController = new ChatwootController(chatwootService); export const chatwootController = new ChatwootController(chatwootService, configService);
export const instanceController = new InstanceController( export const instanceController = new InstanceController(
waMonitor, waMonitor,