-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathsend_service.go
More file actions
2665 lines (2330 loc) · 86.7 KB
/
send_service.go
File metadata and controls
2665 lines (2330 loc) · 86.7 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 send_service
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
"image/png"
"io"
"mime/multipart"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
config "github.com/EvolutionAPI/evolution-go/pkg/config"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"github.com/chai2010/webp"
"github.com/gabriel-vasile/mimetype"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
"golang.org/x/net/html"
"google.golang.org/protobuf/proto"
)
type SendService interface {
SendText(data *TextStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendLink(data *LinkStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendMediaUrl(data *MediaStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendMediaFile(data *MediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error)
SendPoll(data *PollStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendSticker(data *StickerStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendLocation(data *LocationStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendContact(data *ContactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendButton(data *ButtonStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
SendList(data *ListStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
}
type sendService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
config *config.Config
loggerWrapper *logger_wrapper.LoggerManager
}
type SendDataStruct struct {
Id string
Number string
Delay int32
MentionAll bool
MentionedJID []string
FormatJid *bool
Quoted QuotedStruct
MediaHandle string
}
type QuotedStruct struct {
MessageID string `json:"messageId"`
Participant string `json:"participant"`
}
type TextStruct struct {
Number string `json:"number"`
Text string `json:"text"`
Id string `json:"id"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type LinkStruct struct {
Number string `json:"number"`
Text string `json:"text"`
Title string `json:"title"`
Url string `json:"url"`
Description string `json:"description"`
ImgUrl string `json:"imgUrl"`
Id string `json:"id"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type MediaStruct struct {
Number string `json:"number"`
Url string `json:"url"`
Type string `json:"type"`
Caption string `json:"caption"`
Filename string `json:"filename"`
Id string `json:"id"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type PollStruct struct {
Id string `json:"id"`
Number string `json:"number"`
Question string `json:"question"`
MaxAnswer int `json:"maxAnswer"`
Options []string `json:"options"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type StickerStruct struct {
Number string `json:"number"`
Sticker string `json:"sticker"`
Id string `json:"id"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
TransparentColor string `json:"transparentColor,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type LocationStruct struct {
Number string `json:"number"`
Id string `json:"id"`
Name string `json:"name"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Address string `json:"address"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type ContactStruct struct {
Number string `json:"number"`
Id string `json:"id"`
Vcard utils.VCardStruct `json:"vcard"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type Button struct {
Type string `json:"type"`
DisplayText string `json:"displayText"`
Id string `json:"id"`
CopyCode string `json:"copyCode"`
URL string `json:"url"`
PhoneNumber string `json:"phoneNumber"`
Currency string `json:"currency"`
Name string `json:"name"`
KeyType string `json:"keyType"`
Key string `json:"key"`
}
type ButtonStruct struct {
Number string `json:"number"`
Title string `json:"title"`
Description string `json:"description"`
Footer string `json:"footer"`
Buttons []Button `json:"buttons"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type Row struct {
Title string `json:"title"`
Description string `json:"description"`
RowId string `json:"rowId"`
}
type Section struct {
Title string `json:"title"`
Rows []Row `json:"rows"`
}
type ListStruct struct {
Number string `json:"number"`
Title string `json:"title"`
Description string `json:"description"`
ButtonText string `json:"buttonText"`
FooterText string `json:"footerText"`
Sections []Section `json:"sections"`
Delay int32 `json:"delay"`
MentionedJID []string `json:"mentionedJid"`
MentionAll bool `json:"mentionAll"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
}
type CarouselButtonStruct struct {
Type string `json:"type"`
DisplayText string `json:"displayText"`
Id string `json:"id"`
CopyCode string `json:"copyCode,omitempty"`
}
type CarouselCardHeaderStruct struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
ImageUrl string `json:"imageUrl,omitempty"`
VideoUrl string `json:"videoUrl,omitempty"`
}
type CarouselCardBodyStruct struct {
Text string `json:"text"`
}
type CarouselCardStruct struct {
Header CarouselCardHeaderStruct `json:"header"`
Body CarouselCardBodyStruct `json:"body"`
Footer string `json:"footer,omitempty"`
Buttons []CarouselButtonStruct `json:"buttons,omitempty"`
}
type CarouselStruct struct {
Number string `json:"number"`
Body string `json:"body,omitempty"`
Footer string `json:"footer,omitempty"`
Delay int32 `json:"delay"`
FormatJid *bool `json:"formatJid,omitempty"`
Quoted QuotedStruct `json:"quoted"`
Cards []CarouselCardStruct `json:"cards"`
}
type MessageSendStruct struct {
Info types.MessageInfo
Message *waE2E.Message
MessageContextInfo *waE2E.ContextInfo
}
func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := s.clientPointer[instanceId]
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := s.whatsmeowService.StartInstance(instanceId)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = s.clientPointer[instanceId]
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
s.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
return nil, errors.New("no active session found")
}
} else if !client.IsConnected() {
s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
// ensureClientConnectedWithRetry attempts to ensure client connection with automatic reconnection and retry
func (s *sendService) ensureClientConnectedWithRetry(instanceId string, maxRetries int) (*whatsmeow.Client, error) {
for attempt := 1; attempt <= maxRetries; attempt++ {
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Connection attempt %d/%d", instanceId, attempt, maxRetries)
client, err := s.ensureClientConnected(instanceId)
if err == nil {
return client, nil
}
// Check if it's a disconnection error that we can retry
if err.Error() == "client disconnected" || err.Error() == "no active session found" {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Client disconnected on attempt %d/%d, attempting reconnection...", instanceId, attempt, maxRetries)
// Attempt to reconnect the client
reconnectErr := s.whatsmeowService.ReconnectClient(instanceId)
if reconnectErr != nil {
s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to reconnect client on attempt %d: %v", instanceId, attempt, reconnectErr)
} else {
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Reconnection initiated on attempt %d, waiting 3 seconds...", instanceId, attempt)
time.Sleep(3 * time.Second)
}
// If this is not the last attempt, continue to retry
if attempt < maxRetries {
waitTime := time.Duration(attempt*2) * time.Second // Progressive backoff
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Waiting %v before retry attempt %d", instanceId, waitTime, attempt+1)
time.Sleep(waitTime)
continue
}
}
// If it's the last attempt or a non-retryable error, return the error
s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to ensure client connection after %d attempts: %v", instanceId, attempt, err)
return nil, err
}
return nil, fmt.Errorf("failed to connect client after %d attempts", maxRetries)
}
func validateMessageFields(phone string, formatJid *bool, messageID *string, participant *string) (types.JID, error) {
// Apply formatting if formatJid is true (default)
shouldFormat := true // Default value
if formatJid != nil {
shouldFormat = *formatJid
}
var finalPhone string
if shouldFormat {
// Extract raw number if it's already a JID, then apply CreateJID formatting
rawNumber := phone
if strings.Contains(phone, "@s.whatsapp.net") {
rawNumber = strings.Split(phone, "@")[0]
}
normalizedJID, err := utils.CreateJID(rawNumber)
if err != nil {
// If CreateJID fails, try with ParseJID as fallback
recipient, ok := utils.ParseJID(phone)
if !ok {
return types.NewJID("", types.DefaultUserServer), fmt.Errorf("could not parse phone: %s", phone)
}
finalPhone = recipient.String()
} else {
finalPhone = normalizedJID
}
} else {
// Use phone as received without formatting
finalPhone = phone
}
recipient, ok := utils.ParseJID(finalPhone)
if !ok {
return types.NewJID("", types.DefaultUserServer), errors.New("could not parse formatted phone")
}
if messageID != nil {
if participant == nil {
return types.NewJID("", types.DefaultUserServer), errors.New("missing Participant in ContextInfo")
}
}
if participant != nil {
if messageID == nil {
return types.NewJID("", types.DefaultUserServer), errors.New("missing StanzaId in ContextInfo")
}
}
return recipient, nil
}
// validateAndCheckUserExists validates message fields and checks if the user exists on WhatsApp
// Now uses the new approach: CheckUser with formatJid=false by default, and uses remoteJID for messaging
func (s *sendService) validateAndCheckUserExists(phone string, formatJid *bool, messageID *string, participant *string, instance *instance_model.Instance) (types.JID, error) {
// Skip WhatsApp check if disabled in config
if !s.config.CheckUserExists {
s.loggerWrapper.GetLogger(instance.Id).LogDebug("[%s] User existence check disabled by configuration", instance.Id)
// Use original validation logic when check is disabled
return validateMessageFields(phone, formatJid, messageID, participant)
}
// Skip WhatsApp check for group messages, broadcast, newsletter, and LID
if strings.Contains(phone, "@g.us") || strings.Contains(phone, "@broadcast") || strings.Contains(phone, "@newsletter") || strings.Contains(phone, "@lid") {
return validateMessageFields(phone, formatJid, messageID, participant)
}
// Get the client to check if user exists on WhatsApp
client, err := s.ensureClientConnected(instance.Id)
if err != nil {
return types.NewJID("", types.DefaultUserServer), fmt.Errorf("failed to connect client: %v", err)
}
// Use CheckUser approach: formatJid=false by default
formatJidForCheck := false
// First attempt with formatJid=false
remoteJID, found, err := s.checkSingleUserExists(client, phone, formatJidForCheck, instance.Id)
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to check user existence: %v", instance.Id, err)
// Continue with sending even if check fails (network issues, etc.)
return validateMessageFields(phone, formatJid, messageID, participant)
}
// If not found with formatJid=false, try with formatJid=true as fallback
if !found {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] User not found with formatJid=false, trying with formatJid=true", instance.Id)
remoteJIDRetry, foundRetry, errRetry := s.checkSingleUserExists(client, phone, true, instance.Id)
if errRetry == nil && foundRetry {
remoteJID = remoteJIDRetry
found = foundRetry
}
}
if !found {
return types.NewJID("", types.DefaultUserServer), fmt.Errorf("number %s is not registered on WhatsApp", phone)
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s verified as valid WhatsApp user, using remoteJID: %s", instance.Id, phone, remoteJID)
// Validate the remoteJID with formatJid=false for message sending
formatJidFalse := false
return validateMessageFields(remoteJID, &formatJidFalse, messageID, participant)
}
// checkSingleUserExists checks if a single user exists on WhatsApp with the specified formatJid setting
// Returns: remoteJID, found, error
func (s *sendService) checkSingleUserExists(client *whatsmeow.Client, phone string, formatJid bool, instanceId string) (string, bool, error) {
phoneNumbers, err := utils.PrepareNumbersForWhatsAppCheck([]string{phone}, &formatJid)
if err != nil {
return "", false, fmt.Errorf("failed to prepare number for WhatsApp check: %v", err)
}
// Check if the number exists on WhatsApp
resp, err := client.IsOnWhatsApp(context.Background(), phoneNumbers)
if err != nil {
return "", false, fmt.Errorf("failed to check if number %s exists on WhatsApp: %v", phoneNumbers[0], err)
}
// Verify if the number was found
if len(resp) == 0 {
return "", false, fmt.Errorf("number %s not found in WhatsApp response", phoneNumbers[0])
}
// Check if the first result indicates the number is on WhatsApp
if !resp[0].IsIn {
return "", false, nil // Not an error, just not found
}
// Return the remoteJID from WhatsApp's response
remoteJID := fmt.Sprintf("%v", resp[0].JID)
return remoteJID, true, nil
}
func findURL(text string) string {
urlRegex := `http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+`
re := regexp.MustCompile(urlRegex)
urls := re.FindAllString(text, -1)
if len(urls) > 0 {
return urls[0]
}
return ""
}
func (s *sendService) SendText(data *TextStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
return s.sendTextWithRetry(data, instance, 3) // 3 tentativas máximas
}
func (s *sendService) sendTextWithRetry(data *TextStruct, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {
for attempt := 1; attempt <= maxRetries; attempt++ {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendText attempt %d/%d", instance.Id, attempt, maxRetries)
_, err := s.ensureClientConnectedWithRetry(instance.Id, 2)
if err != nil {
if attempt == maxRetries {
return nil, err
}
continue
}
msg := &waE2E.Message{
ExtendedTextMessage: &waE2E.ExtendedTextMessage{
Text: &data.Text,
},
}
message, err := s.SendMessage(instance, msg, "ExtendedTextMessage", &SendDataStruct{
Id: data.Id,
Number: data.Number,
Quoted: data.Quoted,
Delay: data.Delay,
MentionAll: data.MentionAll,
MentionedJID: data.MentionedJID,
FormatJid: data.FormatJid,
})
if err != nil {
// Check if it's a client disconnection error
if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {
s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendText failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)
if attempt < maxRetries {
waitTime := time.Duration(attempt) * time.Second
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)
time.Sleep(waitTime)
continue
}
}
return nil, err
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendText successful on attempt %d", instance.Id, attempt)
return message, nil
}
return nil, fmt.Errorf("failed to send text after %d attempts", maxRetries)
}
func fetchLinkMetadata(url string) (string, string, string, error) {
resp, err := http.Get(url)
if err != nil {
return "", "", "", err
}
defer resp.Body.Close()
doc, err := html.Parse(resp.Body)
if err != nil {
return "", "", "", err
}
var title, description, imgURL string
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode {
if n.Data == "title" && n.FirstChild != nil {
title = n.FirstChild.Data
}
if n.Data == "meta" {
var property, content string
for _, attr := range n.Attr {
if attr.Key == "property" || attr.Key == "name" {
property = attr.Val
}
if attr.Key == "content" {
content = attr.Val
}
}
if (property == "description" || property == "og:description") && content != "" {
description = content
}
if property == "og:image" && content != "" {
imgURL = content
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
return title, description, imgURL, nil
}
func (s *sendService) SendLink(data *LinkStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {
return s.sendLinkWithRetry(data, instance, 3)
}
func (s *sendService) sendLinkWithRetry(data *LinkStruct, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {
for attempt := 1; attempt <= maxRetries; attempt++ {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendLink attempt %d/%d", instance.Id, attempt, maxRetries)
_, err := s.ensureClientConnectedWithRetry(instance.Id, 2)
if err != nil {
if attempt == maxRetries {
return nil, err
}
continue
}
matchedText := findURL(data.Text)
if matchedText != "" {
title, description, imgUrl, err := fetchLinkMetadata(matchedText)
if err != nil {
if attempt == maxRetries {
return nil, err
}
continue
}
data.Title = title
data.Description = description
data.ImgUrl = imgUrl
}
var fileData []byte
if data.ImgUrl != "" {
resp, err := http.Get(data.ImgUrl)
if err != nil {
if attempt == maxRetries {
return nil, err
}
continue
}
defer resp.Body.Close()
fileData, _ = io.ReadAll(resp.Body)
}
previewType := waE2E.ExtendedTextMessage_VIDEO
msg := &waE2E.Message{
ExtendedTextMessage: &waE2E.ExtendedTextMessage{
Text: &data.Text,
Title: &data.Title,
MatchedText: &matchedText,
JPEGThumbnail: fileData,
Description: &data.Description,
PreviewType: &previewType,
},
}
message, err := s.SendMessage(instance, msg, "ExtendedTextMessage", &SendDataStruct{
Id: data.Id,
Number: data.Number,
Quoted: data.Quoted,
Delay: data.Delay,
MentionAll: data.MentionAll,
MentionedJID: data.MentionedJID,
FormatJid: data.FormatJid,
})
if err != nil {
// Check if it's a client disconnection error
if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {
s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendLink failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)
if attempt < maxRetries {
waitTime := time.Duration(attempt) * time.Second
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)
time.Sleep(waitTime)
continue
}
}
return nil, err
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendLink successful on attempt %d", instance.Id, attempt)
return message, nil
}
return nil, fmt.Errorf("failed to send link after %d attempts", maxRetries)
}
type ConvertAudio struct {
Url string `json:"url,omitempty"`
Base64 string `json:"base64,omitempty"`
}
type ApiResponse struct {
Duration int `json:"duration"`
Audio string `json:"audio"`
}
func convertAudioWithApi(apiUrl string, apiKey string, convertData ConvertAudio) ([]byte, int, error) {
var requestBody bytes.Buffer
writer := multipart.NewWriter(&requestBody)
// Adiciona o campo "url" ao form-data se a URL for fornecida
if convertData.Url != "" {
err := writer.WriteField("url", convertData.Url)
if err != nil {
return nil, 0, fmt.Errorf("erro ao adicionar a URL no form-data: %v", err)
}
}
// Adiciona o campo "base64" ao form-data se a string base64 for fornecida
if convertData.Base64 != "" {
err := writer.WriteField("base64", convertData.Base64)
if err != nil {
return nil, 0, fmt.Errorf("erro ao adicionar o base64 no form-data: %v", err)
}
}
// Fecha o writer multipart
err := writer.Close()
if err != nil {
return nil, 0, fmt.Errorf("erro ao finalizar o form-data: %v", err)
}
req, err := http.NewRequest("POST", apiUrl, &requestBody)
if err != nil {
return nil, 0, fmt.Errorf("erro ao criar a requisição: %v", err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("apikey", apiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("erro ao enviar a requisição: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, 0, fmt.Errorf("erro ao ler a resposta: %v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, 0, fmt.Errorf("requisição falhou com status: %d, resposta: %s", resp.StatusCode, string(body))
}
var apiResponse ApiResponse
err = json.Unmarshal(body, &apiResponse)
if err != nil {
return nil, 0, fmt.Errorf("erro ao deserializar a resposta: %v", err)
}
base64ToBytes, err := base64.StdEncoding.DecodeString(apiResponse.Audio)
if err != nil {
return nil, 0, fmt.Errorf("erro ao decodificar o áudio: %v", err)
}
return base64ToBytes, apiResponse.Duration, nil
}
func convertAudioToOpusWithDuration(inputData []byte) ([]byte, int, error) {
cmd := exec.Command("ffmpeg", "-i", "pipe:0",
"-f",
"ogg",
"-vn",
"-c:a",
"libopus",
"-avoid_negative_ts",
"make_zero",
"-b:a",
"128k",
"-ar",
"48000",
"-ac",
"1",
"-write_xing",
"0",
"-compression_level",
"10",
"-application",
"voip",
"-fflags",
"+bitexact",
"-flags",
"+bitexact",
"-id3v2_version",
"0",
"-map_metadata",
"-1",
"-map_chapters",
"-1",
"-write_bext",
"0",
"pipe:1",
)
var outBuffer bytes.Buffer
var errBuffer bytes.Buffer
cmd.Stdin = bytes.NewReader(inputData)
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if err != nil {
return nil, 0, fmt.Errorf("error during conversion: %v, details: %s", err, errBuffer.String())
}
convertedData := outBuffer.Bytes()
outputText := errBuffer.String()
splitTime := strings.Split(outputText, "time=")
if len(splitTime) < 2 {
return nil, 0, errors.New("duração não encontrada")
}
// Use the last occurrence of time= in case there are multiple
timeString := splitTime[len(splitTime)-1]
re := regexp.MustCompile(`(\d+):(\d+):(\d+\.\d+)`)
matches := re.FindStringSubmatch(timeString)
if len(matches) != 4 {
return nil, 0, errors.New("formato de duração não encontrado")
}
hours, _ := strconv.ParseFloat(matches[1], 64)
minutes, _ := strconv.ParseFloat(matches[2], 64)
seconds, _ := strconv.ParseFloat(matches[3], 64)
duration := int(hours*3600 + minutes*60 + seconds)
return convertedData, duration, nil
}
func (s *sendService) SendMediaFile(data *MediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error) {
return s.sendMediaFileWithRetry(data, fileData, instance, 3)
}
func (s *sendService) sendMediaFileWithRetry(data *MediaStruct, fileData []byte, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {
for attempt := 1; attempt <= maxRetries; attempt++ {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaFile attempt %d/%d", instance.Id, attempt, maxRetries)
client, err := s.ensureClientConnectedWithRetry(instance.Id, 2)
if err != nil {
if attempt == maxRetries {
return nil, err
}
continue
}
mime, _ := mimetype.DetectReader(bytes.NewReader(fileData))
mimeType := mime.String()
var uploadType whatsmeow.MediaType
var duration int
switch data.Type {
case "image":
if mimeType != "image/jpeg" && mimeType != "image/png" && mimeType != "image/webp" {
errMsg := fmt.Sprintf("Invalid file format: '%s'. Only 'image/jpeg', 'image/png' and 'image/webp' are accepted", mimeType)
return nil, errors.New(errMsg)
}
if mimeType == "image/webp" {
mimeType = "image/jpeg"
}
uploadType = whatsmeow.MediaImage
case "video":
if mimeType != "video/mp4" {
errMsg := fmt.Sprintf("Invalid file format: '%s'. Only 'video/mp4' is accepted", mimeType)
return nil, errors.New(errMsg)
}
uploadType = whatsmeow.MediaVideo
case "audio":
converterApiUrl := s.config.ApiAudioConverter
converterApiKey := s.config.ApiAudioConverterKey
var convertedData []byte
var err error
if converterApiUrl == "" {
convertedData, duration, err = convertAudioToOpusWithDuration(fileData)
if err != nil {
return nil, err
}
} else {
convertedData, duration, err = convertAudioWithApi(converterApiUrl, converterApiKey, ConvertAudio{Base64: base64.StdEncoding.EncodeToString(fileData)})
if err != nil {
return nil, err
}
}
fileData = convertedData
mimeType = "audio/ogg; codecs=opus"
uploadType = whatsmeow.MediaAudio
case "document":
uploadType = whatsmeow.MediaDocument
default:
return nil, errors.New("invalid media type")
}
// Detectar se é newsletter para usar upload sem criptografia
isNewsletter := strings.Contains(data.Number, "@newsletter")
// Validar se é documento em newsletter (não suportado)
if isNewsletter && data.Type == "document" {
return nil, errors.New("documentos não são suportados em canais do WhatsApp. Use imagem, vídeo, áudio ou enquete")
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaFile - Upload iniciado (Newsletter: %v)...", instance.Id, isNewsletter)
var uploaded whatsmeow.UploadResponse
if isNewsletter {
// Newsletter: upload SEM criptografia
uploaded, err = client.UploadNewsletter(context.Background(), fileData, uploadType)
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Newsletter upload - Handle: %s", instance.Id, uploaded.Handle)
} else {
// Normal: upload COM criptografia
uploaded, err = client.Upload(context.Background(), fileData, uploadType)
}
if err != nil {
return nil, err
}
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Media uploaded with size %d", instance.Id, uploaded.FileLength)
var media *waE2E.Message
var mediaType string
switch data.Type {
case "image":
if isNewsletter {
// Newsletter: SEM MediaKey e FileEncSHA256
media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{
Caption: proto.String(data.Caption),
URL: &uploaded.URL,
DirectPath: &uploaded.DirectPath,
Mimetype: proto.String(mimeType),
FileSHA256: uploaded.FileSHA256,
FileLength: &uploaded.FileLength,
}}
} else {
// Normal: COM MediaKey e FileEncSHA256
media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{
Caption: proto.String(data.Caption),
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String(mimeType),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
}}
}
mediaType = "ImageMessage"
case "video":
lowerMimeType := strings.ToLower(mimeType)
isGif := strings.HasPrefix(lowerMimeType, "image/gif") || strings.HasPrefix(lowerMimeType, "video/gif")
if isNewsletter {
media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{
Caption: proto.String(data.Caption),
URL: &uploaded.URL,
DirectPath: &uploaded.DirectPath,
Mimetype: proto.String(mimeType),
FileSHA256: uploaded.FileSHA256,
FileLength: &uploaded.FileLength,
GifPlayback: proto.Bool(isGif),
}}
} else {
media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{
Caption: proto.String(data.Caption),
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String(mimeType),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
GifPlayback: proto.Bool(isGif),
}}
}
mediaType = "VideoMessage"
case "ptv":
if isNewsletter {
media = &waE2E.Message{PtvMessage: &waE2E.VideoMessage{
URL: &uploaded.URL,
DirectPath: &uploaded.DirectPath,
Mimetype: proto.String(mimeType),
FileSHA256: uploaded.FileSHA256,
FileLength: &uploaded.FileLength,
}}
} else {
media = &waE2E.Message{PtvMessage: &waE2E.VideoMessage{
URL: proto.String(uploaded.URL),
DirectPath: proto.String(uploaded.DirectPath),
MediaKey: uploaded.MediaKey,
Mimetype: proto.String(mimeType),
FileEncSHA256: uploaded.FileEncSHA256,
FileSHA256: uploaded.FileSHA256,
FileLength: proto.Uint64(uint64(len(fileData))),
}}
}
mediaType = "PtvMessage"
case "audio":
if isNewsletter {
media = &waE2E.Message{AudioMessage: &waE2E.AudioMessage{
URL: &uploaded.URL,
PTT: proto.Bool(true),
DirectPath: &uploaded.DirectPath,
Mimetype: proto.String(mimeType),
FileSHA256: uploaded.FileSHA256,
FileLength: &uploaded.FileLength,
Seconds: proto.Uint32(uint32(duration)),
}}
} else {
media = &waE2E.Message{AudioMessage: &waE2E.AudioMessage{
URL: proto.String(uploaded.URL),