Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
1369 lines (1080 loc) · 35.1 KB
/
Copy pathclient.go
File metadata and controls
1369 lines (1080 loc) · 35.1 KB
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
// Package matrixclient is a small Matrix client library used by matterircd
// (and usable by matterbridge), the equivalent of matterclient for Mattermost.
package matrixclient
import (
"context"
"crypto/rand"
"errors"
"math/big"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
lru "github.com/hashicorp/golang-lru/v2"
prefixed "github.com/matterbridge/logrus-prefixed-formatter"
"github.com/sirupsen/logrus"
)
const eventCacheSize = 2000
// Client is a logged in Matrix client keeping track of rooms and users.
type Client struct {
sync.RWMutex
mc *mautrix.Client
handler Handler
ctx context.Context //nolint:containedctx
cancel context.CancelFunc
connected atomic.Bool
synced atomic.Bool // set once the initial sync was processed
// lookupUntil is the deadline in unix nanoseconds for redaction type lookups
// of the sync response being processed, reset for every response.
lookupUntil atomic.Int64
cred Credentials
// stateLock guards the debounce maps and is never held across API calls.
stateLock sync.Mutex
lastViewed map[id.RoomID]viewedMark
lastTyping map[id.RoomID]time.Time
logger *logrus.Entry
rootLogger *logrus.Logger
apiLogger *logrus.Entry
rootAPILogger *logrus.Logger
channels map[id.RoomID]*Channel
dmChannels map[id.RoomID][]id.UserID
directData map[id.UserID][]id.RoomID // last known m.direct account data
users map[id.UserID]*User
presence map[id.UserID]Presence
presenceFetched map[id.UserID]int64
timezones map[string]*time.Location
spaces map[id.RoomID]*space
eventCache *lru.Cache[id.EventID, *event.Event]
invitations map[id.RoomID]Invitation
// Accepted direct invites may not appear in m.direct, even after joining.
acceptedDirect map[id.RoomID]id.UserID
pendingDirect map[id.RoomID]pendingAssoc // associations not yet seen in m.direct, see recordDirect
creatingDirect map[id.UserID]int // SendDirect calls inside CreateRoom, whose room is unknown until it returns
leftRooms map[id.RoomID]struct{} // excludes departed rooms from selection, not DM classification
joinedRooms map[id.RoomID]struct{} // rooms seen in a sync join section or created here, m.direct may list others
// directWriteMu serializes the m.direct snapshot, write and cache update, as each write
// replaces the whole account data. It is never held with the client lock over network I/O.
directWriteMu sync.Mutex
crypto Crypto
verification VerificationController
decryptFailures bool // crypto reports terminal decryption failures
defaultProvider string
lastSync atomic.Int64 // unix nanoseconds of the last processed sync response
syncDuration atomic.Int64 // duration in nanoseconds of the last /sync HTTP request
forceRelogin atomic.Bool
nameResolved func(roomID id.RoomID, name string) // see WithRoomNameResolved
// nameHealing tracks the room IDs with a running healing goroutine.
nameHealing sync.Map
nameLookups chan struct{} // bounds the concurrent name lookups of all healing goroutines
// nameNotify serializes the room name callbacks with the name state they report,
// so a late callback cannot overtake a newer one. It is taken before the client lock.
nameNotify sync.Mutex
nameDirty map[id.RoomID]struct{} // rooms whose fallback name a shared profile change may have changed
}
// New logs in and starts syncing. Handler.Ready is called after the initial sync.
func New(ctx context.Context, cred Credentials, h Handler, opts ...Option) (*Client, error) { //nolint:funlen
var o options
for _, opt := range opts {
opt(&o)
}
rootLogger, rootAPILogger := newLoggers()
mc, err := mautrix.NewClient(cred.Server, "", "")
if err != nil {
return nil, err
}
eventCache, _ := lru.New[id.EventID, *event.Event](eventCacheSize)
c := &Client{
mc: mc,
handler: h,
cred: cred,
defaultProvider: o.defaultProvider,
rootLogger: rootLogger,
logger: rootLogger.WithFields(logrus.Fields{"prefix": "matrixclient"}),
rootAPILogger: rootAPILogger,
apiLogger: rootAPILogger.WithFields(logrus.Fields{"prefix": "matrixclient: API"}),
channels: make(map[id.RoomID]*Channel),
dmChannels: make(map[id.RoomID][]id.UserID),
directData: make(map[id.UserID][]id.RoomID),
users: make(map[id.UserID]*User),
presence: make(map[id.UserID]Presence),
presenceFetched: make(map[id.UserID]int64),
timezones: make(map[string]*time.Location),
spaces: make(map[id.RoomID]*space),
eventCache: eventCache,
invitations: make(map[id.RoomID]Invitation),
acceptedDirect: make(map[id.RoomID]id.UserID),
pendingDirect: make(map[id.RoomID]pendingAssoc),
creatingDirect: make(map[id.UserID]int),
leftRooms: make(map[id.RoomID]struct{}),
joinedRooms: make(map[id.RoomID]struct{}),
nameResolved: o.nameResolved,
nameLookups: make(chan struct{}, maxNameLookups),
nameDirty: make(map[id.RoomID]struct{}),
lastViewed: make(map[id.RoomID]viewedMark),
lastTyping: make(map[id.RoomID]time.Time),
}
ctx, c.cancel = context.WithCancel(ctx)
c.ctx = ctx
if o.userAgent != "" {
mc.UserAgent = o.userAgent
}
// Prevent /sync from implicitly resetting presence to online on every poll
// so explicit SetStatus calls (e.g. away) are not immediately overwritten.
mc.SyncPresence = event.PresenceOffline
mc.Client.Transport = newAPILogTransport(newTransport(&o), c.apiLogger, &c.syncDuration)
syncer, ok := mc.Syncer.(*mautrix.DefaultSyncer)
if !ok {
return nil, errors.New("matrixclient: unexpected syncer type")
}
syncer.FilterJSON = newSyncFilter()
baseParseError := syncer.ParseErrorHandler
syncer.ParseErrorHandler = func(ev *event.Event, err error) bool {
if baseParseError != nil && baseParseError(ev, err) {
return true
}
if ev != nil {
c.resolvePending(ev.RoomID, ev.ID)
}
return false
}
c.register(syncer)
// Ready is called from the sync goroutine, after the events of the first
// sync response were processed, so handler calls stay serialized.
mc.Syncer = &readySyncer{
DefaultSyncer: syncer,
logger: c.logger,
ready: h.Ready,
synced: c.onSynced,
reconnected: c.notifyReconnect,
named: c.noteRoomNames,
track: c.noteTimeline,
summary: c.logSyncSummary,
leftInvites: c.removeLeftInvitations,
decrypted: c.noteDecrypted,
failed: c.onSyncFailed,
begin: c.beginLookups,
syncDuration: &c.syncDuration,
}
err = c.login(ctx, o.crypto)
if err != nil {
c.cancel()
return nil, err
}
c.applyDeviceName(ctx)
c.connected.Store(true)
go c.syncLoop()
go c.maintainPresence()
return c, nil
}
func newLoggers() (*logrus.Logger, *logrus.Logger) {
// Logger for the rest of matrixclient
rootLogger := logrus.New()
rootLogger.SetFormatter(&prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: false,
FullTimestamp: true,
})
// Logger for Matrix API calls
rootAPILogger := logrus.New()
rootAPILogger.SetFormatter(&prefixed.TextFormatter{
PrefixPadding: 18,
DisableColors: false,
FullTimestamp: true,
})
// Default to higher than "warn" to not log anything
rootAPILogger.SetLevel(logrus.ErrorLevel)
return rootLogger, rootAPILogger
}
// loginToken adopts cred.Token, looking up the user and device it belongs to.
func (c *Client) loginToken(ctx context.Context) error {
c.mc.AccessToken = c.cred.Token
resp, err := c.mc.Whoami(ctx)
if err != nil {
return err
}
// Whoami may omit the device ID, only then is the configured one trusted.
if resp.DeviceID != "" && c.cred.DeviceID != "" && resp.DeviceID != c.cred.DeviceID {
return errors.New("matrixclient: token belongs to device " + resp.DeviceID.String() + ", not the configured " + c.cred.DeviceID.String())
}
c.mc.UserID = resp.UserID
c.mc.DeviceID = resp.DeviceID
if c.mc.DeviceID == "" {
c.mc.DeviceID = c.cred.DeviceID
}
return nil
}
func (c *Client) login(ctx context.Context, factory CryptoFactory) error {
if c.cred.Token != "" {
err := c.loginToken(ctx)
if err != nil {
return err
}
if factory == nil {
return nil
}
}
if factory == nil {
_, err := c.mc.Login(ctx, loginReq(c.cred, ""))
return err
}
// The crypto helper logs in itself to reuse the device stored with its keys.
var req *mautrix.ReqLogin
if c.cred.Token == "" {
req = loginReq(c.cred, "")
}
crypto, err := factory(c.mc, req)
if err != nil {
return err
}
c.crypto = crypto
if n, ok := crypto.(DecryptFailureNotifier); ok {
n.OnDecryptFailure(c.noteDecryptFailure)
c.decryptFailures = true
}
c.mc.Crypto = crypto
err = crypto.Init(ctx)
if err != nil {
_ = crypto.Close()
return err
}
if h, ok := c.handler.(VerificationHandler); ok {
if p, supported := crypto.(VerificationProvider); supported {
c.verification, err = p.InitVerification(ctx, h.OnVerification)
if err != nil {
_ = crypto.Close()
return err
}
}
}
c.logger.Info("end-to-end encryption enabled")
return nil
}
func (c *Client) register(s *mautrix.DefaultSyncer) {
s.OnSync(c.syncInvitations)
onState := func(t event.Type, handler mautrix.EventHandler) {
s.OnEventType(t, func(ctx context.Context, ev *event.Event) {
// Stripped invite state belongs to Invitations, not the joined room cache.
if ev.Mautrix.EventSource&event.SourceInvite != 0 {
return
}
handler(ctx, ev)
})
}
s.OnEventType(event.EventMessage, c.handleMessage)
s.OnEventType(event.EventReaction, c.handleReaction)
s.OnEventType(event.StateMember, c.handleMember)
onState(event.StateRoomName, c.handleRoomName)
s.OnEventType(event.AccountDataDirectChats, c.handleDM)
onState(event.StateCanonicalAlias, c.handleCanonicalAlias)
onState(event.StateJoinRules, c.handleJoinRules)
onState(event.StateHistoryVisibility, c.handleHistoryVisibility)
s.OnEventType(event.EventRedaction, c.handleRedaction)
s.OnEventType(event.EphemeralEventTyping, c.handleTyping)
onState(event.StateTopic, c.handleTopic)
onState(event.StatePinnedEvents, c.handlePinnedEvents)
onState(event.StateCreate, c.handleCreate)
onState(event.StateEncryption, c.handleEncryption)
onState(event.StateSpaceChild, c.handleSpaceChild)
s.OnEventType(event.EphemeralEventPresence, c.handlePresence)
}
// newSyncFilter returns a /sync denylist filter that suppresses high-volume
// unused events (such as read receipts, per-room account data, stickers, and
// call signaling) while keeping the default timeline limit of 50 and letting
// unknown/future events through.
func newSyncFilter() *mautrix.Filter {
ignoredState := []event.Type{
event.StateRoomAvatar,
event.StateServerACL,
event.StateGuestAccess,
event.StatePowerLevels,
}
ignoredTimeline := make([]event.Type, 0, len(ignoredState)+2)
ignoredTimeline = append(ignoredTimeline, ignoredState...)
ignoredTimeline = append(ignoredTimeline,
event.EventSticker,
event.Type{Type: "m.call.*"},
)
return &mautrix.Filter{
Room: &mautrix.RoomFilter{
AccountData: &mautrix.FilterPart{
NotTypes: []event.Type{{Type: "*"}},
},
Ephemeral: &mautrix.FilterPart{
NotTypes: []event.Type{event.EphemeralEventReceipt},
},
State: &mautrix.FilterPart{
NotTypes: ignoredState,
},
Timeline: &mautrix.FilterPart{
Limit: 50,
NotTypes: ignoredTimeline,
},
},
}
}
func (c *Client) syncLoop() {
backoff := time.Second
for c.ctx.Err() == nil {
if c.forceRelogin.Swap(false) && c.cred.Token == "" {
err := c.relogin(c.ctx)
if err != nil {
c.apiLogger.Errorf("reconnect: %s", err)
}
}
err := c.mc.SyncWithContext(c.ctx)
if err == nil || c.ctx.Err() != nil {
continue
}
// A sync that was healthy before failing starts over with a short backoff.
if c.connected.Swap(false) {
backoff = time.Second
}
c.apiLogger.Errorf("sync: %s", err)
if errors.Is(err, mautrix.MUnknownToken) {
err = c.relogin(c.ctx)
if err != nil {
c.apiLogger.Errorf("relogin: %s", err)
}
}
select {
case <-c.ctx.Done():
case <-time.After(backoff):
}
backoff = min(backoff*2, maxSyncBackoff)
}
}
// readySyncer calls ready once, after the first sync response was processed.
type readySyncer struct {
*mautrix.DefaultSyncer
logger *logrus.Entry
once sync.Once
ready func()
synced func() (bool, time.Duration)
reconnected func(ReconnectInfo)
named func(*mautrix.RespSync)
track func(*mautrix.RespSync)
summary func(*mautrix.RespSync)
decrypted func(*event.Event)
failed func(err error, wait time.Duration)
syncDuration *atomic.Int64
begin func()
leftInvites func(*mautrix.RespSync)
failures int // consecutive failed syncs, only used from the sync goroutine
}
//nolint:funlen
func (r *readySyncer) ProcessResponse(ctx context.Context, res *mautrix.RespSync, since string) error {
start := time.Now()
r.begin()
r.summary(res)
r.track(res)
prepDuration := time.Since(start)
syncerStart := time.Now()
err := r.DefaultSyncer.ProcessResponse(ctx, res, since)
if err != nil {
return err
}
syncerDuration := time.Since(syncerStart)
if r.failures > 0 {
var reqDuration time.Duration
if r.syncDuration != nil {
reqDuration = time.Duration(r.syncDuration.Load())
}
if reqDuration > 0 {
r.logger.Infof("sync recovered after %d failure(s) (request: %s)", r.failures, reqDuration)
} else {
r.logger.Infof("sync recovered after %d failure(s)", r.failures)
}
}
r.failures = 0
postStart := time.Now()
r.leftInvites(res)
reconnected, downtime := r.synced()
postDuration := time.Since(postStart)
namedStart := time.Now()
r.named(res)
namedDuration := time.Since(namedStart)
readyStart := time.Now()
r.once.Do(r.ready)
if reconnected && r.reconnected != nil {
var limited map[id.RoomID]string
for roomID, room := range res.Rooms.Join {
if room != nil && room.Timeline.Limited {
if limited == nil {
limited = make(map[id.RoomID]string)
}
limited[roomID] = room.Timeline.PrevBatch
}
}
r.reconnected(ReconnectInfo{
Downtime: downtime,
LimitedRooms: limited,
})
}
readyDuration := time.Since(readyStart)
totalDuration := time.Since(start)
if since == "" {
r.logger.Infof("initial sync processed in %s (prep: %s, syncer: %s, named: %s, post: %s, ready: %s)",
totalDuration.Round(time.Millisecond),
prepDuration.Round(time.Millisecond),
syncerDuration.Round(time.Millisecond),
namedDuration.Round(time.Millisecond),
postDuration.Round(time.Millisecond),
readyDuration.Round(time.Millisecond),
)
} else if totalDuration > 500*time.Millisecond {
r.logger.Debugf("sync processed in %s (prep: %s, syncer: %s, named: %s, post: %s, ready: %s)",
totalDuration.Round(time.Millisecond),
prepDuration.Round(time.Millisecond),
syncerDuration.Round(time.Millisecond),
namedDuration.Round(time.Millisecond),
postDuration.Round(time.Millisecond),
readyDuration.Round(time.Millisecond),
)
}
return nil
}
// OnFailedSync retries quickly at first, then backs off exponentially with
// jitter, instead of the 10 second fixed wait of the default syncer. The sync
// resumes from the last next_batch token, so no events are missed.
func (r *readySyncer) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) {
if errors.Is(err, mautrix.MUnknownToken) {
return 0, err
}
wait := min(time.Second<<min(r.failures, 5), maxSyncRetryWait)
jitter, randomErr := rand.Int(rand.Reader, big.NewInt(int64(wait/2)+1))
if randomErr == nil {
wait += time.Duration(jitter.Int64())
}
r.failures++
r.failed(err, wait)
return wait, nil
}
// Dispatch sees the events the crypto helper dispatches after decrypting them.
func (r *readySyncer) Dispatch(ctx context.Context, ev *event.Event) {
r.decrypted(ev)
r.DefaultSyncer.Dispatch(ctx, ev)
}
// Logout stops syncing.
func (c *Client) Logout() {
c.connected.Store(false)
c.cancel()
c.stopHoldbacks()
if c.crypto != nil {
_ = c.crypto.Close()
}
}
// Connected reports whether the client is logged in.
func (c *Client) Connected() bool { return c.connected.Load() }
// Encrypted reports whether end-to-end encryption is enabled.
func (c *Client) Encrypted() bool { return c.crypto != nil }
// DeviceID is the ID of our device, as listed under the sessions of other clients.
// It is empty when end-to-end encryption is disabled.
func (c *Client) DeviceID() id.DeviceID {
if c.crypto == nil {
return ""
}
return c.mc.DeviceID
}
// Fingerprint is the fingerprint of our device's Ed25519 key, for manual verification.
// It is empty when end-to-end encryption is disabled.
func (c *Client) Fingerprint() string {
if p, ok := c.crypto.(FingerprintProvider); ok {
return p.Fingerprint()
}
return ""
}
// DeviceVerified reports whether our device is verified or cross-signed and
// trusted. Trust is resolved from the local crypto store, so verification or
// revocation done elsewhere is only reflected once sync has stored it. It is
// false when end-to-end encryption is disabled or the account has no
// cross-signing.
// When encryption is enabled, a read-only server request first confirms our
// device still exists, so connectivity is required. A non-nil error, including
// a network error, a missing device or an authentication failure, means the
// state could not be determined, which is not the same as unverified.
func (c *Client) DeviceVerified(ctx context.Context) (bool, error) {
if p, ok := c.crypto.(DeviceVerifier); ok {
return p.DeviceVerified(ctx)
}
return false, nil
}
// UserVerified reports whether userID is verified, which is the "secure" state
// of a WHOIS. For our own user it is DeviceVerified, for others their
// cross-signing master key must be signed by our user-signing key. Trust is
// resolved from the local crypto store. It is false when end-to-end encryption
// is disabled or the user has no known cross-signing keys.
func (c *Client) UserVerified(ctx context.Context, userID id.UserID) (bool, error) {
if userID == c.mc.UserID {
return c.DeviceVerified(ctx)
}
if p, ok := c.crypto.(UserVerifier); ok {
return p.UserVerified(ctx, userID)
}
return false, nil
}
// UserID is our own user ID.
func (c *Client) UserID() id.UserID { return c.mc.UserID }
// IsDirect reports whether roomID is a direct message room.
func (c *Client) IsDirect(roomID id.RoomID) bool {
c.RLock()
defer c.RUnlock()
if _, ok := c.dmChannels[roomID]; ok {
return true
}
_, inferred := c.inferredDirectRoomLocked(roomID)
return inferred
}
// DirectUsers returns the users of a direct message room.
func (c *Client) DirectUsers(roomID id.RoomID) []id.UserID {
c.RLock()
defer c.RUnlock()
if users, ok := c.dmChannels[roomID]; ok {
return slices.Clone(users)
}
if peer, inferred := c.inferredDirectRoomLocked(roomID); inferred {
return []id.UserID{peer}
}
return nil
}
// inferredDirectRoomLocked is inferredDirectLocked for a room ID, c must be read locked.
func (c *Client) inferredDirectRoomLocked(roomID id.RoomID) (id.UserID, bool) {
ch, ok := c.channels[roomID]
if !ok {
return "", false
}
ch.RLock()
defer ch.RUnlock()
return c.inferredDirectLocked(ch)
}
// DirectRoom returns the direct message room with userID, or "", excluding invitations and departed rooms.
func (c *Client) DirectRoom(userID id.UserID) id.RoomID {
c.RLock()
defer c.RUnlock()
for roomID, users := range c.dmChannels {
if _, invited := c.invitations[roomID]; invited {
continue
}
if _, left := c.leftRooms[roomID]; left {
continue
}
// m.direct can list rooms we never joined or left earlier, c.channels has entries for those too.
if _, joined := c.joinedRooms[roomID]; !joined {
continue
}
if len(users) == 1 && users[0] == userID {
return roomID
}
}
for roomID := range c.channels {
if _, invited := c.invitations[roomID]; invited {
continue
}
if _, left := c.leftRooms[roomID]; left {
continue
}
if _, mapped := c.dmChannels[roomID]; mapped {
continue
}
if peer, inferred := c.inferredDirectRoomLocked(roomID); inferred && peer == userID {
return roomID
}
}
return ""
}
// LastEventID returns the newest message event seen in a room, "" if none.
func (c *Client) LastEventID(roomID id.RoomID) id.EventID {
c.RLock()
ch, ok := c.channels[roomID]
c.RUnlock()
if !ok {
return ""
}
ch.RLock()
defer ch.RUnlock()
return ch.LastEventID
}
// LastDeliveredEventID returns the newest message event, by timeline position, whose
// handler call has returned, "" if none. Unlike LastEventID, which advances before the
// handler is called, it never includes an event the handler has not seen yet, so a
// consumer that hands events on asynchronously can acknowledge up to it once it has
// handed over everything the handler returned for. Messages of the initial sync count
// as delivered, as they are never passed to the handler.
func (c *Client) LastDeliveredEventID(roomID id.RoomID) id.EventID {
c.RLock()
ch, ok := c.channels[roomID]
c.RUnlock()
if !ok {
return ""
}
ch.RLock()
defer ch.RUnlock()
return ch.DeliveredEventID
}
// RoomInfo is a snapshot of a room.
type RoomInfo struct {
ID id.RoomID
Name string // alias, room name, member names or short ID, with ':' replaced by '/'
IsDirect bool
LastActivity int64 // timestamp in milliseconds of the newest message seen, 0 if none
}
// Rooms returns a snapshot of the known rooms (excluding invitations, departed rooms and 1:1 direct rooms).
func (c *Client) Rooms() []RoomInfo {
c.RLock()
defer c.RUnlock()
rooms := make([]RoomInfo, 0, len(c.channels))
for roomID, ch := range c.channels {
if _, invited := c.invitations[roomID]; invited {
continue
}
if _, left := c.leftRooms[roomID]; left {
continue
}
ch.Lock()
display := c.displayNameLocked(roomID, ch)
_, inferred := c.inferredDirectLocked(ch)
unresolved, direct, members, last := ch.nameUnresolvedLocked(), ch.IsDirect || inferred, len(ch.Members), ch.LastActivity
// Withheld until SendDirect marks it, so it is not listed as a channel and dropped again.
if !direct && c.creatingDirectRoomLocked(ch) {
ch.Unlock()
continue
}
// The name of a DM is not a channel name, the baseline stays what the consumer holds.
if !direct {
ch.reportNameLocked(display)
}
ch.noteListedLocked(direct)
ch.Unlock()
if unresolved {
c.logger.Debugf("room %s has no name or alias, listing it as %s", roomID, display)
c.healRoomName(c.ctx, roomID, ch)
}
// DM associations carry no members, so a direct room may not have any cached yet.
if direct && members <= 1 {
continue
}
rooms = append(rooms, RoomInfo{
ID: roomID,
Name: display,
IsDirect: direct,
LastActivity: last,
})
}
return rooms
}
// roomName converts an alias to a channel name, dropping the default provider.
func (c *Client) roomName(alias id.RoomAlias) string {
if c.defaultProvider != "" {
if name, ok := strings.CutSuffix(string(alias), ":"+c.defaultProvider); ok {
return name
}
}
return strings.Replace(string(alias), ":", "/", 1)
}
// DisplayName returns the known display name of a user, or "".
func (c *Client) DisplayName(userID id.UserID) string {
c.RLock()
defer c.RUnlock()
if u, ok := c.users[userID]; ok && u.MemberEventContent != nil {
return u.Displayname
}
return ""
}
// KnownUsers returns the IDs of all known users.
func (c *Client) KnownUsers() []id.UserID {
c.RLock()
defer c.RUnlock()
ids := make([]id.UserID, 0, len(c.users))
for userID := range c.users {
ids = append(ids, userID)
}
return ids
}
// GetUserCount returns the total number of cached users.
func (c *Client) GetUserCount() int {
c.RLock()
defer c.RUnlock()
return len(c.users)
}
// FindUser returns the first known user for which match returns true.
func (c *Client) FindUser(match func(userID id.UserID, displayName string) bool) (id.UserID, bool) {
c.RLock()
defer c.RUnlock()
for userID, u := range c.users {
var displayName string
if u.MemberEventContent != nil {
displayName = u.Displayname
}
if match(userID, displayName) {
return userID, true
}
}
return "", false
}
// userIDKeyLocked returns the cached copy of userID, if the user is cached, so
// per-user maps share a single copy of every ID. c must be locked.
func (c *Client) userIDKeyLocked(userID id.UserID) id.UserID {
if u, ok := c.users[userID]; ok {
return u.ID
}
return userID
}
// JoinedMembers returns the joined members of a room.
func (c *Client) JoinedMembers(ctx context.Context, roomID id.RoomID) ([]id.UserID, error) {
var (
resp *mautrix.RespJoinedMembers
err error
)
for attempt := 0; ; attempt++ {
resp, err = c.mc.JoinedMembers(ctx, roomID)
if err == nil {
break
}
retry, herr := c.HandleRetry(ctx, "JoinedMembers", err, attempt, maxAPIRetries)
if herr != nil {
return nil, herr
}
if !retry {
return nil, err
}
}
ids := make([]id.UserID, 0, len(resp.Joined))
for userID := range resp.Joined {
ids = append(ids, userID)
}
return ids, nil
}
// Join joins a room by ID or alias, accepting a pending invitation if there is one.
func (c *Client) Join(ctx context.Context, roomIDOrAlias string) (id.RoomID, error) {
if c.defaultProvider != "" && strings.HasPrefix(roomIDOrAlias, "#") && !strings.Contains(roomIDOrAlias, ":") {
roomIDOrAlias += ":" + c.defaultProvider
}
var (
resp *mautrix.RespJoinRoom
err error
)
for attempt := 0; ; attempt++ {
resp, err = c.mc.JoinRoom(ctx, roomIDOrAlias, nil)
if err == nil {
break
}
retry, herr := c.HandleRetry(ctx, "Join", err, attempt, maxAPIRetries)
if herr != nil {
return "", herr
}
if !retry {
return "", err
}
}
c.persistAcceptedDirect(ctx, resp.RoomID)
return resp.RoomID, nil
}
// Send sends a text message, as a thread reply when parentID is set.
func (c *Client) Send(ctx context.Context, roomID id.RoomID, parentID id.EventID, text string) (id.EventID, error) {
content := newTextMessageContent(text)
if parentID != "" {
content.RelatesTo = &event.RelatesTo{Type: event.RelThread, EventID: parentID}
}
return c.sendMessage(ctx, roomID, &content)
}
// SendReply sends a native Matrix rich reply referencing replyToID, optionally inside threadRootID.
func (c *Client) SendReply(ctx context.Context, roomID id.RoomID, threadRootID, replyToID id.EventID, text string) (id.EventID, error) {
content := newTextMessageContent(text)
switch {
case replyToID != "":