2024-03-29 08:06:23 +01:00
|
|
|
package notification
|
|
|
|
|
|
|
|
import (
|
2024-03-29 20:24:53 +01:00
|
|
|
// External
|
|
|
|
werr "git.gibonuddevalla.se/go/wrappederror"
|
|
|
|
|
2024-03-29 08:06:23 +01:00
|
|
|
// Standard
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2024-03-29 20:24:53 +01:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-03-29 08:06:23 +01:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type NTFY struct {
|
2024-03-29 20:24:53 +01:00
|
|
|
URL string
|
|
|
|
Prio int
|
|
|
|
AcknowledgeURL string
|
2024-03-29 08:06:23 +01:00
|
|
|
}
|
|
|
|
|
2024-03-29 20:24:53 +01:00
|
|
|
func NewNTFY(config []byte, prio int, ackURL string) (instance NTFY, err error) {
|
2024-03-29 08:06:23 +01:00
|
|
|
err = json.Unmarshal(config, &instance)
|
|
|
|
if err != nil {
|
2024-03-29 20:24:53 +01:00
|
|
|
err = werr.Wrap(err).WithCode("002-0001").WithData(config)
|
|
|
|
return
|
2024-03-29 08:06:23 +01:00
|
|
|
}
|
2024-03-29 20:24:53 +01:00
|
|
|
instance.Prio = prio
|
|
|
|
instance.AcknowledgeURL = ackURL
|
2024-03-29 08:06:23 +01:00
|
|
|
return instance, nil
|
|
|
|
}
|
|
|
|
|
2024-03-29 20:24:53 +01:00
|
|
|
func (ntfy NTFY) GetPrio() int {
|
|
|
|
return ntfy.Prio
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ntfy NTFY) Send(uuid string, msg []byte) (err error) {
|
|
|
|
var req *http.Request
|
|
|
|
var res *http.Response
|
|
|
|
req, err = http.NewRequest("POST", ntfy.URL, bytes.NewReader(msg))
|
|
|
|
if err != nil {
|
|
|
|
err = werr.Wrap(err).WithCode("002-0002").WithData(ntfy.URL)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ackURL := fmt.Sprintf("http, OK, %s/notification/ack?uuid=%s", ntfy.AcknowledgeURL, uuid)
|
|
|
|
req.Header.Add("X-Actions", ackURL)
|
2024-03-30 17:43:21 +01:00
|
|
|
req.Header.Add("X-Priority", "5")
|
|
|
|
req.Header.Add("X-Tags", "calendar")
|
2024-03-29 20:24:53 +01:00
|
|
|
|
|
|
|
res, err = http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
err = werr.Wrap(err).WithCode("002-0003")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
body, _ := io.ReadAll(res.Body)
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
err = werr.New("Invalid NTFY response").WithCode("002-0004").WithData(body)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ntfyResp := struct {
|
|
|
|
ID string
|
|
|
|
}{}
|
|
|
|
err = json.Unmarshal(body, &ntfyResp)
|
|
|
|
if err != nil {
|
|
|
|
err = werr.Wrap(err).WithCode("002-0005").WithData(body)
|
|
|
|
return
|
|
|
|
}
|
2024-03-29 08:06:23 +01:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|