This repository has been archived by the owner on Jun 30, 2021. It is now read-only.
forked from mautrix/whatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathportal.go
2575 lines (2356 loc) · 78.1 KB
/
portal.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) 2020 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 (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"html"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io/ioutil"
"math"
"math/rand"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/crypto/attachment"
"github.com/Rhymen/go-whatsapp"
"github.com/gabriel-vasile/mimetype"
"github.com/karmanyaahm/groupme"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/pushrules"
"github.com/karmanyaahm/matrix-groupme-go/database"
"github.com/karmanyaahm/matrix-groupme-go/groupmeExt"
"github.com/karmanyaahm/matrix-groupme-go/types"
whatsappExt "github.com/karmanyaahm/matrix-groupme-go/whatsapp-ext"
)
func (bridge *Bridge) GetPortalByMXID(mxid id.RoomID) *Portal {
bridge.portalsLock.Lock()
defer bridge.portalsLock.Unlock()
portal, ok := bridge.portalsByMXID[mxid]
if !ok {
return bridge.loadDBPortal(bridge.DB.Portal.GetByMXID(mxid), nil)
}
return portal
}
func (bridge *Bridge) GetPortalByJID(key database.PortalKey) *Portal {
bridge.portalsLock.Lock()
defer bridge.portalsLock.Unlock()
portal, ok := bridge.portalsByJID[key]
if !ok {
return bridge.loadDBPortal(bridge.DB.Portal.GetByJID(key), &key)
}
return portal
}
func (bridge *Bridge) GetAllPortals() []*Portal {
return bridge.dbPortalsToPortals(bridge.DB.Portal.GetAll())
}
func (bridge *Bridge) GetAllPortalsByJID(jid types.GroupMeID) []*Portal {
return bridge.dbPortalsToPortals(bridge.DB.Portal.GetAllByJID(jid))
}
func (bridge *Bridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
bridge.portalsLock.Lock()
defer bridge.portalsLock.Unlock()
output := make([]*Portal, len(dbPortals))
for index, dbPortal := range dbPortals {
if dbPortal == nil {
continue
}
portal, ok := bridge.portalsByJID[dbPortal.Key]
if !ok {
portal = bridge.loadDBPortal(dbPortal, nil)
}
output[index] = portal
}
return output
}
func (bridge *Bridge) loadDBPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
if dbPortal == nil {
if key == nil {
return nil
}
dbPortal = bridge.DB.Portal.New()
dbPortal.Key = *key
dbPortal.Insert()
}
portal := bridge.NewPortal(dbPortal)
bridge.portalsByJID[portal.Key] = portal
if len(portal.MXID) > 0 {
bridge.portalsByMXID[portal.MXID] = portal
}
return portal
}
func (portal *Portal) GetUsers() []*User {
return nil
}
func (bridge *Bridge) NewManualPortal(key database.PortalKey) *Portal {
portal := &Portal{
Portal: bridge.DB.Portal.New(),
bridge: bridge,
log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", key)),
recentlyHandled: make([]string, recentlyHandledLength),
messages: make(chan PortalMessage, bridge.Config.Bridge.PortalMessageBuffer),
}
portal.Key = key
go portal.handleMessageLoop()
return portal
}
func (bridge *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
portal := &Portal{
Portal: dbPortal,
bridge: bridge,
log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
recentlyHandled: make([]string, recentlyHandledLength),
messages: make(chan PortalMessage, bridge.Config.Bridge.PortalMessageBuffer),
}
go portal.handleMessageLoop()
return portal
}
const recentlyHandledLength = 100
type PortalMessage struct {
chat database.PortalKey
source *User
data *groupme.Message
timestamp uint64
}
type Portal struct {
*database.Portal
bridge *Bridge
log log.Logger
roomCreateLock sync.Mutex
recentlyHandled []string
recentlyHandledLock sync.Mutex
recentlyHandledIndex uint8
backfillLock sync.Mutex
backfilling bool
lastMessageTs uint64
privateChatBackfillInvitePuppet func()
messages chan PortalMessage
hasRelaybot *bool
}
const MaxMessageAgeToCreatePortal = 5 * 60 // 5 minutes
func (portal *Portal) handleMessageLoop() {
for msg := range portal.messages {
if len(portal.MXID) == 0 {
if msg.timestamp+MaxMessageAgeToCreatePortal < uint64(time.Now().Unix()) {
portal.log.Debugln("Not creating portal room for incoming message as the message is too old.")
continue
}
portal.log.Debugln("Creating Matrix room from incoming message")
err := portal.CreateMatrixRoom(msg.source)
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
return
}
}
portal.backfillLock.Lock()
portal.handleMessage(msg)
portal.backfillLock.Unlock()
}
}
func (portal *Portal) handleMessage(msg PortalMessage) {
if len(portal.MXID) == 0 {
portal.log.Warnln("handleMessage called even though portal.MXID is empty")
return
}
portal.HandleTextMessage(msg.source, msg.data)
portal.handleReaction(msg.data.ID.String(), msg.data.FavoritedBy)
}
func (portal *Portal) isRecentlyHandled(id groupme.ID) bool {
idStr := id.String()
for i := recentlyHandledLength - 1; i >= 0; i-- {
if portal.recentlyHandled[i] == idStr {
return true
}
}
return false
}
func (portal *Portal) isDuplicate(id groupme.ID) bool {
msg := portal.bridge.DB.Message.GetByJID(portal.Key, id.String())
if msg != nil {
return true
}
return false
}
func init() {
}
func (portal *Portal) markHandled(source *User, message *groupme.Message, mxid id.EventID) {
msg := portal.bridge.DB.Message.New()
msg.Chat = portal.Key
msg.JID = message.ID.String()
msg.MXID = mxid
msg.Timestamp = uint64(message.CreatedAt.ToTime().Unix())
if message.UserID.String() == source.JID {
msg.Sender = source.JID
} else if portal.IsPrivateChat() {
msg.Sender = portal.Key.JID
} else {
msg.Sender = message.ID.String()
if len(msg.Sender) == 0 {
println("AAAAAAAAAAAAAAAAAAAAAAAAAAIDK")
msg.Sender = message.SenderID.String()
}
}
msg.Content = &groupmeExt.Message{Message: *message}
msg.Insert()
portal.recentlyHandledLock.Lock()
portal.recentlyHandled[0] = "" //FIFO queue being implemented here //TODO: is this efficent
portal.recentlyHandled = portal.recentlyHandled[1:]
portal.recentlyHandled = append(portal.recentlyHandled, message.ID.String())
portal.recentlyHandledLock.Unlock()
}
func (portal *Portal) getMessageIntent(user *User, info *groupme.Message) *appservice.IntentAPI {
if portal.IsPrivateChat() {
if info.UserID.String() == user.GetJID() { //from me
return portal.bridge.GetPuppetByJID(user.JID).DefaultIntent()
}
return portal.MainIntent()
} else if len(info.UserID.String()) == 0 {
println("TODO weird uid stuff")
} else if info.UserID.String() == user.GetJID() { //from me
return portal.bridge.GetPuppetByJID(user.JID).IntentFor(portal)
}
return portal.bridge.GetPuppetByJID(info.UserID.String()).IntentFor(portal)
}
func (portal *Portal) getReactionIntent(jid types.GroupMeID) *appservice.IntentAPI {
return portal.bridge.GetPuppetByJID(jid).IntentFor(portal)
}
func (portal *Portal) startHandling(source *User, info *groupme.Message) *appservice.IntentAPI {
// TODO these should all be trace logs
if portal.lastMessageTs > uint64(info.CreatedAt.ToTime().Unix()+1) {
portal.log.Debugfln("Not handling %s: message is older (%d) than last bridge message (%d)", info.ID, info.CreatedAt, portal.lastMessageTs)
} else if portal.isRecentlyHandled(info.ID) {
portal.log.Debugfln("Not handling %s: message was recently handled", info.ID)
} else if portal.isDuplicate(info.ID) {
portal.log.Debugfln("Not handling %s: message is duplicate", info.ID)
} else if info.System {
portal.log.Debugfln("Not handling %s: message is from system: %s", info.ID, info.Text)
} else {
portal.lastMessageTs = uint64(info.CreatedAt.ToTime().Unix())
intent := portal.getMessageIntent(source, info)
if intent != nil {
portal.log.Debugfln("Starting handling of %s (ts: %d)", info.ID, info.CreatedAt)
} else {
portal.log.Debugfln("Not handling %s: sender is not known", info.ID.String())
}
return intent
}
return nil
}
func (portal *Portal) finishHandling(source *User, message *groupme.Message, mxid id.EventID) {
portal.markHandled(source, message, mxid)
portal.sendDeliveryReceipt(mxid)
portal.log.Debugln("Handled message", message.ID.String(), "->", mxid)
}
func (portal *Portal) SyncParticipants(metadata *groupme.Group) {
changed := false
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
changed = true
}
participantMap := make(map[string]bool)
for _, participant := range metadata.Members {
participantMap[participant.UserID.String()] = true
user := portal.bridge.GetUserByJID(participant.UserID.String())
portal.userMXIDAction(user, portal.ensureMXIDInvited)
puppet := portal.bridge.GetPuppetByJID(participant.UserID.String())
err := puppet.IntentFor(portal).EnsureJoined(portal.MXID)
if err != nil {
portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID.String(), portal.MXID, err)
}
expectedLevel := 0
// if participant.IsSuperAdmin {
// expectedLevel = 95
// } else if participant.IsAdmin {
// expectedLevel = 50
// }
changed = levels.EnsureUserLevel(puppet.MXID, expectedLevel) || changed
if user != nil {
changed = levels.EnsureUserLevel(user.MXID, expectedLevel) || changed
}
puppet.Sync(nil, portal.MXID, *participant) //why nil whynot
}
if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels:", err)
}
}
members, err := portal.MainIntent().JoinedMembers(portal.MXID)
if err != nil {
portal.log.Warnln("Failed to get member list:", err)
} else {
for member := range members.Joined {
jid, ok := portal.bridge.ParsePuppetMXID(member)
if ok {
_, shouldBePresent := participantMap[jid]
if !shouldBePresent {
_, err := portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
UserID: member,
Reason: "User had left this WhatsApp chat",
})
if err != nil {
portal.log.Warnfln("Failed to kick user %s who had left: %v", member, err)
}
}
}
}
}
}
func (portal *Portal) UpdateAvatar(user *User, avatar string, updateInfo bool) bool {
// if len(avatar) == 0 {
// var err error
// avatar, err = user.Conn.GetProfilePicThumb(portal.Key.JID)
// if err != nil {
// portal.log.Errorln(err)
// return false
// }
// }
//TODO: duplicated code from puppet.UpdateAvatar
if len(avatar) == 0 {
if len(portal.Avatar) == 0 {
return false
}
err := portal.MainIntent().SetAvatarURL(id.ContentURI{})
if err != nil {
portal.log.Warnln("Failed to remove avatar:", err)
}
portal.AvatarURL = types.ContentURI{}
portal.Avatar = avatar
return true
}
if portal.Avatar == avatar {
return false
}
//TODO check its actually groupme?
response, err := http.Get(avatar + ".large")
if err != nil {
portal.log.Warnln("Failed to download avatar:", err)
return false
}
defer response.Body.Close()
image, err := ioutil.ReadAll(response.Body)
if err != nil {
portal.log.Warnln("Failed to read downloaded avatar:", err)
return false
}
mime := response.Header.Get("Content-Type")
if len(mime) == 0 {
mime = http.DetectContentType(image)
}
resp, err := portal.MainIntent().UploadBytes(image, mime)
if err != nil {
portal.log.Warnln("Failed to upload avatar:", err)
return false
}
portal.AvatarURL = types.ContentURI{resp.ContentURI}
if len(portal.MXID) > 0 {
_, err = portal.MainIntent().SetRoomAvatar(portal.MXID, resp.ContentURI)
if err != nil {
portal.log.Warnln("Failed to set room topic:", err)
return false
}
}
portal.Avatar = avatar
if updateInfo {
portal.UpdateBridgeInfo()
}
return true
}
func (portal *Portal) UpdateName(name string, setBy types.GroupMeID, updateInfo bool) bool {
if portal.Name != name {
intent := portal.MainIntent()
if len(setBy) > 0 {
intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
}
_, err := intent.SetRoomName(portal.MXID, name)
if err == nil {
portal.Name = name
if updateInfo {
portal.UpdateBridgeInfo()
}
return true
}
portal.log.Warnln("Failed to set room name:", err)
}
return false
}
func (portal *Portal) UpdateTopic(topic string, setBy types.GroupMeID, updateInfo bool) bool {
if portal.Topic != topic {
intent := portal.MainIntent()
if len(setBy) > 0 {
intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
}
_, err := intent.SetRoomTopic(portal.MXID, topic)
if err == nil {
portal.Topic = topic
if updateInfo {
portal.UpdateBridgeInfo()
}
return true
}
portal.log.Warnln("Failed to set room topic:", err)
}
return false
}
func (portal *Portal) UpdateMetadata(user *User) bool {
if portal.IsPrivateChat() {
return false
}
group, err := user.Client.ShowGroup(context.TODO(), groupme.ID(strings.Replace(portal.Key.JID, groupmeExt.NewUserSuffix, "", 1)))
if err != nil {
portal.log.Errorln(err)
return false
}
// if metadata.Status != 0 {
// 401: access denied
// 404: group does (no longer) exist
// 500: ??? happens with status@broadcast
// TODO: update the room, e.g. change priority level
// to send messages to moderator
//return false
// }
portal.SyncParticipants(group)
update := false
update = portal.UpdateName(group.Name, "", false) || update
update = portal.UpdateTopic(group.Description, "", false) || update
// portal.RestrictMessageSending(metadata.Announce)
return update
}
func (portal *Portal) userMXIDAction(user *User, fn func(mxid id.UserID)) {
if user == nil {
return
}
if user == portal.bridge.Relaybot {
for _, mxid := range portal.bridge.Config.Bridge.Relaybot.InviteUsers {
fn(mxid)
}
} else {
fn(user.MXID)
}
}
func (portal *Portal) ensureMXIDInvited(mxid id.UserID) {
err := portal.MainIntent().EnsureInvited(portal.MXID, mxid)
if err != nil {
portal.log.Warnfln("Failed to ensure %s is invited to %s: %v", mxid, portal.MXID, err)
}
}
func (portal *Portal) ensureUserInvited(user *User) {
portal.userMXIDAction(user, portal.ensureMXIDInvited)
customPuppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
if customPuppet != nil && customPuppet.CustomIntent() != nil {
_ = customPuppet.CustomIntent().EnsureJoined(portal.MXID)
}
}
func (portal *Portal) Sync(user *User, group *groupme.Group) {
portal.log.Infoln("Syncing portal for", user.MXID)
if user.IsRelaybot {
yes := true
portal.hasRelaybot = &yes
}
sub := user.Conn.SubscribeToGroup
if portal.IsPrivateChat() {
sub = user.Conn.SubscribeToDM
}
err := sub(context.TODO(), groupme.ID(portal.Key.Receiver), user.Token)
if err != nil {
portal.log.Errorln("Subscribing failed, live metadata updates won't work", err)
}
if len(portal.MXID) == 0 {
if !portal.IsPrivateChat() {
portal.Name = group.Name
}
err := portal.CreateMatrixRoom(user)
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
return
}
} else {
portal.ensureUserInvited(user)
}
if portal.IsPrivateChat() {
return
}
update := false
update = portal.UpdateMetadata(user) || update
update = portal.UpdateAvatar(user, group.ImageURL, false) || update
if update {
portal.Update()
portal.UpdateBridgeInfo()
}
}
func (portal *Portal) GetBasePowerLevels() *event.PowerLevelsEventContent {
anyone := 0
nope := 99
invite := 50
if portal.bridge.Config.Bridge.AllowUserInvite {
invite = 0
}
return &event.PowerLevelsEventContent{
UsersDefault: anyone,
EventsDefault: anyone,
RedactPtr: &anyone,
StateDefaultPtr: &nope,
BanPtr: &nope,
InvitePtr: &invite,
Users: map[id.UserID]int{
portal.MainIntent().UserID: 100,
},
Events: map[string]int{
event.StateRoomName.Type: anyone,
event.StateRoomAvatar.Type: anyone,
event.StateTopic.Type: anyone,
},
}
}
func (portal *Portal) ChangeAdminStatus(jids []string, setAdmin bool) {
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
}
newLevel := 0
if setAdmin {
newLevel = 50
}
changed := false
for _, jid := range jids {
puppet := portal.bridge.GetPuppetByJID(jid)
changed = levels.EnsureUserLevel(puppet.MXID, newLevel) || changed
user := portal.bridge.GetUserByJID(jid)
if user != nil {
changed = levels.EnsureUserLevel(user.MXID, newLevel) || changed
}
}
if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels:", err)
}
}
}
func (portal *Portal) RestrictMessageSending(restrict bool) {
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
}
newLevel := 0
if restrict {
newLevel = 50
}
if levels.EventsDefault == newLevel {
return
}
levels.EventsDefault = newLevel
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels:", err)
}
}
func (portal *Portal) RestrictMetadataChanges(restrict bool) {
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
}
newLevel := 0
if restrict {
newLevel = 50
}
changed := false
changed = levels.EnsureEventLevel(event.StateRoomName, newLevel) || changed
changed = levels.EnsureEventLevel(event.StateRoomAvatar, newLevel) || changed
changed = levels.EnsureEventLevel(event.StateTopic, newLevel) || changed
if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels:", err)
}
}
}
func (portal *Portal) BackfillHistory(user *User, lastMessageTime uint64) error {
if !portal.bridge.Config.Bridge.RecoverHistory {
return nil
}
endBackfill := portal.beginBackfill()
defer endBackfill()
lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
if lastMessage == nil {
return nil
}
if lastMessage.Timestamp >= lastMessageTime {
portal.log.Debugln("Not backfilling: no new messages")
return nil
}
lastMessageID := lastMessage.JID
lastMessageFromMe := lastMessage.Sender == user.JID
portal.log.Infoln("Backfilling history since", lastMessageID, "for", user.MXID)
for len(lastMessageID) > 0 {
portal.log.Debugln("Fetching 50 messages of history after", lastMessageID)
messages, err := user.Client.LoadMessagesAfter(portal.Key.JID, lastMessageID, lastMessageFromMe, portal.IsPrivateChat())
if err != nil {
return err
}
// messages, ok := resp.Content.([]interface{})
if len(messages) == 0 {
portal.log.Debugfln("Didn't get more messages to backfill (resp.Content is %T)", messages)
break
}
portal.handleHistory(user, messages)
lastMessageProto := messages[len(messages)-1]
lastMessageID = lastMessageProto.ID.String()
lastMessageFromMe = lastMessageProto.UserID.String() == user.JID
}
portal.log.Infoln("Backfilling finished")
return nil
}
func (portal *Portal) beginBackfill() func() {
portal.backfillLock.Lock()
portal.backfilling = true
var privateChatPuppetInvited bool
var privateChatPuppet *Puppet
if portal.IsPrivateChat() && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling && portal.Key.JID != portal.Key.Receiver {
privateChatPuppet = portal.bridge.GetPuppetByJID(portal.Key.Receiver)
portal.privateChatBackfillInvitePuppet = func() {
if privateChatPuppetInvited {
return
}
privateChatPuppetInvited = true
_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: privateChatPuppet.MXID})
_ = privateChatPuppet.DefaultIntent().EnsureJoined(portal.MXID)
}
}
return func() {
portal.backfilling = false
portal.privateChatBackfillInvitePuppet = nil
portal.backfillLock.Unlock()
if privateChatPuppet != nil && privateChatPuppetInvited {
//_, _ = privateChatPuppet.DefaultIntent().LeaveRoom(portal.MXID)
//why this shouldn't really happen NOTE
}
}
}
func (portal *Portal) disableNotifications(user *User) {
if !portal.bridge.Config.Bridge.HistoryDisableNotifs {
return
}
puppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
if puppet == nil || puppet.customIntent == nil {
return
}
portal.log.Debugfln("Disabling notifications for %s for backfilling", user.MXID)
ruleID := fmt.Sprintf("net.maunium.silence_while_backfilling.%s", portal.MXID)
err := puppet.customIntent.PutPushRule("global", pushrules.OverrideRule, ruleID, &mautrix.ReqPutPushRule{
Actions: []pushrules.PushActionType{pushrules.ActionDontNotify},
Conditions: []pushrules.PushCondition{{
Kind: pushrules.KindEventMatch,
Key: "room_id",
Pattern: string(portal.MXID),
}},
})
if err != nil {
portal.log.Warnfln("Failed to disable notifications for %s while backfilling: %v", user.MXID, err)
}
}
func (portal *Portal) enableNotifications(user *User) {
if !portal.bridge.Config.Bridge.HistoryDisableNotifs {
return
}
puppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
if puppet == nil || puppet.customIntent == nil {
return
}
portal.log.Debugfln("Re-enabling notifications for %s after backfilling", user.MXID)
ruleID := fmt.Sprintf("net.maunium.silence_while_backfilling.%s", portal.MXID)
err := puppet.customIntent.DeletePushRule("global", pushrules.OverrideRule, ruleID)
if err != nil {
portal.log.Warnfln("Failed to re-enable notifications for %s after backfilling: %v", user.MXID, err)
}
}
func (portal *Portal) FillInitialHistory(user *User) error {
if portal.bridge.Config.Bridge.InitialHistoryFill == 0 {
return nil
}
endBackfill := portal.beginBackfill()
defer endBackfill()
if portal.privateChatBackfillInvitePuppet != nil {
portal.privateChatBackfillInvitePuppet()
}
n := portal.bridge.Config.Bridge.InitialHistoryFill
portal.log.Infoln("Filling initial history, maximum", n, "messages")
var messages []*groupme.Message
before := ""
chunkNum := 1
for n > 0 {
count := 20
if n < count {
count = n
}
portal.log.Debugfln("Fetching chunk %d (%d messages / %d cap) before message %s", chunkNum, count, n, before)
chunk, err := user.Client.LoadMessagesBefore(portal.Key.JID, before, portal.IsPrivateChat())
if err != nil {
return err
}
if len(chunk) == 0 {
portal.log.Infoln("Chunk empty, starting handling of loaded messages")
break
}
//reverses chunk to ascending order (oldest first)
i := 0
j := len(chunk) - 1
for i < j {
chunk[i], chunk[j] = chunk[j], chunk[i]
i++
j--
}
messages = append(chunk, messages...)
portal.log.Debugfln("Fetched chunk and received %d messages", len(chunk))
n -= len(chunk)
before = chunk[0].ID.String()
if len(before) == 0 {
portal.log.Infoln("No message ID for first message, starting handling of loaded messages")
break
}
}
portal.disableNotifications(user)
portal.handleHistory(user, messages)
portal.enableNotifications(user)
portal.log.Infoln("Initial history fill complete")
return nil
}
func (portal *Portal) handleHistory(user *User, messages []*groupme.Message) {
portal.log.Infoln("Handling", len(messages), "messages of history")
for _, message := range messages {
// data, ok := rawMessage.(*groupme.Message)
// if !ok {
// portal.log.Warnln("Unexpected non-WebMessageInfo item in history response:", rawMessage)
// continue
// }
// data := whatsapp.ParseProtoMessage(message)
// if data == nil || data == whatsapp.ErrMessageTypeNotImplemented {
// st := message.GetMessageStubType()
// // Ignore some types that are known to fail
// if st == waProto.WebMessageInfo_CALL_MISSED_VOICE || st == waProto.WebMessageInfo_CALL_MISSED_VIDEO ||
// st == waProto.WebMessageInfo_CALL_MISSED_GROUP_VOICE || st == waProto.WebMessageInfo_CALL_MISSED_GROUP_VIDEO {
// continue
// }
// portal.log.Warnln("Message", message.GetKey().GetId(), "failed to parse during backfilling")
// continue
// }
if portal.privateChatBackfillInvitePuppet != nil && message.UserID.String() == user.JID && portal.IsPrivateChat() {
portal.privateChatBackfillInvitePuppet()
}
portal.handleMessage(PortalMessage{portal.Key, user, message, uint64(message.CreatedAt.ToTime().Unix())})
}
}
type BridgeInfoSection struct {
ID string `json:"id"`
DisplayName string `json:"displayname,omitempty"`
AvatarURL id.ContentURIString `json:"avatar_url,omitempty"`
ExternalURL string `json:"external_url,omitempty"`
}
type BridgeInfoContent struct {
BridgeBot id.UserID `json:"bridgebot"`
Creator id.UserID `json:"creator,omitempty"`
Protocol BridgeInfoSection `json:"protocol"`
Network *BridgeInfoSection `json:"network,omitempty"`
Channel BridgeInfoSection `json:"channel"`
}
var (
StateBridgeInfo = event.Type{Type: "m.bridge", Class: event.StateEventType}
StateHalfShotBridgeInfo = event.Type{Type: "uk.half-shot.bridge", Class: event.StateEventType}
)
func (portal *Portal) getBridgeInfo() (string, BridgeInfoContent) {
bridgeInfo := BridgeInfoContent{
BridgeBot: portal.bridge.Bot.UserID,
Creator: portal.MainIntent().UserID,
Protocol: BridgeInfoSection{
ID: "whatsapp",
DisplayName: "WhatsApp",
AvatarURL: id.ContentURIString(portal.bridge.Config.AppService.Bot.Avatar),
ExternalURL: "https://www.whatsapp.com/",
},
Channel: BridgeInfoSection{
ID: portal.Key.JID,
DisplayName: portal.Name,
AvatarURL: portal.AvatarURL.CUString(),
},
}
bridgeInfoStateKey := fmt.Sprintf("net.maunium.whatsapp://whatsapp/%s", portal.Key.JID)
return bridgeInfoStateKey, bridgeInfo
}
func (portal *Portal) UpdateBridgeInfo() {
if len(portal.MXID) == 0 {
portal.log.Debugln("Not updating bridge info: no Matrix room created")
return
}
portal.log.Debugln("Updating bridge info...")
stateKey, content := portal.getBridgeInfo()
_, err := portal.MainIntent().SendStateEvent(portal.MXID, StateBridgeInfo, stateKey, content)
if err != nil {
portal.log.Warnln("Failed to update m.bridge:", err)
}
_, err = portal.MainIntent().SendStateEvent(portal.MXID, StateHalfShotBridgeInfo, stateKey, content)
if err != nil {
portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
}
}
func (portal *Portal) CreateMatrixRoom(user *User) error {
portal.roomCreateLock.Lock()
defer portal.roomCreateLock.Unlock()
if len(portal.MXID) > 0 {
return nil
}
intent := portal.MainIntent()
if err := intent.EnsureRegistered(); err != nil {
return err
}
portal.log.Infoln("Creating Matrix room. Info source:", user.MXID)
var metadata *groupme.Group
return nil
if portal.IsPrivateChat() {
puppet := portal.bridge.GetPuppetByJID(portal.Key.JID)
meta, err := portal.bridge.StateStore.TryGetMemberRaw("", puppet.MXID)
if err {
println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
return errors.New("Cannot find user information")
}
//m, _ := portal.bridge.StateStore.TryGetMemberRaw(portal.MXID, puppet.MXID)
if portal.bridge.Config.Bridge.PrivateChatPortalMeta {
portal.Name = meta.DisplayName
portal.AvatarURL = types.ContentURI{id.MustParseContentURI(meta.AvatarURL)}
portal.Avatar = meta.Avatar
} else {
portal.Name = ""
}
portal.Topic = "GroupMe private chat"
// } else if portal.IsStatusBroadcastRoom() {
// portal.Name = "WhatsApp Status Broadcast"
// portal.Topic = "WhatsApp status updates from your contacts"
} else {
var err error
metadata, err = user.Client.ShowGroup(context.TODO(), groupme.ID(portal.Key.JID))
if err == nil {
portal.Name = metadata.Name
portal.Topic = metadata.Description
portal.UpdateAvatar(user, metadata.ImageURL, false)
} else {
portal.log.Warnln("Cannot fetch group metadata for new portal")
}
}
bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
initialState := []*event.Event{{
Type: event.StatePowerLevels,
Content: event.Content{
Parsed: portal.GetBasePowerLevels(),
},
}, {
Type: StateBridgeInfo,
Content: event.Content{Parsed: bridgeInfo},
StateKey: &bridgeInfoStateKey,
}, {
// TODO remove this once /~https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
Type: StateHalfShotBridgeInfo,
Content: event.Content{Parsed: bridgeInfo},
StateKey: &bridgeInfoStateKey,
}}
if !portal.AvatarURL.IsEmpty() {
initialState = append(initialState, &event.Event{
Type: event.StateRoomAvatar,
Content: event.Content{
Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL.ContentURI},
},
})
}