This commit is contained in:
Alan Mosko 2023-07-26 10:58:13 -03:00
parent 03f3020e9f
commit 249aecbc0d
70 changed files with 9184 additions and 9768 deletions

View File

@ -30,7 +30,7 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': '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',

View File

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

View File

@ -14,15 +14,7 @@ export type Cors = {
export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
export type LogLevel =
| 'ERROR'
| 'WARN'
| 'DEBUG'
| 'INFO'
| 'LOG'
| 'VERBOSE'
| 'DARK'
| 'WEBHOOKS';
export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS';
export type Log = {
LEVEL: LogLevel[];
@ -155,9 +147,7 @@ export class ConfigService {
}
private envYaml(): Env {
return load(
readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' }),
) as Env;
return load(readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' })) as Env;
}
private envProcess(): Env {
@ -243,8 +233,7 @@ export class ConfigService {
CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true',
GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true',
GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE:
process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE: process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true',
},
},
@ -260,8 +249,7 @@ export class ConfigService {
API_KEY: {
KEY: process.env.AUTHENTICATION_API_KEY,
},
EXPOSE_IN_FETCH_INSTANCES:
process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
JWT: {
EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN)
? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN)

View File

@ -60,11 +60,7 @@ export class RedisCache {
this.logger.verbose('writeData: ' + field);
const json = JSON.stringify(data, BufferJSON.replacer);
return await this.client.hSet(
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
json,
);
return await this.client.hSet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field, json);
} catch (error) {
this.logger.error(error);
}
@ -73,10 +69,7 @@ export class RedisCache {
public async readData(field: string) {
try {
this.logger.verbose('readData: ' + field);
const data = await this.client.hGet(
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
const data = await this.client.hGet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
if (data) {
this.logger.verbose('readData: ' + field + ' success');
@ -93,10 +86,7 @@ export class RedisCache {
public async removeData(field: string) {
try {
this.logger.verbose('removeData: ' + field);
return await this.client.hDel(
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
return await this.client.hDel(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
} catch (error) {
this.logger.error(error);
}
@ -105,9 +95,7 @@ export class RedisCache {
public async delAll(hash?: string) {
try {
this.logger.verbose('instance delAll: ' + hash);
const result = await this.client.del(
hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
);
const result = await this.client.del(hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName);
return result;
} catch (error) {

View File

@ -75,7 +75,7 @@ function bootstrap() {
// });
app.use(
(err: Error, req: Request, res: Response, next: NextFunction) => {
(err: Error, req: Request, res: Response) => {
if (err) {
return res.status(err['status'] || 500).json(err);
}
@ -98,9 +98,7 @@ function bootstrap() {
ServerUP.app = app;
const server = ServerUP[httpServer.TYPE];
server.listen(httpServer.PORT, () =>
logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT),
);
server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));
initWA();

View File

@ -25,11 +25,9 @@ export async function useMultiFileAuthStateDb(
const writeData = async (data: any, key: string): Promise<any> => {
try {
await client.connect();
return await collection.replaceOne(
{ _id: key },
JSON.parse(JSON.stringify(data, BufferJSON.replacer)),
{ upsert: true },
);
return await collection.replaceOne({ _id: key }, JSON.parse(JSON.stringify(data, BufferJSON.replacer)), {
upsert: true,
});
} catch (error) {
logger.error(error);
}

View File

@ -6,7 +6,6 @@ import {
SignalDataTypeMap,
} from '@whiskeysockets/baileys';
import { Redis } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { RedisCache } from '../db/redis.client';

View File

@ -35,11 +35,9 @@ export abstract class Repository implements IRepository {
mkdirSync(create.path, { recursive: true });
}
try {
writeFileSync(
join(create.path, create.fileName + '.json'),
JSON.stringify({ ...create.data }),
{ encoding: 'utf-8' },
);
writeFileSync(join(create.path, create.fileName + '.json'), JSON.stringify({ ...create.data }), {
encoding: 'utf-8',
});
return { message: 'create - success' };
} finally {
@ -47,18 +45,22 @@ export abstract class Repository implements IRepository {
}
};
// eslint-disable-next-line
public insert(data: any, instanceName: string, saveDb = false): Promise<IInsert> {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line
public update(data: any, instanceName: string, saveDb = false): Promise<IInsert> {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line
public find(query: any): Promise<any> {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line
delete(query: any, force?: boolean): Promise<any> {
throw new Error('Method not implemented.');
}

View File

@ -188,9 +188,7 @@ export abstract class RouterBroker {
const getParticipants = request.query as unknown as GetParticipant;
if (!getParticipants?.getParticipants) {
throw new BadRequestException(
'The getParticipants needs to be informed in the query',
);
throw new BadRequestException('The getParticipants needs to be informed in the query');
}
const instance = request.params as unknown as InstanceDto;

View File

@ -1,5 +1,3 @@
import { proto } from '@whiskeysockets/baileys';
import { Logger } from '../../config/logger.config';
import {
ArchiveChatDto,
@ -51,10 +49,7 @@ export class ChatController {
public async fetchProfile({ instanceName }: InstanceDto, data: NumberDto) {
logger.verbose('requested fetchProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchProfile(
instanceName,
data.number,
);
return await this.waMonitor.waInstances[instanceName].fetchProfile(instanceName, data.number);
}
public async fetchContacts({ instanceName }: InstanceDto, query: ContactQuery) {
@ -62,13 +57,8 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchContacts(query);
}
public async getBase64FromMediaMessage(
{ instanceName }: InstanceDto,
data: getBase64FromMediaMessageDto,
) {
logger.verbose(
'requested getBase64FromMediaMessage from ' + instanceName + ' instance',
);
public async getBase64FromMediaMessage({ instanceName }: InstanceDto, data: getBase64FromMediaMessageDto) {
logger.verbose('requested getBase64FromMediaMessage from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data);
}
@ -92,22 +82,14 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings();
}
public async updatePrivacySettings(
{ instanceName }: InstanceDto,
data: PrivacySettingDto,
) {
public async updatePrivacySettings({ instanceName }: InstanceDto, data: PrivacySettingDto) {
logger.verbose('requested updatePrivacySettings from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data);
}
public async fetchBusinessProfile(
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
public async fetchBusinessProfile({ instanceName }: InstanceDto, data: ProfilePictureDto) {
logger.verbose('requested fetchBusinessProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(
data.number,
);
return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(data.number);
}
public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) {
@ -115,30 +97,17 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name);
}
public async updateProfileStatus(
{ instanceName }: InstanceDto,
data: ProfileStatusDto,
) {
public async updateProfileStatus({ instanceName }: InstanceDto, data: ProfileStatusDto) {
logger.verbose('requested updateProfileStatus from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfileStatus(
data.status,
);
return await this.waMonitor.waInstances[instanceName].updateProfileStatus(data.status);
}
public async updateProfilePicture(
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
public async updateProfilePicture({ instanceName }: InstanceDto, data: ProfilePictureDto) {
logger.verbose('requested updateProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfilePicture(
data.picture,
);
return await this.waMonitor.waInstances[instanceName].updateProfilePicture(data.picture);
}
public async removeProfilePicture(
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
public async removeProfilePicture({ instanceName }: InstanceDto) {
logger.verbose('requested removeProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].removeProfilePicture();
}

View File

@ -11,15 +11,10 @@ import { waMonitor } from '../whatsapp.module';
const logger = new Logger('ChatwootController');
export class ChatwootController {
constructor(
private readonly chatwootService: ChatwootService,
private readonly configService: ConfigService,
) {}
constructor(private readonly chatwootService: ChatwootService, private readonly configService: ConfigService) {}
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
logger.verbose(
'requested createChatwoot from ' + instance.instanceName + ' instance',
);
logger.verbose('requested createChatwoot from ' + instance.instanceName + ' instance');
if (data.enabled) {
if (!isURL(data.url, { require_tld: false })) {
@ -88,9 +83,7 @@ export class ChatwootController {
}
public async receiveWebhook(instance: InstanceDto, data: any) {
logger.verbose(
'requested receiveWebhook from ' + instance.instanceName + ' instance',
);
logger.verbose('requested receiveWebhook from ' + instance.instanceName + ' instance');
const chatwootService = new ChatwootService(waMonitor, this.configService);
return chatwootService.receiveWebhook(instance, data);

View File

@ -26,33 +26,18 @@ export class GroupController {
}
public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) {
logger.verbose(
'requested updateGroupPicture from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(
update,
);
logger.verbose('requested updateGroupPicture from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(update);
}
public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) {
logger.verbose(
'requested updateGroupSubject from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(
update,
);
logger.verbose('requested updateGroupSubject from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(update);
}
public async updateGroupDescription(
instance: InstanceDto,
update: GroupDescriptionDto,
) {
logger.verbose(
'requested updateGroupDescription from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(
update,
);
public async updateGroupDescription(instance: InstanceDto, update: GroupDescriptionDto) {
logger.verbose('requested updateGroupDescription from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(update);
}
public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) {
@ -61,12 +46,8 @@ export class GroupController {
}
public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) {
logger.verbose(
'requested fetchAllGroups from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(
getPaticipants,
);
logger.verbose('requested fetchAllGroups from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(getPaticipants);
}
public async inviteCode(instance: InstanceDto, groupJid: GroupJid) {
@ -85,49 +66,28 @@ export class GroupController {
}
public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose(
'requested revokeInviteCode from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(
groupJid,
);
logger.verbose('requested revokeInviteCode from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(groupJid);
}
public async findParticipants(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose(
'requested findParticipants from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].findParticipants(
groupJid,
);
logger.verbose('requested findParticipants from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].findParticipants(groupJid);
}
public async updateGParticipate(
instance: InstanceDto,
update: GroupUpdateParticipantDto,
) {
logger.verbose(
'requested updateGParticipate from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(
update,
);
public async updateGParticipate(instance: InstanceDto, update: GroupUpdateParticipantDto) {
logger.verbose('requested updateGParticipate from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(update);
}
public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) {
logger.verbose(
'requested updateGSetting from ' + instance.instanceName + ' instance',
);
logger.verbose('requested updateGSetting from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update);
}
public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) {
logger.verbose(
'requested toggleEphemeral from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(
update,
);
logger.verbose('requested toggleEphemeral from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(update);
}
public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) {

View File

@ -2,7 +2,7 @@ import { delay } from '@whiskeysockets/baileys';
import { isURL } from 'class-validator';
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';
@ -45,21 +45,14 @@ export class InstanceController {
this.logger.verbose('requested createInstance from ' + instanceName + ' instance');
if (instanceName !== instanceName.toLowerCase().replace(/[^a-z0-9]/g, '')) {
throw new BadRequestException(
'The instance name must be lowercase and without special characters',
);
throw new BadRequestException('The instance name must be lowercase and without special characters');
}
this.logger.verbose('checking duplicate token');
await this.authService.checkDuplicateToken(token);
this.logger.verbose('creating instance');
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
instance.instanceName = instanceName
.toLowerCase()
.replace(/[^a-z0-9]/g, '')
@ -194,9 +187,7 @@ export class InstanceController {
public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) {
try {
this.logger.verbose(
'requested connectToWhatsapp from ' + instanceName + ' instance',
);
this.logger.verbose('requested connectToWhatsapp from ' + instanceName + ' instance');
const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state;
@ -269,16 +260,12 @@ export class InstanceController {
const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'close') {
throw new BadRequestException(
'The "' + instanceName + '" instance is not connected',
);
throw new BadRequestException('The "' + instanceName + '" instance is not connected');
}
try {
this.logger.verbose('logging out instance: ' + instanceName);
await this.waMonitor.waInstances[instanceName]?.client?.logout(
'Log out instance: ' + instanceName,
);
await this.waMonitor.waInstances[instanceName]?.client?.logout('Log out instance: ' + instanceName);
this.logger.verbose('close connection instance: ' + instanceName);
this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
@ -294,9 +281,7 @@ export class InstanceController {
const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'open') {
throw new BadRequestException(
'The "' + instanceName + '" instance needs to be disconnected',
);
throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected');
}
try {
if (instance.state === 'connecting') {

View File

@ -40,10 +40,7 @@ export class SendMessageController {
}
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)) {
return await this.waMonitor.waInstances[instanceName].mediaMessage(data);
@ -55,10 +52,7 @@ export class SendMessageController {
logger.verbose('requested sendSticker from ' + instanceName + ' instance');
logger.verbose(
'isURL: ' +
isURL(data?.stickerMessage?.image) +
', isBase64: ' +
isBase64(data?.stickerMessage?.image),
'isURL: ' + isURL(data?.stickerMessage?.image) + ', isBase64: ' + isBase64(data?.stickerMessage?.image),
);
if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) {
return await this.waMonitor.waInstances[instanceName].mediaSticker(data);
@ -70,10 +64,7 @@ export class SendMessageController {
logger.verbose('requested sendWhatsAppAudio from ' + instanceName + ' instance');
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)) {
return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data);
@ -83,10 +74,7 @@ export class SendMessageController {
public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) {
logger.verbose('requested sendButtons from ' + instanceName + ' instance');
if (
isBase64(data.buttonMessage.mediaMessage?.media) &&
!data.buttonMessage.mediaMessage?.fileName
) {
if (isBase64(data.buttonMessage.mediaMessage?.media) && !data.buttonMessage.mediaMessage?.fileName) {
throw new BadRequestException('For bse64 the file name must be informed.');
}
return await this.waMonitor.waInstances[instanceName].buttonMessage(data);

View File

@ -1,5 +1,3 @@
import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
@ -12,9 +10,7 @@ export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
public async createSettings(instance: InstanceDto, data: SettingsDto) {
logger.verbose(
'requested createSettings from ' + instance.instanceName + ' instance',
);
logger.verbose('requested createSettings from ' + instance.instanceName + ' instance');
if (data.reject_call && data.msg_call.trim() == '') {
throw new BadRequestException('msg_call is required');

View File

@ -7,10 +7,7 @@ import { HttpStatus } from '../routers/index.router';
import { WAMonitoringService } from '../services/monitor.service';
export class ViewsController {
constructor(
private readonly waMonit: WAMonitoringService,
private readonly configService: ConfigService,
) {}
constructor(private readonly waMonit: WAMonitoringService, private readonly configService: ConfigService) {}
public async qrcode(request: Request, response: Response) {
try {

View File

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

View File

@ -24,14 +24,10 @@ async function jwtGuard(req: Request, res: Response, next: NextFunction) {
}
if (
(req.originalUrl.includes('/instance/create') ||
req.originalUrl.includes('/instance/fetchInstances')) &&
(req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) &&
!key
) {
throw new ForbiddenException(
'Missing global api key',
'The global api key must be set',
);
throw new ForbiddenException('Missing global api key', 'The global api key must be set');
}
const jwtOpts = configService.get<Auth>('AUTHENTICATION').JWT;
@ -71,14 +67,10 @@ async function apikey(req: Request, res: Response, next: NextFunction) {
}
if (
(req.originalUrl.includes('/instance/create') ||
req.originalUrl.includes('/instance/fetchInstances')) &&
(req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) &&
!key
) {
throw new ForbiddenException(
'Missing global api key',
'The global api key must be set',
);
throw new ForbiddenException('Missing global api key', 'The global api key must be set');
}
try {

View File

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

View File

@ -24,9 +24,5 @@ const chatwootSchema = new Schema<ChatwootRaw>({
number: { type: String, required: true },
});
export const ChatwootModel = dbserver?.model(
ChatwootRaw.name,
chatwootSchema,
'chatwoot',
);
export const ChatwootModel = dbserver?.model(ChatwootRaw.name, chatwootSchema, 'chatwoot');
export type IChatwootModel = typeof ChatwootModel;

View File

@ -65,9 +65,5 @@ const messageUpdateSchema = new Schema<MessageUpdateRaw>({
owner: { type: String, required: true, min: 1 },
});
export const MessageUpModel = dbserver?.model(
MessageUpdateRaw.name,
messageUpdateSchema,
'messageUpdate',
);
export const MessageUpModel = dbserver?.model(MessageUpdateRaw.name, messageUpdateSchema, 'messageUpdate');
export type IMessageUpModel = typeof MessageUpModel;

View File

@ -16,9 +16,5 @@ const settingsSchema = new Schema<SettingsRaw>({
groups_ignore: { type: Boolean, required: true },
});
export const SettingsModel = dbserver?.model(
SettingsRaw.name,
settingsSchema,
'settings',
);
export const SettingsModel = dbserver?.model(SettingsRaw.name, settingsSchema, 'settings');
export type ISettingsModel = typeof SettingsModel;

View File

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

View File

@ -11,20 +11,13 @@ export class ChatQuery {
}
export class ChatRepository extends Repository {
constructor(
private readonly chatModel: IChatModel,
private readonly configService: ConfigService,
) {
constructor(private readonly chatModel: IChatModel, private readonly configService: ConfigService) {
super(configService);
}
private readonly logger = new Logger('ChatRepository');
public async insert(
data: ChatRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
public async insert(data: ChatRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
this.logger.verbose('inserting chats');
if (data.length === 0) {
this.logger.verbose('no chats to insert');
@ -54,10 +47,7 @@ export class ChatRepository extends Repository {
data: chat,
});
this.logger.verbose(
'chats saved to store in path: ' +
join(this.storePath, 'chats', instanceName) +
'/' +
chat.id,
'chats saved to store in path: ' + join(this.storePath, 'chats', instanceName) + '/' + chat.id,
);
});
@ -90,10 +80,9 @@ export class ChatRepository extends Repository {
if (dirent.isFile()) {
chats.push(
JSON.parse(
readFileSync(
join(this.storePath, 'chats', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
readFileSync(join(this.storePath, 'chats', query.where.owner, dirent.name), {
encoding: 'utf-8',
}),
),
);
}

View File

@ -7,10 +7,7 @@ import { IInsert, Repository } from '../abstract/abstract.repository';
import { ChatwootRaw, IChatwootModel } from '../models';
export class ChatwootRepository extends Repository {
constructor(
private readonly chatwootModel: IChatwootModel,
private readonly configService: ConfigService,
) {
constructor(private readonly chatwootModel: IChatwootModel, private readonly configService: ConfigService) {
super(configService);
}
@ -21,15 +18,9 @@ export class ChatwootRepository extends Repository {
this.logger.verbose('creating chatwoot');
if (this.dbSettings.ENABLED) {
this.logger.verbose('saving chatwoot to db');
const insert = await this.chatwootModel.replaceOne(
{ _id: instance },
{ ...data },
{ upsert: true },
);
const insert = await this.chatwootModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
this.logger.verbose(
'chatwoot saved to db: ' + insert.modifiedCount + ' chatwoot',
);
this.logger.verbose('chatwoot saved to db: ' + insert.modifiedCount + ' chatwoot');
return { insertCount: insert.modifiedCount };
}
@ -42,10 +33,7 @@ export class ChatwootRepository extends Repository {
});
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');

View File

@ -11,20 +11,13 @@ export class ContactQuery {
}
export class ContactRepository extends Repository {
constructor(
private readonly contactModel: IContactModel,
private readonly configService: ConfigService,
) {
constructor(private readonly contactModel: IContactModel, private readonly configService: ConfigService) {
super(configService);
}
private readonly logger = new Logger('ContactRepository');
public async insert(
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
public async insert(data: ContactRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
this.logger.verbose('inserting contacts');
if (data.length === 0) {
@ -75,11 +68,7 @@ export class ContactRepository extends Repository {
}
}
public async update(
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
public async update(data: ContactRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
try {
this.logger.verbose('updating contacts');
@ -155,15 +144,9 @@ export class ContactRepository extends Repository {
this.logger.verbose('finding contacts in store by id');
contacts.push(
JSON.parse(
readFileSync(
join(
this.storePath,
'contacts',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
readFileSync(join(this.storePath, 'contacts', query.where.owner, query.where.id + '.json'), {
encoding: 'utf-8',
}),
),
);
} else {
@ -176,10 +159,9 @@ export class ContactRepository extends Repository {
if (dirent.isFile()) {
contacts.push(
JSON.parse(
readFileSync(
join(this.storePath, 'contacts', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
readFileSync(join(this.storePath, 'contacts', query.where.owner, dirent.name), {
encoding: 'utf-8',
}),
),
);
}

View File

@ -12,20 +12,13 @@ export class MessageQuery {
}
export class MessageRepository extends Repository {
constructor(
private readonly messageModel: IMessageModel,
private readonly configService: ConfigService,
) {
constructor(private readonly messageModel: IMessageModel, private readonly configService: ConfigService) {
super(configService);
}
private readonly logger = new Logger('MessageRepository');
public async insert(
data: MessageRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
public async insert(data: MessageRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
this.logger.verbose('inserting messages');
if (!Array.isArray(data) || data.length === 0) {
@ -121,12 +114,7 @@ export class MessageRepository extends Repository {
messages.push(
JSON.parse(
readFileSync(
join(
this.storePath,
'messages',
query.where.owner,
query.where.key.id + '.json',
),
join(this.storePath, 'messages', query.where.owner, query.where.key.id + '.json'),
{ encoding: 'utf-8' },
),
),
@ -141,10 +129,9 @@ export class MessageRepository extends Repository {
if (dirent.isFile()) {
messages.push(
JSON.parse(
readFileSync(
join(this.storePath, 'messages', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
readFileSync(join(this.storePath, 'messages', query.where.owner, dirent.name), {
encoding: 'utf-8',
}),
),
);
}

View File

@ -12,20 +12,13 @@ export class MessageUpQuery {
}
export class MessageUpRepository extends Repository {
constructor(
private readonly messageUpModel: IMessageUpModel,
private readonly configService: ConfigService,
) {
constructor(private readonly messageUpModel: IMessageUpModel, private readonly configService: ConfigService) {
super(configService);
}
private readonly logger = new Logger('MessageUpRepository');
public async insert(
data: MessageUpdateRaw[],
instanceName: string,
saveDb?: boolean,
): Promise<IInsert> {
public async insert(data: MessageUpdateRaw[], instanceName: string, saveDb?: boolean): Promise<IInsert> {
this.logger.verbose('inserting message up');
if (data.length === 0) {
@ -92,42 +85,32 @@ export class MessageUpRepository extends Repository {
messageUpdate.push(
JSON.parse(
readFileSync(
join(
this.storePath,
'message-up',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
readFileSync(join(this.storePath, 'message-up', query.where.owner, query.where.id + '.json'), {
encoding: 'utf-8',
}),
),
);
} else {
this.logger.verbose('finding message up in store by owner');
const openDir = opendirSync(
join(this.storePath, 'message-up', query.where.owner),
{ encoding: 'utf-8' },
);
const openDir = opendirSync(join(this.storePath, 'message-up', query.where.owner), {
encoding: 'utf-8',
});
for await (const dirent of openDir) {
if (dirent.isFile()) {
messageUpdate.push(
JSON.parse(
readFileSync(
join(this.storePath, 'message-up', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
readFileSync(join(this.storePath, 'message-up', query.where.owner, dirent.name), {
encoding: 'utf-8',
}),
),
);
}
}
}
this.logger.verbose(
'message up found in store: ' + messageUpdate.length + ' message up',
);
this.logger.verbose('message up found in store: ' + messageUpdate.length + ' message up');
return messageUpdate
.sort((x, y) => {
return y.datetime - x.datetime;

View File

@ -43,11 +43,7 @@ export class RepositoryBroker {
this.logger.verbose('creating store path: ' + storePath);
try {
const authDir = join(
storePath,
'auth',
this.configService.get<Auth>('AUTHENTICATION').TYPE,
);
const authDir = join(storePath, 'auth', this.configService.get<Auth>('AUTHENTICATION').TYPE);
const chatsDir = join(storePath, 'chats');
const contactsDir = join(storePath, 'contacts');
const messagesDir = join(storePath, 'messages');

View File

@ -7,10 +7,7 @@ import { IInsert, Repository } from '../abstract/abstract.repository';
import { ISettingsModel, SettingsRaw } from '../models';
export class SettingsRepository extends Repository {
constructor(
private readonly settingsModel: ISettingsModel,
private readonly configService: ConfigService,
) {
constructor(private readonly settingsModel: ISettingsModel, private readonly configService: ConfigService) {
super(configService);
}
@ -21,15 +18,9 @@ export class SettingsRepository extends Repository {
this.logger.verbose('creating settings');
if (this.dbSettings.ENABLED) {
this.logger.verbose('saving settings to db');
const insert = await this.settingsModel.replaceOne(
{ _id: instance },
{ ...data },
{ upsert: true },
);
const insert = await this.settingsModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
this.logger.verbose(
'settings saved to db: ' + insert.modifiedCount + ' settings',
);
this.logger.verbose('settings saved to db: ' + insert.modifiedCount + ' settings');
return { insertCount: insert.modifiedCount };
}
@ -42,10 +33,7 @@ export class SettingsRepository extends Repository {
});
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');

View File

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

View File

@ -1,4 +1,3 @@
import { proto } from '@whiskeysockets/baileys';
import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
@ -93,10 +92,7 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response);
})
.delete(
this.routerPath('deleteMessageForEveryone'),
...guards,
async (req, res) => {
.delete(this.routerPath('deleteMessageForEveryone'), ...guards, async (req, res) => {
logger.verbose('request received in deleteMessageForEveryone');
logger.verbose('request body: ');
logger.verbose(req.body);
@ -112,8 +108,7 @@ export class ChatRouter extends RouterBroker {
});
return res.status(HttpStatus.CREATED).json(response);
},
)
})
.post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => {
logger.verbose('request received in fetchProfilePictureUrl');
logger.verbose('request body: ');
@ -177,8 +172,7 @@ export class ChatRouter extends RouterBroker {
request: req,
schema: null,
ClassRef: getBase64FromMediaMessageDto,
execute: (instance, data) =>
chatController.getBase64FromMediaMessage(instance, data),
execute: (instance, data) => chatController.getBase64FromMediaMessage(instance, data),
});
return res.status(HttpStatus.CREATED).json(response);
@ -264,8 +258,7 @@ export class ChatRouter extends RouterBroker {
request: req,
schema: privacySettingsSchema,
ClassRef: PrivacySettingDto,
execute: (instance, data) =>
chatController.updatePrivacySettings(instance, data),
execute: (instance, data) => chatController.updatePrivacySettings(instance, data),
});
return res.status(HttpStatus.CREATED).json(response);
@ -282,8 +275,7 @@ export class ChatRouter extends RouterBroker {
request: req,
schema: profilePictureSchema,
ClassRef: ProfilePictureDto,
execute: (instance, data) =>
chatController.fetchBusinessProfile(instance, data),
execute: (instance, data) => chatController.fetchBusinessProfile(instance, data),
});
return res.status(HttpStatus.OK).json(response);
@ -334,8 +326,7 @@ export class ChatRouter extends RouterBroker {
request: req,
schema: profilePictureSchema,
ClassRef: ProfilePictureDto,
execute: (instance, data) =>
chatController.updateProfilePicture(instance, data),
execute: (instance, data) => chatController.updateProfilePicture(instance, data),
});
return res.status(HttpStatus.OK).json(response);
@ -352,8 +343,7 @@ export class ChatRouter extends RouterBroker {
request: req,
schema: profilePictureSchema,
ClassRef: ProfilePictureDto,
execute: (instance, data) =>
chatController.removeProfilePicture(instance, data),
execute: (instance) => chatController.removeProfilePicture(instance),
});
return res.status(HttpStatus.OK).json(response);

View File

@ -97,8 +97,7 @@ export class GroupRouter extends RouterBroker {
request: req,
schema: updateGroupDescriptionSchema,
ClassRef: GroupDescriptionDto,
execute: (instance, data) =>
groupController.updateGroupDescription(instance, data),
execute: (instance, data) => groupController.updateGroupDescription(instance, data),
});
res.status(HttpStatus.CREATED).json(response);

View File

@ -37,11 +37,7 @@ router
version: packageJson.version,
});
})
.use(
'/instance',
new InstanceRouter(configService, ...guards).router,
new ViewsRouter(instanceExistsGuard).router,
)
.use('/instance', new InstanceRouter(configService, ...guards).router, new ViewsRouter(instanceExistsGuard).router)
.use('/message', new MessageRouter(...guards).router)
.use('/chat', new ChatRouter(...guards).router)
.use('/group', new GroupRouter(...guards).router)

View File

@ -161,13 +161,9 @@ export class InstanceRouter extends RouterBroker {
if (db.ENABLED) {
try {
await dbserver.dropDatabase();
return res
.status(HttpStatus.CREATED)
.json({ error: false, message: 'Database deleted' });
return res.status(HttpStatus.CREATED).json({ error: false, message: 'Database deleted' });
} catch (error) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ error: true, message: error.message });
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: true, message: error.message });
}
}

View File

@ -80,8 +80,7 @@ export class MessageRouter extends RouterBroker {
request: req,
schema: audioMessageSchema,
ClassRef: SendMediaDto,
execute: (instance, data) =>
sendMessageController.sendWhatsAppAudio(instance, data),
execute: (instance, data) => sendMessageController.sendWhatsAppAudio(instance, data),
});
return res.status(HttpStatus.CREATED).json(response);

View File

@ -64,9 +64,7 @@ export class AuthService {
private async apikey(instance: InstanceDto, token?: string) {
const apikey = token ? token : v4().toUpperCase();
this.logger.verbose(
token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey,
);
this.logger.verbose(token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey);
const auth = await this.repository.auth.create({ apikey }, instance.instanceName);
@ -102,13 +100,9 @@ export class AuthService {
public async generateHash(instance: InstanceDto, token?: string) {
const options = this.configService.get<Auth>('AUTHENTICATION');
this.logger.verbose(
'generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName,
);
this.logger.verbose('generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName);
return (await this[options.TYPE](instance, token)) as
| { jwt: string }
| { apikey: string };
return (await this[options.TYPE](instance, token)) as { jwt: string } | { apikey: string };
}
public async refreshToken({ oldToken }: OldToken) {
@ -151,10 +145,7 @@ export class AuthService {
try {
this.logger.verbose('checking webhook');
const webhook = await this.repository.webhook.find(decode.instanceName);
if (
webhook?.enabled &&
this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN
) {
if (webhook?.enabled && this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN) {
this.logger.verbose('sending webhook');
const httpService = axios.create({ baseURL: webhook.url });

View File

@ -21,10 +21,7 @@ export class ChatwootService {
private provider: any;
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly configService: ConfigService,
) {
constructor(private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService) {
this.messageCache = new Set();
}
@ -55,9 +52,7 @@ export class ChatwootService {
private async getProvider(instance: InstanceDto) {
this.logger.verbose('get provider to instance: ' + instance.instanceName);
try {
const provider = await this.waMonitor.waInstances[
instance.instanceName
].findChatwoot();
const provider = await this.waMonitor.waInstances[instance.instanceName].findChatwoot();
if (!provider) {
this.logger.warn('provider not found');
@ -170,9 +165,7 @@ export class ChatwootService {
});
this.logger.verbose('check duplicate inbox');
const checkDuplicate = findInbox.payload
.map((inbox) => inbox.name)
.includes(inboxName);
const checkDuplicate = findInbox.payload.map((inbox) => inbox.name).includes(inboxName);
let inboxId: number;
@ -212,13 +205,7 @@ export class ChatwootService {
this.logger.verbose('find contact in chatwoot and create if not exists');
const contact =
(await this.findContact(instance, '123456')) ||
((await this.createContact(
instance,
'123456',
inboxId,
false,
'EvolutionAPI',
)) as any);
((await this.createContact(instance, '123456', inboxId, false, 'EvolutionAPI')) as any);
if (!contact) {
this.logger.warn('contact not found');
@ -417,23 +404,18 @@ export class ChatwootService {
if (isGroup) {
this.logger.verbose('get group name');
const group = await this.waMonitor.waInstances[
instance.instanceName
].client.groupMetadata(chatId);
const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId);
nameContact = `${group.subject} (GROUP)`;
this.logger.verbose('find or create participant in chatwoot');
const picture_url = await this.waMonitor.waInstances[
instance.instanceName
].profilePicture(body.key.participant.split('@')[0]);
const findParticipant = await this.findContact(
instance,
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(
body.key.participant.split('@')[0],
);
const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]);
if (findParticipant) {
if (!findParticipant.name || findParticipant.name === chatId) {
await this.updateContact(instance, findParticipant.id, {
@ -455,9 +437,7 @@ export class ChatwootService {
this.logger.verbose('find or create contact in chatwoot');
const picture_url = await this.waMonitor.waInstances[
instance.instanceName
].profilePicture(chatId);
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId);
const findContact = await this.findContact(instance, chatId);
@ -502,8 +482,7 @@ export class ChatwootService {
return null;
}
const contactId =
contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
if (!body.key.fromMe && contact.name === chatId && nameContact !== chatId) {
this.logger.verbose('update contact name in chatwoot');
@ -521,8 +500,7 @@ export class ChatwootService {
if (contactConversations) {
this.logger.verbose('return conversation if exists');
const conversation = contactConversations.payload.find(
(conversation) =>
conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id,
(conversation) => conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id,
);
if (conversation) {
this.logger.verbose('conversation found');
@ -572,9 +550,7 @@ export class ChatwootService {
}
this.logger.verbose('find inbox by name');
const findByName = inbox.payload.find(
(inbox) => inbox.name === instance.instanceName,
);
const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName);
if (!findByName) {
this.logger.warn('inbox not found');
@ -676,8 +652,7 @@ export class ChatwootService {
this.logger.verbose('find conversation by contact id');
const conversation = findConversation.data.payload.find(
(conversation) =>
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
(conversation) => conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
);
if (!conversation) {
@ -797,8 +772,7 @@ export class ChatwootService {
this.logger.verbose('find conversation by contact id');
const conversation = findConversation.data.payload.find(
(conversation) =>
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
(conversation) => conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
);
if (!conversation) {
@ -848,12 +822,7 @@ export class ChatwootService {
}
}
public async sendAttachment(
waInstance: any,
number: string,
media: any,
caption?: string,
) {
public async sendAttachment(waInstance: any, number: string, media: any, caption?: string) {
this.logger.verbose('send attachment to instance: ' + waInstance.instanceName);
try {
@ -934,9 +903,7 @@ export class ChatwootService {
public async receiveWebhook(instance: InstanceDto, body: any) {
try {
this.logger.verbose(
'receive webhook to chatwoot instance: ' + instance.instanceName,
);
this.logger.verbose('receive webhook to chatwoot instance: ' + instance.instanceName);
const client = await this.clientCw(instance);
if (!client) {
@ -985,11 +952,7 @@ export class ChatwootService {
if (!state) {
this.logger.verbose('state not found');
await this.createBotMessage(
instance,
`⚠️ ${body.inbox.name} instance not found.`,
'incoming',
);
await this.createBotMessage(instance, `⚠️ ${body.inbox.name} instance not found.`, 'incoming');
}
if (state) {
@ -1047,19 +1010,10 @@ export class ChatwootService {
}
}
if (
body.message_type === 'outgoing' &&
body?.conversation?.messages?.length &&
chatId !== '123456'
) {
if (body.message_type === 'outgoing' && body?.conversation?.messages?.length && chatId !== '123456') {
this.logger.verbose('check if is group');
this.messageCacheFile = path.join(
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
this.logger.verbose('cache file path: ' + this.messageCacheFile);
this.messageCache = this.loadMessageCache();
@ -1080,9 +1034,7 @@ export class ChatwootService {
if (senderName === null || senderName === undefined) {
formatText = messageReceived;
} else {
formatText = this.provider.sign_msg
? `*${senderName}:*\n\n${messageReceived}`
: messageReceived;
formatText = this.provider.sign_msg ? `*${senderName}:*\n\n${messageReceived}` : messageReceived;
}
for (const message of body.conversation.messages) {
@ -1096,12 +1048,7 @@ export class ChatwootService {
formatText = null;
}
await this.sendAttachment(
waInstance,
chatId,
attachment.data_url,
formatText,
);
await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
}
} else {
this.logger.verbose('message is text');
@ -1180,8 +1127,7 @@ export class ChatwootService {
messageContextInfo: msg.messageContextInfo?.stanzaId,
stickerMessage: msg.stickerMessage?.fileSha256.toString('base64'),
documentMessage: msg.documentMessage?.caption,
documentWithCaptionMessage:
msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
audioMessage: msg.audioMessage?.caption,
contactMessage: msg.contactMessage?.vcard,
contactsArrayMessage: msg.contactsArrayMessage,
@ -1369,12 +1315,7 @@ export class ChatwootService {
}
this.logger.verbose('send data to chatwoot');
const send = await this.sendData(
getConversion,
fileName,
messageType,
content,
);
const send = await this.sendData(getConversion, fileName, messageType, content);
if (!send) {
this.logger.warn('message not sent');
@ -1400,12 +1341,7 @@ export class ChatwootService {
this.logger.verbose('message is not group');
this.logger.verbose('send data to chatwoot');
const send = await this.sendData(
getConversion,
fileName,
messageType,
bodyMessage,
);
const send = await this.sendData(getConversion, fileName, messageType, bodyMessage);
if (!send) {
this.logger.warn('message not sent');
@ -1446,12 +1382,7 @@ export class ChatwootService {
}
this.logger.verbose('send data to chatwoot');
const send = await this.createMessage(
instance,
getConversion,
content,
messageType,
);
const send = await this.createMessage(instance, getConversion, content, messageType);
if (!send) {
this.logger.warn('message not sent');
@ -1477,12 +1408,7 @@ export class ChatwootService {
this.logger.verbose('message is not group');
this.logger.verbose('send data to chatwoot');
const send = await this.createMessage(
instance,
getConversion,
bodyMessage,
messageType,
);
const send = await this.createMessage(instance, getConversion, bodyMessage, messageType);
if (!send) {
this.logger.warn('message not sent');
@ -1544,16 +1470,9 @@ export class ChatwootService {
return await this.createBotMessage(instance, erroQRcode, 'incoming');
} else {
this.logger.verbose('qrcode success');
const fileData = Buffer.from(
body?.qrcode.base64.replace('data:image/png;base64,', ''),
'base64',
);
const fileData = Buffer.from(body?.qrcode.base64.replace('data:image/png;base64,', ''), 'base64');
const fileName = `${path.join(
waInstance?.storePath,
'temp',
`${`${instance}.png`}`,
)}`;
const fileName = `${path.join(waInstance?.storePath, 'temp', `${`${instance}.png`}`)}`;
this.logger.verbose('temp file name: ' + fileName);
@ -1561,12 +1480,7 @@ export class ChatwootService {
writeFileSync(fileName, fileData, 'utf8');
this.logger.verbose('send qrcode to chatwoot');
await this.createBotQr(
instance,
'QRCode successfully generated!',
'incoming',
fileName,
);
await this.createBotQr(instance, 'QRCode successfully generated!', 'incoming', fileName);
let msgQrCode = `⚡️ QRCode successfully generated!\n\nScan this QR code within the next 40 seconds.`;

View File

@ -5,14 +5,7 @@ import { Db } from 'mongodb';
import mongoose from 'mongoose';
import { join } from 'path';
import {
Auth,
ConfigService,
Database,
DelInstance,
HttpServer,
Redis,
} from '../../config/env.config';
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';
@ -64,16 +57,12 @@ export class WAMonitoringService {
public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
if (typeof time === 'number' && time > 0) {
this.logger.verbose(
`Instance "${instance}" don't have connection, will be removed in ${time} minutes`,
);
this.logger.verbose(`Instance "${instance}" don't have connection, will be removed in ${time} minutes`);
setTimeout(async () => {
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
await this.waInstances[instance]?.client?.logout(
'Log out instance: ' + instance,
);
await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance);
this.waInstances[instance]?.client?.ws?.close();
this.waInstances[instance]?.client?.end(undefined);
delete this.waInstances[instance];
@ -125,21 +114,16 @@ export class WAMonitoringService {
};
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance['serverUrl'] =
this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['apikey'] = (
await this.repository.auth.find(key)
).apikey;
instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
instanceData.instance['chatwoot'] = chatwoot;
}
instances.push(instanceData);
} else {
this.logger.verbose(
'instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state,
);
this.logger.verbose('instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state);
const instanceData = {
instance: {
@ -149,12 +133,9 @@ export class WAMonitoringService {
};
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance['serverUrl'] =
this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['apikey'] = (
await this.repository.auth.find(key)
).apikey;
instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
instanceData.instance['chatwoot'] = chatwoot;
}
@ -177,10 +158,7 @@ export class WAMonitoringService {
collections.forEach(async (collection) => {
const name = collection.namespace.replace(/^[\w-]+./, '');
await this.dbInstance.collection(name).deleteMany({
$or: [
{ _id: { $regex: /^app.state.*/ } },
{ _id: { $regex: /^session-.*/ } },
],
$or: [{ _id: { $regex: /^app.state.*/ } }, { _id: { $regex: /^session-.*/ } }],
});
this.logger.verbose('instance files deleted: ' + name);
});
@ -265,12 +243,7 @@ export class WAMonitoringService {
public async loadInstance() {
this.logger.verbose('load instances');
const set = async (name: string) => {
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
instance.instanceName = name;
this.logger.verbose('instance loaded: ' + name);
@ -300,9 +273,7 @@ export class WAMonitoringService {
const collections: any[] = await this.dbInstance.collections();
if (collections.length > 0) {
this.logger.verbose('reading collections and setting instances');
collections.forEach(
async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')),
);
collections.forEach(async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')));
} else {
this.logger.verbose('no collections found');
}

View File

@ -18,9 +18,7 @@ export class SettingsService {
public async find(instance: InstanceDto): Promise<SettingsDto> {
try {
this.logger.verbose('find settings: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[
instance.instanceName
].findSettings();
const result = await this.waMonitor.waInstances[instance.instanceName].findSettings();
if (Object.keys(result).length === 0) {
throw new Error('Settings not found');

View File

@ -18,9 +18,7 @@ export class WebhookService {
public async find(instance: InstanceDto): Promise<WebhookDto> {
try {
this.logger.verbose('find webhook: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[
instance.instanceName
].findWebhook();
const result = await this.waMonitor.waInstances[instance.instanceName].findWebhook();
if (Object.keys(result).length === 0) {
throw new Error('Webhook not found');

View File

@ -66,11 +66,7 @@ import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, ROOT_DIR } from '../../config/path.config';
import { dbserver } from '../../db/db.connect';
import { RedisCache } from '../../db/redis.client';
import {
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from '../../exceptions';
import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../exceptions';
import { useMultiFileAuthStateDb } from '../../utils/use-multi-file-auth-state-db';
import { useMultiFileAuthStateRedisDb } from '../../utils/use-multi-file-auth-state-redis-db';
import {
@ -202,10 +198,7 @@ export class WAStartupService {
this.logger.verbose('Database enabled, trying to get from database');
const collection = dbserver
.getClient()
.db(
this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME +
'-instances',
)
.db(this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME + '-instances')
.collection(this.instanceName);
const data = await collection.findOne({ _id: 'creds' });
if (data) {
@ -398,8 +391,7 @@ export class WAStartupService {
const we = event.replace(/[.-]/gm, '_').toUpperCase();
const transformedWe = we.replace(/_/gm, '-').toLowerCase();
const expose =
this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
const expose = this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
const tokenStore = await this.repository.auth.find(this.instanceName);
const instanceApikey = tokenStore?.apikey || 'Apikey not found';
@ -537,11 +529,7 @@ export class WAStartupService {
}
}
private async connectionUpdate({
qr,
connection,
lastDisconnect,
}: Partial<ConnectionState>) {
private async connectionUpdate({ qr, connection, lastDisconnect }: Partial<ConnectionState>) {
this.logger.verbose('Connection update');
if (qr) {
this.logger.verbose('QR code found');
@ -609,9 +597,7 @@ export class WAStartupService {
console.log(this.phoneNumber);
if (this.phoneNumber) {
await delay(2000);
this.instance.qrcode.pairingCode = await this.client.requestPairingCode(
this.phoneNumber,
);
this.instance.qrcode.pairingCode = await this.client.requestPairingCode(this.phoneNumber);
} else {
this.instance.qrcode.pairingCode = null;
}
@ -676,8 +662,7 @@ export class WAStartupService {
if (connection === 'close') {
this.logger.verbose('Connection closed');
const shouldReconnect =
(lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) {
this.logger.verbose('Reconnecting to whatsapp');
await this.connectToWhatsapp();
@ -711,9 +696,7 @@ export class WAStartupService {
if (connection === 'open') {
this.logger.verbose('Connection opened');
this.instance.wuid = this.client.user.id.replace(/:\d+/, '');
this.instance.profilePictureUrl = (
await this.profilePicture(this.instance.wuid)
).profilePictureUrl;
this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl;
this.logger.info(
`
@ -746,8 +729,7 @@ export class WAStartupService {
}
if (webMessageInfo[0].message?.pollCreationMessage) {
this.logger.verbose('Returning poll message');
const messageSecretBase64 =
webMessageInfo[0].message?.messageContextInfo?.messageSecret;
const messageSecretBase64 = webMessageInfo[0].message?.messageContextInfo?.messageSecret;
if (typeof messageSecretBase64 === 'string') {
const messageSecret = Buffer.from(messageSecretBase64, 'base64');
@ -841,10 +823,7 @@ export class WAStartupService {
const socketConfig: UserFacingSocketConfig = {
auth: {
creds: this.instance.authState.state.creds,
keys: makeCacheableSignalKeyStore(
this.instance.authState.state.keys,
P({ level: 'error' }),
),
keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' })),
},
logger: P({ level: this.logBaileys }),
printQRInTerminal: false,
@ -855,18 +834,13 @@ export class WAStartupService {
defaultQueryTimeoutMs: undefined,
emitOwnEvents: false,
msgRetryCounterCache: this.msgRetryCounterCache,
getMessage: async (key) =>
(await this.getMessage(key)) as Promise<proto.IMessage>,
getMessage: async (key) => (await this.getMessage(key)) as Promise<proto.IMessage>,
generateHighQualityLinkPreview: true,
syncFullHistory: true,
userDevicesCache: this.userDevicesCache,
transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 },
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(
message.buttonsMessage ||
message.listMessage ||
message.templateMessage
);
const requiresPatch = !!(message.buttonsMessage || message.listMessage || message.templateMessage);
if (requiresPatch) {
message = {
viewOnceMessageV2: {
@ -929,11 +903,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CHATS_UPSERT, chatsRaw);
this.logger.verbose('Inserting chats in database');
await this.repository.chat.insert(
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
await this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
},
'chats.update': async (
@ -998,11 +968,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
this.logger.verbose('Inserting contacts in database');
await this.repository.contact.insert(
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.insert(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
},
'contacts.update': async (contacts: Partial<Contact>[], database: Database) => {
@ -1023,11 +989,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw);
this.logger.verbose('Updating contacts in database');
await this.repository.contact.update(
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
},
};
@ -1060,11 +1022,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CHATS_SET, chatsRaw);
this.logger.verbose('Inserting chats in database');
await this.repository.chat.insert(
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
await this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
}
const messagesRaw: MessageRaw[] = [];
@ -1075,11 +1033,7 @@ export class WAStartupService {
if (!m.message) {
continue;
}
if (
messagesRepository.find(
(mr) => mr.owner === this.instance.name && mr.key.id === m.key.id,
)
) {
if (messagesRepository.find((mr) => mr.owner === this.instance.name && mr.key.id === m.key.id)) {
continue;
}
@ -1160,11 +1114,7 @@ export class WAStartupService {
}
this.logger.verbose('Inserting message in database');
await this.repository.message.insert(
[messageRaw],
this.instance.name,
database.SAVE_DATA.NEW_MESSAGE,
);
await this.repository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
this.logger.verbose('Verifying contact from message');
const contact = await this.repository.contact.find({
@ -1174,8 +1124,7 @@ export class WAStartupService {
const contactRaw: ContactRaw = {
id: received.key.remoteJid,
pushName: received.pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid))
.profilePictureUrl,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
owner: this.instance.name,
};
@ -1189,8 +1138,7 @@ export class WAStartupService {
const contactRaw: ContactRaw = {
id: received.key.remoteJid,
pushName: contact[0].pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid))
.profilePictureUrl,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
owner: this.instance.name,
};
@ -1206,11 +1154,7 @@ export class WAStartupService {
}
this.logger.verbose('Updating contact in database');
await this.repository.contact.update(
[contactRaw],
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
return;
}
@ -1220,18 +1164,10 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
this.logger.verbose('Inserting contact in database');
await this.repository.contact.insert(
[contactRaw],
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
},
'messages.update': async (
args: WAMessageUpdate[],
database: Database,
settings: SettingsRaw,
) => {
'messages.update': async (args: WAMessageUpdate[], database: Database, settings: SettingsRaw) => {
this.logger.verbose('Event received: messages.update');
const status: Record<number, wa.StatusMessage> = {
0: 'ERROR',
@ -1622,11 +1558,7 @@ export class WAStartupService {
}
}
private async sendMessageWithTyping<T = proto.IMessage>(
number: string,
message: T,
options?: Options,
) {
private async sendMessageWithTyping<T = proto.IMessage>(number: string, message: T, options?: Options) {
this.logger.verbose('Sending message with typing');
const numberWA = await this.whatsappNumber({ numbers: [number] });
@ -1646,9 +1578,7 @@ export class WAStartupService {
this.logger.verbose('Subscribing to presence');
await this.client.sendPresenceUpdate(options?.presence ?? 'composing', sender);
this.logger.verbose(
'Sending presence update: ' + options?.presence ?? 'composing',
);
this.logger.verbose('Sending presence update: ' + options?.presence ?? 'composing');
await delay(options.delay);
this.logger.verbose('Set delay: ' + options.delay);
@ -1664,9 +1594,7 @@ export class WAStartupService {
if (options?.quoted) {
const m = options?.quoted;
const msg = m?.message
? m
: ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
if (!msg) {
throw 'Message not found';
@ -1688,10 +1616,7 @@ export class WAStartupService {
if (options?.mentions) {
this.logger.verbose('Mentions defined');
if (
!Array.isArray(options.mentions.mentioned) &&
!options.mentions.everyOne
) {
if (!Array.isArray(options.mentions.mentioned) && !options.mentions.everyOne) {
throw new BadRequestException('Mentions must be an array');
}
@ -1874,9 +1799,7 @@ export class WAStartupService {
}
this.logger.verbose('Getting contacts with push name');
status.statusJidList = contacts
.filter((contact) => contact.pushName)
.map((contact) => contact.id);
status.statusJidList = contacts.filter((contact) => contact.pushName).map((contact) => contact.id);
this.logger.verbose(status.statusJidList);
}
@ -1993,9 +1916,7 @@ export class WAStartupService {
this.logger.verbose('Media type: ' + mediaType);
if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) {
this.logger.verbose(
'If media type is document and file name is not defined then',
);
this.logger.verbose('If media type is document and file name is not defined then');
const regex = new RegExp(/.*\/(.+?)\./);
const arrayMatch = regex.exec(mediaMessage.media);
mediaMessage.fileName = arrayMatch[1];
@ -2108,11 +2029,7 @@ export class WAStartupService {
this.logger.verbose('Sending media message');
const generate = await this.prepareMediaMessage(data.mediaMessage);
return await this.sendMessageWithTyping(
data.number,
{ ...generate.message },
data?.options,
);
return await this.sendMessageWithTyping(data.number, { ...generate.message }, data?.options);
}
private async processAudio(audio: string, number: string) {
@ -2234,10 +2151,7 @@ export class WAStartupService {
};
if (!arrayUnique(btnItems.text) || !arrayUnique(btnItems.ids)) {
throw new BadRequestException(
'Button texts cannot be repeated',
'Button IDs cannot be repeated.',
);
throw new BadRequestException('Button texts cannot be repeated', 'Button IDs cannot be repeated.');
}
return await this.sendMessageWithTyping(
@ -2304,11 +2218,7 @@ export class WAStartupService {
const vcard = (contact: ContactMessage) => {
this.logger.verbose('Creating vcard');
let result =
'BEGIN:VCARD\n' +
'VERSION:3.0\n' +
`N:${contact.fullName}\n` +
`FN:${contact.fullName}\n`;
let result = 'BEGIN:VCARD\n' + 'VERSION:3.0\n' + `N:${contact.fullName}\n` + `FN:${contact.fullName}\n`;
if (contact.organization) {
this.logger.verbose('Organization defined');
@ -2331,9 +2241,7 @@ export class WAStartupService {
}
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');
return result;
@ -2423,8 +2331,7 @@ export class WAStartupService {
public async archiveChat(data: ArchiveChatDto) {
this.logger.verbose('Archiving chat');
try {
data.lastMessage.messageTimestamp =
data.lastMessage?.messageTimestamp ?? Date.now();
data.lastMessage.messageTimestamp = data.lastMessage?.messageTimestamp ?? Date.now();
await this.client.chatModify(
{
archive: data.archive,
@ -2440,10 +2347,7 @@ export class WAStartupService {
} catch (error) {
throw new InternalServerErrorException({
archived: false,
message: [
'An error occurred while archiving the chat. Open a calling.',
error.toString(),
],
message: ['An error occurred while archiving the chat. Open a calling.', error.toString()],
});
}
}
@ -2453,10 +2357,7 @@ export class WAStartupService {
try {
return await this.client.sendMessage(del.remoteJid, { delete: del });
} catch (error) {
throw new InternalServerErrorException(
'Error while deleting message for everyone',
error?.toString(),
);
throw new InternalServerErrorException('Error while deleting message for everyone', error?.toString());
}
}
@ -2466,9 +2367,7 @@ export class WAStartupService {
const m = data?.message;
const convertToMp4 = data?.convertToMp4 ?? false;
const msg = m?.message
? m
: ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
if (!msg) {
throw 'Message not found';
@ -2659,10 +2558,7 @@ export class WAStartupService {
},
};
} catch (error) {
throw new InternalServerErrorException(
'Error updating privacy settings',
error.toString(),
);
throw new InternalServerErrorException('Error updating privacy settings', error.toString());
}
}
@ -2690,10 +2586,7 @@ export class WAStartupService {
...profile,
};
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile name',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile name', error.toString());
}
}
@ -2704,10 +2597,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile name',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile name', error.toString());
}
}
@ -2718,10 +2608,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile status',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile status', error.toString());
}
}
@ -2750,10 +2637,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile picture',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile picture', error.toString());
}
}
@ -2764,10 +2648,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error removing profile picture',
error.toString(),
);
throw new InternalServerErrorException('Error removing profile picture', error.toString());
}
}
@ -2819,10 +2700,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error update group picture',
error.toString(),
);
throw new InternalServerErrorException('Error update group picture', error.toString());
}
}
@ -2833,10 +2711,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating group subject',
error.toString(),
);
throw new InternalServerErrorException('Error updating group subject', error.toString());
}
}
@ -2847,10 +2722,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating group description',
error.toString(),
);
throw new InternalServerErrorException('Error updating group description', error.toString());
}
}
@ -2986,10 +2858,7 @@ export class WAStartupService {
public async updateGSetting(update: GroupUpdateSettingDto) {
this.logger.verbose('Updating setting for group: ' + update.groupJid);
try {
const updateSetting = await this.client.groupSettingUpdate(
update.groupJid,
update.action,
);
const updateSetting = await this.client.groupSettingUpdate(update.groupJid, update.action);
return { updateSetting: updateSetting };
} catch (error) {
throw new BadRequestException('Error updating setting', error.toString());
@ -2999,10 +2868,7 @@ export class WAStartupService {
public async toggleEphemeral(update: GroupToggleEphemeralDto) {
this.logger.verbose('Toggling ephemeral for group: ' + update.groupJid);
try {
const toggleEphemeral = await this.client.groupToggleEphemeral(
update.groupJid,
update.expiration,
);
const toggleEphemeral = await this.client.groupToggleEphemeral(update.groupJid, update.expiration);
return { success: true };
} catch (error) {
throw new BadRequestException('Error updating setting', error.toString());

View File

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

View File

@ -66,12 +66,7 @@ export const repository = new RepositoryBroker(
export const cache = new RedisCache();
export const waMonitor = new WAMonitoringService(
eventEmitter,
configService,
repository,
cache,
);
export const waMonitor = new WAMonitoringService(eventEmitter, configService, repository, cache);
const authService = new AuthService(configService, waMonitor, repository);