-
Notifications
You must be signed in to change notification settings - Fork 26
/
matrix.go
64 lines (59 loc) · 1.57 KB
/
matrix.go
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
package main
import (
"context"
"errors"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/id"
)
func (mtx *configMatrix) enabled() bool {
return mtx != nil && mtx.Enabled && mtx.HomeServer != "" && mtx.Username != "" && mtx.Password != "" && mtx.Room != ""
}
func (a *goBlog) getMatrixClient(mtx *configMatrix) (*mautrix.Client, error) {
if !mtx.enabled() {
return nil, errors.New("matrix not configured")
}
mtx.clientInit.Do(func() {
mtxClient, err := mautrix.NewClient(mtx.HomeServer, "", "")
if err != nil {
mtx.err = err
return
}
mtxClient.Client = a.httpClient
_, err = mtxClient.Login(context.Background(), &mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{
Type: mautrix.IdentifierTypeUser,
User: mtx.Username,
},
Password: mtx.Password,
InitialDeviceDisplayName: "GoBlog",
StoreCredentials: true,
StoreHomeserverURL: true,
DeviceID: id.DeviceID(mtx.DeviceId),
})
if err != nil {
mtx.err = err
return
}
mtx.client = mtxClient
})
return mtx.client, mtx.err
}
func (a *goBlog) sendMatrix(mtx *configMatrix, message string) (string, error) {
if !mtx.enabled() {
return "", nil
}
mtxClient, err := a.getMatrixClient(mtx)
if err != nil {
return "", err
}
resolveResp, err := mtxClient.ResolveAlias(context.Background(), id.RoomAlias(mtx.Room))
if err != nil {
return "", err
}
resp, err := mtxClient.SendText(context.Background(), resolveResp.RoomID, message)
if err != nil {
return "", err
}
return resp.EventID.String(), nil
}