forked from mautrix/whatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
1629 lines (1523 loc) · 55 KB
/
user.go
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
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2024 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/rs/zerolog"
"go.mau.fi/util/exzerolog"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
waProto "go.mau.fi/whatsmeow/binary/proto"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
waLog "go.mau.fi/whatsmeow/util/log"
"golang.org/x/sync/semaphore"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/bridge"
"maunium.net/go/mautrix/bridge/bridgeconfig"
"maunium.net/go/mautrix/bridge/status"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/pushrules"
"maunium.net/go/mautrix-whatsapp/database"
)
type User struct {
*database.User
Client *whatsmeow.Client
Session *store.Device
bridge *WABridge
zlog zerolog.Logger
Admin bool
Whitelisted bool
RelayWhitelisted bool
PermissionLevel bridgeconfig.PermissionLevel
mgmtCreateLock sync.Mutex
spaceCreateLock sync.Mutex
connLock sync.Mutex
historySyncs chan *events.HistorySync
lastPresence types.Presence
mediaRetryLock *semaphore.Weighted
historySyncLoopsStarted bool
enqueueBackfillsTimer *time.Timer
spaceMembershipChecked bool
lastPhoneOfflineWarning time.Time
groupListCache []*types.GroupInfo
groupListCacheLock sync.Mutex
groupListCacheTime time.Time
BackfillQueue *BackfillQueue
BridgeState *bridge.BridgeStateQueue
resyncQueue map[types.JID]resyncQueueItem
resyncQueueLock sync.Mutex
nextResync time.Time
createKeyDedup string
skipGroupCreateDelay types.JID
groupJoinLock sync.Mutex
}
type resyncQueueItem struct {
portal *Portal
puppet *Puppet
}
func (br *WABridge) getUserByMXID(userID id.UserID, onlyIfExists bool) *User {
_, isPuppet := br.ParsePuppetMXID(userID)
if isPuppet || userID == br.Bot.UserID {
return nil
}
br.usersLock.Lock()
defer br.usersLock.Unlock()
user, ok := br.usersByMXID[userID]
if !ok {
userIDPtr := &userID
if onlyIfExists {
userIDPtr = nil
}
ctx := context.TODO()
dbUser, err := br.DB.User.GetByMXID(ctx, userID)
if err != nil {
br.ZLog.Err(err).Stringer("mxid", userID).Msg("Failed to get user by MXID from database")
return nil
}
return br.loadDBUser(ctx, dbUser, userIDPtr)
}
return user
}
func (br *WABridge) GetUserByMXID(userID id.UserID) *User {
return br.getUserByMXID(userID, false)
}
func (br *WABridge) GetIUser(userID id.UserID, create bool) bridge.User {
u := br.getUserByMXID(userID, !create)
if u == nil {
return nil
}
return u
}
func (user *User) GetPermissionLevel() bridgeconfig.PermissionLevel {
return user.PermissionLevel
}
func (user *User) GetManagementRoomID() id.RoomID {
return user.ManagementRoom
}
func (user *User) GetMXID() id.UserID {
return user.MXID
}
func (user *User) GetCommandState() map[string]interface{} {
return nil
}
func (br *WABridge) GetUserByMXIDIfExists(userID id.UserID) *User {
return br.getUserByMXID(userID, true)
}
func (br *WABridge) GetUserByJID(jid types.JID) *User {
br.usersLock.Lock()
defer br.usersLock.Unlock()
user, ok := br.usersByUsername[jid.User]
if !ok {
ctx := context.TODO()
dbUser, err := br.DB.User.GetByUsername(ctx, jid.User)
if err != nil {
br.ZLog.Err(err).Stringer("jid", jid).Msg("Failed to get user by JID from database")
return nil
}
return br.loadDBUser(ctx, dbUser, nil)
}
return user
}
func (user *User) addToJIDMap() {
user.bridge.usersLock.Lock()
user.bridge.usersByUsername[user.JID.User] = user
user.bridge.usersLock.Unlock()
}
func (user *User) removeFromJIDMap(state status.BridgeState) {
user.bridge.usersLock.Lock()
jidUser, ok := user.bridge.usersByUsername[user.JID.User]
if ok && user == jidUser {
delete(user.bridge.usersByUsername, user.JID.User)
}
user.bridge.usersLock.Unlock()
user.bridge.Metrics.TrackLoginState(user.JID, false)
user.BridgeState.Send(state)
}
func (br *WABridge) GetAllUsers() []*User {
br.usersLock.Lock()
defer br.usersLock.Unlock()
ctx := context.TODO()
dbUsers, err := br.DB.User.GetAll(ctx)
if err != nil {
br.ZLog.Error().Err(err).Msg("Failed to get all users from database")
return nil
}
output := make([]*User, len(dbUsers))
for index, dbUser := range dbUsers {
user, ok := br.usersByMXID[dbUser.MXID]
if !ok {
user = br.loadDBUser(ctx, dbUser, nil)
}
output[index] = user
}
return output
}
func (br *WABridge) loadDBUser(ctx context.Context, dbUser *database.User, mxid *id.UserID) *User {
if dbUser == nil {
if mxid == nil {
return nil
}
dbUser = br.DB.User.New()
dbUser.MXID = *mxid
err := dbUser.Insert(ctx)
if err != nil {
br.ZLog.Error().Err(err).Msg("Failed to insert new user into database")
return nil
}
}
user := br.NewUser(dbUser)
br.usersByMXID[user.MXID] = user
if !user.JID.IsEmpty() {
var err error
user.Session, err = br.WAContainer.GetDevice(user.JID)
if err != nil {
user.zlog.Err(err).Msg("Failed to load user's whatsapp session")
} else if user.Session == nil {
user.zlog.Warn().Stringer("jid", user.JID).Msg("Didn't find session data for user's JID, treating user as logged out")
user.JID = types.EmptyJID
err = user.Update(ctx)
if err != nil {
user.zlog.Err(err).Msg("Failed to save user after clearing JID")
}
} else {
user.Session.Log = waLog.Zerolog(user.zlog.With().Str("component", "whatsmeow").Str("db_section", "whatsmeow").Logger())
br.usersByUsername[user.JID.User] = user
}
}
if len(user.ManagementRoom) > 0 {
br.managementRooms[user.ManagementRoom] = user
}
return user
}
func (br *WABridge) NewUser(dbUser *database.User) *User {
user := &User{
User: dbUser,
bridge: br,
zlog: br.ZLog.With().Str("user_id", dbUser.MXID.String()).Logger(),
historySyncs: make(chan *events.HistorySync, 32),
lastPresence: types.PresenceUnavailable,
resyncQueue: make(map[types.JID]resyncQueueItem),
mediaRetryLock: semaphore.NewWeighted(br.Config.Bridge.HistorySync.MediaRequests.MaxAsyncHandle),
}
user.PermissionLevel = user.bridge.Config.Bridge.Permissions.Get(user.MXID)
user.RelayWhitelisted = user.PermissionLevel >= bridgeconfig.PermissionLevelRelay
user.Whitelisted = user.PermissionLevel >= bridgeconfig.PermissionLevelUser
user.Admin = user.PermissionLevel >= bridgeconfig.PermissionLevelAdmin
user.BridgeState = br.NewBridgeStateQueue(user)
user.enqueueBackfillsTimer = time.NewTimer(5 * time.Second)
user.enqueueBackfillsTimer.Stop()
go user.puppetResyncLoop()
return user
}
const resyncMinInterval = 7 * 24 * time.Hour
const resyncLoopInterval = 4 * time.Hour
func (user *User) puppetResyncLoop() {
user.nextResync = time.Now().Add(resyncLoopInterval).Add(-time.Duration(rand.Intn(3600)) * time.Second)
for {
time.Sleep(user.nextResync.Sub(time.Now()))
user.nextResync = time.Now().Add(resyncLoopInterval)
user.doPuppetResync()
}
}
func (user *User) EnqueuePuppetResync(puppet *Puppet) {
if puppet.LastSync.Add(resyncMinInterval).After(time.Now()) {
return
}
user.resyncQueueLock.Lock()
if _, exists := user.resyncQueue[puppet.JID]; !exists {
user.resyncQueue[puppet.JID] = resyncQueueItem{puppet: puppet}
user.zlog.Debug().
Stringer("jid", puppet.JID).
Str("next_resync", time.Until(user.nextResync).String()).
Msg("Enqueued resync for puppet")
}
user.resyncQueueLock.Unlock()
}
func (user *User) EnqueuePortalResync(portal *Portal) {
if !portal.IsGroupChat() || portal.LastSync.Add(resyncMinInterval).After(time.Now()) {
return
}
user.resyncQueueLock.Lock()
if _, exists := user.resyncQueue[portal.Key.JID]; !exists {
user.resyncQueue[portal.Key.JID] = resyncQueueItem{portal: portal}
user.zlog.Debug().
Stringer("jid", portal.Key.JID).
Str("next_resync", time.Until(user.nextResync).String()).
Msg("Enqueued resync for portal")
}
user.resyncQueueLock.Unlock()
}
func (user *User) doPuppetResync() {
if !user.IsLoggedIn() {
return
}
user.resyncQueueLock.Lock()
if len(user.resyncQueue) == 0 {
user.resyncQueueLock.Unlock()
return
}
log := user.zlog.With().Str("action", "puppet resync").Logger()
ctx := log.WithContext(context.TODO())
queue := user.resyncQueue
user.resyncQueue = make(map[types.JID]resyncQueueItem)
user.resyncQueueLock.Unlock()
var puppetJIDs []types.JID
var puppets []*Puppet
var portals []*Portal
for jid, item := range queue {
var lastSync time.Time
if item.puppet != nil {
lastSync = item.puppet.LastSync
} else if item.portal != nil {
lastSync = item.portal.LastSync
}
if lastSync.Add(resyncMinInterval).After(time.Now()) {
log.Debug().
Stringer("jid", jid).
Str("last_sync", time.Since(lastSync).String()).
Msg("Not resyncing, last sync was too recent")
continue
}
if item.puppet != nil {
puppets = append(puppets, item.puppet)
puppetJIDs = append(puppetJIDs, jid)
} else if item.portal != nil {
portals = append(portals, item.portal)
}
}
for _, portal := range portals {
groupInfo, err := user.Client.GetGroupInfo(portal.Key.JID)
if err != nil {
log.Warn().Err(err).Stringer("jid", portal.Key.JID).Msg("Failed to get group info for background sync")
} else {
log.Debug().Stringer("jid", portal.Key.JID).Msg("Doing background sync for group")
portal.UpdateMatrixRoom(ctx, user, groupInfo, nil)
}
}
if len(puppetJIDs) == 0 {
return
}
log.Debug().Array("jids", exzerolog.ArrayOfStringers(puppetJIDs)).Msg("Doing background sync for users")
infos, err := user.Client.GetUserInfo(puppetJIDs)
if err != nil {
log.Err(err).Msg("Failed to get user info for background sync")
return
}
for _, puppet := range puppets {
info, ok := infos[puppet.JID]
if !ok {
log.Warn().Stringer("jid", puppet.JID).Msg("Didn't get info for puppet in background sync")
continue
}
var contactPtr *types.ContactInfo
contact, err := user.Session.Contacts.GetContact(puppet.JID)
if err != nil {
log.Err(err).Stringer("jid", puppet.JID).Msg("Failed to get contact info for puppet in background sync")
} else if contact.Found {
contactPtr = &contact
}
puppet.Sync(ctx, user, contactPtr, info.PictureID != "" && info.PictureID != puppet.Avatar, true)
}
}
func (user *User) ensureInvited(ctx context.Context, intent *appservice.IntentAPI, roomID id.RoomID, isDirect bool) (ok bool) {
extraContent := make(map[string]interface{})
if isDirect {
extraContent["is_direct"] = true
}
customPuppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
if customPuppet != nil && customPuppet.CustomIntent() != nil {
extraContent["fi.mau.will_auto_accept"] = true
}
_, err := intent.InviteUser(ctx, roomID, &mautrix.ReqInviteUser{UserID: user.MXID}, extraContent)
var httpErr mautrix.HTTPError
if err != nil && errors.As(err, &httpErr) && httpErr.RespError != nil && strings.Contains(httpErr.RespError.Err, "is already in the room") {
err = user.bridge.StateStore.SetMembership(ctx, roomID, user.MXID, event.MembershipJoin)
if err != nil {
user.zlog.Err(err).Stringer("room_id", roomID).Msg("Failed to update membership to join in state store after invite failed")
}
ok = true
return
} else if err != nil {
user.zlog.Err(err).Stringer("room_id", roomID).Msg("Failed to invite user to room")
} else {
ok = true
}
if customPuppet != nil && customPuppet.CustomIntent() != nil {
err = customPuppet.CustomIntent().EnsureJoined(ctx, roomID, appservice.EnsureJoinedParams{IgnoreCache: true})
if err != nil {
user.zlog.Err(err).Stringer("room_id", roomID).Msg("Failed to auto-join room")
ok = false
} else {
ok = true
}
}
return
}
func (user *User) GetSpaceRoom(ctx context.Context) id.RoomID {
if !user.bridge.Config.Bridge.PersonalFilteringSpaces {
return ""
}
if len(user.SpaceRoom) == 0 {
user.spaceCreateLock.Lock()
defer user.spaceCreateLock.Unlock()
if len(user.SpaceRoom) > 0 {
return user.SpaceRoom
}
resp, err := user.bridge.Bot.CreateRoom(ctx, &mautrix.ReqCreateRoom{
Visibility: "private",
Name: "WhatsApp",
Topic: "Your WhatsApp bridged chats",
InitialState: []*event.Event{{
Type: event.StateRoomAvatar,
Content: event.Content{
Parsed: &event.RoomAvatarEventContent{
URL: user.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
},
},
}},
CreationContent: map[string]interface{}{
"type": event.RoomTypeSpace,
},
PowerLevelOverride: &event.PowerLevelsEventContent{
Users: map[id.UserID]int{
user.bridge.Bot.UserID: 9001,
user.MXID: 50,
},
},
})
if err != nil {
user.zlog.Err(err).Msg("Failed to auto-create space room")
} else {
user.SpaceRoom = resp.RoomID
err = user.Update(ctx)
if err != nil {
user.zlog.Err(err).Msg("Failed to save user after creating space room")
}
user.ensureInvited(ctx, user.bridge.Bot, user.SpaceRoom, false)
}
} else if !user.spaceMembershipChecked && !user.bridge.StateStore.IsInRoom(ctx, user.SpaceRoom, user.MXID) {
user.ensureInvited(ctx, user.bridge.Bot, user.SpaceRoom, false)
}
user.spaceMembershipChecked = true
return user.SpaceRoom
}
func (user *User) GetManagementRoom(ctx context.Context) id.RoomID {
if len(user.ManagementRoom) == 0 {
user.mgmtCreateLock.Lock()
defer user.mgmtCreateLock.Unlock()
if len(user.ManagementRoom) > 0 {
return user.ManagementRoom
}
creationContent := make(map[string]interface{})
if !user.bridge.Config.Bridge.FederateRooms {
creationContent["m.federate"] = false
}
resp, err := user.bridge.Bot.CreateRoom(ctx, &mautrix.ReqCreateRoom{
Topic: "WhatsApp bridge notices",
IsDirect: true,
CreationContent: creationContent,
})
if err != nil {
user.zlog.Err(err).Msg("Failed to auto-create management room")
} else {
user.SetManagementRoom(resp.RoomID)
}
}
return user.ManagementRoom
}
func (user *User) SetManagementRoom(roomID id.RoomID) {
ctx := context.TODO()
existingUser, ok := user.bridge.managementRooms[roomID]
if ok {
existingUser.ManagementRoom = ""
err := existingUser.Update(ctx)
if err != nil {
user.zlog.Err(err).
Stringer("other_user_mxid", existingUser.MXID).
Msg("Failed to save previous user after removing from old management room")
}
}
user.ManagementRoom = roomID
user.bridge.managementRooms[user.ManagementRoom] = user
err := user.Update(ctx)
if err != nil {
user.zlog.Err(err).Msg("Failed to save user after setting management room")
}
}
var ErrAlreadyLoggedIn = errors.New("already logged in")
func (user *User) obfuscateJID(jid types.JID) string {
// Turn the first 4 bytes of HMAC-SHA256(hs_token, phone) into a number and replace the middle of the actual phone with that deterministic random number.
randomNumber := binary.BigEndian.Uint32(hmac.New(sha256.New, []byte(user.bridge.Config.AppService.HSToken)).Sum([]byte(jid.User))[:4])
return fmt.Sprintf("+%s-%d-%s:%d", jid.User[:1], randomNumber, jid.User[len(jid.User)-2:], jid.Device)
}
func (user *User) createClient(sess *store.Device) {
user.Client = whatsmeow.NewClient(sess, waLog.Zerolog(user.zlog.With().Str("component", "whatsmeow").Logger()))
user.Client.AddEventHandler(user.HandleEvent)
user.Client.SetForceActiveDeliveryReceipts(user.bridge.Config.Bridge.ForceActiveDeliveryReceipts)
user.Client.AutomaticMessageRerequestFromPhone = true
user.Client.GetMessageForRetry = func(requester, to types.JID, id types.MessageID) *waProto.Message {
Analytics.Track(user.MXID, "WhatsApp incoming retry (message not found)", map[string]interface{}{
"requester": user.obfuscateJID(requester),
"messageID": id,
})
user.bridge.Metrics.TrackRetryReceipt(0, false)
return nil
}
user.Client.PreRetryCallback = func(receipt *events.Receipt, messageID types.MessageID, retryCount int, msg *waProto.Message) bool {
Analytics.Track(user.MXID, "WhatsApp incoming retry (accepted)", map[string]interface{}{
"requester": user.obfuscateJID(receipt.Sender),
"messageID": messageID,
"retryCount": retryCount,
})
user.bridge.Metrics.TrackRetryReceipt(retryCount, true)
return true
}
if !user.bridge.Config.WhatsApp.ProxyOnlyLogin || sess.ID == nil {
if proxy, err := user.getProxy("login"); err != nil {
user.zlog.Err(err).Msg("Failed to get proxy address")
} else if err = user.Client.SetProxyAddress(proxy, whatsmeow.SetProxyOptions{
NoMedia: user.bridge.Config.WhatsApp.ProxyOnlyLogin,
}); err != nil {
user.zlog.Err(err).Msg("Failed to set proxy address")
}
}
if user.bridge.Config.WhatsApp.ProxyOnlyLogin {
user.Client.ToggleProxyOnlyForLogin(true)
}
}
type respGetProxy struct {
ProxyURL string `json:"proxy_url"`
}
func (user *User) getProxy(reason string) (string, error) {
if user.bridge.Config.WhatsApp.GetProxyURL == "" {
return user.bridge.Config.WhatsApp.Proxy, nil
}
parsed, err := url.Parse(user.bridge.Config.WhatsApp.GetProxyURL)
if err != nil {
return "", fmt.Errorf("failed to parse address: %w", err)
}
q := parsed.Query()
q.Set("reason", reason)
parsed.RawQuery = q.Encode()
req, err := http.NewRequest(http.MethodGet, parsed.String(), nil)
if err != nil {
return "", fmt.Errorf("failed to prepare request: %w", err)
}
req.Header.Set("User-Agent", mautrix.DefaultUserAgent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("failed to send request: %w", err)
} else if resp.StatusCode >= 300 || resp.StatusCode < 200 {
return "", fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
var respData respGetProxy
err = json.NewDecoder(resp.Body).Decode(&respData)
if err != nil {
return "", fmt.Errorf("failed to decode response: %w", err)
}
return respData.ProxyURL, nil
}
func (user *User) Login(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error) {
user.connLock.Lock()
defer user.connLock.Unlock()
if user.Session != nil {
return nil, ErrAlreadyLoggedIn
} else if user.Client != nil {
user.unlockedDeleteConnection()
}
newSession := user.bridge.WAContainer.NewDevice()
newSession.Log = waLog.Zerolog(user.zlog.With().Str("component", "whatsmeow session").Logger())
user.createClient(newSession)
qrChan, err := user.Client.GetQRChannel(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get QR channel: %w", err)
}
err = user.Client.Connect()
if err != nil {
return nil, fmt.Errorf("failed to connect to WhatsApp: %w", err)
}
return qrChan, nil
}
func (user *User) Connect() bool {
user.connLock.Lock()
defer user.connLock.Unlock()
if user.Client != nil {
return user.Client.IsConnected()
} else if user.Session == nil {
return false
}
user.zlog.Debug().Msg("Connecting to WhatsApp")
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateConnecting, Error: WAConnecting})
user.createClient(user.Session)
err := user.Client.Connect()
if err != nil {
user.zlog.Err(err).Msg("Error connecting to WhatsApp")
user.BridgeState.Send(status.BridgeState{
StateEvent: status.StateUnknownError,
Error: WAConnectionFailed,
Info: map[string]interface{}{
"go_error": err.Error(),
},
})
return false
}
return true
}
func (user *User) unlockedDeleteConnection() {
if user.Client == nil {
return
}
user.Client.Disconnect()
user.Client.RemoveEventHandlers()
user.Client = nil
user.bridge.Metrics.TrackConnectionState(user.JID, false)
}
func (user *User) DeleteConnection() {
user.connLock.Lock()
defer user.connLock.Unlock()
user.unlockedDeleteConnection()
}
func (user *User) HasSession() bool {
return user.Session != nil
}
func (user *User) DeleteSession(ctx context.Context) {
log := zerolog.Ctx(ctx)
if user.Session != nil {
err := user.Session.Delete()
if err != nil {
log.Err(err).Msg("Failed to delete session")
}
user.Session = nil
}
if !user.JID.IsEmpty() {
user.JID = types.EmptyJID
err := user.Update(ctx)
if err != nil {
log.Err(err).Msg("Failed to save user after clearing JID")
}
}
// Delete all of the backfill and history sync data.
err := user.bridge.DB.BackfillQueue.DeleteAll(ctx, user.MXID)
if err != nil {
log.Err(err).Msg("Failed to delete backfill queue data")
}
err = user.bridge.DB.HistorySync.DeleteAllConversations(ctx, user.MXID)
if err != nil {
log.Err(err).Msg("Failed to delete historical conversation list")
}
err = user.bridge.DB.HistorySync.DeleteAllMessages(ctx, user.MXID)
if err != nil {
log.Err(err).Msg("Failed to delete historical messages")
}
err = user.bridge.DB.MediaBackfillRequest.DeleteAllMediaBackfillRequests(ctx, user.MXID)
if err != nil {
log.Err(err).Msg("Failed to delete media backfill requests")
}
}
func (user *User) IsConnected() bool {
return user.Client != nil && user.Client.IsConnected()
}
func (user *User) IsLoggedIn() bool {
return user.IsConnected() && user.Client.IsLoggedIn()
}
func (user *User) sendMarkdownBridgeAlert(ctx context.Context, formatString string, args ...interface{}) {
if user.bridge.Config.Bridge.DisableBridgeAlerts {
return
}
notice := fmt.Sprintf(formatString, args...)
content := format.RenderMarkdown(notice, true, false)
_, err := user.bridge.Bot.SendMessageEvent(ctx, user.GetManagementRoom(ctx), event.EventMessage, content)
if err != nil {
user.zlog.Warn().Err(err).Str("notice", notice).Msg("Failed to send bridge alert")
}
}
const callEventMaxAge = 15 * time.Minute
func (user *User) handleCallStart(sender types.JID, id, callType string, ts time.Time) {
if !user.bridge.Config.Bridge.CallStartNotices || ts.Add(callEventMaxAge).Before(time.Now()) {
return
}
portal := user.GetPortalByJID(sender)
text := "Incoming call. Use the WhatsApp app to answer."
if callType != "" {
text = fmt.Sprintf("Incoming %s call. Use the WhatsApp app to answer.", callType)
}
portal.events <- &PortalEvent{
Message: &PortalMessage{
fake: &fakeMessage{
Sender: sender,
Text: text,
ID: id,
Time: ts,
Important: true,
},
source: user,
},
}
}
const PhoneDisconnectWarningTime = 12 * 24 * time.Hour // 12 days
const PhoneDisconnectPingTime = 10 * 24 * time.Hour
const PhoneMinPingInterval = 24 * time.Hour
func (user *User) sendHackyPhonePing(ctx context.Context) {
user.PhoneLastPinged = time.Now()
msgID := user.Client.GenerateMessageID()
keyIDs := make([]*waProto.AppStateSyncKeyId, 0, 1)
lastKeyID, err := user.GetLastAppStateKeyID(ctx)
if lastKeyID != nil {
keyIDs = append(keyIDs, &waProto.AppStateSyncKeyId{
KeyID: lastKeyID,
})
} else {
user.zlog.Warn().Err(err).Msg("Failed to get last app state key ID to send hacky phone ping - sending empty request")
}
resp, err := user.Client.SendMessage(ctx, user.JID.ToNonAD(), &waProto.Message{
ProtocolMessage: &waProto.ProtocolMessage{
Type: waProto.ProtocolMessage_APP_STATE_SYNC_KEY_REQUEST.Enum(),
AppStateSyncKeyRequest: &waProto.AppStateSyncKeyRequest{
KeyIDs: keyIDs,
},
},
}, whatsmeow.SendRequestExtra{Peer: true, ID: msgID})
if err != nil {
user.zlog.Err(err).Msg("Failed to send hacky phone ping")
} else {
user.zlog.Debug().
Str("message_id", msgID).
Int64("message_ts", resp.Timestamp.Unix()).
Msg("Sent hacky phone ping because phone has been offline for >10 days")
user.PhoneLastPinged = resp.Timestamp
err = user.Update(ctx)
if err != nil {
user.zlog.Err(err).Msg("Failed to save user after sending hacky phone ping")
}
}
}
func (user *User) PhoneRecentlySeen(doPing bool) bool {
if doPing && !user.PhoneLastSeen.IsZero() && user.PhoneLastSeen.Add(PhoneDisconnectPingTime).Before(time.Now()) && user.PhoneLastPinged.Add(PhoneMinPingInterval).Before(time.Now()) {
// Over 10 days since the phone was seen and over a day since the last somewhat hacky ping, send a new ping.
go user.sendHackyPhonePing(context.TODO())
}
return user.PhoneLastSeen.IsZero() || user.PhoneLastSeen.Add(PhoneDisconnectWarningTime).After(time.Now())
}
// phoneSeen records a timestamp when the user's main device was seen online.
// The stored timestamp can later be used to warn the user if the main device is offline for too long.
func (user *User) phoneSeen(ts time.Time) {
if user.PhoneLastSeen.Add(1 * time.Hour).After(ts) {
// The last seen timestamp isn't going to be perfectly accurate in any case,
// so don't spam the database with an update every time there's an event.
return
} else if !user.PhoneRecentlySeen(false) {
if user.BridgeState.GetPrev().Error == WAPhoneOffline && user.IsConnected() {
user.zlog.Debug().Msg("Saw phone after current bridge state said it has been offline, switching state back to connected")
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateConnected})
} else {
user.zlog.Debug().
Bool("is_connected", user.IsConnected()).
Str("prev_error", string(user.BridgeState.GetPrev().Error)).
Msg("Saw phone after current bridge state said it has been offline, not sending new bridge state")
}
}
user.PhoneLastSeen = ts
go func() {
err := user.Update(context.TODO())
if err != nil {
user.zlog.Err(err).Msg("Failed to save user after updating phone last seen")
}
}()
}
func formatDisconnectTime(dur time.Duration) string {
days := int(math.Floor(dur.Hours() / 24))
hours := int(dur.Hours()) % 24
if hours == 0 {
return fmt.Sprintf("%d days", days)
} else if hours == 1 {
return fmt.Sprintf("%d days and 1 hour", days)
} else {
return fmt.Sprintf("%d days and %d hours", days, hours)
}
}
func (user *User) sendPhoneOfflineWarning(ctx context.Context) {
if user.lastPhoneOfflineWarning.Add(12 * time.Hour).After(time.Now()) {
// Don't spam the warning too much
return
}
user.lastPhoneOfflineWarning = time.Now()
timeSinceSeen := time.Now().Sub(user.PhoneLastSeen)
user.sendMarkdownBridgeAlert(ctx, "Your phone hasn't been seen in %s. The server will force the bridge to log out if the phone is not active at least every 2 weeks.", formatDisconnectTime(timeSinceSeen))
}
func (user *User) HandleEvent(event interface{}) {
ctx := user.zlog.With().
Str("action", "handle whatsapp event").
Type("wa_event_type", event).
Logger().
WithContext(context.TODO())
switch v := event.(type) {
case *events.LoggedOut:
go user.handleLoggedOut(ctx, v.OnConnect, v.Reason)
case *events.Connected:
user.bridge.Metrics.TrackConnectionState(user.JID, true)
user.bridge.Metrics.TrackLoginState(user.JID, true)
if len(user.Client.Store.PushName) > 0 {
go func() {
err := user.Client.SendPresence(user.lastPresence)
if err != nil {
user.zlog.Warn().Err(err).Msg("Failed to send initial presence after connecting")
}
}()
}
go user.tryAutomaticDoublePuppeting()
if user.bridge.Config.Bridge.HistorySync.Backfill && !user.historySyncLoopsStarted {
go user.handleHistorySyncsLoop()
user.historySyncLoopsStarted = true
}
case *events.OfflineSyncPreview:
user.zlog.Info().
Int("message_count", v.Messages).
Int("receipt_count", v.Receipts).
Int("notification_count", v.Notifications).
Int("app_data_change_count", v.AppDataChanges).
Msg("Server sent number of events that were missed during downtime")
user.BridgeState.Send(status.BridgeState{
StateEvent: status.StateBackfilling,
Message: fmt.Sprintf("backfilling %d messages and %d receipts", v.Messages, v.Receipts),
})
case *events.OfflineSyncCompleted:
if !user.PhoneRecentlySeen(true) {
user.zlog.Info().
Time("phone_last_seen", user.PhoneLastSeen).
Msg("Offline sync completed, but phone last seen date is still old - sending phone offline bridge status")
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WAPhoneOffline})
} else {
if user.BridgeState.GetPrev().StateEvent == status.StateBackfilling {
user.zlog.Info().Msg("Offline sync completed")
}
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateConnected})
}
case *events.AppStateSyncComplete:
if len(user.Client.Store.PushName) > 0 && v.Name == appstate.WAPatchCriticalBlock {
err := user.Client.SendPresence(user.lastPresence)
if err != nil {
user.zlog.Warn().Err(err).Msg("Failed to send presence after app state sync")
}
} else if v.Name == appstate.WAPatchCriticalUnblockLow {
go func() {
err := user.ResyncContacts(false)
if err != nil {
user.zlog.Err(err).Msg("Failed to resync contacts after app state sync")
}
}()
}
case *events.PushNameSetting:
// Send presence available when connecting and when the pushname is changed.
// This makes sure that outgoing messages always have the right pushname.
err := user.Client.SendPresence(user.lastPresence)
if err != nil {
user.zlog.Warn().Err(err).Msg("Failed to send presence after push name update")
}
_, _, err = user.Client.Store.Contacts.PutPushName(user.JID.ToNonAD(), v.Action.GetName())
if err != nil {
user.zlog.Err(err).Msg("Failed to update push name in store")
}
go user.syncPuppet(user.JID.ToNonAD(), "push name setting")
case *events.PairSuccess:
user.PhoneLastSeen = time.Now()
user.Session = user.Client.Store
user.JID = v.ID
user.addToJIDMap()
err := user.Update(ctx)
if err != nil {
user.zlog.Err(err).Msg("Failed to save user after pair success")
}
case *events.StreamError:
var message string
if v.Code != "" {
message = fmt.Sprintf("Unknown stream error with code %s", v.Code)
} else if children := v.Raw.GetChildren(); len(children) > 0 {
message = fmt.Sprintf("Unknown stream error (contains %s node)", children[0].Tag)
} else {
message = "Unknown stream error"
}
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateUnknownError, Message: message})
user.bridge.Metrics.TrackConnectionState(user.JID, false)
case *events.StreamReplaced:
if user.bridge.Config.Bridge.CrashOnStreamReplaced {
user.zlog.Info().Msg("Stopping bridge due to StreamReplaced event")
user.bridge.ManualStop(60)
} else {
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateUnknownError, Message: "Stream replaced"})
user.bridge.Metrics.TrackConnectionState(user.JID, false)
user.sendMarkdownBridgeAlert(ctx, "The bridge was started in another location. Use `reconnect` to reconnect this one.")
}
case *events.ConnectFailure:
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateUnknownError, Message: fmt.Sprintf("Unknown connection failure: %s (%s)", v.Reason, v.Message)})
user.bridge.Metrics.TrackConnectionState(user.JID, false)
user.bridge.Metrics.TrackConnectionFailure(fmt.Sprintf("status-%d", v.Reason))
case *events.ClientOutdated:
user.zlog.Error().Msg("Got a client outdated connect failure. The bridge is likely out of date, please update immediately.")
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateUnknownError, Message: "Connect failure: 405 client outdated"})
user.bridge.Metrics.TrackConnectionState(user.JID, false)
user.bridge.Metrics.TrackConnectionFailure("client-outdated")
case *events.TemporaryBan:
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Message: v.String()})
user.bridge.Metrics.TrackConnectionState(user.JID, false)
user.bridge.Metrics.TrackConnectionFailure("temporary-ban")
case *events.Disconnected:
// Don't send the normal transient disconnect state if we're already in a different transient disconnect state.
// TODO remove this if/when the phone offline state is moved to a sub-state of CONNECTED
if user.BridgeState.GetPrev().Error != WAPhoneOffline && user.PhoneRecentlySeen(false) {
user.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WADisconnected})
}
user.bridge.Metrics.TrackConnectionState(user.JID, false)
case *events.Contact:
go user.syncPuppet(v.JID, "contact event")
case *events.PushName:
go user.syncPuppet(v.JID, "push name event")
case *events.BusinessName:
go user.syncPuppet(v.JID, "business name event")
case *events.GroupInfo:
user.groupListCache = nil
go user.handleGroupUpdate(v)
case *events.JoinedGroup:
user.groupListCache = nil
go user.handleGroupCreate(v)
case *events.NewsletterJoin:
go user.handleNewsletterJoin(v)
case *events.NewsletterLeave:
go user.handleNewsletterLeave(v)
case *events.Picture:
go user.handlePictureUpdate(ctx, v)
case *events.Receipt:
if v.IsFromMe && v.Sender.Device == 0 {
user.phoneSeen(v.Timestamp)
}
go user.handleReceipt(v)
case *events.ChatPresence: