-
-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathhandlers.go
More file actions
6793 lines (5802 loc) · 202 KB
/
handlers.go
File metadata and controls
6793 lines (5802 loc) · 202 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
package main
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
"image/jpeg"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/nfnt/resize"
"github.com/patrickmn/go-cache"
"github.com/rs/zerolog/log"
"github.com/vincent-petithory/dataurl"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waCommon"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/types"
"google.golang.org/protobuf/proto"
)
type Values struct {
m map[string]string
}
func (v Values) Get(key string) string {
return v.m[key]
}
func (s *server) GetHealth() http.HandlerFunc {
type HealthResponse struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
Uptime string `json:"uptime"`
ActiveConnections int `json:"active_connections"`
TotalUsers int `json:"total_users"`
ConnectedUsers int `json:"connected_users"`
LoggedInUsers int `json:"logged_in_users"`
MemoryStats map[string]interface{} `json:"memory_stats"`
GoRoutines int `json:"goroutines"`
Version string `json:"version,omitempty"`
}
startTime := time.Now()
return func(w http.ResponseWriter, r *http.Request) {
uptime := time.Since(startTime)
var totalUsers int
rows, err := s.db.Query("SELECT COUNT(*) FROM users")
if err == nil {
defer rows.Close()
if rows.Next() {
rows.Scan(&totalUsers)
}
}
clientManager.RLock()
activeConnections := len(clientManager.whatsmeowClients)
connectedUsers := 0
loggedInUsers := 0
for _, client := range clientManager.whatsmeowClients {
if client != nil {
if client.IsConnected() {
connectedUsers++
}
if client.IsLoggedIn() {
loggedInUsers++
}
}
}
clientManager.RUnlock()
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
memoryStats := map[string]interface{}{
"alloc_mb": memStats.Alloc / 1024 / 1024,
"total_alloc_mb": memStats.TotalAlloc / 1024 / 1024,
"sys_mb": memStats.Sys / 1024 / 1024,
"num_gc": memStats.NumGC,
}
response := HealthResponse{
Status: "ok",
Timestamp: time.Now().UTC().Format(time.RFC3339),
Uptime: uptime.String(),
ActiveConnections: activeConnections,
TotalUsers: totalUsers,
ConnectedUsers: connectedUsers,
LoggedInUsers: loggedInUsers,
MemoryStats: memoryStats,
GoRoutines: runtime.NumGoroutine(),
Version: version,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Error().Err(err).Msg("Failed to write health check response")
}
}
}
// messageTypes moved to constants.go as supportedEventTypes
func (s *server) authadmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token != *adminToken {
s.Respond(w, r, http.StatusUnauthorized, errors.New("unauthorized"))
return
}
next.ServeHTTP(w, r)
})
}
func (s *server) authalice(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ctx context.Context
txtid := ""
name := ""
webhook := ""
jid := ""
events := ""
proxy_url := ""
qrcode := ""
var hasHmac bool // ← Nova variável para status HMAC
// Get token from headers or uri parameters
token := r.Header.Get("token")
if token == "" {
token = strings.Join(r.URL.Query()["token"], "")
}
myuserinfo, found := userinfocache.Get(token)
if !found {
log.Info().Msg("Looking for user information in DB")
// Checks DB from matching user and store user values in context
rows, err := s.db.Query("SELECT id,name,webhook,jid,events,proxy_url,qrcode,history,hmac_key IS NOT NULL AND length(hmac_key) > 0,CASE WHEN s3_enabled THEN 'true' ELSE 'false' END,COALESCE(media_delivery, 'base64') FROM users WHERE token=$1 LIMIT 1", token)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
return
}
defer rows.Close()
var history sql.NullInt64
var s3Enabled, mediaDelivery string
for rows.Next() {
err = rows.Scan(&txtid, &name, &webhook, &jid, &events, &proxy_url, &qrcode, &history, &hasHmac, &s3Enabled, &mediaDelivery)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
return
}
historyStr := "0"
if history.Valid {
historyStr = fmt.Sprintf("%d", history.Int64)
}
// Debug logging for history value
log.Debug().Str("userId", txtid).Bool("historyValid", history.Valid).Int64("historyValue", history.Int64).Str("historyStr", historyStr).Msg("User authentication - history debug")
v := Values{map[string]string{
"Id": txtid,
"Name": name,
"Jid": jid,
"Webhook": webhook,
"Token": token,
"Proxy": proxy_url,
"Events": events,
"Qrcode": qrcode,
"History": historyStr,
"HasHmac": strconv.FormatBool(hasHmac),
"S3Enabled": s3Enabled,
"MediaDelivery": mediaDelivery,
}}
userinfocache.Set(token, v, cache.NoExpiration)
log.Info().Str("name", name).Msg("User info name from DB")
ctx = context.WithValue(r.Context(), "userinfo", v)
}
} else {
ctx = context.WithValue(r.Context(), "userinfo", myuserinfo)
log.Info().Str("name", myuserinfo.(Values).Get("name")).Msg("User info name from Cache")
txtid = myuserinfo.(Values).Get("Id")
}
if txtid == "" {
s.Respond(w, r, http.StatusUnauthorized, errors.New("unauthorized"))
return
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Connects to Whatsapp Servers
func (s *server) Connect() http.HandlerFunc {
type connectStruct struct {
Subscribe []string
Immediate bool
}
return func(w http.ResponseWriter, r *http.Request) {
webhook := r.Context().Value("userinfo").(Values).Get("Webhook")
jid := r.Context().Value("userinfo").(Values).Get("Jid")
txtid := r.Context().Value("userinfo").(Values).Get("Id")
token := r.Context().Value("userinfo").(Values).Get("Token")
eventstring := ""
// Decodes request BODY looking for events to subscribe
decoder := json.NewDecoder(r.Body)
var t connectStruct
err := decoder.Decode(&t)
if err != nil {
s.Respond(w, r, http.StatusBadRequest, errors.New("could not decode Payload"))
return
}
if clientManager.GetWhatsmeowClient(txtid) != nil {
isConnected := clientManager.GetWhatsmeowClient(txtid).IsConnected()
if isConnected == true {
s.Respond(w, r, http.StatusInternalServerError, errors.New("already connected"))
return
}
}
var subscribedEvents []string
if len(t.Subscribe) < 1 {
if !Find(subscribedEvents, "") {
subscribedEvents = append(subscribedEvents, "")
}
} else {
for _, arg := range t.Subscribe {
if !Find(supportedEventTypes, arg) {
log.Warn().Str("Type", arg).Msg("Event type discarded")
continue
}
if !Find(subscribedEvents, arg) {
subscribedEvents = append(subscribedEvents, arg)
}
}
}
eventstring = strings.Join(subscribedEvents, ",")
_, err = s.db.Exec("UPDATE users SET events=$1 WHERE id=$2", eventstring, txtid)
if err != nil {
log.Warn().Msg("Could not set events in users table")
}
log.Info().Str("events", eventstring).Msg("Setting subscribed events")
v := updateUserInfo(r.Context().Value("userinfo"), "Events", eventstring)
userinfocache.Set(token, v, cache.NoExpiration)
log.Info().Str("jid", jid).Msg("Attempt to connect")
killchannel[txtid] = make(chan bool, 1)
go s.startClient(txtid, jid, token, subscribedEvents)
if t.Immediate == false {
log.Warn().Msg("Waiting 10 seconds")
time.Sleep(10000 * time.Millisecond)
if clientManager.GetWhatsmeowClient(txtid) != nil {
if !clientManager.GetWhatsmeowClient(txtid).IsConnected() {
s.Respond(w, r, http.StatusInternalServerError, errors.New("failed to Connect"))
return
}
} else {
s.Respond(w, r, http.StatusInternalServerError, errors.New("failed to connect"))
return
}
}
response := map[string]interface{}{"webhook": webhook, "jid": jid, "events": eventstring, "details": "Connected!"}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
return
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
return
}
}
}
// Disconnects from Whatsapp websocket, does not log out device
func (s *server) Disconnect() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
jid := r.Context().Value("userinfo").(Values).Get("Jid")
token := r.Context().Value("userinfo").(Values).Get("Token")
if clientManager.GetWhatsmeowClient(txtid) == nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New("no session"))
return
}
if clientManager.GetWhatsmeowClient(txtid).IsConnected() == true {
//if clientManager.GetWhatsmeowClient(txtid).IsLoggedIn() == true {
log.Info().Str("jid", jid).Msg("Disconnection successfull")
_, err := s.db.Exec("UPDATE users SET connected=0,events=$1 WHERE id=$2", "", txtid)
if err != nil {
log.Warn().Str("txtid", txtid).Msg("Could not set events in users table")
}
log.Info().Str("txtid", txtid).Msg("Update DB on disconnection")
v := updateUserInfo(r.Context().Value("userinfo"), "Events", "")
userinfocache.Set(token, v, cache.NoExpiration)
response := map[string]interface{}{"Details": "Disconnected"}
responseJson, err := json.Marshal(response)
clientManager.DeleteWhatsmeowClient(txtid)
select {
case killchannel[txtid] <- true:
default:
}
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
//} else {
// log.Warn().Str("jid", jid).Msg("Ignoring disconnect as it was not connected")
// s.Respond(w, r, http.StatusInternalServerError, errors.New("Cannot disconnect because it is not logged in"))
// return
//}
} else {
log.Warn().Str("jid", jid).Msg("Ignoring disconnect as it was not connected")
s.Respond(w, r, http.StatusInternalServerError, errors.New("cannot disconnect because it is not logged in"))
return
}
}
}
// Gets WebHook
func (s *server) GetWebhook() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
webhook := ""
events := ""
txtid := r.Context().Value("userinfo").(Values).Get("Id")
rows, err := s.db.Query("SELECT webhook,events FROM users WHERE id=$1 LIMIT 1", txtid)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("could not get webhook: %v", err)))
return
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&webhook, &events)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("could not get webhook: %s", fmt.Sprintf("%s", err))))
return
}
}
err = rows.Err()
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("could not get webhook: %s", fmt.Sprintf("%s", err))))
return
}
eventarray := strings.Split(events, ",")
response := map[string]interface{}{"webhook": webhook, "subscribe": eventarray}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
}
}
// DeleteWebhook removes the webhook and clears events for a user
func (s *server) DeleteWebhook() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
token := r.Context().Value("userinfo").(Values).Get("Token")
// Update the database to remove the webhook and clear events
_, err := s.db.Exec("UPDATE users SET webhook='', events='' WHERE id=$1", txtid)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("could not delete webhook: %v", err)))
return
}
// Update the user info cache
v := updateUserInfo(r.Context().Value("userinfo"), "Webhook", "")
v = updateUserInfo(v, "Events", "")
userinfocache.Set(token, v, cache.NoExpiration)
response := map[string]interface{}{"Details": "Webhook and events deleted successfully"}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
}
}
// UpdateWebhook updates the webhook URL and events for a user
func (s *server) UpdateWebhook() http.HandlerFunc {
type updateWebhookStruct struct {
WebhookURL string `json:"webhook"`
Events []string `json:"events,omitempty"`
Active bool `json:"active"`
}
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
token := r.Context().Value("userinfo").(Values).Get("Token")
decoder := json.NewDecoder(r.Body)
var t updateWebhookStruct
err := decoder.Decode(&t)
if err != nil {
s.Respond(w, r, http.StatusBadRequest, errors.New("could not decode payload"))
return
}
webhook := t.WebhookURL
var eventstring string
var validEvents []string
for _, event := range t.Events {
if !Find(supportedEventTypes, event) {
log.Warn().Str("Type", event).Msg("Event type discarded")
continue
}
validEvents = append(validEvents, event)
}
eventstring = strings.Join(validEvents, ",")
if eventstring == "," || eventstring == "" {
eventstring = ""
}
if !t.Active {
webhook = ""
eventstring = ""
}
if len(t.Events) > 0 {
_, err = s.db.Exec("UPDATE users SET webhook=$1, events=$2 WHERE id=$3", webhook, eventstring, txtid)
// Update MyClient if connected - integrated UpdateEvents functionality
if len(validEvents) > 0 {
clientManager.UpdateMyClientSubscriptions(txtid, validEvents)
log.Info().Strs("events", validEvents).Str("user", txtid).Msg("Updated event subscriptions")
}
} else {
// Update only webhook
_, err = s.db.Exec("UPDATE users SET webhook=$1 WHERE id=$2", webhook, txtid)
}
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("could not update webhook: %v", err)))
return
}
v := updateUserInfo(r.Context().Value("userinfo"), "Webhook", webhook)
v = updateUserInfo(v, "Events", eventstring)
userinfocache.Set(token, v, cache.NoExpiration)
response := map[string]interface{}{"webhook": webhook, "events": validEvents, "active": t.Active}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
}
}
// SetWebhook sets the webhook URL and events for a user
func (s *server) SetWebhook() http.HandlerFunc {
type webhookStruct struct {
WebhookURL string `json:"webhookurl"`
Events []string `json:"events,omitempty"`
}
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
token := r.Context().Value("userinfo").(Values).Get("Token")
decoder := json.NewDecoder(r.Body)
var t webhookStruct
err := decoder.Decode(&t)
if err != nil {
s.Respond(w, r, http.StatusBadRequest, errors.New("could not decode payload"))
return
}
webhook := t.WebhookURL
// If events are provided, validate them
var eventstring string
if len(t.Events) > 0 {
var validEvents []string
for _, event := range t.Events {
if !Find(supportedEventTypes, event) {
log.Warn().Str("Type", event).Msg("Event type discarded")
continue
}
validEvents = append(validEvents, event)
}
eventstring = strings.Join(validEvents, ",")
if eventstring == "," || eventstring == "" {
eventstring = ""
}
// Update both webhook and events
_, err = s.db.Exec("UPDATE users SET webhook=$1, events=$2 WHERE id=$3", webhook, eventstring, txtid)
// Update MyClient if connected - integrated UpdateEvents functionality
if len(validEvents) > 0 {
clientManager.UpdateMyClientSubscriptions(txtid, validEvents)
log.Info().Strs("events", validEvents).Str("user", txtid).Msg("Updated event subscriptions")
}
} else {
// Update only webhook
_, err = s.db.Exec("UPDATE users SET webhook=$1 WHERE id=$2", webhook, txtid)
}
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("could not set webhook: %v", err)))
return
}
v := updateUserInfo(r.Context().Value("userinfo"), "Webhook", webhook)
v = updateUserInfo(v, "Events", eventstring)
userinfocache.Set(token, v, cache.NoExpiration)
response := map[string]interface{}{"webhook": webhook}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
}
}
// Gets QR code encoded in Base64
func (s *server) GetQR() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
code := ""
if clientManager.GetWhatsmeowClient(txtid) == nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New("no session"))
return
} else {
if clientManager.GetWhatsmeowClient(txtid).IsConnected() == false {
s.Respond(w, r, http.StatusInternalServerError, errors.New("not connected"))
return
}
rows, err := s.db.Query("SELECT qrcode AS code FROM users WHERE id=$1 LIMIT 1", txtid)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
return
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&code)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
return
}
}
err = rows.Err()
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
return
}
if clientManager.GetWhatsmeowClient(txtid).IsLoggedIn() == true {
s.Respond(w, r, http.StatusInternalServerError, errors.New("already logged in"))
return
}
}
log.Info().Str("instance", txtid).Str("qrcode", code).Msg("Get QR successful")
response := map[string]interface{}{"QRCode": fmt.Sprintf("%s", code)}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
}
}
// Logs out device from Whatsapp (requires to scan QR next time)
func (s *server) Logout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
jid := r.Context().Value("userinfo").(Values).Get("Jid")
if clientManager.GetWhatsmeowClient(txtid) == nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New("no session"))
return
} else {
if clientManager.GetWhatsmeowClient(txtid).IsLoggedIn() == true &&
clientManager.GetWhatsmeowClient(txtid).IsConnected() == true {
err := clientManager.GetWhatsmeowClient(txtid).Logout(context.Background())
if err != nil {
log.Error().Str("jid", jid).Msg("Could not perform logout")
s.Respond(w, r, http.StatusInternalServerError, errors.New("could not perform logout"))
return
} else {
log.Info().Str("jid", jid).Msg("Logged out")
clientManager.DeleteWhatsmeowClient(txtid)
select {
case killchannel[txtid] <- true:
default:
}
}
} else {
if clientManager.GetWhatsmeowClient(txtid).IsConnected() == true {
log.Warn().Str("jid", jid).Msg("Ignoring logout as it was not logged in")
s.Respond(w, r, http.StatusInternalServerError, errors.New("could not logout as it was not logged in"))
return
} else {
log.Warn().Str("jid", jid).Msg("Ignoring logout as it was not connected")
s.Respond(w, r, http.StatusInternalServerError, errors.New("could not disconnect as it was not connected"))
return
}
}
}
response := map[string]interface{}{"Details": "Logged out"}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
}
}
// Pair by Phone. Retrieves the code to pair by phone number instead of QR
func (s *server) PairPhone() http.HandlerFunc {
type pairStruct struct {
Phone string
}
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
if clientManager.GetWhatsmeowClient(txtid) == nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New("no session"))
return
}
decoder := json.NewDecoder(r.Body)
var t pairStruct
err := decoder.Decode(&t)
if err != nil {
s.Respond(w, r, http.StatusBadRequest, errors.New("could not decode Payload"))
return
}
if t.Phone == "" {
s.Respond(w, r, http.StatusBadRequest, errors.New("missing Phone in Payload"))
return
}
isLoggedIn := clientManager.GetWhatsmeowClient(txtid).IsLoggedIn()
if isLoggedIn {
log.Error().Msg(fmt.Sprintf("%s", "already paired"))
s.Respond(w, r, http.StatusBadRequest, errors.New("already paired"))
return
}
linkingCode, err := clientManager.GetWhatsmeowClient(txtid).PairPhone(context.Background(), t.Phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
if err != nil {
log.Error().Msg(fmt.Sprintf("%s", err))
s.Respond(w, r, http.StatusBadRequest, err)
return
}
response := map[string]interface{}{"LinkingCode": linkingCode}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
}
}
// Gets Connected and LoggedIn Status
func (s *server) GetStatus() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userInfo := r.Context().Value("userinfo").(Values)
log.Info().
Str("Id", userInfo.Get("Id")).
Str("Jid", userInfo.Get("Jid")).
Str("Name", userInfo.Get("Name")).
Str("Webhook", userInfo.Get("Webhook")).
Str("Token", userInfo.Get("Token")).
Str("Events", userInfo.Get("Events")).
Str("Proxy", userInfo.Get("Proxy")).
Str("History", userInfo.Get("History")).
Str("HasHmac", userInfo.Get("HasHmac")).
Msg("User info values")
txtid := userInfo.Get("Id")
isConnected := clientManager.GetWhatsmeowClient(txtid).IsConnected()
isLoggedIn := clientManager.GetWhatsmeowClient(txtid).IsLoggedIn()
var proxyURL string
s.db.QueryRow("SELECT proxy_url FROM users WHERE id = $1", txtid).Scan(&proxyURL)
proxyConfig := map[string]interface{}{
"enabled": proxyURL != "",
"proxy_url": proxyURL,
}
var s3Enabled bool
var s3Endpoint, s3Region, s3Bucket, s3PublicURL, s3MediaDelivery string
var s3PathStyle bool
var s3RetentionDays int
// Start with safe defaults so the field is always present in the response
s3Config := map[string]interface{}{
"enabled": false,
"endpoint": "",
"region": "",
"bucket": "",
"access_key": "***",
"path_style": false,
"public_url": "",
"media_delivery": "",
"retention_days": 0,
}
err := s.db.QueryRow(`SELECT COALESCE(s3_enabled, false), COALESCE(s3_endpoint, ''), COALESCE(s3_region, ''), COALESCE(s3_bucket, ''), COALESCE(s3_path_style, false), COALESCE(s3_public_url, ''), COALESCE(media_delivery, ''), COALESCE(s3_retention_days, 0) FROM users WHERE id = $1`, txtid).Scan(&s3Enabled, &s3Endpoint, &s3Region, &s3Bucket, &s3PathStyle, &s3PublicURL, &s3MediaDelivery, &s3RetentionDays)
if err == nil {
// Overwrite defaults with actual values if the query succeeded
s3Config["enabled"] = s3Enabled
s3Config["endpoint"] = s3Endpoint
s3Config["region"] = s3Region
s3Config["bucket"] = s3Bucket
s3Config["path_style"] = s3PathStyle
s3Config["public_url"] = s3PublicURL
s3Config["media_delivery"] = s3MediaDelivery
s3Config["retention_days"] = s3RetentionDays
} else {
if err != sql.ErrNoRows {
log.Warn().Err(err).Str("user_id", txtid).Msg("Failed to query S3 config for user")
}
}
var hmacKey []byte
err = s.db.QueryRow("SELECT hmac_key FROM users WHERE id = $1", txtid).Scan(&hmacKey)
if err != nil && err != sql.ErrNoRows {
log.Error().Err(err).Str("userID", txtid).Msg("Failed to query HMAC key")
}
hmacConfigured := len(hmacKey) > 0
response := map[string]interface{}{
"id": txtid,
"name": userInfo.Get("Name"),
"connected": isConnected,
"loggedIn": isLoggedIn,
"token": userInfo.Get("Token"),
"jid": userInfo.Get("Jid"),
"webhook": userInfo.Get("Webhook"),
"events": userInfo.Get("Events"),
"proxy_url": userInfo.Get("Proxy"),
"qrcode": userInfo.Get("Qrcode"),
"history": userInfo.Get("History"),
"proxy_config": proxyConfig,
"s3_config": s3Config,
"hmac_configured": hmacConfigured,
}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
}
}
// Sends a document/attachment message
func (s *server) SendDocument() http.HandlerFunc {
type documentStruct struct {
Caption string
Phone string
Document string
FileName string
Id string
MimeType string
ContextInfo waE2E.ContextInfo
QuotedMessage *waE2E.Message `json:"QuotedMessage,omitempty"`
}
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
msgid := ""
var resp whatsmeow.SendResponse
if clientManager.GetWhatsmeowClient(txtid) == nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New("no session"))
return
}
decoder := json.NewDecoder(r.Body)
var t documentStruct
var err error
err = decoder.Decode(&t)
if err != nil {
s.Respond(w, r, http.StatusBadRequest, errors.New("could not decode Payload"))
return
}
if t.Phone == "" {
s.Respond(w, r, http.StatusBadRequest, errors.New("missing Phone in Payload"))
return
}
if t.Document == "" {
s.Respond(w, r, http.StatusBadRequest, errors.New("missing Document in Payload"))
return
}
if t.FileName == "" {
s.Respond(w, r, http.StatusBadRequest, errors.New("missing FileName in Payload"))
return
}
recipient, err := validateMessageFields(t.Phone, t.ContextInfo.StanzaID, t.ContextInfo.Participant)
if err != nil {
log.Error().Msg(fmt.Sprintf("%s", err))
s.Respond(w, r, http.StatusBadRequest, err)
return
}
if t.Id == "" {
msgid = clientManager.GetWhatsmeowClient(txtid).GenerateMessageID()
} else {
msgid = t.Id
}
var uploaded whatsmeow.UploadResponse
var filedata []byte
if t.Document[0:29] == "data:application/octet-stream" {
var dataURL, err = dataurl.DecodeString(t.Document)
if err != nil {
s.Respond(w, r, http.StatusBadRequest, errors.New("could not decode base64 encoded data from payload"))
return
} else {
filedata = dataURL.Data
uploaded, err = clientManager.GetWhatsmeowClient(txtid).Upload(context.Background(), filedata, whatsmeow.MediaDocument)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("failed to upload file: %v", err)))
return
}
}
} else {
s.Respond(w, r, http.StatusBadRequest, errors.New("document data should start with \"data:application/octet-stream;base64,\""))
return
}
msg := &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{
URL: proto.String(uploaded.URL),
FileName: &t.FileName,
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String(func() string {
if t.MimeType != "" {
return t.MimeType
}
return http.DetectContentType(filedata)
}()),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(filedata))),
Caption: proto.String(t.Caption),
}}
if t.ContextInfo.StanzaID != nil {
var qm *waE2E.Message
// If QuotedMessage was provided, use it.
if t.QuotedMessage != nil {
qm = t.QuotedMessage
} else {
// Otherwise, it uses the old logic (empty message).
qm = &waE2E.Message{Conversation: proto.String("")}
}
if msg.DocumentMessage.ContextInfo == nil {
msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{
StanzaID: proto.String(*t.ContextInfo.StanzaID),
Participant: proto.String(*t.ContextInfo.Participant),
QuotedMessage: qm,
}
}
}
if t.ContextInfo.MentionedJID != nil {
if msg.DocumentMessage.ContextInfo == nil {
msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{}
}
msg.DocumentMessage.ContextInfo.MentionedJID = t.ContextInfo.MentionedJID
}
if t.ContextInfo.IsForwarded != nil && *t.ContextInfo.IsForwarded {
if msg.DocumentMessage.ContextInfo == nil {
msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{}
}
msg.DocumentMessage.ContextInfo.IsForwarded = proto.Bool(true)
}
resp, err = clientManager.GetWhatsmeowClient(txtid).SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{ID: msgid})
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New(fmt.Sprintf("Error sending message: %v", err)))
return
}
historyStr := r.Context().Value("userinfo").(Values).Get("History")
historyLimit, _ := strconv.Atoi(historyStr)
s.saveOutgoingMessageToHistory(txtid, recipient.String(), msgid, "document", t.Caption, "", historyLimit)
// Publish sent message event to RabbitMQ
token := r.Context().Value("userinfo").(Values).Get("Token")
userID := r.Context().Value("userinfo").(Values).Get("Id")
s.publishSentMessageEvent(token, userID, txtid, recipient, msgid, msg, resp.Timestamp)
log.Info().Str("timestamp", fmt.Sprintf("%v", resp.Timestamp)).Str("id", msgid).Msg("Message sent")
response := map[string]interface{}{"Details": "Sent", "Timestamp": resp.Timestamp.Unix(), "Id": msgid}
responseJson, err := json.Marshal(response)
if err != nil {
s.Respond(w, r, http.StatusInternalServerError, err)
} else {
s.Respond(w, r, http.StatusOK, string(responseJson))
}
return
}
}
// Sends an audio message
func (s *server) SendAudio() http.HandlerFunc {
type audioStruct struct {
Phone string
Audio string
Caption string
Id string
PTT *bool `json:"ptt,omitempty"`
MimeType string `json:"mimetype,omitempty"`
Seconds uint32
Waveform []byte
ContextInfo waE2E.ContextInfo
QuotedMessage *waE2E.Message `json:"QuotedMessage,omitempty"`
}
return func(w http.ResponseWriter, r *http.Request) {
txtid := r.Context().Value("userinfo").(Values).Get("Id")
msgid := ""
var resp whatsmeow.SendResponse
if clientManager.GetWhatsmeowClient(txtid) == nil {
s.Respond(w, r, http.StatusInternalServerError, errors.New("no session"))
return
}
decoder := json.NewDecoder(r.Body)
var t audioStruct