Merge branch 'main' into groupJid-query-or-body

This commit is contained in:
Davidson Gomes 2023-07-26 17:43:28 -03:00 committed by GitHub
commit 68402393b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
62 changed files with 695 additions and 1274 deletions

View File

@ -3,10 +3,14 @@ module.exports = {
parserOptions: { parserOptions: {
sourceType: 'CommonJS', sourceType: 'CommonJS',
}, },
plugins: ['@typescript-eslint/eslint-plugin'], plugins: [
'@typescript-eslint',
'simple-import-sort',
'import'
],
extends: [ extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'plugin:prettier/recommended' 'plugin:prettier/recommended'
], ],
globals: { globals: {
@ -26,7 +30,11 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'error',
'import/first': 'error',
'import/no-duplicates': 'error',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
'@typescript-eslint/ban-types': [ '@typescript-eslint/ban-types': [
'error', 'error',
{ {

6
.gitignore vendored
View File

@ -22,12 +22,13 @@ docker-compose.yaml
/yarn.lock /yarn.lock
/package-lock.json /package-lock.json
# IDE - VSCode # IDEs
.vscode/* .vscode/*
!.vscode/settings.json !.vscode/settings.json
!.vscode/tasks.json !.vscode/tasks.json
!.vscode/launch.json !.vscode/launch.json
!.vscode/extensions.json !.vscode/extensions.json
.nova/*
# Prisma # Prisma
/prisma/migrations /prisma/migrations
@ -40,3 +41,6 @@ docker-compose.yaml
/store /store
/temp/* /temp/*
.DS_Store
*.DS_Store

View File

@ -2,8 +2,11 @@ module.exports = {
semi: true, semi: true,
trailingComma: 'all', trailingComma: 'all',
singleQuote: true, singleQuote: true,
printWidth: 90, printWidth: 120,
arrowParens: 'always',
tabWidth: 2, tabWidth: 2,
bracketSameLine: true, useTabs: false,
bracketSpacing: true bracketSameLine: false,
bracketSpacing: true,
parser: 'typescript'
} }

View File

@ -1,3 +1,11 @@
# 1.4.6 (homolog)
### Fixed
* Fixed bug of creating new inbox by chatwoot
* When conversation reopens is pending when conversation pending is true
* Added docker-compose file with dockerhub image
# 1.4.5 (2023-07-26 09:32) # 1.4.5 (2023-07-26 09:32)
### Fixed ### Fixed

View File

@ -0,0 +1,28 @@
version: '3.3'
services:
api:
container_name: evolution_api
image: davidsongomes/evolution-api:latest
restart: always
ports:
- 8080:8080
volumes:
- evolution_instances:/evolution/instances
- evolution_store:/evolution/store
networks:
- evolution-net
env_file:
- ./Docker/.env
command: ['node', './dist/src/main.js']
expose:
- 8080
volumes:
evolution_instances:
evolution_store:
networks:
evolution-net:
external: true

View File

@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "1.4.5", "version": "1.4.6",
"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": {
@ -8,7 +8,8 @@
"start": "ts-node --files --transpile-only ./src/main.ts", "start": "ts-node --files --transpile-only ./src/main.ts",
"start:prod": "bash start.sh", "start:prod": "bash start.sh",
"dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts", "dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts",
"test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts" "test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts",
"lint": "eslint --fix --ext .ts src"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -80,16 +81,19 @@
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/js-yaml": "^4.0.5", "@types/js-yaml": "^4.0.5",
"@types/jsonwebtoken": "^8.5.9", "@types/jsonwebtoken": "^8.5.9",
"@types/mime-types": "^2.1.1",
"@types/node": "^18.15.11", "@types/node": "^18.15.11",
"@types/qrcode": "^1.5.0", "@types/qrcode": "^1.5.0",
"@types/qrcode-terminal": "^0.12.0", "@types/qrcode-terminal": "^0.12.0",
"@types/uuid": "^8.3.4", "@types/uuid": "^8.3.4",
"@typescript-eslint/eslint-plugin": "^5.57.1", "@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.57.1", "@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.38.0", "eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1", "eslint-plugin-prettier": "^4.2.1",
"prettier": "^2.8.7", "eslint-plugin-simple-import-sort": "^10.0.0",
"prettier": "^2.8.8",
"ts-node-dev": "^2.0.0", "ts-node-dev": "^2.0.0",
"typescript": "^4.9.5" "typescript": "^4.9.5"
} }

View File

@ -1,7 +1,7 @@
import { isBooleanString } from 'class-validator';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { load } from 'js-yaml'; import { load } from 'js-yaml';
import { join } from 'path'; import { join } from 'path';
import { isBooleanString } from 'class-validator';
export type HttpServer = { TYPE: 'http' | 'https'; PORT: number; URL: string }; export type HttpServer = { TYPE: 'http' | 'https'; PORT: number; URL: string };
@ -14,15 +14,7 @@ export type Cors = {
export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
export type LogLevel = export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS';
| 'ERROR'
| 'WARN'
| 'DEBUG'
| 'INFO'
| 'LOG'
| 'VERBOSE'
| 'DARK'
| 'WEBHOOKS';
export type Log = { export type Log = {
LEVEL: LogLevel[]; LEVEL: LogLevel[];
@ -156,9 +148,7 @@ export class ConfigService {
} }
private envYaml(): Env { private envYaml(): Env {
return load( return load(readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' })) as Env;
readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' }),
) as Env;
} }
private envProcess(): Env { private envProcess(): Env {
@ -244,8 +234,7 @@ export class ConfigService {
CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true', CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true',
GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true', GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true',
GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true', GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE: GROUP_PARTICIPANTS_UPDATE: process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
CALL: process.env?.WEBHOOK_EVENTS_CALL === 'true', CALL: process.env?.WEBHOOK_EVENTS_CALL === 'true',
NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true', NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true',
}, },
@ -262,8 +251,7 @@ export class ConfigService {
API_KEY: { API_KEY: {
KEY: process.env.AUTHENTICATION_API_KEY, KEY: process.env.AUTHENTICATION_API_KEY,
}, },
EXPOSE_IN_FETCH_INSTANCES: EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
JWT: { JWT: {
EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN) EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN)
? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN) ? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN)

View File

@ -1,6 +1,7 @@
import { configService, Log } from './env.config';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { configService, Log } from './env.config';
const formatDateLog = (timestamp: number) => const formatDateLog = (timestamp: number) =>
dayjs(timestamp) dayjs(timestamp)
.toDate() .toDate()

View File

@ -1,4 +1,5 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { configService, Database } from '../config/env.config'; import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config'; import { Logger } from '../config/logger.config';

View File

@ -1,7 +1,8 @@
import { createClient, RedisClientType } from '@redis/client'; import { createClient, RedisClientType } from '@redis/client';
import { Logger } from '../config/logger.config';
import { BufferJSON } from '@whiskeysockets/baileys'; import { BufferJSON } from '@whiskeysockets/baileys';
import { Redis } from '../config/env.config'; import { Redis } from '../config/env.config';
import { Logger } from '../config/logger.config';
export class RedisCache { export class RedisCache {
constructor() { constructor() {
@ -59,11 +60,7 @@ export class RedisCache {
this.logger.verbose('writeData: ' + field); this.logger.verbose('writeData: ' + field);
const json = JSON.stringify(data, BufferJSON.replacer); const json = JSON.stringify(data, BufferJSON.replacer);
return await this.client.hSet( return await this.client.hSet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field, json);
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
json,
);
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }
@ -72,10 +69,7 @@ export class RedisCache {
public async readData(field: string) { public async readData(field: string) {
try { try {
this.logger.verbose('readData: ' + field); this.logger.verbose('readData: ' + field);
const data = await this.client.hGet( const data = await this.client.hGet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
if (data) { if (data) {
this.logger.verbose('readData: ' + field + ' success'); this.logger.verbose('readData: ' + field + ' success');
@ -92,10 +86,7 @@ export class RedisCache {
public async removeData(field: string) { public async removeData(field: string) {
try { try {
this.logger.verbose('removeData: ' + field); this.logger.verbose('removeData: ' + field);
return await this.client.hDel( return await this.client.hDel(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }
@ -104,9 +95,7 @@ export class RedisCache {
public async delAll(hash?: string) { public async delAll(hash?: string) {
try { try {
this.logger.verbose('instance delAll: ' + hash); this.logger.verbose('instance delAll: ' + hash);
const result = await this.client.del( const result = await this.client.del(hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName);
hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
);
return result; return result;
} catch (error) { } catch (error) {

View File

@ -1,16 +1,18 @@
import 'express-async-errors';
// import * as Sentry from '@sentry/node';
import compression from 'compression'; import compression from 'compression';
import { configService, Cors, HttpServer } from './config/env.config';
import cors from 'cors'; import cors from 'cors';
import express, { json, NextFunction, Request, Response, urlencoded } from 'express'; import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
import { join } from 'path'; import { join } from 'path';
import { configService, Cors, HttpServer } from './config/env.config';
import { onUnexpectedError } from './config/error.config'; import { onUnexpectedError } from './config/error.config';
import { Logger } from './config/logger.config'; import { Logger } from './config/logger.config';
import { ROOT_DIR } from './config/path.config'; import { ROOT_DIR } from './config/path.config';
import { waMonitor } from './whatsapp/whatsapp.module';
import { HttpStatus, router } from './whatsapp/routers/index.router';
import 'express-async-errors';
import { ServerUP } from './utils/server-up'; import { ServerUP } from './utils/server-up';
import * as Sentry from '@sentry/node'; import { HttpStatus, router } from './whatsapp/routers/index.router';
import { waMonitor } from './whatsapp/whatsapp.module';
function initWA() { function initWA() {
waMonitor.loadInstance(); waMonitor.loadInstance();
@ -73,7 +75,7 @@ function bootstrap() {
// }); // });
app.use( app.use(
(err: Error, req: Request, res: Response, next: NextFunction) => { (err: Error, req: Request, res: Response) => {
if (err) { if (err) {
return res.status(err['status'] || 500).json(err); return res.status(err['status'] || 500).json(err);
} }
@ -96,9 +98,7 @@ function bootstrap() {
ServerUP.app = app; ServerUP.app = app;
const server = ServerUP[httpServer.TYPE]; const server = ServerUP[httpServer.TYPE];
server.listen(httpServer.PORT, () => server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));
logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT),
);
initWA(); initWA();

View File

@ -1,8 +1,9 @@
import { Express } from 'express'; import { Express } from 'express';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { configService, SslConf } from '../config/env.config';
import * as https from 'https';
import * as http from 'http'; import * as http from 'http';
import * as https from 'https';
import { configService, SslConf } from '../config/env.config';
export class ServerUP { export class ServerUP {
static #app: Express; static #app: Express;

View File

@ -6,6 +6,7 @@ import {
proto, proto,
SignalDataTypeMap, SignalDataTypeMap,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import { configService, Database } from '../config/env.config'; import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config'; import { Logger } from '../config/logger.config';
import { dbserver } from '../db/db.connect'; import { dbserver } from '../db/db.connect';
@ -24,12 +25,12 @@ export async function useMultiFileAuthStateDb(
const writeData = async (data: any, key: string): Promise<any> => { const writeData = async (data: any, key: string): Promise<any> => {
try { try {
await client.connect(); await client.connect();
return await collection.replaceOne( return await collection.replaceOne({ _id: key }, JSON.parse(JSON.stringify(data, BufferJSON.replacer)), {
{ _id: key }, upsert: true,
JSON.parse(JSON.stringify(data, BufferJSON.replacer)), });
{ upsert: true }, } catch (error) {
); logger.error(error);
} catch {} }
}; };
const readData = async (key: string): Promise<any> => { const readData = async (key: string): Promise<any> => {
@ -38,14 +39,18 @@ export async function useMultiFileAuthStateDb(
const data = await collection.findOne({ _id: key }); const data = await collection.findOne({ _id: key });
const creds = JSON.stringify(data); const creds = JSON.stringify(data);
return JSON.parse(creds, BufferJSON.reviver); return JSON.parse(creds, BufferJSON.reviver);
} catch {} } catch (error) {
logger.error(error);
}
}; };
const removeData = async (key: string) => { const removeData = async (key: string) => {
try { try {
await client.connect(); await client.connect();
return await collection.deleteOne({ _id: key }); return await collection.deleteOne({ _id: key });
} catch {} } catch (error) {
logger.error(error);
}
}; };
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds(); const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();

View File

@ -5,9 +5,9 @@ import {
proto, proto,
SignalDataTypeMap, SignalDataTypeMap,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import { RedisCache } from '../db/redis.client';
import { Logger } from '../config/logger.config'; import { Logger } from '../config/logger.config';
import { Redis } from '../config/env.config'; import { RedisCache } from '../db/redis.client';
export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{ export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
state: AuthenticationState; state: AuthenticationState;

View File

@ -877,23 +877,8 @@ export const chatwootSchema: JSONSchema7 = {
reopen_conversation: { type: 'boolean', enum: [true, false] }, reopen_conversation: { type: 'boolean', enum: [true, false] },
conversation_pending: { type: 'boolean', enum: [true, false] }, conversation_pending: { type: 'boolean', enum: [true, false] },
}, },
required: [ required: ['enabled', 'account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'],
'enabled', ...isNotEmpty('account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'),
'account_id',
'token',
'url',
'sign_msg',
'reopen_conversation',
'conversation_pending',
],
...isNotEmpty(
'account_id',
'token',
'url',
'sign_msg',
'reopen_conversation',
'conversation_pending',
),
}; };
export const settingsSchema: JSONSchema7 = { export const settingsSchema: JSONSchema7 = {
@ -907,18 +892,6 @@ export const settingsSchema: JSONSchema7 = {
read_messages: { type: 'boolean', enum: [true, false] }, read_messages: { type: 'boolean', enum: [true, false] },
read_status: { type: 'boolean', enum: [true, false] }, read_status: { type: 'boolean', enum: [true, false] },
}, },
required: [ required: ['reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'],
'reject_call', ...isNotEmpty('reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'),
'groups_ignore',
'always_online',
'read_messages',
'read_status',
],
...isNotEmpty(
'reject_call',
'groups_ignore',
'always_online',
'read_messages',
'read_status',
),
}; };

View File

@ -1,5 +1,6 @@
import { existsSync, mkdirSync, writeFileSync } from 'fs'; import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { ConfigService, Database } from '../../config/env.config'; import { ConfigService, Database } from '../../config/env.config';
import { ROOT_DIR } from '../../config/path.config'; import { ROOT_DIR } from '../../config/path.config';
@ -34,11 +35,9 @@ export abstract class Repository implements IRepository {
mkdirSync(create.path, { recursive: true }); mkdirSync(create.path, { recursive: true });
} }
try { try {
writeFileSync( writeFileSync(join(create.path, create.fileName + '.json'), JSON.stringify({ ...create.data }), {
join(create.path, create.fileName + '.json'), encoding: 'utf-8',
JSON.stringify({ ...create.data }), });
{ encoding: 'utf-8' },
);
return { message: 'create - success' }; return { message: 'create - success' };
} finally { } finally {
@ -46,19 +45,23 @@ export abstract class Repository implements IRepository {
} }
}; };
public insert(data: any, instanceName: string, saveDb = false): Promise<IInsert> { // eslint-disable-next-line
public insert(data: any, instanceName: string, saveDb = false): Promise<IInsert> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
public update(data: any, instanceName: string, saveDb = false): Promise<IInsert> { // eslint-disable-next-line
public update(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> { // eslint-disable-next-line
public find(query: any): Promise<any> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
delete(query: any, force?: boolean): Promise<any> { // eslint-disable-next-line
delete(query: any, force?: boolean): Promise<any> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
} }

View File

@ -1,11 +1,13 @@
import { InstanceDto } from '../dto/instance.dto';
import { JSONSchema7 } from 'json-schema';
import { Request } from 'express';
import { validate } from 'jsonschema';
import { BadRequestException } from '../../exceptions';
import 'express-async-errors'; import 'express-async-errors';
import { Request } from 'express';
import { JSONSchema7 } from 'json-schema';
import { validate } from 'jsonschema';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { GetParticipant, GroupInvite, GroupJid } from '../dto/group.dto'; import { GetParticipant, GroupInvite, GroupJid } from '../dto/group.dto';
import { InstanceDto } from '../dto/instance.dto';
type DataValidate<T> = { type DataValidate<T> = {
request: Request; request: Request;
@ -98,6 +100,7 @@ export abstract class RouterBroker {
public async groupValidate<T>(args: DataValidate<T>) { public async groupValidate<T>(args: DataValidate<T>) {
const { request, ClassRef, schema, execute } = args; const { request, ClassRef, schema, execute } = args;
const instance = request.params as unknown as InstanceDto; const instance = request.params as unknown as InstanceDto;
const body = request.body; const body = request.body;
@ -188,9 +191,7 @@ export abstract class RouterBroker {
const getParticipants = request.query as unknown as GetParticipant; const getParticipants = request.query as unknown as GetParticipant;
if (!getParticipants?.getParticipants) { if (!getParticipants?.getParticipants) {
throw new BadRequestException( throw new BadRequestException('The getParticipants needs to be informed in the query');
'The getParticipants needs to be informed in the query',
);
} }
const instance = request.params as unknown as InstanceDto; const instance = request.params as unknown as InstanceDto;

View File

@ -1,7 +1,8 @@
import { proto } from '@whiskeysockets/baileys'; import { Logger } from '../../config/logger.config';
import { import {
ArchiveChatDto, ArchiveChatDto,
DeleteMessage, DeleteMessage,
getBase64FromMediaMessageDto,
NumberDto, NumberDto,
PrivacySettingDto, PrivacySettingDto,
ProfileNameDto, ProfileNameDto,
@ -9,14 +10,12 @@ import {
ProfileStatusDto, ProfileStatusDto,
ReadMessageDto, ReadMessageDto,
WhatsAppNumberDto, WhatsAppNumberDto,
getBase64FromMediaMessageDto,
} from '../dto/chat.dto'; } from '../dto/chat.dto';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { ContactQuery } from '../repository/contact.repository'; import { ContactQuery } from '../repository/contact.repository';
import { MessageQuery } from '../repository/message.repository'; import { MessageQuery } from '../repository/message.repository';
import { MessageUpQuery } from '../repository/messageUp.repository'; import { MessageUpQuery } from '../repository/messageUp.repository';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('ChatController'); const logger = new Logger('ChatController');
@ -50,10 +49,7 @@ export class ChatController {
public async fetchProfile({ instanceName }: InstanceDto, data: NumberDto) { public async fetchProfile({ instanceName }: InstanceDto, data: NumberDto) {
logger.verbose('requested fetchProfile from ' + instanceName + ' instance'); logger.verbose('requested fetchProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchProfile( return await this.waMonitor.waInstances[instanceName].fetchProfile(instanceName, data.number);
instanceName,
data.number,
);
} }
public async fetchContacts({ instanceName }: InstanceDto, query: ContactQuery) { public async fetchContacts({ instanceName }: InstanceDto, query: ContactQuery) {
@ -61,13 +57,8 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchContacts(query); return await this.waMonitor.waInstances[instanceName].fetchContacts(query);
} }
public async getBase64FromMediaMessage( public async getBase64FromMediaMessage({ instanceName }: InstanceDto, data: getBase64FromMediaMessageDto) {
{ instanceName }: InstanceDto, logger.verbose('requested getBase64FromMediaMessage from ' + instanceName + ' instance');
data: getBase64FromMediaMessageDto,
) {
logger.verbose(
'requested getBase64FromMediaMessage from ' + instanceName + ' instance',
);
return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data); return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data);
} }
@ -91,22 +82,14 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings(); return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings();
} }
public async updatePrivacySettings( public async updatePrivacySettings({ instanceName }: InstanceDto, data: PrivacySettingDto) {
{ instanceName }: InstanceDto,
data: PrivacySettingDto,
) {
logger.verbose('requested updatePrivacySettings from ' + instanceName + ' instance'); logger.verbose('requested updatePrivacySettings from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data); return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data);
} }
public async fetchBusinessProfile( public async fetchBusinessProfile({ instanceName }: InstanceDto, data: ProfilePictureDto) {
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
logger.verbose('requested fetchBusinessProfile from ' + instanceName + ' instance'); logger.verbose('requested fetchBusinessProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile( return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(data.number);
data.number,
);
} }
public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) { public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) {
@ -114,30 +97,17 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name); return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name);
} }
public async updateProfileStatus( public async updateProfileStatus({ instanceName }: InstanceDto, data: ProfileStatusDto) {
{ instanceName }: InstanceDto,
data: ProfileStatusDto,
) {
logger.verbose('requested updateProfileStatus from ' + instanceName + ' instance'); logger.verbose('requested updateProfileStatus from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfileStatus( return await this.waMonitor.waInstances[instanceName].updateProfileStatus(data.status);
data.status,
);
} }
public async updateProfilePicture( public async updateProfilePicture({ instanceName }: InstanceDto, data: ProfilePictureDto) {
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
logger.verbose('requested updateProfilePicture from ' + instanceName + ' instance'); logger.verbose('requested updateProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfilePicture( return await this.waMonitor.waInstances[instanceName].updateProfilePicture(data.picture);
data.picture,
);
} }
public async removeProfilePicture( public async removeProfilePicture({ instanceName }: InstanceDto) {
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
logger.verbose('requested removeProfilePicture from ' + instanceName + ' instance'); logger.verbose('requested removeProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].removeProfilePicture(); return await this.waMonitor.waInstances[instanceName].removeProfilePicture();
} }

View File

@ -1,24 +1,20 @@
import { isURL } from 'class-validator'; import { isURL } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { ChatwootService } from '../services/chatwoot.service';
import { Logger } from '../../config/logger.config';
import { waMonitor } from '../whatsapp.module';
import { ConfigService, HttpServer } from '../../config/env.config'; import { ConfigService, HttpServer } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootService } from '../services/chatwoot.service';
import { waMonitor } from '../whatsapp.module';
const logger = new Logger('ChatwootController'); const logger = new Logger('ChatwootController');
export class ChatwootController { export class ChatwootController {
constructor( constructor(private readonly chatwootService: ChatwootService, private readonly configService: ConfigService) {}
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('requested createChatwoot from ' + instance.instanceName + ' instance');
'requested createChatwoot from ' + instance.instanceName + ' instance',
);
if (data.enabled) { if (data.enabled) {
if (!isURL(data.url, { require_tld: false })) { if (!isURL(data.url, { require_tld: false })) {
@ -89,9 +85,7 @@ export class ChatwootController {
} }
public async receiveWebhook(instance: InstanceDto, data: any) { public async receiveWebhook(instance: InstanceDto, data: any) {
logger.verbose( logger.verbose('requested receiveWebhook from ' + instance.instanceName + ' instance');
'requested receiveWebhook from ' + instance.instanceName + ' instance',
);
const chatwootService = new ChatwootService(waMonitor, this.configService); const chatwootService = new ChatwootService(waMonitor, this.configService);
return chatwootService.receiveWebhook(instance, data); return chatwootService.receiveWebhook(instance, data);

View File

@ -1,3 +1,4 @@
import { Logger } from '../../config/logger.config';
import { import {
CreateGroupDto, CreateGroupDto,
GetParticipant, GetParticipant,
@ -13,7 +14,6 @@ import {
} from '../dto/group.dto'; } from '../dto/group.dto';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('ChatController'); const logger = new Logger('ChatController');
@ -26,33 +26,18 @@ export class GroupController {
} }
public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) { public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) {
logger.verbose( logger.verbose('requested updateGroupPicture from ' + instance.instanceName + ' instance');
'requested updateGroupPicture from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(update);
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(
update,
);
} }
public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) { public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) {
logger.verbose( logger.verbose('requested updateGroupSubject from ' + instance.instanceName + ' instance');
'requested updateGroupSubject from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(update);
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(
update,
);
} }
public async updateGroupDescription( public async updateGroupDescription(instance: InstanceDto, update: GroupDescriptionDto) {
instance: InstanceDto, logger.verbose('requested updateGroupDescription from ' + instance.instanceName + ' instance');
update: GroupDescriptionDto, return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(update);
) {
logger.verbose(
'requested updateGroupDescription from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(
update,
);
} }
public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) { public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) {
@ -61,12 +46,8 @@ export class GroupController {
} }
public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) { public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) {
logger.verbose( logger.verbose('requested fetchAllGroups from ' + instance.instanceName + ' instance');
'requested fetchAllGroups from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(getPaticipants);
);
return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(
getPaticipants,
);
} }
public async inviteCode(instance: InstanceDto, groupJid: GroupJid) { public async inviteCode(instance: InstanceDto, groupJid: GroupJid) {
@ -85,49 +66,28 @@ export class GroupController {
} }
public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) { public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose( logger.verbose('requested revokeInviteCode from ' + instance.instanceName + ' instance');
'requested revokeInviteCode from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(groupJid);
);
return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(
groupJid,
);
} }
public async findParticipants(instance: InstanceDto, groupJid: GroupJid) { public async findParticipants(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose( logger.verbose('requested findParticipants from ' + instance.instanceName + ' instance');
'requested findParticipants from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].findParticipants(groupJid);
);
return await this.waMonitor.waInstances[instance.instanceName].findParticipants(
groupJid,
);
} }
public async updateGParticipate( public async updateGParticipate(instance: InstanceDto, update: GroupUpdateParticipantDto) {
instance: InstanceDto, logger.verbose('requested updateGParticipate from ' + instance.instanceName + ' instance');
update: GroupUpdateParticipantDto, return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(update);
) {
logger.verbose(
'requested updateGParticipate from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(
update,
);
} }
public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) { public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) {
logger.verbose( logger.verbose('requested updateGSetting from ' + instance.instanceName + ' instance');
'requested updateGSetting from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update); return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update);
} }
public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) { public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) {
logger.verbose( logger.verbose('requested toggleEphemeral from ' + instance.instanceName + ' instance');
'requested toggleEphemeral from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(update);
);
return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(
update,
);
} }
public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) { public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) {

View File

@ -1,19 +1,20 @@
import { delay } from '@whiskeysockets/baileys'; import { delay } from '@whiskeysockets/baileys';
import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2'; import EventEmitter2 from 'eventemitter2';
import { Auth, ConfigService, HttpServer } from '../../config/env.config';
import { ConfigService, HttpServer } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { RedisCache } from '../../db/redis.client';
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';
import { AuthService, OldToken } from '../services/auth.service'; import { AuthService, OldToken } from '../services/auth.service';
import { WAMonitoringService } from '../services/monitor.service';
import { WAStartupService } from '../services/whatsapp.service';
import { WebhookService } from '../services/webhook.service';
import { ChatwootService } from '../services/chatwoot.service'; import { ChatwootService } from '../services/chatwoot.service';
import { Logger } from '../../config/logger.config'; import { WAMonitoringService } from '../services/monitor.service';
import { wa } from '../types/wa.types';
import { RedisCache } from '../../db/redis.client';
import { isURL } from 'class-validator';
import { SettingsService } from '../services/settings.service'; import { SettingsService } from '../services/settings.service';
import { WebhookService } from '../services/webhook.service';
import { WAStartupService } from '../services/whatsapp.service';
import { wa } from '../types/wa.types';
export class InstanceController { export class InstanceController {
constructor( constructor(
@ -55,21 +56,14 @@ export class InstanceController {
this.logger.verbose('requested createInstance from ' + instanceName + ' instance'); this.logger.verbose('requested createInstance from ' + instanceName + ' instance');
if (instanceName !== instanceName.toLowerCase().replace(/[^a-z0-9]/g, '')) { if (instanceName !== instanceName.toLowerCase().replace(/[^a-z0-9]/g, '')) {
throw new BadRequestException( throw new BadRequestException('The instance name must be lowercase and without special characters');
'The instance name must be lowercase and without special characters',
);
} }
this.logger.verbose('checking duplicate token'); this.logger.verbose('checking duplicate token');
await this.authService.checkDuplicateToken(token); await this.authService.checkDuplicateToken(token);
this.logger.verbose('creating instance'); this.logger.verbose('creating instance');
const instance = new WAStartupService( const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
instance.instanceName = instanceName instance.instanceName = instanceName
.toLowerCase() .toLowerCase()
.replace(/[^a-z0-9]/g, '') .replace(/[^a-z0-9]/g, '')
@ -175,17 +169,11 @@ export class InstanceController {
throw new BadRequestException('sign_msg is required'); throw new BadRequestException('sign_msg is required');
} }
if ( if (chatwoot_reopen_conversation !== true && chatwoot_reopen_conversation !== false) {
chatwoot_reopen_conversation !== true &&
chatwoot_reopen_conversation !== false
) {
throw new BadRequestException('reopen_conversation is required'); throw new BadRequestException('reopen_conversation is required');
} }
if ( if (chatwoot_conversation_pending !== true && chatwoot_conversation_pending !== false) {
chatwoot_conversation_pending !== true &&
chatwoot_conversation_pending !== false
) {
throw new BadRequestException('conversation_pending is required'); throw new BadRequestException('conversation_pending is required');
} }
@ -246,9 +234,7 @@ export class InstanceController {
public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) { public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) {
try { try {
this.logger.verbose( this.logger.verbose('requested connectToWhatsapp from ' + instanceName + ' instance');
'requested connectToWhatsapp from ' + instanceName + ' instance',
);
const instance = this.waMonitor.waInstances[instanceName]; const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state; const state = instance?.connectionStatus?.state;
@ -321,16 +307,12 @@ export class InstanceController {
const { instance } = await this.connectionState({ instanceName }); const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'close') { if (instance.state === 'close') {
throw new BadRequestException( throw new BadRequestException('The "' + instanceName + '" instance is not connected');
'The "' + instanceName + '" instance is not connected',
);
} }
try { try {
this.logger.verbose('logging out instance: ' + instanceName); this.logger.verbose('logging out instance: ' + instanceName);
await this.waMonitor.waInstances[instanceName]?.client?.logout( await this.waMonitor.waInstances[instanceName]?.client?.logout('Log out instance: ' + instanceName);
'Log out instance: ' + instanceName,
);
this.logger.verbose('close connection instance: ' + instanceName); this.logger.verbose('close connection instance: ' + instanceName);
this.waMonitor.waInstances[instanceName]?.client?.ws?.close(); this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
@ -346,9 +328,7 @@ export class InstanceController {
const { instance } = await this.connectionState({ instanceName }); const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'open') { if (instance.state === 'open') {
throw new BadRequestException( throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected');
'The "' + instanceName + '" instance needs to be disconnected',
);
} }
try { try {
if (instance.state === 'connecting') { if (instance.state === 'connecting') {

View File

@ -1,4 +1,6 @@
import { isBase64, isURL } from 'class-validator'; import { isBase64, isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { import {
@ -16,8 +18,6 @@ import {
} from '../dto/sendMessage.dto'; } from '../dto/sendMessage.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('MessageRouter'); const logger = new Logger('MessageRouter');
export class SendMessageController { export class SendMessageController {
@ -39,12 +39,7 @@ export class SendMessageController {
throw new BadRequestException('For base64 the file name must be informed.'); throw new BadRequestException('For base64 the file name must be informed.');
} }
logger.verbose( logger.verbose('isURL: ' + isURL(data?.mediaMessage?.media) + ', isBase64: ' + isBase64(data?.mediaMessage?.media));
'isURL: ' +
isURL(data?.mediaMessage?.media) +
', isBase64: ' +
isBase64(data?.mediaMessage?.media),
);
if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) { if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) {
return await this.waMonitor.waInstances[instanceName].mediaMessage(data); return await this.waMonitor.waInstances[instanceName].mediaMessage(data);
} }
@ -55,10 +50,7 @@ export class SendMessageController {
logger.verbose('requested sendSticker from ' + instanceName + ' instance'); logger.verbose('requested sendSticker from ' + instanceName + ' instance');
logger.verbose( logger.verbose(
'isURL: ' + 'isURL: ' + isURL(data?.stickerMessage?.image) + ', isBase64: ' + isBase64(data?.stickerMessage?.image),
isURL(data?.stickerMessage?.image) +
', isBase64: ' +
isBase64(data?.stickerMessage?.image),
); );
if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) { if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) {
return await this.waMonitor.waInstances[instanceName].mediaSticker(data); return await this.waMonitor.waInstances[instanceName].mediaSticker(data);
@ -69,12 +61,7 @@ export class SendMessageController {
public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) { public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) {
logger.verbose('requested sendWhatsAppAudio from ' + instanceName + ' instance'); logger.verbose('requested sendWhatsAppAudio from ' + instanceName + ' instance');
logger.verbose( logger.verbose('isURL: ' + isURL(data?.audioMessage?.audio) + ', isBase64: ' + isBase64(data?.audioMessage?.audio));
'isURL: ' +
isURL(data?.audioMessage?.audio) +
', isBase64: ' +
isBase64(data?.audioMessage?.audio),
);
if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) { if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) {
return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data); return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data);
} }
@ -83,10 +70,7 @@ export class SendMessageController {
public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) { public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) {
logger.verbose('requested sendButtons from ' + instanceName + ' instance'); logger.verbose('requested sendButtons from ' + instanceName + ' instance');
if ( if (isBase64(data.buttonMessage.mediaMessage?.media) && !data.buttonMessage.mediaMessage?.fileName) {
isBase64(data.buttonMessage.mediaMessage?.media) &&
!data.buttonMessage.mediaMessage?.fileName
) {
throw new BadRequestException('For bse64 the file name must be informed.'); throw new BadRequestException('For bse64 the file name must be informed.');
} }
return await this.waMonitor.waInstances[instanceName].buttonMessage(data); return await this.waMonitor.waInstances[instanceName].buttonMessage(data);
@ -109,7 +93,7 @@ export class SendMessageController {
public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) { public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) {
logger.verbose('requested sendReaction from ' + instanceName + ' instance'); logger.verbose('requested sendReaction from ' + instanceName + ' instance');
if (!data.reactionMessage.reaction.match(/[^\(\)\w\sà-ú"-\+]+/)) { if (!data.reactionMessage.reaction.match(/[^()\w\sà-ú"-+]+/)) {
throw new BadRequestException('"reaction" must be an emoji'); throw new BadRequestException('"reaction" must be an emoji');
} }
return await this.waMonitor.waInstances[instanceName].reactionMessage(data); return await this.waMonitor.waInstances[instanceName].reactionMessage(data);

View File

@ -1,9 +1,10 @@
import { isURL } from 'class-validator'; // import { isURL } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import { Logger } from '../../config/logger.config';
// import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto'; import { SettingsDto } from '../dto/settings.dto';
import { SettingsService } from '../services/settings.service'; import { SettingsService } from '../services/settings.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('SettingsController'); const logger = new Logger('SettingsController');
@ -11,9 +12,8 @@ export class SettingsController {
constructor(private readonly settingsService: SettingsService) {} constructor(private readonly settingsService: SettingsService) {}
public async createSettings(instance: InstanceDto, data: SettingsDto) { public async createSettings(instance: InstanceDto, data: SettingsDto) {
logger.verbose(
'requested createSettings from ' + instance.instanceName + ' instance', logger.verbose('requested createSettings from ' + instance.instanceName + ' instance');
);
return this.settingsService.create(instance, data); return this.settingsService.create(instance, data);
} }

View File

@ -1,4 +1,5 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { Auth, ConfigService } from '../../config/env.config'; import { Auth, ConfigService } from '../../config/env.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
@ -6,10 +7,7 @@ import { HttpStatus } from '../routers/index.router';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
export class ViewsController { export class ViewsController {
constructor( constructor(private readonly waMonit: WAMonitoringService, private readonly configService: ConfigService) {}
private readonly waMonit: WAMonitoringService,
private readonly configService: ConfigService,
) {}
public async qrcode(request: Request, response: Response) { public async qrcode(request: Request, response: Response) {
try { try {

View File

@ -1,9 +1,10 @@
import { isURL } from 'class-validator'; import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { WebhookService } from '../services/webhook.service'; import { WebhookService } from '../services/webhook.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('WebhookController'); const logger = new Logger('WebhookController');

View File

@ -1,16 +1,7 @@
import { import { proto, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
WAPrivacyOnlineValue,
WAPrivacyValue,
WAReadReceiptsValue,
proto,
} from '@whiskeysockets/baileys';
export class OnWhatsAppDto { export class OnWhatsAppDto {
constructor( constructor(public readonly jid: string, public readonly exists: boolean, public readonly name?: string) {}
public readonly jid: string,
public readonly exists: boolean,
public readonly name?: string,
) {}
} }
export class getBase64FromMediaMessageDto { export class getBase64FromMediaMessageDto {

View File

@ -1,12 +1,13 @@
import { isJWT } from 'class-validator'; import { isJWT } from 'class-validator';
import { NextFunction, Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { name } from '../../../package.json';
import { Auth, configService } from '../../config/env.config'; import { Auth, configService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { name } from '../../../package.json'; import { ForbiddenException, UnauthorizedException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { JwtPayload } from '../services/auth.service'; import { JwtPayload } from '../services/auth.service';
import { ForbiddenException, UnauthorizedException } from '../../exceptions';
import { repository } from '../whatsapp.module'; import { repository } from '../whatsapp.module';
const logger = new Logger('GUARD'); const logger = new Logger('GUARD');
@ -22,15 +23,8 @@ async function jwtGuard(req: Request, res: Response, next: NextFunction) {
return next(); return next();
} }
if ( if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
(req.originalUrl.includes('/instance/create') || throw new ForbiddenException('Missing global api key', 'The global api key must be set');
req.originalUrl.includes('/instance/fetchInstances')) &&
!key
) {
throw new ForbiddenException(
'Missing global api key',
'The global api key must be set',
);
} }
const jwtOpts = configService.get<Auth>('AUTHENTICATION').JWT; const jwtOpts = configService.get<Auth>('AUTHENTICATION').JWT;
@ -69,15 +63,8 @@ async function apikey(req: Request, res: Response, next: NextFunction) {
return next(); return next();
} }
if ( if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
(req.originalUrl.includes('/instance/create') || throw new ForbiddenException('Missing global api key', 'The global api key must be set');
req.originalUrl.includes('/instance/fetchInstances')) &&
!key
) {
throw new ForbiddenException(
'Missing global api key',
'The global api key must be set',
);
} }
try { try {
@ -86,7 +73,9 @@ async function apikey(req: Request, res: Response, next: NextFunction) {
if (instanceKey.apikey === key) { if (instanceKey.apikey === key) {
return next(); return next();
} }
} catch (error) {} } catch (error) {
logger.error(error);
}
throw new UnauthorizedException(); throw new UnauthorizedException();
} }

View File

@ -1,16 +1,13 @@
import { NextFunction, Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { configService, Database, Redis } from '../../config/env.config';
import { INSTANCE_DIR } from '../../config/path.config'; import { INSTANCE_DIR } from '../../config/path.config';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
import { import { BadRequestException, ForbiddenException, NotFoundException } from '../../exceptions';
BadRequestException,
ForbiddenException,
NotFoundException,
} from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { cache, waMonitor } from '../whatsapp.module'; import { cache, waMonitor } from '../whatsapp.module';
import { Database, Redis, configService } from '../../config/env.config';
async function getInstance(instanceName: string) { async function getInstance(instanceName: string) {
const db = configService.get<Database>('DATABASE'); const db = configService.get<Database>('DATABASE');
@ -35,10 +32,7 @@ async function getInstance(instanceName: string) {
} }
export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) { export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) {
if ( if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) {
req.originalUrl.includes('/instance/create') ||
req.originalUrl.includes('/instance/fetchInstances')
) {
return next(); return next();
} }
@ -58,9 +52,7 @@ export async function instanceLoggedGuard(req: Request, _: Response, next: NextF
if (req.originalUrl.includes('/instance/create')) { if (req.originalUrl.includes('/instance/create')) {
const instance = req.body as InstanceDto; const instance = req.body as InstanceDto;
if (await getInstance(instance.instanceName)) { if (await getInstance(instance.instanceName)) {
throw new ForbiddenException( throw new ForbiddenException(`This name "${instance.instanceName}" is already in use.`);
`This name "${instance.instanceName}" is already in use.`,
);
} }
if (waMonitor.waInstances[instance.instanceName]) { if (waMonitor.waInstances[instance.instanceName]) {

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class AuthRaw { export class AuthRaw {

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class ChatRaw { export class ChatRaw {

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class ChatwootRaw { export class ChatwootRaw {
@ -25,9 +26,5 @@ const chatwootSchema = new Schema<ChatwootRaw>({
number: { type: String, required: true }, number: { type: String, required: true },
}); });
export const ChatwootModel = dbserver?.model( export const ChatwootModel = dbserver?.model(ChatwootRaw.name, chatwootSchema, 'chatwoot');
ChatwootRaw.name,
chatwootSchema,
'chatwoot',
);
export type IChatwootModel = typeof ChatwootModel; export type IChatwootModel = typeof ChatwootModel;

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class ContactRaw { export class ContactRaw {

View File

@ -1,7 +1,7 @@
export * from './auth.model';
export * from './chat.model'; export * from './chat.model';
export * from './chatwoot.model';
export * from './contact.model'; export * from './contact.model';
export * from './message.model'; export * from './message.model';
export * from './auth.model';
export * from './webhook.model';
export * from './chatwoot.model';
export * from './settings.model'; export * from './settings.model';
export * from './webhook.model';

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
import { wa } from '../types/wa.types'; import { wa } from '../types/wa.types';
@ -64,9 +65,5 @@ const messageUpdateSchema = new Schema<MessageUpdateRaw>({
owner: { type: String, required: true, min: 1 }, owner: { type: String, required: true, min: 1 },
}); });
export const MessageUpModel = dbserver?.model( export const MessageUpModel = dbserver?.model(MessageUpdateRaw.name, messageUpdateSchema, 'messageUpdate');
MessageUpdateRaw.name,
messageUpdateSchema,
'messageUpdate',
);
export type IMessageUpModel = typeof MessageUpModel; export type IMessageUpModel = typeof MessageUpModel;

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class SettingsRaw { export class SettingsRaw {
@ -21,9 +22,5 @@ const settingsSchema = new Schema<SettingsRaw>({
read_status: { type: Boolean, required: true }, read_status: { type: Boolean, required: true },
}); });
export const SettingsModel = dbserver?.model( export const SettingsModel = dbserver?.model(SettingsRaw.name, settingsSchema, 'settings');
SettingsRaw.name,
settingsSchema,
'settings',
);
export type ISettingsModel = typeof SettingsModel; export type ISettingsModel = typeof SettingsModel;

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class WebhookRaw { export class WebhookRaw {

View File

@ -1,16 +1,14 @@
import { join } from 'path';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IAuthModel, AuthRaw } from '../models';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { AUTH_DIR } from '../../config/path.config'; import { join } from 'path';
import { Auth, ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { AUTH_DIR } from '../../config/path.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { AuthRaw, IAuthModel } from '../models';
export class AuthRepository extends Repository { export class AuthRepository extends Repository {
constructor( constructor(private readonly authModel: IAuthModel, readonly configService: ConfigService) {
private readonly authModel: IAuthModel,
readonly configService: ConfigService,
) {
super(configService); super(configService);
this.auth = configService.get<Auth>('AUTHENTICATION'); this.auth = configService.get<Auth>('AUTHENTICATION');
} }
@ -23,11 +21,7 @@ export class AuthRepository extends Repository {
this.logger.verbose('creating auth'); this.logger.verbose('creating auth');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving auth to db'); this.logger.verbose('saving auth to db');
const insert = await this.authModel.replaceOne( const insert = await this.authModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
{ _id: instance },
{ ...data },
{ upsert: true },
);
this.logger.verbose('auth saved to db: ' + insert.modifiedCount + ' auth'); this.logger.verbose('auth saved to db: ' + insert.modifiedCount + ' auth');
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
@ -40,9 +34,7 @@ export class AuthRepository extends Repository {
fileName: instance, fileName: instance,
data, data,
}); });
this.logger.verbose( this.logger.verbose('auth saved to store in path: ' + join(AUTH_DIR, this.auth.TYPE) + '/' + instance);
'auth saved to store in path: ' + join(AUTH_DIR, this.auth.TYPE) + '/' + instance,
);
this.logger.verbose('auth created'); this.logger.verbose('auth created');
return { insertCount: 1 }; return { insertCount: 1 };

View File

@ -1,29 +1,23 @@
import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync, rmSync } from 'fs'; import { opendirSync, readFileSync, rmSync } from 'fs';
import { ChatRaw, IChatModel } from '../models'; import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ChatRaw, IChatModel } from '../models';
export class ChatQuery { export class ChatQuery {
where: ChatRaw; where: ChatRaw;
} }
export class ChatRepository extends Repository { export class ChatRepository extends Repository {
constructor( constructor(private readonly chatModel: IChatModel, private readonly configService: ConfigService) {
private readonly chatModel: IChatModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('ChatRepository'); private readonly logger = new Logger('ChatRepository');
public async insert( public async insert(data: ChatRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: ChatRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
this.logger.verbose('inserting chats'); this.logger.verbose('inserting chats');
if (data.length === 0) { if (data.length === 0) {
this.logger.verbose('no chats to insert'); this.logger.verbose('no chats to insert');
@ -53,10 +47,7 @@ export class ChatRepository extends Repository {
data: chat, data: chat,
}); });
this.logger.verbose( this.logger.verbose(
'chats saved to store in path: ' + 'chats saved to store in path: ' + join(this.storePath, 'chats', instanceName) + '/' + chat.id,
join(this.storePath, 'chats', instanceName) +
'/' +
chat.id,
); );
}); });
@ -89,10 +80,9 @@ export class ChatRepository extends Repository {
if (dirent.isFile()) { if (dirent.isFile()) {
chats.push( chats.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'chats', query.where.owner, dirent.name), {
join(this.storePath, 'chats', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }

View File

@ -1,15 +1,13 @@
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ConfigService } from '../../config/env.config';
import { join } from 'path';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { IChatwootModel, ChatwootRaw } from '../models'; import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ChatwootRaw, IChatwootModel } from '../models';
export class ChatwootRepository extends Repository { export class ChatwootRepository extends Repository {
constructor( constructor(private readonly chatwootModel: IChatwootModel, private readonly configService: ConfigService) {
private readonly chatwootModel: IChatwootModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
@ -20,15 +18,9 @@ export class ChatwootRepository extends Repository {
this.logger.verbose('creating chatwoot'); this.logger.verbose('creating chatwoot');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving chatwoot to db'); this.logger.verbose('saving chatwoot to db');
const insert = await this.chatwootModel.replaceOne( const insert = await this.chatwootModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
{ _id: instance },
{ ...data },
{ upsert: true },
);
this.logger.verbose( this.logger.verbose('chatwoot saved to db: ' + insert.modifiedCount + ' chatwoot');
'chatwoot saved to db: ' + insert.modifiedCount + ' chatwoot',
);
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
} }
@ -40,12 +32,7 @@ export class ChatwootRepository extends Repository {
data, data,
}); });
this.logger.verbose( this.logger.verbose('chatwoot saved to store in path: ' + join(this.storePath, 'chatwoot') + '/' + instance);
'chatwoot saved to store in path: ' +
join(this.storePath, 'chatwoot') +
'/' +
instance,
);
this.logger.verbose('chatwoot created'); this.logger.verbose('chatwoot created');
return { insertCount: 1 }; return { insertCount: 1 };

View File

@ -1,29 +1,23 @@
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config'; import { ConfigService, StoreConf } from '../../config/env.config';
import { ContactRaw, IContactModel } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ContactRaw, IContactModel } from '../models';
export class ContactQuery { export class ContactQuery {
where: ContactRaw; where: ContactRaw;
} }
export class ContactRepository extends Repository { export class ContactRepository extends Repository {
constructor( constructor(private readonly contactModel: IContactModel, private readonly configService: ConfigService) {
private readonly contactModel: IContactModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('ContactRepository'); private readonly logger = new Logger('ContactRepository');
public async insert( public async insert(data: ContactRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
this.logger.verbose('inserting contacts'); this.logger.verbose('inserting contacts');
if (data.length === 0) { if (data.length === 0) {
@ -54,10 +48,7 @@ export class ContactRepository extends Repository {
data: contact, data: contact,
}); });
this.logger.verbose( this.logger.verbose(
'contacts saved to store in path: ' + 'contacts saved to store in path: ' + join(this.storePath, 'contacts', instanceName) + '/' + contact.id,
join(this.storePath, 'contacts', instanceName) +
'/' +
contact.id,
); );
}); });
@ -74,11 +65,7 @@ export class ContactRepository extends Repository {
} }
} }
public async update( public async update(data: ContactRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
try { try {
this.logger.verbose('updating contacts'); this.logger.verbose('updating contacts');
@ -119,10 +106,7 @@ export class ContactRepository extends Repository {
data: contact, data: contact,
}); });
this.logger.verbose( this.logger.verbose(
'contacts updated in store in path: ' + 'contacts updated in store in path: ' + join(this.storePath, 'contacts', instanceName) + '/' + contact.id,
join(this.storePath, 'contacts', instanceName) +
'/' +
contact.id,
); );
}); });
@ -154,15 +138,9 @@ export class ContactRepository extends Repository {
this.logger.verbose('finding contacts in store by id'); this.logger.verbose('finding contacts in store by id');
contacts.push( contacts.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'contacts', query.where.owner, query.where.id + '.json'), {
join( encoding: 'utf-8',
this.storePath, }),
'contacts',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
), ),
); );
} else { } else {
@ -175,10 +153,9 @@ export class ContactRepository extends Repository {
if (dirent.isFile()) { if (dirent.isFile()) {
contacts.push( contacts.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'contacts', query.where.owner, dirent.name), {
join(this.storePath, 'contacts', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }

View File

@ -1,9 +1,10 @@
import { ConfigService, StoreConf } from '../../config/env.config';
import { join } from 'path';
import { IMessageModel, MessageRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IMessageModel, MessageRaw } from '../models';
export class MessageQuery { export class MessageQuery {
where: MessageRaw; where: MessageRaw;
@ -11,20 +12,13 @@ export class MessageQuery {
} }
export class MessageRepository extends Repository { export class MessageRepository extends Repository {
constructor( constructor(private readonly messageModel: IMessageModel, private readonly configService: ConfigService) {
private readonly messageModel: IMessageModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('MessageRepository'); private readonly logger = new Logger('MessageRepository');
public async insert( public async insert(data: MessageRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: MessageRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
this.logger.verbose('inserting messages'); this.logger.verbose('inserting messages');
if (!Array.isArray(data) || data.length === 0) { if (!Array.isArray(data) || data.length === 0) {
@ -74,10 +68,7 @@ export class MessageRepository extends Repository {
data: message, data: message,
}); });
this.logger.verbose( this.logger.verbose(
'messages saved to store in path: ' + 'messages saved to store in path: ' + join(this.storePath, 'messages', instanceName) + '/' + message.key.id,
join(this.storePath, 'messages', instanceName) +
'/' +
message.key.id,
); );
}); });
@ -119,15 +110,9 @@ export class MessageRepository extends Repository {
this.logger.verbose('finding messages in store by id'); this.logger.verbose('finding messages in store by id');
messages.push( messages.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'messages', query.where.owner, query.where.key.id + '.json'), {
join( encoding: 'utf-8',
this.storePath, }),
'messages',
query.where.owner,
query.where.key.id + '.json',
),
{ encoding: 'utf-8' },
),
), ),
); );
} else { } else {
@ -140,10 +125,9 @@ export class MessageRepository extends Repository {
if (dirent.isFile()) { if (dirent.isFile()) {
messages.push( messages.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'messages', query.where.owner, dirent.name), {
join(this.storePath, 'messages', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }

View File

@ -1,9 +1,10 @@
import { ConfigService, StoreConf } from '../../config/env.config';
import { IMessageUpModel, MessageUpdateRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { join } from 'path';
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IMessageUpModel, MessageUpdateRaw } from '../models';
export class MessageUpQuery { export class MessageUpQuery {
where: MessageUpdateRaw; where: MessageUpdateRaw;
@ -11,20 +12,13 @@ export class MessageUpQuery {
} }
export class MessageUpRepository extends Repository { export class MessageUpRepository extends Repository {
constructor( constructor(private readonly messageUpModel: IMessageUpModel, private readonly configService: ConfigService) {
private readonly messageUpModel: IMessageUpModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('MessageUpRepository'); private readonly logger = new Logger('MessageUpRepository');
public async insert( public async insert(data: MessageUpdateRaw[], instanceName: string, saveDb?: boolean): Promise<IInsert> {
data: MessageUpdateRaw[],
instanceName: string,
saveDb?: boolean,
): Promise<IInsert> {
this.logger.verbose('inserting message up'); this.logger.verbose('inserting message up');
if (data.length === 0) { if (data.length === 0) {
@ -54,10 +48,7 @@ export class MessageUpRepository extends Repository {
data: update, data: update,
}); });
this.logger.verbose( this.logger.verbose(
'message up saved to store in path: ' + 'message up saved to store in path: ' + join(this.storePath, 'message-up', instanceName) + '/' + update.id,
join(this.storePath, 'message-up', instanceName) +
'/' +
update.id,
); );
}); });
@ -91,42 +82,32 @@ export class MessageUpRepository extends Repository {
messageUpdate.push( messageUpdate.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'message-up', query.where.owner, query.where.id + '.json'), {
join( encoding: 'utf-8',
this.storePath, }),
'message-up',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
), ),
); );
} else { } else {
this.logger.verbose('finding message up in store by owner'); this.logger.verbose('finding message up in store by owner');
const openDir = opendirSync( const openDir = opendirSync(join(this.storePath, 'message-up', query.where.owner), {
join(this.storePath, 'message-up', query.where.owner), encoding: 'utf-8',
{ encoding: 'utf-8' }, });
);
for await (const dirent of openDir) { for await (const dirent of openDir) {
if (dirent.isFile()) { if (dirent.isFile()) {
messageUpdate.push( messageUpdate.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'message-up', query.where.owner, dirent.name), {
join(this.storePath, 'message-up', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }
} }
} }
this.logger.verbose( this.logger.verbose('message up found in store: ' + messageUpdate.length + ' message up');
'message up found in store: ' + messageUpdate.length + ' message up',
);
return messageUpdate return messageUpdate
.sort((x, y) => { .sort((x, y) => {
return y.datetime - x.datetime; return y.datetime - x.datetime;

View File

@ -1,17 +1,17 @@
import { MessageRepository } from './message.repository';
import { ChatRepository } from './chat.repository';
import { ContactRepository } from './contact.repository';
import { MessageUpRepository } from './messageUp.repository';
import { MongoClient } from 'mongodb';
import { WebhookRepository } from './webhook.repository';
import { ChatwootRepository } from './chatwoot.repository';
import { SettingsRepository } from './settings.repository';
import { AuthRepository } from './auth.repository';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { join } from 'path';
import fs from 'fs'; import fs from 'fs';
import { MongoClient } from 'mongodb';
import { join } from 'path';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { AuthRepository } from './auth.repository';
import { ChatRepository } from './chat.repository';
import { ChatwootRepository } from './chatwoot.repository';
import { ContactRepository } from './contact.repository';
import { MessageRepository } from './message.repository';
import { MessageUpRepository } from './messageUp.repository';
import { SettingsRepository } from './settings.repository';
import { WebhookRepository } from './webhook.repository';
export class RepositoryBroker { export class RepositoryBroker {
constructor( constructor(
public readonly message: MessageRepository, public readonly message: MessageRepository,
@ -43,11 +43,7 @@ export class RepositoryBroker {
this.logger.verbose('creating store path: ' + storePath); this.logger.verbose('creating store path: ' + storePath);
try { try {
const authDir = join( const authDir = join(storePath, 'auth', this.configService.get<Auth>('AUTHENTICATION').TYPE);
storePath,
'auth',
this.configService.get<Auth>('AUTHENTICATION').TYPE,
);
const chatsDir = join(storePath, 'chats'); const chatsDir = join(storePath, 'chats');
const contactsDir = join(storePath, 'contacts'); const contactsDir = join(storePath, 'contacts');
const messagesDir = join(storePath, 'messages'); const messagesDir = join(storePath, 'messages');
@ -97,22 +93,23 @@ export class RepositoryBroker {
this.logger.error(error); this.logger.error(error);
} }
} else { } else {
const storePath = join(process.cwd(), 'store');
this.logger.verbose('creating store path: ' + storePath);
const tempDir = join(storePath, 'temp');
const chatwootDir = join(storePath, 'chatwoot');
if (!fs.existsSync(chatwootDir)) {
this.logger.verbose('creating chatwoot dir: ' + chatwootDir);
fs.mkdirSync(chatwootDir, { recursive: true });
}
if (!fs.existsSync(tempDir)) {
this.logger.verbose('creating temp dir: ' + tempDir);
fs.mkdirSync(tempDir, { recursive: true });
}
try { try {
const storePath = join(process.cwd(), 'store');
this.logger.verbose('creating store path: ' + storePath);
const tempDir = join(storePath, 'temp');
const chatwootDir = join(storePath, 'chatwoot');
if (!fs.existsSync(chatwootDir)) {
this.logger.verbose('creating chatwoot dir: ' + chatwootDir);
fs.mkdirSync(chatwootDir, { recursive: true });
}
if (!fs.existsSync(tempDir)) {
this.logger.verbose('creating temp dir: ' + tempDir);
fs.mkdirSync(tempDir, { recursive: true });
}
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }

View File

@ -1,15 +1,13 @@
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ConfigService } from '../../config/env.config';
import { join } from 'path';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { ISettingsModel, SettingsRaw } from '../models'; import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ISettingsModel, SettingsRaw } from '../models';
export class SettingsRepository extends Repository { export class SettingsRepository extends Repository {
constructor( constructor(private readonly settingsModel: ISettingsModel, private readonly configService: ConfigService) {
private readonly settingsModel: ISettingsModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
@ -20,15 +18,9 @@ export class SettingsRepository extends Repository {
this.logger.verbose('creating settings'); this.logger.verbose('creating settings');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving settings to db'); this.logger.verbose('saving settings to db');
const insert = await this.settingsModel.replaceOne( const insert = await this.settingsModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
{ _id: instance },
{ ...data },
{ upsert: true },
);
this.logger.verbose( this.logger.verbose('settings saved to db: ' + insert.modifiedCount + ' settings');
'settings saved to db: ' + insert.modifiedCount + ' settings',
);
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
} }
@ -40,12 +32,7 @@ export class SettingsRepository extends Repository {
data, data,
}); });
this.logger.verbose( this.logger.verbose('settings saved to store in path: ' + join(this.storePath, 'settings') + '/' + instance);
'settings saved to store in path: ' +
join(this.storePath, 'settings') +
'/' +
instance,
);
this.logger.verbose('settings created'); this.logger.verbose('settings created');
return { insertCount: 1 }; return { insertCount: 1 };

View File

@ -1,15 +1,13 @@
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ConfigService } from '../../config/env.config';
import { join } from 'path';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { IWebhookModel, WebhookRaw } from '../models'; import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IWebhookModel, WebhookRaw } from '../models';
export class WebhookRepository extends Repository { export class WebhookRepository extends Repository {
constructor( constructor(private readonly webhookModel: IWebhookModel, private readonly configService: ConfigService) {
private readonly webhookModel: IWebhookModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
@ -20,11 +18,7 @@ export class WebhookRepository extends Repository {
this.logger.verbose('creating webhook'); this.logger.verbose('creating webhook');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving webhook to db'); this.logger.verbose('saving webhook to db');
const insert = await this.webhookModel.replaceOne( const insert = await this.webhookModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
{ _id: instance },
{ ...data },
{ upsert: true },
);
this.logger.verbose('webhook saved to db: ' + insert.modifiedCount + ' webhook'); this.logger.verbose('webhook saved to db: ' + insert.modifiedCount + ' webhook');
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
@ -38,12 +32,7 @@ export class WebhookRepository extends Repository {
data, data,
}); });
this.logger.verbose( this.logger.verbose('webhook saved to store in path: ' + join(this.storePath, 'webhook') + '/' + instance);
'webhook saved to store in path: ' +
join(this.storePath, 'webhook') +
'/' +
instance,
);
this.logger.verbose('webhook created'); this.logger.verbose('webhook created');
return { insertCount: 1 }; return { insertCount: 1 };

View File

@ -1,4 +1,6 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
archiveChatSchema, archiveChatSchema,
contactValidateSchema, contactValidateSchema,
@ -13,9 +15,11 @@ import {
readMessageSchema, readMessageSchema,
whatsappNumberSchema, whatsappNumberSchema,
} from '../../validate/validate.schema'; } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { import {
ArchiveChatDto, ArchiveChatDto,
DeleteMessage, DeleteMessage,
getBase64FromMediaMessageDto,
NumberDto, NumberDto,
PrivacySettingDto, PrivacySettingDto,
ProfileNameDto, ProfileNameDto,
@ -23,17 +27,13 @@ import {
ProfileStatusDto, ProfileStatusDto,
ReadMessageDto, ReadMessageDto,
WhatsAppNumberDto, WhatsAppNumberDto,
getBase64FromMediaMessageDto,
} from '../dto/chat.dto'; } from '../dto/chat.dto';
import { InstanceDto } from '../dto/instance.dto';
import { ContactQuery } from '../repository/contact.repository'; import { ContactQuery } from '../repository/contact.repository';
import { MessageQuery } from '../repository/message.repository'; import { MessageQuery } from '../repository/message.repository';
import { chatController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router';
import { MessageUpQuery } from '../repository/messageUp.repository'; import { MessageUpQuery } from '../repository/messageUp.repository';
import { proto } from '@whiskeysockets/baileys'; import { chatController } from '../whatsapp.module';
import { InstanceDto } from '../dto/instance.dto'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('ChatRouter'); const logger = new Logger('ChatRouter');
@ -92,27 +92,23 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.delete( .delete(this.routerPath('deleteMessageForEveryone'), ...guards, async (req, res) => {
this.routerPath('deleteMessageForEveryone'), logger.verbose('request received in deleteMessageForEveryone');
...guards, logger.verbose('request body: ');
async (req, res) => { logger.verbose(req.body);
logger.verbose('request received in deleteMessageForEveryone');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: '); logger.verbose('request query: ');
logger.verbose(req.query); logger.verbose(req.query);
const response = await this.dataValidate<DeleteMessage>({ const response = await this.dataValidate<DeleteMessage>({
request: req, request: req,
schema: deleteMessageSchema, schema: deleteMessageSchema,
ClassRef: DeleteMessage, ClassRef: DeleteMessage,
execute: (instance, data) => chatController.deleteMessage(instance, data), execute: (instance, data) => chatController.deleteMessage(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}, })
)
.post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => { .post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => {
logger.verbose('request received in fetchProfilePictureUrl'); logger.verbose('request received in fetchProfilePictureUrl');
logger.verbose('request body: '); logger.verbose('request body: ');
@ -176,8 +172,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: null, schema: null,
ClassRef: getBase64FromMediaMessageDto, ClassRef: getBase64FromMediaMessageDto,
execute: (instance, data) => execute: (instance, data) => chatController.getBase64FromMediaMessage(instance, data),
chatController.getBase64FromMediaMessage(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
@ -263,8 +258,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: privacySettingsSchema, schema: privacySettingsSchema,
ClassRef: PrivacySettingDto, ClassRef: PrivacySettingDto,
execute: (instance, data) => execute: (instance, data) => chatController.updatePrivacySettings(instance, data),
chatController.updatePrivacySettings(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
@ -281,8 +275,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
ClassRef: ProfilePictureDto, ClassRef: ProfilePictureDto,
execute: (instance, data) => execute: (instance, data) => chatController.fetchBusinessProfile(instance, data),
chatController.fetchBusinessProfile(instance, data),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
@ -333,8 +326,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
ClassRef: ProfilePictureDto, ClassRef: ProfilePictureDto,
execute: (instance, data) => execute: (instance, data) => chatController.updateProfilePicture(instance, data),
chatController.updateProfilePicture(instance, data),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
@ -351,8 +343,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
ClassRef: ProfilePictureDto, ClassRef: ProfilePictureDto,
execute: (instance, data) => execute: (instance) => chatController.removeProfilePicture(instance),
chatController.removeProfilePicture(instance, data),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);

View File

@ -1,12 +1,13 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { instanceNameSchema, chatwootSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { chatwootController } from '../whatsapp.module';
import { ChatwootService } from '../services/chatwoot.service';
import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { chatwootSchema, instanceNameSchema } from '../../validate/validate.schema';
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';
const logger = new Logger('ChatwootRouter'); const logger = new Logger('ChatwootRouter');

View File

@ -1,34 +1,35 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
createGroupSchema, createGroupSchema,
getParticipantsSchema,
groupInviteSchema,
groupJidSchema, groupJidSchema,
updateParticipantsSchema, groupSendInviteSchema,
updateSettingsSchema,
toggleEphemeralSchema, toggleEphemeralSchema,
updateGroupDescriptionSchema,
updateGroupPictureSchema, updateGroupPictureSchema,
updateGroupSubjectSchema, updateGroupSubjectSchema,
updateGroupDescriptionSchema, updateParticipantsSchema,
groupInviteSchema, updateSettingsSchema,
groupSendInviteSchema,
getParticipantsSchema,
} from '../../validate/validate.schema'; } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { import {
CreateGroupDto, CreateGroupDto,
GetParticipant,
GroupDescriptionDto,
GroupInvite, GroupInvite,
GroupJid, GroupJid,
GroupPictureDto, GroupPictureDto,
GroupSendInvite,
GroupSubjectDto, GroupSubjectDto,
GroupDescriptionDto, GroupToggleEphemeralDto,
GroupUpdateParticipantDto, GroupUpdateParticipantDto,
GroupUpdateSettingDto, GroupUpdateSettingDto,
GroupToggleEphemeralDto,
GroupSendInvite,
GetParticipant,
} from '../dto/group.dto'; } from '../dto/group.dto';
import { groupController } from '../whatsapp.module'; import { groupController } from '../whatsapp.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('GroupRouter'); const logger = new Logger('GroupRouter');
@ -96,8 +97,7 @@ export class GroupRouter extends RouterBroker {
request: req, request: req,
schema: updateGroupDescriptionSchema, schema: updateGroupDescriptionSchema,
ClassRef: GroupDescriptionDto, ClassRef: GroupDescriptionDto,
execute: (instance, data) => execute: (instance, data) => groupController.updateGroupDescription(instance, data),
groupController.updateGroupDescription(instance, data),
}); });
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);

View File

@ -1,16 +1,17 @@
import { Router } from 'express'; import { Router } from 'express';
import fs from 'fs';
import { Auth, configService } from '../../config/env.config'; import { Auth, configService } from '../../config/env.config';
import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard';
import { authGuard } from '../guards/auth.guard'; import { authGuard } from '../guards/auth.guard';
import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard';
import { ChatRouter } from './chat.router'; import { ChatRouter } from './chat.router';
import { ChatwootRouter } from './chatwoot.router';
import { GroupRouter } from './group.router'; import { GroupRouter } from './group.router';
import { InstanceRouter } from './instance.router'; import { InstanceRouter } from './instance.router';
import { MessageRouter } from './sendMessage.router'; import { MessageRouter } from './sendMessage.router';
import { SettingsRouter } from './settings.router';
import { ViewsRouter } from './view.router'; import { ViewsRouter } from './view.router';
import { WebhookRouter } from './webhook.router'; import { WebhookRouter } from './webhook.router';
import { ChatwootRouter } from './chatwoot.router';
import fs from 'fs';
import { SettingsRouter } from './settings.router';
enum HttpStatus { enum HttpStatus {
OK = 200, OK = 200,
@ -36,11 +37,7 @@ router
version: packageJson.version, version: packageJson.version,
}); });
}) })
.use( .use('/instance', new InstanceRouter(configService, ...guards).router, new ViewsRouter(instanceExistsGuard).router)
'/instance',
new InstanceRouter(configService, ...guards).router,
new ViewsRouter(instanceExistsGuard).router,
)
.use('/message', new MessageRouter(...guards).router) .use('/message', new MessageRouter(...guards).router)
.use('/chat', new ChatRouter(...guards).router) .use('/chat', new ChatRouter(...guards).router)
.use('/group', new GroupRouter(...guards).router) .use('/group', new GroupRouter(...guards).router)
@ -48,4 +45,4 @@ router
.use('/chatwoot', new ChatwootRouter(...guards).router) .use('/chatwoot', new ChatwootRouter(...guards).router)
.use('/settings', new SettingsRouter(...guards).router); .use('/settings', new SettingsRouter(...guards).router);
export { router, HttpStatus }; export { HttpStatus, router };

View File

@ -1,13 +1,14 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { instanceNameSchema, oldTokenSchema } from '../../validate/validate.schema';
import { InstanceDto } from '../dto/instance.dto';
import { instanceController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router';
import { OldToken } from '../services/auth.service';
import { Auth, ConfigService, Database } from '../../config/env.config'; import { Auth, ConfigService, Database } from '../../config/env.config';
import { dbserver } from '../../db/db.connect';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { dbserver } from '../../db/db.connect';
import { instanceNameSchema, oldTokenSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto';
import { OldToken } from '../services/auth.service';
import { instanceController } from '../whatsapp.module';
import { HttpStatus } from './index.router';
const logger = new Logger('InstanceRouter'); const logger = new Logger('InstanceRouter');
@ -160,19 +161,13 @@ export class InstanceRouter extends RouterBroker {
if (db.ENABLED) { if (db.ENABLED) {
try { try {
await dbserver.dropDatabase(); await dbserver.dropDatabase();
return res return res.status(HttpStatus.CREATED).json({ error: false, message: 'Database deleted' });
.status(HttpStatus.CREATED)
.json({ error: false, message: 'Database deleted' });
} catch (error) { } catch (error) {
return res return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: true, message: error.message });
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ error: true, message: error.message });
} }
} }
return res return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: true, message: 'Database is not enabled' });
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ error: true, message: 'Database is not enabled' });
}); });
} }

View File

@ -1,4 +1,6 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
audioMessageSchema, audioMessageSchema,
buttonMessageSchema, buttonMessageSchema,
@ -12,6 +14,7 @@ import {
stickerMessageSchema, stickerMessageSchema,
textMessageSchema, textMessageSchema,
} from '../../validate/validate.schema'; } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { import {
SendAudioDto, SendAudioDto,
SendButtonDto, SendButtonDto,
@ -26,9 +29,7 @@ import {
SendTextDto, SendTextDto,
} from '../dto/sendMessage.dto'; } from '../dto/sendMessage.dto';
import { sendMessageController } from '../whatsapp.module'; import { sendMessageController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('MessageRouter'); const logger = new Logger('MessageRouter');
@ -79,8 +80,7 @@ export class MessageRouter extends RouterBroker {
request: req, request: req,
schema: audioMessageSchema, schema: audioMessageSchema,
ClassRef: SendMediaDto, ClassRef: SendMediaDto,
execute: (instance, data) => execute: (instance, data) => sendMessageController.sendWhatsAppAudio(instance, data),
sendMessageController.sendWhatsAppAudio(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);

View File

@ -1,12 +1,13 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, settingsSchema } from '../../validate/validate.schema'; import { instanceNameSchema, settingsSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto'; import { SettingsDto } from '../dto/settings.dto';
// import { SettingsService } from '../services/settings.service';
import { settingsController } from '../whatsapp.module'; import { settingsController } from '../whatsapp.module';
import { SettingsService } from '../services/settings.service';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('SettingsRouter'); const logger = new Logger('SettingsRouter');

View File

@ -1,4 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { viewsController } from '../whatsapp.module'; import { viewsController } from '../whatsapp.module';

View File

@ -1,11 +1,12 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema'; import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { webhookController } from '../whatsapp.module'; import { webhookController } from '../whatsapp.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('WebhookRouter'); const logger = new Logger('WebhookRouter');

View File

@ -1,14 +1,15 @@
import { Auth, ConfigService, Webhook } from '../../config/env.config';
import { InstanceDto } from '../dto/instance.dto';
import { name as apiName } from '../../../package.json';
import { verify, sign } from 'jsonwebtoken';
import { Logger } from '../../config/logger.config';
import { v4 } from 'uuid';
import { isJWT } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import axios from 'axios'; import axios from 'axios';
import { WAMonitoringService } from './monitor.service'; import { isJWT } from 'class-validator';
import { sign, verify } from 'jsonwebtoken';
import { v4 } from 'uuid';
import { name as apiName } from '../../../package.json';
import { Auth, ConfigService, Webhook } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { RepositoryBroker } from '../repository/repository.manager'; import { RepositoryBroker } from '../repository/repository.manager';
import { WAMonitoringService } from './monitor.service';
export type JwtPayload = { export type JwtPayload = {
instanceName: string; instanceName: string;
@ -63,9 +64,7 @@ export class AuthService {
private async apikey(instance: InstanceDto, token?: string) { private async apikey(instance: InstanceDto, token?: string) {
const apikey = token ? token : v4().toUpperCase(); const apikey = token ? token : v4().toUpperCase();
this.logger.verbose( this.logger.verbose(token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey);
token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey,
);
const auth = await this.repository.auth.create({ apikey }, instance.instanceName); const auth = await this.repository.auth.create({ apikey }, instance.instanceName);
@ -101,13 +100,9 @@ export class AuthService {
public async generateHash(instance: InstanceDto, token?: string) { public async generateHash(instance: InstanceDto, token?: string) {
const options = this.configService.get<Auth>('AUTHENTICATION'); const options = this.configService.get<Auth>('AUTHENTICATION');
this.logger.verbose( this.logger.verbose('generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName);
'generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName,
);
return (await this[options.TYPE](instance, token)) as return (await this[options.TYPE](instance, token)) as { jwt: string } | { apikey: string };
| { jwt: string }
| { apikey: string };
} }
public async refreshToken({ oldToken }: OldToken) { public async refreshToken({ oldToken }: OldToken) {
@ -150,10 +145,7 @@ export class AuthService {
try { try {
this.logger.verbose('checking webhook'); this.logger.verbose('checking webhook');
const webhook = await this.repository.webhook.find(decode.instanceName); const webhook = await this.repository.webhook.find(decode.instanceName);
if ( if (webhook?.enabled && this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN) {
webhook?.enabled &&
this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN
) {
this.logger.verbose('sending webhook'); this.logger.verbose('sending webhook');
const httpService = axios.create({ baseURL: webhook.url }); const httpService = axios.create({ baseURL: webhook.url });

View File

@ -1,19 +1,17 @@
import { InstanceDto } from '../dto/instance.dto';
import path from 'path';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { WAMonitoringService } from './monitor.service';
import { Logger } from '../../config/logger.config';
import ChatwootClient from '@figuro/chatwoot-sdk'; import ChatwootClient from '@figuro/chatwoot-sdk';
import { createReadStream, readFileSync, unlinkSync, writeFileSync } from 'fs';
import axios from 'axios'; import axios from 'axios';
import FormData from 'form-data'; import FormData from 'form-data';
import { SendTextDto } from '../dto/sendMessage.dto'; import { createReadStream, readFileSync, unlinkSync, writeFileSync } from 'fs';
import mimeTypes from 'mime-types'; import mimeTypes from 'mime-types';
import { SendAudioDto } from '../dto/sendMessage.dto'; import path from 'path';
import { SendMediaDto } from '../dto/sendMessage.dto';
import { ROOT_DIR } from '../../config/path.config';
import { ConfigService, HttpServer } from '../../config/env.config'; import { ConfigService, HttpServer } from '../../config/env.config';
import { type } from 'os'; import { Logger } from '../../config/logger.config';
import { ROOT_DIR } from '../../config/path.config';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
import { SendAudioDto, SendMediaDto, SendTextDto } from '../dto/sendMessage.dto';
import { WAMonitoringService } from './monitor.service';
export class ChatwootService { export class ChatwootService {
private messageCacheFile: string; private messageCacheFile: string;
@ -23,10 +21,7 @@ export class ChatwootService {
private provider: any; private provider: any;
constructor( constructor(private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService) {
private readonly waMonitor: WAMonitoringService,
private readonly configService: ConfigService,
) {
this.messageCache = new Set(); this.messageCache = new Set();
} }
@ -57,9 +52,7 @@ export class ChatwootService {
private async getProvider(instance: InstanceDto) { private async getProvider(instance: InstanceDto) {
this.logger.verbose('get provider to instance: ' + instance.instanceName); this.logger.verbose('get provider to instance: ' + instance.instanceName);
try { try {
const provider = await this.waMonitor.waInstances[ const provider = await this.waMonitor.waInstances[instance.instanceName].findChatwoot();
instance.instanceName
].findChatwoot();
if (!provider) { if (!provider) {
this.logger.warn('provider not found'); this.logger.warn('provider not found');
@ -172,9 +165,7 @@ export class ChatwootService {
}); });
this.logger.verbose('check duplicate inbox'); this.logger.verbose('check duplicate inbox');
const checkDuplicate = findInbox.payload const checkDuplicate = findInbox.payload.map((inbox) => inbox.name).includes(inboxName);
.map((inbox) => inbox.name)
.includes(inboxName);
let inboxId: number; let inboxId: number;
@ -214,13 +205,7 @@ export class ChatwootService {
this.logger.verbose('find contact in chatwoot and create if not exists'); this.logger.verbose('find contact in chatwoot and create if not exists');
const contact = const contact =
(await this.findContact(instance, '123456')) || (await this.findContact(instance, '123456')) ||
((await this.createContact( ((await this.createContact(instance, '123456', inboxId, false, 'EvolutionAPI')) as any);
instance,
'123456',
inboxId,
false,
'EvolutionAPI',
)) as any);
if (!contact) { if (!contact) {
this.logger.warn('contact not found'); this.logger.warn('contact not found');
@ -425,23 +410,18 @@ export class ChatwootService {
if (isGroup) { if (isGroup) {
this.logger.verbose('get group name'); this.logger.verbose('get group name');
const group = await this.waMonitor.waInstances[ const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId);
instance.instanceName
].client.groupMetadata(chatId);
nameContact = `${group.subject} (GROUP)`; nameContact = `${group.subject} (GROUP)`;
this.logger.verbose('find or create participant in chatwoot'); this.logger.verbose('find or create participant in chatwoot');
const picture_url = await this.waMonitor.waInstances[ const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(
instance.instanceName
].profilePicture(body.key.participant.split('@')[0]);
const findParticipant = await this.findContact(
instance,
body.key.participant.split('@')[0], body.key.participant.split('@')[0],
); );
const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]);
if (findParticipant) { if (findParticipant) {
if (!findParticipant.name || findParticipant.name === chatId) { if (!findParticipant.name || findParticipant.name === chatId) {
await this.updateContact(instance, findParticipant.id, { await this.updateContact(instance, findParticipant.id, {
@ -463,9 +443,7 @@ export class ChatwootService {
this.logger.verbose('find or create contact in chatwoot'); this.logger.verbose('find or create contact in chatwoot');
const picture_url = await this.waMonitor.waInstances[ const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId);
instance.instanceName
].profilePicture(chatId);
const findContact = await this.findContact(instance, chatId); const findContact = await this.findContact(instance, chatId);
@ -510,8 +488,7 @@ export class ChatwootService {
return null; return null;
} }
const contactId = const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
if (!body.key.fromMe && contact.name === chatId && nameContact !== chatId) { if (!body.key.fromMe && contact.name === chatId && nameContact !== chatId) {
this.logger.verbose('update contact name in chatwoot'); this.logger.verbose('update contact name in chatwoot');
@ -529,14 +506,20 @@ export class ChatwootService {
if (contactConversations) { if (contactConversations) {
let conversation: any; let conversation: any;
if (this.provider.reopen_conversation) { if (this.provider.reopen_conversation) {
conversation = contactConversations.payload.find( conversation = contactConversations.payload.find((conversation) => conversation.inbox_id == filterInbox.id);
(conversation) => conversation.inbox_id == filterInbox.id,
); if (this.provider.conversation_pending) {
await client.conversations.toggleStatus({
accountId: this.provider.account_id,
conversationId: conversation.id,
data: {
status: 'pending',
},
});
}
} else { } else {
conversation = contactConversations.payload.find( conversation = contactConversations.payload.find(
(conversation) => (conversation) => conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id,
conversation.status !== 'resolved' &&
conversation.inbox_id == filterInbox.id,
); );
} }
this.logger.verbose('return conversation if exists'); this.logger.verbose('return conversation if exists');
@ -595,9 +578,7 @@ export class ChatwootService {
} }
this.logger.verbose('find inbox by name'); this.logger.verbose('find inbox by name');
const findByName = inbox.payload.find( const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName);
(inbox) => inbox.name === instance.instanceName,
);
if (!findByName) { if (!findByName) {
this.logger.warn('inbox not found'); this.logger.warn('inbox not found');
@ -699,8 +680,7 @@ export class ChatwootService {
this.logger.verbose('find conversation by contact id'); this.logger.verbose('find conversation by contact id');
const conversation = findConversation.data.payload.find( const conversation = findConversation.data.payload.find(
(conversation) => (conversation) => conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
); );
if (!conversation) { if (!conversation) {
@ -820,8 +800,7 @@ export class ChatwootService {
this.logger.verbose('find conversation by contact id'); this.logger.verbose('find conversation by contact id');
const conversation = findConversation.data.payload.find( const conversation = findConversation.data.payload.find(
(conversation) => (conversation) => conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
); );
if (!conversation) { if (!conversation) {
@ -871,12 +850,7 @@ export class ChatwootService {
} }
} }
public async sendAttachment( public async sendAttachment(waInstance: any, number: string, media: any, caption?: string) {
waInstance: any,
number: string,
media: any,
caption?: string,
) {
this.logger.verbose('send attachment to instance: ' + waInstance.instanceName); this.logger.verbose('send attachment to instance: ' + waInstance.instanceName);
try { try {
@ -957,9 +931,7 @@ export class ChatwootService {
public async receiveWebhook(instance: InstanceDto, body: any) { public async receiveWebhook(instance: InstanceDto, body: any) {
try { try {
this.logger.verbose( this.logger.verbose('receive webhook to chatwoot instance: ' + instance.instanceName);
'receive webhook to chatwoot instance: ' + instance.instanceName,
);
const client = await this.clientCw(instance); const client = await this.clientCw(instance);
if (!client) { if (!client) {
@ -972,8 +944,7 @@ export class ChatwootService {
this.logger.verbose('check if is group'); this.logger.verbose('check if is group');
const chatId = const chatId =
body.conversation.meta.sender?.phone_number?.replace('+', '') || body.conversation.meta.sender?.phone_number?.replace('+', '') || body.conversation.meta.sender?.identifier;
body.conversation.meta.sender?.identifier;
const messageReceived = body.content; const messageReceived = body.content;
const senderName = body?.sender?.name; const senderName = body?.sender?.name;
const waInstance = this.waMonitor.waInstances[instance.instanceName]; const waInstance = this.waMonitor.waInstances[instance.instanceName];
@ -993,11 +964,7 @@ export class ChatwootService {
await waInstance.connectToWhatsapp(number); await waInstance.connectToWhatsapp(number);
} else { } else {
this.logger.verbose('whatsapp already connected'); this.logger.verbose('whatsapp already connected');
await this.createBotMessage( await this.createBotMessage(instance, `🚨 ${body.inbox.name} instance is connected.`, 'incoming');
instance,
`🚨 ${body.inbox.name} instance is connected.`,
'incoming',
);
} }
} }
@ -1008,20 +975,12 @@ export class ChatwootService {
if (!state) { if (!state) {
this.logger.verbose('state not found'); this.logger.verbose('state not found');
await this.createBotMessage( await this.createBotMessage(instance, `⚠️ ${body.inbox.name} instance not found.`, 'incoming');
instance,
`⚠️ ${body.inbox.name} instance not found.`,
'incoming',
);
} }
if (state) { if (state) {
this.logger.verbose('state: ' + state + ' found'); this.logger.verbose('state: ' + state + ' found');
await this.createBotMessage( await this.createBotMessage(instance, `⚠️ ${body.inbox.name} instance status: *${state}*`, 'incoming');
instance,
`⚠️ ${body.inbox.name} instance status: *${state}*`,
'incoming',
);
} }
} }
@ -1049,6 +1008,8 @@ export class ChatwootService {
chatwoot_token: this.provider.token, chatwoot_token: this.provider.token,
chatwoot_url: this.provider.url, chatwoot_url: this.provider.url,
chatwoot_sign_msg: this.provider.sign_msg, chatwoot_sign_msg: this.provider.sign_msg,
chatwoot_reopen_conversation: this.provider.reopen_conversation,
chatwoot_conversation_pending: this.provider.conversation_pending,
}; };
if (command.split(':')[2]) { if (command.split(':')[2]) {
@ -1070,19 +1031,10 @@ export class ChatwootService {
} }
} }
if ( if (body.message_type === 'outgoing' && body?.conversation?.messages?.length && chatId !== '123456') {
body.message_type === 'outgoing' &&
body?.conversation?.messages?.length &&
chatId !== '123456'
) {
this.logger.verbose('check if is group'); this.logger.verbose('check if is group');
this.messageCacheFile = path.join( this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.logger.verbose('cache file path: ' + this.messageCacheFile); this.logger.verbose('cache file path: ' + this.messageCacheFile);
this.messageCache = this.loadMessageCache(); this.messageCache = this.loadMessageCache();
@ -1103,9 +1055,7 @@ export class ChatwootService {
if (senderName === null || senderName === undefined) { if (senderName === null || senderName === undefined) {
formatText = messageReceived; formatText = messageReceived;
} else { } else {
formatText = this.provider.sign_msg formatText = this.provider.sign_msg ? `*${senderName}:*\n\n${messageReceived}` : messageReceived;
? `*${senderName}:*\n\n${messageReceived}`
: messageReceived;
} }
for (const message of body.conversation.messages) { for (const message of body.conversation.messages) {
@ -1119,12 +1069,7 @@ export class ChatwootService {
formatText = null; formatText = null;
} }
await this.sendAttachment( await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
waInstance,
chatId,
attachment.data_url,
formatText,
);
} }
} else { } else {
this.logger.verbose('message is text'); this.logger.verbose('message is text');
@ -1203,8 +1148,7 @@ export class ChatwootService {
messageContextInfo: msg.messageContextInfo?.stanzaId, messageContextInfo: msg.messageContextInfo?.stanzaId,
stickerMessage: undefined, stickerMessage: undefined,
documentMessage: msg.documentMessage?.caption, documentMessage: msg.documentMessage?.caption,
documentWithCaptionMessage: documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
audioMessage: msg.audioMessage?.caption, audioMessage: msg.audioMessage?.caption,
contactMessage: msg.contactMessage?.vcard, contactMessage: msg.contactMessage?.vcard,
contactsArrayMessage: msg.contactsArrayMessage, contactsArrayMessage: msg.contactsArrayMessage,
@ -1405,24 +1349,14 @@ export class ChatwootService {
} }
this.logger.verbose('send data to chatwoot'); this.logger.verbose('send data to chatwoot');
const send = await this.sendData( const send = await this.sendData(getConversion, fileName, messageType, content);
getConversion,
fileName,
messageType,
content,
);
if (!send) { if (!send) {
this.logger.warn('message not sent'); this.logger.warn('message not sent');
return; return;
} }
this.messageCacheFile = path.join( this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.messageCache = this.loadMessageCache(); this.messageCache = this.loadMessageCache();
@ -1436,24 +1370,14 @@ export class ChatwootService {
this.logger.verbose('message is not group'); this.logger.verbose('message is not group');
this.logger.verbose('send data to chatwoot'); this.logger.verbose('send data to chatwoot');
const send = await this.sendData( const send = await this.sendData(getConversion, fileName, messageType, bodyMessage);
getConversion,
fileName,
messageType,
bodyMessage,
);
if (!send) { if (!send) {
this.logger.warn('message not sent'); this.logger.warn('message not sent');
return; return;
} }
this.messageCacheFile = path.join( this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.messageCache = this.loadMessageCache(); this.messageCache = this.loadMessageCache();
@ -1482,24 +1406,14 @@ export class ChatwootService {
} }
this.logger.verbose('send data to chatwoot'); this.logger.verbose('send data to chatwoot');
const send = await this.createMessage( const send = await this.createMessage(instance, getConversion, content, messageType);
instance,
getConversion,
content,
messageType,
);
if (!send) { if (!send) {
this.logger.warn('message not sent'); this.logger.warn('message not sent');
return; return;
} }
this.messageCacheFile = path.join( this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.messageCache = this.loadMessageCache(); this.messageCache = this.loadMessageCache();
@ -1513,24 +1427,14 @@ export class ChatwootService {
this.logger.verbose('message is not group'); this.logger.verbose('message is not group');
this.logger.verbose('send data to chatwoot'); this.logger.verbose('send data to chatwoot');
const send = await this.createMessage( const send = await this.createMessage(instance, getConversion, bodyMessage, messageType);
instance,
getConversion,
bodyMessage,
messageType,
);
if (!send) { if (!send) {
this.logger.warn('message not sent'); this.logger.warn('message not sent');
return; return;
} }
this.messageCacheFile = path.join( this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.messageCache = this.loadMessageCache(); this.messageCache = this.loadMessageCache();
@ -1580,16 +1484,9 @@ export class ChatwootService {
return await this.createBotMessage(instance, erroQRcode, 'incoming'); return await this.createBotMessage(instance, erroQRcode, 'incoming');
} else { } else {
this.logger.verbose('qrcode success'); this.logger.verbose('qrcode success');
const fileData = Buffer.from( const fileData = Buffer.from(body?.qrcode.base64.replace('data:image/png;base64,', ''), 'base64');
body?.qrcode.base64.replace('data:image/png;base64,', ''),
'base64',
);
const fileName = `${path.join( const fileName = `${path.join(waInstance?.storePath, 'temp', `${`${instance}.png`}`)}`;
waInstance?.storePath,
'temp',
`${`${instance}.png`}`,
)}`;
this.logger.verbose('temp file name: ' + fileName); this.logger.verbose('temp file name: ' + fileName);
@ -1597,22 +1494,17 @@ export class ChatwootService {
writeFileSync(fileName, fileData, 'utf8'); writeFileSync(fileName, fileData, 'utf8');
this.logger.verbose('send qrcode to chatwoot'); this.logger.verbose('send qrcode to chatwoot');
await this.createBotQr( await this.createBotQr(instance, 'QRCode successfully generated!', 'incoming', fileName);
instance,
'QRCode successfully generated!',
'incoming',
fileName,
);
let msgQrCode = `⚡️ QRCode successfully generated!\n\nScan this QR code within the next 40 seconds.`; let msgQrCode = `⚡️ QRCode successfully generated!\n\nScan this QR code within the next 40 seconds.`;
if (body?.qrcode?.pairingCode) { if (body?.qrcode?.pairingCode) {
msgQrCode = msgQrCode =
msgQrCode + msgQrCode +
`\n\n*Pairing Code:* ${body.qrcode.pairingCode.substring( `\n\n*Pairing Code:* ${body.qrcode.pairingCode.substring(0, 4)}-${body.qrcode.pairingCode.substring(
0,
4, 4,
)}-${body.qrcode.pairingCode.substring(4, 8)}`; 8,
)}`;
} }
this.logger.verbose('send message to chatwoot'); this.logger.verbose('send message to chatwoot');
@ -1649,6 +1541,7 @@ export class ChatwootService {
requestData['number'] = number; requestData['number'] = number;
} }
// eslint-disable-next-line
const config = { const config = {
method: 'post', method: 'post',
maxBodyLength: Infinity, maxBodyLength: Infinity,

View File

@ -1,24 +1,15 @@
import { opendirSync, readdirSync, rmSync } from 'fs';
import { WAStartupService } from './whatsapp.service';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import EventEmitter2 from 'eventemitter2';
import { join } from 'path';
import { Logger } from '../../config/logger.config';
import {
Auth,
ConfigService,
Database,
DelInstance,
HttpServer,
Redis,
} from '../../config/env.config';
import { RepositoryBroker } from '../repository/repository.manager';
import { NotFoundException } from '../../exceptions';
import { Db } from 'mongodb';
import { RedisCache } from '../../db/redis.client';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import EventEmitter2 from 'eventemitter2';
import { opendirSync, readdirSync, rmSync } from 'fs';
import { Db } from 'mongodb';
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 { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
import mongoose from 'mongoose'; import { RedisCache } from '../../db/redis.client';
import { NotFoundException } from '../../exceptions';
import { import {
AuthModel, AuthModel,
ChatwootModel, ChatwootModel,
@ -28,6 +19,8 @@ import {
SettingsModel, SettingsModel,
WebhookModel, WebhookModel,
} from '../models'; } from '../models';
import { RepositoryBroker } from '../repository/repository.manager';
import { WAStartupService } from './whatsapp.service';
export class WAMonitoringService { export class WAMonitoringService {
constructor( constructor(
@ -63,16 +56,12 @@ export class WAMonitoringService {
public delInstanceTime(instance: string) { public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE'); const time = this.configService.get<DelInstance>('DEL_INSTANCE');
if (typeof time === 'number' && time > 0) { if (typeof time === 'number' && time > 0) {
this.logger.verbose( this.logger.verbose(`Instance "${instance}" don't have connection, will be removed in ${time} minutes`);
`Instance "${instance}" don't have connection, will be removed in ${time} minutes`,
);
setTimeout(async () => { setTimeout(async () => {
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') { if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') { if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
await this.waInstances[instance]?.client?.logout( await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance);
'Log out instance: ' + instance,
);
this.waInstances[instance]?.client?.ws?.close(); this.waInstances[instance]?.client?.ws?.close();
this.waInstances[instance]?.client?.end(undefined); this.waInstances[instance]?.client?.end(undefined);
delete this.waInstances[instance]; delete this.waInstances[instance];
@ -124,21 +113,16 @@ export class WAMonitoringService {
}; };
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) { if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance['serverUrl'] = instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['apikey'] = ( instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
await this.repository.auth.find(key)
).apikey;
instanceData.instance['chatwoot'] = chatwoot; instanceData.instance['chatwoot'] = chatwoot;
} }
instances.push(instanceData); instances.push(instanceData);
} else { } else {
this.logger.verbose( this.logger.verbose('instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state);
'instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state,
);
const instanceData = { const instanceData = {
instance: { instance: {
@ -148,12 +132,9 @@ export class WAMonitoringService {
}; };
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) { if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance['serverUrl'] = instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['apikey'] = ( instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
await this.repository.auth.find(key)
).apikey;
instanceData.instance['chatwoot'] = chatwoot; instanceData.instance['chatwoot'] = chatwoot;
} }
@ -176,14 +157,11 @@ export class WAMonitoringService {
collections.forEach(async (collection) => { collections.forEach(async (collection) => {
const name = collection.namespace.replace(/^[\w-]+./, ''); const name = collection.namespace.replace(/^[\w-]+./, '');
await this.dbInstance.collection(name).deleteMany({ await this.dbInstance.collection(name).deleteMany({
$or: [ $or: [{ _id: { $regex: /^app.state.*/ } }, { _id: { $regex: /^session-.*/ } }],
{ _id: { $regex: /^app.state.*/ } },
{ _id: { $regex: /^session-.*/ } },
],
}); });
this.logger.verbose('instance files deleted: ' + name); this.logger.verbose('instance files deleted: ' + name);
}); });
} else if (this.redis.ENABLED) { // } else if (this.redis.ENABLED) {
} else { } else {
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' }); const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
for await (const dirent of dir) { for await (const dirent of dir) {
@ -264,12 +242,7 @@ export class WAMonitoringService {
public async loadInstance() { public async loadInstance() {
this.logger.verbose('load instances'); this.logger.verbose('load instances');
const set = async (name: string) => { const set = async (name: string) => {
const instance = new WAStartupService( const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
instance.instanceName = name; instance.instanceName = name;
this.logger.verbose('instance loaded: ' + name); this.logger.verbose('instance loaded: ' + name);
@ -299,9 +272,7 @@ export class WAMonitoringService {
const collections: any[] = await this.dbInstance.collections(); const collections: any[] = await this.dbInstance.collections();
if (collections.length > 0) { if (collections.length > 0) {
this.logger.verbose('reading collections and setting instances'); this.logger.verbose('reading collections and setting instances');
collections.forEach( collections.forEach(async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')));
async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')),
);
} else { } else {
this.logger.verbose('no collections found'); this.logger.verbose('no collections found');
} }
@ -337,7 +308,9 @@ export class WAMonitoringService {
try { try {
this.logger.verbose('instance: ' + instanceName + ' - removing from memory'); this.logger.verbose('instance: ' + instanceName + ' - removing from memory');
this.waInstances[instanceName] = undefined; this.waInstances[instanceName] = undefined;
} catch {} } catch (error) {
this.logger.error(error);
}
try { try {
this.logger.verbose('request cleaning up instance: ' + instanceName); this.logger.verbose('request cleaning up instance: ' + instanceName);

View File

@ -1,7 +1,7 @@
import { Logger } from '../../config/logger.config';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto'; import { SettingsDto } from '../dto/settings.dto';
import { WAMonitoringService } from './monitor.service'; import { WAMonitoringService } from './monitor.service';
import { Logger } from '../../config/logger.config';
export class SettingsService { export class SettingsService {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
@ -18,9 +18,7 @@ export class SettingsService {
public async find(instance: InstanceDto): Promise<SettingsDto> { public async find(instance: InstanceDto): Promise<SettingsDto> {
try { try {
this.logger.verbose('find settings: ' + instance.instanceName); this.logger.verbose('find settings: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[ const result = await this.waMonitor.waInstances[instance.instanceName].findSettings();
instance.instanceName
].findSettings();
if (Object.keys(result).length === 0) { if (Object.keys(result).length === 0) {
throw new Error('Settings not found'); throw new Error('Settings not found');

View File

@ -1,7 +1,7 @@
import { Logger } from '../../config/logger.config';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { WAMonitoringService } from './monitor.service'; import { WAMonitoringService } from './monitor.service';
import { Logger } from '../../config/logger.config';
export class WebhookService { export class WebhookService {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
@ -18,9 +18,7 @@ export class WebhookService {
public async find(instance: InstanceDto): Promise<WebhookDto> { public async find(instance: InstanceDto): Promise<WebhookDto> {
try { try {
this.logger.verbose('find webhook: ' + instance.instanceName); this.logger.verbose('find webhook: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[ const result = await this.waMonitor.waInstances[instance.instanceName].findWebhook();
instance.instanceName
].findWebhook();
if (Object.keys(result).length === 0) { if (Object.keys(result).length === 0) {
throw new Error('Webhook not found'); throw new Error('Webhook not found');

View File

@ -1,9 +1,10 @@
import ffmpegPath from '@ffmpeg-installer/ffmpeg';
import { Boom } from '@hapi/boom';
import makeWASocket, { import makeWASocket, {
AnyMessageContent, AnyMessageContent,
BufferedEventData, BufferedEventData,
BufferJSON, BufferJSON,
CacheStore, CacheStore,
makeCacheableSignalKeyStore,
Chat, Chat,
ConnectionState, ConnectionState,
Contact, Contact,
@ -12,11 +13,13 @@ import makeWASocket, {
downloadMediaMessage, downloadMediaMessage,
fetchLatestBaileysVersion, fetchLatestBaileysVersion,
generateWAMessageFromContent, generateWAMessageFromContent,
getAggregateVotesInPollMessage,
getContentType, getContentType,
getDevice, getDevice,
GroupMetadata, GroupMetadata,
isJidGroup, isJidGroup,
isJidUser, isJidUser,
makeCacheableSignalKeyStore,
MessageUpsertType, MessageUpsertType,
MiscMessageGenerationOptions, MiscMessageGenerationOptions,
ParticipantAction, ParticipantAction,
@ -29,8 +32,23 @@ import makeWASocket, {
WAMessage, WAMessage,
WAMessageUpdate, WAMessageUpdate,
WASocket, WASocket,
getAggregateVotesInPollMessage,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import axios from 'axios';
import { exec, execSync } from 'child_process';
import { arrayUnique, isBase64, isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
import fs, { existsSync, readFileSync } from 'fs';
import Long from 'long';
import NodeCache from 'node-cache';
import { getMIMEType } from 'node-mime-types';
import { release } from 'os';
import { join } from 'path';
import P from 'pino';
import qrcode, { QRCodeToDataURLOptions } from 'qrcode';
import qrcodeTerminal from 'qrcode-terminal';
import sharp from 'sharp';
import { v4 } from 'uuid';
import { import {
Auth, Auth,
CleanStoreConf, CleanStoreConf,
@ -38,31 +56,41 @@ import {
ConfigSessionPhone, ConfigSessionPhone,
Database, Database,
HttpServer, HttpServer,
Log,
QrCode, QrCode,
Redis, Redis,
Webhook, Webhook,
} from '../../config/env.config'; } from '../../config/env.config';
import fs from 'fs';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, ROOT_DIR } from '../../config/path.config'; import { INSTANCE_DIR, ROOT_DIR } from '../../config/path.config';
import { existsSync, readFileSync } from 'fs'; import { dbserver } from '../../db/db.connect';
import { join } from 'path'; import { RedisCache } from '../../db/redis.client';
import axios from 'axios'; import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../exceptions';
import { v4 } from 'uuid'; import { useMultiFileAuthStateDb } from '../../utils/use-multi-file-auth-state-db';
import qrcode, { QRCodeToDataURLOptions } from 'qrcode'; import { useMultiFileAuthStateRedisDb } from '../../utils/use-multi-file-auth-state-redis-db';
import qrcodeTerminal from 'qrcode-terminal'; import {
import { Events, TypeMediaMessage, wa, MessageSubtype } from '../types/wa.types'; ArchiveChatDto,
import { Boom } from '@hapi/boom'; DeleteMessage,
import EventEmitter2 from 'eventemitter2'; getBase64FromMediaMessageDto,
import { release } from 'os'; NumberBusiness,
import P from 'pino'; OnWhatsAppDto,
import { execSync, exec } from 'child_process'; PrivacySettingDto,
import ffmpegPath from '@ffmpeg-installer/ffmpeg'; ReadMessageDto,
import { RepositoryBroker } from '../repository/repository.manager'; WhatsAppNumberDto,
import { MessageRaw, MessageUpdateRaw } from '../models/message.model'; } from '../dto/chat.dto';
import { ContactRaw } from '../models/contact.model'; import {
import { ChatRaw } from '../models/chat.model'; CreateGroupDto,
import { getMIMEType } from 'node-mime-types'; GetParticipant,
GroupDescriptionDto,
GroupInvite,
GroupJid,
GroupPictureDto,
GroupSendInvite,
GroupSubjectDto,
GroupToggleEphemeralDto,
GroupUpdateParticipantDto,
GroupUpdateSettingDto,
} from '../dto/group.dto';
import { import {
ContactMessage, ContactMessage,
MediaMessage, MediaMessage,
@ -73,58 +101,26 @@ import {
SendListDto, SendListDto,
SendLocationDto, SendLocationDto,
SendMediaDto, SendMediaDto,
SendReactionDto,
SendTextDto,
SendPollDto, SendPollDto,
SendStickerDto, SendReactionDto,
SendStatusDto, SendStatusDto,
SendStickerDto,
SendTextDto,
StatusMessage, StatusMessage,
} from '../dto/sendMessage.dto'; } from '../dto/sendMessage.dto';
import { arrayUnique, isBase64, isURL } from 'class-validator';
import {
ArchiveChatDto,
DeleteMessage,
NumberBusiness,
OnWhatsAppDto,
PrivacySettingDto,
ReadMessageDto,
WhatsAppNumberDto,
getBase64FromMediaMessageDto,
} from '../dto/chat.dto';
import { MessageQuery } from '../repository/message.repository';
import { ContactQuery } from '../repository/contact.repository';
import {
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from '../../exceptions';
import {
CreateGroupDto,
GroupInvite,
GroupJid,
GroupPictureDto,
GroupUpdateParticipantDto,
GroupUpdateSettingDto,
GroupToggleEphemeralDto,
GroupSubjectDto,
GroupDescriptionDto,
GroupSendInvite,
GetParticipant,
} from '../dto/group.dto';
import { MessageUpQuery } from '../repository/messageUp.repository';
import { useMultiFileAuthStateDb } from '../../utils/use-multi-file-auth-state-db';
import Long from 'long';
import { WebhookRaw } from '../models/webhook.model';
import { ChatwootRaw } from '../models/chatwoot.model';
import { SettingsRaw } from '../models'; import { SettingsRaw } from '../models';
import { dbserver } from '../../db/db.connect'; import { ChatRaw } from '../models/chat.model';
import NodeCache from 'node-cache'; import { ChatwootRaw } from '../models/chatwoot.model';
import { useMultiFileAuthStateRedisDb } from '../../utils/use-multi-file-auth-state-redis-db'; import { ContactRaw } from '../models/contact.model';
import sharp from 'sharp'; import { MessageRaw, MessageUpdateRaw } from '../models/message.model';
import { RedisCache } from '../../db/redis.client'; import { WebhookRaw } from '../models/webhook.model';
import { Log } from '../../config/env.config'; import { ContactQuery } from '../repository/contact.repository';
import { ChatwootService } from './chatwoot.service'; import { MessageQuery } from '../repository/message.repository';
import { MessageUpQuery } from '../repository/messageUp.repository';
import { RepositoryBroker } from '../repository/repository.manager';
import { Events, MessageSubtype, TypeMediaMessage, wa } from '../types/wa.types';
import { waMonitor } from '../whatsapp.module'; import { waMonitor } from '../whatsapp.module';
import { ChatwootService } from './chatwoot.service';
export class WAStartupService { export class WAStartupService {
constructor( constructor(
@ -201,10 +197,7 @@ export class WAStartupService {
this.logger.verbose('Database enabled, trying to get from database'); this.logger.verbose('Database enabled, trying to get from database');
const collection = dbserver const collection = dbserver
.getClient() .getClient()
.db( .db(this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME + '-instances')
this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME +
'-instances',
)
.collection(this.instanceName); .collection(this.instanceName);
const data = await collection.findOne({ _id: 'creds' }); const data = await collection.findOne({ _id: 'creds' });
if (data) { if (data) {
@ -316,14 +309,10 @@ export class WAStartupService {
this.logger.verbose(`Chatwoot number: ${this.localChatwoot.number}`); this.logger.verbose(`Chatwoot number: ${this.localChatwoot.number}`);
this.localChatwoot.reopen_conversation = data?.reopen_conversation; this.localChatwoot.reopen_conversation = data?.reopen_conversation;
this.logger.verbose( this.logger.verbose(`Chatwoot reopen conversation: ${this.localChatwoot.reopen_conversation}`);
`Chatwoot reopen conversation: ${this.localChatwoot.reopen_conversation}`,
);
this.localChatwoot.conversation_pending = data?.conversation_pending; this.localChatwoot.conversation_pending = data?.conversation_pending;
this.logger.verbose( this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`);
`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`,
);
this.logger.verbose('Chatwoot loaded'); this.logger.verbose('Chatwoot loaded');
} }
@ -424,11 +413,10 @@ export class WAStartupService {
const webhookGlobal = this.configService.get<Webhook>('WEBHOOK'); const webhookGlobal = this.configService.get<Webhook>('WEBHOOK');
const webhookLocal = this.localWebhook.events; const webhookLocal = this.localWebhook.events;
const serverUrl = this.configService.get<HttpServer>('SERVER').URL; const serverUrl = this.configService.get<HttpServer>('SERVER').URL;
const we = event.replace(/[\.-]/gm, '_').toUpperCase(); const we = event.replace(/[.-]/gm, '_').toUpperCase();
const transformedWe = we.replace(/_/gm, '-').toLowerCase(); const transformedWe = we.replace(/_/gm, '-').toLowerCase();
const expose = const expose = this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
const tokenStore = await this.repository.auth.find(this.instanceName); const tokenStore = await this.repository.auth.find(this.instanceName);
const instanceApikey = tokenStore?.apikey || 'Apikey not found'; const instanceApikey = tokenStore?.apikey || 'Apikey not found';
@ -437,7 +425,7 @@ export class WAStartupService {
if (local) { if (local) {
if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) { if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) {
this.logger.verbose('Sending data to webhook local'); this.logger.verbose('Sending data to webhook local');
let baseURL; let baseURL: string;
if (this.localWebhook.webhook_by_events) { if (this.localWebhook.webhook_by_events) {
baseURL = `${this.localWebhook.url}/${transformedWe}`; baseURL = `${this.localWebhook.url}/${transformedWe}`;
@ -566,11 +554,7 @@ export class WAStartupService {
} }
} }
private async connectionUpdate({ private async connectionUpdate({ qr, connection, lastDisconnect }: Partial<ConnectionState>) {
qr,
connection,
lastDisconnect,
}: Partial<ConnectionState>) {
this.logger.verbose('Connection update'); this.logger.verbose('Connection update');
if (qr) { if (qr) {
this.logger.verbose('QR code found'); this.logger.verbose('QR code found');
@ -637,9 +621,7 @@ export class WAStartupService {
if (this.phoneNumber) { if (this.phoneNumber) {
await delay(2000); await delay(2000);
this.instance.qrcode.pairingCode = await this.client.requestPairingCode( this.instance.qrcode.pairingCode = await this.client.requestPairingCode(this.phoneNumber);
this.phoneNumber,
);
} else { } else {
this.instance.qrcode.pairingCode = null; this.instance.qrcode.pairingCode = null;
} }
@ -704,8 +686,7 @@ export class WAStartupService {
if (connection === 'close') { if (connection === 'close') {
this.logger.verbose('Connection closed'); this.logger.verbose('Connection closed');
const shouldReconnect = const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
(lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) { if (shouldReconnect) {
this.logger.verbose('Reconnecting to whatsapp'); this.logger.verbose('Reconnecting to whatsapp');
await this.connectToWhatsapp(); await this.connectToWhatsapp();
@ -714,7 +695,7 @@ export class WAStartupService {
this.logger.verbose('Sending data to webhook in event STATUS_INSTANCE'); this.logger.verbose('Sending data to webhook in event STATUS_INSTANCE');
this.sendDataWebhook(Events.STATUS_INSTANCE, { this.sendDataWebhook(Events.STATUS_INSTANCE, {
instance: this.instance.name, instance: this.instance.name,
status: 'removed', status: 'closed',
}); });
if (this.localChatwoot.enabled) { if (this.localChatwoot.enabled) {
@ -723,7 +704,7 @@ export class WAStartupService {
{ instanceName: this.instance.name }, { instanceName: this.instance.name },
{ {
instance: this.instance.name, instance: this.instance.name,
status: 'removed', status: 'closed',
}, },
); );
} }
@ -739,9 +720,7 @@ export class WAStartupService {
if (connection === 'open') { if (connection === 'open') {
this.logger.verbose('Connection opened'); this.logger.verbose('Connection opened');
this.instance.wuid = this.client.user.id.replace(/:\d+/, ''); this.instance.wuid = this.client.user.id.replace(/:\d+/, '');
this.instance.profilePictureUrl = ( this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl;
await this.profilePicture(this.instance.wuid)
).profilePictureUrl;
this.logger.info( this.logger.info(
` `
@ -774,8 +753,7 @@ export class WAStartupService {
} }
if (webMessageInfo[0].message?.pollCreationMessage) { if (webMessageInfo[0].message?.pollCreationMessage) {
this.logger.verbose('Returning poll message'); this.logger.verbose('Returning poll message');
const messageSecretBase64 = const messageSecretBase64 = webMessageInfo[0].message?.messageContextInfo?.messageSecret;
webMessageInfo[0].message?.messageContextInfo?.messageSecret;
if (typeof messageSecretBase64 === 'string') { if (typeof messageSecretBase64 === 'string') {
const messageSecret = Buffer.from(messageSecretBase64, 'base64'); const messageSecret = Buffer.from(messageSecretBase64, 'base64');
@ -809,22 +787,16 @@ export class WAStartupService {
for (const [key, value] of Object.entries(cleanStore)) { for (const [key, value] of Object.entries(cleanStore)) {
if (value === true) { if (value === true) {
execSync( execSync(
`rm -rf ${join( `rm -rf ${join(this.storePath, key.toLowerCase().replace('_', '-'), this.instance.name)}/*.json`,
this.storePath,
key.toLowerCase().replace('_', '-'),
this.instance.name,
)}/*.json`,
); );
this.logger.verbose( this.logger.verbose(
`Cleaned ${join( `Cleaned ${join(this.storePath, key.toLowerCase().replace('_', '-'), this.instance.name)}/*.json`,
this.storePath,
key.toLowerCase().replace('_', '-'),
this.instance.name,
)}/*.json`,
); );
} }
} }
} catch (error) {} } catch (error) {
this.logger.error(error);
}
}, (cleanStore?.CLEANING_INTERVAL ?? 3600) * 1000); }, (cleanStore?.CLEANING_INTERVAL ?? 3600) * 1000);
} }
} }
@ -867,10 +839,7 @@ export class WAStartupService {
const socketConfig: UserFacingSocketConfig = { const socketConfig: UserFacingSocketConfig = {
auth: { auth: {
creds: this.instance.authState.state.creds, creds: this.instance.authState.state.creds,
keys: makeCacheableSignalKeyStore( keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' })),
this.instance.authState.state.keys,
P({ level: 'error' }),
),
}, },
logger: P({ level: this.logBaileys }), logger: P({ level: this.logBaileys }),
printQRInTerminal: false, printQRInTerminal: false,
@ -882,18 +851,13 @@ export class WAStartupService {
defaultQueryTimeoutMs: undefined, defaultQueryTimeoutMs: undefined,
emitOwnEvents: false, emitOwnEvents: false,
msgRetryCounterCache: this.msgRetryCounterCache, msgRetryCounterCache: this.msgRetryCounterCache,
getMessage: async (key) => getMessage: async (key) => (await this.getMessage(key)) as Promise<proto.IMessage>,
(await this.getMessage(key)) as Promise<proto.IMessage>,
generateHighQualityLinkPreview: true, generateHighQualityLinkPreview: true,
syncFullHistory: true, syncFullHistory: true,
userDevicesCache: this.userDevicesCache, userDevicesCache: this.userDevicesCache,
transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 }, transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 },
patchMessageBeforeSending: (message) => { patchMessageBeforeSending: (message) => {
const requiresPatch = !!( const requiresPatch = !!(message.buttonsMessage || message.listMessage || message.templateMessage);
message.buttonsMessage ||
message.listMessage ||
message.templateMessage
);
if (requiresPatch) { if (requiresPatch) {
message = { message = {
viewOnceMessageV2: { viewOnceMessageV2: {
@ -956,11 +920,7 @@ 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( await this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
}, },
'chats.update': async ( 'chats.update': async (
@ -1025,11 +985,7 @@ 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( await this.repository.contact.insert(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
}, },
'contacts.update': async (contacts: Partial<Contact>[], database: Database) => { 'contacts.update': async (contacts: Partial<Contact>[], database: Database) => {
@ -1050,11 +1006,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw); await this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw);
this.logger.verbose('Updating contacts in database'); this.logger.verbose('Updating contacts in database');
await this.repository.contact.update( await this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
}, },
}; };
@ -1087,11 +1039,7 @@ 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( await this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
} }
const messagesRaw: MessageRaw[] = []; const messagesRaw: MessageRaw[] = [];
@ -1102,11 +1050,7 @@ export class WAStartupService {
if (!m.message) { if (!m.message) {
continue; continue;
} }
if ( if (messagesRepository.find((mr) => mr.owner === this.instance.name && mr.key.id === m.key.id)) {
messagesRepository.find(
(mr) => mr.owner === this.instance.name && mr.key.id === m.key.id,
)
) {
continue; continue;
} }
@ -1145,11 +1089,7 @@ export class WAStartupService {
this.logger.verbose('Event received: messages.upsert'); this.logger.verbose('Event received: messages.upsert');
const received = messages[0]; const received = messages[0];
if ( if (type !== 'notify' || received.message?.protocolMessage || received.message?.pollUpdateMessage) {
type !== 'notify' ||
received.message?.protocolMessage ||
received.message?.pollUpdateMessage
) {
this.logger.verbose('message rejected'); this.logger.verbose('message rejected');
return; return;
} }
@ -1195,11 +1135,7 @@ export class WAStartupService {
} }
this.logger.verbose('Inserting message in database'); this.logger.verbose('Inserting message in database');
await this.repository.message.insert( await this.repository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
[messageRaw],
this.instance.name,
database.SAVE_DATA.NEW_MESSAGE,
);
this.logger.verbose('Verifying contact from message'); this.logger.verbose('Verifying contact from message');
const contact = await this.repository.contact.find({ const contact = await this.repository.contact.find({
@ -1209,8 +1145,7 @@ export class WAStartupService {
const contactRaw: ContactRaw = { const contactRaw: ContactRaw = {
id: received.key.remoteJid, id: received.key.remoteJid,
pushName: received.pushName, pushName: received.pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)) profilePictureUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
.profilePictureUrl,
owner: this.instance.name, owner: this.instance.name,
}; };
@ -1224,8 +1159,7 @@ export class WAStartupService {
const contactRaw: ContactRaw = { const contactRaw: ContactRaw = {
id: received.key.remoteJid, id: received.key.remoteJid,
pushName: contact[0].pushName, pushName: contact[0].pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)) profilePictureUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
.profilePictureUrl,
owner: this.instance.name, owner: this.instance.name,
}; };
@ -1241,11 +1175,7 @@ export class WAStartupService {
} }
this.logger.verbose('Updating contact in database'); this.logger.verbose('Updating contact in database');
await this.repository.contact.update( await this.repository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
[contactRaw],
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
return; return;
} }
@ -1255,18 +1185,10 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
this.logger.verbose('Inserting contact in database'); this.logger.verbose('Inserting contact in database');
await this.repository.contact.insert( await this.repository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
[contactRaw],
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
}, },
'messages.update': async ( 'messages.update': async (args: WAMessageUpdate[], database: Database, settings: SettingsRaw) => {
args: WAMessageUpdate[],
database: Database,
settings: SettingsRaw,
) => {
this.logger.verbose('Event received: messages.update'); this.logger.verbose('Event received: messages.update');
const status: Record<number, wa.StatusMessage> = { const status: Record<number, wa.StatusMessage> = {
0: 'ERROR', 0: 'ERROR',
@ -1341,11 +1263,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.MESSAGES_UPDATE, message); await this.sendDataWebhook(Events.MESSAGES_UPDATE, message);
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], this.instance.name, database.SAVE_DATA.MESSAGE_UPDATE);
[message],
this.instance.name,
database.SAVE_DATA.MESSAGE_UPDATE,
);
} }
} }
}, },
@ -1555,7 +1473,7 @@ export class WAStartupService {
.replace(/\+/g, '') .replace(/\+/g, '')
.replace(/\(/g, '') .replace(/\(/g, '')
.replace(/\)/g, '') .replace(/\)/g, '')
.split(/\:/)[0] .split(':')[0]
.split('@')[0]; .split('@')[0];
if (number.includes('-') && number.length >= 24) { if (number.includes('-') && number.length >= 24) {
@ -1620,7 +1538,6 @@ export class WAStartupService {
this.logger.verbose('Getting profile with jid: ' + jid); this.logger.verbose('Getting profile with jid: ' + jid);
try { try {
this.logger.verbose('Getting profile info'); this.logger.verbose('Getting profile info');
const info = await waMonitor.instanceInfo(instanceName);
const business = await this.fetchBusinessProfile(jid); const business = await this.fetchBusinessProfile(jid);
if (number) { if (number) {
@ -1667,11 +1584,7 @@ export class WAStartupService {
} }
} }
private async sendMessageWithTyping<T = proto.IMessage>( private async sendMessageWithTyping<T = proto.IMessage>(number: string, message: T, options?: Options) {
number: string,
message: T,
options?: Options,
) {
this.logger.verbose('Sending message with typing'); this.logger.verbose('Sending message with typing');
const numberWA = await this.whatsappNumber({ numbers: [number] }); const numberWA = await this.whatsappNumber({ numbers: [number] });
@ -1691,9 +1604,7 @@ export class WAStartupService {
this.logger.verbose('Subscribing to presence'); this.logger.verbose('Subscribing to presence');
await this.client.sendPresenceUpdate(options?.presence ?? 'composing', sender); await this.client.sendPresenceUpdate(options?.presence ?? 'composing', sender);
this.logger.verbose( this.logger.verbose('Sending presence update: ' + options?.presence ?? 'composing');
'Sending presence update: ' + options?.presence ?? 'composing',
);
await delay(options.delay); await delay(options.delay);
this.logger.verbose('Set delay: ' + options.delay); this.logger.verbose('Set delay: ' + options.delay);
@ -1709,9 +1620,7 @@ export class WAStartupService {
if (options?.quoted) { if (options?.quoted) {
const m = options?.quoted; const m = options?.quoted;
const msg = m?.message const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
? m
: ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
if (!msg) { if (!msg) {
throw 'Message not found'; throw 'Message not found';
@ -1912,9 +1821,7 @@ export class WAStartupService {
} }
this.logger.verbose('Getting contacts with push name'); this.logger.verbose('Getting contacts with push name');
status.statusJidList = contacts status.statusJidList = contacts.filter((contact) => contact.pushName).map((contact) => contact.id);
.filter((contact) => contact.pushName)
.map((contact) => contact.id);
this.logger.verbose(status.statusJidList); this.logger.verbose(status.statusJidList);
} }
@ -2031,9 +1938,7 @@ export class WAStartupService {
this.logger.verbose('Media type: ' + mediaType); this.logger.verbose('Media type: ' + mediaType);
if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) { if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) {
this.logger.verbose( this.logger.verbose('If media type is document and file name is not defined then');
'If media type is document and file name is not defined then',
);
const regex = new RegExp(/.*\/(.+?)\./); const regex = new RegExp(/.*\/(.+?)\./);
const arrayMatch = regex.exec(mediaMessage.media); const arrayMatch = regex.exec(mediaMessage.media);
mediaMessage.fileName = arrayMatch[1]; mediaMessage.fileName = arrayMatch[1];
@ -2146,11 +2051,7 @@ export class WAStartupService {
this.logger.verbose('Sending media message'); this.logger.verbose('Sending media message');
const generate = await this.prepareMediaMessage(data.mediaMessage); const generate = await this.prepareMediaMessage(data.mediaMessage);
return await this.sendMessageWithTyping( return await this.sendMessageWithTyping(data.number, { ...generate.message }, data?.options);
data.number,
{ ...generate.message },
data?.options,
);
} }
private async processAudio(audio: string, number: string) { private async processAudio(audio: string, number: string) {
@ -2195,18 +2096,15 @@ export class WAStartupService {
this.logger.verbose('Converting audio to mp4'); this.logger.verbose('Converting audio to mp4');
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
exec( exec(`${ffmpegPath.path} -i ${tempAudioPath} -vn -ab 128k -ar 44100 -f ipod ${outputAudio} -y`, (error) => {
`${ffmpegPath.path} -i ${tempAudioPath} -vn -ab 128k -ar 44100 -f ipod ${outputAudio} -y`, fs.unlinkSync(tempAudioPath);
(error, _stdout, _stderr) => { this.logger.verbose('Temp audio deleted');
fs.unlinkSync(tempAudioPath);
this.logger.verbose('Temp audio deleted');
if (error) reject(error); if (error) reject(error);
this.logger.verbose('Audio converted to mp4'); this.logger.verbose('Audio converted to mp4');
resolve(outputAudio); resolve(outputAudio);
}, });
);
}); });
} }
@ -2272,10 +2170,7 @@ export class WAStartupService {
}; };
if (!arrayUnique(btnItems.text) || !arrayUnique(btnItems.ids)) { if (!arrayUnique(btnItems.text) || !arrayUnique(btnItems.ids)) {
throw new BadRequestException( throw new BadRequestException('Button texts cannot be repeated', 'Button IDs cannot be repeated.');
'Button texts cannot be repeated',
'Button IDs cannot be repeated.',
);
} }
return await this.sendMessageWithTyping( return await this.sendMessageWithTyping(
@ -2342,11 +2237,7 @@ export class WAStartupService {
const vcard = (contact: ContactMessage) => { const vcard = (contact: ContactMessage) => {
this.logger.verbose('Creating vcard'); this.logger.verbose('Creating vcard');
let result = let result = 'BEGIN:VCARD\n' + 'VERSION:3.0\n' + `N:${contact.fullName}\n` + `FN:${contact.fullName}\n`;
'BEGIN:VCARD\n' +
'VERSION:3.0\n' +
`N:${contact.fullName}\n` +
`FN:${contact.fullName}\n`;
if (contact.organization) { if (contact.organization) {
this.logger.verbose('Organization defined'); this.logger.verbose('Organization defined');
@ -2368,10 +2259,7 @@ export class WAStartupService {
contact.wuid = this.createJid(contact.phoneNumber); contact.wuid = this.createJid(contact.phoneNumber);
} }
result += result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD';
`item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` +
'item1.X-ABLabel:Celular\n' +
'END:VCARD';
this.logger.verbose('Vcard created'); this.logger.verbose('Vcard created');
return result; return result;
@ -2461,8 +2349,7 @@ export class WAStartupService {
public async archiveChat(data: ArchiveChatDto) { public async archiveChat(data: ArchiveChatDto) {
this.logger.verbose('Archiving chat'); this.logger.verbose('Archiving chat');
try { try {
data.lastMessage.messageTimestamp = data.lastMessage.messageTimestamp = data.lastMessage?.messageTimestamp ?? Date.now();
data.lastMessage?.messageTimestamp ?? Date.now();
await this.client.chatModify( await this.client.chatModify(
{ {
archive: data.archive, archive: data.archive,
@ -2478,10 +2365,7 @@ export class WAStartupService {
} catch (error) { } catch (error) {
throw new InternalServerErrorException({ throw new InternalServerErrorException({
archived: false, archived: false,
message: [ message: ['An error occurred while archiving the chat. Open a calling.', error.toString()],
'An error occurred while archiving the chat. Open a calling.',
error.toString(),
],
}); });
} }
} }
@ -2491,10 +2375,7 @@ export class WAStartupService {
try { try {
return await this.client.sendMessage(del.remoteJid, { delete: del }); return await this.client.sendMessage(del.remoteJid, { delete: del });
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error while deleting message for everyone', error?.toString());
'Error while deleting message for everyone',
error?.toString(),
);
} }
} }
@ -2504,9 +2385,7 @@ export class WAStartupService {
const m = data?.message; const m = data?.message;
const convertToMp4 = data?.convertToMp4 ?? false; const convertToMp4 = data?.convertToMp4 ?? false;
const msg = m?.message const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
? m
: ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
if (!msg) { if (!msg) {
throw 'Message not found'; throw 'Message not found';
@ -2696,10 +2575,7 @@ export class WAStartupService {
}, },
}; };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating privacy settings', error.toString());
'Error updating privacy settings',
error.toString(),
);
} }
} }
@ -2727,10 +2603,7 @@ export class WAStartupService {
...profile, ...profile,
}; };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating profile name', error.toString());
'Error updating profile name',
error.toString(),
);
} }
} }
@ -2741,10 +2614,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating profile name', error.toString());
'Error updating profile name',
error.toString(),
);
} }
} }
@ -2755,10 +2625,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating profile status', error.toString());
'Error updating profile status',
error.toString(),
);
} }
} }
@ -2787,10 +2654,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating profile picture', error.toString());
'Error updating profile picture',
error.toString(),
);
} }
} }
@ -2801,10 +2665,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error removing profile picture', error.toString());
'Error removing profile picture',
error.toString(),
);
} }
} }
@ -2865,10 +2726,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error update group picture', error.toString());
'Error update group picture',
error.toString(),
);
} }
} }
@ -2879,10 +2737,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating group subject', error.toString());
'Error updating group subject',
error.toString(),
);
} }
} }
@ -2893,10 +2748,7 @@ export class WAStartupService {
return { update: 'success' }; return { update: 'success' };
} catch (error) { } catch (error) {
throw new InternalServerErrorException( throw new InternalServerErrorException('Error updating group description', error.toString());
'Error updating group description',
error.toString(),
);
} }
} }
@ -3032,10 +2884,7 @@ export class WAStartupService {
public async updateGSetting(update: GroupUpdateSettingDto) { public async updateGSetting(update: GroupUpdateSettingDto) {
this.logger.verbose('Updating setting for group: ' + update.groupJid); this.logger.verbose('Updating setting for group: ' + update.groupJid);
try { try {
const updateSetting = await this.client.groupSettingUpdate( const updateSetting = await this.client.groupSettingUpdate(update.groupJid, update.action);
update.groupJid,
update.action,
);
return { updateSetting: updateSetting }; return { updateSetting: updateSetting };
} catch (error) { } catch (error) {
throw new BadRequestException('Error updating setting', error.toString()); throw new BadRequestException('Error updating setting', error.toString());
@ -3045,10 +2894,7 @@ export class WAStartupService {
public async toggleEphemeral(update: GroupToggleEphemeralDto) { public async toggleEphemeral(update: GroupToggleEphemeralDto) {
this.logger.verbose('Toggling ephemeral for group: ' + update.groupJid); this.logger.verbose('Toggling ephemeral for group: ' + update.groupJid);
try { try {
const toggleEphemeral = await this.client.groupToggleEphemeral( await this.client.groupToggleEphemeral(update.groupJid, update.expiration);
update.groupJid,
update.expiration,
);
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
throw new BadRequestException('Error updating setting', error.toString()); throw new BadRequestException('Error updating setting', error.toString());

View File

@ -76,23 +76,10 @@ export declare namespace wa {
statusReason?: number; statusReason?: number;
}; };
export type StatusMessage = export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED';
| 'ERROR'
| 'PENDING'
| 'SERVER_ACK'
| 'DELIVERY_ACK'
| 'READ'
| 'DELETED'
| 'PLAYED';
} }
export const TypeMediaMessage = [ export const TypeMediaMessage = ['imageMessage', 'documentMessage', 'audioMessage', 'videoMessage', 'stickerMessage'];
'imageMessage',
'documentMessage',
'audioMessage',
'videoMessage',
'stickerMessage',
];
export const MessageSubtype = [ export const MessageSubtype = [
'ephemeralMessage', 'ephemeralMessage',

View File

@ -1,43 +1,40 @@
import { Auth, configService } from '../config/env.config'; import { configService } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { eventEmitter } from '../config/event.config'; import { eventEmitter } from '../config/event.config';
import { MessageRepository } from './repository/message.repository'; import { Logger } from '../config/logger.config';
import { WAMonitoringService } from './services/monitor.service'; import { dbserver } from '../db/db.connect';
import { ChatRepository } from './repository/chat.repository'; import { RedisCache } from '../db/redis.client';
import { ContactRepository } from './repository/contact.repository';
import { MessageUpRepository } from './repository/messageUp.repository';
import { ChatController } from './controllers/chat.controller'; import { ChatController } from './controllers/chat.controller';
import { ChatwootController } from './controllers/chatwoot.controller';
import { GroupController } from './controllers/group.controller';
import { InstanceController } from './controllers/instance.controller'; import { InstanceController } from './controllers/instance.controller';
import { SendMessageController } from './controllers/sendMessage.controller'; import { SendMessageController } from './controllers/sendMessage.controller';
import { AuthService } from './services/auth.service'; import { SettingsController } from './controllers/settings.controller';
import { GroupController } from './controllers/group.controller';
import { ViewsController } from './controllers/views.controller'; import { ViewsController } from './controllers/views.controller';
import { WebhookService } from './services/webhook.service';
import { WebhookController } from './controllers/webhook.controller'; import { WebhookController } from './controllers/webhook.controller';
import { ChatwootService } from './services/chatwoot.service';
import { ChatwootController } from './controllers/chatwoot.controller';
import { RepositoryBroker } from './repository/repository.manager';
import { import {
AuthModel, AuthModel,
ChatModel, ChatModel,
ChatwootModel,
ContactModel, ContactModel,
MessageModel, MessageModel,
MessageUpModel, MessageUpModel,
ChatwootModel,
WebhookModel,
SettingsModel, SettingsModel,
WebhookModel,
} from './models'; } from './models';
import { dbserver } from '../db/db.connect';
import { WebhookRepository } from './repository/webhook.repository';
import { ChatwootRepository } from './repository/chatwoot.repository';
import { AuthRepository } from './repository/auth.repository'; import { AuthRepository } from './repository/auth.repository';
import { WAStartupService } from './services/whatsapp.service'; import { ChatRepository } from './repository/chat.repository';
import { delay } from '@whiskeysockets/baileys'; import { ChatwootRepository } from './repository/chatwoot.repository';
import { Events } from './types/wa.types'; import { ContactRepository } from './repository/contact.repository';
import { RedisCache } from '../db/redis.client'; import { MessageRepository } from './repository/message.repository';
import { MessageUpRepository } from './repository/messageUp.repository';
import { RepositoryBroker } from './repository/repository.manager';
import { SettingsRepository } from './repository/settings.repository'; import { SettingsRepository } from './repository/settings.repository';
import { WebhookRepository } from './repository/webhook.repository';
import { AuthService } from './services/auth.service';
import { ChatwootService } from './services/chatwoot.service';
import { WAMonitoringService } from './services/monitor.service';
import { SettingsService } from './services/settings.service'; import { SettingsService } from './services/settings.service';
import { SettingsController } from './controllers/settings.controller'; import { WebhookService } from './services/webhook.service';
const logger = new Logger('WA MODULE'); const logger = new Logger('WA MODULE');
@ -65,12 +62,7 @@ export const repository = new RepositoryBroker(
export const cache = new RedisCache(); export const cache = new RedisCache();
export const waMonitor = new WAMonitoringService( export const waMonitor = new WAMonitoringService(eventEmitter, configService, repository, cache);
eventEmitter,
configService,
repository,
cache,
);
const authService = new AuthService(configService, waMonitor, repository); const authService = new AuthService(configService, waMonitor, repository);