This repository has been archived by the owner on Dec 18, 2023. It is now read-only.
forked from mautrix/signal
-
Notifications
You must be signed in to change notification settings - Fork 4
/
portal.go
1901 lines (1702 loc) · 65.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
//
// 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"
"github.com/samber/lo"
"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"
"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/format"
"maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-signal/database"
"go.mau.fi/mautrix-signal/msgconv/signalfmt"
"go.mau.fi/mautrix-signal/pkg/signalmeow"
)
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
}
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
portal.Update()
}
func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser {
portal.matrixMessages <- portalMatrixMessage{user: user.(*User), evt: evt}
}
}
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.ChatID).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.Key().ChatID,
DisplayName: portal.Name,
AvatarURL: portal.AvatarURL.CUString(),
},
}
var bridgeInfoStateKey string
bridgeInfoStateKey = fmt.Sprintf("fi.mau.signal://signal/%s", portal.Key().ChatID)
bridgeInfo.Channel.ExternalURL = fmt.Sprintf("https://signal.me/#p/%s", portal.Key().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) 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 *SignalBridge) getAllPortals() []*Portal {
return br.dbPortalsToPortals(br.DB.Portal.GetAll())
}
func (br *SignalBridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
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.Key()]
if !ok {
portal = br.loadPortal(dbPortal, nil)
}
output[index] = portal
}
return output
}
// ** 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.Key().ChatID).Logger(),
signalMessages: make(chan portalSignalMessage, br.Config.Bridge.PortalMessageBuffer),
matrixMessages: make(chan portalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
//commands: make(map[string]*discordgo.ApplicationCommand),
}
go portal.messageLoop()
return portal
}
func (portal *Portal) messageLoop() {
for {
portal.log.Debug().Msg("Waiting for message")
select {
case msg := <-portal.matrixMessages:
portal.log.Debug().Msg("Got message from matrix")
portal.handleMatrixMessages(msg)
case msg := <-portal.signalMessages:
portal.log.Debug().Msg("Got message from signal")
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.sendMessageStatusCheckpointFailed(msg.evt, errUserNotLoggedIn)
msg.user.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Message: "You have been logged out of Signal, please reconnect"})
return
}
switch msg.evt.Type {
case event.EventMessage, event.EventSticker:
portal.handleMatrixMessage(msg.user, msg.evt)
case event.EventRedaction:
portal.handleMatrixRedaction(msg.user, msg.evt)
case event.EventReaction:
portal.handleMatrixReaction(msg.user, msg.evt)
default:
portal.log.Warn().Str("type", msg.evt.Type.String()).Msg("Unhandled matrix message type")
}
}
func (portal *Portal) handleMatrixMessage(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
origEvtID := evt.ID
ms := metricSender{portal: portal, timings: &timings}
var dbMsg *database.Message
if retryMeta := evt.Content.AsMessage().MessageSendRetry; retryMeta != nil {
origEvtID = retryMeta.OriginalEventID
dbMsg = portal.bridge.DB.Message.GetByMXID(origEvtID)
if dbMsg != nil {
//portal.log.Debugfln("Ignoring retry request %s (#%d, age: %s) for %s/%s from %s as message was already sent", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
go ms.sendMessageMetrics(evt, nil, "", true)
return
} else if dbMsg != nil {
//portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s/%s from %s", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
} else {
//portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s from %s (original message not known)", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, evt.Sender)
}
} else {
//portal.log.Debugfln("Received message %s from %s (age: %s)", evt.ID, evt.Sender, messageAge)
}
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)
}()
}
ctx := context.Background()
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))
}
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(evt.ID, sender.SignalID, timestamp)
if portal.ExpirationTime > 0 {
portal.addDisappearingMessage(evt.ID, int64(portal.ExpirationTime), true)
}
}
}
func (portal *Portal) handleMatrixRedaction(sender *User, evt *event.Event) {
// Find the original signal message based on eventID
dbMessage := portal.bridge.DB.Message.GetByMXID(evt.Redacts)
if dbMessage == nil {
portal.log.Info().Msgf("Could not find original message for redaction %s", evt.ID)
}
// Might be a reaction redaction, find the original message for the reaction
dbReaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts, evt.RoomID)
if dbReaction == nil {
portal.log.Info().Msgf("Could not find original reaction for redaction %s", evt.ID)
}
if dbMessage == nil && dbReaction == nil {
portal.sendMessageStatusCheckpointFailed(evt, errors.New("could not find original message or reaction"))
portal.log.Error().Msgf("Could not find original message or reaction for redaction %s", evt.ID)
return
}
// If this is a message redaction, send a redaction to Signal
if dbMessage != nil {
msg := signalmeow.DataMessageForDelete(dedupedTimestamp(dbMessage))
err := portal.sendSignalMessage(context.Background(), msg, sender, evt.ID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(evt, err)
portal.log.Error().Msgf("Failed to send redaction %s", evt.ID)
return
}
dbMessage.Delete(nil)
}
// If this is a reaction redaction, send a reaction to Signal with remove == true
if dbReaction != nil {
msg := signalmeow.DataMessageForReaction(dbReaction.Emoji, dbReaction.MsgAuthor, dbReaction.MsgTimestamp, true)
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
}
dbReaction.Delete(nil)
}
portal.sendMessageStatusCheckpointSuccess(evt)
}
func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) {
// Find the original signal message based on eventID
relatedEventID := evt.Content.AsReaction().RelatesTo.EventID
dbMessage := portal.bridge.DB.Message.GetByMXID(relatedEventID)
if dbMessage == nil {
portal.sendMessageStatusCheckpointFailed(evt, errors.New("could not find original message for reaction"))
portal.log.Error().Msgf("Could not find original message for reaction %s", evt.ID)
return
}
emoji := evt.Content.AsReaction().RelatesTo.Key
signalEmoji := variationselector.FullyQualify(emoji) // Signal seems to require fully qualified emojis
targetAuthorUUID := dbMessage.Sender
targetTimestamp := dedupedTimestamp(dbMessage)
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 := portal.bridge.DB.Reaction.GetBySignalID(
portal.ChatID,
portal.Receiver,
sender.SignalID,
targetAuthorUUID,
targetTimestamp,
)
if dbReaction != nil {
portal.log.Debug().Msgf("Deleting existing reaction with author %s, target %s, targettime: %d", sender.SignalID, targetAuthorUUID, targetTimestamp)
// Send a redaction to redact the existing reaction
intent := portal.MainIntent()
_, err := intent.RedactEvent(portal.MXID, dbReaction.MXID)
if err != nil {
portal.sendMessageStatusCheckpointFailed(evt, err)
portal.log.Warn().Msgf("Failed to redact existing reaction: %v", err)
}
dbReaction.Delete(nil)
}
// Store our new reaction in the database
portal.storeReactionInDB(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 convertAudio(ctx context.Context, mimeType string, audio []byte) (string, []byte, error) {
var outMimeType string
var outAudio []byte
var err error
switch mimeType {
case "audio/aac", "audio/mp4", "audio/amr", "audio/mpeg", "audio/ogg; codecs=opus":
// Allowed
outMimeType = mimeType
outAudio = audio
case "audio/ogg":
// Hopefully it's opus already
outMimeType = "audio/ogg; codecs=opus"
outAudio = audio
default:
return "", nil, fmt.Errorf("%w %q in audio message", errMediaUnsupportedType, mimeType)
}
if err != nil {
return "", nil, fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, "video/mp4")
}
return outMimeType, outAudio, 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)
}
var outgoingMessage *signalmeow.SignalContent
switch content.MsgType {
case event.MsgText, event.MsgEmote, event.MsgNotice:
var text string
var mentions []string
if content.Format == event.FormatHTML {
text, mentions = portal.parseMentionsFromMatrixBody(content)
} else {
text = content.Body
mentions = nil
}
if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
return nil, errMNoticeDisabled
}
if content.MsgType == event.MsgEmote {
text = "/me " + text
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
outgoingMessage = signalmeow.DataMessageForText(text)
if mentions != nil && len(mentions) > 0 {
signalmeow.AddMentionsToDataMessage(outgoingMessage, mentions)
}
case event.MsgImage:
fileName := content.Body
var caption string
if content.FileName != "" && content.Body != content.FileName {
fileName = content.FileName
caption = content.Body
}
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
}
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption)
case event.MessageType(event.EventSticker.Type):
fileName := content.Body
var caption string
if content.FileName != "" && content.Body != content.FileName {
fileName = content.FileName
caption = 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, fileName)
if err != nil {
return nil, err
}
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption)
case event.MsgVideo:
fileName := content.Body
var caption string
if content.FileName != "" && content.Body != content.FileName {
fileName = content.FileName
caption = content.Body
}
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)
case event.MsgAudio:
fileName := content.Body
var caption string
if content.FileName != "" && content.Body != content.FileName {
fileName = content.FileName
caption = content.Body
}
image, err := portal.downloadAndDecryptMatrixMedia(ctx, content)
if err != nil {
return nil, err
}
newMimeType, convertedAudio, err := convertAudio(ctx, content.GetInfo().MimeType, image)
if err != nil {
return nil, err
}
attachmentPointer, err := signalmeow.UploadAttachment(sender.SignalDevice, convertedAudio, newMimeType, fileName)
if err != nil {
return nil, err
}
outgoingMessage = signalmeow.DataMessageForAttachment(attachmentPointer, caption)
case event.MsgFile:
fileName := content.Body
var caption string
if content.FileName != "" && content.Body != content.FileName {
fileName = content.FileName
caption = content.Body
}
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)
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 := portal.bridge.DB.Message.GetByMXID(replyID)
if originalMessage == nil {
return nil, fmt.Errorf("%v %s", "Reply not found", replyID)
}
signalmeow.AddQuoteToDataMessage(
outgoingMessage,
originalMessage.Sender,
dedupedTimestamp(originalMessage),
)
}
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) {
if old_message := portal.bridge.DB.Message.GetBySignalID(
portalMessage.sender.SignalID,
portalMessage.message.Base().Timestamp,
portal.ChatID,
portal.Receiver,
); old_message != nil {
portal.log.Info().Msgf("Ignoring message %d by %s as it was already handled", old_message.Timestamp, old_message.Sender)
return
}
if portal.MXID == "" {
portal.log.Debug().Msg("Creating Matrix room from incoming message")
if err := portal.CreateMatrixRoom(portalMessage.user, nil); err != nil {
portal.log.Error().Err(err).Msg("Failed to create portal room")
return
}
portal.log.Info().Msgf("Created matrix room: %s", portal.MXID)
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(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(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle attachment message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeReaction {
err := portal.handleSignalReactionMessage(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle reaction message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeDelete {
err := portal.handleSignalDeleteMessage(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle redaction message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeSticker {
err := portal.handleSignalStickerMessage(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 {
portal.log.Error().Err(err).Msg("Failed to handle typing message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeReceipt {
portal.log.Debug().Msg("Received receipt message")
err := portal.handleSignalReceiptMessage(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle receipt message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeCall {
err := portal.handleSignalCallMessage(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle call message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeContactCard {
err := portal.handleSignalContactCardMessage(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle contact card message")
return
}
} else if portalMessage.message.MessageType() == signalmeow.IncomingSignalMessageTypeUnhandled {
err := portal.handleSignalUnhandledMessage(portalMessage, intent)
if err != nil {
portal.log.Error().Err(err).Msg("Failed to handle unhandled message")
return
}
} else {
portal.log.Warn().Msgf("Unknown message type: %v", portalMessage.message.MessageType())
return
}
}
func (portal *Portal) storeMessageInDB(eventID id.EventID, senderSignalID string, timestamp uint64) {
dbMessage := portal.bridge.DB.Message.New()
dbMessage.MXID = eventID
dbMessage.MXRoom = portal.MXID
dbMessage.Sender = senderSignalID
dbMessage.Timestamp = timestamp
dbMessage.SignalChatID = portal.ChatID
dbMessage.SignalReceiver = portal.Receiver
dbMessage.Insert(nil)
}
func (portal *Portal) storeReactionInDB(
eventID id.EventID,
senderSignalID string,
msgAuthor string,
msgTimestamp uint64,
emoji string,
) {
dbReaction := portal.bridge.DB.Reaction.New()
dbReaction.MXID = eventID
dbReaction.MXRoom = portal.MXID
dbReaction.SignalChatID = portal.ChatID
dbReaction.SignalReceiver = portal.Receiver
dbReaction.Author = senderSignalID
dbReaction.MsgAuthor = msgAuthor
dbReaction.MsgTimestamp = msgTimestamp
dbReaction.Emoji = emoji
dbReaction.Insert(nil)
}
func (portal *Portal) addSignalQuote(content *event.MessageEventContent, quote *signalmeow.IncomingSignalMessageQuoteData) {
if quote != nil {
originalMessage := portal.bridge.DB.Message.GetBySignalID(
quote.QuotedSender, quote.QuotedTimestamp, portal.ChatID, portal.Receiver,
)
if originalMessage == nil {
portal.log.Warn().Msgf("Couldn't find message with Signal ID %s/%d", quote.QuotedSender, quote.QuotedTimestamp)
return
}
eventID := originalMessage.MXID
if eventID != "" {
content.RelatesTo = &event.RelatesTo{
InReplyTo: &event.InReplyTo{
EventID: eventID,
},
}
mentionMXID := portal.bridge.FormatPuppetMXID(originalMessage.Sender)
user := portal.bridge.GetUserBySignalID(originalMessage.Sender)
if user != nil {
mentionMXID = user.MXID