-
Notifications
You must be signed in to change notification settings - Fork 71
/
portal.go
2334 lines (2136 loc) · 74.8 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
// beeper-imessage - A Matrix-iMessage puppeting bridge.
// Copyright (C) 2022 Tulir Asokan
// Copyright (C) 2023 Beeper, Inc.
//
// 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/sha256"
"errors"
"fmt"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/gabriel-vasile/mimetype"
"github.com/google/uuid"
"github.com/rs/zerolog"
"go.mau.fi/util/exzerolog"
"go.mau.fi/util/jsontime"
"golang.org/x/exp/slices"
"maunium.net/go/maulogger/v2"
"maunium.net/go/maulogger/v2/maulogadapt"
"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/id"
"github.com/beeper/imessage/database"
"github.com/beeper/imessage/imessage"
"github.com/beeper/imessage/imessage/direct"
"github.com/beeper/imessage/imessage/direct/util/uri"
"github.com/beeper/imessage/ipc"
"github.com/beeper/imessage/msgconv"
)
func (br *IMBridge) GetPortalByMXID(mxid id.RoomID) *Portal {
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
portal, ok := br.portalsByMXID[mxid]
if !ok {
ctx := context.TODO()
dbPortal, err := br.DB.Portal.GetByMXID(ctx, mxid)
if err != nil {
br.ZLog.Err(err).Str("mxid", mxid.String()).Msg("Failed to get portal from database")
return nil
}
return br.loadDBPortal(ctx, dbPortal, nil)
}
return portal
}
func (br *IMBridge) GetPortalByID(key database.Key) *Portal {
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
return br.maybeGetPortalByID(context.TODO(), key, true)
}
func (br *IMBridge) FindPortalByParticipants(participants []uri.ParsedURI, receiver int) *Portal {
ctx := context.TODO()
portal, err := br.DB.Portal.GetByParticipants(ctx, participants, receiver)
if err != nil {
br.ZLog.Err(err).Any("participants", participants).Msg("Failed to find portal by participants from database")
return nil
} else if portal == nil {
return nil
}
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
existing, ok := br.portalsByKey[portal.Key]
if ok {
return existing
}
return br.loadDBPortal(ctx, portal, nil)
}
func (br *IMBridge) GetPortalByIDIfExists(key database.Key) *Portal {
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
return br.maybeGetPortalByID(context.TODO(), key, false)
}
func (br *IMBridge) maybeGetPortalByID(ctx context.Context, key database.Key, createIfNotExist bool) *Portal {
var fallbackKey *database.Key
if createIfNotExist {
fallbackKey = &key
}
portal, ok := br.portalsByKey[key]
if !ok {
dbPortal, err := br.DB.Portal.GetByURI(ctx, key)
if err != nil {
br.ZLog.Err(err).Object("portal_key", key).Msg("Failed to get portal from database")
return nil
}
return br.loadDBPortal(ctx, dbPortal, fallbackKey)
}
return portal
}
func (br *IMBridge) GetAllPortals() []*Portal {
return br.loadManyPortals(br.DB.Portal.GetAllWithMXID)
}
func (br *IMBridge) GetAllPortalsForUser(receiver int) []*Portal {
return br.loadManyPortals(func(ctx context.Context) ([]*database.Portal, error) {
return br.DB.Portal.GetAllForUser(ctx, receiver)
})
}
func (br *IMBridge) FindPortalsWithRecentMessages(receiver int, interval time.Duration) []*Portal {
return br.loadManyPortals(func(ctx context.Context) ([]*database.Portal, error) {
return br.DB.Portal.FindWithRecentMessages(ctx, receiver, interval)
})
}
func (br *IMBridge) loadManyPortals(query func(ctx context.Context) ([]*database.Portal, error)) []*Portal {
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
dbPortals, err := query(context.TODO())
if err != nil {
br.ZLog.Err(err).Msg("Failed to load all portals from database")
return []*Portal{}
}
output := make([]*Portal, len(dbPortals))
for index, dbPortal := range dbPortals {
if dbPortal == nil {
continue
}
portal, ok := br.portalsByKey[dbPortal.Key]
if !ok {
portal = br.loadDBPortal(context.TODO(), dbPortal, nil)
}
output[index] = portal
}
return output
}
func (br *IMBridge) loadDBPortal(ctx context.Context, dbPortal *database.Portal, key *database.Key) *Portal {
if dbPortal == nil {
if key == nil {
return nil
}
dbPortal = br.DB.Portal.New()
dbPortal.Key = *key
err := dbPortal.Insert(ctx)
if err != nil {
br.ZLog.Err(err).Object("portal_key", key).Msg("Failed to insert portal")
return nil
}
}
portal := br.NewPortal(dbPortal)
br.portalsByKey[portal.Key] = portal
if len(portal.MXID) > 0 {
br.portalsByMXID[portal.MXID] = portal
}
return portal
}
func (br *IMBridge) GetAllIPortals() (iportals []bridge.Portal) {
portals := br.GetAllPortals()
iportals = make([]bridge.Portal, len(portals))
for i, portal := range portals {
iportals[i] = portal
}
return iportals
}
func (br *IMBridge) GetIPortal(mxid id.RoomID) bridge.Portal {
p := br.GetPortalByMXID(mxid)
if p == nil {
return nil
}
return p
}
func (br *IMBridge) NewPortal(dbPortal *database.Portal) *Portal {
portal := &Portal{
Portal: dbPortal,
bridge: br,
Messages: make(chan any, 100),
MatrixMessages: make(chan *event.Event, 100),
}
portal.user = br.GetUserByRowID(dbPortal.Receiver)
portal.MsgConv = &msgconv.MessageConverter{
PortalMethods: portal,
ConvertHEIF: portal.bridge.Config.Bridge.ConvertHEIF,
ConvertTIFF: portal.bridge.Config.Bridge.ConvertTIFF,
ConvertMOV: portal.bridge.Config.Bridge.ConvertMOV,
ConvertCAF: true,
MaxFileSize: br.MediaConfig.UploadSize,
Threads: portal.bridge.Config.Bridge.MatrixThreads,
}
portal.updateLogger()
portal.log = maulogadapt.ZeroAsMau(&portal.zlog)
go portal.handleMessageLoop()
return portal
}
type Portal struct {
*database.Portal
bridge *IMBridge
user *User
// Deprecated
log maulogger.Logger
zlog zerolog.Logger
Messages chan any
MatrixMessages chan *event.Event
MsgConv *msgconv.MessageConverter
roomCreateLock sync.Mutex
userIsTyping bool
typingLock sync.Mutex
}
func (portal *Portal) updateLogger() {
portal.zlog = portal.bridge.ZLog.With().
Str("portal_id", portal.URI.String()).
Int("portal_receiver", portal.Receiver).
Str("room_id", portal.MXID.String()).
Logger()
}
var (
_ bridge.Portal = (*Portal)(nil)
_ bridge.ReadReceiptHandlingPortal = (*Portal)(nil)
_ bridge.TypingPortal = (*Portal)(nil)
// _ bridge.MembershipHandlingPortal = (*Portal)(nil)
// _ bridge.MetaHandlingPortal = (*Portal)(nil)
// _ bridge.DisappearingPortal = (*Portal)(nil)
)
const intentKey = "com.beeper.portal.intent"
func (portal *Portal) UploadMatrixMedia(ctx context.Context, data []byte, fileName, contentType string) (id.ContentURIString, error) {
intent, ok := ctx.Value(intentKey).(*appservice.IntentAPI)
if !ok {
intent = portal.MainIntent()
}
req := mautrix.ReqUploadMedia{
ContentBytes: data,
ContentType: contentType,
FileName: fileName,
}
if portal.bridge.Config.Homeserver.AsyncMedia {
uploaded, err := intent.UploadAsync(req)
if err != nil {
return "", err
}
return uploaded.ContentURI.CUString(), nil
} else {
uploaded, err := intent.UploadMedia(req)
if err != nil {
return "", err
}
return uploaded.ContentURI.CUString(), nil
}
}
func (portal *Portal) DownloadMatrixMedia(ctx context.Context, uriString id.ContentURIString) ([]byte, error) {
parsedURI, err := uriString.Parse()
if err != nil {
return nil, fmt.Errorf("malformed content URI: %w", err)
}
return portal.MainIntent().DownloadBytesContext(ctx, parsedURI)
}
func (portal *Portal) GetiMessageThreadRoot(ctx context.Context, content *event.MessageEventContent) string {
threadRootMXID := content.RelatesTo.GetThreadParent()
replyToID := content.RelatesTo.GetReplyTo()
log := zerolog.Ctx(ctx).With().
Str("reply_to_mxid", replyToID.String()).
Str("thread_root_mxid", threadRootMXID.String()).
Logger()
var replyToMsg *database.Message
var err error
if len(threadRootMXID) > 0 {
replyToMsg, err = portal.bridge.DB.Message.GetByMXID(ctx, threadRootMXID)
if err != nil {
log.Warn().Err(err).Msg("Failed to get thread root message from database")
return ""
}
} else if len(replyToID) > 0 {
replyToMsg, err = portal.bridge.DB.Message.GetByMXID(ctx, replyToID)
if err != nil {
log.Warn().Err(err).Msg("Failed to get reply target message from database")
return ""
}
if replyToMsg != nil && replyToMsg.ReplyToID != uuid.Nil {
replyToMsg, err = portal.bridge.DB.Message.GetByID(ctx, portal.Key, replyToMsg.ReplyToID, replyToMsg.ReplyToPart)
if err != nil {
log.Warn().Err(err).
Str("reply_to_guid", replyToMsg.ReplyToID.String()).
Int("reply_to_part", replyToMsg.ReplyToPart).
Msg("Failed to get thread root based on reply target message from database")
return ""
}
}
}
if replyToMsg == nil {
return ""
}
return imessage.ParsedThreadRoot{
MessagePartInfo: imessage.MessagePartInfo{
PartID: replyToMsg.Part,
StartIndex: replyToMsg.StartIndex,
Length: replyToMsg.Length,
},
ID: replyToMsg.ID,
}.String()
}
func (portal *Portal) IsEncrypted() bool {
return portal.Encrypted
}
func (portal *Portal) MarkEncrypted() {
portal.Encrypted = true
portal.Update(context.TODO())
}
func (portal *Portal) ReceiveMatrixEvent(u bridge.User, evt *event.Event) {
brUser := u.(*User)
if brUser != portal.user {
portal.sendErrorMessage(evt, fmt.Errorf("internal error: user id mismatch"), "", true, status.MsgStatusPermFailure)
} else if !portal.user.IsLoggedIn() {
portal.sendErrorMessage(evt, fmt.Errorf("not logged into iMessage"), "", true, status.MsgStatusPermFailure)
} else {
portal.MatrixMessages <- evt
}
}
func (portal *Portal) HandleMatrixMeta(u bridge.User, evt *event.Event) {
brUser := u.(*User)
if brUser != portal.user {
portal.sendErrorMessage(evt, fmt.Errorf("internal error: user id mismatch"), "", true, status.MsgStatusPermFailure)
} else if !portal.user.IsLoggedIn() {
portal.sendErrorMessage(evt, fmt.Errorf("not logged into iMessage"), "", true, status.MsgStatusPermFailure)
} else {
switch evt.Type {
case event.StateRoomName:
portal.HandleMatrixRoomName(evt)
case event.StateRoomAvatar:
portal.HandleMatrixRoomAvatar(evt)
}
}
}
func (portal *Portal) handleMatrixParticipantChange(u bridge.User, evt *event.Event, newParticipants []uri.ParsedURI) {
brUser := u.(*User)
if brUser != portal.user {
portal.sendErrorMessage(evt, fmt.Errorf("internal error: user id mismatch"), "", true, status.MsgStatusPermFailure)
return
} else if !portal.user.IsLoggedIn() {
portal.sendErrorMessage(evt, fmt.Errorf("not logged into iMessage"), "", true, status.MsgStatusPermFailure)
return
}
portal.zlog.Info().
Any("old_participants", portal.Participants).
Any("new_participants", newParticipants).
Msg("Updating iMessage chat participants")
_, err := portal.user.IM.UpdateParticipants(context.TODO(), portal.OutgoingHandle, portal.Participants, portal.GroupID, newParticipants)
if err != nil {
portal.zlog.Warn().Err(err).Msg("Failed to leave iMessage chat")
return
}
portal.Participants = newParticipants
portal.SyncParticipants(portal.Participants)
err = portal.Update(context.TODO())
if err != nil {
portal.zlog.Warn().Err(err).Msg("Failed to save new participants list")
}
}
func (portal *Portal) HandleMatrixLeave(u bridge.User, evt *event.Event) {
newParticipants := slices.DeleteFunc(slices.Clone(portal.Participants), func(uri uri.ParsedURI) bool {
return slices.Contains(portal.user.IM.User.Handles, uri)
})
portal.handleMatrixParticipantChange(u, evt, newParticipants)
}
func (portal *Portal) HandleMatrixKick(u bridge.User, ghost bridge.Ghost, evt *event.Event) {
newParticipants := slices.DeleteFunc(slices.Clone(portal.Participants), func(uri uri.ParsedURI) bool {
return uri == ghost.(*Puppet).URI
})
portal.handleMatrixParticipantChange(u, evt, newParticipants)
}
func (portal *Portal) HandleMatrixInvite(u bridge.User, ghost bridge.Ghost, evt *event.Event) {
newParticipants := uri.Sort(append(slices.Clone(portal.Participants), ghost.(*Puppet).URI))
portal.handleMatrixParticipantChange(u, evt, newParticipants)
}
func (portal *Portal) SyncParticipants(memberURIs []uri.ParsedURI) (memberIDs []id.UserID) {
// Don't sync own ghosts into portal
memberURIs = slices.DeleteFunc(slices.Clone(memberURIs), func(uri uri.ParsedURI) bool {
return slices.Contains(portal.user.IM.User.Handles, uri)
})
var members map[id.UserID]mautrix.JoinedMember
if portal.MXID != "" {
membersResp, err := portal.MainIntent().JoinedMembers(portal.MXID)
if err != nil {
portal.log.Warnfln("Failed to get members in room to remove extra members: %v", err)
} else {
members = membersResp.Joined
delete(members, portal.bridge.Bot.UserID)
delete(members, portal.user.MXID)
}
}
portal.zlog.Debug().
Int("chat_info_member_count", len(memberURIs)).
Int("room_member_count", len(members)).
Msg("Syncing participants")
for _, memberURI := range memberURIs {
puppet := portal.user.GetPuppetByURI(memberURI)
puppet.Sync()
memberIDs = append(memberIDs, puppet.MXID)
if portal.MXID != "" {
err := puppet.Intent.EnsureJoined(portal.MXID)
if err != nil {
portal.log.Warnfln("Failed to make puppet of %s join %s: %v", memberURI, portal.MXID, err)
}
}
if members != nil {
delete(members, puppet.MXID)
}
}
if portal.MXID != "" && members != nil {
for userID := range members {
portal.log.Debugfln("Removing %s as they don't seem to be in the group anymore", userID)
_, err := portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
Reason: "user is no longer in group",
UserID: userID,
})
if err != nil {
portal.log.Errorfln("Failed to remove %s: %v", userID, err)
}
}
}
return memberIDs
}
func (portal *Portal) UpdateName(name string, intent *appservice.IntentAPI) bool {
if portal.Name == name && portal.NameSet {
return false
}
portal.Name = name
if len(portal.MXID) == 0 {
// We still want to count this as an update, but we won't actually set
// anything in a matrix room because there isn't one.
return true
}
if intent == nil {
intent = portal.MainIntent()
}
_, err := intent.SetRoomName(portal.MXID, name)
if mainIntent := portal.MainIntent(); errors.Is(err, mautrix.MForbidden) && intent != mainIntent {
_, err = mainIntent.SetRoomName(portal.MXID, name)
}
if err != nil {
portal.log.Warnln("Failed to set room name:", err)
} else {
portal.Name = name
portal.NameSet = true
portal.UpdateBridgeInfo()
return true
}
return false
}
func (portal *Portal) SyncWithInfo(sourceMsg *imessage.Message) {
portal.zlog.Debug().Msg("Syncing with chat info")
update := false
if sourceMsg.GroupID != "" && sourceMsg.GroupID != portal.GroupID {
portal.log.Infofln("Found portal thread ID in sync: %s (prev: %s)", sourceMsg.GroupID, portal.GroupID)
portal.GroupID = sourceMsg.GroupID
update = true
}
if !portal.IsPrivateChat() {
update = portal.UpdateName(sourceMsg.GroupName, nil) || update
portal.SyncParticipants(sourceMsg.Participants)
}
if update {
// TODO don't ignore errors
portal.Update(context.TODO())
portal.UpdateBridgeInfo()
}
}
func (portal *Portal) ensureUserInvited(user *User) {
user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat())
}
func (portal *Portal) Sync(backfill bool) {
if len(portal.MXID) == 0 {
portal.log.Infoln("Creating Matrix room due to sync")
err := portal.CreateMatrixRoom(nil)
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
}
return
}
portal.ensureUserInvited(portal.user)
portal.addToSpace(portal.user)
pls, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
portal.zlog.Warn().Err(err).Msg("Failed to get power levels")
} else if portal.updatePowerLevels(pls) {
resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, pls)
if err != nil {
portal.zlog.Warn().Err(err).Msg("Failed to update power levels")
} else {
portal.zlog.Debug().Str("event_id", resp.EventID.String()).Msg("Updated power levels")
}
}
if !portal.IsPrivateChat() {
// TODO can anything be synced in group chats?
} else {
portal.GetDMPuppet().Sync()
}
}
type CustomReadReceipt struct {
Timestamp int64 `json:"ts,omitempty"`
DoublePuppetSource string `json:"fi.mau.double_puppet_source,omitempty"`
}
type CustomReadMarkers struct {
mautrix.ReqSetReadMarkers
ReadExtra CustomReadReceipt `json:"com.beeper.read.extra"`
FullyReadExtra CustomReadReceipt `json:"com.beeper.fully_read.extra"`
}
func (portal *Portal) markRead(intent *appservice.IntentAPI, eventID id.EventID, readAt time.Time) error {
if intent == nil {
return nil
}
var extra CustomReadReceipt
if intent == portal.user.DoublePuppetIntent {
extra.DoublePuppetSource = portal.bridge.Name
}
if !readAt.IsZero() {
extra.Timestamp = readAt.UnixMilli()
}
content := CustomReadMarkers{
ReqSetReadMarkers: mautrix.ReqSetReadMarkers{
Read: eventID,
FullyRead: eventID,
},
ReadExtra: extra,
FullyReadExtra: extra,
}
return intent.SetReadMarkers(portal.MXID, &content)
}
func (portal *Portal) HandleiMessageReadReceipt(rr *imessage.ReadReceipt) {
if len(portal.MXID) == 0 {
return
}
var intent *appservice.IntentAPI
if rr.IsFromMe {
intent = portal.user.DoublePuppetIntent
} else if portal.IsPrivateChat() {
intent = portal.MainIntent()
} else {
portal.log.Debugfln("Dropping unexpected read receipt %+v", *rr)
return
}
if intent == nil {
portal.log.Errorfln("Dropping read receipt %+v because intent is nil", *rr)
return
}
// TODO don't ignore errors
if message, _ := portal.bridge.DB.Message.GetLastPartByID(context.TODO(), portal.Key, rr.ReadUpTo); message != nil {
err := portal.markRead(intent, message.MXID, rr.ReadAt)
if err != nil {
portal.log.Warnln("Failed to send read receipt for %s from %s: %v", message.MXID, intent.UserID)
}
} else if tapback, _ := portal.bridge.DB.Tapback.GetByTapbackID(context.TODO(), portal.Key, rr.ReadUpTo); tapback != nil {
err := portal.markRead(intent, tapback.MXID, rr.ReadAt)
if err != nil {
portal.log.Warnln("Failed to send read receipt for %s from %s: %v", tapback.MXID, intent.UserID)
}
} else {
portal.log.Debugfln("Dropping read receipt for %s: not found in db messages or tapbacks", rr.ReadUpTo)
}
}
type UnreadAccountData struct {
Unread bool `json:"unread"`
Timestamp uint64 `json:"ts,omitempty"`
}
func (portal *Portal) HandleiMessageMarkUnread(msg *imessage.MarkUnread) {
markedUnreadKey := "m.marked_unread"
markedUnread := UnreadAccountData{
Unread: true,
Timestamp: uint64(time.Now().UnixMilli()),
}
err := portal.user.DoublePuppetIntent.SetRoomAccountData(portal.MXID, markedUnreadKey, &markedUnread)
if err != nil {
portal.zlog.Err(err).Msg("Couldn't set account data to mark unread")
}
}
func (portal *Portal) handleMessageLoop() {
for {
var start time.Time
var thing string
select {
case untypedMsg := <-portal.Messages:
start = time.Now()
switch msg := untypedMsg.(type) {
case *imessage.Message:
thing = "iMessage"
portal.HandleiMessage(msg)
case *imessage.GroupInfoChange:
portal.HandleiMessageGroupInfoChange(msg)
case *imessage.MessageEdit:
thing = "iMessage edit"
portal.HandleiMessageEdit(msg)
case *imessage.MessageUnsend:
thing = "iMessage unsend"
portal.HandleiMessageUnsend(msg)
case *imessage.ReadReceipt:
thing = "read receipt"
portal.HandleiMessageReadReceipt(msg)
case *imessage.MarkUnread:
thing = "mark unread"
portal.HandleiMessageMarkUnread(msg)
case *imessage.SendMessageStatus:
thing = "message status"
portal.HandleiMessageSendMessageStatus(msg)
case *direct.MessageDelivered:
thing = "delivered"
portal.HandleiMessageDelivered(msg)
default:
thing = "unsupported iMessage struct"
portal.log.Warnfln("Unsupported data type %T in portal message channel", untypedMsg)
}
case evt := <-portal.MatrixMessages:
start = time.Now()
switch evt.Type {
case event.EventMessage, event.EventSticker:
thing = "Matrix message"
portal.HandleMatrixMessage(evt)
case event.EventRedaction:
thing = "Matrix redaction"
portal.HandleMatrixRedaction(evt)
case event.EventReaction:
thing = "Matrix reaction"
portal.HandleMatrixReaction(evt)
default:
thing = "unsupported Matrix event"
portal.log.Warnfln("Unsupported event type %+v in portal message channel", evt.Type)
}
}
portal.log.Debugfln(
"Handled %s in %s",
thing, time.Since(start),
)
}
}
func (portal *Portal) HandleiMessageDelivered(deliv *direct.MessageDelivered) {
var eventID id.EventID
// TODO don't ignore errors
if msg, err := portal.bridge.DB.Message.GetLastPartByID(context.TODO(), portal.Key, deliv.ID); msg != nil {
eventID = msg.MXID
} else if tapback, _ := portal.bridge.DB.Tapback.GetByTapbackID(context.TODO(), portal.Key, deliv.ID); tapback != nil {
eventID = tapback.MXID
} else {
if err != nil {
fmt.Println("MEOW 3:<", err)
}
portal.log.Debugfln("Dropping delivered status for %s: not found in db messages or tapbacks", deliv.ID)
return
}
go portal.bridge.SendRawMessageCheckpoint(&status.MessageCheckpoint{
EventID: eventID,
RoomID: portal.MXID,
Step: status.MsgStepRemote,
Timestamp: jsontime.UnixMilliNow(),
Status: status.MsgStatusDelivered,
ReportedBy: status.MsgReportedByBridge,
})
deliveredTo := make([]id.UserID, 0, len(deliv.To))
for to := range deliv.To {
deliveredTo = append(deliveredTo, portal.bridge.FormatPuppetMXID(portal.user.RowID, to))
}
portal.zlog.Debug().
Array("delivered_to", exzerolog.ArrayOfStringers(deliveredTo)).
Stringer("message_uuid", deliv.ID).
Msg("Got delivery receipts for message")
// Only enable delivery status in groups for now
if portal.IsPrivateChat() && len(deliveredTo) == 1 && deliveredTo[0] == portal.MainIntent().UserID {
go portal.sendSuccessMessageStatus(eventID, deliv.ID, deliveredTo)
}
}
func (portal *Portal) HandleiMessageSendMessageStatus(msgStatus *imessage.SendMessageStatus) {
var eventID id.EventID
// TODO don't ignore errors
if msg, err := portal.bridge.DB.Message.GetLastPartByID(context.TODO(), portal.Key, msgStatus.GUID); msg != nil {
eventID = msg.MXID
} else if tapback, _ := portal.bridge.DB.Tapback.GetByTapbackID(context.TODO(), portal.Key, msgStatus.GUID); tapback != nil {
eventID = tapback.MXID
} else {
if err != nil {
fmt.Println("MEOW 3:<", err)
}
portal.log.Debugfln("Dropping send message status for %s: not found in db messages or tapbacks", msgStatus.GUID)
return
}
portal.log.Debugfln("Processing message status with type %s/%s for event %s/%s in %s/%s", msgStatus.Status, msgStatus.StatusCode, eventID, msgStatus.GUID, portal.MXID, portal.URI)
switch msgStatus.Status {
case "delivered":
go portal.bridge.SendRawMessageCheckpoint(&status.MessageCheckpoint{
EventID: eventID,
RoomID: portal.MXID,
Step: status.MsgStepRemote,
Timestamp: jsontime.UnixMilliNow(),
Status: status.MsgStatusDelivered,
ReportedBy: status.MsgReportedByBridge,
})
if p := portal.GetDMPuppet(); p != nil {
go portal.sendSuccessMessageStatus(eventID, msgStatus.GUID, []id.UserID{p.MXID})
}
case "fail":
portal.zlog.Debug().Any("status", msgStatus).Msg("Got failed message status")
evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID)
if err != nil {
portal.log.Warnfln("Failed to lookup event %s/%s %s/%s: %v", string(eventID), portal.MXID, msgStatus.GUID, portal.URI, err)
return
}
errString := "internal error"
humanReadableError := "internal error"
if len(msgStatus.Message) != 0 {
humanReadableError = msgStatus.Message
if len(msgStatus.StatusCode) != 0 {
errString = fmt.Sprintf("%s: %s", msgStatus.StatusCode, msgStatus.Message)
} else {
errString = msgStatus.Message
}
} else if len(msgStatus.StatusCode) != 0 {
errString = msgStatus.StatusCode
}
portal.sendErrorMessage(evt, errors.New(errString), humanReadableError, true, status.MsgStatusPermFailure)
default:
portal.log.Warnfln("Unrecognized message status type %s", msgStatus.Status)
}
}
func (portal *Portal) GetBasePowerLevels() *event.PowerLevelsEventContent {
anyone := 0
nope := 99
return &event.PowerLevelsEventContent{
UsersDefault: anyone,
EventsDefault: anyone,
RedactPtr: &anyone,
StateDefaultPtr: &nope,
BanPtr: &nope,
InvitePtr: &anyone,
KickPtr: &anyone,
Users: map[id.UserID]int{
portal.user.MXID: 1,
portal.MainIntent().UserID: 100,
portal.bridge.Bot.UserID: 100,
},
Events: map[string]int{
event.StateRoomName.Type: anyone,
event.StateRoomAvatar.Type: anyone,
event.StateTopic.Type: anyone,
},
}
}
func (portal *Portal) updatePowerLevels(pl *event.PowerLevelsEventContent) bool {
update := false
anyone := 0
if pl.Invite() != anyone {
pl.InvitePtr = &anyone
update = true
}
if pl.Kick() != anyone {
pl.KickPtr = &anyone
update = true
}
update = pl.EnsureUserLevel(portal.user.MXID, 1) || update
return pl.EnsureUserLevel(portal.bridge.Bot.UserID, 100) || update
}
const bridgeInfoProto = "fi.mau.imessage"
func (portal *Portal) getBridgeInfoStateKey() string {
return fmt.Sprintf("%s://%s/%s",
bridgeInfoProto, strings.ToLower(portal.Service.String()), portal.URI.Identifier)
}
func (portal *Portal) GetBridgeInfo() (string, *database.CustomBridgeInfoContent) {
content := portal.Portal.GetBridgeInfo()
content.BridgeEventContent.BridgeBot = portal.bridge.Bot.UserID
content.BridgeEventContent.Creator = portal.MainIntent().UserID
content.BridgeEventContent.Protocol.AvatarURL = id.ContentURIString(portal.bridge.Config.AppService.Bot.Avatar)
return portal.getBridgeInfoStateKey(), content
}
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...")
intent := portal.MainIntent()
if portal.Encrypted && intent != portal.bridge.Bot && portal.IsPrivateChat() {
intent = portal.bridge.Bot
}
stateKey, content := portal.GetBridgeInfo()
_, err := intent.SendStateEvent(portal.MXID, event.StateBridge, stateKey, content)
if err != nil {
portal.log.Warnln("Failed to update m.bridge:", err)
}
_, err = intent.SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
if err != nil {
portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
}
}
func (portal *Portal) GetEncryptionEventContent() (evt *event.EncryptionEventContent) {
evt = &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1}
if rot := portal.bridge.Config.Bridge.Encryption.Rotation; rot.EnableCustom {
evt.RotationPeriodMillis = rot.Milliseconds
evt.RotationPeriodMessages = rot.Messages
}
return
}
func (portal *Portal) shouldSetDMRoomMetadata() bool {
return !portal.IsPrivateChat() ||
portal.bridge.Config.Bridge.PrivateChatPortalMeta == "always" ||
(portal.IsEncrypted() && portal.bridge.Config.Bridge.PrivateChatPortalMeta != "never")
}
func (portal *Portal) getRoomCreateContent() *mautrix.ReqCreateRoom {
bridgeInfoStateKey, bridgeInfo := portal.GetBridgeInfo()
initialState := []*event.Event{{
Type: event.StatePowerLevels,
Content: event.Content{
Parsed: portal.GetBasePowerLevels(),
},
}, {
Type: event.StateBridge,
Content: event.Content{Parsed: bridgeInfo},
StateKey: &bridgeInfoStateKey,
}, {
// TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
Type: event.StateHalfShotBridge,
Content: event.Content{Parsed: bridgeInfo},
StateKey: &bridgeInfoStateKey,
}}
if portal.bridge.Config.Bridge.Encryption.Default {
initialState = append(initialState, &event.Event{
Type: event.StateEncryption,
Content: event.Content{
Parsed: portal.GetEncryptionEventContent(),
},
})
portal.Encrypted = true
}
if parsedAvatarURL, err := portal.AvatarURL.Parse(); err != nil {
portal.log.Warnln("Failed to parse avatar URL:", err)
} else if !parsedAvatarURL.IsEmpty() && portal.shouldSetDMRoomMetadata() {
initialState = append(initialState, &event.Event{
Type: event.StateRoomAvatar,
Content: event.Content{
Parsed: event.RoomAvatarEventContent{URL: parsedAvatarURL},
},
})
}
var invite []id.UserID
if portal.IsPrivateChat() {
invite = append(invite, portal.bridge.Bot.UserID)
}
autoJoinInvites := portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry
if autoJoinInvites {
invite = append(invite, portal.user.MXID)
}
creationContent := make(map[string]interface{})
if !portal.bridge.Config.Bridge.FederateRooms {
creationContent["m.federate"] = false
}
req := &mautrix.ReqCreateRoom{
Visibility: "private",
Name: portal.Name,
Invite: invite,
Preset: "private_chat",
IsDirect: portal.IsPrivateChat(),
InitialState: initialState,
CreationContent: creationContent,
BeeperAutoJoinInvites: autoJoinInvites,
}
if !portal.shouldSetDMRoomMetadata() {
req.Name = ""
}
return req
}
// CreateMatrixRoom creates a matrix room
// sourceMsg is only required for group chats, otherwise can be nil
func (portal *Portal) CreateMatrixRoom(sourceMsg *imessage.Message) error {
portal.roomCreateLock.Lock()
defer portal.roomCreateLock.Unlock()
if len(portal.MXID) > 0 {
return nil
}
intent := portal.MainIntent()
err := intent.EnsureRegistered()
if err != nil {
return err
}
if portal.IsPrivateChat() {
puppet := portal.GetDMPuppet()
puppet.Sync()
portal.Name = puppet.Displayname
portal.AvatarURL = puppet.AvatarURL.CUString()
portal.AvatarHash = puppet.AvatarHash
if sourceMsg != nil {
portal.Service = sourceMsg.Service
} else {
portal.Service = imessage.ServiceIMessage
}
} else {
// If there's no chat info for a group, it probably doesn't exist, and we shouldn't auto-create a Matrix room for it.
if sourceMsg == nil {
return fmt.Errorf("failed to get chat info: not implemented")
}
portal.Name = sourceMsg.GroupName
portal.GroupID = sourceMsg.GroupID
portal.Participants = sourceMsg.Participants
portal.Service = sourceMsg.Service
}
req := portal.getRoomCreateContent()
if req.BeeperAutoJoinInvites && !portal.IsPrivateChat() {
req.Invite = append(req.Invite, portal.SyncParticipants(sourceMsg.Participants)...)
}
resp, err := intent.CreateRoom(req)
if err != nil {
return err
}
portal.NameSet = true
portal.AvatarSet = true
portal.MXID = resp.RoomID
portal.updateLogger()
portal.zlog.Debug().Msg("Storing created room ID in database")
// TODO don't ignore errors
portal.Update(context.TODO())
portal.bridge.portalsLock.Lock()
portal.bridge.portalsByMXID[portal.MXID] = portal
portal.bridge.portalsLock.Unlock()
portal.zlog.Debug().Interface("members", req.Invite).Msg("Updating state store with initial memberships")