forked from IgorKendyS/papi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1513 lines (1249 loc) · 57.8 KB
/
server.ts
File metadata and controls
1513 lines (1249 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ╔═══════════════════════════════════════════════════════════════╗
* ║ PASTORINI API ║
* ║ WhatsApp API powered by Baileys ║
* ║ © 2025 Pastorini ║
* ╚═══════════════════════════════════════════════════════════════╝
*/
import 'dotenv/config'
import express, { type Request, type Response, type NextFunction } from 'express'
import cors from 'cors'
import cookieParser from 'cookie-parser'
import path from 'path'
import fs from 'fs'
import crypto from 'crypto'
import os from 'os'
import instanceManager from './instanceManager'
import { generateCarouselMessage, generateListMessage, generateButtonMessage, prepareWAMessageMedia, type CarouselCard } from './lib/Utils/messages.js'
import * as qrcode from 'qrcode'
import { fileURLToPath } from 'url'
import licenseManager from './lib/License/licenseManager.js'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// ==================== PROTEÇÃO DE CRÉDITOS ====================
const PROTECTED_FOOTER = `<!-- Footer Fixo -->
<footer id="mainFooter" style="position: fixed; bottom: 0; left: 0; right: 0; text-align: center; padding: 12px 20px; background: rgba(10,10,10,0.95); backdrop-filter: blur(10px); border-top: 1px solid rgba(255,255,255,0.1); color: #888; font-size: 0.8rem; z-index: 100;">
<span id="footerCredits">© 2025 <a href="https://wa.me/5582988898565" target="_blank" style="color: #10b981; text-decoration: none;">Pastorini API</a> - Powered by Baileys</span>
</footer>`
const FOOTER_PROTECTION_SCRIPT = `
<script>
// Proteção de créditos do footer
(function() {
const fc = '© 2025 <a href="https://wa.me/5582988898565" target="_blank" style="color: #10b981; text-decoration: none;">Pastorini API</a> - Powered by Baileys';
const fe = document.getElementById('footerCredits');
const ff = document.getElementById('mainFooter');
function checkFooter() {
if (!fe || !ff || fe.innerHTML !== fc || ff.style.display === 'none' || ff.style.visibility === 'hidden' || ff.style.opacity === '0') {
if (ff) { ff.style.cssText = 'position:fixed;bottom:0;left:0;right:0;text-align:center;padding:12px 20px;background:rgba(10,10,10,0.95);backdrop-filter:blur(10px);border-top:1px solid rgba(255,255,255,0.1);color:#888;font-size:0.8rem;z-index:100;display:block;visibility:visible;opacity:1;'; }
if (fe) fe.innerHTML = fc;
else if (ff) ff.innerHTML = '<span id="footerCredits">' + fc + '</span>';
}
}
checkFooter();
setInterval(checkFooter, 2000);
new MutationObserver(checkFooter).observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
})();
</script>`
// Arquivos HTML protegidos
const PROTECTED_HTML_FILES = ['index.html', 'docs.html', 'api-tester.html', 'qr-client.html']
// Armazena hashes originais dos arquivos
const originalFileHashes: Map<string, string> = new Map()
/**
* Calcula hash MD5 de um conteúdo
*/
function calculateHash(content: string): string {
return crypto.createHash('md5').update(content).digest('hex')
}
/**
* Verifica se o arquivo HTML contém o footer de créditos
*/
function hasValidFooter(content: string): boolean {
return content.includes('id="mainFooter"') &&
content.includes('id="footerCredits"') &&
content.includes('Pastorini API') &&
content.includes('wa.me/5582988898565')
}
/**
* Injeta o footer de créditos no HTML se estiver faltando
*/
function injectFooterIfMissing(content: string): string {
if (hasValidFooter(content)) {
return content
}
console.log('[Credits] ⚠️ Footer de créditos removido - restaurando...')
// Injeta antes do </body>
let modified = content
// Remove footer existente se estiver corrompido
modified = modified.replace(/<footer[^>]*id="mainFooter"[^>]*>[\s\S]*?<\/footer>/gi, '')
// Injeta o footer correto antes do </body>
if (modified.includes('</body>')) {
modified = modified.replace('</body>', `${PROTECTED_FOOTER}\n</body>`)
}
// Verifica se tem o script de proteção
if (!modified.includes('Proteção de créditos do footer')) {
modified = modified.replace('</body>', `${FOOTER_PROTECTION_SCRIPT}\n</body>`)
}
return modified
}
/**
* Verifica e restaura arquivos HTML protegidos no startup
*/
function verifyAndRestoreProtectedFiles(): void {
const publicDir = path.join(__dirname, 'public')
console.log('[Credits] 🔒 Verificando integridade dos arquivos protegidos...')
for (const filename of PROTECTED_HTML_FILES) {
const filePath = path.join(publicDir, filename)
try {
if (!fs.existsSync(filePath)) {
console.log(`[Credits] ⚠️ Arquivo não encontrado: ${filename}`)
continue
}
let content = fs.readFileSync(filePath, 'utf-8')
const originalHash = calculateHash(content)
// Verifica se tem footer válido
if (!hasValidFooter(content)) {
console.log(`[Credits] ⚠️ Footer inválido em ${filename} - restaurando...`)
content = injectFooterIfMissing(content)
fs.writeFileSync(filePath, content, 'utf-8')
console.log(`[Credits] ✓ ${filename} restaurado com sucesso`)
} else {
console.log(`[Credits] ✓ ${filename} - OK`)
}
// Armazena hash para verificação posterior
originalFileHashes.set(filename, calculateHash(content))
} catch (error) {
console.error(`[Credits] ❌ Erro ao verificar ${filename}:`, error)
}
}
console.log('[Credits] 🔒 Verificação concluída')
}
/**
* Middleware para servir arquivos HTML com proteção de créditos
*/
function creditsProtectionMiddleware(req: Request, res: Response, next: NextFunction): void {
// Só processa arquivos HTML protegidos
const requestedFile = req.path === '/' ? 'index.html' : req.path.substring(1)
if (!PROTECTED_HTML_FILES.includes(requestedFile)) {
return next()
}
const filePath = path.join(__dirname, 'public', requestedFile)
try {
if (!fs.existsSync(filePath)) {
return next()
}
let content = fs.readFileSync(filePath, 'utf-8')
// Verifica e injeta footer se necessário
if (!hasValidFooter(content)) {
console.log(`[Credits] ⚠️ Footer removido detectado em ${requestedFile} - injetando...`)
content = injectFooterIfMissing(content)
// Salva o arquivo corrigido
fs.writeFileSync(filePath, content, 'utf-8')
}
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.send(content)
} catch (error) {
console.error(`[Credits] Erro ao servir ${requestedFile}:`, error)
next()
}
}
const app = express()
const PORT = 3000
// API Key for panel access (optional)
const PANEL_API_KEY = process.env.PANEL_API_KEY || ''
app.use(cors())
app.use(cookieParser())
app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ limit: '50mb', extended: true }))
// Panel API Key middleware - protects panel access (HTML pages)
const panelAuthMiddleware = (req: Request, res: Response, next: NextFunction) => {
// If no API key configured, allow access
if (!PANEL_API_KEY) {
return next()
}
// Allow API routes (they have their own auth middleware below)
if (req.path.startsWith('/api/')) {
return next()
}
// Allow static assets (css, js, images, fonts)
if (req.path.match(/\.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$/)) {
return next()
}
// Protected pages
const protectedPages = ['/', '/index.html', '/api-tester.html', '/docs.html']
if (!protectedPages.includes(req.path)) {
return next()
}
// Check for API key in multiple places:
// 1. Cookie (preferred - secure)
// 2. Query param: ?key=xxx
const cookieKey = req.cookies?.panelKey
const queryKey = req.query.key as string
// Valid key via cookie - allow access
if (cookieKey && cookieKey === PANEL_API_KEY) {
return next()
}
// If key provided via query param and is valid, set cookie and redirect to clean URL
if (queryKey && queryKey === PANEL_API_KEY) {
res.cookie('panelKey', queryKey, {
httpOnly: false, // Allow JS to read for API calls
secure: false, // Allow HTTP for development
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
})
// Store in session for API calls
return res.redirect(req.path)
}
// Invalid key provided via query
if (queryKey && queryKey !== PANEL_API_KEY) {
return res.status(401).send(`
<!DOCTYPE html>
<html>
<head><title>Acesso Negado</title></head>
<body style="font-family:Arial;background:#111;color:#fff;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;">
<div style="text-align:center;">
<h1 style="color:#ef4444;">❌ Chave Inválida</h1>
<p><a href="${req.path}" style="color:#10b981;">Tentar novamente</a></p>
</div>
</body>
</html>
`)
}
// No key - show login form
return res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Acesso ao Painel</title>
<style>
body { font-family: Arial, sans-serif; background: #111; color: #fff; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
.login-box { background: #1a1a1a; padding: 40px; border-radius: 12px; text-align: center; max-width: 400px; }
h1 { color: #10b981; margin-bottom: 20px; }
input { padding: 12px; width: 100%; border: 1px solid #333; border-radius: 8px; background: #222; color: #fff; margin-bottom: 15px; box-sizing: border-box; }
button { padding: 12px 30px; background: #10b981; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; width: 100%; }
button:hover { background: #059669; }
.hint { color: #666; font-size: 0.8rem; margin-top: 15px; }
</style>
</head>
<body>
<div class="login-box">
<h1>🔐 Pastorini API</h1>
<p style="color:#888;margin-bottom:20px;">Digite a chave de acesso ao painel</p>
<form onsubmit="event.preventDefault(); const k=document.getElementById('key').value; if(k) window.location.href='${req.path}?key='+encodeURIComponent(k);">
<input type="password" id="key" placeholder="API Key" autofocus><br>
<button type="submit">Entrar</button>
</form>
<p class="hint">A chave é definida na variável PANEL_API_KEY</p>
</div>
</body>
</html>
`)
}
// API Key middleware - protects API routes
const apiAuthMiddleware = (req: Request, res: Response, next: NextFunction) => {
// If no API key configured, allow access (development mode)
if (!PANEL_API_KEY) {
return next()
}
// Only protect /api/ routes
if (!req.path.startsWith('/api/')) {
return next()
}
// Public API routes that don't require authentication
const publicApiRoutes = [
'/api/stats', // Server stats (for monitoring)
'/api/license/status', // License status check
'/api/activate', // License activation
'/api/heartbeat', // License heartbeat
'/api/panel/auth', // Panel authentication (login)
'/api/panel/logout', // Panel logout
]
// Check if it's a public route
if (publicApiRoutes.some(route => req.path === route)) {
return next()
}
// Public status for QR client (check pattern /api/instances/:id/public-status)
if (req.path.match(/^\/api\/instances\/[^/]+\/public-status$/)) {
return next()
}
// Public QR for client (check pattern /api/instances/:id/qr and verify referer is qr-client)
if (req.path.match(/^\/api\/instances\/[^/]+\/qr$/) && req.headers.referer?.includes('qr-client.html')) {
return next()
}
// Check for API key in multiple places:
// 1. Header: x-api-key
// 2. Header: Authorization: Bearer <key>
// 3. Query param: ?key=xxx
const headerKey = req.headers['x-api-key'] as string
const authHeader = req.headers['authorization']
const bearerKey = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null
const queryKey = req.query.key as string
const providedKey = headerKey || bearerKey || queryKey
// Valid key - allow access
if (providedKey && providedKey === PANEL_API_KEY) {
return next()
}
// No key or invalid key - return 401
return res.status(401).json({
error: 'Unauthorized',
message: 'API key required. Provide via x-api-key header, Authorization: Bearer <key>, or ?key= query param'
})
}
app.use(panelAuthMiddleware)
app.use(apiAuthMiddleware)
// Middleware de proteção de créditos (antes do static)
app.use(creditsProtectionMiddleware)
// Servir arquivos estáticos
app.use(express.static(path.join(__dirname, 'public')))
// License check middleware - blocks API if license is invalid
const licenseMiddleware = (req: Request, res: Response, next: NextFunction) => {
// Allow public routes
const publicPaths = ['/api/license/status', '/api/instances/:id/public-status', '/api/stats']
const isPublicPath = publicPaths.some(p => req.path.includes(p.replace(':id', '')))
if (isPublicPath || !req.path.startsWith('/api/')) {
return next()
}
if (!licenseManager.isAllowed()) {
const status = licenseManager.getStatus()
return res.status(403).json({
error: 'License blocked',
status: status.status,
message: status.message
})
}
next()
}
app.use(licenseMiddleware)
// Panel authentication endpoint (POST to avoid key in URL)
app.post('/api/panel/auth', (req: Request, res: Response) => {
const { key } = req.body
if (!PANEL_API_KEY) {
return res.json({ success: true, message: 'No authentication required' })
}
if (key && key === PANEL_API_KEY) {
// Set secure cookie
res.cookie('panelKey', key, {
httpOnly: true,
secure: req.secure || req.headers['x-forwarded-proto'] === 'https',
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
})
return res.json({ success: true })
}
return res.status(401).json({ error: 'Invalid key' })
})
// Panel logout endpoint
app.post('/api/panel/logout', (req: Request, res: Response) => {
res.clearCookie('panelKey')
return res.json({ success: true })
})
/**
* Normaliza um número de telefone para o formato JID do WhatsApp
* Trata especialmente números brasileiros com o 9º dígito
*
* Regras para Brasil (DDI 55):
* - Celulares: 55 + DDD (2 dígitos) + 9 + número (8 dígitos) = 13 dígitos
* - Se o número tiver 13 dígitos e começar com 55, remove o 9 após o DDD
* - DDDs de SP (11-19) sempre precisam do 9
* - Outros DDDs (21-99) o 9 foi adicionado gradualmente
*
* @param phone Número de telefone (pode incluir @s.whatsapp.net ou não)
* @returns JID normalizado no formato numero@s.whatsapp.net
*/
function normalizeJid(phone: string): string {
if (!phone) return phone
// Se já é um JID de grupo, retorna como está
if (phone.includes('@g.us') || phone.includes('@broadcast') || phone.includes('@lid')) {
return phone
}
// Remove o sufixo @s.whatsapp.net se existir
let number = phone.replace('@s.whatsapp.net', '').replace('@c.us', '')
// Remove caracteres não numéricos (exceto +)
number = number.replace(/[^\d+]/g, '')
// Remove o + do início se existir
number = number.replace(/^\+/, '')
// Tratamento especial para números brasileiros
if (number.startsWith('55')) {
const withoutCountry = number.substring(2) // Remove o 55
// Verifica se é um número de celular brasileiro com 9º dígito
// Formato com 9: DDD (2) + 9 + número (8) = 11 dígitos após o 55
// Formato sem 9: DDD (2) + número (8) = 10 dígitos após o 55
if (withoutCountry.length === 11) {
const ddd = withoutCountry.substring(0, 2)
const ninthDigit = withoutCountry.substring(2, 3)
const restOfNumber = withoutCountry.substring(3)
// Se o terceiro dígito é 9 e o número tem 11 dígitos, pode ser o 9º dígito extra
// Verifica se o número após o 9 começa com 9, 8, 7 (típico de celulares)
if (ninthDigit === '9') {
const firstDigitAfterNine = restOfNumber.substring(0, 1)
// Se após remover o 9, o número começa com 9, 8 ou 7, é celular
// Remove o 9 extra para DDDs que não precisam
// DDDs de SP (11-19) geralmente precisam do 9
// Outros DDDs podem ou não precisar
// Estratégia: tentar primeiro sem o 9 extra para DDDs fora de SP
const dddNum = parseInt(ddd)
// Para DDDs fora de SP (20+), remove o 9 se presente
// Para DDDs de SP (11-19), mantém o 9
if (dddNum >= 20 && ['9', '8', '7'].includes(firstDigitAfterNine)) {
// Remove o 9º dígito para DDDs fora de SP
number = '55' + ddd + restOfNumber
console.log(`[JID] Número brasileiro normalizado (removido 9): ${phone} -> ${number}`)
}
}
}
// Se tem 10 dígitos após o 55, está no formato correto (sem 9 extra)
}
return `${number}@s.whatsapp.net`
}
/**
* Verifica se um número existe no WhatsApp e retorna o JID correto
* Útil para resolver problemas de 9º dígito e LID
*/
async function resolveJid(socket: any, phone: string): Promise<string> {
const normalizedJid = normalizeJid(phone)
console.log(`[JID] Iniciando resolução: ${phone} -> normalizado: ${normalizedJid}`)
try {
// Tenta verificar se o número existe
const numberOnly = normalizedJid.replace('@s.whatsapp.net', '')
console.log(`[JID] Verificando número: ${numberOnly}`)
const results = await socket.onWhatsApp(numberOnly)
console.log(`[JID] Resultado onWhatsApp:`, JSON.stringify(results, null, 2))
const [result] = results || []
if (result?.exists && result?.jid) {
console.log(`[JID] ✓ Número verificado: ${phone} -> ${result.jid}`)
// Verifica se é LID
if (result.jid.includes('@lid')) {
console.log(`[JID] ⚠ Número usa formato LID (novo formato Meta)`)
}
return result.jid
}
console.log(`[JID] Número não encontrado diretamente, tentando variações...`)
// Se não encontrou, tenta com/sem o 9
const number = numberOnly
if (number.startsWith('55') && number.length === 12) {
// Tenta adicionar o 9
const withNine = number.substring(0, 4) + '9' + number.substring(4)
console.log(`[JID] Tentando com 9: ${withNine}`)
const [resultWithNine] = await socket.onWhatsApp(withNine) || []
if (resultWithNine?.exists && resultWithNine?.jid) {
console.log(`[JID] ✓ Número encontrado com 9: ${phone} -> ${resultWithNine.jid}`)
return resultWithNine.jid
}
} else if (number.startsWith('55') && number.length === 13) {
// Tenta remover o 9
const withoutNine = number.substring(0, 4) + number.substring(5)
console.log(`[JID] Tentando sem 9: ${withoutNine}`)
const [resultWithoutNine] = await socket.onWhatsApp(withoutNine) || []
if (resultWithoutNine?.exists && resultWithoutNine?.jid) {
console.log(`[JID] ✓ Número encontrado sem 9: ${phone} -> ${resultWithoutNine.jid}`)
return resultWithoutNine.jid
}
}
console.log(`[JID] ✗ Número não encontrado em nenhuma variação`)
} catch (error) {
console.log(`[JID] ✗ Erro ao verificar número:`, error)
}
// Retorna o JID normalizado se não conseguiu verificar
console.log(`[JID] Usando JID normalizado (não verificado): ${normalizedJid}`)
return normalizedJid
}
// List instances
app.get('/api/instances', (req: Request, res: Response) => {
const instances = instanceManager.getAllInstances()
res.json(instances)
})
// Create instance
app.post('/api/instances', async (req: Request, res: Response) => {
const id = req.body.id as string
if (!id) return res.status(400).json({ error: 'ID is required' })
try {
const instance = await instanceManager.createInstance(id)
if (!instance) {
return res.status(500).json({ error: 'Failed to create instance' })
}
res.json({
id: instance.id,
status: instance.status
})
} catch (error) {
console.error(error)
res.status(500).json({ error: 'Failed to create instance' })
}
})
app.get('/api/instances/:id/qr', async (req: Request, res: Response) => {
const id = req.params.id
if (!id) return res.status(400).json({ error: 'ID is required' })
const instance = instanceManager.getInstance(id)
if (!instance) return res.status(404).json({ error: 'Instance not found' })
if (!instance.qr) return res.status(400).json({ error: 'QR not ready or already connected' })
try {
const qrImage = await qrcode.toDataURL(instance.qr)
res.json({ qrImage })
} catch (error) {
res.status(500).json({ error: 'Failed to generate QR image' })
}
})
// Delete instance
app.delete('/api/instances/:id', async (req: Request, res: Response) => {
const id = req.params.id
if (!id) return res.status(400).json({ error: 'ID is required' })
await instanceManager.deleteInstance(id)
res.json({ success: true })
})
// Send Carousel
app.post('/api/instances/:id/send-carousel', async (req: Request, res: Response) => {
const id = req.params.id
console.log(`[Carousel] Request received for instance: ${id}`);
if (!id) return res.status(400).json({ error: 'ID is required' })
const { jid, title, body, footer, cards: requestCards } = req.body
console.log(`[Carousel] Target JID: ${jid}`);
console.log(`[Carousel] Title: ${title}, Body: ${body}, Footer: ${footer}`);
const instance = instanceManager.getInstance(id)
if (!instance || !instance.socket) {
console.error(`[Carousel] Instance not found or not connected. Instance: ${!!instance}, Socket: ${!!instance?.socket}`);
return res.status(404).json({ error: 'Instance not found or not connected' })
}
try {
console.log('[Carousel] Generating message content...');
// Usar cards do request ou fallback para exemplo
const cards: CarouselCard[] = (requestCards && requestCards.length > 0) ? requestCards.map((card: any) => ({
header: {
title: card.title || 'Produto',
subtitle: card.footer || '',
imageUrl: card.imageUrl || card.header?.imageUrl
},
body: card.body || '',
footer: card.footer || '',
buttons: (card.buttons || []).map((btn: any) => {
// Converter formato simplificado para formato Baileys
if (btn.id && btn.title) {
return { displayText: btn.title, quickReplyButton: { id: btn.id } };
}
return btn;
})
})) : [
{
header: {
title: 'Oferta Especial',
subtitle: 'Aproveite agora',
imageUrl: 'https://www.w3schools.com/w3css/img_lights.jpg'
},
body: 'Melhores produtos com desconto!',
footer: 'Promoção válida até amanhã',
buttons: [
{ displayText: 'Ver Site', urlButton: { url: 'https://google.com' } },
{ displayText: 'Eu Quero', quickReplyButton: { id: 'want_it' } }
]
}
];
// Upload media for cards
for (const card of cards) {
if (card.header?.imageUrl) {
try {
console.log(`[Carousel] Uploading image for card: ${card.header.title}`);
const message = await prepareWAMessageMedia(
{ image: { url: card.header.imageUrl } },
{
upload: instance.socket.waUploadToServer,
logger: instance.socket.logger
}
);
card.header.imageMessage = message.imageMessage || undefined;
} catch (error) {
console.error(`[Carousel] Failed to upload image for card ${card.header.title}:`, error);
}
}
if (card.header?.videoUrl) {
try {
console.log(`[Carousel] Uploading video for card: ${card.header.title}`);
const message = await prepareWAMessageMedia(
{ video: { url: card.header.videoUrl } },
{
upload: instance.socket.waUploadToServer,
logger: instance.socket.logger
}
);
card.header.videoMessage = message.videoMessage || undefined;
} catch (error) {
console.error(`[Carousel] Failed to upload video for card ${card.header.title}:`, error);
}
}
}
console.log('[Carousel] Socket User:', instance.socket.user);
console.log('[Carousel] Cards:', JSON.stringify(cards, null, 2));
console.log('[Carousel] Title:', title, 'Body:', body, 'Footer:', footer);
const carouselContent = generateCarouselMessage({ cards, title, body, footer });
console.log('[Carousel] Sending message via relayMessage...');
const resolvedJid = await resolveJid(instance.socket, jid)
console.log('[Carousel] JID Original:', jid);
console.log('[Carousel] JID Resolvido:', resolvedJid);
// Enviar diretamente como interactiveMessage (sem viewOnceMessage wrapper)
// Isso pode funcionar melhor em dispositivos iOS
const messageContent = {
interactiveMessage: carouselContent
};
console.log('[Carousel] Message Content (sem viewOnce):', JSON.stringify(messageContent, null, 2));
await instance.socket.relayMessage(resolvedJid, messageContent, {});
console.log('[Carousel] Message sent successfully to:', resolvedJid);
res.json({ success: true, jidOriginal: jid, jidResolved: resolvedJid })
} catch (error) {
console.error('[Carousel] Failed to send message:', error)
res.status(500).json({ error: 'Failed to send message: ' + (error as Error).message })
}
})
// Send List Message
app.post('/api/instances/:id/send-list', async (req: Request, res: Response) => {
const id = req.params.id
if (!id) return res.status(400).json({ error: 'ID is required' })
const { jid, title, text, footer, buttonText, sections } = req.body
const instance = instanceManager.getInstance(id)
if (!instance || !instance.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
const listInteractive = generateListMessage(sections, buttonText, text, title, footer)
console.log('[List] Sending via sendMessage...');
console.log('[List] Content:', JSON.stringify(listInteractive, null, 2));
// Usar sendMessage que processa corretamente o interactiveMessage
await instance.socket.sendMessage(resolvedJid, {
viewOnceMessage: {
message: {
interactiveMessage: listInteractive
}
}
} as any);
console.log('[List] Message sent successfully to:', resolvedJid);
res.json({ success: true })
} catch (error) {
console.error('[List] Error:', error)
res.status(500).json({ error: 'Failed to send list message' })
}
})
// Send Button Message
app.post('/api/instances/:id/send-buttons', async (req: Request, res: Response) => {
const id = req.params.id
if (!id) return res.status(400).json({ error: 'ID is required' })
const { jid, text, footer, buttons, headerType, mediaUrl } = req.body
const instance = instanceManager.getInstance(id)
if (!instance || !instance.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
const buttonsInteractive = generateButtonMessage(buttons, text, footer, headerType, mediaUrl)
console.log('[Buttons] Sending via sendMessage...');
console.log('[Buttons] Content:', JSON.stringify(buttonsInteractive, null, 2));
// Usar sendMessage que processa corretamente o interactiveMessage
await instance.socket.sendMessage(resolvedJid, {
viewOnceMessage: {
message: {
interactiveMessage: buttonsInteractive
}
}
} as any);
console.log('[Buttons] Message sent successfully to:', resolvedJid);
res.json({ success: true })
} catch (error) {
console.error('[Buttons] Error:', error)
res.status(500).json({ error: 'Failed to send button message' })
}
})
// ==================== NOVAS ROTAS ====================
// Get instance status
app.get('/api/instances/:id/status', (req: Request, res: Response) => {
const id = req.params.id
if (!id) return res.status(400).json({ error: 'ID is required' })
const instance = instanceManager.getInstance(id)
if (!instance) return res.status(404).json({ error: 'Instance not found' })
const { socket, ...rest } = instance as any
res.json(rest)
})
// Send text message
app.post('/api/instances/:id/send-text', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, text } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, { text })
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send message' })
}
})
// Send image
app.post('/api/instances/:id/send-image', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, url, caption } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, { image: { url }, caption })
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send image' })
}
})
// Send video
app.post('/api/instances/:id/send-video', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, url, caption, gifPlayback } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, { video: { url }, caption, gifPlayback })
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send video' })
}
})
// Send audio
app.post('/api/instances/:id/send-audio', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, url, ptt } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, { audio: { url }, ptt })
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send audio' })
}
})
// Send document
app.post('/api/instances/:id/send-document', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, url, filename, mimetype } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, { document: { url }, fileName: filename, mimetype })
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send document' })
}
})
// Send location
app.post('/api/instances/:id/send-location', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, latitude, longitude, name, address } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, {
location: { degreesLatitude: latitude, degreesLongitude: longitude, name, address }
})
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send location' })
}
})
// Send contact
app.post('/api/instances/:id/send-contact', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, name, phone } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
const vcard = `BEGIN:VCARD\nVERSION:3.0\nFN:${name}\nTEL;type=CELL;type=VOICE;waid=${phone.replace(/\D/g, '')}:${phone}\nEND:VCARD`
await instance.socket.sendMessage(resolvedJid, {
contacts: { displayName: name, contacts: [{ vcard }] }
})
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send contact' })
}
})
// Send reaction
app.post('/api/instances/:id/send-reaction', async (req: Request, res: Response) => {
const id = req.params.id
const { jid, messageId, emoji } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const resolvedJid = await resolveJid(instance.socket, jid)
await instance.socket.sendMessage(resolvedJid, {
react: { text: emoji, key: { remoteJid: resolvedJid, id: messageId } }
})
res.json({ success: true })
} catch (error) {
res.status(500).json({ error: 'Failed to send reaction' })
}
})
// ==================== GRUPOS ====================
// Create group
app.post('/api/instances/:id/groups/create', async (req: Request, res: Response) => {
const id = req.params.id
const { name, participants } = req.body
if (!name) return res.status(400).json({ error: 'Group name is required' })
if (!participants || !Array.isArray(participants) || participants.length === 0) {
return res.status(400).json({ error: 'At least one participant is required' })
}
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const result = await instance.socket.groupCreate(name, participants)
res.json({ success: true, group: result })
} catch (error: any) {
console.error('Error creating group:', error)
res.status(500).json({ error: 'Failed to create group', details: error?.message || 'Unknown error' })
}
})
// Get group metadata
app.get('/api/instances/:id/groups/:groupId/metadata', async (req: Request, res: Response) => {
const { id, groupId } = req.params
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const metadata = await instance.socket.groupMetadata(groupId)
res.json(metadata)
} catch (error) {
res.status(500).json({ error: 'Failed to get group metadata' })
}
})
// Get group invite code
app.get('/api/instances/:id/groups/:groupId/invite-code', async (req: Request, res: Response) => {
const { id, groupId } = req.params
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const code = await instance.socket.groupInviteCode(groupId)
res.json({ code, link: `https://chat.whatsapp.com/${code}` })
} catch (error) {
res.status(500).json({ error: 'Failed to get invite code' })
}
})
// Manage group participants
app.post('/api/instances/:id/groups/:groupId/participants', async (req: Request, res: Response) => {
const { id, groupId } = req.params
const { action, participants } = req.body
const instance = instanceManager.getInstance(id)
if (!instance?.socket) return res.status(404).json({ error: 'Instance not found or not connected' })
try {
const result = await instance.socket.groupParticipantsUpdate(groupId, participants, action)
res.json({ success: true, result })
} catch (error) {
res.status(500).json({ error: 'Failed to update participants' })
}
})