cluster

Infrastructure files for Nordgedanken and Midnightthoughts.
git clone git://archive.git.mtrnord.blog/MTRNord/cluster.git
Log | Files | Refs | README

matrix.go (1362B)


      1 // matrix.go — low-level Matrix client helpers not wrapped by mautrix.
      2 package main
      3 
      4 import (
      5 	"context"
      6 	"encoding/json"
      7 	"fmt"
      8 	"io"
      9 	"net/http"
     10 	"net/url"
     11 	"strings"
     12 
     13 	"maunium.net/go/mautrix"
     14 )
     15 
     16 // matrixGetJSON makes an authenticated GET to the homeserver and JSON-decodes
     17 // the response. Used for endpoints not wrapped by the mautrix client.
     18 func matrixGetJSON(ctx context.Context, client *mautrix.Client, path string, out interface{}) error {
     19 	base := strings.TrimRight(client.HomeserverURL.String(), "/")
     20 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+path, nil)
     21 	if err != nil {
     22 		return err
     23 	}
     24 	req.Header.Set("Authorization", "Bearer "+client.AccessToken)
     25 	resp, err := http.DefaultClient.Do(req)
     26 	if err != nil {
     27 		return err
     28 	}
     29 	defer resp.Body.Close()
     30 	body, err := io.ReadAll(resp.Body)
     31 	if err != nil {
     32 		return err
     33 	}
     34 	if resp.StatusCode != http.StatusOK {
     35 		return fmt.Errorf("HTTP %d: %s", resp.StatusCode, body)
     36 	}
     37 	return json.Unmarshal(body, out)
     38 }
     39 
     40 // getAccountData fetches a single account-data event for the authenticated user.
     41 func getAccountData(ctx context.Context, client *mautrix.Client, eventType string, out interface{}) error {
     42 	path := "/_matrix/client/v3/user/" +
     43 		url.PathEscape(client.UserID.String()) +
     44 		"/account_data/" +
     45 		url.PathEscape(eventType)
     46 	return matrixGetJSON(ctx, client, path, out)
     47 }