-
-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathindex.html
More file actions
1231 lines (1153 loc) · 64.3 KB
/
Copy pathindex.html
File metadata and controls
1231 lines (1153 loc) · 64.3 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
<!DOCTYPE html>
<html lang="pt-Br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unoapi - Manager</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- DataTables CSS -->
<link href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
<!-- Socket IO-->
<script src="/socket.io.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.navbar {
margin-bottom: 20px;
}
.edit-modal {
max-width: 80vw;
}
.editForm {
width: 80vw;
}
.switch {
position: relative;
display: inline-block;
width: 52px;
height: 24px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.d-none {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 17px;
width: 17px;
left: 5px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.webhook {
margin: 15px 45px;
font-size: 14px;
font-weight: 700;
}
.webhook:not(:last-child) {
border-bottom: 1px solid #e1e1e1d6;
padding-bottom: 10px;
margin: 10px 50px;
}
div#login {
height: 100%;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
body {
min-height: 100vh;
display: flex;
margin: 0 auto;
flex-direction: column;
}
.container {
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: stretch;
}
#tokenForm {
display: flex;
flex-direction: column;
width: 100%;
padding: 0 25%;
font-size: 25px;
font-weight: bold;
}
.edit-form-row {
margin-bottom: 15px;
}
:root {
--bs-breakpoint-xs: 0;
--bs-breakpoint-sm: 480px;
--bs-breakpoint-md: 768px;
--bs-breakpoint-lg: 1024px;
--bs-breakpoint-xl: 1300px;
--bs-breakpoint-xxl: 1560px;
}
.form-label {
margin-top: 10px;
margin-bottom: -10px;
}
</style>
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="https://raw.githubusercontent.com/clairton/unoapi-cloud/61c7e67e3d043b5d6cc142fd2192b78efffefce0/logos/Unoapi_logo.svg" alt="Logo" width="250" height="80" class="d-inline-block align-text-top">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse d-none" id="navbarNav">
<ul class="navbar-nav ms-auto">
<!-- Configurations Dropdown -->
<li class="nav-item dropdown d-none" id="navbarDropdown">
<a class="nav-link dropdown-toggle" href="#" id="configDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-cog"></i>
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="configDropdown">
<li>
<button class="dropdown-item" onclick="addInstance()"><i class="fas fa-plus"></i> Adicionar Instância</button>
</li>
<li><hr class="dropdown-divider"></li>
<li>
<button class="dropdown-item text-danger" onclick="logout()"><i class="fas fa-sign-out"></i> SAIR</button>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div id="login">
<div id="tokenForm" class="mb-4">
<label for="tokenInput" class="form-label">Token configurado:</label>
<div class="input-group mb-3">
<input type="text" id="tokenInput" class="form-control" placeholder="Insira o token aqui" aria-describedby="connectButton">
<button class="btn btn-dark" type="button" id="connectButton"><i class="fas fa-sign-in"></i> Conectar</button>
</div>
</div>
<p id="errorMessage" class="text-danger d-none">Erro: Token inválido ou conexão falhou.</p>
</div>
<div class="container mt-4">
<table id="sessionsTable" class="table table-striped table-bordered d-none" style="width: 100%;">
<thead>
<tr>
<th>Identificação</th>
<th>Número</th>
<th>Status</th>
<th>Server</th>
<th>Ações</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<!-- Modal para adicionar instância -->
<div class="modal fade" id="addInstanceModal" tabindex="-1" aria-labelledby="addInstanceModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addInstanceModalLabel">Adicionar Sessão</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="addInstanceForm">
<div class="mb-3">
<label for="instanceNumber" class="form-label">Número da Conexão</label>
<input type="number" class="form-control" id="instanceNumber" placeholder="Número no formato 55 DDD NUMERO" required>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="submitInstanceNumber()">Configurar</button>
</div>
</div>
</div>
</div>
<!-- Modal Editar -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog edit-modal">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editModalLabel">Editar/Adicionar Sessão</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="editForm">
<div class="row edit-form-row">
<div class="col-12 col-md-12 col-lg-6">
<label for="provider" class="form-label">Provider</label>
<select id="provider" name="provider" class="form-control">
<option value="baileys">baileys</option>
<option value="whatsmeow">whatsmeow</option>
<option value="forwarder">forwarder</option>
</select>
</div>
</div>
<div class="row edit-form-row">
<div class="col-12 col-md-12 col-lg-6">
<label for="label" class="form-label">Identificação</label>
<input type="text" class="form-control" id="label" name="lavel" placeholder="Identificação">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="authToken" class="form-label">Auth Token</label>
<input type="text" class="form-control" id="authToken" name="authToken" placeholder="Auth Token">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="openaiApiKey" class="form-label">Openai Api Key</label>
<input type="text" class="form-control" id="openaiApiKey" name="openaiApiKey" placeholder="Openai Api Key">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="openaiApiTranscribeModel" class="form-label">Openai Transcribe Model</label>
<input type="text" class="form-control" id="openaiApiTranscribeModel" name="openaiApiTranscribeModel" placeholder="Openai Transcribe Model">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="wavoipToken" class="form-label">Token Wavoip</label>
<input type="text" class="form-control" id="wavoipToken" name="wavoipToken" placeholder="Token WAVOIP...">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="rejectCallsWebhook" class="form-label">Mensagem de Ligação Recebida e/ou Rejeitada</label>
<input type="text" class="form-control" id="rejectCallsWebhook" name="rejectCallsWebhook" placeholder="Estava te ligando...">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="connectionType" class="form-label">Tipo de Conexão</label>
<select id="connectionType" name="connectionType" class="form-control">
<option value="qrcode" selected>QrCode</option>
<option value="pairing_code">PairingCode</option>
<option value="forward">Forward</option>
</select>
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="proxyUrl" class="form-label">Proxy Url (Precisa Reiniciar a Unoapi ao Alterar)</label>
<input type="text" class="form-control" id="proxyUrl" name="proxyUrl" placeholder="Ex: socks5://user:pass@ip/domain:port">
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="rejectCalls" class="form-label">Mensagem ao Rejeitar Chamadas</label>
<textarea class="form-control" id="rejectCalls" name="rejectCalls" placeholder="Deixe em Branco para não Rejeitar ligações automaticamente" oninput="this.style.height = ''; this.style.height = this.scrollHeight + 'px'"></textarea>
</div>
<div class="col-12 col-md-12 col-lg-6">
<label for="server" class="form-label">Server</label>
<input type="text" class="form-control" id="server" name="server" placeholder="Ex: default is server_1">
</div>
</div>
<div class="row edit-form-row">
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreGroupMessages" name="ignoreGroupMessages" checked>
<span class="slider round"></span>
</label>
<label for="ignoreGroupMessages" class="form-label">Ignorar Mensagens de Grupo</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreNewsletterMessages" name="ignoreNewsletterMessages" checked>
<span class="slider round"></span>
</label>
<label for="ignoreNewsletterMessages" class="form-label">Ignorar Mensagens de Newsletter</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreHistoryMessages" name="ignoreHistoryMessages" checked>
<span class="slider round"></span>
</label>
<label for="ignoreHistoryMessages" class="form-label">Ignorar Histórico de Mensagens</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="readOnReceipt" name="readOnReceipt" checked>
<span class="slider round"></span>
</label>
<label for="readOnReceipt" class="form-label">Ler a mensagem ao receber</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="sendProfilePicture" name="sendProfilePicture">
<span class="slider round"></span>
</label>
<label for="sendProfilePicture" class="form-label">Enviar Foto de Perfil</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreBroadcastStatuses" name="ignoreBroadcastStatuses" checked>
<span class="slider round"></span>
</label>
<label for="ignoreBroadcastStatuses" class="form-label">Ignorar Status</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="sendConnectionStatus" name="sendConnectionStatus">
<span class="slider round"></span>
</label>
<label for="sendConnectionStatus" class="form-label">Enviar Status da Conexão</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="notifyFailedMessages" name="notifyFailedMessages">
<span class="slider round"></span>
</label>
<label for="notifyFailedMessages" class="form-label">Notificar Falhas</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="composingMessage" name="composingMessage">
<span class="slider round"></span>
</label>
<label for="composingMessage" class="form-label">Enviar "Digitando"</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="sendReactionAsReply" name="sendReactionAsReply">
<span class="slider round"></span>
</label>
<label for="sendReactionAsReply" class="form-label">Enviar Reação Como Resposta</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreOwnMessages" name="ignoreOwnMessages">
<span class="slider round"></span>
</label>
<label for="ignoreOwnMessages" class="form-label">Ignorar Mensagens Próprias</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreYourselfMessages" name="ignoreYourselfMessages">
<span class="slider round"></span>
</label>
<label for="ignoreYourselfMessages" class="form-label">Ignorar Suas Mensagens</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="autoConnect" name="autoConnect" checked>
<span class="slider round"></span>
</label>
<label for="autoConnect" class="form-label">Conexão Automática"</label>
</div>
<div class="col-12 col-md-6 col-lg-6 col-xl-4 col-xxl-3">
<label class="switch">
<input type="checkbox" id="ignoreBroadcastMessages" name="ignoreBroadcastMessages" checked>
<span class="slider round"></span>
</label>
<label for="ignoreBroadcastMessages" class="form-label">Ignorar Listas de Transmissão</label>
</div>
</div>
<div id="webhooksContainer">
<h6>Webhooks</h6>
<div class="webhook mb-3">
<label for="webhookId" class="form-label">ID</label>
<input type="text" class="form-control mb-2 webhook-id" placeholder="Webhook ID">
<label for="webhookUrl" class="form-label">URL Absoluta</label>
<input type="text" class="form-control mb-2 webhook-url" placeholder="Webhook URL Absoluta">
<label for="webhookToken" class="form-label">Token</label>
<input type="text" class="form-control mb-2 webhook-token" placeholder="Webhook Token">
<label for="webhookHeader" class="form-label">Header</label>
<input type="text" class="form-control mb-2 webhook-header" placeholder="Webhook Header">
<label for="sendNewMessages" class="form-label">Enviar Novas Mensagens</label>
<label class="switch">
<input type="checkbox" class="webhook-sendNewMessages">
<span class="slider round"></span>
</label>
<label for="sendGroupMessages" class="form-label">Enviar Mensagens de Grupos</label>
<label class="switch">
<input type="checkbox" class="webhook-sendGroupMessages">
<span class="slider round"></span>
</label>
<label for="sendNewsletterMessages" class="form-label">Enviar Mensagens de Newsletter</label>
<label class="switch">
<input type="checkbox" class="webhook-sendNewsletterMessages">
<span class="slider round"></span>
</label>
<label for="sendOutgoingMessages" class="form-label">Enviar Mensagens de Saída</label>
<label class="switch">
<input type="checkbox" class="webhook-sendOutgoingMessages">
<span class="slider round"></span>
</label>
<label for="sendIncomingMessages" class="form-label">Enviar Mensagens de Entrada</label>
<label class="switch">
<input type="checkbox" class="webhook-sendIncomingMessages">
<span class="slider round"></span>
</label>
<label for="sendUpdateMessages" class="form-label">Enviar Atualização de Mensagens</label>
<label class="switch">
<input type="checkbox" class="webhook-sendUpdateMessages">
<span class="slider round"></span>
</label>
<label for="sendTranscribeAudio" class="form-label">Enviar Transcrição de Áudio</label>
<label class="switch">
<input type="checkbox" class="webhook-sendTranscribeAudio">
<span class="slider round"></span>
</label>
<label for="addToBlackListOnOutgoingMessageWithTtl" class="form-label">Adicionar ao blacklits quando ouver uma mensagem de saida por X segundos</label>
<label>
<input type="text" class="webhook-addToBlackListOnOutgoingMessageWithTtl" class="form-control">
</label>
<button type="button" class="btn btn-danger btn-sm mt-2 remove-webhook">Remover</button>
</div>
</div>
<button type="button" id="addWebhookButton" class="btn btn-secondary btn-sm">Adicionar Webhook</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="saveEditButton">Salvar</button>
</div>
</div>
</div>
</div>
<!-- Modal Conectar -->
<div class="modal fade" id="connectModal" tabindex="-1" aria-labelledby="connectModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="connectModalLabel">Conectar Sessão</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-center">
<p id="qrCodeMessage">Aguarde o evento com o QrCode/PairingCode</p>
<div id="qrCodeContainer">QrCode/PairingCode será exibido aqui</div>
</div>
</div>
</div>
</div>
<!-- Modal Mensagem -->
<div class="modal fade" id="messageModal" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="messageModalLabel">Testar Sessão</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="messageModalForm">
<div class="mb-3">
<label for="messageModalNumber" class="form-label">Whatsapp Destinatário</label>
<input type="number" class="form-control" id="messageModalNumber" placeholder="Número no formato 55 DDD NUMERO" required>
</div>
<div class="mb-3">
<label for="messageModalText" class="form-label">Mensagem em texto</label>
<input type="text" class="form-control" id="messageModalText" placeholder="" required>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="submitMessage()">Enviar</button>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script>
const apiUrl = `${window.location.origin}`;
const tokenKey = "whatsappApiToken";
const qrcodes = {};
let currentPhoneNumber = ''
let currentQrTimeOut = ''
let lastTimeout = undefined
let qrPollIntervalId = undefined
let statusPollIntervalId = undefined
const onBroadcast = function(data) {
if (data.phone == currentPhoneNumber) {
const qrcodeDiv = document.getElementById('qrCodeContainer');
const statusDiv = document.getElementById('qrCodeMessage');
if (data.type === 'qrcode' && data.content) {
// Exibe o QR Code
qrcodeDiv.innerHTML = `<img src="${data.content}" alt="QR Code">`;
statusDiv.textContent = `Leia o QR Code Abaixo`;
const timeoutMs = currentQrTimeOut - (currentQrTimeOut / 5)
if (lastTimeout) {
clearTimeout(lastTimeout);
}
lastTimeout = setTimeout(function() {
qrcodeDiv.innerHTML = 'Esperando um novo QrCode/PairingCode';
qrcodeDiv.textContent = '';
}, timeoutMs);
} else if (data.type === 'status' && data.content) {
if (data.content.toLowerCase().indexOf('connected with') !== -1) {
qrcodeDiv.innerHTML = '';
statusDiv.textContent = `Conectado!`;
} else if (data.content.toLowerCase().indexOf('generate qrcode is exceded') !== -1) {
console.log("QRCODE EXCEDIDO")
qrcodeDiv.innerHTML = '';
statusDiv.textContent = 'Gerando novo QrCode/PairingCode...';
attemptRegister(phoneNumber, localStorage.getItem(tokenKey));
} else {
qrcodeDiv.innerHTML = ''
statusDiv.textContent = `Status: ${data.content}`;
}
}
}
}
// init websocket
function initWebSocket() {
if (window.socket && window.socket.connected) {
console.log("WebSocket já está conectado.");
return;
}
const socket = io(apiUrl, { path: '/ws' });
window.socket = socket;
var lastTimeout = undefined;
socket.on('broadcast', function(data) {
if (data.type === 'qrcode' && data.content && data.phone) {
qrcodes[data.phone] = data.content;
}
onBroadcast(data);
});
}
initWebSocket();
//Logout
function logout() {
localStorage.removeItem(tokenKey);
$('.container').addClass('d-none');
$('#navbarDropdown').addClass('d-none');
window.location.reload();
}
$(document).ready(function () {
var table;
const storedToken = localStorage.getItem(tokenKey);
if (storedToken) {
fetchSessions(storedToken, true);
}
//Login
$('#connectButton').on('click', function () {
const token = $('#tokenInput').val().trim();
if (token) {
fetchSessions(token);
}
});
//Add Webhook
$('#addWebhookButton').on('click', function () {
const webhookTemplate = `
<div class="webhook mb-3">
<label for="webhookId" class="form-label">ID</label>
<input type="text" class="form-control mb-2 webhook-id" placeholder="Webhook ID">
<label for="webhookUrl" class="form-label">URL Absoluta</label>
<input type="text" class="form-control mb-2 webhook-url" placeholder="Webhook URL Absoluta">
<label for="webhookToken" class="form-label">Token</label>
<input type="text" class="form-control mb-2 webhook-token" placeholder="Webhook Token">
<label for="webhookHeader" class="form-label">Header</label>
<input type="text" class="form-control mb-2 webhook-header" placeholder="Webhook Header">
<label for="sendNewMessages" class="form-label">Enviar Novas Mensagens</label>
<label class="switch">
<input type="checkbox" class="webhook-sendNewMessages">
<span class="slider round"></span>
</label>
<label for="sendGroupMessages" class="form-label">Enviar Mensagens de Grupos</label>
<label class="switch">
<input type="checkbox" class="webhook-sendGroupMessages">
<span class="slider round"></span>
</label>
<label for="sendNewsletterMessages" class="form-label">Enviar Mensagens de Newsletter</label>
<label class="switch">
<input type="checkbox" class="webhook-sendNewsletterMessages">
<span class="slider round"></span>
</label>
<label for="sendOutgoingMessages" class="form-label">Enviar Mensagens de Saída</label>
<label class="switch">
<input type="checkbox" class="webhook-sendOutgoingMessages">
<span class="slider round"></span>
</label>
<label for="sendIncomingMessages" class="form-label">Enviar Mensagens de Entrada</label>
<label class="switch">
<input type="checkbox" class="webhook-sendIncomingMessages">
<span class="slider round"></span>
</label>
<label for="sendUpdateMessages" class="form-label">Enviar Atualização de Mensagens</label>
<label class="switch">
<input type="checkbox" class="webhook-sendUpdateMessages">
<span class="slider round"></span>
</label>
<label for="sendTranscribeAudio" class="form-label">Enviar Transcrição de Áudio</label>
<label class="switch">
<input type="checkbox" class="webhook-sendTranscribeAudio">
<span class="slider round"></span>
</label>
<label for="addToBlackListOnOutgoingMessageWithTtl" class="form-label">Adicionar ao blacklits quando ouver uma mensagem de saida por X segundos</label>
<label>
<input type="text" class="webhook-addToBlackListOnOutgoingMessageWithTtl" class="form-control">
</label>
<button type="button" class="btn btn-danger btn-sm mt-2 remove-webhook">Remover</button>
</div>`;
$('#webhooksContainer').append(webhookTemplate);
});
$('#webhooksContainer').on('click', '.remove-webhook', function () {
$(this).closest('.webhook').remove();
});
//Create DataTable And Fetch Conected Sessions
function fetchSessions(token, hideForm = true) {
if (!$.fn.dataTable.isDataTable('#sessionsTable')) {
table = $('#sessionsTable').DataTable({
language: {
"decimal": "",
"emptyTable": "Nenhuma sessão nesta instalação",
"info": "Exibindo _START_ até _END_ de _TOTAL_ sessões",
"infoEmpty": "Nenhum Registro",
"infoFiltered": "(filtrado de _MAX_ registros no total)",
"infoPostFix": "",
"thousands": ".",
"lengthMenu": "Exibir _MENU_ Sessões",
"loadingRecords": "Carregando...",
"processing": "Processando...",
"search": "Pesquisar:",
"zeroRecords": "Nenhuma sessão configurada",
"paginate": {
"first": "Primeiro",
"last": "Último",
"next": "Próximo",
"previous": "Anterior"
},
"aria": {
"sortAscending": ": ativar para ordenar a coluna de forma ascendente",
"sortDescending": ": ativar para ordenar a coluna de forma descendente"
}
}
});
}
getSessionAndpopulateTable(token, hideForm)
}
// Populate Datatable with session numbers
function getSessionAndpopulateTable(token, hideForm) {
const headers = { Authorization: `Bearer ${token}` };
fetch(apiUrl + '/sessions', { headers })
.then(response => {
if (!response.ok) throw new Error("Token inválido ou falha na conexão.");
localStorage.setItem(tokenKey, token);
return response.json();
})
.then(resp => {
if (hideForm) {
$('#navbarDropdown').removeClass('d-none');
$('#login').addClass('d-none');
}
populateTable(resp.data); // Popula a tabela com os dados
})
.catch(() => {
$('#errorMessage').removeClass('d-none');
$('#sessionsTable').addClass('d-none');
});
}
// Populate Datatable with session numbers
function populateTable(sessions) {
$('#errorMessage').addClass('d-none');
$('#sessionsTable').removeClass('d-none');
// Limpa os dados antigos da tabela antes de adicionar os novos
table.clear();
sessions.forEach(session => {
const statusLower = (session.status || '').toLowerCase()
const disconnectBtn = ['online', 'connecting'].includes(statusLower)
? `<button class="btn btn-sm btn-secondary disconnect-btn" data-number="${session.display_phone_number}">
<i class="fas fa-unlink"></i> Desconectar
</button>`
: '';
const connectBtn = !['online', 'connecting'].includes(statusLower)
? `<button class=\"btn btn-sm btn-success connect-btn\" data-bs-toggle=\"modal\" data-bs-target=\"#connectModal\" data-number=\"${session.display_phone_number}\">
<i class=\"fas fa-link\"></i> Conectar
</button>`
: '';
const buttons = `
<button class=\"btn btn-sm btn-warning edit-btn\" data-bs-toggle=\"modal\" data-bs-target=\"#editModal\" data-number=\"${session.display_phone_number}\">
<i class=\"fas fa-edit\"></i> Editar
</button>
${connectBtn}
${disconnectBtn}
<button class=\"btn btn-sm btn-danger delete-btn\" data-number=\"${session.display_phone_number}\">
<i class=\"fas fa-trash\"></i> Deletar
</button>
<button class=\"btn btn-sm btn-success message-btn\" data-bs-target=\"#messageModal\" data-number=\"${session.display_phone_number}\">
<i class=\"fas fa-message\"></i> Testar
</button>`;
table.row.add([
session.label,
session.display_phone_number,
session.status,
session.server,
buttons
]).draw(false);
});
}
//deregister function
$('#sessionsTable tbody').on('click', '.delete-btn', function() {
if (!confirm('Tem certeza que deseja deletar essa sessão?')) {
return
}
const number = $(this).data('number');
const token = localStorage.getItem(tokenKey);
if (token) {
fetch(`${apiUrl}/v15.0/${number}/deregister`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
.then(response => {
if (!response.ok) throw new Error("Erro no request.");
})
.then(_ => {
alert("A sessão foi removida, recarrega a pagina para atualizar a lista!");
})
.catch(error => alert(error.message));
}
});
//Disconnect button
$('#sessionsTable tbody').on('click', '.disconnect-btn', function() {
const number = $(this).data('number');
const token = localStorage.getItem(tokenKey);
if (!token) { alert('Token não encontrado.'); return }
fetch(`${apiUrl}/sessions/${number}/disconnect`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
.then(response => {
if (!response.ok) throw new Error('Erro ao desconectar sessão.');
alert('Sessão desconectada.');
// opcional: recarrega dados
fetchSessions(token, false);
})
.catch(error => alert(error.message));
});
//Edit button
$('#sessionsTable tbody').on('click', '.edit-btn', function () {
const number = $(this).data('number');
const token = localStorage.getItem(tokenKey);
if (token) {
fetch(`${apiUrl}/v15.0/${number}`, {
headers: { Authorization: `Bearer ${token}` }
})
.then(response => {
if (!response.ok) throw new Error("Erro ao buscar dados da sessão.");
return response.json();
})
.then(data => {
populateEditForm(data);
$('#editModal').data('number', number);
$('#editModal').modal('show');
})
.catch(error => alert(error.message));
}
});
//Message button
$('#sessionsTable tbody').on('click', '.message-btn', function () {
const number = $(this).data('number');
$('#messageModal').data('number', number);
$('#messageModal').modal('show');
});
//Edit form for session number
function populateEditForm(session) {
$('#provider').val(session.provider || 'baileys');
$('#label').val(session.label);
$('#authToken').val(session.authToken);
$('#wavoipToken').val(session.wavoipToken);
$('#openaiApiKey').val(session.openaiApiKey);
$('#openaiApiTranscribeModel').val(session.openaiApiTranscribeModel);
$('#rejectCallsWebhook').val(session.rejectCallsWebhook);
$('#rejectCalls').val(session.rejectCalls);
$('#ignoreGroupMessages').prop('checked', session.ignoreGroupMessages);
$('#ignoreNewsletterMessages').prop('checked', session.ignoreNewsletterMessages);
$('#ignoreHistoryMessages').prop('checked', session.ignoreHistoryMessages);
$('#readOnReceipt').prop('checked', session.readOnReceipt);
$('#sendProfilePicture').prop('checked', session.sendProfilePicture);
$('#ignoreOwnMessages').prop('checked', session.ignoreOwnMessages);
$('#ignoreYourselfMessages').prop('checked', session.ignoreYourselfMessages);
$('#ignoreBroadcastStatuses').prop('checked', session.ignoreBroadcastStatuses);
$('#sendConnectionStatus').prop('checked', session.sendConnectionStatus);
$('#notifyFailedMessages').prop('checked', session.notifyFailedMessages);
$('#composingMessage').prop('checked', session.composingMessage);
$('#sendReactionAsReply').prop('checked', session.sendReactionAsReply);
$('#autoConnect').prop('checked', session.autoConnect);
$('#ignoreBroadcastMessages').prop('checked', session.ignoreBroadcastMessages);
$('#connectionType').val(session.connectionType);
$('#proxyUrl').val(session.proxyUrl);
$('#server').val(session.server);
// Limpar webhooks existentes no formulário de edição
$('#webhooksContainer .webhook').remove();
if (session.webhooks && Array.isArray(session.webhooks)) {
session.webhooks.forEach(webhook => {
const webhookTemplate = `
<div class="webhook mb-3">
<label for="webhookId" class="form-label">ID</label>
<input type="text" class="form-control mb-2 webhook-id" value="${webhook.id}" placeholder="Webhook ID">
<label for="webhookUrl" class="form-label">URL Absoluta</label>
<input type="text" class="form-control mb-2 webhook-url" value="${webhook.urlAbsolute}" placeholder="Webhook URL Absoluta">
<label for="webhookToken" class="form-label">Token</label>
<input type="text" class="form-control mb-2 webhook-token" value="${webhook.token}" placeholder="Webhook Token">
<label for="webhookHeader" class="form-label">Header</label>
<input type="text" class="form-control mb-2 webhook-header" value="${webhook.header}" placeholder="Webhook Header">
<label for="sendNewMessages" class="form-label">Enviar Novas Mensagens</label>
<label class="switch">
<input type="checkbox" class="webhook-sendNewMessages" ${webhook.sendNewMessages ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="sendGroupMessages" class="form-label">Enviar Mensagens de Grupos</label>
<label class="switch">
<input type="checkbox" class="webhook-sendGroupMessages" ${webhook.sendGroupMessages ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="sendNewsletterMessages" class="form-label">Enviar Mensagens de Newsletter</label>
<label class="switch">
<input type="checkbox" class="webhook-sendNewsletterMessages" ${webhook.sendNewsletterMessages ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="sendOutgoingMessages" class="form-label">Enviar Mensagens de Saída</label>
<label class="switch">
<input type="checkbox" class="webhook-sendOutgoingMessages" ${webhook.sendOutgoingMessages ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="sendIncomingMessages" class="form-label">Enviar Mensagens de Entrada</label>
<label class="switch">
<input type="checkbox" class="webhook-sendIncomingMessages" ${webhook.sendIncomingMessages ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="sendUpdateMessages" class="form-label">Enviar Atualização de Mensagens</label>
<label class="switch">
<input type="checkbox" class="webhook-sendUpdateMessages" ${webhook.sendUpdateMessages ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="sendTranscribeAudio" class="form-label">Enviar Transcrição de Áudio</label>
<label class="switch">
<input type="checkbox" class="webhook-sendTranscribeAudio" ${webhook.sendTranscribeAudio ? 'checked' : ''}>
<span class="slider round"></span>
</label>
<label for="addToBlackListOnOutgoingMessageWithTtl" class="form-label">Adicionar ao blacklits quando ouver uma mensagem de saida por X segundos</label>
<label>
<input type="text" class="webhook-addToBlackListOnOutgoingMessageWithTtl" value="${webhook.addToBlackListOnOutgoingMessageWithTtl || ''}" class="form-control">
</label>
<button type="button" class="btn btn-danger btn-sm mt-2 remove-webhook">Remover</button>
</div>`;
$('#webhooksContainer').append(webhookTemplate);
});
}
}
//Save/set configs
$('#saveEditButton').on('click', function () {
const token = localStorage.getItem(tokenKey);
const number = $('#editModal').data('number');
if (token && number) {
const sessionData = {
provider: $('#provider').val(),
label: $('#label').val(),
authToken: $('#authToken').val(),
wavoipToken: $('#wavoipToken').val(),
openaiApiKey: $('#openaiApiKey').val(),
openaiApiTranscribeModel: $('#openaiApiTranscribeModel').val(),
rejectCalls: $('#rejectCalls').val(),
rejectCallsWebhook: $('#rejectCallsWebhook').val(),
ignoreGroupMessages: $('#ignoreGroupMessages').is(':checked'),
ignoreNewsletterMessages: $('#ignoreNewsletterMessages').is(':checked'),
ignoreHistoryMessages: $('#ignoreHistoryMessages').is(':checked'),
readOnReceipt: $('#readOnReceipt').is(':checked'),
sendProfilePicture: $('#sendProfilePicture').is(':checked'),
ignoreOwnMessages: $('#ignoreOwnMessages').is(':checked'),
ignoreYourselfMessages: $('#ignoreYourselfMessages').is(':checked'),
sendConnectionStatus: $('#sendConnectionStatus').is(':checked'),
ignoreBroadcastStatuses: $('#ignoreBroadcastStatuses').is(':checked'),
notifyFailedMessages: $('#notifyFailedMessages').is(':checked'),
composingMessage: $('#composingMessage').is(':checked'),
sendReactionAsReply: $('#sendReactionAsReply').is(':checked'),
autoConnect: $('#autoConnect').is(':checked'),
ignoreBroadcastMessages: $('#ignoreBroadcastMessages').is(':checked'),
connectionType: $('#connectionType').val(),
proxyUrl: $('#proxyUrl').val(),
server: $('#server').val(),
webhooks: []
};
$('#webhooksContainer .webhook').each(function () {
const webhook = {
id: $(this).find('.webhook-id').val(),
urlAbsolute: $(this).find('.webhook-url').val(),
token: $(this).find('.webhook-token').val(),
header: $(this).find('.webhook-header').val(),
sendNewMessages: $(this).find('.webhook-sendNewMessages').is(':checked'),
sendGroupMessages: $(this).find('.webhook-sendGroupMessages').is(':checked'),
sendNewsletterMessages: $(this).find('.webhook-sendNewsletterMessages').is(':checked'),
sendOutgoingMessages: $(this).find('.webhook-sendOutgoingMessages').is(':checked'),
sendIncomingMessages: $(this).find('.webhook-sendIncomingMessages').is(':checked'),
sendUpdateMessages: $(this).find('.webhook-sendUpdateMessages').is(':checked'),
sendTranscribeAudio: $(this).find('.webhook-sendTranscribeAudio').is(':checked'),
addToBlackListOnOutgoingMessageWithTtl: $(this).find('.webhook-addToBlackListOnOutgoingMessageWithTtl').val(),
};
sessionData.webhooks.push(webhook);
});
sessionData.overrideWebhooks = true
fetch(`${apiUrl}/v15.0/${number}/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(sessionData)
})
.then(response => {
if (!response.ok) throw new Error("Erro ao salvar dados da sessão.");
return response.json();
})
.then(() => {
$('#editModal').modal('hide');
fetchSessions(token, true);
})
.catch(error => alert(error.message));
}
});
//QRCODE AND CONNECT