godyn/notifications/notification.go
2023-10-16 15:52:17 +02:00

95 lines
2.4 KiB
Go

package notifications
import (
"errors"
"net/http"
"strconv"
"strings"
"time"
"velvettear/godyn/config"
"velvettear/godyn/log"
)
const PRIORITY_MAX = 5
const PRIORITY_HIGH = 4
const PRIORITY_DEFAULT = 3
const PRIORITY_LOW = 2
const PRIORITY_MIN = 1
// exported function(s)
func Send(notification Notification) {
if !config.NotificationEnabled() {
return
}
timestamp := time.Now().UnixMilli()
url, error := getNotificationUrl()
if error != nil {
log.Warning("encountered an error sending a notification", error.Error())
return
}
request, error := http.NewRequest("POST", url, strings.NewReader(notification.Message))
if error != nil {
log.Error("encountered an error creating a notification http request", error.Error())
return
}
request.Header.Set("Title", notification.Title)
request.Header.Set("Priority", strconv.Itoa(notification.getPriority()))
if notification.hasEmoji() {
request.Header.Set("Tags", notification.Emoji)
}
authorize(request)
response, error := http.DefaultClient.Do(request)
if error != nil {
log.ErrorTimed("encountered an error sending a notification", timestamp, error.Error())
return
}
if response.StatusCode != 200 {
log.ErrorTimed("probably encountered an error sending a notification", timestamp, "status code: "+strconv.Itoa(response.StatusCode))
return
}
log.DebugTimed("successfully sent a notification", timestamp)
}
// unexported function(s)
func getNotificationUrl() (string, error) {
url := config.NotificationUrl()
if len(url) == 0 {
return "", errors.New("notification url is not configured")
}
topic := config.NotificationTopic()
if len(topic) == 0 {
return "", errors.New("notification topic is not configured")
}
if !strings.HasSuffix(url, "/") {
url += "/"
}
return url + topic, nil
}
func authorize(request *http.Request) {
username := config.NotificationUsername()
password := config.NotificationPassword()
if len(username) == 0 || len(password) == 0 {
return
}
request.SetBasicAuth(username, password)
}
func (notification *Notification) hasEmoji() bool {
return len(notification.Emoji) > 0
}
func (notification *Notification) getPriority() int {
if notification.Priority < PRIORITY_MIN || notification.Priority > PRIORITY_MAX {
notification.Priority = PRIORITY_DEFAULT
}
return notification.Priority
}
// struct(s)
type Notification struct {
Title string
Message string
Emoji string
Priority int
}