Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Hotfix] - Melhorias no Websocket #1337

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
c987845
fix(websocket): adequando todos os nomes de eventos
fabioselau077 Jun 29, 2023
726d7f7
fix(websocket): limpando código
fabioselau077 Jun 29, 2023
6436440
refactor(websocket): alterando send para o passado
fabioselau077 Jun 29, 2023
f4b3b2d
refactor(websocket): só enviando websocket se tem ouvinte no canal
fabioselau077 Jun 29, 2023
5bacca6
fix(websocket): Validando a session
fabioselau077 Jun 30, 2023
aafc14e
fix(bucketAlreadyExists): verificando se existe o defaultBucketName
fabioselau077 Jul 10, 2023
bc3ac07
fix(readme): atualizando o readme
fabioselau077 Jul 10, 2023
d3259aa
fix(merge): resolve conflict and merge with master
fabioselau077 Jul 10, 2023
752a93b
fix(config): nome do arquivo com id da mensagem
fabioselau077 Aug 22, 2023
fbeead3
Merge pull request #1 from fabioselau077/hotfix/name_file_and_bucket_s3
fabioselau077 Aug 22, 2023
cbf356f
Merge pull request #2 from fabioselau077/hotfix/melhorias_websocket
fabioselau077 Aug 22, 2023
bd126a3
Merge pull request #3 from fabioselau077/hotfix/validando_antes_verif…
fabioselau077 Aug 22, 2023
0b40bea
comment acl
fabioselau077 Aug 24, 2023
88ca54d
Merge pull request #4 from fabioselau077/hotfix/comment_acl_s3
fabioselau077 Aug 24, 2023
6bfc1bc
comment acl
fabioselau077 Aug 24, 2023
5aeedeb
fix: Added scurity session for sockets
icleitoncosta Aug 27, 2023
aa08c46
fix: improovment sockets events
icleitoncosta Aug 27, 2023
f5a03ac
Merge branch 'wppconnect-team:main' into main
fabioselau077 Sep 25, 2023
fea536f
Revert "Hotfix/melhorias websocket"
fabioselau077 Sep 25, 2023
26bef05
Merge pull request #5 from fabioselau077/revert-2-hotfix/melhorias_we…
fabioselau077 Sep 25, 2023
f85b393
fix(websocket): merge com a master
fabioselau077 Sep 25, 2023
7ad4b70
fix(functions): revertendo código
fabioselau077 Sep 25, 2023
53bdc07
fix(auth): pegando a posicao correta do token
fabioselau077 Sep 25, 2023
1ea9b18
fix(utils): add status find
fabioselau077 Sep 25, 2023
bee9bdd
Merge branch 'main' into hotfix/melhorias_websocket
joaosouz4dev Jun 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/controller/messageController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import { Request, Response } from 'express';

import { unlinkAsync } from '../util/functions';
import { callSocket, unlinkAsync } from '../util/functions';

function returnError(req: Request, res: Response, error: any) {
req.logger.error(error);
Expand Down Expand Up @@ -99,7 +99,11 @@ export async function sendMessage(req: Request, res: Response) {

if (results.length === 0)
return res.status(400).json('Error sending message');
req.io.emit('mensagem-enviada', results);

/**
* Deprecated event 'mensagem-enviada'
*/
callSocket(req, ['mensagem-enviada', 'sent-message'], results);
returnSucess(res, results);
} catch (error) {
returnError(req, res, error);
Expand Down Expand Up @@ -856,7 +860,13 @@ export async function replyMessage(req: Request, res: Response) {

if (results.length === 0)
return res.status(400).json('Error sending message');
req.io.emit('mensagem-enviada', { message: message, to: phone });
/**
* Deprecated event 'mensagem-enviada'
*/
callSocket(req, ['mensagem-enviada', 'sent-message'], {
message: message,
to: phone,
});
returnSucess(res, results);
} catch (error) {
returnError(req, res, error);
Expand Down
7 changes: 4 additions & 3 deletions src/controller/sessionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { Logger } from 'winston';
import { version } from '../../package.json';
import config from '../config';
import CreateSessionUtil from '../util/createSessionUtil';
import { callWebHook, contactToArray } from '../util/functions';
import { callSocket, callWebHook, contactToArray } from '../util/functions';
import getAllTokens from '../util/getAllTokens';
import { clientsArray, deleteSessionOnArray } from '../util/sessionUtil';

Expand Down Expand Up @@ -243,7 +243,8 @@ export async function closeSession(req: Request, res: Response) {
(clientsArray as any)[session] = { status: null };

await req.client.close();
req.io.emit('whatsapp-status', false);

callSocket(req, 'whatsapp-status', false);
callWebHook(req.client, req, 'closesession', {
message: `Session: ${session} disconnected`,
connected: false,
Expand Down Expand Up @@ -300,7 +301,7 @@ export async function logOutSession(req: Request, res: Response) {
});
}

req.io.emit('whatsapp-status', false);
callSocket(req, 'whatsapp-status', false);
callWebHook(req.client, req, 'logoutsession', {
message: `Session: ${session} logged out`,
connected: false,
Expand Down
12 changes: 8 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { Logger } from 'winston';
import { version } from '../package.json';
import config from './config';
import { convert } from './mapper/index';
import { verifyTokenSocket } from './middleware/auth';
import routes from './routes';
import { ServerOptions } from './types/ServerOptions';
import {
Expand Down Expand Up @@ -74,7 +75,7 @@ export function initServer(serverOptions: Partial<ServerOptions>): {
app.use((req: any, res: any, next: NextFunction) => {
req.serverOptions = serverOptions;
req.logger = logger;
req.io = io as any;
req.io = io;

const oldSend = res.send;

Expand Down Expand Up @@ -107,12 +108,15 @@ export function initServer(serverOptions: Partial<ServerOptions>): {
origin: '*',
},
});
io.use(verifyTokenSocket);

io.on('connection', (sock) => {
logger.info(`ID: ${sock.id} entrou`);

sock.on('disconnect', () => {
logger.info(`ID: ${sock.id} saiu`);
logger.info(
`ID: ${sock.id} has disconnected. Session: ${
sock.handshake.auth?.session || 'Unknown'
}`
);
});
});

Expand Down
50 changes: 50 additions & 0 deletions src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
*/
import bcrypt from 'bcrypt';
import { NextFunction, Request, Response } from 'express';
import { Socket } from 'socket.io';

import { logger } from '..';
import config from '../config';
import { clientsArray } from '../util/sessionUtil';

function formatSession(session: string) {
Expand Down Expand Up @@ -89,4 +92,51 @@ const verifyToken = (req: Request, res: Response, next: NextFunction) => {
}
};

export const verifyTokenSocket = (socket: Socket, next: any) => {
const secureToken = config.secretKey;
const { token, session } = socket.handshake.auth;
if (!session || !token)
return next(new Error('Session or token not informed'));

try {
let tokenDecrypt = '';
let sessionDecrypt = '';

try {
sessionDecrypt = session.split(':')[0];
tokenDecrypt = token.split(':')[1].replace(/_/g, '/').replace(/-/g, '+');
} catch (error) {
try {
if (token && token !== '' && token.split(' ').length > 0) {
const token_value = token.split(' ')[0];
if (token_value)
tokenDecrypt = token_value.replace(/_/g, '/').replace(/-/g, '+');
else tokenDecrypt = token;
} else {
tokenDecrypt = token;
}
} catch (e) {
logger.error(e);
return next(new Error('Check that a Session and Token are correct'));
}
}
bcrypt.compare(
sessionDecrypt + secureToken,
tokenDecrypt,
function (err, result) {
if (result) {
socket.join(session);
logger.info(`ID: ${socket.id} joined the channel ${session}`);
return next();
} else {
return next(new Error('Check that a Session and Token are correct'));
}
}
);
} catch (error) {
logger.error(error);
return next(new Error('Check that a Session and Token are correct'));
}
};

export default verifyToken;
22 changes: 15 additions & 7 deletions src/util/createSessionUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import { download } from '../controller/sessionController';
import { WhatsAppServer } from '../types/WhatsAppServer';
import chatWootClient from './chatWootClient';
import { autoDownload, callWebHook, startHelper } from './functions';
import { autoDownload, callSocket, callWebHook, startHelper } from './functions';

Check failure on line 22 in src/util/createSessionUtil.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `·autoDownload,·callSocket,·callWebHook,·startHelper·` with `⏎··autoDownload,⏎··callSocket,⏎··callWebHook,⏎··startHelper,⏎`
import { clientsArray, eventEmitter } from './sessionUtil';
import Factory from './tokenStore/factory';

Expand Down Expand Up @@ -101,6 +101,10 @@
client.close();
clientsArray[session] = undefined;
}
callSocket(req, 'status-find', {
status: statusFind,
session: client.session,
});
callWebHook(client, req, 'status-find', {
status: statusFind,
session: client.session,
Expand Down Expand Up @@ -159,7 +163,7 @@
qrCode = qrCode.replace('data:image/png;base64,', '');
const imageBuffer = Buffer.from(qrCode, 'base64');

req.io.emit('qrCode', {
callSocket(req, ['qrCode', 'qr-code'], {
data: 'data:image/png;base64,' + imageBuffer.toString('base64'),
session: client.session,
});
Expand Down Expand Up @@ -259,30 +263,34 @@

async listenAcks(client: WhatsAppServer, req: Request) {
await client.onAck(async (ack) => {
req.io.emit('onack', ack);
callSocket(req, ['onack', 'on-ack'], ack);
callWebHook(client, req, 'onack', ack);
});
}

async onPresenceChanged(client: WhatsAppServer, req: Request) {
await client.onPresenceChanged(async (presenceChangedEvent) => {
req.io.emit('onpresencechanged', presenceChangedEvent);
callSocket(
req,
['onpresencechanged', 'on-presence-changed'],
presenceChangedEvent
);
callWebHook(client, req, 'onpresencechanged', presenceChangedEvent);
});
}

async onReactionMessage(client: WhatsAppServer, req: Request) {
await client.isConnected();
await client.onReactionMessage(async (reaction: any) => {
req.io.emit('onreactionmessage', reaction);
callSocket(req, ['onreactionmessage', 'on-reaction-message'], reaction);
callWebHook(client, req, 'onreactionmessage', reaction);
});
}

async onRevokedMessage(client: WhatsAppServer, req: Request) {
await client.isConnected();
await client.onRevokedMessage(async (response: any) => {
req.io.emit('onrevokedmessage', response);
callSocket(req, ['onrevokedmessage', 'on-revoked-message'], response);
callWebHook(client, req, 'onrevokedmessage', response);
});
}
Expand All @@ -296,7 +304,7 @@
async onLabelUpdated(client: WhatsAppServer, req: Request) {
await client.isConnected();
await client.onUpdateLabel(async (response: any) => {
req.io.emit('onupdatelabel', response);
callSocket(req, ['onupdatelabel', 'on-update-label'], response);
callWebHook(client, req, 'onupdatelabel', response);
});
}
Expand Down
13 changes: 13 additions & 0 deletions src/util/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,19 @@ export function groupNameToArray(group: any) {
return localArr;
}

export function callSocket(req: any, event: string | string[], data: any) {
event = Array.isArray(event) ? event : [event];
const session = req?.session || data?.session;

const listeners = req.io?.sockets?.adapter?.rooms?.get(session)?.size || 0;

if (listeners == 0) return;
for (const evt of event) {
req.io.to(session).emit(evt, data);
}
return;
}

export async function callWebHook(
client: any,
req: Request,
Expand Down
Loading