forked from mautrix/signal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
portal.go
2186 lines (2023 loc) · 74.3 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-signal - A Matrix-signal puppeting bridge.
// Copyright (C) 2023 Scott Weber, 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/sha256"
"encoding/hex"
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog"
"go.mau.fi/util/jsontime"
"go.mau.fi/util/variationselector"
"google.golang.org/protobuf/proto"
"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"
"go.mau.fi/mautrix-signal/database"
"go.mau.fi/mautrix-signal/msgconv"
"go.mau.fi/mautrix-signal/msgconv/matrixfmt"
"go.mau.fi/mautrix-signal/msgconv/signalfmt"
"go.mau.fi/mautrix-signal/pkg/signalmeow"
"go.mau.fi/mautrix-signal/pkg/signalmeow/events"
signalpb "go.mau.fi/mautrix-signal/pkg/signalmeow/protobuf"
"go.mau.fi/mautrix-signal/pkg/signalmeow/types"
)
func (br *SignalBridge) GetPortalByMXID(mxid id.RoomID) *Portal {
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
portal, ok := br.portalsByMXID[mxid]
if !ok {
dbPortal, err := br.DB.Portal.GetByMXID(context.TODO(), mxid)
if err != nil {
br.ZLog.Err(err).Msg("Failed to get portal from database")
return nil
}
return br.loadPortal(context.TODO(), dbPortal, nil)
}
return portal
}
func (br *SignalBridge) GetPortalByChatID(key database.PortalKey) *Portal {
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
// If this PortalKey is for a group, Receiver should be empty
if key.UserID() == uuid.Nil {
key.Receiver = uuid.Nil
}
portal, ok := br.portalsByID[key]
if !ok {
dbPortal, err := br.DB.Portal.GetByChatID(context.TODO(), key)
if err != nil {
br.ZLog.Err(err).Msg("Failed to get portal from database")
return nil
}
return br.loadPortal(context.TODO(), dbPortal, &key)
}
return portal
}
func (br *SignalBridge) GetAllPortalsWithMXID() []*Portal {
portals, err := br.dbPortalsToPortals(br.DB.Portal.GetAllWithMXID(context.TODO()))
if err != nil {
br.ZLog.Err(err).Msg("Failed to get all portals with mxid")
return nil
}
return portals
}
func (br *SignalBridge) FindPrivateChatPortalsWith(userID uuid.UUID) []*Portal {
portals, err := br.dbPortalsToPortals(br.DB.Portal.FindPrivateChatsWith(context.TODO(), userID))
if err != nil {
br.ZLog.Err(err).Msg("Failed to get all DM portals with user")
return nil
}
return portals
}
func (br *SignalBridge) GetAllIPortals() (iportals []bridge.Portal) {
portals, err := br.dbPortalsToPortals(br.DB.Portal.GetAllWithMXID(context.TODO()))
if err != nil {
br.ZLog.Err(err).Msg("Failed to get all portals with mxid")
return nil
}
iportals = make([]bridge.Portal, len(portals))
for i, portal := range portals {
iportals[i] = portal
}
return iportals
}
func (br *SignalBridge) loadPortal(ctx context.Context, dbPortal *database.Portal, key *database.PortalKey) *Portal {
if dbPortal == nil {
if key == nil {
return nil
}
dbPortal = br.DB.Portal.New()
dbPortal.PortalKey = *key
err := dbPortal.Insert(ctx)
if err != nil {
br.ZLog.Err(err).Msg("Failed to insert new portal")
return nil
}
}
portal := br.NewPortal(dbPortal)
br.portalsByID[portal.PortalKey] = portal
if portal.MXID != "" {
br.portalsByMXID[portal.MXID] = portal
}
return portal
}
func (br *SignalBridge) dbPortalsToPortals(dbPortals []*database.Portal, err error) ([]*Portal, error) {
if err != nil {
return nil, err
}
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
output := make([]*Portal, len(dbPortals))
for index, dbPortal := range dbPortals {
if dbPortal == nil {
continue
}
portal, ok := br.portalsByID[dbPortal.PortalKey]
if !ok {
portal = br.loadPortal(context.TODO(), dbPortal, nil)
}
output[index] = portal
}
return output, nil
}
type portalSignalMessage struct {
evt *events.ChatEvent
user *User
}
type portalMatrixMessage struct {
evt *event.Event
user *User
}
type Portal struct {
*database.Portal
MsgConv *msgconv.MessageConverter
bridge *SignalBridge
log zerolog.Logger
roomCreateLock sync.Mutex
encryptLock sync.Mutex
signalMessages chan portalSignalMessage
matrixMessages chan portalMatrixMessage
currentlyTyping []id.UserID
currentlyTypingLock sync.Mutex
relayUser *User
}
var signalFormatParams *signalfmt.FormatParams
var matrixFormatParams *matrixfmt.HTMLParser
func (br *SignalBridge) NewPortal(dbPortal *database.Portal) *Portal {
log := br.ZLog.With().Str("chat_id", dbPortal.ChatID).Logger()
if dbPortal.MXID != "" {
log = log.With().Stringer("room_id", dbPortal.MXID).Logger()
}
portal := &Portal{
Portal: dbPortal,
bridge: br,
log: log,
signalMessages: make(chan portalSignalMessage, br.Config.Bridge.PortalMessageBuffer),
matrixMessages: make(chan portalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
}
portal.MsgConv = &msgconv.MessageConverter{
PortalMethods: portal,
SignalFmtParams: signalFormatParams,
MatrixFmtParams: matrixFormatParams,
ConvertVoiceMessages: true,
MaxFileSize: br.MediaConfig.UploadSize,
}
go portal.messageLoop()
return portal
}
func init() {
event.TypeMap[event.StateBridge] = reflect.TypeOf(CustomBridgeInfoContent{})
event.TypeMap[event.StateHalfShotBridge] = reflect.TypeOf(CustomBridgeInfoContent{})
}
var (
_ bridge.Portal = (*Portal)(nil)
_ bridge.ReadReceiptHandlingPortal = (*Portal)(nil)
_ bridge.TypingPortal = (*Portal)(nil)
_ bridge.DisappearingPortal = (*Portal)(nil)
//_ bridge.MembershipHandlingPortal = (*Portal)(nil)
//_ bridge.MetaHandlingPortal = (*Portal)(nil)
)
func (portal *Portal) IsEncrypted() bool {
return portal.Encrypted
}
func (portal *Portal) MarkEncrypted() {
portal.Encrypted = true
err := portal.Update(context.TODO())
if err != nil {
portal.log.Err(err).Msg("Failed to update portal in database after marking as encrypted")
}
}
func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser || portal.HasRelaybot() {
portal.matrixMessages <- portalMatrixMessage{user: user.(*User), evt: evt}
}
}
func (portal *Portal) GetRelayUser() *User {
if !portal.HasRelaybot() {
return nil
} else if portal.relayUser == nil {
portal.relayUser = portal.bridge.GetUserByMXID(portal.RelayUserID)
}
return portal.relayUser
}
func (portal *Portal) IsPrivateChat() bool {
return portal.UserID() != uuid.Nil
}
func (portal *Portal) IsNoteToSelf() bool {
userID := portal.UserID()
return userID != uuid.Nil && userID == portal.Receiver
}
func (portal *Portal) MainIntent() *appservice.IntentAPI {
if portal.IsPrivateChat() {
return portal.bridge.GetPuppetBySignalID(portal.UserID()).DefaultIntent()
}
return portal.bridge.Bot
}
type CustomBridgeInfoContent struct {
event.BridgeEventContent
RoomType string `json:"com.beeper.room_type,omitempty"`
}
func (portal *Portal) getBridgeInfo() (string, CustomBridgeInfoContent) {
bridgeInfo := event.BridgeEventContent{
BridgeBot: portal.bridge.Bot.UserID,
Creator: portal.MainIntent().UserID,
Protocol: event.BridgeInfoSection{
ID: "signal",
DisplayName: "Signal",
AvatarURL: portal.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
ExternalURL: "https://signal.org/",
},
Channel: event.BridgeInfoSection{
ID: portal.ChatID,
DisplayName: portal.Name,
AvatarURL: portal.AvatarURL.CUString(),
},
}
bridgeInfoStateKey := fmt.Sprintf("fi.mau.signal://signal/%s", portal.ChatID)
bridgeInfo.Channel.ExternalURL = fmt.Sprintf("https://signal.me/#p/%s", portal.ChatID)
var roomType string
if portal.IsPrivateChat() {
roomType = "dm"
}
return bridgeInfoStateKey, CustomBridgeInfoContent{bridgeInfo, roomType}
}
func (portal *Portal) UpdateBridgeInfo(ctx context.Context) {
if len(portal.MXID) == 0 {
portal.log.Debug().Msg("Not updating bridge info: no Matrix room created")
return
}
portal.log.Debug().Msg("Updating bridge info...")
stateKey, content := portal.getBridgeInfo()
_, err := portal.MainIntent().SendStateEvent(ctx, portal.MXID, event.StateBridge, stateKey, content)
if err != nil {
portal.log.Warn().Err(err).Msg("Failed to update m.bridge")
}
// TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
_, err = portal.MainIntent().SendStateEvent(ctx, portal.MXID, event.StateHalfShotBridge, stateKey, content)
if err != nil {
portal.log.Warn().Err(err).Msg("Failed to update uk.half-shot.bridge")
}
}
func (portal *Portal) messageLoop() {
for {
select {
case msg := <-portal.matrixMessages:
portal.handleMatrixMessages(msg)
case msg := <-portal.signalMessages:
portal.handleSignalMessage(msg)
}
}
}
func (portal *Portal) handleMatrixMessages(msg portalMatrixMessage) {
log := portal.log.With().
Str("action", "handle matrix event").
Stringer("event_id", msg.evt.ID).
Str("event_type", msg.evt.Type.String()).
Logger()
ctx := log.WithContext(context.TODO())
switch msg.evt.Type {
case event.EventMessage, event.EventSticker:
portal.handleMatrixMessage(ctx, msg.user, msg.evt)
case event.EventRedaction:
portal.handleMatrixRedaction(ctx, msg.user, msg.evt)
case event.EventReaction:
portal.handleMatrixReaction(ctx, msg.user, msg.evt)
default:
log.Warn().Str("type", msg.evt.Type.Type).Msg("Unhandled matrix message type")
}
}
func (portal *Portal) handleMatrixMessage(ctx context.Context, sender *User, evt *event.Event) {
log := zerolog.Ctx(ctx)
evtTS := time.UnixMilli(evt.Timestamp)
timings := messageTimings{
initReceive: evt.Mautrix.ReceivedAt.Sub(evtTS),
decrypt: evt.Mautrix.DecryptionDuration,
totalReceive: time.Since(evtTS),
}
implicitRRStart := time.Now()
portal.handleMatrixReadReceipt(sender, "", uint64(evt.Timestamp), false)
timings.implicitRR = time.Since(implicitRRStart)
start := time.Now()
messageAge := timings.totalReceive
ms := metricSender{portal: portal, timings: &timings, ctx: ctx}
log.Debug().
Stringer("sender", evt.Sender).
Dur("age", messageAge).
Msg("Received message")
errorAfter := portal.bridge.Config.Bridge.MessageHandlingTimeout.ErrorAfter
deadline := portal.bridge.Config.Bridge.MessageHandlingTimeout.Deadline
isScheduled, _ := evt.Content.Raw["com.beeper.scheduled"].(bool)
if isScheduled {
log.Debug().Msg("Message is a scheduled message, extending handling timeouts")
errorAfter *= 10
deadline *= 10
}
if errorAfter > 0 {
remainingTime := errorAfter - messageAge
if remainingTime < 0 {
go ms.sendMessageMetrics(evt, errTimeoutBeforeHandling, "Timeout handling", true)
return
} else if remainingTime < 1*time.Second {
log.Warn().
Dur("remaining_time", remainingTime).
Dur("max_timeout", errorAfter).
Msg("Message was delayed before reaching the bridge")
}
go func() {
time.Sleep(remainingTime)
ms.sendMessageMetrics(evt, errMessageTakingLong, "Timeout handling", false)
}()
}
if deadline > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, deadline)
defer cancel()
}
timings.preproc = time.Since(start)
start = time.Now()
content, ok := evt.Content.Parsed.(*event.MessageEventContent)
if !ok {
log.Error().Type("content_type", content).Msg("Unexpected parsed content type")
go ms.sendMessageMetrics(evt, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed), "Error converting", true)
return
}
realSenderMXID := sender.MXID
isRelay := false
if !sender.IsLoggedIn() {
sender = portal.GetRelayUser()
if sender == nil {
go ms.sendMessageMetrics(evt, errUserNotLoggedIn, "Ignoring", true)
return
} else if !sender.IsLoggedIn() {
go ms.sendMessageMetrics(evt, errRelaybotNotLoggedIn, "Ignoring", true)
return
}
isRelay = true
}
var editTargetMsg *database.Message
if editTarget := content.RelatesTo.GetReplaceID(); editTarget != "" {
var err error
editTargetMsg, err = portal.bridge.DB.Message.GetByMXID(ctx, editTarget)
if err != nil {
log.Err(err).Stringer("edit_target_mxid", editTarget).Msg("Failed to get edit target message")
go ms.sendMessageMetrics(evt, errFailedToGetEditTarget, "Error converting", true)
return
} else if editTargetMsg == nil {
log.Err(err).Stringer("edit_target_mxid", editTarget).Msg("Edit target message not found")
go ms.sendMessageMetrics(evt, errEditUnknownTarget, "Error converting", true)
return
} else if editTargetMsg.Sender != sender.SignalID {
go ms.sendMessageMetrics(evt, errEditDifferentSender, "Error converting", true)
return
}
if content.NewContent != nil {
content = content.NewContent
evt.Content.Parsed = content
}
}
relaybotFormatted := isRelay && portal.addRelaybotFormat(ctx, realSenderMXID, evt, content)
if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
go ms.sendMessageMetrics(evt, errMNoticeDisabled, "Error converting", true)
return
}
ctx = context.WithValue(ctx, msgconvContextKeyClient, sender.Client)
msg, err := portal.MsgConv.ToSignal(ctx, evt, content, relaybotFormatted)
if err != nil {
log.Err(err).Msg("Failed to convert message")
go ms.sendMessageMetrics(evt, err, "Error converting", true)
return
}
var wrappedMsg *signalpb.Content
if editTargetMsg == nil {
wrappedMsg = &signalpb.Content{
DataMessage: msg,
}
} else {
wrappedMsg = &signalpb.Content{
EditMessage: &signalpb.EditMessage{
TargetSentTimestamp: proto.Uint64(editTargetMsg.Timestamp),
DataMessage: msg,
},
}
}
timings.convert = time.Since(start)
start = time.Now()
err = portal.sendSignalMessage(ctx, wrappedMsg, sender, evt.ID)
timings.totalSend = time.Since(start)
go ms.sendMessageMetrics(evt, err, "Error sending", true)
if err == nil {
if editTargetMsg != nil {
err = editTargetMsg.SetTimestamp(ctx, msg.GetTimestamp())
if err != nil {
log.Err(err).Msg("Failed to update message timestamp in database after editing")
}
} else {
portal.storeMessageInDB(ctx, evt.ID, sender.SignalID, msg.GetTimestamp(), 0)
if portal.ExpirationTime > 0 {
portal.addDisappearingMessage(ctx, evt.ID, uint32(portal.ExpirationTime), true)
}
}
}
}
func (portal *Portal) handleMatrixRedaction(ctx context.Context, sender *User, evt *event.Event) {
log := zerolog.Ctx(ctx)
// Find the original signal message based on eventID
dbMessage, err := portal.bridge.DB.Message.GetByMXID(ctx, evt.Redacts)
if err != nil {
log.Err(err).Msg("Failed to get redaction target message")
}
// Might be a reaction redaction, find the original message for the reaction
dbReaction, err := portal.bridge.DB.Reaction.GetByMXID(ctx, evt.Redacts)
if err != nil {
log.Err(err).Msg("Failed to get redaction target reaction")
}
if !sender.IsLoggedIn() {
sender = portal.GetRelayUser()
if sender == nil {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errUserNotLoggedIn)
return
} else if !sender.IsLoggedIn() {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errRelaybotNotLoggedIn)
return
}
}
if dbMessage != nil {
if dbMessage.Sender != sender.SignalID {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errRedactionTargetSentBySomeoneElse)
return
}
msg := signalmeow.DataMessageForDelete(dbMessage.Timestamp)
err = portal.sendSignalMessage(ctx, msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(ctx, evt, err)
log.Err(err).Msg("Failed to send message redaction to Signal")
return
}
err = dbMessage.Delete(ctx)
if err != nil {
log.Err(err).Msg("Failed to delete redacted message from database")
} else if otherParts, err := portal.bridge.DB.Message.GetAllPartsBySignalID(ctx, dbMessage.Sender, dbMessage.Timestamp, portal.Receiver); err != nil {
log.Err(err).Msg("Failed to get other parts of redacted message from database")
} else if len(otherParts) > 0 {
// If there are other parts of the message, send a redaction for each of them
for _, otherPart := range otherParts {
_, err = portal.MainIntent().RedactEvent(ctx, portal.MXID, otherPart.MXID, mautrix.ReqRedact{
Reason: "Other part of Signal message redacted",
TxnID: "mxsg_partredact_" + otherPart.MXID.String(),
})
if err != nil {
log.Err(err).
Stringer("part_event_id", otherPart.MXID).
Int("part_index", otherPart.PartIndex).
Msg("Failed to redact other part of redacted message")
}
err = otherPart.Delete(ctx)
if err != nil {
log.Err(err).
Stringer("part_event_id", otherPart.MXID).
Int("part_index", otherPart.PartIndex).
Msg("Failed to delete other part of redacted message from database")
}
}
}
portal.sendMessageStatusCheckpointSuccess(ctx, evt)
} else if dbReaction != nil {
if dbReaction.Author != sender.SignalID {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errUnreactTargetSentBySomeoneElse)
return
}
msg := signalmeow.DataMessageForReaction(dbReaction.Emoji, dbReaction.MsgAuthor, dbReaction.MsgTimestamp, true)
err = portal.sendSignalMessage(ctx, msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(ctx, evt, err)
log.Err(err).Msg("Failed to send reaction redaction to Signal")
return
}
err = dbReaction.Delete(ctx)
if err != nil {
log.Err(err).Msg("Failed to delete redacted reaction from database")
}
portal.sendMessageStatusCheckpointSuccess(ctx, evt)
} else {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errRedactionTargetNotFound)
}
}
func (portal *Portal) handleMatrixReaction(ctx context.Context, sender *User, evt *event.Event) {
log := zerolog.Ctx(ctx)
if !sender.IsLoggedIn() {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errCantRelayReactions)
return
}
// Find the original signal message based on eventID
relatedEventID := evt.Content.AsReaction().RelatesTo.EventID
targetMsg, err := portal.bridge.DB.Message.GetByMXID(ctx, relatedEventID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(ctx, evt, err)
log.Err(err).Msg("Failed to get reaction target message")
return
} else if targetMsg == nil {
portal.sendMessageStatusCheckpointFailed(ctx, evt, errReactionTargetNotFound)
log.Warn().Msg("Reaction target message not found")
return
}
emoji := evt.Content.AsReaction().RelatesTo.Key
signalEmoji := variationselector.FullyQualify(emoji) // Signal seems to require fully qualified emojis
msg := signalmeow.DataMessageForReaction(signalEmoji, targetMsg.Sender, targetMsg.Timestamp, false)
err = portal.sendSignalMessage(ctx, msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(ctx, evt, err)
log.Error().Msg("Failed to send reaction")
return
}
// Signal only allows one reaction from each user
// Check if there's an existing reaction in the database for this sender and redact/delete it
dbReaction, err := portal.bridge.DB.Reaction.GetBySignalID(
ctx,
targetMsg.Sender,
targetMsg.Timestamp,
sender.SignalID,
portal.Receiver,
)
if err != nil {
log.Err(err).Msg("Failed to get existing reaction from database")
} else if dbReaction != nil {
log.Debug().Stringer("existing_event_id", dbReaction.MXID).Msg("Redacting existing reaction after sending new one")
_, err = portal.MainIntent().RedactEvent(ctx, portal.MXID, dbReaction.MXID)
if err != nil {
log.Err(err).Msg("Failed to redact existing reaction")
}
}
if dbReaction != nil {
dbReaction.MXID = evt.ID
dbReaction.Emoji = signalEmoji
err = dbReaction.Update(ctx)
if err != nil {
log.Err(err).Msg("Failed to update reaction in database")
}
} else {
dbReaction = portal.bridge.DB.Reaction.New()
dbReaction.MXID = evt.ID
dbReaction.RoomID = portal.MXID
dbReaction.SignalChatID = portal.ChatID
dbReaction.SignalReceiver = portal.Receiver
dbReaction.Author = sender.SignalID
dbReaction.MsgAuthor = targetMsg.Sender
dbReaction.MsgTimestamp = targetMsg.Timestamp
dbReaction.Emoji = signalEmoji
err = dbReaction.Insert(ctx)
if err != nil {
log.Err(err).Msg("Failed to insert reaction to database")
}
}
portal.sendMessageStatusCheckpointSuccess(ctx, evt)
}
func (portal *Portal) sendSignalMessage(ctx context.Context, msg *signalpb.Content, sender *User, evtID id.EventID) error {
log := zerolog.Ctx(ctx).With().
Str("action", "send signal message").
Stringer("event_id", evtID).
Str("portal_chat_id", portal.ChatID).
Logger()
ctx = log.WithContext(ctx)
log.Debug().Msg("Sending event to Signal")
// Check to see if portal.ChatID is a standard UUID (with dashes)
if portal.IsPrivateChat() {
// this is a 1:1 chat
result := sender.Client.SendMessage(ctx, portal.UserID(), msg)
if !result.WasSuccessful {
return result.Error
}
} else {
// this is a group chat
groupID := types.GroupIdentifier(portal.ChatID)
result, err := sender.Client.SendGroupMessage(ctx, groupID, msg)
if err != nil {
// check the start of the error string, see if it starts with "No group master key found for group identifier"
if strings.HasPrefix(err.Error(), "No group master key found for group identifier") {
portal.MainIntent().SendNotice(ctx, portal.MXID, "Missing group encryption key. Please ask a group member to send a message in this chat, then retry sending.")
}
log.Err(err).Msg("Error sending event to Signal group")
return err
}
totalRecipients := len(result.FailedToSendTo) + len(result.SuccessfullySentTo)
log = log.With().
Int("total_recipients", totalRecipients).
Int("failed_to_send_to_count", len(result.FailedToSendTo)).
Int("successfully_sent_to_count", len(result.SuccessfullySentTo)).
Logger()
if len(result.FailedToSendTo) > 0 {
log.Error().Msg("Failed to send event to some members of Signal group")
}
if len(result.SuccessfullySentTo) == 0 && len(result.FailedToSendTo) == 0 {
log.Debug().Msg("No successes or failures - Probably sent to myself")
} else if len(result.SuccessfullySentTo) == 0 {
log.Error().Msg("Failed to send event to all members of Signal group")
return errors.New("failed to send to any members of Signal group")
} else if len(result.SuccessfullySentTo) < totalRecipients {
log.Warn().Msg("Only sent event to some members of Signal group")
} else {
log.Debug().Msg("Sent event to all members of Signal group")
}
}
return nil
}
func (portal *Portal) sendMessageStatusCheckpointSuccess(ctx context.Context, evt *event.Event) {
portal.sendDeliveryReceipt(ctx, evt.ID)
portal.bridge.SendMessageSuccessCheckpoint(evt, status.MsgStepRemote, 0)
var deliveredTo *[]id.UserID
if portal.IsPrivateChat() {
deliveredTo = &[]id.UserID{}
}
portal.sendStatusEvent(ctx, evt.ID, "", nil, deliveredTo)
}
func (portal *Portal) sendMessageStatusCheckpointFailed(ctx context.Context, evt *event.Event, err error) {
portal.sendDeliveryReceipt(ctx, evt.ID)
portal.bridge.SendMessageErrorCheckpoint(evt, status.MsgStepRemote, err, true, 0)
portal.sendStatusEvent(ctx, evt.ID, "", err, nil)
}
type msgconvContextKey int
const (
msgconvContextKeyIntent msgconvContextKey = iota
msgconvContextKeyClient
)
func (portal *Portal) UploadMatrixMedia(ctx context.Context, data []byte, fileName, contentType string) (id.ContentURIString, error) {
intent := ctx.Value(msgconvContextKeyIntent).(*appservice.IntentAPI)
req := mautrix.ReqUploadMedia{
ContentBytes: data,
ContentType: contentType,
FileName: fileName,
}
if portal.bridge.Config.Homeserver.AsyncMedia {
uploaded, err := intent.UploadAsync(ctx, req)
if err != nil {
return "", err
}
return uploaded.ContentURI.CUString(), nil
} else {
uploaded, err := intent.UploadMedia(ctx, 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().DownloadBytes(ctx, parsedURI)
}
func (portal *Portal) GetData(ctx context.Context) *database.Portal {
return portal.Portal
}
func (portal *Portal) GetClient(ctx context.Context) *signalmeow.Client {
return ctx.Value(msgconvContextKeyClient).(*signalmeow.Client)
}
func (portal *Portal) GetMatrixReply(ctx context.Context, msg *signalpb.DataMessage_Quote) (replyTo id.EventID, replyTargetSender id.UserID) {
if msg == nil {
return
}
log := zerolog.Ctx(ctx).With().
Str("reply_target_author", msg.GetAuthorAci()).
Uint64("reply_target_ts", msg.GetId()).
Logger()
if senderUUID, err := uuid.Parse(msg.GetAuthorAci()); err != nil {
log.Err(err).Msg("Failed to parse sender UUID in Signal quote")
} else if message, err := portal.bridge.DB.Message.GetBySignalID(ctx, senderUUID, msg.GetId(), 0, portal.Receiver); err != nil {
log.Err(err).Msg("Failed to get reply target message from database")
} else if message == nil {
log.Warn().Msg("Reply target message not found")
} else {
replyTo = message.MXID
targetUser := portal.bridge.GetUserBySignalID(message.Sender)
if targetUser != nil {
replyTargetSender = targetUser.MXID
} else {
replyTargetSender = portal.bridge.FormatPuppetMXID(message.Sender)
}
}
return
}
func (portal *Portal) GetSignalReply(ctx context.Context, content *event.MessageEventContent) *signalpb.DataMessage_Quote {
replyToID := content.RelatesTo.GetReplyTo()
if len(replyToID) == 0 {
return nil
}
replyToMsg, err := portal.bridge.DB.Message.GetByMXID(ctx, replyToID)
if err != nil {
zerolog.Ctx(ctx).Err(err).
Stringer("reply_to_mxid", replyToID).
Msg("Failed to get reply target message from database")
} else if replyToMsg == nil {
zerolog.Ctx(ctx).Warn().
Stringer("reply_to_mxid", replyToID).
Msg("Reply target message not found")
} else {
return &signalpb.DataMessage_Quote{
Id: proto.Uint64(replyToMsg.Timestamp),
AuthorAci: proto.String(replyToMsg.Sender.String()),
Type: signalpb.DataMessage_Quote_NORMAL.Enum(),
// This is a hack to make Signal iOS and desktop render replies to file messages.
// Unfortunately it also makes Signal Desktop show a file icon on replies to text messages.
// TODO store file or text flag in database and fill this field only when replying to file messages.
Attachments: make([]*signalpb.DataMessage_Quote_QuotedAttachment, 1),
}
}
return nil
}
func (portal *Portal) handleSignalMessage(portalMessage portalSignalMessage) {
sender := portal.bridge.GetPuppetBySignalID(portalMessage.evt.Info.Sender)
if sender == nil {
portal.log.Warn().
Stringer("sender_uuid", portalMessage.evt.Info.Sender).
Msg("Couldn't get puppet for message")
return
}
switch typedEvt := portalMessage.evt.Event.(type) {
case *signalpb.DataMessage:
portal.handleSignalDataMessage(portalMessage.user, sender, typedEvt)
case *signalpb.TypingMessage:
portal.handleSignalTypingMessage(sender, typedEvt)
case *signalpb.EditMessage:
portal.handleSignalEditMessage(sender, typedEvt.GetTargetSentTimestamp(), typedEvt.GetDataMessage())
default:
portal.log.Error().
Type("data_type", typedEvt).
Msg("Invalid inner event type inside ChatEvent")
}
}
func (portal *Portal) handleSignalDataMessage(source *User, sender *Puppet, msg *signalpb.DataMessage) {
genericCtx := portal.log.With().
Str("action", "handle signal data message").
Uint64("msg_ts", msg.GetTimestamp()).
Logger().WithContext(context.TODO())
// Always update sender info when we receive a message from them, there's caching inside the function
sender.UpdateInfo(genericCtx, source)
// Handle earlier missed group changes here.
// If this message is a group change, don't handle it here, it's handled below.
if msg.GetGroupV2().GetGroupChange() == nil && portal.Revision < msg.GetGroupV2().GetRevision() {
portal.UpdateInfo(genericCtx, source, nil, msg.GetGroupV2().GetRevision())
} else if portal.IsPrivateChat() && portal.UserID() == portal.Receiver && portal.Name != NoteToSelfName {
// Slightly hacky way to make note to self names backfill
portal.UpdateDMInfo(genericCtx, false)
}
switch {
case msgconv.CanConvertSignal(msg):
portal.handleSignalNormalDataMessage(source, sender, msg)
case msg.Reaction != nil:
portal.handleSignalReaction(sender, msg.Reaction, msg.GetTimestamp())
case msg.Delete != nil:
portal.handleSignalDelete(sender, msg.Delete, msg.GetTimestamp())
case msg.GetGroupV2().GetGroupChange() != nil:
portal.handleSignalGroupChange(source, sender, msg.GroupV2, msg.GetTimestamp())
case msg.StoryContext != nil, msg.GroupCallUpdate != nil:
// ignore
default:
portal.log.Warn().
Str("action", "handle signal message").
Stringer("sender_uuid", sender.SignalID).
Uint64("msg_ts", msg.GetTimestamp()).
Msg("Unrecognized content in message")
}
}
func (portal *Portal) handleSignalGroupChange(source *User, sender *Puppet, groupMeta *signalpb.GroupContextV2, ts uint64) {
log := portal.log.With().
Str("action", "handle signal group change").
Stringer("sender_uuid", sender.SignalID).
Uint64("change_ts", ts).
Uint32("new_revision", groupMeta.GetRevision()).
Logger()
ctx := log.WithContext(context.TODO())
groupChange, err := source.Client.DecryptGroupChange(ctx, groupMeta)
if err != nil {
log.Err(err).Msg("Handling GroupChange failed")
return
}
if groupChange.Revision <= portal.Revision {
return
}
portal.Revision = groupChange.Revision
if groupChange.ModifyTitle != nil {
portal.updateName(ctx, *groupChange.ModifyTitle, sender)
}
if groupChange.ModifyDescription != nil {
portal.updateTopic(ctx, *groupChange.ModifyDescription, sender)
}
if groupChange.ModifyAvatar != nil {
portal.updateAvatarWithInfo(ctx, source, groupChange, sender)
}
if groupChange.ModifyDisappearingMessagesDuration != nil {
portal.updateExpirationTimer(ctx, *groupChange.ModifyDisappearingMessagesDuration)
}
intent := sender.IntentFor(portal)
modifyRoles := groupChange.ModifyMemberRoles
for _, deleteBannedMember := range groupChange.DeleteBannedMembers {
_, err := portal.sendMembershipForPuppetAndUser(ctx, sender, *deleteBannedMember, event.MembershipLeave, "unbanned")
if err != nil {
log.Warn().Stringer("signal_user_id", deleteBannedMember).Msg("Couldn't get puppet for unban")
}
}
for _, addMember := range groupChange.AddMembers {
modifyRoles = append(modifyRoles, &signalmeow.RoleMember{UserID: addMember.UserID, Role: addMember.Role})
var puppet *Puppet
if addMember.JoinFromInviteLink {
puppet = portal.bridge.GetPuppetBySignalID(addMember.UserID)
if puppet != nil {
if puppet.customIntent == nil {
user := portal.bridge.GetUserBySignalID(addMember.UserID)
if user != nil {
portal.MainIntent().SendCustomMembershipEvent(ctx, portal.MXID, user.MXID, event.MembershipInvite, "Joined via invite Link")
}
}
_, err = puppet.IntentFor(portal).SendCustomMembershipEvent(ctx, portal.MXID, puppet.IntentFor(portal).UserID, event.MembershipJoin, "")
if errors.Is(err, mautrix.MForbidden) {
_, err = portal.MainIntent().SendCustomMembershipEvent(ctx, portal.MXID, puppet.IntentFor(portal).UserID, event.MembershipInvite, "Joined via invite Link")
} else if err == nil {
continue
}
}
} else {
puppet, _ = portal.sendMembershipForPuppetAndUser(ctx, sender, addMember.UserID, event.MembershipInvite, "added")
}
if puppet != nil {
puppet.IntentFor(portal).SendCustomMembershipEvent(ctx, portal.MXID, puppet.IntentFor(portal).UserID, event.MembershipJoin, "")
} else {
log.Warn().Stringer("signal_user_id", addMember.UserID).Msg("Couldn't get puppet for invite")
}
}
bannedMembers := make(map[uuid.UUID]bool)
for _, addBannedMember := range groupChange.AddBannedMembers {
bannedMembers[addBannedMember.UserID] = true
_, err := portal.sendMembershipForPuppetAndUser(ctx, sender, addBannedMember.UserID, event.MembershipBan, "banned")
if err != nil {
log.Warn().Stringer("signal_user_id", addBannedMember.UserID).Msg("Couldn't get puppet for ban")
}
}
for _, deleteMember := range groupChange.DeleteMembers {
if bannedMembers[*deleteMember] {
continue
}
_, err := portal.sendMembershipForPuppetAndUser(ctx, sender, *deleteMember, event.MembershipLeave, "deleted")
if err != nil {
log.Warn().Stringer("signal_user_id", deleteMember).Msg("Couldn't get puppet for removal")
}
}
for _, deletePendingMember := range groupChange.DeletePendingMembers {
if bannedMembers[*deletePendingMember] {
continue
}
_, err := portal.sendMembershipForPuppetAndUser(ctx, sender, *deletePendingMember, event.MembershipLeave, "invite withdrawn")
if err != nil {
log.Warn().Stringer("signal_user_id", deletePendingMember).Msg("Couldn't get puppet for removal")
}
}
for _, deleteRequestingMember := range groupChange.DeleteRequestingMembers {
if bannedMembers[*deleteRequestingMember] {
continue
}
_, err := portal.sendMembershipForPuppetAndUser(ctx, sender, *deleteRequestingMember, event.MembershipLeave, "request rejected")
if err != nil {
log.Warn().Stringer("signal_user_id", deleteRequestingMember).Msg("Couldn't get puppet for removal")
}
}
for _, promotePendingMember := range groupChange.PromotePendingMembers {
puppet, err := portal.sendMembershipForPuppetAndUser(ctx, sender, promotePendingMember.UserID, event.MembershipInvite, "request accepted")
if err == nil {