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

123 lines
2.6 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) {
if ev.Sender == userID {
return
}
if ev.RoomID != room {
return
}
msgType, ok := ev.MessageType()
if !ok || msgType != "m.text" {
return
}
body, ok := ev.Body()
if !ok {
log.Printf("[matrix] Message with no body: %#v", ev)
return
}
body = strings.Trim(body, " \t\n")
switch body {
case txt.CommandHelp:
if _, err := cli.SendNotice(room, txt.HelpMessage); err != nil {
log.Printf("Error sending message: %s", err)
}
case txt.CommandState:
state := storage.Status().State
msg := txt.StateUnknown
if state.Open != nil {
switch *state.Open {
case true:
msg = txt.StateOpen
case false:
msg = txt.StateClosed
}
}
if _, err := cli.SendNotice(room, msg); err != nil {
log.Printf("Error sending message: %s", err)
}
case txt.CommandClose, txt.CommandClosed:
storage.Modify(func(status *spaceapi.SpaceStatus) {
open := false
status.State.Open = &open
})
}
})
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.SendNotice(room, msg); err != nil {
log.Printf("Error sending Matrix message: %s", err)
}
}, nil
}