-
Notifications
You must be signed in to change notification settings - Fork 1
/
matrix.nim
75 lines (53 loc) · 1.62 KB
/
matrix.nim
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
# https://matrix.org/docs/guides/client-server-api
# https://matrix.org/docs/spec/
# Main program
from os import nil
import json
import cps
import types, evq, http, httpserver, httpclient, logger
const log_tag = "matrix"
type
MatrixClient = ref object
url: string
token: string
MatrixLoginReq = object
`type`: string
user: string
password: string
MatrixLoginRsp = object
user_id: string
access_token: string
home_server: string
device_id: string
template debug(mc: MatrixClient, s: string) =
discard
proc post(mc: MatrixClient, meth: string, req: JsonNode): JsonNode {.cps:C.} =
let client = httpClient.newClient()
mc.debug("< " & meth & ": " & $ req)
let rsp = client.request("POST", mc.url & meth, $req)
result = client.readBody(rsp).parseJson()
mc.debug("> " & meth & ": " & $result)
proc get(mc: MatrixClient, meth: string): JsonNode {.cps:C.} =
let client = httpClient.newClient()
let rsp = client.request("GET", mc.url & meth)
result = client.readBody(rsp).parseJson()
mc.debug("> " & meth & ": " & $result)
proc newMatrixClient*(server: string): MatrixClient =
MatrixClient(
url: "https://" & server & "/_matrix/client/r0/"
)
proc login*(mc: MatrixClient, user, password: string) {.cps:C.} =
let req = % MatrixLoginReq(
type: "m.login.password",
user: user,
password: password
)
let rsp = mc.post("login", req)
if rsp.hasKey "user_id":
let lr = rsp.to(MatrixLoginRsp)
mc.token = lr.access_token
else:
warn $rsp["error"]
proc sync*(mc: MatrixClient) {.cps:C.} =
let s = mc.get("sync?access_token=" & mc.token)
echo s