forked from mautrix/signal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
portal.go
1963 lines (1777 loc) · 66 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
//
// 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"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"reflect"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog"
"go.mau.fi/util/exerrors"
"go.mau.fi/util/exfmt"
"go.mau.fi/util/ffmpeg"
"go.mau.fi/util/jsontime"
"go.mau.fi/util/variationselector"
cwebp "go.mau.fi/webp"
"golang.org/x/exp/slices"
"golang.org/x/image/webp"
"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/crypto/attachment"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-signal/database"
"go.mau.fi/mautrix-signal/msgconv/matrixfmt"
"go.mau.fi/mautrix-signal/msgconv/signalfmt"
"go.mau.fi/mautrix-signal/pkg/signalmeow"
signalpb "go.mau.fi/mautrix-signal/pkg/signalmeow/protobuf"
)
type portalSignalMessage struct {
message signalmeow.IncomingSignalMessage
user *User
sender *Puppet
sync bool
}
type portalMatrixMessage struct {
evt *event.Event
user *User
}
type Portal struct {
*database.Portal
bridge *SignalBridge
log zerolog.Logger
roomCreateLock sync.Mutex
encryptLock sync.Mutex
signalMessages chan portalSignalMessage
matrixMessages chan portalMatrixMessage
currentlyTyping []id.UserID
currentlyTypingLock sync.Mutex
latestReadTimestamp uint64 // Cache the latest read timestamp to avoid unnecessary read receipts
relayUser *User
}
const recentMessageBufferSize = 32
func init() {
event.TypeMap[event.StateBridge] = reflect.TypeOf(CustomBridgeInfoContent{})
event.TypeMap[event.StateHalfShotBridge] = reflect.TypeOf(CustomBridgeInfoContent{})
}
// ** Interfaces that Portal implements **
var _ bridge.Portal = (*Portal)(nil)
var _ bridge.ReadReceiptHandlingPortal = (*Portal)(nil)
var _ bridge.TypingPortal = (*Portal)(nil)
var _ bridge.DisappearingPortal = (*Portal)(nil)
//var _ bridge.MembershipHandlingPortal = (*Portal)(nil)
//var _ bridge.MetaHandlingPortal = (*Portal)(nil)
// ** bridge.Portal Interface **
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 isUUID(s string) bool {
if _, uuidErr := uuid.Parse(s); uuidErr == nil {
return true
}
return false
}
func (portal *Portal) IsPrivateChat() bool {
// If ChatID is a UUID, it's a private chat, otherwise it's base64 and a group chat
return isUUID(portal.ChatID)
}
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(),
},
}
var bridgeInfoStateKey string
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() {
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(portal.MXID, event.StateBridge, stateKey, content)
if err != nil {
portal.log.Warn().Msgf("Failed to update m.bridge: %v", err)
}
// TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
_, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
if err != nil {
portal.log.Warn().Msgf("Failed to update uk.half-shot.bridge: %v", err)
}
}
// ** bridge.ChildOverride methods (for SignalBridge in main.go) **
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) 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) 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
}
// ** Portal Creation and Message Handling **
func (br *SignalBridge) NewPortal(dbPortal *database.Portal) *Portal {
portal := &Portal{
Portal: dbPortal,
bridge: br,
log: br.ZLog.With().Str("chat_id", dbPortal.ChatID).Logger(),
signalMessages: make(chan portalSignalMessage, br.Config.Bridge.PortalMessageBuffer),
matrixMessages: make(chan portalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
}
go portal.messageLoop()
return portal
}
func (portal *Portal) messageLoop() {
for {
select {
case msg := <-portal.matrixMessages:
portal.handleMatrixMessages(msg)
case msg := <-portal.signalMessages:
portal.handleSignalMessages(msg)
}
}
}
func (portal *Portal) handleMatrixMessages(msg portalMatrixMessage) {
// If we have no SignalDevice, the bridge isn't logged in properly,
// so send BAD_CREDENTIALS so the user knows
if !msg.user.SignalDevice.IsDeviceLoggedIn() && !portal.HasRelaybot() {
go portal.sendMessageMetrics(msg.evt, errUserNotLoggedIn, "Ignoring", nil)
msg.user.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Message: "You have been logged out of Signal, please reconnect"})
return
}
log := portal.log.With().Str("event_id", msg.evt.ID.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.String()).Msg("Unhandled matrix message type")
}
}
func (portal *Portal) handleMatrixMessage(ctx context.Context, sender *User, evt *event.Event) {
evtTS := time.UnixMilli(evt.Timestamp)
timings := messageTimings{
initReceive: evt.Mautrix.ReceivedAt.Sub(evtTS),
decrypt: evt.Mautrix.DecryptionDuration,
totalReceive: time.Since(evtTS),
}
implicitRRStart := time.Now()
timings.implicitRR = time.Since(implicitRRStart)
start := time.Now()
messageAge := timings.totalReceive
ms := metricSender{portal: portal, timings: &timings}
portal.log.Debug().Msgf("Received message %s from %s (age: %s)", evt.ID, evt.Sender, messageAge)
errorAfter := portal.bridge.Config.Bridge.MessageHandlingTimeout.ErrorAfter
deadline := portal.bridge.Config.Bridge.MessageHandlingTimeout.Deadline
isScheduled, _ := evt.Content.Raw["com.beeper.scheduled"].(bool)
if isScheduled {
portal.log.Debug().Msgf("%s is a scheduled message, extending handling timeouts", evt.ID)
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 {
portal.log.Warn().Msgf("Message %s was delayed before reaching the bridge, only have %s (of %s timeout) until delay warning", evt.ID, remainingTime, errorAfter)
}
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()
msg, err := portal.convertMatrixMessage(ctx, sender, evt)
if err != nil || msg == nil {
if err == nil {
err = fmt.Errorf("msg is nil")
}
portal.log.Error().Msgf("Error converting message %s: %v", evt.ID, err)
go ms.sendMessageMetrics(evt, err, "Error converting", true)
return
}
timestamp := *msg.DataMessage.Timestamp
if timestamp == 0 {
timestamp = uint64(start.UnixMilli())
}
timings.convert = time.Since(start)
start = time.Now()
// If the portal has disappearing messages enabled, set the expiration time
if portal.ExpirationTime > 0 {
signalmeow.AddExpiryToDataMessage(msg, uint32(portal.ExpirationTime))
}
if !sender.IsLoggedIn() {
sender = portal.GetRelayUser()
}
err = portal.sendSignalMessage(ctx, msg, sender, evt.ID)
timings.totalSend = time.Since(start)
go ms.sendMessageMetrics(evt, err, "Error sending", true)
if err == nil {
portal.storeMessageInDB(ctx, evt.ID, sender.SignalID, timestamp, 0)
if portal.ExpirationTime > 0 {
portal.addDisappearingMessage(ctx, evt.ID, int64(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 dbMessage == nil && dbReaction == nil {
portal.sendMessageStatusCheckpointFailed(evt, errors.New("could not find original message or reaction"))
log.Warn().Msg("No target message or reaction found for redaction")
return
}
if !sender.IsLoggedIn() {
sender = portal.GetRelayUser()
}
// If this is a message redaction, send a redaction to Signal
if dbMessage != nil {
msg := signalmeow.DataMessageForDelete(dbMessage.Timestamp)
err = portal.sendSignalMessage(ctx, msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(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(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).
Str("part_event_id", otherPart.MXID.String()).
Int("part_index", otherPart.PartIndex).
Msg("Failed to redact other part of redacted message")
}
err = otherPart.Delete(ctx)
if err != nil {
log.Err(err).
Str("part_event_id", otherPart.MXID.String()).
Int("part_index", otherPart.PartIndex).
Msg("Failed to delete other part of redacted message from database")
}
}
}
}
if dbReaction != nil {
msg := signalmeow.DataMessageForReaction(dbReaction.Emoji, dbReaction.MsgAuthor, dbReaction.MsgTimestamp, true)
err = portal.sendSignalMessage(ctx, msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(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(evt)
}
func (portal *Portal) handleMatrixReaction(ctx context.Context, sender *User, evt *event.Event) {
log := zerolog.Ctx(ctx)
if !sender.IsLoggedIn() {
log.Error().Msg("Cannot relay reaction from non-logged-in user. Ignoring")
return
}
// Find the original signal message based on eventID
relatedEventID := evt.Content.AsReaction().RelatesTo.EventID
dbMessage, err := portal.bridge.DB.Message.GetByMXID(ctx, relatedEventID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(evt, err)
log.Err(err).Msg("Failed to get reaction target message")
return
} else if dbMessage == nil {
portal.sendMessageStatusCheckpointFailed(evt, errors.New("could not find original message for reaction"))
log.Warn().Msg("No target message found for reaction")
return
}
emoji := evt.Content.AsReaction().RelatesTo.Key
signalEmoji := variationselector.FullyQualify(emoji) // Signal seems to require fully qualified emojis
targetAuthorUUID := dbMessage.Sender
targetTimestamp := dbMessage.Timestamp
msg := signalmeow.DataMessageForReaction(signalEmoji, targetAuthorUUID, targetTimestamp, false)
err = portal.sendSignalMessage(context.Background(), msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(evt, err)
portal.log.Error().Msgf("Failed to send reaction %s", evt.ID)
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,
targetAuthorUUID,
targetTimestamp,
sender.SignalID,
portal.Receiver,
)
if err != nil {
log.Err(err).Msg("Failed to get existing reaction from database")
} else if dbReaction != nil {
log.Debug().Str("existing_event_id", dbReaction.MXID.String()).Msg("Redacting existing reaction after sending new one")
_, err = portal.MainIntent().RedactEvent(portal.MXID, dbReaction.MXID)
if err != nil {
log.Err(err).Msg("Failed to redact existing reaction")
}
// TODO update instead of deleting
err = dbReaction.Delete(ctx)
if err != nil {
log.Err(err).Msg("Failed to delete reaction from database")
}
}
// Store our new reaction in the database
portal.storeReactionInDB(ctx, evt.ID, sender.SignalID, targetAuthorUUID, targetTimestamp, signalEmoji)
portal.sendMessageStatusCheckpointSuccess(evt)
}
func (portal *Portal) downloadAndDecryptMatrixMedia(ctx context.Context, content *event.MessageEventContent) ([]byte, error) {
var file *event.EncryptedFileInfo
rawMXC := content.URL
if content.File != nil {
file = content.File
rawMXC = file.URL
}
mxc, err := rawMXC.Parse()
if err != nil {
return nil, err
}
data, err := portal.MainIntent().DownloadBytesContext(ctx, mxc)
if err != nil {
return nil, exerrors.NewDualError(errMediaDownloadFailed, err)
}
if file != nil {
err = file.DecryptInPlace(data)
if err != nil {
return nil, exerrors.NewDualError(errMediaDecryptFailed, err)
}
}
return data, nil
}
func convertWebPtoPNG(webpImage []byte) ([]byte, error) {
webpDecoded, err := webp.Decode(bytes.NewReader(webpImage))
if err != nil {
return nil, fmt.Errorf("failed to decode webp image: %w", err)
}
var pngBuffer bytes.Buffer
if err = png.Encode(&pngBuffer, webpDecoded); err != nil {
return nil, fmt.Errorf("failed to encode png image: %w", err)
}
return pngBuffer.Bytes(), nil
}
type PaddedImage struct {
image.Image
Size int
OffsetX int
OffsetY int
}
func (img *PaddedImage) Bounds() image.Rectangle {
return image.Rect(0, 0, img.Size, img.Size)
}
func (img *PaddedImage) At(x, y int) color.Color {
return img.Image.At(x+img.OffsetX, y+img.OffsetY)
}
func convertToWebPSticker(img []byte) ([]byte, error) {
decodedImg, _, err := image.Decode(bytes.NewReader(img))
if err != nil {
return img, fmt.Errorf("failed to decode image: %w", err)
}
bounds := decodedImg.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width != height {
paddedImg := &PaddedImage{
Image: decodedImg,
OffsetX: bounds.Min.Y,
OffsetY: bounds.Min.X,
}
if width > height {
paddedImg.Size = width
paddedImg.OffsetY -= (paddedImg.Size - height) / 2
} else {
paddedImg.Size = height
paddedImg.OffsetX -= (paddedImg.Size - width) / 2
}
decodedImg = paddedImg
}
var webpBuffer bytes.Buffer
if err = cwebp.Encode(&webpBuffer, decodedImg, nil); err != nil {
return img, fmt.Errorf("failed to encode webp image: %w", err)
}
return webpBuffer.Bytes(), nil
}
func convertImage(ctx context.Context, mimeType string, image []byte) (string, []byte, error) {
var outMimeType string
var outImage []byte
var err error
switch mimeType {
case "image/jpeg", "image/png", "image/gif":
// Allowed
outMimeType = mimeType
outImage = image
case "image/webp":
outMimeType = "image/png"
outImage, err = convertWebPtoPNG(image)
default:
return "", nil, fmt.Errorf("%w %q", errMediaUnsupportedType, mimeType)
}
if err != nil {
return "", nil, fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, outMimeType)
}
return outMimeType, outImage, nil
}
func convertSticker(ctx context.Context, mimeType string, sticker []byte, width, height int) (string, []byte, error) {
var outMimeType string = mimeType
var outSticker []byte = sticker
var err error
if mimeType != "image/webp" || width != height {
outSticker, err = convertToWebPSticker(sticker)
outMimeType = "image/webp"
}
if err != nil {
return "", nil, fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, outMimeType)
}
return outMimeType, outSticker, nil
}
func convertVideo(ctx context.Context, mimeType string, video []byte) (string, []byte, error) {
var outMimeType string
var outVideo []byte
var err error
switch mimeType {
case "video/mp4", "video/3gpp":
// Allowed
outMimeType = mimeType
outVideo = video
case "video/webm":
outMimeType = "video/mp4"
outVideo, err = ffmpeg.ConvertBytes(ctx, video, ".mp4", []string{"-f", "webm"}, []string{
"-pix_fmt", "yuv420p", "-c:v", "libx264",
}, mimeType)
default:
return "", nil, fmt.Errorf("%w %q in video message", errMediaUnsupportedType, mimeType)
}
if err != nil {
return "", nil, fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, outMimeType)
}
return outMimeType, outVideo, nil
}
func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, evt *event.Event) (*signalmeow.SignalContent, error) {
content, ok := evt.Content.Parsed.(*event.MessageEventContent)
if !ok {
return nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
}
if evt.Type == event.EventSticker {
content.MsgType = event.MessageType(event.EventSticker.Type)
}
realSenderMXID := sender.MXID
isRelay := false
if !sender.IsLoggedIn() {
if !portal.HasRelaybot() {
return nil, errUserNotLoggedIn
}
sender = portal.GetRelayUser()
if !sender.IsLoggedIn() {
return nil, errRelaybotNotLoggedIn
}
isRelay = true
}
var outgoingMessage *signalmeow.SignalContent
relaybotFormatted := isRelay && portal.addRelaybotFormat(realSenderMXID, content)
if relaybotFormatted && content.FileName == "" {
content.FileName = content.Body
}
if evt.Type == event.EventSticker {
if relaybotFormatted {
// Stickers can't have captions, so force relaybot stickers to be images
content.MsgType = event.MsgImage
} else {
content.MsgType = event.MessageType(event.EventSticker.Type)
}
}
switch content.MsgType {
case event.MsgText, event.MsgEmote, event.MsgNotice:
if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
return nil, errMNoticeDisabled
}
if content.MsgType == event.MsgEmote && !relaybotFormatted {
content.Body = "/me " + content.Body
if content.FormattedBody != "" {
content.FormattedBody = "/me " + content.FormattedBody
}
}
outgoingMessage = signalmeow.DataMessageForText(matrixfmt.Parse(matrixFormatParams, content))
if ctx.Err() != nil {
return nil, ctx.Err()
}
case event.MsgImage:
fileName := content.Body
var caption string
var ranges []*signalpb.BodyRange
if content.FileName != "" && (content.Body != content.FileName || content.Format == event.FormatHTML) {
fileName = content.FileName
caption, ranges = matrixfmt.Parse(matrixFormatParams, content)
}
image, err := portal.downloadAndDecryptMatrixMedia(ctx, content)
if err != nil {
return nil, err
}
newMimeType, convertedImage, err := convertImage(ctx, content.GetInfo().MimeType, image)
if err != nil {
return nil, err
}
attachmentPointer, err := signalmeow.UploadAttachment(sender.SignalDevice, convertedImage, newMimeType, fileName)
if err != nil {
return nil, err
}
attachmentPointer.Height = proto.Uint32(uint32(content.GetInfo().Height))
attachmentPointer.Width = proto.Uint32(uint32(content.GetInfo().Width))
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption, ranges)
case event.MessageType(event.EventSticker.Type):
var emoji *string
// TODO check for single grapheme cluster?
if len([]rune(content.Body)) == 1 {
emoji = proto.String(variationselector.Remove(content.Body))
}
image, err := portal.downloadAndDecryptMatrixMedia(ctx, content)
if err != nil {
return nil, err
}
newMimeType, convertedSticker, err := convertSticker(ctx, content.GetInfo().MimeType, image, content.GetInfo().Width, content.GetInfo().Height)
if err != nil {
return nil, err
}
attachmentPointer, err := signalmeow.UploadAttachment(sender.SignalDevice, convertedSticker, newMimeType, content.FileName)
if err != nil {
return nil, err
}
attachmentPointer.Height = proto.Uint32(uint32(content.GetInfo().Height))
attachmentPointer.Width = proto.Uint32(uint32(content.GetInfo().Width))
attachmentPointer.Flags = proto.Uint32(uint32(signalpb.AttachmentPointer_BORDERLESS))
outgoingMessage = &signalmeow.SignalContent{
DataMessage: &signalpb.DataMessage{
Timestamp: proto.Uint64(uint64(time.Now().UnixMilli())),
Sticker: &signalpb.DataMessage_Sticker{
// Signal iOS validates that pack id/key are of the correct length.
// Android is fine with any non-nil values (like a zero-length byte string).
PackId: make([]byte, 16),
PackKey: make([]byte, 32),
StickerId: proto.Uint32(0),
Data: (*signalpb.AttachmentPointer)(attachmentPointer),
Emoji: emoji,
},
},
}
case event.MsgVideo:
fileName := content.Body
var caption string
var ranges []*signalpb.BodyRange
if content.FileName != "" && (content.Body != content.FileName || content.Format == event.FormatHTML) {
fileName = content.FileName
caption, ranges = matrixfmt.Parse(matrixFormatParams, content)
}
image, err := portal.downloadAndDecryptMatrixMedia(ctx, content)
if err != nil {
return nil, err
}
newMimeType, convertedVideo, err := convertVideo(ctx, content.GetInfo().MimeType, image)
if err != nil {
return nil, err
}
attachmentPointer, err := signalmeow.UploadAttachment(sender.SignalDevice, convertedVideo, newMimeType, fileName)
if err != nil {
return nil, err
}
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption, ranges)
case event.MsgAudio:
fileName := content.Body
var caption string
var ranges []*signalpb.BodyRange
if content.FileName != "" && (content.Body != content.FileName || content.Format == event.FormatHTML) {
fileName = content.FileName
caption, ranges = matrixfmt.Parse(matrixFormatParams, content)
}
data, err := portal.downloadAndDecryptMatrixMedia(ctx, content)
if err != nil {
return nil, err
}
_, isVoice := evt.Content.Raw["org.matrix.msc3245.voice"]
mime := content.GetInfo().MimeType
if isVoice {
data, err = ffmpeg.ConvertBytes(ctx, data, ".m4a", []string{}, []string{"-c:a", "aac"}, mime)
if err != nil {
return nil, err
}
mime = "audio/aac"
fileName += ".m4a"
}
attachmentPointer, err := signalmeow.UploadAttachment(sender.SignalDevice, data, mime, fileName)
if err != nil {
return nil, err
}
if isVoice {
attachmentPointer.Flags = proto.Uint32(uint32(signalpb.AttachmentPointer_VOICE_MESSAGE))
}
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption, ranges)
case event.MsgFile:
fileName := content.Body
var caption string
var ranges []*signalpb.BodyRange
if content.FileName != "" && (content.Body != content.FileName || content.Format == event.FormatHTML) {
fileName = content.FileName
caption, ranges = matrixfmt.Parse(matrixFormatParams, content)
}
file, err := portal.downloadAndDecryptMatrixMedia(ctx, content)
if err != nil {
return nil, err
}
attachmentPointer, err := signalmeow.UploadAttachment(sender.SignalDevice, file, content.GetInfo().MimeType, fileName)
if err != nil {
return nil, err
}
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption, ranges)
case event.MsgLocation:
fallthrough
default:
return nil, fmt.Errorf("%w %q", errUnknownMsgType, content.MsgType)
}
// Include a quote if this is a reply
replyID := content.RelatesTo.GetReplyTo()
if replyID != "" {
originalMessage, err := portal.bridge.DB.Message.GetByMXID(ctx, replyID)
if err != nil {
return nil, fmt.Errorf("failed to get reply target: %w", err)
} else if originalMessage != nil {
signalmeow.AddQuoteToDataMessage(
outgoingMessage,
originalMessage.Sender,
originalMessage.Timestamp,
)
} else {
zerolog.Ctx(ctx).Warn().Str("reply_event_id", replyID.String()).Msg("Reply target not found")
}
}
return outgoingMessage, nil
}
func (portal *Portal) sendSignalMessage(ctx context.Context, msg *signalmeow.SignalContent, sender *User, evtID id.EventID) error {
recipientSignalID := portal.ChatID
portal.log.Debug().Msgf("Sending event %s to Signal %s", evtID, recipientSignalID)
// Check to see if recipientSignalID is a standard UUID (with dashes)
var err error
if _, uuidErr := uuid.Parse(recipientSignalID); uuidErr == nil {
// this is a 1:1 chat
result := signalmeow.SendMessage(ctx, sender.SignalDevice, recipientSignalID, msg)
if !result.WasSuccessful {
err = result.FailedSendResult.Error
portal.log.Error().Msgf("Error sending event %s to Signal %s: %s", evtID, recipientSignalID, err)
}
} else {
// this is a group chat
groupID := signalmeow.GroupIdentifier(recipientSignalID)
result, err := signalmeow.SendGroupMessage(ctx, sender.SignalDevice, 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(portal.MXID, "Missing group encryption key. Please ask a group member to send a message in this chat, then retry sending.")
}
portal.log.Error().Msgf("Error sending event %s to Signal group %s: %s", evtID, recipientSignalID, err)
return err
}
totalRecipients := len(result.FailedToSendTo) + len(result.SuccessfullySentTo)
if len(result.FailedToSendTo) > 0 {
portal.log.Error().Msgf("Failed to send event %s to %d of %d members of Signal group %s", evtID, len(result.FailedToSendTo), totalRecipients, recipientSignalID)
}
if len(result.SuccessfullySentTo) == 0 && len(result.FailedToSendTo) == 0 {
portal.log.Debug().Msgf("No successes or failures - Probably sent to myself")
} else if len(result.SuccessfullySentTo) == 0 {
portal.log.Error().Msgf("Failed to send event %s to all %d members of Signal group %s", evtID, totalRecipients, recipientSignalID)
err = errors.New("failed to send to any members of Signal group")
} else if len(result.SuccessfullySentTo) < totalRecipients {
portal.log.Warn().Msgf("Only sent event %s to %d of %d members of Signal group %s", evtID, len(result.SuccessfullySentTo), totalRecipients, recipientSignalID)
} else {
portal.log.Debug().Msgf("Sent event %s to all %d members of Signal group %s", evtID, totalRecipients, recipientSignalID)
}
}
return err
}
func (portal *Portal) sendMessageStatusCheckpointSuccess(evt *event.Event) {
portal.sendDeliveryReceipt(evt.ID)
portal.bridge.SendMessageSuccessCheckpoint(evt, status.MsgStepRemote, 0)
var deliveredTo *[]id.UserID
if portal.IsPrivateChat() {
deliveredTo = &[]id.UserID{}
}
portal.sendStatusEvent(evt.ID, "", nil, deliveredTo)
}
func (portal *Portal) sendMessageStatusCheckpointFailed(evt *event.Event, err error) {
portal.sendDeliveryReceipt(evt.ID)
portal.bridge.SendMessageErrorCheckpoint(evt, status.MsgStepRemote, err, true, 0)
portal.sendStatusEvent(evt.ID, "", err, nil)
}
func (portal *Portal) handleSignalMessages(portalMessage portalSignalMessage) {
log := portal.log.With().
Str("action", "handle signal message").
Str("sender", portalMessage.sender.SignalID.String()).
Uint64("timestamp", portalMessage.message.Base().Timestamp).
Int("part_index", portalMessage.message.Base().PartIndex).
Logger()
ctx := log.WithContext(context.TODO())
if existingMessage, err := portal.bridge.DB.Message.GetBySignalID(
ctx,
portalMessage.sender.SignalID,
portalMessage.message.Base().Timestamp,
portalMessage.message.Base().PartIndex,
portal.Receiver,
); err != nil {
log.Err(err).Msg("Failed to check if message was already handled")
return
} else if existingMessage != nil {
log.Debug().Msg("Ignoring duplicate message")
return
}
if portal.MXID == "" {
log.Debug().Msg("Creating Matrix room from incoming message")
if err := portal.CreateMatrixRoom(portalMessage.user, nil); err != nil {
log.Error().Err(err).Msg("Failed to create portal room")
return
}
ensureGroupPuppetsAreJoinedToPortal(context.Background(), portalMessage.user, portal)
signalmeow.SendContactSyncRequest(context.TODO(), portalMessage.user.SignalDevice)
}
intent := portalMessage.sender.IntentFor(portal)
if intent == nil {
portal.log.Error().Msg("Failed to get message intent")
return
}
var err error
if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeText {
err = portal.handleSignalTextMessage(ctx, portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle text message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeAttachment {
err = portal.handleSignalAttachmentMessage(ctx, portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle attachment message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeReaction {
portal.handleSignalReactionMessage(ctx, portalMessage, intent)
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeDelete {
portal.handleSignalDeleteMessage(ctx, portalMessage, intent)
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeSticker {
err := portal.handleSignalStickerMessage(ctx, portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle sticker message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeTyping {
err := portal.handleSignalTypingMessage(portalMessage, intent)
if err != nil {