forked from mautrix/whatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
portal.go
5521 lines (5173 loc) · 188 KB
/
portal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2024 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
_ "image/gif"
"image/jpeg"
"image/png"
"io"
"maps"
"math"
"mime"
"net/http"
"reflect"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/rs/zerolog"
"github.com/tidwall/gjson"
cwebp "go.mau.fi/webp"
"go.mau.fi/whatsmeow"
waProto "go.mau.fi/whatsmeow/binary/proto"
"go.mau.fi/whatsmeow/proto/waMmsRetry"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
"golang.org/x/exp/slices"
"golang.org/x/image/draw"
"golang.org/x/image/webp"
"google.golang.org/protobuf/proto"
"go.mau.fi/util/exerrors"
"go.mau.fi/util/exmime"
"go.mau.fi/util/exzerolog"
"go.mau.fi/util/ffmpeg"
"go.mau.fi/util/jsontime"
"go.mau.fi/util/random"
"go.mau.fi/util/variationselector"
"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"
"maunium.net/go/mautrix-whatsapp/database"
)
const StatusBroadcastTopic = "WhatsApp status updates from your contacts"
const StatusBroadcastName = "WhatsApp Status Broadcast"
const BroadcastTopic = "WhatsApp broadcast list"
const UnnamedBroadcastName = "Unnamed broadcast list"
const PrivateChatTopic = "WhatsApp private chat"
var ErrStatusBroadcastDisabled = errors.New("status bridging is disabled")
func (br *WABridge) GetPortalByMXID(mxid id.RoomID) *Portal {
ctx := context.TODO()
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
portal, ok := br.portalsByMXID[mxid]
if !ok {
dbPortal, err := br.DB.Portal.GetByMXID(ctx, mxid)
if err != nil {
br.ZLog.Err(err).Stringer("mxid", mxid).Msg("Failed to get portal by MXID")
return nil
}
return br.loadDBPortal(ctx, dbPortal, nil)
}
return portal
}
func (br *WABridge) GetIPortal(mxid id.RoomID) bridge.Portal {
p := br.GetPortalByMXID(mxid)
if p == nil {
return nil
}
return p
}
func (portal *Portal) IsEncrypted() bool {
return portal.Encrypted
}
func (portal *Portal) MarkEncrypted() {
portal.Encrypted = true
err := portal.Update(context.TODO())
if err != nil {
portal.zlog.Err(err).Msg("Failed to mark portal as encrypted")
}
}
func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser || portal.HasRelaybot() {
portal.events <- &PortalEvent{
MatrixMessage: &PortalMatrixMessage{
user: user.(*User),
evt: evt,
receivedAt: time.Now(),
},
}
}
}
func (br *WABridge) GetPortalByJID(key database.PortalKey) *Portal {
ctx := context.TODO()
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
portal, ok := br.portalsByJID[key]
if !ok {
dbPortal, err := br.DB.Portal.GetByJID(ctx, key)
if err != nil {
br.ZLog.Err(err).Str("key", key.String()).Msg("Failed to get portal by JID")
return nil
}
return br.loadDBPortal(ctx, dbPortal, &key)
}
return portal
}
func (br *WABridge) GetExistingPortalByJID(key database.PortalKey) *Portal {
ctx := context.TODO()
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
portal, ok := br.portalsByJID[key]
if !ok {
dbPortal, err := br.DB.Portal.GetByJID(ctx, key)
if err != nil {
br.ZLog.Err(err).Str("key", key.String()).Msg("Failed to get portal by JID")
return nil
}
return br.loadDBPortal(ctx, dbPortal, nil)
}
return portal
}
func (br *WABridge) GetAllPortals() []*Portal {
return br.dbPortalsToPortals(br.DB.Portal.GetAll(context.TODO()))
}
func (br *WABridge) 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 *WABridge) GetAllPortalsByJID(jid types.JID) []*Portal {
return br.dbPortalsToPortals(br.DB.Portal.GetAllByJID(context.TODO(), jid))
}
func (br *WABridge) GetAllByParentGroup(jid types.JID) []*Portal {
return br.dbPortalsToPortals(br.DB.Portal.GetAllByParentGroup(context.TODO(), jid))
}
func (br *WABridge) dbPortalsToPortals(dbPortals []*database.Portal, err error) []*Portal {
if err != nil {
br.ZLog.Err(err).Msg("Failed to get portals")
return nil
}
br.portalsLock.Lock()
defer br.portalsLock.Unlock()
output := make([]*Portal, len(dbPortals))
for index, dbPortal := range dbPortals {
if dbPortal == nil {
continue
}
portal, ok := br.portalsByJID[dbPortal.Key]
if !ok {
portal = br.loadDBPortal(context.TODO(), dbPortal, nil)
}
output[index] = portal
}
return output
}
func (br *WABridge) loadDBPortal(ctx context.Context, dbPortal *database.Portal, key *database.PortalKey) *Portal {
if dbPortal == nil {
if key == nil {
return nil
}
dbPortal = br.DB.Portal.New()
dbPortal.Key = *key
err := dbPortal.Insert(ctx)
if err != nil {
br.ZLog.Err(err).Str("key", key.String()).Msg("Failed to insert new portal")
return nil
}
}
portal := br.NewPortal(dbPortal)
br.portalsByJID[portal.Key] = portal
if len(portal.MXID) > 0 {
br.portalsByMXID[portal.MXID] = portal
}
return portal
}
func (portal *Portal) GetUsers() []*User {
// TODO what's this for?
return nil
}
func (br *WABridge) NewManualPortal(key database.PortalKey) *Portal {
dbPortal := br.DB.Portal.New()
dbPortal.Key = key
return br.NewPortal(dbPortal)
}
func (br *WABridge) NewPortal(dbPortal *database.Portal) *Portal {
portal := &Portal{
Portal: dbPortal,
bridge: br,
events: make(chan *PortalEvent, br.Config.Bridge.PortalMessageBuffer),
mediaErrorCache: make(map[types.MessageID]*FailedMediaMeta),
}
portal.updateLogger()
go portal.handleMessageLoop()
return portal
}
func (portal *Portal) updateLogger() {
logWith := portal.bridge.ZLog.With().Stringer("portal_key", portal.Key)
if portal.MXID != "" {
logWith = logWith.Stringer("room_id", portal.MXID)
}
portal.zlog = logWith.Logger()
}
const recentlyHandledLength = 100
type fakeMessage struct {
Sender types.JID
Text string
ID string
Time time.Time
Important bool
}
type PortalEvent struct {
Message *PortalMessage
MatrixMessage *PortalMatrixMessage
}
type PortalMessage struct {
evt *events.Message
undecryptable *events.UndecryptableMessage
receipt *events.Receipt
fake *fakeMessage
source *User
}
type PortalMatrixMessage struct {
evt *event.Event
user *User
receivedAt time.Time
}
type recentlyHandledWrapper struct {
id types.MessageID
err database.MessageErrorType
}
type Portal struct {
*database.Portal
bridge *WABridge
zlog zerolog.Logger
roomCreateLock sync.Mutex
encryptLock sync.Mutex
backfillLock sync.Mutex
avatarLock sync.Mutex
latestEventBackfillLock sync.Mutex
parentGroupUpdateLock sync.Mutex
recentlyHandled [recentlyHandledLength]recentlyHandledWrapper
recentlyHandledLock sync.Mutex
recentlyHandledIndex uint8
currentlyTyping []id.UserID
currentlyTypingLock sync.Mutex
events chan *PortalEvent
mediaErrorCache map[types.MessageID]*FailedMediaMeta
galleryCache []*event.MessageEventContent
galleryCacheRootEvent id.EventID
galleryCacheStart time.Time
galleryCacheReplyTo *ReplyInfo
galleryCacheSender types.JID
currentlySleepingToDelete sync.Map
relayUser *User
parentPortal *Portal
}
const GalleryMaxTime = 10 * time.Minute
func (portal *Portal) stopGallery() {
if portal.galleryCache != nil {
portal.galleryCache = nil
portal.galleryCacheSender = types.EmptyJID
portal.galleryCacheReplyTo = nil
portal.galleryCacheStart = time.Time{}
portal.galleryCacheRootEvent = ""
}
}
func (portal *Portal) startGallery(evt *events.Message, msg *ConvertedMessage) {
portal.galleryCache = []*event.MessageEventContent{msg.Content}
portal.galleryCacheSender = evt.Info.Sender.ToNonAD()
portal.galleryCacheReplyTo = msg.ReplyTo
portal.galleryCacheStart = time.Now()
}
func (portal *Portal) extendGallery(msg *ConvertedMessage) int {
portal.galleryCache = append(portal.galleryCache, msg.Content)
msg.Content = &event.MessageEventContent{
MsgType: event.MsgBeeperGallery,
Body: "Sent a gallery",
BeeperGalleryImages: portal.galleryCache,
}
msg.Content.SetEdit(portal.galleryCacheRootEvent)
// Don't set the gallery images in the edit fallback
msg.Content.BeeperGalleryImages = nil
return len(portal.galleryCache) - 1
}
var (
_ bridge.Portal = (*Portal)(nil)
_ bridge.ReadReceiptHandlingPortal = (*Portal)(nil)
_ bridge.MembershipHandlingPortal = (*Portal)(nil)
_ bridge.MetaHandlingPortal = (*Portal)(nil)
_ bridge.TypingPortal = (*Portal)(nil)
)
func (portal *Portal) handleWhatsAppMessageLoopItem(msg *PortalMessage) {
log := portal.zlog.With().
Str("action", "handle whatsapp event").
Stringer("source_user_jid", msg.source.JID).
Stringer("source_user_mxid", msg.source.MXID).
Logger()
ctx := log.WithContext(context.TODO())
if len(portal.MXID) == 0 {
if msg.fake == nil && msg.undecryptable == nil && (msg.evt == nil || !containsSupportedMessage(msg.evt.Message)) {
log.Debug().Msg("Not creating portal room for incoming message: message is not a chat message")
return
}
log.Debug().Msg("Creating Matrix room from incoming message")
err := portal.CreateMatrixRoom(ctx, msg.source, nil, nil, false, true)
if err != nil {
log.Err(err).Msg("Failed to create portal room")
return
}
}
portal.latestEventBackfillLock.Lock()
defer portal.latestEventBackfillLock.Unlock()
switch {
case msg.evt != nil:
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.
Str("message_id", msg.evt.Info.ID).
Stringer("message_sender", msg.evt.Info.Sender)
})
portal.handleMessage(ctx, msg.source, msg.evt, false)
case msg.receipt != nil:
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("receipt_type", msg.receipt.Type.GoString())
})
portal.handleReceipt(ctx, msg.receipt, msg.source)
case msg.undecryptable != nil:
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.
Str("message_id", msg.undecryptable.Info.ID).
Stringer("message_sender", msg.undecryptable.Info.Sender).
Bool("undecryptable", true)
})
portal.stopGallery()
portal.handleUndecryptableMessage(ctx, msg.source, msg.undecryptable)
case msg.fake != nil:
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.
Str("fake_message_id", msg.fake.ID).
Stringer("message_sender", msg.fake.Sender)
})
portal.stopGallery()
msg.fake.ID = "FAKE::" + msg.fake.ID
portal.handleFakeMessage(ctx, *msg.fake)
default:
log.Warn().Any("event_data", msg).Msg("Unexpected PortalMessage with no message")
}
}
func (portal *Portal) handleMatrixMessageLoopItem(msg *PortalMatrixMessage) {
log := portal.zlog.With().
Str("action", "handle matrix event").
Stringer("event_id", msg.evt.ID).
Str("event_type", msg.evt.Type.Type).
Stringer("sender", msg.evt.Sender).
Logger()
ctx := log.WithContext(context.TODO())
portal.latestEventBackfillLock.Lock()
defer portal.latestEventBackfillLock.Unlock()
evtTS := time.UnixMilli(msg.evt.Timestamp)
timings := messageTimings{
initReceive: msg.evt.Mautrix.ReceivedAt.Sub(evtTS),
decrypt: msg.evt.Mautrix.DecryptionDuration,
portalQueue: time.Since(msg.receivedAt),
totalReceive: time.Since(evtTS),
}
implicitRRStart := time.Now()
/* EDIT LARS
portal.handleMatrixReadReceipt(ctx, msg.user, "", evtTS, false)
*/
timings.implicitRR = time.Since(implicitRRStart)
switch msg.evt.Type {
case event.EventMessage, event.EventSticker, TypeMSC3381V2PollResponse, TypeMSC3381PollResponse, TypeMSC3381PollStart:
portal.HandleMatrixMessage(ctx, msg.user, msg.evt, timings)
case event.EventRedaction:
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Stringer("redaction_target_mxid", msg.evt.Redacts)
})
portal.HandleMatrixRedaction(ctx, msg.user, msg.evt)
case event.EventReaction:
portal.HandleMatrixReaction(ctx, msg.user, msg.evt)
default:
log.Warn().Msg("Unsupported event type in portal message channel")
}
}
func (portal *Portal) handleDeliveryReceipt(ctx context.Context, receipt *events.Receipt, source *User) {
if !portal.IsPrivateChat() {
return
}
log := zerolog.Ctx(ctx)
for _, msgID := range receipt.MessageIDs {
msg, err := portal.bridge.DB.Message.GetByJID(ctx, portal.Key, msgID)
if err != nil {
log.Err(err).Str("message_id", msgID).Msg("Failed to get receipt target message")
continue
} else if msg == nil || msg.IsFakeMXID() {
continue
}
if msg.Sender == source.JID {
portal.bridge.SendRawMessageCheckpoint(&status.MessageCheckpoint{
EventID: msg.MXID,
RoomID: portal.MXID,
Step: status.MsgStepRemote,
Timestamp: jsontime.UM(receipt.Timestamp),
Status: status.MsgStatusDelivered,
ReportedBy: status.MsgReportedByBridge,
})
portal.sendStatusEvent(ctx, msg.MXID, "", nil, &[]id.UserID{portal.MainIntent().UserID})
}
}
}
func (portal *Portal) handleReceipt(ctx context.Context, receipt *events.Receipt, source *User) {
if receipt.Sender.Server != types.DefaultUserServer {
// TODO handle lids
return
}
if receipt.Type == types.ReceiptTypeDelivered {
portal.handleDeliveryReceipt(ctx, receipt, source)
return
}
// The order of the message ID array depends on the sender's platform, so we just have to find
// the last message based on timestamp. Also, timestamps only have second precision, so if
// there are many messages at the same second just mark them all as read, because we don't
// know which one is last
markAsRead := make([]*database.Message, 0, 1)
var bestTimestamp time.Time
log := zerolog.Ctx(ctx)
for _, msgID := range receipt.MessageIDs {
msg, err := portal.bridge.DB.Message.GetByJID(ctx, portal.Key, msgID)
if err != nil {
log.Err(err).Str("message_id", msgID).Msg("Failed to get receipt target message")
} else if msg == nil || msg.IsFakeMXID() {
continue
}
if msg.Timestamp.After(bestTimestamp) {
bestTimestamp = msg.Timestamp
markAsRead = append(markAsRead[:0], msg)
} else if msg != nil && msg.Timestamp.Equal(bestTimestamp) {
markAsRead = append(markAsRead, msg)
}
}
if receipt.Sender.User == source.JID.User {
if len(markAsRead) > 0 {
source.SetLastReadTS(ctx, portal.Key, markAsRead[0].Timestamp)
} else {
source.SetLastReadTS(ctx, portal.Key, receipt.Timestamp)
}
}
intent := portal.bridge.GetPuppetByJID(receipt.Sender).IntentFor(portal)
for _, msg := range markAsRead {
err := intent.SetReadMarkers(ctx, portal.MXID, source.makeReadMarkerContent(msg.MXID, intent.IsCustomPuppet))
if err != nil {
log.Err(err).
Stringer("message_mxid", msg.MXID).
Stringer("read_by_user_mxid", intent.UserID).
Msg("Failed to mark message as read")
} else {
log.Debug().
Stringer("message_mxid", msg.MXID).
Stringer("read_by_user_mxid", intent.UserID).
Msg("Marked message as read")
}
}
}
func (portal *Portal) handleMessageLoop() {
for {
portal.handleOneMessageLoopItem()
}
}
func (portal *Portal) handleOneMessageLoopItem() {
defer func() {
if err := recover(); err != nil {
logEvt := portal.zlog.WithLevel(zerolog.FatalLevel).
Str(zerolog.ErrorStackFieldName, string(debug.Stack()))
actualErr, ok := err.(error)
if ok {
logEvt = logEvt.Err(actualErr)
} else {
logEvt = logEvt.Any(zerolog.ErrorFieldName, err)
}
logEvt.Msg("Portal message handler panicked")
}
}()
select {
case msg := <-portal.events:
if msg.Message != nil {
portal.handleWhatsAppMessageLoopItem(msg.Message)
} else if msg.MatrixMessage != nil {
portal.handleMatrixMessageLoopItem(msg.MatrixMessage)
} else {
portal.zlog.Warn().Msg("Unexpected PortalEvent with no data")
}
}
}
func containsSupportedMessage(waMsg *waProto.Message) bool {
if waMsg == nil {
return false
}
return waMsg.Conversation != nil || waMsg.ExtendedTextMessage != nil || waMsg.ImageMessage != nil ||
waMsg.StickerMessage != nil || waMsg.AudioMessage != nil || waMsg.VideoMessage != nil || waMsg.PtvMessage != nil ||
waMsg.DocumentMessage != nil || waMsg.ContactMessage != nil || waMsg.LocationMessage != nil ||
waMsg.LiveLocationMessage != nil || waMsg.GroupInviteMessage != nil || waMsg.ContactsArrayMessage != nil ||
waMsg.HighlyStructuredMessage != nil || waMsg.TemplateMessage != nil || waMsg.TemplateButtonReplyMessage != nil ||
waMsg.ListMessage != nil || waMsg.ListResponseMessage != nil || waMsg.PollCreationMessage != nil || waMsg.PollCreationMessageV2 != nil
}
func getMessageType(waMsg *waProto.Message) string {
switch {
case waMsg == nil:
return "ignore"
case waMsg.Conversation != nil, waMsg.ExtendedTextMessage != nil:
return "text"
case waMsg.ImageMessage != nil:
return fmt.Sprintf("image %s", waMsg.GetImageMessage().GetMimetype())
case waMsg.StickerMessage != nil:
return fmt.Sprintf("sticker %s", waMsg.GetStickerMessage().GetMimetype())
case waMsg.VideoMessage != nil:
return fmt.Sprintf("video %s", waMsg.GetVideoMessage().GetMimetype())
case waMsg.PtvMessage != nil:
return fmt.Sprintf("round video %s", waMsg.GetPtvMessage().GetMimetype())
case waMsg.AudioMessage != nil:
return fmt.Sprintf("audio %s", waMsg.GetAudioMessage().GetMimetype())
case waMsg.DocumentMessage != nil:
return fmt.Sprintf("document %s", waMsg.GetDocumentMessage().GetMimetype())
case waMsg.ContactMessage != nil:
return "contact"
case waMsg.ContactsArrayMessage != nil:
return "contact array"
case waMsg.LocationMessage != nil:
return "location"
case waMsg.LiveLocationMessage != nil:
return "live location start"
case waMsg.GroupInviteMessage != nil:
return "group invite"
case waMsg.ReactionMessage != nil:
return "reaction"
case waMsg.EncReactionMessage != nil:
return "encrypted reaction"
case waMsg.PollCreationMessage != nil || waMsg.PollCreationMessageV2 != nil || waMsg.PollCreationMessageV3 != nil:
return "poll create"
case waMsg.PollUpdateMessage != nil:
return "poll update"
case waMsg.ProtocolMessage != nil:
switch waMsg.GetProtocolMessage().GetType() {
case waProto.ProtocolMessage_REVOKE:
if waMsg.GetProtocolMessage().GetKey() == nil {
return "ignore"
}
return "revoke"
case waProto.ProtocolMessage_MESSAGE_EDIT:
return "edit"
case waProto.ProtocolMessage_EPHEMERAL_SETTING:
return "disappearing timer change"
case waProto.ProtocolMessage_APP_STATE_SYNC_KEY_SHARE, waProto.ProtocolMessage_HISTORY_SYNC_NOTIFICATION, waProto.ProtocolMessage_INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC:
return "ignore"
default:
return fmt.Sprintf("unknown_protocol_%d", waMsg.GetProtocolMessage().GetType())
}
case waMsg.ButtonsMessage != nil:
return "buttons"
case waMsg.ButtonsResponseMessage != nil:
return "buttons response"
case waMsg.TemplateMessage != nil:
return "template"
case waMsg.HighlyStructuredMessage != nil:
return "highly structured template"
case waMsg.TemplateButtonReplyMessage != nil:
return "template button reply"
case waMsg.InteractiveMessage != nil:
return "interactive"
case waMsg.ListMessage != nil:
return "list"
case waMsg.ProductMessage != nil:
return "product"
case waMsg.ListResponseMessage != nil:
return "list response"
case waMsg.OrderMessage != nil:
return "order"
case waMsg.InvoiceMessage != nil:
return "invoice"
case waMsg.SendPaymentMessage != nil, waMsg.RequestPaymentMessage != nil,
waMsg.DeclinePaymentRequestMessage != nil, waMsg.CancelPaymentRequestMessage != nil,
waMsg.PaymentInviteMessage != nil:
return "payment"
case waMsg.Call != nil:
return "call"
case waMsg.Chat != nil:
return "chat"
case waMsg.SenderKeyDistributionMessage != nil, waMsg.StickerSyncRmrMessage != nil:
return "ignore"
default:
return "unknown"
}
}
func pluralUnit(val int, name string) string {
if val == 1 {
return fmt.Sprintf("%d %s", val, name)
} else if val == 0 {
return ""
}
return fmt.Sprintf("%d %ss", val, name)
}
func naturalJoin(parts []string) string {
if len(parts) == 0 {
return ""
} else if len(parts) == 1 {
return parts[0]
} else if len(parts) == 2 {
return fmt.Sprintf("%s and %s", parts[0], parts[1])
} else {
return fmt.Sprintf("%s and %s", strings.Join(parts[:len(parts)-1], ", "), parts[len(parts)-1])
}
}
func formatDuration(d time.Duration) string {
const Day = time.Hour * 24
var days, hours, minutes, seconds int
days, d = int(d/Day), d%Day
hours, d = int(d/time.Hour), d%time.Hour
minutes, d = int(d/time.Minute), d%time.Minute
seconds = int(d / time.Second)
parts := make([]string, 0, 4)
if days > 0 {
parts = append(parts, pluralUnit(days, "day"))
}
if hours > 0 {
parts = append(parts, pluralUnit(hours, "hour"))
}
if minutes > 0 {
parts = append(parts, pluralUnit(seconds, "minute"))
}
if seconds > 0 {
parts = append(parts, pluralUnit(seconds, "second"))
}
return naturalJoin(parts)
}
func (portal *Portal) convertMessage(ctx context.Context, intent *appservice.IntentAPI, source *User, info *types.MessageInfo, waMsg *waProto.Message, isBackfill bool) *ConvertedMessage {
switch {
case waMsg.Conversation != nil || waMsg.ExtendedTextMessage != nil:
return portal.convertTextMessage(ctx, intent, source, waMsg)
case waMsg.TemplateMessage != nil:
return portal.convertTemplateMessage(ctx, intent, source, info, waMsg.GetTemplateMessage())
case waMsg.HighlyStructuredMessage != nil:
return portal.convertTemplateMessage(ctx, intent, source, info, waMsg.GetHighlyStructuredMessage().GetHydratedHsm())
case waMsg.TemplateButtonReplyMessage != nil:
return portal.convertTemplateButtonReplyMessage(ctx, intent, waMsg.GetTemplateButtonReplyMessage())
case waMsg.ListMessage != nil:
return portal.convertListMessage(ctx, intent, source, waMsg.GetListMessage())
case waMsg.ListResponseMessage != nil:
return portal.convertListResponseMessage(ctx, intent, waMsg.GetListResponseMessage())
case waMsg.PollCreationMessage != nil:
return portal.convertPollCreationMessage(ctx, intent, waMsg.GetPollCreationMessage())
case waMsg.PollCreationMessageV2 != nil:
return portal.convertPollCreationMessage(ctx, intent, waMsg.GetPollCreationMessageV2())
case waMsg.PollCreationMessageV3 != nil:
return portal.convertPollCreationMessage(ctx, intent, waMsg.GetPollCreationMessageV3())
case waMsg.PollUpdateMessage != nil:
return portal.convertPollUpdateMessage(ctx, intent, source, info, waMsg.GetPollUpdateMessage())
case waMsg.ImageMessage != nil:
return portal.convertMediaMessage(ctx, intent, source, info, waMsg.GetImageMessage(), "photo", isBackfill)
case waMsg.StickerMessage != nil:
return portal.convertMediaMessage(ctx, intent, source, info, waMsg.GetStickerMessage(), "sticker", isBackfill)
case waMsg.VideoMessage != nil:
return portal.convertMediaMessage(ctx, intent, source, info, waMsg.GetVideoMessage(), "video attachment", isBackfill)
case waMsg.PtvMessage != nil:
return portal.convertMediaMessage(ctx, intent, source, info, waMsg.GetPtvMessage(), "video message", isBackfill)
case waMsg.AudioMessage != nil:
typeName := "audio attachment"
if waMsg.GetAudioMessage().GetPTT() {
typeName = "voice message"
}
return portal.convertMediaMessage(ctx, intent, source, info, waMsg.GetAudioMessage(), typeName, isBackfill)
case waMsg.DocumentMessage != nil:
return portal.convertMediaMessage(ctx, intent, source, info, waMsg.GetDocumentMessage(), "file attachment", isBackfill)
case waMsg.ContactMessage != nil:
return portal.convertContactMessage(ctx, intent, waMsg.GetContactMessage())
case waMsg.ContactsArrayMessage != nil:
return portal.convertContactsArrayMessage(ctx, intent, waMsg.GetContactsArrayMessage())
case waMsg.LocationMessage != nil:
return portal.convertLocationMessage(ctx, intent, waMsg.GetLocationMessage())
case waMsg.LiveLocationMessage != nil:
return portal.convertLiveLocationMessage(ctx, intent, waMsg.GetLiveLocationMessage())
case waMsg.GroupInviteMessage != nil:
return portal.convertGroupInviteMessage(ctx, intent, info, waMsg.GetGroupInviteMessage())
case waMsg.ProtocolMessage != nil && waMsg.ProtocolMessage.GetType() == waProto.ProtocolMessage_EPHEMERAL_SETTING:
portal.ExpirationTime = waMsg.ProtocolMessage.GetEphemeralExpiration()
err := portal.Update(ctx)
if err != nil {
zerolog.Ctx(ctx).Err(err).Msg("Failed to save portal after updating expiration timer")
}
return &ConvertedMessage{
Intent: intent,
Type: event.EventMessage,
Content: &event.MessageEventContent{
Body: portal.formatDisappearingMessageNotice(),
MsgType: event.MsgNotice,
},
}
default:
return nil
}
}
func (portal *Portal) implicitlyEnableDisappearingMessages(ctx context.Context, timer time.Duration) {
portal.ExpirationTime = uint32(timer.Seconds())
err := portal.Update(ctx)
if err != nil {
zerolog.Ctx(ctx).Err(err).Msg("Failed to save portal after implicitly enabling disappearing timer")
}
intent := portal.MainIntent()
if portal.Encrypted {
intent = portal.bridge.Bot
}
duration := formatDuration(time.Duration(portal.ExpirationTime) * time.Second)
_, err = portal.sendMessage(ctx, intent, event.EventMessage, &event.MessageEventContent{
MsgType: event.MsgNotice,
Body: fmt.Sprintf("Automatically enabled disappearing message timer (%s) because incoming message is disappearing", duration),
}, nil, 0)
if err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Msg("Failed to send notice about implicit disappearing timer")
}
}
func (portal *Portal) UpdateGroupDisappearingMessages(ctx context.Context, sender *types.JID, timestamp time.Time, timer uint32) {
if portal.ExpirationTime == timer {
return
}
portal.ExpirationTime = timer
err := portal.Update(ctx)
if err != nil {
zerolog.Ctx(ctx).Err(err).Msg("Failed to save portal after updating expiration timer")
}
intent := portal.MainIntent()
if sender != nil && sender.Server == types.DefaultUserServer {
intent = portal.bridge.GetPuppetByJID(sender.ToNonAD()).IntentFor(portal)
} else {
sender = &types.EmptyJID
}
_, err = portal.sendMessage(ctx, intent, event.EventMessage, &event.MessageEventContent{
Body: portal.formatDisappearingMessageNotice(),
MsgType: event.MsgNotice,
}, nil, timestamp.UnixMilli())
if err != nil {
zerolog.Ctx(ctx).Warn().Err(err).
Uint32("new_timer", timer).
Stringer("sender_jid", sender).
Msg("Failed to notify portal about disappearing message timer change")
}
}
func (portal *Portal) formatDisappearingMessageNotice() string {
if portal.ExpirationTime == 0 {
return "Turned off disappearing messages"
}
return fmt.Sprintf("Set the disappearing message timer to %s", formatDuration(time.Duration(portal.ExpirationTime)*time.Second))
}
const UndecryptableMessageNotice = "Decrypting message from WhatsApp failed, waiting for sender to re-send... " +
"([learn more](https://faq.whatsapp.com/general/security-and-privacy/seeing-waiting-for-this-message-this-may-take-a-while))"
var undecryptableMessageContent event.MessageEventContent
func init() {
undecryptableMessageContent = format.RenderMarkdown(UndecryptableMessageNotice, true, false)
undecryptableMessageContent.MsgType = event.MsgNotice
}
func (portal *Portal) handleUndecryptableMessage(ctx context.Context, source *User, evt *events.UndecryptableMessage) {
log := zerolog.Ctx(ctx)
if len(portal.MXID) == 0 {
log.Warn().Msg("handleUndecryptableMessage called even though portal.MXID is empty")
return
} else if portal.isRecentlyHandled(evt.Info.ID, database.MsgErrDecryptionFailed) {
log.Debug().Msg("Not handling recently handled message")
return
} else if existingMsg, err := portal.bridge.DB.Message.GetByJID(ctx, portal.Key, evt.Info.ID); err != nil {
log.Err(err).Msg("Failed to get message from database to check if undecryptable message is duplicate")
return
} else if existingMsg != nil {
log.Debug().Msg("Not handling duplicate message")
return
}
metricType := "error"
if evt.IsUnavailable {
metricType = "unavailable"
}
Analytics.Track(source.MXID, "WhatsApp undecryptable message", map[string]interface{}{
"messageID": evt.Info.ID,
"undecryptableType": metricType,
})
intent := portal.getMessageIntent(ctx, source, &evt.Info)
if intent == nil {
return
}
content := undecryptableMessageContent
resp, err := portal.sendMessage(ctx, intent, event.EventMessage, &content, nil, evt.Info.Timestamp.UnixMilli())
if err != nil {
log.Err(err).Msg("Failed to send WhatsApp decryption error message to Matrix")
return
}
portal.finishHandling(ctx, nil, &evt.Info, resp.EventID, intent.UserID, database.MsgUnknown, 0, database.MsgErrDecryptionFailed)
}
func (portal *Portal) handleFakeMessage(ctx context.Context, msg fakeMessage) {
log := zerolog.Ctx(ctx)
if portal.isRecentlyHandled(msg.ID, database.MsgNoError) {
log.Debug().Msg("Not handling recently handled message")
return
} else if existingMsg, err := portal.bridge.DB.Message.GetByJID(ctx, portal.Key, msg.ID); err != nil {
log.Err(err).Msg("Failed to get message from database to check if fake message is duplicate")
return
} else if existingMsg != nil {
log.Debug().Msg("Not handling duplicate message")
return
}
if msg.Sender.Server != types.DefaultUserServer {
log.Debug().Msg("Not handling message from @lid user")
// TODO handle lids
return
}
intent := portal.bridge.GetPuppetByJID(msg.Sender).IntentFor(portal)
if !intent.IsCustomPuppet && portal.IsPrivateChat() && msg.Sender.User == portal.Key.Receiver.User && portal.Key.Receiver != portal.Key.JID {
log.Debug().Msg("Not handling fake message for user who doesn't have double puppeting enabled")
return
}
msgType := event.MsgNotice
if msg.Important {
msgType = event.MsgText
}
resp, err := portal.sendMessage(ctx, intent, event.EventMessage, &event.MessageEventContent{
MsgType: msgType,
Body: msg.Text,
}, nil, msg.Time.UnixMilli())
if err != nil {
log.Err(err).Msg("Failed to send fake message to Matrix")
} else {
portal.finishHandling(ctx, nil, &types.MessageInfo{
ID: msg.ID,
Timestamp: msg.Time,
MessageSource: types.MessageSource{
Sender: msg.Sender,
},
}, resp.EventID, intent.UserID, database.MsgFake, 0, database.MsgNoError)
}
}
func (portal *Portal) handleMessage(ctx context.Context, source *User, evt *events.Message, historical bool) {
log := zerolog.Ctx(ctx)
if len(portal.MXID) == 0 {
log.Warn().Msg("handleMessage called even though portal.MXID is empty")
return
}
msgID := evt.Info.ID
msgType := getMessageType(evt.Message)
if msgType == "ignore" {
return
} else if portal.isRecentlyHandled(msgID, database.MsgNoError) {
log.Debug().Msg("Not handling recently handled message")
return
}
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("wa_message_type", msgType)
})
existingMsg, err := portal.bridge.DB.Message.GetByJID(ctx, portal.Key, msgID)
if err != nil {
log.Err(err).Msg("Failed to get message from database to check if message is duplicate")
return
}
if existingMsg != nil {
if existingMsg.Error == database.MsgErrDecryptionFailed {
resolveType := "sender"
if evt.UnavailableRequestID != "" {
resolveType = "phone"
}
Analytics.Track(source.MXID, "WhatsApp undecryptable message resolved", map[string]interface{}{
"messageID": evt.Info.ID,
"resolveType": resolveType,
})
log.Debug().Str("resolved_via", resolveType).Msg("Got decryptable version of previously undecryptable message")
} else {
log.Debug().Msg("Not handling duplicate message")
return
}
}
var editTargetMsg *database.Message
if msgType == "edit" {
editTargetID := evt.Message.GetProtocolMessage().GetKey().GetId()
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("edit_target_id", editTargetID)
})
editTargetMsg, err = portal.bridge.DB.Message.GetByJID(ctx, portal.Key, editTargetID)
if err != nil {
log.Err(err).Msg("Failed to get edit target message from database")
return
} else if editTargetMsg == nil {
log.Warn().Msg("Not handling edit: couldn't find edit target")
return
} else if editTargetMsg.Type != database.MsgNormal {
log.Warn().Str("edit_target_db_type", string(editTargetMsg.Type)).
Msg("Not handling edit: edit target is not a normal message")
return
} else if editTargetMsg.Sender.User != evt.Info.Sender.User {
log.Warn().Stringer("edit_target_sender", editTargetMsg.Sender).
Msg("Not handling edit: edit was sent by another user")
return
}
evt.Message = evt.Message.GetProtocolMessage().GetEditedMessage()
}
intent := portal.getMessageIntent(ctx, source, &evt.Info)
if intent == nil {
return