aboutsummaryrefslogtreecommitdiff
path: root/appservice/matrix.go
blob: 88c4b5ddd37a199ac7336547b88245aec8fc3eb4 (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
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
package appservice

import (
	"fmt"
	"net/url"
	"net/http"
	"time"
	"bytes"
	"encoding/json"

	log "github.com/sirupsen/logrus"

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

var httpClient *http.Client

func init() {
	tr := &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    30 * time.Second,
		DisableCompression: true,
	}
	httpClient = &http.Client{Transport: tr}
}

func mxGetApiCall(endpoint string, response interface{}) error {
	log.Debugf("Matrix GET request: %s\n", endpoint)

	req, err := http.NewRequest("GET", config.Server + endpoint, nil)
	if err != nil {
		return err
	}

	return mxDoAndParse(req, response)
}

func mxPutApiCall(endpoint string, data interface{}, response interface{}) error {
	body, err := json.Marshal(data)
	if err != nil {
		return err
	}

	log.Debugf("Matrix PUT request: %s %s\n", endpoint, string(body))

	req, err := http.NewRequest("PUT", config.Server + endpoint, bytes.NewBuffer(body))
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "application/json")

	return mxDoAndParse(req, response)
}

func mxPostApiCall(endpoint string, data interface{}, response interface{}) error {
	body, err := json.Marshal(data)
	if err != nil {
		return err
	}

	log.Debugf("Matrix POST request: %s %s\n", endpoint, string(body))

	req, err := http.NewRequest("POST", config.Server + endpoint, bytes.NewBuffer(body))
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "application/json")

	return mxDoAndParse(req, response)
}

func mxDoAndParse(req *http.Request, response interface{}) error {
	req.Header.Add("Authorization", "Bearer " + registration.AsToken)

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

	if resp.StatusCode != http.StatusOK {
		var e MxError
		err = json.NewDecoder(resp.Body).Decode(&e)
		if err != nil {
			return err
		}
		log.Debugf("Response (%d): %#v\n", resp.StatusCode, e)
		return &e
	}

	err = json.NewDecoder(resp.Body).Decode(response)
	if err != nil {
		return err
	}

	log.Debugf("Response: %#v\n", response)
	return nil
}

// ----

func mxRegisterUser(username string) error {
	req := RegisterRequest{
		Username: username,
	}
	var rep RegisterResponse
	return mxPostApiCall("/_matrix/client/r0/register?kind=user", &req, &rep)
}

func mxProfileDisplayname(userid string, displayname string) error {
	req := ProfileDisplaynameRequest{
		Displayname: displayname,
	}
	var rep struct{}
	err := mxPutApiCall(fmt.Sprintf("/_matrix/client/r0/profile/%s/displayname?user_id=%s",
		url.QueryEscape(userid), url.QueryEscape(userid)),
		&req, &rep)
	return err
}

func mxDirectoryRoom(alias string) (string, error) {
	var rep DirectoryRoomResponse
	err := mxGetApiCall("/_matrix/client/r0/directory/room/" + url.QueryEscape(alias), &rep)
	if err != nil {
		return "", err
	}
	return rep.RoomId, nil
}

func mxCreateRoom(name string, alias string, invite []string) (string, error) {
	rq := CreateRoomRequest{
		Preset: "private_chat",
		RoomAliasName: alias,
		Name: name,
		Topic: "",
		Invite: invite,
		CreationContent: map[string]interface{} {
			"m.federate": false,
		},
		PowerLevels: map[string]interface{} {
			"invite": 100,
		},
	}
	var rep CreateRoomResponse
	err := mxPostApiCall("/_matrix/client/r0/createRoom", &rq, &rep)
	if err != nil {
		return "", err
	}
	return rep.RoomId, nil
}

func mxCreateDirectRoomAs(name string, invite []string, as_user string) (string, error) {
	rq := CreateRoomNoAliasRequest{
		Preset: "private_chat",
		Name: name,
		Topic: "",
		Invite: invite,
		CreationContent: map[string]interface{} {
			"m.federate": false,
		},
		PowerLevels: map[string]interface{} {
			"invite": 100,
		},
		IsDirect: true,
	}
	var rep CreateRoomResponse
	err := mxPostApiCall("/_matrix/client/r0/createRoom?user_id=" + url.QueryEscape(as_user), &rq, &rep)
	if err != nil {
		return "", err
	}
	return rep.RoomId, nil
}

func mxRoomInvite(room string, user string) error {
	rq := RoomInviteRequest{
		UserId: user,
	}
	var rep struct{}
	err := mxPostApiCall("/_matrix/client/r0/rooms/" + url.QueryEscape(room) + "/invite", &rq, &rep)
	return err
}

func mxRoomKick(room string, user string, reason string) error {
	rq := RoomKickRequest{
		UserId: user,
		Reason: reason,
	}
	var rep struct{}
	err := mxPostApiCall("/_matrix/client/r0/rooms/" + url.QueryEscape(room) + "/kick", &rq, &rep)
	return err
}

func mxRoomJoinAs(room string, user string) error {
	rq := struct{}{}
	var rep RoomJoinResponse
	err := mxPostApiCall("/_matrix/client/r0/rooms/" + url.QueryEscape(room) + "/join?user_id=" + url.QueryEscape(user), &rq, &rep)
	return err
}

func mxRoomLeaveAs(room string, user string) error {
	rq := struct{}{}
	var rep struct{}
	err := mxPostApiCall("/_matrix/client/r0/rooms/" + url.QueryEscape(room) + "/leave?user_id=" + url.QueryEscape(user), &rq, &rep)
	return err
}

func mxSendMessageAs(room string, typ string, body string, user string) error {
	txn_id := time.Now().UnixNano()
	rq := RoomSendMessageRequest{
		MsgType: typ,
		Body: body,
	}
	var rep RoomSendResponse
	err := mxPutApiCall(fmt.Sprintf(
		"/_matrix/client/r0/rooms/%s/send/m.room.message/%d?user_id=%s",
		url.QueryEscape(room), txn_id, url.QueryEscape(user)),
		&rq, &rep)
	return err
}