A simple server for serving our SpaceAPI interactively.
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.
spaceapi/matrix/matrix.go

77 lines
1.7 KiB

package matrix
import (
"fmt"
"log"
"strings"
"git.hacknology.de/projekte/spaceapi"
"git.hacknology.de/projekte/spaceapi/txt"
"github.com/matrix-org/gomatrix"
)
// Listener creates a listener, that will broadcast the spaceapi status to a Matrix room.
func Listener(storage *spaceapi.Storage, homeServer, userID, token, room string) (spaceapi.Listener, error) {
if !strings.HasPrefix(room, "!") {
return nil, fmt.Errorf("room needs to start with a '!'")
}
log.Printf("[matrix] Connecting to %s as %s", homeServer, userID)
cli, err := gomatrix.NewClient(homeServer, userID, token)
if err != nil {
return nil, fmt.Errorf("error creating client: %s", err)
}
rooms, err := cli.JoinedRooms()
if err != nil {
return nil, fmt.Errorf("error getting room list: %s", err)
}
joined := false
for _, r := range rooms.JoinedRooms {
if r == room {
log.Printf("[matrix] Room already joined.")
joined = true
}
}
if !joined {
log.Printf("[matrix] Joining room %q", room)
if _, err := cli.JoinRoom(room, "", nil); err != nil {
return nil, fmt.Errorf("error joining room: %s", err)
}
}
syncer := cli.Syncer.(*gomatrix.DefaultSyncer)
syncer.OnEventType("m.room.message", func(ev *gomatrix.Event) {
// TODO react to events
})
go func() {
for {
if err := cli.Sync(); err != nil {
log.Printf("Error during sync: %s", err)
}
}
}()
return func(old, new spaceapi.SpaceStatus) {
if new.State.Open == nil {
return
}
if old.State.Open == new.State.Open {
return
}
msg := txt.TransitionToOpen
if !*new.State.Open {
msg = txt.TransitionToClosed
}
if _, err := cli.SendText(room, msg); err != nil {
log.Printf("Error sending Matrix message: %s", err)
}
}, nil
}