Co-authored-by: Timo Behrendt <t.behrendt@t00n.de> Co-committed-by: Timo Behrendt <t.behrendt@t00n.de>
88 lines
1.7 KiB
Go
88 lines
1.7 KiB
Go
package notificationProviderGotify
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
)
|
|
|
|
type NotificationProviderImplGotifyConfig struct {
|
|
Url string `yaml:"url"`
|
|
Token string `yaml:"token"`
|
|
Priority int `yaml:"priority"`
|
|
}
|
|
|
|
type NotificationProviderImplGotify struct {
|
|
Url url.URL
|
|
Token string
|
|
Priority int
|
|
HTTPClient *http.Client
|
|
}
|
|
|
|
func New(config NotificationProviderImplGotifyConfig) (*NotificationProviderImplGotify, error) {
|
|
if config.Url == "" {
|
|
return nil, fmt.Errorf("url is required")
|
|
}
|
|
|
|
url, err := url.Parse(config.Url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if config.Token == "" {
|
|
return nil, fmt.Errorf("token is required")
|
|
}
|
|
|
|
if config.Priority < 0 || config.Priority > 4 {
|
|
return nil, fmt.Errorf("priority must be between 0 and 4")
|
|
}
|
|
|
|
return &NotificationProviderImplGotify{
|
|
*url,
|
|
config.Token,
|
|
config.Priority,
|
|
&http.Client{},
|
|
}, nil
|
|
}
|
|
|
|
func (p *NotificationProviderImplGotify) SendNotification(title string, message string) error {
|
|
type GotifyMessage struct {
|
|
Message string `json:"message"`
|
|
Title string `json:"title"`
|
|
Priority int `json:"priority"`
|
|
}
|
|
|
|
messageJson, err := json.Marshal(GotifyMessage{
|
|
message,
|
|
title,
|
|
p.Priority,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
messageUrl := p.Url
|
|
messageUrl.JoinPath("message")
|
|
messageUrl.Query().Add("token", p.Token)
|
|
|
|
req, err := http.NewRequest("POST", messageUrl.String(), bytes.NewBuffer(messageJson))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
res, err := p.HTTPClient.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if res.StatusCode != 200 {
|
|
return fmt.Errorf("unexpected status code: %d", res.StatusCode)
|
|
}
|
|
|
|
return nil
|
|
}
|