aboutsummaryrefslogtreecommitdiff
path: root/mxlib/mediaobject.go
blob: a369cfe01438bc21f149d2fa9a499a7087a4cb98 (plain) (blame)
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
package mxlib

import (
	"fmt"
	"io"
	"net/http"
	"net/url"

	"git.deuxfleurs.fr/Deuxfleurs/easybridge/connector"
)

type MediaObject struct {
	mxClient   *Client
	filename   string
	size       int64
	mimetype   string
	imageSize  *connector.ImageSize
	MxcServer  string
	MxcMediaId string
}

func (m *MediaObject) Filename() string {
	return m.filename
}

func (m *MediaObject) Size() int64 {
	return m.size
}

func (m *MediaObject) Mimetype() string {
	return m.mimetype
}

func (m *MediaObject) ImageSize() *connector.ImageSize {
	return m.imageSize
}

func (m *MediaObject) Read() (io.ReadCloser, error) {
	req, err := http.NewRequest("GET", m.URL(), nil)
	if err != nil {
		return nil, err
	}

	req.Header.Add("Authorization", "Bearer "+m.mxClient.Token)

	resp, err := m.mxClient.httpClient.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP error %d", resp.StatusCode)
	}

	return resp.Body, nil
}

func (m *MediaObject) URL() string {
	return fmt.Sprintf("%s/_matrix/media/r0/download/%s/%s/%s",
		m.mxClient.Server, m.MxcServer, m.MxcMediaId, url.QueryEscape(m.filename))
}

func (m *MediaObject) MxcUri() string {
	return fmt.Sprintf("mxc://%s/%s", m.MxcServer, m.MxcMediaId)
}