Skip to content

Commit c24812b

Browse files
committed
Insert satinize message to save DB
1 parent e2a5fbf commit c24812b

File tree

1 file changed

+45
-18
lines changed

1 file changed

+45
-18
lines changed

src/infra/baileys/services.ts

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ export default class Instance{
6666
const browser: WABrowserDescription = [UserConfig.sessionClient, UserConfig.sessionName, release()];
6767
const agents = await genProxy(UserConfig.proxyUrl);
6868

69-
// Criar Promise para aguardar o QR code
7069
this.qrCodePromise = new Promise((resolve) => {
7170
this.qrCodeResolver = resolve;
7271
});
@@ -93,13 +92,13 @@ export default class Instance{
9392
qrTimeout: UserConfig.qrCodeTimeout * 1000
9493
});
9594
}catch(err){
96-
console.error(`[${this.owner}/${this.instanceName}] Erro ao criar socket`, err);
95+
console.error(`[${this.owner}/${this.instanceName}] Error creating socket`, err);
9796
await this.reconnectWithBackoff();
9897
throw err;
9998
}
10099

101100
this.sock = sock;
102-
this.attachSocketErrorHandlers(); // novo: listeners específicos
101+
this.attachSocketErrorHandlers();
103102

104103
this.key = `${this.owner}_${this.instanceName}`;
105104

@@ -167,27 +166,24 @@ export default class Instance{
167166
}
168167

169168
private attachSocketErrorHandlers(){
170-
// Listener de erro no websocket interno
171169
try{
172170
this.sock?.ws?.on?.('error', (err: any) => this.handleSocketError(err));
173171
this.sock?.ws?.on?.('close', () => {
174-
// fechamento inesperado sem gerar connection.update
175172
if(this.instance?.connectionStatus === 'ONLINE'){
176-
console.warn(`[${this.owner}/${this.instanceName}] ws fechado inesperadamente`);
173+
console.warn(`[${this.owner}/${this.instanceName}] ws closed unexpectedly`);
177174
this.handleSocketError(new Error('ws closed'));
178175
}
179176
});
180177
}catch(e){
181-
console.warn(`[${this.owner}/${this.instanceName}] Falha ao registrar handlers ws`, e);
178+
console.warn(`[${this.owner}/${this.instanceName}] Failed to register ws handlers`, e);
182179
}
183180

184-
// Se agentes proxy existirem podemos tentar ouvir eventos
185181
try{
186182
const anySock: any = this.sock;
187183
anySock?.options?.agent?.on?.('error', (err: any) => this.handleSocketError(err));
188184
anySock?.options?.fetchAgent?.on?.('error', (err: any) => this.handleSocketError(err));
189185
}catch(e){
190-
// silencioso
186+
console.warn(`[${this.owner}/${this.instanceName}] Failed to register agents handlers`, e);
191187
}
192188
}
193189

@@ -196,7 +192,7 @@ export default class Instance{
196192
const msg = String(err?.message || '');
197193
const code = err?.code;
198194
const isUndici = code === 'UND_ERR_SOCKET' || /terminated/i.test(msg) || /other side closed/i.test(msg);
199-
console.error(`[${this.owner}/${this.instanceName}] Socket/Fetch error capturado`, { code, msg });
195+
console.error(`[${this.owner}/${this.instanceName}] Socket/Fetch error captured`, { code, msg });
200196
if(isUndici){
201197
this.reconnectWithBackoff();
202198
}
@@ -205,36 +201,35 @@ export default class Instance{
205201
private async reconnectWithBackoff(){
206202
if(this.instance?.connectionStatus === 'REMOVED') return;
207203
if(this.reconnectAttempts >= this.maxReconnectAttempts){
208-
console.error(`[${this.owner}/${this.instanceName}] Limite de reconexões atingido`);
204+
console.error(`[${this.owner}/${this.instanceName}] Reconnection limit reached`);
209205
return;
210206
}
211207
const wait = Math.min(30000, 1000 * 2 ** this.reconnectAttempts);
212208
this.reconnectAttempts++;
213-
console.log(`[${this.owner}/${this.instanceName}] Tentando reconectar em ${wait}ms (tentativa ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
209+
console.log(`[${this.owner}/${this.instanceName}] Trying to reconnect in ${wait}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
214210
await delay(wait);
215211
try{
216212
await this.create({ owner: this.owner, instanceName: this.instanceName, phoneNumber: this.phoneNumber });
217213
}catch(e){
218-
console.error(`[${this.owner}/${this.instanceName}] Falha na reconexão`, e);
214+
console.error(`[${this.owner}/${this.instanceName}] Reconnection failed`, e);
219215
}
220216
}
221217

222218
private registerGlobalHandlers(){
223-
// Evita derrubar processo por erro não tratado de stream/undici
224219
if(!(global as any).__zap_global_error_wrapped){
225220
(global as any).__zap_global_error_wrapped = true;
226221

227222
process.on('uncaughtException', (err) => {
228223
if(/terminated/i.test(String(err?.message))){
229-
console.error('UncaughtException (terminated) capturado. Processo preservado.');
224+
console.error('UncaughtException (terminated) captured. Process preserved.');
230225
}else{
231226
console.error('UncaughtException', err);
232227
}
233228
});
234229

235230
process.on('unhandledRejection', (reason: any) => {
236231
if(/terminated/i.test(String(reason?.message))){
237-
console.error('UnhandledRejection (terminated) capturado.');
232+
console.error('UnhandledRejection (terminated) captured. Process preserved.');
238233
}else{
239234
console.error('UnhandledRejection', reason);
240235
}
@@ -398,7 +393,8 @@ export default class Instance{
398393
});
399394
}
400395

401-
await PrismaConnection.saveManyMessages(`${this.instance.owner}_${this.instance.instanceName}`, messages);
396+
const sanitized = messages.map(m => this.sanitizeWAMessage(m));
397+
await PrismaConnection.saveManyMessages(`${this.instance.owner}_${this.instance.instanceName}`, sanitized);
402398
trySendWebhook("messages.set", this.instance, rawMessages);
403399
}
404400

@@ -470,7 +466,8 @@ export default class Instance{
470466
});
471467
}
472468

473-
await PrismaConnection.saveManyMessages(`${this.instance.owner}_${this.instance.instanceName}`, messages.messages);
469+
const sanitized = messages.messages.map(m => this.sanitizeWAMessage(m));
470+
await PrismaConnection.saveManyMessages(`${this.instance.owner}_${this.instance.instanceName}`, sanitized);
474471
await trySendWebhook("messages.upsert", this.instance, rawMessages);
475472

476473
});
@@ -643,6 +640,36 @@ export default class Instance{
643640

644641
}
645642

643+
private deepSanitize(value: any): any {
644+
if (value === null || value === undefined) return value;
645+
if (typeof value === 'bigint') return Number(value);
646+
if (typeof value === 'function') return undefined;
647+
if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');
648+
if (Array.isArray(value)) {
649+
return value.map(v => this.deepSanitize(v)).filter(v => v !== undefined);
650+
}
651+
if (typeof value === 'object') {
652+
if ('low' in value && 'high' in value &&
653+
typeof (value as any).low === 'number' &&
654+
typeof (value as any).high === 'number') {
655+
const low = (value as any).low >>> 0;
656+
const high = (value as any).high >>> 0;
657+
return high * 2 ** 32 + low;
658+
}
659+
const out: any = {};
660+
for (const [k, v] of Object.entries(value)) {
661+
const sv = this.deepSanitize(v);
662+
if (sv !== undefined) out[k] = sv;
663+
}
664+
return out;
665+
}
666+
return value;
667+
}
668+
669+
private sanitizeWAMessage(msg: any): any {
670+
return this.deepSanitize(msg);
671+
}
672+
646673
}
647674

648675

0 commit comments

Comments
 (0)