-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
client.go
2402 lines (2166 loc) · 90.7 KB
/
client.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
// Package mautrix implements the Matrix Client-Server API.
//
// Specification can be found at https://spec.matrix.org/v1.2/client-server-api/
package mautrix
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"slices"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/rs/zerolog"
"go.mau.fi/util/ptr"
"go.mau.fi/util/retryafter"
"golang.org/x/exp/maps"
"maunium.net/go/mautrix/crypto/backup"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/pushrules"
)
type CryptoHelper interface {
Encrypt(context.Context, id.RoomID, event.Type, any) (*event.EncryptedEventContent, error)
Decrypt(context.Context, *event.Event) (*event.Event, error)
WaitForSession(context.Context, id.RoomID, id.SenderKey, id.SessionID, time.Duration) bool
RequestSession(context.Context, id.RoomID, id.SenderKey, id.SessionID, id.UserID, id.DeviceID)
Init(context.Context) error
}
type VerificationHelper interface {
// Init initializes the helper. This should be called before any other
// methods.
Init(context.Context) error
// StartVerification starts an interactive verification flow with the given
// user via a to-device event.
StartVerification(ctx context.Context, to id.UserID) (id.VerificationTransactionID, error)
// StartInRoomVerification starts an interactive verification flow with the
// given user in the given room.
StartInRoomVerification(ctx context.Context, roomID id.RoomID, to id.UserID) (id.VerificationTransactionID, error)
// AcceptVerification accepts a verification request.
AcceptVerification(ctx context.Context, txnID id.VerificationTransactionID) error
// DismissVerification dismisses a verification request. This will not send
// a cancellation to the other device. This method should only be called
// *before* the request has been accepted and will error otherwise.
DismissVerification(ctx context.Context, txnID id.VerificationTransactionID) error
// CancelVerification cancels a verification request. This method should
// only be called *after* the request has been accepted, although it will
// not error if called beforehand.
CancelVerification(ctx context.Context, txnID id.VerificationTransactionID, code event.VerificationCancelCode, reason string) error
// HandleScannedQRData handles the data from a QR code scan.
HandleScannedQRData(ctx context.Context, data []byte) error
// ConfirmQRCodeScanned confirms that our QR code has been scanned.
ConfirmQRCodeScanned(ctx context.Context, txnID id.VerificationTransactionID) error
// StartSAS starts a SAS verification flow.
StartSAS(ctx context.Context, txnID id.VerificationTransactionID) error
// ConfirmSAS indicates that the user has confirmed that the SAS matches
// SAS shown on the other user's device.
ConfirmSAS(ctx context.Context, txnID id.VerificationTransactionID) error
}
// Client represents a Matrix client.
type Client struct {
HomeserverURL *url.URL // The base homeserver URL
UserID id.UserID // The user ID of the client. Used for forming HTTP paths which use the client's user ID.
DeviceID id.DeviceID // The device ID of the client.
AccessToken string // The access_token for the client.
UserAgent string // The value for the User-Agent header
Client *http.Client // The underlying HTTP client which will be used to make HTTP requests.
Syncer Syncer // The thing which can process /sync responses
Store SyncStore // The thing which can store tokens/ids
StateStore StateStore
Crypto CryptoHelper
Verification VerificationHelper
SpecVersions *RespVersions
Log zerolog.Logger
RequestHook func(req *http.Request)
ResponseHook func(req *http.Request, resp *http.Response, err error, duration time.Duration)
UpdateRequestOnRetry func(req *http.Request, cause error) *http.Request
SyncPresence event.Presence
SyncTraceLog bool
StreamSyncMinAge time.Duration
// Number of times that mautrix will retry any HTTP request
// if the request fails entirely or returns a HTTP gateway error (502-504)
DefaultHTTPRetries int
// Amount of time to wait between HTTP retries, defaults to 4 seconds
DefaultHTTPBackoff time.Duration
// Set to true to disable automatically sleeping on 429 errors.
IgnoreRateLimit bool
txnID int32
// Should the ?user_id= query parameter be set in requests?
// See https://spec.matrix.org/v1.6/application-service-api/#identity-assertion
SetAppServiceUserID bool
// Should the org.matrix.msc3202.device_id query parameter be set in requests?
// See https://github.com/matrix-org/matrix-spec-proposals/pull/3202
SetAppServiceDeviceID bool
syncingID uint32 // Identifies the current Sync. Only one Sync can be active at any given time.
}
type ClientWellKnown struct {
Homeserver HomeserverInfo `json:"m.homeserver"`
IdentityServer IdentityServerInfo `json:"m.identity_server"`
}
type HomeserverInfo struct {
BaseURL string `json:"base_url"`
}
type IdentityServerInfo struct {
BaseURL string `json:"base_url"`
}
// DiscoverClientAPI resolves the client API URL from a Matrix server name.
// Use ParseUserID to extract the server name from a user ID.
// https://spec.matrix.org/v1.2/client-server-api/#server-discovery
func DiscoverClientAPI(ctx context.Context, serverName string) (*ClientWellKnown, error) {
wellKnownURL := url.URL{
Scheme: "https",
Host: serverName,
Path: "/.well-known/matrix/client",
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, wellKnownURL.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", DefaultUserAgent+" (.well-known fetcher)")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var wellKnown ClientWellKnown
err = json.Unmarshal(data, &wellKnown)
if err != nil {
return nil, errors.New(".well-known response not JSON")
}
return &wellKnown, nil
}
// SetCredentials sets the user ID and access token on this client instance.
//
// Deprecated: use the StoreCredentials field in ReqLogin instead.
func (cli *Client) SetCredentials(userID id.UserID, accessToken string) {
cli.AccessToken = accessToken
cli.UserID = userID
}
// ClearCredentials removes the user ID and access token on this client instance.
func (cli *Client) ClearCredentials() {
cli.AccessToken = ""
cli.UserID = ""
cli.DeviceID = ""
}
// Sync starts syncing with the provided Homeserver. If Sync() is called twice then the first sync will be stopped and the
// error will be nil.
//
// This function will block until a fatal /sync error occurs, so it should almost always be started as a new goroutine.
// Fatal sync errors can be caused by:
// - The failure to create a filter.
// - Client.Syncer.OnFailedSync returning an error in response to a failed sync.
// - Client.Syncer.ProcessResponse returning an error.
//
// If you wish to continue retrying in spite of these fatal errors, call Sync() again.
func (cli *Client) Sync() error {
return cli.SyncWithContext(context.Background())
}
func (cli *Client) SyncWithContext(ctx context.Context) error {
// Mark the client as syncing.
// We will keep syncing until the syncing state changes. Either because
// Sync is called or StopSync is called.
syncingID := cli.incrementSyncingID()
nextBatch, err := cli.Store.LoadNextBatch(ctx, cli.UserID)
if err != nil {
return err
}
filterID, err := cli.Store.LoadFilterID(ctx, cli.UserID)
if err != nil {
return err
}
if filterID == "" {
filterJSON := cli.Syncer.GetFilterJSON(cli.UserID)
resFilter, err := cli.CreateFilter(ctx, filterJSON)
if err != nil {
return err
}
filterID = resFilter.FilterID
if err := cli.Store.SaveFilterID(ctx, cli.UserID, filterID); err != nil {
return err
}
}
lastSuccessfulSync := time.Now().Add(-cli.StreamSyncMinAge - 1*time.Hour)
// Always do first sync with 0 timeout
isFailing := true
for {
streamResp := false
if cli.StreamSyncMinAge > 0 && time.Since(lastSuccessfulSync) > cli.StreamSyncMinAge {
cli.Log.Debug().Msg("Last sync is old, will stream next response")
streamResp = true
}
timeout := 30000
if isFailing || nextBatch == "" {
timeout = 0
}
resSync, err := cli.FullSyncRequest(ctx, ReqSync{
Timeout: timeout,
Since: nextBatch,
FilterID: filterID,
FullState: false,
SetPresence: cli.SyncPresence,
StreamResponse: streamResp,
})
if err != nil {
isFailing = true
if ctx.Err() != nil {
return ctx.Err()
}
duration, err2 := cli.Syncer.OnFailedSync(resSync, err)
if err2 != nil {
return err2
}
if duration <= 0 {
continue
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(duration):
continue
}
}
isFailing = false
lastSuccessfulSync = time.Now()
// Check that the syncing state hasn't changed
// Either because we've stopped syncing or another sync has been started.
// We discard the response from our sync.
if cli.getSyncingID() != syncingID {
return nil
}
// Save the token now *before* processing it. This means it's possible
// to not process some events, but it means that we won't get constantly stuck processing
// a malformed/buggy event which keeps making us panic.
err = cli.Store.SaveNextBatch(ctx, cli.UserID, resSync.NextBatch)
if err != nil {
return err
}
if err = cli.Syncer.ProcessResponse(ctx, resSync, nextBatch); err != nil {
return err
}
nextBatch = resSync.NextBatch
}
}
func (cli *Client) incrementSyncingID() uint32 {
return atomic.AddUint32(&cli.syncingID, 1)
}
func (cli *Client) getSyncingID() uint32 {
return atomic.LoadUint32(&cli.syncingID)
}
// StopSync stops the ongoing sync started by Sync.
func (cli *Client) StopSync() {
// Advance the syncing state so that any running Syncs will terminate.
cli.incrementSyncingID()
}
type contextKey int
const (
LogBodyContextKey contextKey = iota
LogRequestIDContextKey
)
func (cli *Client) RequestStart(req *http.Request) {
if cli.RequestHook != nil {
cli.RequestHook(req)
}
}
func (cli *Client) LogRequestDone(req *http.Request, resp *http.Response, err error, handlerErr error, contentLength int, duration time.Duration) {
var evt *zerolog.Event
if errors.Is(err, context.Canceled) {
evt = zerolog.Ctx(req.Context()).Warn()
} else if err != nil {
evt = zerolog.Ctx(req.Context()).Err(err)
} else if handlerErr != nil {
evt = zerolog.Ctx(req.Context()).Warn().
AnErr("body_parse_err", handlerErr)
} else if cli.SyncTraceLog && strings.HasSuffix(req.URL.Path, "/_matrix/client/v3/sync") {
evt = zerolog.Ctx(req.Context()).Trace()
} else {
evt = zerolog.Ctx(req.Context()).Debug()
}
evt = evt.
Str("method", req.Method).
Str("url", req.URL.String()).
Dur("duration", duration)
if cli.ResponseHook != nil {
cli.ResponseHook(req, resp, err, duration)
}
if resp != nil {
mime := resp.Header.Get("Content-Type")
length := resp.ContentLength
if length == -1 && contentLength > 0 {
length = int64(contentLength)
}
evt = evt.Int("status_code", resp.StatusCode).
Int64("response_length", length).
Str("response_mime", mime)
if serverRequestID := resp.Header.Get("X-Beeper-Request-ID"); serverRequestID != "" {
evt.Str("beeper_request_id", serverRequestID)
}
}
if body := req.Context().Value(LogBodyContextKey); body != nil {
evt.Interface("req_body", body)
}
if errors.Is(err, context.Canceled) {
evt.Msg("Request canceled")
} else if err != nil {
evt.Msg("Request failed")
} else if handlerErr != nil {
evt.Msg("Request parsing failed")
} else {
evt.Msg("Request completed")
}
}
func (cli *Client) MakeRequest(ctx context.Context, method string, httpURL string, reqBody any, resBody any) ([]byte, error) {
return cli.MakeFullRequest(ctx, FullRequest{Method: method, URL: httpURL, RequestJSON: reqBody, ResponseJSON: resBody})
}
type ClientResponseHandler = func(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error)
type FullRequest struct {
Method string
URL string
Headers http.Header
RequestJSON interface{}
RequestBytes []byte
RequestBody io.Reader
RequestLength int64
ResponseJSON interface{}
MaxAttempts int
BackoffDuration time.Duration
SensitiveContent bool
Handler ClientResponseHandler
DontReadResponse bool
Logger *zerolog.Logger
Client *http.Client
}
var requestID int32
var logSensitiveContent = os.Getenv("MAUTRIX_LOG_SENSITIVE_CONTENT") == "yes"
func (params *FullRequest) compileRequest(ctx context.Context) (*http.Request, error) {
var logBody any
reqBody := params.RequestBody
if params.RequestJSON != nil {
jsonStr, err := json.Marshal(params.RequestJSON)
if err != nil {
return nil, HTTPError{
Message: "failed to marshal JSON",
WrappedError: err,
}
}
if params.SensitiveContent && !logSensitiveContent {
logBody = "<sensitive content omitted>"
} else {
logBody = params.RequestJSON
}
reqBody = bytes.NewReader(jsonStr)
} else if params.RequestBytes != nil {
logBody = fmt.Sprintf("<%d bytes>", len(params.RequestBytes))
reqBody = bytes.NewReader(params.RequestBytes)
params.RequestLength = int64(len(params.RequestBytes))
} else if params.RequestLength > 0 && params.RequestBody != nil {
logBody = fmt.Sprintf("<%d bytes>", params.RequestLength)
if rsc, ok := params.RequestBody.(io.ReadSeekCloser); ok {
// Prevent HTTP from closing the request body, it might be needed for retries
reqBody = nopCloseSeeker{rsc}
}
} else if params.Method != http.MethodGet && params.Method != http.MethodHead {
params.RequestJSON = struct{}{}
logBody = params.RequestJSON
reqBody = bytes.NewReader([]byte("{}"))
}
reqID := atomic.AddInt32(&requestID, 1)
logger := zerolog.Ctx(ctx)
if logger.GetLevel() == zerolog.Disabled || logger == zerolog.DefaultContextLogger {
logger = params.Logger
}
ctx = logger.With().
Int32("req_id", reqID).
Logger().WithContext(ctx)
ctx = context.WithValue(ctx, LogBodyContextKey, logBody)
ctx = context.WithValue(ctx, LogRequestIDContextKey, int(reqID))
req, err := http.NewRequestWithContext(ctx, params.Method, params.URL, reqBody)
if err != nil {
return nil, HTTPError{
Message: "failed to create request",
WrappedError: err,
}
}
if params.Headers != nil {
req.Header = params.Headers
}
if params.RequestJSON != nil {
req.Header.Set("Content-Type", "application/json")
}
if params.RequestLength > 0 && params.RequestBody != nil {
req.ContentLength = params.RequestLength
}
return req, nil
}
func (cli *Client) MakeFullRequest(ctx context.Context, params FullRequest) ([]byte, error) {
data, _, err := cli.MakeFullRequestWithResp(ctx, params)
return data, err
}
func (cli *Client) MakeFullRequestWithResp(ctx context.Context, params FullRequest) ([]byte, *http.Response, error) {
if params.MaxAttempts == 0 {
params.MaxAttempts = 1 + cli.DefaultHTTPRetries
}
if params.BackoffDuration == 0 {
if cli.DefaultHTTPBackoff == 0 {
params.BackoffDuration = 4 * time.Second
} else {
params.BackoffDuration = cli.DefaultHTTPBackoff
}
}
if params.Logger == nil {
params.Logger = &cli.Log
}
req, err := params.compileRequest(ctx)
if err != nil {
return nil, nil, err
}
if params.Handler == nil {
if params.DontReadResponse {
params.Handler = noopHandleResponse
} else {
params.Handler = handleNormalResponse
}
}
req.Header.Set("User-Agent", cli.UserAgent)
if len(cli.AccessToken) > 0 {
req.Header.Set("Authorization", "Bearer "+cli.AccessToken)
}
if params.Client == nil {
params.Client = cli.Client
}
return cli.executeCompiledRequest(req, params.MaxAttempts-1, params.BackoffDuration, params.ResponseJSON, params.Handler, params.DontReadResponse, params.Client)
}
func (cli *Client) cliOrContextLog(ctx context.Context) *zerolog.Logger {
log := zerolog.Ctx(ctx)
if log.GetLevel() == zerolog.Disabled || log == zerolog.DefaultContextLogger {
return &cli.Log
}
return log
}
func (cli *Client) doRetry(req *http.Request, cause error, retries int, backoff time.Duration, responseJSON any, handler ClientResponseHandler, dontReadResponse bool, client *http.Client) ([]byte, *http.Response, error) {
log := zerolog.Ctx(req.Context())
if req.Body != nil {
var err error
if req.GetBody != nil {
req.Body, err = req.GetBody()
if err != nil {
log.Warn().Err(err).Msg("Failed to get new body to retry request")
return nil, nil, cause
}
} else if bodySeeker, ok := req.Body.(io.ReadSeeker); ok {
_, err = bodySeeker.Seek(0, io.SeekStart)
if err != nil {
log.Warn().Err(err).Msg("Failed to seek to beginning of request body")
return nil, nil, cause
}
} else {
log.Warn().Msg("Failed to get new body to retry request: GetBody is nil and Body is not an io.ReadSeeker")
return nil, nil, cause
}
}
log.Warn().Err(cause).
Int("retry_in_seconds", int(backoff.Seconds())).
Msg("Request failed, retrying")
time.Sleep(backoff)
if cli.UpdateRequestOnRetry != nil {
req = cli.UpdateRequestOnRetry(req, cause)
}
return cli.executeCompiledRequest(req, retries-1, backoff*2, responseJSON, handler, dontReadResponse, client)
}
func readResponseBody(req *http.Request, res *http.Response) ([]byte, error) {
contents, err := io.ReadAll(res.Body)
if err != nil {
return nil, HTTPError{
Request: req,
Response: res,
Message: "failed to read response body",
WrappedError: err,
}
}
return contents, nil
}
func closeTemp(log *zerolog.Logger, file *os.File) {
_ = file.Close()
err := os.Remove(file.Name())
if err != nil {
log.Warn().Err(err).Str("file_name", file.Name()).Msg("Failed to remove response temp file")
}
}
func streamResponse(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) {
log := zerolog.Ctx(req.Context())
file, err := os.CreateTemp("", "mautrix-response-")
if err != nil {
log.Warn().Err(err).Msg("Failed to create temporary file for streaming response")
_, err = handleNormalResponse(req, res, responseJSON)
return nil, err
}
defer closeTemp(log, file)
if _, err = io.Copy(file, res.Body); err != nil {
return nil, fmt.Errorf("failed to copy response to file: %w", err)
} else if _, err = file.Seek(0, 0); err != nil {
return nil, fmt.Errorf("failed to seek to beginning of response file: %w", err)
} else if err = json.NewDecoder(file).Decode(responseJSON); err != nil {
return nil, fmt.Errorf("failed to unmarshal response body: %w", err)
} else {
return nil, nil
}
}
func noopHandleResponse(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) {
return nil, nil
}
func handleNormalResponse(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) {
if contents, err := readResponseBody(req, res); err != nil {
return nil, err
} else if responseJSON == nil {
return contents, nil
} else if err = json.Unmarshal(contents, &responseJSON); err != nil {
return nil, HTTPError{
Request: req,
Response: res,
Message: "failed to unmarshal response body",
ResponseBody: string(contents),
WrappedError: err,
}
} else {
return contents, nil
}
}
func ParseErrorResponse(req *http.Request, res *http.Response) ([]byte, error) {
contents, err := readResponseBody(req, res)
if err != nil {
return contents, err
}
respErr := &RespError{
StatusCode: res.StatusCode,
}
if _ = json.Unmarshal(contents, respErr); respErr.ErrCode == "" {
respErr = nil
}
return contents, HTTPError{
Request: req,
Response: res,
RespError: respErr,
}
}
func (cli *Client) executeCompiledRequest(req *http.Request, retries int, backoff time.Duration, responseJSON any, handler ClientResponseHandler, dontReadResponse bool, client *http.Client) ([]byte, *http.Response, error) {
cli.RequestStart(req)
startTime := time.Now()
res, err := client.Do(req)
duration := time.Now().Sub(startTime)
if res != nil && !dontReadResponse {
defer res.Body.Close()
}
if err != nil {
if retries > 0 && !errors.Is(err, context.Canceled) {
return cli.doRetry(req, err, retries, backoff, responseJSON, handler, dontReadResponse, client)
}
err = HTTPError{
Request: req,
Response: res,
Message: "request error",
WrappedError: err,
}
cli.LogRequestDone(req, res, err, nil, 0, duration)
return nil, res, err
}
if retries > 0 && retryafter.Should(res.StatusCode, !cli.IgnoreRateLimit) {
backoff = retryafter.Parse(res.Header.Get("Retry-After"), backoff)
return cli.doRetry(req, fmt.Errorf("HTTP %d", res.StatusCode), retries, backoff, responseJSON, handler, dontReadResponse, client)
}
var body []byte
if res.StatusCode < 200 || res.StatusCode >= 300 {
body, err = ParseErrorResponse(req, res)
cli.LogRequestDone(req, res, nil, nil, len(body), duration)
} else {
body, err = handler(req, res, responseJSON)
cli.LogRequestDone(req, res, nil, err, len(body), duration)
}
return body, res, err
}
// Whoami gets the user ID of the current user. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3accountwhoami
func (cli *Client) Whoami(ctx context.Context) (resp *RespWhoami, err error) {
urlPath := cli.BuildClientURL("v3", "account", "whoami")
_, err = cli.MakeRequest(ctx, http.MethodGet, urlPath, nil, &resp)
return
}
// CreateFilter makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3useruseridfilter
func (cli *Client) CreateFilter(ctx context.Context, filter *Filter) (resp *RespCreateFilter, err error) {
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "filter")
_, err = cli.MakeRequest(ctx, http.MethodPost, urlPath, filter, &resp)
return
}
// SyncRequest makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3sync
func (cli *Client) SyncRequest(ctx context.Context, timeout int, since, filterID string, fullState bool, setPresence event.Presence) (resp *RespSync, err error) {
return cli.FullSyncRequest(ctx, ReqSync{
Timeout: timeout,
Since: since,
FilterID: filterID,
FullState: fullState,
SetPresence: setPresence,
})
}
type ReqSync struct {
Timeout int
Since string
FilterID string
FullState bool
SetPresence event.Presence
StreamResponse bool
BeeperStreaming bool
Client *http.Client
}
func (req *ReqSync) BuildQuery() map[string]string {
query := map[string]string{
"timeout": strconv.Itoa(req.Timeout),
}
if req.Since != "" {
query["since"] = req.Since
}
if req.FilterID != "" {
query["filter"] = req.FilterID
}
if req.SetPresence != "" {
query["set_presence"] = string(req.SetPresence)
}
if req.FullState {
query["full_state"] = "true"
}
if req.BeeperStreaming {
// TODO remove this
query["streaming"] = ""
query["com.beeper.streaming"] = "true"
}
return query
}
// FullSyncRequest makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3sync
func (cli *Client) FullSyncRequest(ctx context.Context, req ReqSync) (resp *RespSync, err error) {
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "sync"}, req.BuildQuery())
fullReq := FullRequest{
Method: http.MethodGet,
URL: urlPath,
ResponseJSON: &resp,
Client: req.Client,
// We don't want automatic retries for SyncRequest, the Sync() wrapper handles those.
MaxAttempts: 1,
}
if req.StreamResponse {
fullReq.Handler = streamResponse
}
start := time.Now()
_, err = cli.MakeFullRequest(ctx, fullReq)
duration := time.Now().Sub(start)
timeout := time.Duration(req.Timeout) * time.Millisecond
buffer := 10 * time.Second
if req.Since == "" {
buffer = 1 * time.Minute
}
if err == nil && duration > timeout+buffer {
cli.cliOrContextLog(ctx).Warn().
Str("since", req.Since).
Dur("duration", duration).
Dur("timeout", timeout).
Msg("Sync request took unusually long")
}
return
}
// RegisterAvailable checks if a username is valid and available for registration on the server.
//
// See https://spec.matrix.org/v1.4/client-server-api/#get_matrixclientv3registeravailable for more details
//
// This will always return an error if the username isn't available, so checking the actual response struct is generally
// not necessary. It is still returned for future-proofing. For a simple availability check, just check that the returned
// error is nil. `errors.Is` can be used to find the exact reason why a username isn't available:
//
// _, err := cli.RegisterAvailable("cat")
// if errors.Is(err, mautrix.MUserInUse) {
// // Username is taken
// } else if errors.Is(err, mautrix.MInvalidUsername) {
// // Username is not valid
// } else if errors.Is(err, mautrix.MExclusive) {
// // Username is reserved for an appservice
// } else if errors.Is(err, mautrix.MLimitExceeded) {
// // Too many requests
// } else if err != nil {
// // Unknown error
// } else {
// // Username is available
// }
func (cli *Client) RegisterAvailable(ctx context.Context, username string) (resp *RespRegisterAvailable, err error) {
u := cli.BuildURLWithQuery(ClientURLPath{"v3", "register", "available"}, map[string]string{"username": username})
_, err = cli.MakeRequest(ctx, http.MethodGet, u, nil, &resp)
if err == nil && !resp.Available {
err = fmt.Errorf(`request returned OK status without "available": true`)
}
return
}
func (cli *Client) register(ctx context.Context, url string, req *ReqRegister) (resp *RespRegister, uiaResp *RespUserInteractive, err error) {
var bodyBytes []byte
bodyBytes, err = cli.MakeFullRequest(ctx, FullRequest{
Method: http.MethodPost,
URL: url,
RequestJSON: req,
SensitiveContent: len(req.Password) > 0,
})
if err != nil {
httpErr, ok := err.(HTTPError)
// if response has a 401 status, but doesn't have the errcode field, it's probably a UIA response.
if ok && httpErr.IsStatus(http.StatusUnauthorized) && httpErr.RespError == nil {
err = json.Unmarshal(bodyBytes, &uiaResp)
}
} else {
// body should be RespRegister
err = json.Unmarshal(bodyBytes, &resp)
}
return
}
// Register makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3register
//
// Registers with kind=user. For kind=guest, see RegisterGuest.
func (cli *Client) Register(ctx context.Context, req *ReqRegister) (*RespRegister, *RespUserInteractive, error) {
u := cli.BuildClientURL("v3", "register")
return cli.register(ctx, u, req)
}
// RegisterGuest makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3register
// with kind=guest.
//
// For kind=user, see Register.
func (cli *Client) RegisterGuest(ctx context.Context, req *ReqRegister) (*RespRegister, *RespUserInteractive, error) {
query := map[string]string{
"kind": "guest",
}
u := cli.BuildURLWithQuery(ClientURLPath{"v3", "register"}, query)
return cli.register(ctx, u, req)
}
// RegisterDummy performs m.login.dummy registration according to https://spec.matrix.org/v1.2/client-server-api/#dummy-auth
//
// Only a username and password need to be provided on the ReqRegister struct. Most local/developer homeservers will allow registration
// this way. If the homeserver does not, an error is returned.
//
// This does not set credentials on the client instance. See SetCredentials() instead.
//
// res, err := cli.RegisterDummy(&mautrix.ReqRegister{
// Username: "alice",
// Password: "wonderland",
// })
// if err != nil {
// panic(err)
// }
// token := res.AccessToken
func (cli *Client) RegisterDummy(ctx context.Context, req *ReqRegister) (*RespRegister, error) {
res, uia, err := cli.Register(ctx, req)
if err != nil && uia == nil {
return nil, err
} else if uia == nil {
return nil, errors.New("server did not return user-interactive auth flows")
} else if !uia.HasSingleStageFlow(AuthTypeDummy) {
return nil, errors.New("server does not support m.login.dummy")
}
req.Auth = BaseAuthData{Type: AuthTypeDummy, Session: uia.Session}
res, _, err = cli.Register(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// GetLoginFlows fetches the login flows that the homeserver supports using https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3login
func (cli *Client) GetLoginFlows(ctx context.Context) (resp *RespLoginFlows, err error) {
urlPath := cli.BuildClientURL("v3", "login")
_, err = cli.MakeRequest(ctx, http.MethodGet, urlPath, nil, &resp)
return
}
// Login a user to the homeserver according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3login
func (cli *Client) Login(ctx context.Context, req *ReqLogin) (resp *RespLogin, err error) {
_, err = cli.MakeFullRequest(ctx, FullRequest{
Method: http.MethodPost,
URL: cli.BuildClientURL("v3", "login"),
RequestJSON: req,
ResponseJSON: &resp,
SensitiveContent: len(req.Password) > 0 || len(req.Token) > 0,
})
if req.StoreCredentials && err == nil {
cli.DeviceID = resp.DeviceID
cli.AccessToken = resp.AccessToken
cli.UserID = resp.UserID
cli.Log.Debug().
Str("user_id", cli.UserID.String()).
Str("device_id", cli.DeviceID.String()).
Msg("Stored credentials after login")
}
if req.StoreHomeserverURL && err == nil && resp.WellKnown != nil && len(resp.WellKnown.Homeserver.BaseURL) > 0 {
var urlErr error
cli.HomeserverURL, urlErr = url.Parse(resp.WellKnown.Homeserver.BaseURL)
if urlErr != nil {
cli.Log.Warn().
Err(urlErr).
Str("homeserver_url", resp.WellKnown.Homeserver.BaseURL).
Msg("Failed to parse homeserver URL in login response")
} else {
cli.Log.Debug().
Str("homeserver_url", cli.HomeserverURL.String()).
Msg("Updated homeserver URL after login")
}
}
return
}
// Logout the current user. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3logout
// This does not clear the credentials from the client instance. See ClearCredentials() instead.
func (cli *Client) Logout(ctx context.Context) (resp *RespLogout, err error) {
urlPath := cli.BuildClientURL("v3", "logout")
_, err = cli.MakeRequest(ctx, http.MethodPost, urlPath, nil, &resp)
return
}
// LogoutAll logs out all the devices of the current user. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3logoutall
// This does not clear the credentials from the client instance. See ClearCredentials() instead.
func (cli *Client) LogoutAll(ctx context.Context) (resp *RespLogout, err error) {
urlPath := cli.BuildClientURL("v3", "logout", "all")
_, err = cli.MakeRequest(ctx, http.MethodPost, urlPath, nil, &resp)
return
}
// Versions returns the list of supported Matrix versions on this homeserver. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientversions
func (cli *Client) Versions(ctx context.Context) (resp *RespVersions, err error) {
urlPath := cli.BuildClientURL("versions")
_, err = cli.MakeRequest(ctx, http.MethodGet, urlPath, nil, &resp)
if resp != nil {
cli.SpecVersions = resp
}
return
}
// Capabilities returns capabilities on this homeserver. See https://spec.matrix.org/v1.3/client-server-api/#capabilities-negotiation
func (cli *Client) Capabilities(ctx context.Context) (resp *RespCapabilities, err error) {
urlPath := cli.BuildClientURL("v3", "capabilities")
_, err = cli.MakeRequest(ctx, http.MethodGet, urlPath, nil, &resp)
return
}
// JoinRoom joins the client to a room ID or alias. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3joinroomidoralias
//
// If serverName is specified, this will be added as a query param to instruct the homeserver to join via that server. If content is specified, it will
// be JSON encoded and used as the request body.
func (cli *Client) JoinRoom(ctx context.Context, roomIDorAlias, serverName string, content interface{}) (resp *RespJoinRoom, err error) {
var urlPath string
if serverName != "" {
urlPath = cli.BuildURLWithQuery(ClientURLPath{"v3", "join", roomIDorAlias}, map[string]string{
"via": serverName,
})
} else {
urlPath = cli.BuildClientURL("v3", "join", roomIDorAlias)
}
_, err = cli.MakeRequest(ctx, http.MethodPost, urlPath, content, &resp)
if err == nil && cli.StateStore != nil {
err = cli.StateStore.SetMembership(ctx, resp.RoomID, cli.UserID, event.MembershipJoin)
if err != nil {
err = fmt.Errorf("failed to update state store: %w", err)
}
}
return
}
// JoinRoomByID joins the client to a room ID. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidjoin
//
// Unlike JoinRoom, this method can only be used to join rooms that the server already knows about.
// It's mostly intended for bridges and other things where it's already certain that the server is in the room.
func (cli *Client) JoinRoomByID(ctx context.Context, roomID id.RoomID) (resp *RespJoinRoom, err error) {
_, err = cli.MakeRequest(ctx, http.MethodPost, cli.BuildClientURL("v3", "rooms", roomID, "join"), nil, &resp)
if err == nil && cli.StateStore != nil {
err = cli.StateStore.SetMembership(ctx, resp.RoomID, cli.UserID, event.MembershipJoin)
if err != nil {
err = fmt.Errorf("failed to update state store: %w", err)
}
}
return
}
func (cli *Client) GetProfile(ctx context.Context, mxid id.UserID) (resp *RespUserProfile, err error) {
urlPath := cli.BuildClientURL("v3", "profile", mxid)
_, err = cli.MakeRequest(ctx, http.MethodGet, urlPath, nil, &resp)
return
}
// GetDisplayName returns the display name of the user with the specified MXID. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3profileuseriddisplayname
func (cli *Client) GetDisplayName(ctx context.Context, mxid id.UserID) (resp *RespUserDisplayName, err error) {
urlPath := cli.BuildClientURL("v3", "profile", mxid, "displayname")
_, err = cli.MakeRequest(ctx, http.MethodGet, urlPath, nil, &resp)
return
}
// GetOwnDisplayName returns the user's display name. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3profileuseriddisplayname
func (cli *Client) GetOwnDisplayName(ctx context.Context) (resp *RespUserDisplayName, err error) {
return cli.GetDisplayName(ctx, cli.UserID)
}
// SetDisplayName sets the user's profile display name. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3profileuseriddisplayname
func (cli *Client) SetDisplayName(ctx context.Context, displayName string) (err error) {
urlPath := cli.BuildClientURL("v3", "profile", cli.UserID, "displayname")
s := struct {
DisplayName string `json:"displayname"`
}{displayName}
_, err = cli.MakeRequest(ctx, http.MethodPut, urlPath, &s, nil)
return