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/xmpp/xmpp.go

71 lines
1.5 KiB

package xmpp
import (
"fmt"
"log"
"net"
"strings"
"git.hacknology.de/projekte/spaceapi"
"github.com/mattn/go-xmpp"
)
func AddXMPPListener(storage *spaceapi.Storage, jid, password, target, handle string) error {
xmppHost, err := lookupHost(jid)
if err != nil {
return fmt.Errorf("can not find SRV record: %s", err)
}
log.Printf("Connecting to %s as %s", xmppHost, jid)
client, err := xmpp.NewClientNoTLS(xmppHost, jid, password, false)
if err != nil {
return fmt.Errorf("can not connect to server: %s", err)
}
if _, err := client.JoinMUCNoHistory(target, handle); err != nil {
return fmt.Errorf("can not join room: %s", err)
}
storage.AddListener(func(status spaceapi.SpaceStatus) {
if status.State.Open == nil {
return
}
msg := "Space is now OPEN!"
if !*status.State.Open {
msg = "Space is now CLOSED!"
}
if _, err := client.Send(xmpp.Chat{
Remote: target,
Type: "groupchat",
Text: msg,
}); err != nil {
log.Printf("Error sending status update: %s", err)
}
})
return nil
}
const defaultClientPort = 5222
func lookupHost(jid string) (string, error) {
if !strings.Contains(jid, "@") {
return "", fmt.Errorf("not a valid JID: %s", jid)
}
parts := strings.SplitN(jid, "@", 2)
_, addrs, err := net.LookupSRV("xmpp-client", "tcp", parts[1])
if err != nil {
return "", fmt.Errorf("%s", err)
}
if len(addrs) == 0 {
return fmt.Sprintf("%s:%d", parts[1], defaultClientPort), nil
}
return fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port), nil
}