| 1 |
// Package mautrix implements the Matrix Client-Server API. |
| 2 |
// |
| 3 |
// Specification can be found at https://spec.matrix.org/v1.2/client-server-api/ |
| 4 |
package mautrix |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"context" |
| 9 |
"encoding/json" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"io/ioutil" |
| 14 |
"net/http" |
| 15 |
"net/url" |
| 16 |
"os" |
| 17 |
"strconv" |
| 18 |
"sync/atomic" |
| 19 |
"time" |
| 20 |
|
| 21 |
"maunium.net/go/mautrix/event" |
| 22 |
"maunium.net/go/mautrix/id" |
| 23 |
"maunium.net/go/mautrix/pushrules" |
| 24 |
) |
| 25 |
|
| 26 |
type Logger interface { |
| 27 |
Debugfln(message string, args ...interface{}) |
| 28 |
} |
| 29 |
|
| 30 |
// StubLogger is an implementation of Logger that does nothing |
| 31 |
type StubLogger struct{} |
| 32 |
|
| 33 |
func (sl *StubLogger) Debugfln(message string, args ...interface{}) {} |
| 34 |
func (sl *StubLogger) Warnfln(message string, args ...interface{}) {} |
| 35 |
|
| 36 |
var stubLogger = &StubLogger{} |
| 37 |
|
| 38 |
type WarnLogger interface { |
| 39 |
Logger |
| 40 |
Warnfln(message string, args ...interface{}) |
| 41 |
} |
| 42 |
|
| 43 |
type Stringifiable interface { |
| 44 |
String() string |
| 45 |
} |
| 46 |
|
| 47 |
// Client represents a Matrix client. |
| 48 |
type Client struct { |
| 49 |
HomeserverURL *url.URL // The base homeserver URL |
| 50 |
UserID id.UserID // The user ID of the client. Used for forming HTTP paths which use the client's user ID. |
| 51 |
DeviceID id.DeviceID // The device ID of the client. |
| 52 |
AccessToken string // The access_token for the client. |
| 53 |
UserAgent string // The value for the User-Agent header |
| 54 |
Client *http.Client // The underlying HTTP client which will be used to make HTTP requests. |
| 55 |
Syncer Syncer // The thing which can process /sync responses |
| 56 |
Store Storer // The thing which can store rooms/tokens/ids |
| 57 |
Logger Logger |
| 58 |
SyncPresence event.Presence |
| 59 |
|
| 60 |
StreamSyncMinAge time.Duration |
| 61 |
|
| 62 |
// Number of times that mautrix will retry any HTTP request |
| 63 |
// if the request fails entirely or returns a HTTP gateway error (502-504) |
| 64 |
DefaultHTTPRetries int |
| 65 |
// Set to true to disable automatically sleeping on 429 errors. |
| 66 |
IgnoreRateLimit bool |
| 67 |
|
| 68 |
txnID int32 |
| 69 |
|
| 70 |
// The ?user_id= query parameter for application services. This must be set *prior* to calling a method. |
| 71 |
// If this is empty, no user_id parameter will be sent. |
| 72 |
// See https://spec.matrix.org/v1.2/application-service-api/#identity-assertion |
| 73 |
AppServiceUserID id.UserID |
| 74 |
|
| 75 |
syncingID uint32 // Identifies the current Sync. Only one Sync can be active at any given time. |
| 76 |
} |
| 77 |
|
| 78 |
type ClientWellKnown struct { |
| 79 |
Homeserver HomeserverInfo `json:"m.homeserver"` |
| 80 |
IdentityServer IdentityServerInfo `json:"m.identity_server"` |
| 81 |
} |
| 82 |
|
| 83 |
type HomeserverInfo struct { |
| 84 |
BaseURL string `json:"base_url"` |
| 85 |
} |
| 86 |
|
| 87 |
type IdentityServerInfo struct { |
| 88 |
BaseURL string `json:"base_url"` |
| 89 |
} |
| 90 |
|
| 91 |
// DiscoverClientAPI resolves the client API URL from a Matrix server name. |
| 92 |
// Use ParseUserID to extract the server name from a user ID. |
| 93 |
// https://spec.matrix.org/v1.2/client-server-api/#server-discovery |
| 94 |
func DiscoverClientAPI(serverName string) (*ClientWellKnown, error) { |
| 95 |
wellKnownURL := url.URL{ |
| 96 |
Scheme: "https", |
| 97 |
Host: serverName, |
| 98 |
Path: "/.well-known/matrix/client", |
| 99 |
} |
| 100 |
|
| 101 |
req, err := http.NewRequest("GET", wellKnownURL.String(), nil) |
| 102 |
if err != nil { |
| 103 |
return nil, err |
| 104 |
} |
| 105 |
|
| 106 |
req.Header.Set("Accept", "application/json") |
| 107 |
req.Header.Set("User-Agent", DefaultUserAgent+" .well-known fetcher") |
| 108 |
|
| 109 |
client := &http.Client{Timeout: 30 * time.Second} |
| 110 |
resp, err := client.Do(req) |
| 111 |
if err != nil { |
| 112 |
return nil, err |
| 113 |
} |
| 114 |
defer resp.Body.Close() |
| 115 |
|
| 116 |
if resp.StatusCode == http.StatusNotFound { |
| 117 |
return nil, nil |
| 118 |
} |
| 119 |
|
| 120 |
data, err := ioutil.ReadAll(resp.Body) |
| 121 |
if err != nil { |
| 122 |
return nil, err |
| 123 |
} |
| 124 |
|
| 125 |
var wellKnown ClientWellKnown |
| 126 |
err = json.Unmarshal(data, &wellKnown) |
| 127 |
if err != nil { |
| 128 |
return nil, errors.New(".well-known response not JSON") |
| 129 |
} |
| 130 |
|
| 131 |
return &wellKnown, nil |
| 132 |
} |
| 133 |
|
| 134 |
// SetCredentials sets the user ID and access token on this client instance. |
| 135 |
// |
| 136 |
// Deprecated: use the StoreCredentials field in ReqLogin instead. |
| 137 |
func (cli *Client) SetCredentials(userID id.UserID, accessToken string) { |
| 138 |
cli.AccessToken = accessToken |
| 139 |
cli.UserID = userID |
| 140 |
} |
| 141 |
|
| 142 |
// ClearCredentials removes the user ID and access token on this client instance. |
| 143 |
func (cli *Client) ClearCredentials() { |
| 144 |
cli.AccessToken = "" |
| 145 |
cli.UserID = "" |
| 146 |
cli.DeviceID = "" |
| 147 |
} |
| 148 |
|
| 149 |
// Sync starts syncing with the provided Homeserver. If Sync() is called twice then the first sync will be stopped and the |
| 150 |
// error will be nil. |
| 151 |
// |
| 152 |
// This function will block until a fatal /sync error occurs, so it should almost always be started as a new goroutine. |
| 153 |
// Fatal sync errors can be caused by: |
| 154 |
// - The failure to create a filter. |
| 155 |
// - Client.Syncer.OnFailedSync returning an error in response to a failed sync. |
| 156 |
// - Client.Syncer.ProcessResponse returning an error. |
| 157 |
// If you wish to continue retrying in spite of these fatal errors, call Sync() again. |
| 158 |
func (cli *Client) Sync() error { |
| 159 |
return cli.SyncWithContext(context.Background()) |
| 160 |
} |
| 161 |
|
| 162 |
func (cli *Client) SyncWithContext(ctx context.Context) error { |
| 163 |
// Mark the client as syncing. |
| 164 |
// We will keep syncing until the syncing state changes. Either because |
| 165 |
// Sync is called or StopSync is called. |
| 166 |
syncingID := cli.incrementSyncingID() |
| 167 |
nextBatch := cli.Store.LoadNextBatch(cli.UserID) |
| 168 |
filterID := cli.Store.LoadFilterID(cli.UserID) |
| 169 |
if filterID == "" { |
| 170 |
filterJSON := cli.Syncer.GetFilterJSON(cli.UserID) |
| 171 |
resFilter, err := cli.CreateFilter(filterJSON) |
| 172 |
if err != nil { |
| 173 |
return err |
| 174 |
} |
| 175 |
filterID = resFilter.FilterID |
| 176 |
cli.Store.SaveFilterID(cli.UserID, filterID) |
| 177 |
} |
| 178 |
lastSuccessfulSync := time.Now().Add(-cli.StreamSyncMinAge - 1*time.Hour) |
| 179 |
for { |
| 180 |
streamResp := false |
| 181 |
if cli.StreamSyncMinAge > 0 && time.Since(lastSuccessfulSync) > cli.StreamSyncMinAge { |
| 182 |
cli.Logger.Debugfln("Last sync is old, will stream next response") |
| 183 |
streamResp = true |
| 184 |
} |
| 185 |
resSync, err := cli.FullSyncRequest(ReqSync{ |
| 186 |
Timeout: 30000, |
| 187 |
Since: nextBatch, |
| 188 |
FilterID: filterID, |
| 189 |
FullState: false, |
| 190 |
SetPresence: cli.SyncPresence, |
| 191 |
Context: ctx, |
| 192 |
StreamResponse: streamResp, |
| 193 |
}) |
| 194 |
if err != nil { |
| 195 |
if ctx.Err() != nil { |
| 196 |
return ctx.Err() |
| 197 |
} |
| 198 |
duration, err2 := cli.Syncer.OnFailedSync(resSync, err) |
| 199 |
if err2 != nil { |
| 200 |
return err2 |
| 201 |
} |
| 202 |
time.Sleep(duration) |
| 203 |
continue |
| 204 |
} |
| 205 |
lastSuccessfulSync = time.Now() |
| 206 |
|
| 207 |
// Check that the syncing state hasn't changed |
| 208 |
// Either because we've stopped syncing or another sync has been started. |
| 209 |
// We discard the response from our sync. |
| 210 |
if cli.getSyncingID() != syncingID { |
| 211 |
return nil |
| 212 |
} |
| 213 |
|
| 214 |
// Save the token now *before* processing it. This means it's possible |
| 215 |
// to not process some events, but it means that we won't get constantly stuck processing |
| 216 |
// a malformed/buggy event which keeps making us panic. |
| 217 |
cli.Store.SaveNextBatch(cli.UserID, resSync.NextBatch) |
| 218 |
if err = cli.Syncer.ProcessResponse(resSync, nextBatch); err != nil { |
| 219 |
return err |
| 220 |
} |
| 221 |
|
| 222 |
nextBatch = resSync.NextBatch |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
func (cli *Client) incrementSyncingID() uint32 { |
| 227 |
return atomic.AddUint32(&cli.syncingID, 1) |
| 228 |
} |
| 229 |
|
| 230 |
func (cli *Client) getSyncingID() uint32 { |
| 231 |
return atomic.LoadUint32(&cli.syncingID) |
| 232 |
} |
| 233 |
|
| 234 |
// StopSync stops the ongoing sync started by Sync. |
| 235 |
func (cli *Client) StopSync() { |
| 236 |
// Advance the syncing state so that any running Syncs will terminate. |
| 237 |
cli.incrementSyncingID() |
| 238 |
} |
| 239 |
|
| 240 |
const logBodyContextKey = "fi.mau.mautrix.log_body" |
| 241 |
const logRequestIDContextKey = "fi.mau.mautrix.request_id" |
| 242 |
|
| 243 |
func (cli *Client) LogRequest(req *http.Request) { |
| 244 |
if cli.Logger == stubLogger { |
| 245 |
return |
| 246 |
} |
| 247 |
body, ok := req.Context().Value(logBodyContextKey).(string) |
| 248 |
reqID, _ := req.Context().Value(logRequestIDContextKey).(int) |
| 249 |
if ok && len(body) > 0 { |
| 250 |
cli.Logger.Debugfln("req #%d: %s %s %s", reqID, req.Method, req.URL.String(), body) |
| 251 |
} else { |
| 252 |
cli.Logger.Debugfln("req #%d: %s %s", reqID, req.Method, req.URL.String()) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
func (cli *Client) MakeRequest(method string, httpURL string, reqBody interface{}, resBody interface{}) ([]byte, error) { |
| 257 |
return cli.MakeFullRequest(FullRequest{Method: method, URL: httpURL, RequestJSON: reqBody, ResponseJSON: resBody}) |
| 258 |
} |
| 259 |
|
| 260 |
type ClientResponseHandler = func(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) |
| 261 |
|
| 262 |
type FullRequest struct { |
| 263 |
Method string |
| 264 |
URL string |
| 265 |
Headers http.Header |
| 266 |
RequestJSON interface{} |
| 267 |
RequestBytes []byte |
| 268 |
RequestBody io.Reader |
| 269 |
RequestLength int64 |
| 270 |
ResponseJSON interface{} |
| 271 |
Context context.Context |
| 272 |
MaxAttempts int |
| 273 |
SensitiveContent bool |
| 274 |
Handler ClientResponseHandler |
| 275 |
} |
| 276 |
|
| 277 |
var requestID int32 |
| 278 |
var logSensitiveContent = os.Getenv("MAUTRIX_LOG_SENSITIVE_CONTENT") == "yes" |
| 279 |
|
| 280 |
func (params *FullRequest) compileRequest() (*http.Request, error) { |
| 281 |
var logBody string |
| 282 |
reqBody := params.RequestBody |
| 283 |
if params.Context == nil { |
| 284 |
params.Context = context.Background() |
| 285 |
} |
| 286 |
if params.RequestJSON != nil { |
| 287 |
jsonStr, err := json.Marshal(params.RequestJSON) |
| 288 |
if err != nil { |
| 289 |
return nil, HTTPError{ |
| 290 |
Message: "failed to marshal JSON", |
| 291 |
WrappedError: err, |
| 292 |
} |
| 293 |
} |
| 294 |
if params.SensitiveContent && !logSensitiveContent { |
| 295 |
logBody = "<sensitive content omitted>" |
| 296 |
} else { |
| 297 |
logBody = string(jsonStr) |
| 298 |
} |
| 299 |
reqBody = bytes.NewReader(jsonStr) |
| 300 |
} else if params.RequestBytes != nil { |
| 301 |
logBody = fmt.Sprintf("<%d bytes>", len(params.RequestBytes)) |
| 302 |
reqBody = bytes.NewReader(params.RequestBytes) |
| 303 |
params.RequestLength = int64(len(params.RequestBytes)) |
| 304 |
} else if params.RequestLength > 0 && params.RequestBody != nil { |
| 305 |
logBody = fmt.Sprintf("<%d bytes>", params.RequestLength) |
| 306 |
} |
| 307 |
ctx := context.WithValue(params.Context, logBodyContextKey, logBody) |
| 308 |
reqID := atomic.AddInt32(&requestID, 1) |
| 309 |
ctx = context.WithValue(ctx, logRequestIDContextKey, int(reqID)) |
| 310 |
req, err := http.NewRequestWithContext(ctx, params.Method, params.URL, reqBody) |
| 311 |
if err != nil { |
| 312 |
return nil, HTTPError{ |
| 313 |
Message: "failed to create request", |
| 314 |
WrappedError: err, |
| 315 |
} |
| 316 |
} |
| 317 |
if params.Headers != nil { |
| 318 |
req.Header = params.Headers |
| 319 |
} |
| 320 |
if params.RequestJSON != nil { |
| 321 |
req.Header.Set("Content-Type", "application/json") |
| 322 |
} |
| 323 |
if params.RequestLength > 0 && params.RequestBody != nil { |
| 324 |
req.ContentLength = params.RequestLength |
| 325 |
} |
| 326 |
return req, nil |
| 327 |
} |
| 328 |
|
| 329 |
// MakeFullRequest makes a JSON HTTP request to the given URL. |
| 330 |
// If "resBody" is not nil, the response body will be json.Unmarshalled into it. |
| 331 |
// |
| 332 |
// Returns the HTTP body as bytes on 2xx with a nil error. Returns an error if the response is not 2xx along |
| 333 |
// with the HTTP body bytes if it got that far. This error is an HTTPError which includes the returned |
| 334 |
// HTTP status code and possibly a RespError as the WrappedError, if the HTTP body could be decoded as a RespError. |
| 335 |
func (cli *Client) MakeFullRequest(params FullRequest) ([]byte, error) { |
| 336 |
if params.MaxAttempts == 0 { |
| 337 |
params.MaxAttempts = 1 + cli.DefaultHTTPRetries |
| 338 |
} |
| 339 |
req, err := params.compileRequest() |
| 340 |
if err != nil { |
| 341 |
return nil, err |
| 342 |
} |
| 343 |
if params.Handler == nil { |
| 344 |
params.Handler = cli.handleNormalResponse |
| 345 |
} |
| 346 |
req.Header.Set("User-Agent", cli.UserAgent) |
| 347 |
if len(cli.AccessToken) > 0 { |
| 348 |
req.Header.Set("Authorization", "Bearer "+cli.AccessToken) |
| 349 |
} |
| 350 |
return cli.executeCompiledRequest(req, params.MaxAttempts-1, 4*time.Second, params.ResponseJSON, params.Handler) |
| 351 |
} |
| 352 |
|
| 353 |
func (cli *Client) logWarning(format string, args ...interface{}) { |
| 354 |
warnLogger, ok := cli.Logger.(WarnLogger) |
| 355 |
if ok { |
| 356 |
warnLogger.Warnfln(format, args...) |
| 357 |
} else { |
| 358 |
cli.Logger.Debugfln(format, args...) |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
func (cli *Client) doRetry(req *http.Request, cause error, retries int, backoff time.Duration, responseJSON interface{}, handler ClientResponseHandler) ([]byte, error) { |
| 363 |
reqID, _ := req.Context().Value(logRequestIDContextKey).(int) |
| 364 |
if req.Body != nil { |
| 365 |
if req.GetBody == nil { |
| 366 |
cli.logWarning("Failed to get new body to retry request #%d: GetBody is nil", reqID) |
| 367 |
return nil, cause |
| 368 |
} |
| 369 |
var err error |
| 370 |
req.Body, err = req.GetBody() |
| 371 |
if err != nil { |
| 372 |
cli.logWarning("Failed to get new body to retry request #%d: %v", reqID, err) |
| 373 |
return nil, cause |
| 374 |
} |
| 375 |
} |
| 376 |
cli.logWarning("Request #%d failed: %v, retrying in %d seconds", reqID, cause, int(backoff.Seconds())) |
| 377 |
time.Sleep(backoff) |
| 378 |
return cli.executeCompiledRequest(req, retries-1, backoff*2, responseJSON, handler) |
| 379 |
} |
| 380 |
|
| 381 |
func (cli *Client) readRequestBody(req *http.Request, res *http.Response) ([]byte, error) { |
| 382 |
contents, err := ioutil.ReadAll(res.Body) |
| 383 |
if err != nil { |
| 384 |
return nil, HTTPError{ |
| 385 |
Request: req, |
| 386 |
Response: res, |
| 387 |
|
| 388 |
Message: "failed to read response body", |
| 389 |
WrappedError: err, |
| 390 |
} |
| 391 |
} |
| 392 |
return contents, nil |
| 393 |
} |
| 394 |
|
| 395 |
func (cli *Client) closeTemp(file *os.File) { |
| 396 |
_ = file.Close() |
| 397 |
err := os.Remove(file.Name()) |
| 398 |
if err != nil { |
| 399 |
cli.logWarning("Failed to remove temp file %s: %v", file.Name(), err) |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
func (cli *Client) streamResponse(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) { |
| 404 |
file, err := ioutil.TempFile("", "mautrix-response-") |
| 405 |
if err != nil { |
| 406 |
cli.logWarning("Failed to create temporary file: %v", err) |
| 407 |
_, err = cli.handleNormalResponse(req, res, responseJSON) |
| 408 |
return nil, err |
| 409 |
} |
| 410 |
defer cli.closeTemp(file) |
| 411 |
if _, err = io.Copy(file, res.Body); err != nil { |
| 412 |
return nil, fmt.Errorf("failed to copy response to file: %w", err) |
| 413 |
} else if _, err = file.Seek(0, 0); err != nil { |
| 414 |
return nil, fmt.Errorf("failed to seek to beginning of response file: %w", err) |
| 415 |
} else if err = json.NewDecoder(file).Decode(responseJSON); err != nil { |
| 416 |
return nil, fmt.Errorf("failed to unmarshal response body: %w", err) |
| 417 |
} else { |
| 418 |
return nil, nil |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
func (cli *Client) handleNormalResponse(req *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) { |
| 423 |
if contents, err := cli.readRequestBody(req, res); err != nil { |
| 424 |
return nil, err |
| 425 |
} else if responseJSON == nil { |
| 426 |
return contents, nil |
| 427 |
} else if err = json.Unmarshal(contents, &responseJSON); err != nil { |
| 428 |
return nil, HTTPError{ |
| 429 |
Request: req, |
| 430 |
Response: res, |
| 431 |
|
| 432 |
Message: "failed to unmarshal response body", |
| 433 |
ResponseBody: string(contents), |
| 434 |
WrappedError: err, |
| 435 |
} |
| 436 |
} else { |
| 437 |
return contents, nil |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
func (cli *Client) handleResponseError(req *http.Request, res *http.Response) ([]byte, error) { |
| 442 |
contents, err := cli.readRequestBody(req, res) |
| 443 |
if err != nil { |
| 444 |
return contents, err |
| 445 |
} |
| 446 |
|
| 447 |
respErr := &RespError{} |
| 448 |
if _ = json.Unmarshal(contents, respErr); respErr.ErrCode == "" { |
| 449 |
respErr = nil |
| 450 |
} |
| 451 |
|
| 452 |
return contents, HTTPError{ |
| 453 |
Request: req, |
| 454 |
Response: res, |
| 455 |
RespError: respErr, |
| 456 |
} |
| 457 |
} |
| 458 |
|
| 459 |
// parseBackoffFromResponse extracts the backoff time specified in the Retry-After header if present. See |
| 460 |
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After. |
| 461 |
func (cli *Client) parseBackoffFromResponse(res *http.Response, now time.Time, fallback time.Duration) time.Duration { |
| 462 |
retryAfterHeaderValue := res.Header.Get("Retry-After") |
| 463 |
if retryAfterHeaderValue == "" { |
| 464 |
return fallback |
| 465 |
} |
| 466 |
|
| 467 |
if t, err := time.Parse(http.TimeFormat, retryAfterHeaderValue); err == nil { |
| 468 |
return t.Sub(now) |
| 469 |
} |
| 470 |
|
| 471 |
if seconds, err := strconv.Atoi(retryAfterHeaderValue); err == nil { |
| 472 |
return time.Duration(seconds) * time.Second |
| 473 |
} |
| 474 |
|
| 475 |
cli.logWarning(`Failed to parse Retry-After header value "%s"`, retryAfterHeaderValue) |
| 476 |
|
| 477 |
return fallback |
| 478 |
} |
| 479 |
|
| 480 |
func (cli *Client) shouldRetry(res *http.Response) bool { |
| 481 |
return res.StatusCode == http.StatusBadGateway || |
| 482 |
res.StatusCode == http.StatusServiceUnavailable || |
| 483 |
res.StatusCode == http.StatusGatewayTimeout || |
| 484 |
(res.StatusCode == http.StatusTooManyRequests && !cli.IgnoreRateLimit) |
| 485 |
} |
| 486 |
|
| 487 |
func (cli *Client) executeCompiledRequest(req *http.Request, retries int, backoff time.Duration, responseJSON interface{}, handler ClientResponseHandler) ([]byte, error) { |
| 488 |
cli.LogRequest(req) |
| 489 |
res, err := cli.Client.Do(req) |
| 490 |
if res != nil { |
| 491 |
defer res.Body.Close() |
| 492 |
} |
| 493 |
if err != nil { |
| 494 |
if retries > 0 { |
| 495 |
return cli.doRetry(req, err, retries, backoff, responseJSON, handler) |
| 496 |
} |
| 497 |
return nil, HTTPError{ |
| 498 |
Request: req, |
| 499 |
Response: res, |
| 500 |
|
| 501 |
Message: "request error", |
| 502 |
WrappedError: err, |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
if retries > 0 && cli.shouldRetry(res) { |
| 507 |
if res.StatusCode == http.StatusTooManyRequests { |
| 508 |
backoff = cli.parseBackoffFromResponse(res, time.Now(), backoff) |
| 509 |
} |
| 510 |
return cli.doRetry(req, fmt.Errorf("HTTP %d", res.StatusCode), retries, backoff, responseJSON, handler) |
| 511 |
} |
| 512 |
|
| 513 |
if res.StatusCode < 200 || res.StatusCode >= 300 { |
| 514 |
return cli.handleResponseError(req, res) |
| 515 |
} |
| 516 |
return handler(req, res, responseJSON) |
| 517 |
} |
| 518 |
|
| 519 |
// Whoami gets the user ID of the current user. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3accountwhoami |
| 520 |
func (cli *Client) Whoami() (resp *RespWhoami, err error) { |
| 521 |
urlPath := cli.BuildClientURL("v3", "account", "whoami") |
| 522 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 523 |
return |
| 524 |
} |
| 525 |
|
| 526 |
// CreateFilter makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3useruseridfilter |
| 527 |
func (cli *Client) CreateFilter(filter *Filter) (resp *RespCreateFilter, err error) { |
| 528 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "filter") |
| 529 |
_, err = cli.MakeRequest("POST", urlPath, filter, &resp) |
| 530 |
return |
| 531 |
} |
| 532 |
|
| 533 |
// SyncRequest makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3sync |
| 534 |
func (cli *Client) SyncRequest(timeout int, since, filterID string, fullState bool, setPresence event.Presence, ctx context.Context) (resp *RespSync, err error) { |
| 535 |
return cli.FullSyncRequest(ReqSync{ |
| 536 |
Timeout: timeout, |
| 537 |
Since: since, |
| 538 |
FilterID: filterID, |
| 539 |
FullState: fullState, |
| 540 |
SetPresence: setPresence, |
| 541 |
Context: ctx, |
| 542 |
}) |
| 543 |
} |
| 544 |
|
| 545 |
type ReqSync struct { |
| 546 |
Timeout int |
| 547 |
Since string |
| 548 |
FilterID string |
| 549 |
FullState bool |
| 550 |
SetPresence event.Presence |
| 551 |
|
| 552 |
Context context.Context |
| 553 |
StreamResponse bool |
| 554 |
} |
| 555 |
|
| 556 |
func (req *ReqSync) BuildQuery() map[string]string { |
| 557 |
query := map[string]string{ |
| 558 |
"timeout": strconv.Itoa(req.Timeout), |
| 559 |
} |
| 560 |
if req.Since != "" { |
| 561 |
query["since"] = req.Since |
| 562 |
} |
| 563 |
if req.FilterID != "" { |
| 564 |
query["filter"] = req.FilterID |
| 565 |
} |
| 566 |
if req.SetPresence != "" { |
| 567 |
query["set_presence"] = string(req.SetPresence) |
| 568 |
} |
| 569 |
if req.FullState { |
| 570 |
query["full_state"] = "true" |
| 571 |
} |
| 572 |
return query |
| 573 |
} |
| 574 |
|
| 575 |
// FullSyncRequest makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3sync |
| 576 |
func (cli *Client) FullSyncRequest(req ReqSync) (resp *RespSync, err error) { |
| 577 |
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "sync"}, req.BuildQuery()) |
| 578 |
fullReq := FullRequest{ |
| 579 |
Method: http.MethodGet, |
| 580 |
URL: urlPath, |
| 581 |
ResponseJSON: &resp, |
| 582 |
Context: req.Context, |
| 583 |
// We don't want automatic retries for SyncRequest, the Sync() wrapper handles those. |
| 584 |
MaxAttempts: 1, |
| 585 |
} |
| 586 |
if req.StreamResponse { |
| 587 |
fullReq.Handler = cli.streamResponse |
| 588 |
} |
| 589 |
start := time.Now() |
| 590 |
_, err = cli.MakeFullRequest(fullReq) |
| 591 |
duration := time.Now().Sub(start) |
| 592 |
timeout := time.Duration(req.Timeout) * time.Millisecond |
| 593 |
buffer := 10 * time.Second |
| 594 |
if req.Since == "" { |
| 595 |
buffer = 1 * time.Minute |
| 596 |
} |
| 597 |
if err == nil && duration > timeout+buffer { |
| 598 |
cli.logWarning("Sync request (%s) took %s with timeout %s", req.Since, duration, timeout) |
| 599 |
} |
| 600 |
return |
| 601 |
} |
| 602 |
|
| 603 |
func (cli *Client) register(url string, req *ReqRegister) (resp *RespRegister, uiaResp *RespUserInteractive, err error) { |
| 604 |
var bodyBytes []byte |
| 605 |
bodyBytes, err = cli.MakeFullRequest(FullRequest{ |
| 606 |
Method: http.MethodPost, |
| 607 |
URL: url, |
| 608 |
RequestJSON: req, |
| 609 |
SensitiveContent: len(req.Password) > 0, |
| 610 |
}) |
| 611 |
if err != nil { |
| 612 |
httpErr, ok := err.(HTTPError) |
| 613 |
// if response has a 401 status, but doesn't have the errcode field, it's probably a UIA response. |
| 614 |
if ok && httpErr.IsStatus(http.StatusUnauthorized) && httpErr.RespError == nil { |
| 615 |
err = json.Unmarshal(bodyBytes, &uiaResp) |
| 616 |
} |
| 617 |
} else { |
| 618 |
// body should be RespRegister |
| 619 |
err = json.Unmarshal(bodyBytes, &resp) |
| 620 |
} |
| 621 |
return |
| 622 |
} |
| 623 |
|
| 624 |
// Register makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3register |
| 625 |
// |
| 626 |
// Registers with kind=user. For kind=guest, see RegisterGuest. |
| 627 |
func (cli *Client) Register(req *ReqRegister) (*RespRegister, *RespUserInteractive, error) { |
| 628 |
u := cli.BuildClientURL("v3", "register") |
| 629 |
return cli.register(u, req) |
| 630 |
} |
| 631 |
|
| 632 |
// RegisterGuest makes an HTTP request according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3register |
| 633 |
// with kind=guest. |
| 634 |
// |
| 635 |
// For kind=user, see Register. |
| 636 |
func (cli *Client) RegisterGuest(req *ReqRegister) (*RespRegister, *RespUserInteractive, error) { |
| 637 |
query := map[string]string{ |
| 638 |
"kind": "guest", |
| 639 |
} |
| 640 |
u := cli.BuildURLWithQuery(ClientURLPath{"v3", "register"}, query) |
| 641 |
return cli.register(u, req) |
| 642 |
} |
| 643 |
|
| 644 |
// RegisterDummy performs m.login.dummy registration according to https://spec.matrix.org/v1.2/client-server-api/#dummy-auth |
| 645 |
// |
| 646 |
// Only a username and password need to be provided on the ReqRegister struct. Most local/developer homeservers will allow registration |
| 647 |
// this way. If the homeserver does not, an error is returned. |
| 648 |
// |
| 649 |
// This does not set credentials on the client instance. See SetCredentials() instead. |
| 650 |
// |
| 651 |
// res, err := cli.RegisterDummy(&mautrix.ReqRegister{ |
| 652 |
// Username: "alice", |
| 653 |
// Password: "wonderland", |
| 654 |
// }) |
| 655 |
// if err != nil { |
| 656 |
// panic(err) |
| 657 |
// } |
| 658 |
// token := res.AccessToken |
| 659 |
func (cli *Client) RegisterDummy(req *ReqRegister) (*RespRegister, error) { |
| 660 |
res, uia, err := cli.Register(req) |
| 661 |
if err != nil && uia == nil { |
| 662 |
return nil, err |
| 663 |
} else if uia == nil { |
| 664 |
return nil, errors.New("server did not return user-interactive auth flows") |
| 665 |
} else if !uia.HasSingleStageFlow(AuthTypeDummy) { |
| 666 |
return nil, errors.New("server does not support m.login.dummy") |
| 667 |
} |
| 668 |
req.Auth = BaseAuthData{Type: AuthTypeDummy, Session: uia.Session} |
| 669 |
res, _, err = cli.Register(req) |
| 670 |
if err != nil { |
| 671 |
return nil, err |
| 672 |
} |
| 673 |
return res, nil |
| 674 |
} |
| 675 |
|
| 676 |
// GetLoginFlows fetches the login flows that the homeserver supports using https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3login |
| 677 |
func (cli *Client) GetLoginFlows() (resp *RespLoginFlows, err error) { |
| 678 |
urlPath := cli.BuildClientURL("v3", "login") |
| 679 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 680 |
return |
| 681 |
} |
| 682 |
|
| 683 |
// Login a user to the homeserver according to https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3login |
| 684 |
func (cli *Client) Login(req *ReqLogin) (resp *RespLogin, err error) { |
| 685 |
_, err = cli.MakeFullRequest(FullRequest{ |
| 686 |
Method: http.MethodPost, |
| 687 |
URL: cli.BuildClientURL("v3", "login"), |
| 688 |
RequestJSON: req, |
| 689 |
ResponseJSON: &resp, |
| 690 |
SensitiveContent: len(req.Password) > 0 || len(req.Token) > 0, |
| 691 |
}) |
| 692 |
if req.StoreCredentials && err == nil { |
| 693 |
cli.DeviceID = resp.DeviceID |
| 694 |
cli.AccessToken = resp.AccessToken |
| 695 |
cli.UserID = resp.UserID |
| 696 |
cli.Logger.Debugfln("Stored credentials for %s/%s after login", cli.UserID, cli.DeviceID) |
| 697 |
} |
| 698 |
if req.StoreHomeserverURL && err == nil && resp.WellKnown != nil && len(resp.WellKnown.Homeserver.BaseURL) > 0 { |
| 699 |
var urlErr error |
| 700 |
cli.HomeserverURL, urlErr = url.Parse(resp.WellKnown.Homeserver.BaseURL) |
| 701 |
if urlErr != nil { |
| 702 |
cli.logWarning("Failed to parse homeserver URL '%s' in login response: %v", resp.WellKnown.Homeserver.BaseURL, urlErr) |
| 703 |
} else { |
| 704 |
cli.Logger.Debugfln("Updated homeserver URL to %s after login", cli.HomeserverURL.String()) |
| 705 |
} |
| 706 |
} |
| 707 |
return |
| 708 |
} |
| 709 |
|
| 710 |
// Logout the current user. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3logout |
| 711 |
// This does not clear the credentials from the client instance. See ClearCredentials() instead. |
| 712 |
func (cli *Client) Logout() (resp *RespLogout, err error) { |
| 713 |
urlPath := cli.BuildClientURL("v3", "logout") |
| 714 |
_, err = cli.MakeRequest("POST", urlPath, nil, &resp) |
| 715 |
return |
| 716 |
} |
| 717 |
|
| 718 |
// LogoutAll logs out all the devices of the current user. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3logoutall |
| 719 |
// This does not clear the credentials from the client instance. See ClearCredentials() instead. |
| 720 |
func (cli *Client) LogoutAll() (resp *RespLogout, err error) { |
| 721 |
urlPath := cli.BuildClientURL("v3", "logout", "all") |
| 722 |
_, err = cli.MakeRequest("POST", urlPath, nil, &resp) |
| 723 |
return |
| 724 |
} |
| 725 |
|
| 726 |
// Versions returns the list of supported Matrix versions on this homeserver. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientversions |
| 727 |
func (cli *Client) Versions() (resp *RespVersions, err error) { |
| 728 |
urlPath := cli.BuildClientURL("versions") |
| 729 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 730 |
return |
| 731 |
} |
| 732 |
|
| 733 |
// JoinRoom joins the client to a room ID or alias. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3joinroomidoralias |
| 734 |
// |
| 735 |
// 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 |
| 736 |
// be JSON encoded and used as the request body. |
| 737 |
func (cli *Client) JoinRoom(roomIDorAlias, serverName string, content interface{}) (resp *RespJoinRoom, err error) { |
| 738 |
var urlPath string |
| 739 |
if serverName != "" { |
| 740 |
urlPath = cli.BuildURLWithQuery(ClientURLPath{"v3", "join", roomIDorAlias}, map[string]string{ |
| 741 |
"server_name": serverName, |
| 742 |
}) |
| 743 |
} else { |
| 744 |
urlPath = cli.BuildClientURL("v3", "join", roomIDorAlias) |
| 745 |
} |
| 746 |
_, err = cli.MakeRequest("POST", urlPath, content, &resp) |
| 747 |
return |
| 748 |
} |
| 749 |
|
| 750 |
// JoinRoomByID joins the client to a room ID. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidjoin |
| 751 |
// |
| 752 |
// Unlike JoinRoom, this method can only be used to join rooms that the server already knows about. |
| 753 |
// It's mostly intended for bridges and other things where it's already certain that the server is in the room. |
| 754 |
func (cli *Client) JoinRoomByID(roomID id.RoomID) (resp *RespJoinRoom, err error) { |
| 755 |
_, err = cli.MakeRequest("POST", cli.BuildClientURL("v3", "rooms", roomID, "join"), nil, &resp) |
| 756 |
return |
| 757 |
} |
| 758 |
|
| 759 |
// GetDisplayName returns the display name of the user with the specified MXID. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3profileuseriddisplayname |
| 760 |
func (cli *Client) GetDisplayName(mxid id.UserID) (resp *RespUserDisplayName, err error) { |
| 761 |
urlPath := cli.BuildClientURL("v3", "profile", mxid, "displayname") |
| 762 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 763 |
return |
| 764 |
} |
| 765 |
|
| 766 |
// GetOwnDisplayName returns the user's display name. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3profileuseriddisplayname |
| 767 |
func (cli *Client) GetOwnDisplayName() (resp *RespUserDisplayName, err error) { |
| 768 |
return cli.GetDisplayName(cli.UserID) |
| 769 |
} |
| 770 |
|
| 771 |
// SetDisplayName sets the user's profile display name. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3profileuseriddisplayname |
| 772 |
func (cli *Client) SetDisplayName(displayName string) (err error) { |
| 773 |
urlPath := cli.BuildClientURL("v3", "profile", cli.UserID, "displayname") |
| 774 |
s := struct { |
| 775 |
DisplayName string `json:"displayname"` |
| 776 |
}{displayName} |
| 777 |
_, err = cli.MakeRequest("PUT", urlPath, &s, nil) |
| 778 |
return |
| 779 |
} |
| 780 |
|
| 781 |
// GetAvatarURL gets the avatar URL of the user with the specified MXID. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3profileuseridavatar_url |
| 782 |
func (cli *Client) GetAvatarURL(mxid id.UserID) (url id.ContentURI, err error) { |
| 783 |
urlPath := cli.BuildClientURL("v3", "profile", cli.UserID, "avatar_url") |
| 784 |
s := struct { |
| 785 |
AvatarURL id.ContentURI `json:"avatar_url"` |
| 786 |
}{} |
| 787 |
|
| 788 |
_, err = cli.MakeRequest("GET", urlPath, nil, &s) |
| 789 |
if err != nil { |
| 790 |
return |
| 791 |
} |
| 792 |
url = s.AvatarURL |
| 793 |
return |
| 794 |
} |
| 795 |
|
| 796 |
// GetOwnAvatarURL gets the user's avatar URL. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3profileuseridavatar_url |
| 797 |
func (cli *Client) GetOwnAvatarURL() (url id.ContentURI, err error) { |
| 798 |
return cli.GetAvatarURL(cli.UserID) |
| 799 |
} |
| 800 |
|
| 801 |
// SetAvatarURL sets the user's avatar URL. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3profileuseridavatar_url |
| 802 |
func (cli *Client) SetAvatarURL(url id.ContentURI) (err error) { |
| 803 |
urlPath := cli.BuildClientURL("v3", "profile", cli.UserID, "avatar_url") |
| 804 |
s := struct { |
| 805 |
AvatarURL string `json:"avatar_url"` |
| 806 |
}{url.String()} |
| 807 |
_, err = cli.MakeRequest("PUT", urlPath, &s, nil) |
| 808 |
if err != nil { |
| 809 |
return err |
| 810 |
} |
| 811 |
|
| 812 |
return nil |
| 813 |
} |
| 814 |
|
| 815 |
// GetAccountData gets the user's account data of this type. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype |
| 816 |
func (cli *Client) GetAccountData(name string, output interface{}) (err error) { |
| 817 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "account_data", name) |
| 818 |
_, err = cli.MakeRequest("GET", urlPath, nil, output) |
| 819 |
return |
| 820 |
} |
| 821 |
|
| 822 |
// SetAccountData sets the user's account data of this type. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3useruseridaccount_datatype |
| 823 |
func (cli *Client) SetAccountData(name string, data interface{}) (err error) { |
| 824 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "account_data", name) |
| 825 |
_, err = cli.MakeRequest("PUT", urlPath, &data, nil) |
| 826 |
if err != nil { |
| 827 |
return err |
| 828 |
} |
| 829 |
|
| 830 |
return nil |
| 831 |
} |
| 832 |
|
| 833 |
// GetRoomAccountData gets the user's account data of this type in a specific room. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3useruseridaccount_datatype |
| 834 |
func (cli *Client) GetRoomAccountData(roomID id.RoomID, name string, output interface{}) (err error) { |
| 835 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "rooms", roomID, "account_data", name) |
| 836 |
_, err = cli.MakeRequest("GET", urlPath, nil, output) |
| 837 |
return |
| 838 |
} |
| 839 |
|
| 840 |
// SetRoomAccountData sets the user's account data of this type in a specific room. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3useruseridroomsroomidaccount_datatype |
| 841 |
func (cli *Client) SetRoomAccountData(roomID id.RoomID, name string, data interface{}) (err error) { |
| 842 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "rooms", roomID, "account_data", name) |
| 843 |
_, err = cli.MakeRequest("PUT", urlPath, &data, nil) |
| 844 |
if err != nil { |
| 845 |
return err |
| 846 |
} |
| 847 |
|
| 848 |
return nil |
| 849 |
} |
| 850 |
|
| 851 |
type ReqSendEvent struct { |
| 852 |
Timestamp int64 |
| 853 |
TransactionID string |
| 854 |
} |
| 855 |
|
| 856 |
// SendMessageEvent sends a message event into a room. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid |
| 857 |
// contentJSON should be a pointer to something that can be encoded as JSON using json.Marshal. |
| 858 |
func (cli *Client) SendMessageEvent(roomID id.RoomID, eventType event.Type, contentJSON interface{}, extra ...ReqSendEvent) (resp *RespSendEvent, err error) { |
| 859 |
var req ReqSendEvent |
| 860 |
if len(extra) > 0 { |
| 861 |
req = extra[0] |
| 862 |
} |
| 863 |
|
| 864 |
var txnID string |
| 865 |
if len(req.TransactionID) > 0 { |
| 866 |
txnID = req.TransactionID |
| 867 |
} else { |
| 868 |
txnID = cli.TxnID() |
| 869 |
} |
| 870 |
|
| 871 |
queryParams := map[string]string{} |
| 872 |
if req.Timestamp > 0 { |
| 873 |
queryParams["ts"] = strconv.FormatInt(req.Timestamp, 10) |
| 874 |
} |
| 875 |
|
| 876 |
urlData := ClientURLPath{"v3", "rooms", roomID, "send", eventType.String(), txnID} |
| 877 |
|
| 878 |
urlPath := cli.BuildURLWithQuery(urlData, queryParams) |
| 879 |
_, err = cli.MakeRequest("PUT", urlPath, contentJSON, &resp) |
| 880 |
return |
| 881 |
} |
| 882 |
|
| 883 |
// SendStateEvent sends a state event into a room. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey |
| 884 |
// contentJSON should be a pointer to something that can be encoded as JSON using json.Marshal. |
| 885 |
func (cli *Client) SendStateEvent(roomID id.RoomID, eventType event.Type, stateKey string, contentJSON interface{}) (resp *RespSendEvent, err error) { |
| 886 |
urlPath := cli.BuildClientURL("v3", "rooms", roomID, "state", eventType.String(), stateKey) |
| 887 |
_, err = cli.MakeRequest("PUT", urlPath, contentJSON, &resp) |
| 888 |
return |
| 889 |
} |
| 890 |
|
| 891 |
// SendMassagedStateEvent sends a state event into a room with a custom timestamp. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey |
| 892 |
// contentJSON should be a pointer to something that can be encoded as JSON using json.Marshal. |
| 893 |
func (cli *Client) SendMassagedStateEvent(roomID id.RoomID, eventType event.Type, stateKey string, contentJSON interface{}, ts int64) (resp *RespSendEvent, err error) { |
| 894 |
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "rooms", roomID, "state", eventType.String(), stateKey}, map[string]string{ |
| 895 |
"ts": strconv.FormatInt(ts, 10), |
| 896 |
}) |
| 897 |
_, err = cli.MakeRequest("PUT", urlPath, contentJSON, &resp) |
| 898 |
return |
| 899 |
} |
| 900 |
|
| 901 |
// SendText sends an m.room.message event into the given room with a msgtype of m.text |
| 902 |
// See https://spec.matrix.org/v1.2/client-server-api/#mtext |
| 903 |
func (cli *Client) SendText(roomID id.RoomID, text string) (*RespSendEvent, error) { |
| 904 |
return cli.SendMessageEvent(roomID, event.EventMessage, &event.MessageEventContent{ |
| 905 |
MsgType: event.MsgText, |
| 906 |
Body: text, |
| 907 |
}) |
| 908 |
} |
| 909 |
|
| 910 |
// SendImage sends an m.room.message event into the given room with a msgtype of m.image |
| 911 |
// See https://spec.matrix.org/v1.2/client-server-api/#mimage |
| 912 |
// |
| 913 |
// Deprecated: This does not allow setting image metadata, you should prefer SendMessageEvent with a properly filled &event.MessageEventContent |
| 914 |
func (cli *Client) SendImage(roomID id.RoomID, body string, url id.ContentURI) (*RespSendEvent, error) { |
| 915 |
return cli.SendMessageEvent(roomID, event.EventMessage, &event.MessageEventContent{ |
| 916 |
MsgType: event.MsgImage, |
| 917 |
Body: body, |
| 918 |
URL: url.CUString(), |
| 919 |
}) |
| 920 |
} |
| 921 |
|
| 922 |
// SendVideo sends an m.room.message event into the given room with a msgtype of m.video |
| 923 |
// See https://spec.matrix.org/v1.2/client-server-api/#mvideo |
| 924 |
// |
| 925 |
// Deprecated: This does not allow setting video metadata, you should prefer SendMessageEvent with a properly filled &event.MessageEventContent |
| 926 |
func (cli *Client) SendVideo(roomID id.RoomID, body string, url id.ContentURI) (*RespSendEvent, error) { |
| 927 |
return cli.SendMessageEvent(roomID, event.EventMessage, &event.MessageEventContent{ |
| 928 |
MsgType: event.MsgVideo, |
| 929 |
Body: body, |
| 930 |
URL: url.CUString(), |
| 931 |
}) |
| 932 |
} |
| 933 |
|
| 934 |
// SendNotice sends an m.room.message event into the given room with a msgtype of m.notice |
| 935 |
// See https://spec.matrix.org/v1.2/client-server-api/#mnotice |
| 936 |
func (cli *Client) SendNotice(roomID id.RoomID, text string) (*RespSendEvent, error) { |
| 937 |
return cli.SendMessageEvent(roomID, event.EventMessage, &event.MessageEventContent{ |
| 938 |
MsgType: event.MsgNotice, |
| 939 |
Body: text, |
| 940 |
}) |
| 941 |
} |
| 942 |
|
| 943 |
func (cli *Client) SendReaction(roomID id.RoomID, eventID id.EventID, reaction string) (*RespSendEvent, error) { |
| 944 |
return cli.SendMessageEvent(roomID, event.EventReaction, &event.ReactionEventContent{ |
| 945 |
RelatesTo: event.RelatesTo{ |
| 946 |
EventID: eventID, |
| 947 |
Type: event.RelAnnotation, |
| 948 |
Key: reaction, |
| 949 |
}, |
| 950 |
}) |
| 951 |
} |
| 952 |
|
| 953 |
// RedactEvent redacts the given event. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidredacteventidtxnid |
| 954 |
func (cli *Client) RedactEvent(roomID id.RoomID, eventID id.EventID, extra ...ReqRedact) (resp *RespSendEvent, err error) { |
| 955 |
req := ReqRedact{} |
| 956 |
if len(extra) > 0 { |
| 957 |
req = extra[0] |
| 958 |
} |
| 959 |
if req.Extra == nil { |
| 960 |
req.Extra = make(map[string]interface{}) |
| 961 |
} |
| 962 |
if len(req.Reason) > 0 { |
| 963 |
req.Extra["reason"] = req.Reason |
| 964 |
} |
| 965 |
var txnID string |
| 966 |
if len(req.TxnID) > 0 { |
| 967 |
txnID = req.TxnID |
| 968 |
} else { |
| 969 |
txnID = cli.TxnID() |
| 970 |
} |
| 971 |
urlPath := cli.BuildClientURL("v3", "rooms", roomID, "redact", eventID, txnID) |
| 972 |
_, err = cli.MakeRequest("PUT", urlPath, req.Extra, &resp) |
| 973 |
return |
| 974 |
} |
| 975 |
|
| 976 |
// CreateRoom creates a new Matrix room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3createroom |
| 977 |
// resp, err := cli.CreateRoom(&mautrix.ReqCreateRoom{ |
| 978 |
// Preset: "public_chat", |
| 979 |
// }) |
| 980 |
// fmt.Println("Room:", resp.RoomID) |
| 981 |
func (cli *Client) CreateRoom(req *ReqCreateRoom) (resp *RespCreateRoom, err error) { |
| 982 |
urlPath := cli.BuildClientURL("v3", "createRoom") |
| 983 |
_, err = cli.MakeRequest("POST", urlPath, req, &resp) |
| 984 |
return |
| 985 |
} |
| 986 |
|
| 987 |
// LeaveRoom leaves the given room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidleave |
| 988 |
func (cli *Client) LeaveRoom(roomID id.RoomID, optionalReq ...*ReqLeave) (resp *RespLeaveRoom, err error) { |
| 989 |
req := &ReqLeave{} |
| 990 |
if len(optionalReq) == 1 { |
| 991 |
req = optionalReq[0] |
| 992 |
} else if len(optionalReq) > 1 { |
| 993 |
panic("invalid number of arguments to LeaveRoom") |
| 994 |
} |
| 995 |
u := cli.BuildClientURL("v3", "rooms", roomID, "leave") |
| 996 |
_, err = cli.MakeRequest("POST", u, req, &resp) |
| 997 |
return |
| 998 |
} |
| 999 |
|
| 1000 |
// ForgetRoom forgets a room entirely. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidforget |
| 1001 |
func (cli *Client) ForgetRoom(roomID id.RoomID) (resp *RespForgetRoom, err error) { |
| 1002 |
u := cli.BuildClientURL("v3", "rooms", roomID, "forget") |
| 1003 |
_, err = cli.MakeRequest("POST", u, struct{}{}, &resp) |
| 1004 |
return |
| 1005 |
} |
| 1006 |
|
| 1007 |
// InviteUser invites a user to a room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite |
| 1008 |
func (cli *Client) InviteUser(roomID id.RoomID, req *ReqInviteUser) (resp *RespInviteUser, err error) { |
| 1009 |
u := cli.BuildClientURL("v3", "rooms", roomID, "invite") |
| 1010 |
_, err = cli.MakeRequest("POST", u, req, &resp) |
| 1011 |
return |
| 1012 |
} |
| 1013 |
|
| 1014 |
// InviteUserByThirdParty invites a third-party identifier to a room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite-1 |
| 1015 |
func (cli *Client) InviteUserByThirdParty(roomID id.RoomID, req *ReqInvite3PID) (resp *RespInviteUser, err error) { |
| 1016 |
u := cli.BuildClientURL("v3", "rooms", roomID, "invite") |
| 1017 |
_, err = cli.MakeRequest("POST", u, req, &resp) |
| 1018 |
return |
| 1019 |
} |
| 1020 |
|
| 1021 |
// KickUser kicks a user from a room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidkick |
| 1022 |
func (cli *Client) KickUser(roomID id.RoomID, req *ReqKickUser) (resp *RespKickUser, err error) { |
| 1023 |
u := cli.BuildClientURL("v3", "rooms", roomID, "kick") |
| 1024 |
_, err = cli.MakeRequest("POST", u, req, &resp) |
| 1025 |
return |
| 1026 |
} |
| 1027 |
|
| 1028 |
// BanUser bans a user from a room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidban |
| 1029 |
func (cli *Client) BanUser(roomID id.RoomID, req *ReqBanUser) (resp *RespBanUser, err error) { |
| 1030 |
u := cli.BuildClientURL("v3", "rooms", roomID, "ban") |
| 1031 |
_, err = cli.MakeRequest("POST", u, req, &resp) |
| 1032 |
return |
| 1033 |
} |
| 1034 |
|
| 1035 |
// UnbanUser unbans a user from a room. See https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidunban |
| 1036 |
func (cli *Client) UnbanUser(roomID id.RoomID, req *ReqUnbanUser) (resp *RespUnbanUser, err error) { |
| 1037 |
u := cli.BuildClientURL("v3", "rooms", roomID, "unban") |
| 1038 |
_, err = cli.MakeRequest("POST", u, req, &resp) |
| 1039 |
return |
| 1040 |
} |
| 1041 |
|
| 1042 |
// UserTyping sets the typing status of the user. See https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidtypinguserid |
| 1043 |
func (cli *Client) UserTyping(roomID id.RoomID, typing bool, timeout int64) (resp *RespTyping, err error) { |
| 1044 |
req := ReqTyping{Typing: typing, Timeout: timeout} |
| 1045 |
u := cli.BuildClientURL("v3", "rooms", roomID, "typing", cli.UserID) |
| 1046 |
_, err = cli.MakeRequest("PUT", u, req, &resp) |
| 1047 |
return |
| 1048 |
} |
| 1049 |
|
| 1050 |
// GetPresence gets the presence of the user with the specified MXID. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3presenceuseridstatus |
| 1051 |
func (cli *Client) GetPresence(userID id.UserID) (resp *RespPresence, err error) { |
| 1052 |
resp = new(RespPresence) |
| 1053 |
u := cli.BuildClientURL("v3", "presence", userID, "status") |
| 1054 |
_, err = cli.MakeRequest("GET", u, nil, resp) |
| 1055 |
return |
| 1056 |
} |
| 1057 |
|
| 1058 |
// GetOwnPresence gets the user's presence. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3presenceuseridstatus |
| 1059 |
func (cli *Client) GetOwnPresence() (resp *RespPresence, err error) { |
| 1060 |
return cli.GetPresence(cli.UserID) |
| 1061 |
} |
| 1062 |
|
| 1063 |
func (cli *Client) SetPresence(status event.Presence) (err error) { |
| 1064 |
req := ReqPresence{Presence: status} |
| 1065 |
u := cli.BuildClientURL("v3", "presence", cli.UserID, "status") |
| 1066 |
_, err = cli.MakeRequest("PUT", u, req, nil) |
| 1067 |
return |
| 1068 |
} |
| 1069 |
|
| 1070 |
// StateEvent gets a single state event in a room. It will attempt to JSON unmarshal into the given "outContent" struct with |
| 1071 |
// the HTTP response body, or return an error. |
| 1072 |
// See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3roomsroomidstateeventtypestatekey |
| 1073 |
func (cli *Client) StateEvent(roomID id.RoomID, eventType event.Type, stateKey string, outContent interface{}) (err error) { |
| 1074 |
u := cli.BuildClientURL("v3", "rooms", roomID, "state", eventType.String(), stateKey) |
| 1075 |
_, err = cli.MakeRequest("GET", u, nil, outContent) |
| 1076 |
return |
| 1077 |
} |
| 1078 |
|
| 1079 |
// parseRoomStateArray parses a JSON array as a stream and stores the events inside it in a room state map. |
| 1080 |
func parseRoomStateArray(_ *http.Request, res *http.Response, responseJSON interface{}) ([]byte, error) { |
| 1081 |
response := make(RoomStateMap) |
| 1082 |
responsePtr := responseJSON.(*map[event.Type]map[string]*event.Event) |
| 1083 |
*responsePtr = response |
| 1084 |
dec := json.NewDecoder(res.Body) |
| 1085 |
|
| 1086 |
arrayStart, err := dec.Token() |
| 1087 |
if err != nil { |
| 1088 |
return nil, err |
| 1089 |
} else if arrayStart != json.Delim('[') { |
| 1090 |
return nil, fmt.Errorf("expected array start, got %+v", arrayStart) |
| 1091 |
} |
| 1092 |
|
| 1093 |
for i := 1; dec.More(); i++ { |
| 1094 |
var evt *event.Event |
| 1095 |
err = dec.Decode(&evt) |
| 1096 |
if err != nil { |
| 1097 |
return nil, fmt.Errorf("failed to parse state array item #%d: %v", i, err) |
| 1098 |
} |
| 1099 |
_ = evt.Content.ParseRaw(evt.Type) |
| 1100 |
subMap, ok := response[evt.Type] |
| 1101 |
if !ok { |
| 1102 |
subMap = make(map[string]*event.Event) |
| 1103 |
response[evt.Type] = subMap |
| 1104 |
} |
| 1105 |
subMap[*evt.StateKey] = evt |
| 1106 |
} |
| 1107 |
|
| 1108 |
arrayEnd, err := dec.Token() |
| 1109 |
if err != nil { |
| 1110 |
return nil, err |
| 1111 |
} else if arrayEnd != json.Delim(']') { |
| 1112 |
return nil, fmt.Errorf("expected array end, got %+v", arrayStart) |
| 1113 |
} |
| 1114 |
return nil, nil |
| 1115 |
} |
| 1116 |
|
| 1117 |
// State gets all state in a room. |
| 1118 |
// See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3roomsroomidstate |
| 1119 |
func (cli *Client) State(roomID id.RoomID) (stateMap RoomStateMap, err error) { |
| 1120 |
_, err = cli.MakeFullRequest(FullRequest{ |
| 1121 |
Method: http.MethodGet, |
| 1122 |
URL: cli.BuildClientURL("v3", "rooms", roomID, "state"), |
| 1123 |
ResponseJSON: &stateMap, |
| 1124 |
Handler: parseRoomStateArray, |
| 1125 |
}) |
| 1126 |
return |
| 1127 |
} |
| 1128 |
|
| 1129 |
// UploadLink uploads an HTTP URL and then returns an MXC URI. |
| 1130 |
func (cli *Client) UploadLink(link string) (*RespMediaUpload, error) { |
| 1131 |
res, err := cli.Client.Get(link) |
| 1132 |
if res != nil { |
| 1133 |
defer res.Body.Close() |
| 1134 |
} |
| 1135 |
if err != nil { |
| 1136 |
return nil, err |
| 1137 |
} |
| 1138 |
return cli.Upload(res.Body, res.Header.Get("Content-Type"), res.ContentLength) |
| 1139 |
} |
| 1140 |
|
| 1141 |
func (cli *Client) GetDownloadURL(mxcURL id.ContentURI) string { |
| 1142 |
return cli.BuildURL(MediaURLPath{"v3", "download", mxcURL.Homeserver, mxcURL.FileID}) |
| 1143 |
} |
| 1144 |
|
| 1145 |
func (cli *Client) Download(mxcURL id.ContentURI) (io.ReadCloser, error) { |
| 1146 |
resp, err := cli.Client.Get(cli.GetDownloadURL(mxcURL)) |
| 1147 |
if err != nil { |
| 1148 |
return nil, err |
| 1149 |
} |
| 1150 |
return resp.Body, nil |
| 1151 |
} |
| 1152 |
|
| 1153 |
func (cli *Client) DownloadBytes(mxcURL id.ContentURI) ([]byte, error) { |
| 1154 |
resp, err := cli.Download(mxcURL) |
| 1155 |
if err != nil { |
| 1156 |
return nil, err |
| 1157 |
} |
| 1158 |
defer resp.Close() |
| 1159 |
return ioutil.ReadAll(resp) |
| 1160 |
} |
| 1161 |
|
| 1162 |
// UnstableCreateMXC creates a blank Matrix content URI to allow uploading the content asynchronously later. |
| 1163 |
// See https://github.com/matrix-org/matrix-spec-proposals/pull/2246 |
| 1164 |
func (cli *Client) UnstableCreateMXC() (*RespCreateMXC, error) { |
| 1165 |
u, _ := url.Parse(cli.BuildURL(MediaURLPath{"unstable", "fi.mau.msc2246", "create"})) |
| 1166 |
var m RespCreateMXC |
| 1167 |
_, err := cli.MakeFullRequest(FullRequest{ |
| 1168 |
Method: http.MethodPost, |
| 1169 |
URL: u.String(), |
| 1170 |
ResponseJSON: &m, |
| 1171 |
}) |
| 1172 |
return &m, err |
| 1173 |
} |
| 1174 |
|
| 1175 |
// UnstableUploadAsync creates a blank content URI with UnstableCreateMXC, starts uploading the data in the background |
| 1176 |
// and returns the created MXC immediately. See https://github.com/matrix-org/matrix-spec-proposals/pull/2246 for more info. |
| 1177 |
func (cli *Client) UnstableUploadAsync(req ReqUploadMedia) (*RespCreateMXC, error) { |
| 1178 |
resp, err := cli.UnstableCreateMXC() |
| 1179 |
if err != nil { |
| 1180 |
return nil, err |
| 1181 |
} |
| 1182 |
req.UnstableMXC = resp.ContentURI |
| 1183 |
go func() { |
| 1184 |
_, err = cli.UploadMedia(req) |
| 1185 |
if err != nil { |
| 1186 |
cli.logWarning("Failed to upload %s: %v", req.UnstableMXC, err) |
| 1187 |
} |
| 1188 |
}() |
| 1189 |
return resp, nil |
| 1190 |
} |
| 1191 |
|
| 1192 |
func (cli *Client) UploadBytes(data []byte, contentType string) (*RespMediaUpload, error) { |
| 1193 |
return cli.UploadBytesWithName(data, contentType, "") |
| 1194 |
} |
| 1195 |
|
| 1196 |
func (cli *Client) UploadBytesWithName(data []byte, contentType, fileName string) (*RespMediaUpload, error) { |
| 1197 |
return cli.UploadMedia(ReqUploadMedia{ |
| 1198 |
ContentBytes: data, |
| 1199 |
ContentType: contentType, |
| 1200 |
FileName: fileName, |
| 1201 |
}) |
| 1202 |
} |
| 1203 |
|
| 1204 |
// Upload uploads the given data to the content repository and returns an MXC URI. |
| 1205 |
// |
| 1206 |
// Deprecated: UploadMedia should be used instead. |
| 1207 |
func (cli *Client) Upload(content io.Reader, contentType string, contentLength int64) (*RespMediaUpload, error) { |
| 1208 |
return cli.UploadMedia(ReqUploadMedia{ |
| 1209 |
Content: content, |
| 1210 |
ContentLength: contentLength, |
| 1211 |
ContentType: contentType, |
| 1212 |
}) |
| 1213 |
} |
| 1214 |
|
| 1215 |
type ReqUploadMedia struct { |
| 1216 |
ContentBytes []byte |
| 1217 |
Content io.Reader |
| 1218 |
ContentLength int64 |
| 1219 |
ContentType string |
| 1220 |
FileName string |
| 1221 |
|
| 1222 |
// UnstableMXC specifies an existing MXC URI which doesn't have content yet to upload into. |
| 1223 |
// See https://github.com/matrix-org/matrix-spec-proposals/pull/2246 for more info. |
| 1224 |
UnstableMXC id.ContentURI |
| 1225 |
} |
| 1226 |
|
| 1227 |
// UploadMedia uploads the given data to the content repository and returns an MXC URI. |
| 1228 |
// See https://spec.matrix.org/v1.2/client-server-api/#post_matrixmediav3upload |
| 1229 |
func (cli *Client) UploadMedia(data ReqUploadMedia) (*RespMediaUpload, error) { |
| 1230 |
u, _ := url.Parse(cli.BuildURL(MediaURLPath{"v3", "upload"})) |
| 1231 |
method := http.MethodPost |
| 1232 |
if !data.UnstableMXC.IsEmpty() { |
| 1233 |
u, _ = url.Parse(cli.BuildURL(MediaURLPath{"unstable", "fi.mau.msc2246", "upload", data.UnstableMXC.Homeserver, data.UnstableMXC.FileID})) |
| 1234 |
method = http.MethodPut |
| 1235 |
} |
| 1236 |
if len(data.FileName) > 0 { |
| 1237 |
q := u.Query() |
| 1238 |
q.Set("filename", data.FileName) |
| 1239 |
u.RawQuery = q.Encode() |
| 1240 |
} |
| 1241 |
|
| 1242 |
var headers http.Header |
| 1243 |
if len(data.ContentType) > 0 { |
| 1244 |
headers = http.Header{"Content-Type": []string{data.ContentType}} |
| 1245 |
} |
| 1246 |
|
| 1247 |
var m RespMediaUpload |
| 1248 |
_, err := cli.MakeFullRequest(FullRequest{ |
| 1249 |
Method: method, |
| 1250 |
URL: u.String(), |
| 1251 |
Headers: headers, |
| 1252 |
RequestBytes: data.ContentBytes, |
| 1253 |
RequestBody: data.Content, |
| 1254 |
RequestLength: data.ContentLength, |
| 1255 |
ResponseJSON: &m, |
| 1256 |
}) |
| 1257 |
return &m, err |
| 1258 |
} |
| 1259 |
|
| 1260 |
// GetURLPreview asks the homeserver to fetch a preview for a given URL. |
| 1261 |
// |
| 1262 |
// See https://spec.matrix.org/v1.2/client-server-api/#get_matrixmediav3preview_url |
| 1263 |
func (cli *Client) GetURLPreview(url string) (*RespPreviewURL, error) { |
| 1264 |
reqURL := cli.BuildURLWithQuery(MediaURLPath{"v3", "preview_url"}, map[string]string{ |
| 1265 |
"url": url, |
| 1266 |
}) |
| 1267 |
var output RespPreviewURL |
| 1268 |
_, err := cli.MakeRequest(http.MethodGet, reqURL, nil, &output) |
| 1269 |
return &output, err |
| 1270 |
} |
| 1271 |
|
| 1272 |
// JoinedMembers returns a map of joined room members. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3roomsroomidjoined_members |
| 1273 |
// |
| 1274 |
// In general, usage of this API is discouraged in favour of /sync, as calling this API can race with incoming membership changes. |
| 1275 |
// This API is primarily designed for application services which may want to efficiently look up joined members in a room. |
| 1276 |
func (cli *Client) JoinedMembers(roomID id.RoomID) (resp *RespJoinedMembers, err error) { |
| 1277 |
u := cli.BuildClientURL("v3", "rooms", roomID, "joined_members") |
| 1278 |
_, err = cli.MakeRequest("GET", u, nil, &resp) |
| 1279 |
return |
| 1280 |
} |
| 1281 |
|
| 1282 |
func (cli *Client) Members(roomID id.RoomID, req ...ReqMembers) (resp *RespMembers, err error) { |
| 1283 |
var extra ReqMembers |
| 1284 |
if len(req) > 0 { |
| 1285 |
extra = req[0] |
| 1286 |
} |
| 1287 |
query := map[string]string{} |
| 1288 |
if len(extra.At) > 0 { |
| 1289 |
query["at"] = extra.At |
| 1290 |
} |
| 1291 |
if len(extra.Membership) > 0 { |
| 1292 |
query["membership"] = string(extra.Membership) |
| 1293 |
} |
| 1294 |
if len(extra.NotMembership) > 0 { |
| 1295 |
query["not_membership"] = string(extra.NotMembership) |
| 1296 |
} |
| 1297 |
u := cli.BuildURLWithQuery(ClientURLPath{"v3", "rooms", roomID, "members"}, query) |
| 1298 |
_, err = cli.MakeRequest("GET", u, nil, &resp) |
| 1299 |
return |
| 1300 |
} |
| 1301 |
|
| 1302 |
// JoinedRooms returns a list of rooms which the client is joined to. See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3joined_rooms |
| 1303 |
// |
| 1304 |
// In general, usage of this API is discouraged in favour of /sync, as calling this API can race with incoming membership changes. |
| 1305 |
// This API is primarily designed for application services which may want to efficiently look up joined rooms. |
| 1306 |
func (cli *Client) JoinedRooms() (resp *RespJoinedRooms, err error) { |
| 1307 |
u := cli.BuildClientURL("v3", "joined_rooms") |
| 1308 |
_, err = cli.MakeRequest("GET", u, nil, &resp) |
| 1309 |
return |
| 1310 |
} |
| 1311 |
|
| 1312 |
// Messages returns a list of message and state events for a room. It uses |
| 1313 |
// pagination query parameters to paginate history in the room. |
| 1314 |
// See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3roomsroomidmessages |
| 1315 |
func (cli *Client) Messages(roomID id.RoomID, from, to string, dir rune, filter *FilterPart, limit int) (resp *RespMessages, err error) { |
| 1316 |
query := map[string]string{ |
| 1317 |
"from": from, |
| 1318 |
"dir": string(dir), |
| 1319 |
} |
| 1320 |
if filter != nil { |
| 1321 |
filterJSON, err := json.Marshal(filter) |
| 1322 |
if err != nil { |
| 1323 |
return nil, err |
| 1324 |
} |
| 1325 |
query["filter"] = string(filterJSON) |
| 1326 |
} |
| 1327 |
if to != "" { |
| 1328 |
query["to"] = to |
| 1329 |
} |
| 1330 |
if limit != 0 { |
| 1331 |
query["limit"] = strconv.Itoa(limit) |
| 1332 |
} |
| 1333 |
|
| 1334 |
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "rooms", roomID, "messages"}, query) |
| 1335 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1336 |
return |
| 1337 |
} |
| 1338 |
|
| 1339 |
// Context returns a number of events that happened just before and after the |
| 1340 |
// specified event. It use pagination query parameters to paginate history in |
| 1341 |
// the room. |
| 1342 |
// See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3roomsroomidcontexteventid |
| 1343 |
func (cli *Client) Context(roomID id.RoomID, eventID id.EventID, filter *FilterPart, limit int) (resp *RespContext, err error) { |
| 1344 |
query := map[string]string{} |
| 1345 |
if filter != nil { |
| 1346 |
filterJSON, err := json.Marshal(filter) |
| 1347 |
if err != nil { |
| 1348 |
return nil, err |
| 1349 |
} |
| 1350 |
query["filter"] = string(filterJSON) |
| 1351 |
} |
| 1352 |
if limit != 0 { |
| 1353 |
query["limit"] = strconv.Itoa(limit) |
| 1354 |
} |
| 1355 |
|
| 1356 |
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "rooms", roomID, "context", eventID}, query) |
| 1357 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1358 |
return |
| 1359 |
} |
| 1360 |
|
| 1361 |
func (cli *Client) GetEvent(roomID id.RoomID, eventID id.EventID) (resp *event.Event, err error) { |
| 1362 |
urlPath := cli.BuildClientURL("v3", "rooms", roomID, "event", eventID) |
| 1363 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1364 |
return |
| 1365 |
} |
| 1366 |
|
| 1367 |
func (cli *Client) MarkRead(roomID id.RoomID, eventID id.EventID) (err error) { |
| 1368 |
return cli.MarkReadWithContent(roomID, eventID, struct{}{}) |
| 1369 |
} |
| 1370 |
|
| 1371 |
// MarkReadWithContent sends a read receipt including custom data. |
| 1372 |
// N.B. This is not (yet) a part of the spec, normal servers will drop any extra content. |
| 1373 |
func (cli *Client) MarkReadWithContent(roomID id.RoomID, eventID id.EventID, content interface{}) (err error) { |
| 1374 |
urlPath := cli.BuildClientURL("v3", "rooms", roomID, "receipt", "m.read", eventID) |
| 1375 |
_, err = cli.MakeRequest("POST", urlPath, &content, nil) |
| 1376 |
return |
| 1377 |
} |
| 1378 |
|
| 1379 |
func (cli *Client) SetReadMarkers(roomID id.RoomID, content interface{}) (err error) { |
| 1380 |
urlPath := cli.BuildClientURL("v3", "rooms", roomID, "read_markers") |
| 1381 |
_, err = cli.MakeRequest("POST", urlPath, &content, nil) |
| 1382 |
return |
| 1383 |
} |
| 1384 |
|
| 1385 |
func (cli *Client) AddTag(roomID id.RoomID, tag string, order float64) error { |
| 1386 |
var tagData event.Tag |
| 1387 |
if order == order { |
| 1388 |
tagData.Order = json.Number(strconv.FormatFloat(order, 'e', -1, 64)) |
| 1389 |
} |
| 1390 |
return cli.AddTagWithCustomData(roomID, tag, tagData) |
| 1391 |
} |
| 1392 |
|
| 1393 |
func (cli *Client) AddTagWithCustomData(roomID id.RoomID, tag string, data interface{}) (err error) { |
| 1394 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "rooms", roomID, "tags", tag) |
| 1395 |
_, err = cli.MakeRequest("PUT", urlPath, data, nil) |
| 1396 |
return |
| 1397 |
} |
| 1398 |
|
| 1399 |
func (cli *Client) GetTags(roomID id.RoomID) (tags event.TagEventContent, err error) { |
| 1400 |
err = cli.GetTagsWithCustomData(roomID, &tags) |
| 1401 |
return |
| 1402 |
} |
| 1403 |
|
| 1404 |
func (cli *Client) GetTagsWithCustomData(roomID id.RoomID, resp interface{}) (err error) { |
| 1405 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "rooms", roomID, "tags") |
| 1406 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1407 |
return |
| 1408 |
} |
| 1409 |
|
| 1410 |
func (cli *Client) RemoveTag(roomID id.RoomID, tag string) (err error) { |
| 1411 |
urlPath := cli.BuildClientURL("v3", "user", cli.UserID, "rooms", roomID, "tags", tag) |
| 1412 |
_, err = cli.MakeRequest("DELETE", urlPath, nil, nil) |
| 1413 |
return |
| 1414 |
} |
| 1415 |
|
| 1416 |
// Deprecated: Synapse may not handle setting m.tag directly properly, so you should use the Add/RemoveTag methods instead. |
| 1417 |
func (cli *Client) SetTags(roomID id.RoomID, tags event.Tags) (err error) { |
| 1418 |
return cli.SetRoomAccountData(roomID, "m.tag", map[string]event.Tags{ |
| 1419 |
"tags": tags, |
| 1420 |
}) |
| 1421 |
} |
| 1422 |
|
| 1423 |
// TurnServer returns turn server details and credentials for the client to use when initiating calls. |
| 1424 |
// See https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3voipturnserver |
| 1425 |
func (cli *Client) TurnServer() (resp *RespTurnServer, err error) { |
| 1426 |
urlPath := cli.BuildClientURL("v3", "voip", "turnServer") |
| 1427 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1428 |
return |
| 1429 |
} |
| 1430 |
|
| 1431 |
func (cli *Client) CreateAlias(alias id.RoomAlias, roomID id.RoomID) (resp *RespAliasCreate, err error) { |
| 1432 |
urlPath := cli.BuildClientURL("v3", "directory", "room", alias) |
| 1433 |
_, err = cli.MakeRequest("PUT", urlPath, &ReqAliasCreate{RoomID: roomID}, &resp) |
| 1434 |
return |
| 1435 |
} |
| 1436 |
|
| 1437 |
func (cli *Client) ResolveAlias(alias id.RoomAlias) (resp *RespAliasResolve, err error) { |
| 1438 |
urlPath := cli.BuildClientURL("v3", "directory", "room", alias) |
| 1439 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1440 |
return |
| 1441 |
} |
| 1442 |
|
| 1443 |
func (cli *Client) DeleteAlias(alias id.RoomAlias) (resp *RespAliasDelete, err error) { |
| 1444 |
urlPath := cli.BuildClientURL("v3", "directory", "room", alias) |
| 1445 |
_, err = cli.MakeRequest("DELETE", urlPath, nil, &resp) |
| 1446 |
return |
| 1447 |
} |
| 1448 |
|
| 1449 |
func (cli *Client) GetAliases(roomID id.RoomID) (resp *RespAliasList, err error) { |
| 1450 |
urlPath := cli.BuildClientURL("v3", "rooms", roomID, "aliases") |
| 1451 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1452 |
return |
| 1453 |
} |
| 1454 |
|
| 1455 |
func (cli *Client) UploadKeys(req *ReqUploadKeys) (resp *RespUploadKeys, err error) { |
| 1456 |
urlPath := cli.BuildClientURL("v3", "keys", "upload") |
| 1457 |
_, err = cli.MakeRequest("POST", urlPath, req, &resp) |
| 1458 |
return |
| 1459 |
} |
| 1460 |
|
| 1461 |
func (cli *Client) QueryKeys(req *ReqQueryKeys) (resp *RespQueryKeys, err error) { |
| 1462 |
urlPath := cli.BuildClientURL("v3", "keys", "query") |
| 1463 |
_, err = cli.MakeRequest("POST", urlPath, req, &resp) |
| 1464 |
return |
| 1465 |
} |
| 1466 |
|
| 1467 |
func (cli *Client) ClaimKeys(req *ReqClaimKeys) (resp *RespClaimKeys, err error) { |
| 1468 |
urlPath := cli.BuildClientURL("v3", "keys", "claim") |
| 1469 |
_, err = cli.MakeRequest("POST", urlPath, req, &resp) |
| 1470 |
return |
| 1471 |
} |
| 1472 |
|
| 1473 |
func (cli *Client) GetKeyChanges(from, to string) (resp *RespKeyChanges, err error) { |
| 1474 |
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "keys", "changes"}, map[string]string{ |
| 1475 |
"from": from, |
| 1476 |
"to": to, |
| 1477 |
}) |
| 1478 |
_, err = cli.MakeRequest("POST", urlPath, nil, &resp) |
| 1479 |
return |
| 1480 |
} |
| 1481 |
|
| 1482 |
func (cli *Client) SendToDevice(eventType event.Type, req *ReqSendToDevice) (resp *RespSendToDevice, err error) { |
| 1483 |
urlPath := cli.BuildClientURL("v3", "sendToDevice", eventType.String(), cli.TxnID()) |
| 1484 |
_, err = cli.MakeRequest("PUT", urlPath, req, &resp) |
| 1485 |
return |
| 1486 |
} |
| 1487 |
|
| 1488 |
func (cli *Client) GetDevicesInfo() (resp *RespDevicesInfo, err error) { |
| 1489 |
urlPath := cli.BuildClientURL("v3", "devices") |
| 1490 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1491 |
return |
| 1492 |
} |
| 1493 |
|
| 1494 |
func (cli *Client) GetDeviceInfo(deviceID id.DeviceID) (resp *RespDeviceInfo, err error) { |
| 1495 |
urlPath := cli.BuildClientURL("v3", "devices", deviceID) |
| 1496 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1497 |
return |
| 1498 |
} |
| 1499 |
|
| 1500 |
func (cli *Client) SetDeviceInfo(deviceID id.DeviceID, req *ReqDeviceInfo) error { |
| 1501 |
urlPath := cli.BuildClientURL("v3", "devices", deviceID) |
| 1502 |
_, err := cli.MakeRequest("PUT", urlPath, req, nil) |
| 1503 |
return err |
| 1504 |
} |
| 1505 |
|
| 1506 |
func (cli *Client) DeleteDevice(deviceID id.DeviceID, req *ReqDeleteDevice) error { |
| 1507 |
urlPath := cli.BuildClientURL("v3", "devices", deviceID) |
| 1508 |
_, err := cli.MakeRequest("DELETE", urlPath, req, nil) |
| 1509 |
return err |
| 1510 |
} |
| 1511 |
|
| 1512 |
func (cli *Client) DeleteDevices(req *ReqDeleteDevices) error { |
| 1513 |
urlPath := cli.BuildClientURL("v3", "delete_devices") |
| 1514 |
_, err := cli.MakeRequest("DELETE", urlPath, req, nil) |
| 1515 |
return err |
| 1516 |
} |
| 1517 |
|
| 1518 |
type UIACallback = func(*RespUserInteractive) interface{} |
| 1519 |
|
| 1520 |
// UploadCrossSigningKeys uploads the given cross-signing keys to the server. |
| 1521 |
// Because the endpoint requires user-interactive authentication a callback must be provided that, |
| 1522 |
// given the UI auth parameters, produces the required result (or nil to end the flow). |
| 1523 |
func (cli *Client) UploadCrossSigningKeys(keys *UploadCrossSigningKeysReq, uiaCallback UIACallback) error { |
| 1524 |
content, err := cli.MakeFullRequest(FullRequest{ |
| 1525 |
Method: http.MethodPost, |
| 1526 |
URL: cli.BuildClientURL("v3", "keys", "device_signing", "upload"), |
| 1527 |
RequestJSON: keys, |
| 1528 |
SensitiveContent: keys.Auth != nil, |
| 1529 |
}) |
| 1530 |
if respErr, ok := err.(HTTPError); ok && respErr.IsStatus(http.StatusUnauthorized) { |
| 1531 |
// try again with UI auth |
| 1532 |
var uiAuthResp RespUserInteractive |
| 1533 |
if err := json.Unmarshal(content, &uiAuthResp); err != nil { |
| 1534 |
return fmt.Errorf("failed to decode UIA response: %w", err) |
| 1535 |
} |
| 1536 |
auth := uiaCallback(&uiAuthResp) |
| 1537 |
if auth != nil { |
| 1538 |
keys.Auth = auth |
| 1539 |
return cli.UploadCrossSigningKeys(keys, uiaCallback) |
| 1540 |
} |
| 1541 |
} |
| 1542 |
return err |
| 1543 |
} |
| 1544 |
|
| 1545 |
func (cli *Client) UploadSignatures(req *ReqUploadSignatures) (resp *RespUploadSignatures, err error) { |
| 1546 |
urlPath := cli.BuildClientURL("v3", "keys", "signatures", "upload") |
| 1547 |
_, err = cli.MakeRequest("POST", urlPath, req, &resp) |
| 1548 |
return |
| 1549 |
} |
| 1550 |
|
| 1551 |
// GetPushRules returns the push notification rules for the global scope. |
| 1552 |
func (cli *Client) GetPushRules() (*pushrules.PushRuleset, error) { |
| 1553 |
return cli.GetScopedPushRules("global") |
| 1554 |
} |
| 1555 |
|
| 1556 |
// GetScopedPushRules returns the push notification rules for the given scope. |
| 1557 |
func (cli *Client) GetScopedPushRules(scope string) (resp *pushrules.PushRuleset, err error) { |
| 1558 |
u, _ := url.Parse(cli.BuildClientURL("v3", "pushrules", scope)) |
| 1559 |
// client.BuildURL returns the URL without a trailing slash, but the pushrules endpoint requires the slash. |
| 1560 |
u.Path += "/" |
| 1561 |
_, err = cli.MakeRequest("GET", u.String(), nil, &resp) |
| 1562 |
return |
| 1563 |
} |
| 1564 |
|
| 1565 |
func (cli *Client) GetPushRule(scope string, kind pushrules.PushRuleType, ruleID string) (resp *pushrules.PushRule, err error) { |
| 1566 |
urlPath := cli.BuildClientURL("v3", "pushrules", scope, kind, ruleID) |
| 1567 |
_, err = cli.MakeRequest("GET", urlPath, nil, &resp) |
| 1568 |
if resp != nil { |
| 1569 |
resp.Type = kind |
| 1570 |
} |
| 1571 |
return |
| 1572 |
} |
| 1573 |
|
| 1574 |
func (cli *Client) DeletePushRule(scope string, kind pushrules.PushRuleType, ruleID string) error { |
| 1575 |
urlPath := cli.BuildClientURL("v3", "pushrules", scope, kind, ruleID) |
| 1576 |
_, err := cli.MakeRequest("DELETE", urlPath, nil, nil) |
| 1577 |
return err |
| 1578 |
} |
| 1579 |
|
| 1580 |
func (cli *Client) PutPushRule(scope string, kind pushrules.PushRuleType, ruleID string, req *ReqPutPushRule) error { |
| 1581 |
query := make(map[string]string) |
| 1582 |
if len(req.After) > 0 { |
| 1583 |
query["after"] = req.After |
| 1584 |
} |
| 1585 |
if len(req.Before) > 0 { |
| 1586 |
query["before"] = req.Before |
| 1587 |
} |
| 1588 |
urlPath := cli.BuildURLWithQuery(ClientURLPath{"v3", "pushrules", scope, kind, ruleID}, query) |
| 1589 |
_, err := cli.MakeRequest("PUT", urlPath, req, nil) |
| 1590 |
return err |
| 1591 |
} |
| 1592 |
|
| 1593 |
// BatchSend sends a batch of historical events into a room. This is only available for appservices. |
| 1594 |
// |
| 1595 |
// See https://github.com/matrix-org/matrix-doc/pull/2716 for more info. |
| 1596 |
func (cli *Client) BatchSend(roomID id.RoomID, req *ReqBatchSend) (resp *RespBatchSend, err error) { |
| 1597 |
path := ClientURLPath{"unstable", "org.matrix.msc2716", "rooms", roomID, "batch_send"} |
| 1598 |
query := map[string]string{ |
| 1599 |
"prev_event_id": req.PrevEventID.String(), |
| 1600 |
} |
| 1601 |
if len(req.BatchID) > 0 { |
| 1602 |
query["batch_id"] = req.BatchID.String() |
| 1603 |
} |
| 1604 |
_, err = cli.MakeRequest("POST", cli.BuildURLWithQuery(path, query), req, &resp) |
| 1605 |
return |
| 1606 |
} |
| 1607 |
|
| 1608 |
// TxnID returns the next transaction ID. |
| 1609 |
func (cli *Client) TxnID() string { |
| 1610 |
txnID := atomic.AddInt32(&cli.txnID, 1) |
| 1611 |
return fmt.Sprintf("mautrix-go_%d_%d", time.Now().UnixNano(), txnID) |
| 1612 |
} |
| 1613 |
|
| 1614 |
// NewClient creates a new Matrix Client ready for syncing |
| 1615 |
func NewClient(homeserverURL string, userID id.UserID, accessToken string) (*Client, error) { |
| 1616 |
hsURL, err := parseAndNormalizeBaseURL(homeserverURL) |
| 1617 |
if err != nil { |
| 1618 |
return nil, err |
| 1619 |
} |
| 1620 |
return &Client{ |
| 1621 |
AccessToken: accessToken, |
| 1622 |
UserAgent: DefaultUserAgent, |
| 1623 |
HomeserverURL: hsURL, |
| 1624 |
UserID: userID, |
| 1625 |
Client: &http.Client{Timeout: 180 * time.Second}, |
| 1626 |
Syncer: NewDefaultSyncer(), |
| 1627 |
Logger: stubLogger, |
| 1628 |
// By default, use an in-memory store which will never save filter ids / next batch tokens to disk. |
| 1629 |
// The client will work with this storer: it just won't remember across restarts. |
| 1630 |
// In practice, a database backend should be used. |
| 1631 |
Store: NewInMemoryStore(), |
| 1632 |
}, nil |
| 1633 |
} |