a simple matrix package for basic actions
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.1 KiB

package matrix
import (
"encoding/json"
"fmt"
"gopkg.in/h2non/gentleman.v2"
"gopkg.in/h2non/gentleman.v2/plugins/query"
)
// Sync syncs
func Sync(authinfo Authinfo) (RespSync, error) {
cli := gentleman.New()
cli.URL(authinfo.HomeServer)
req := cli.Request()
req.Path("/_matrix/client/r0/sync")
req.Method("GET")
req.Use(query.Set("access_token", authinfo.AccessToken))
res, err := req.Send()
if err != nil {
fmt.Println("ERR1")
return RespSync{}, err
}
if !res.Ok {
fmt.Println("ERR2")
fmt.Println(res)
return RespSync{}, err
}
var syncReponse RespSync
if err := json.Unmarshal(res.Bytes(), &syncReponse); err != nil {
return RespSync{}, err
}
return syncReponse, nil
}
// SyncPartial syncs the state using sync token obtained in a previous request
// as a timestamp
func SyncPartial(authinfo Authinfo, nextBatch string, eventsChannel chan PackagedEvent) (RespSync, error) {
cli := gentleman.New()
cli.URL(authinfo.HomeServer)
req := cli.Request()
req.Path("/_matrix/client/r0/sync")
req.Method("GET")
req.Use(query.Set("access_token", authinfo.AccessToken))
req.Use(query.Set("since", nextBatch))
req.Use(query.Set("timeout", "1"))
res, err := req.Send()
if err != nil {
fmt.Println("ERR1")
return RespSync{}, err
}
if !res.Ok {
fmt.Println("ERR2")
fmt.Println(res)
return RespSync{}, err
}
// unmarshal the response
var syncReponse RespSync
if err := json.Unmarshal(res.Bytes(), &syncReponse); err != nil {
return RespSync{}, err
}
// accept all room invites
for room := range syncReponse.Rooms.Invite {
err := join(authinfo, room)
if err != nil {
return RespSync{}, fmt.Errorf("could not join room: %s", err)
}
}
// iterate over all new events, insert all new events not from the bot itself into the eventsChannel
for roomname, room := range syncReponse.Rooms.Join {
for _, event := range room.Timeline.Events {
packagedEvent := PackagedEvent{
RoomName: roomname,
Event: event,
}
// if the event recieved is not from ourself, insert the event into the eventsChannel
if event.Sender != authinfo.UserID {
eventsChannel <- packagedEvent
}
}
}
return syncReponse, nil
}