Correctly get room ID

Signed-off-by: Marcus Noble <github@marcusnoble.co.uk>
This commit is contained in:
Marcus Noble 2021-12-05 15:30:58 +00:00
parent 538673281e
commit 2a79d08e71
Signed by: AverageMarcus
GPG Key ID: B8F2DB8A7AEBAF78
3 changed files with 46 additions and 44 deletions

View File

@ -31,7 +31,7 @@ func HandleAlertmanagerPayloadPost(c *fiber.Ctx) error {
message = fmt.Sprintf("☑️ %s", alert.Annotations["description"])
}
_, err := matrixClient.SendText(id.RoomID(*defaultRoom), message)
_, err := matrixClient.SendText(id.RoomID(getRoom(*defaultRoom)), message)
if err != nil {
fmt.Println("Failed sending to Matrix", err)
if httpErr, ok := err.(mautrix.HTTPError); ok {

44
main.go
View File

@ -58,6 +58,50 @@ func main() {
app.Listen(fmt.Sprintf(":%s", port))
}
func getRoom(roomID string) string {
room := parseRoom(roomID)
if strings.HasPrefix(room, "#") || !strings.HasPrefix("!", room) {
if !strings.HasPrefix(room, "#") {
room = fmt.Sprintf("#%s", room)
}
resp, err := matrixClient.ResolveAlias(id.RoomAlias(room))
if err == nil {
room = resp.RoomID.String()
} else {
room = strings.Replace(room, "#", "!", 1)
}
}
return room
}
func parseRoom(room string) string {
prefix := ""
local := ""
domain := ""
parts := strings.Split(room, ":")
if len(parts) == 2 {
domain = parts[1]
} else {
domain = matrixClient.HomeserverURL.Host
}
if strings.HasPrefix(parts[0], "!") {
prefix = "!"
parts[0] = strings.TrimPrefix(parts[0], "!")
}
if strings.HasPrefix(parts[0], "#") {
prefix = "#"
parts[0] = strings.TrimPrefix(parts[0], "#")
}
local = parts[0]
return fmt.Sprintf("%s%s:%s", prefix, local, domain)
}
func HandlePayloadPost(c *fiber.Ctx) error {
payload := Payload{}

View File

@ -2,10 +2,6 @@ package main
import (
"errors"
"fmt"
"strings"
"maunium.net/go/mautrix/id"
)
type PayloadType string
@ -38,45 +34,7 @@ func (p *Payload) Validate(defaultRoom *string) error {
return errors.New("'roomID' is required")
}
room := parseRoom(p.RoomID)
if strings.HasPrefix(room, "#") || !strings.HasPrefix("!", room) {
if !strings.HasPrefix(room, "#") {
room = fmt.Sprintf("#%s", room)
}
resp, err := matrixClient.ResolveAlias(id.RoomAlias(room))
if err == nil {
p.RoomID = resp.RoomID.String()
} else {
p.RoomID = strings.Replace(room, "#", "!", 1)
}
}
p.RoomID = getRoom(p.RoomID)
return nil
}
func parseRoom(room string) string {
prefix := ""
local := ""
domain := ""
parts := strings.Split(room, ":")
if len(parts) == 2 {
domain = parts[1]
} else {
domain = matrixClient.HomeserverURL.Host
}
if strings.HasPrefix(parts[0], "!") {
prefix = "!"
parts[0] = strings.TrimPrefix(parts[0], "!")
}
if strings.HasPrefix(parts[0], "#") {
prefix = "#"
parts[0] = strings.TrimPrefix(parts[0], "#")
}
local = parts[0]
return fmt.Sprintf("%s%s:%s", prefix, local, domain)
}