feat(notifications): add ntfy support (#1323)

* feat(notifications): add ntfy support

* fix(test): update

* fix: added missing semicolon
This commit is contained in:
ze0s 2023-12-30 13:49:06 +01:00 committed by GitHub
parent 3234f0d919
commit 3dd1629a3f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 197 additions and 17 deletions

View file

@ -80,6 +80,7 @@ const (
NotificationTypeSlack NotificationType = "SLACK"
NotificationTypeTelegram NotificationType = "TELEGRAM"
NotificationTypeGotify NotificationType = "GOTIFY"
NotificationTypeNtfy NotificationType = "NTFY"
NotificationTypeLunaSea NotificationType = "LUNASEA"
)

View file

@ -91,8 +91,6 @@ func setupAuthHandler() {
}
func TestAuthHandlerLogin(t *testing.T) {
t.Parallel()
logger := zerolog.Nop()
encoder := encoder{}
cookieStore := sessions.NewCookieStore([]byte("test"))
@ -156,8 +154,6 @@ func TestAuthHandlerLogin(t *testing.T) {
}
func TestAuthHandlerValidateOK(t *testing.T) {
t.Parallel()
logger := zerolog.Nop()
encoder := encoder{}
cookieStore := sessions.NewCookieStore([]byte("test"))
@ -233,8 +229,6 @@ func TestAuthHandlerValidateOK(t *testing.T) {
}
func TestAuthHandlerValidateBad(t *testing.T) {
t.Parallel()
logger := zerolog.Nop()
encoder := encoder{}
cookieStore := sessions.NewCookieStore([]byte("test"))
@ -284,8 +278,6 @@ func TestAuthHandlerValidateBad(t *testing.T) {
}
func TestAuthHandlerLoginBad(t *testing.T) {
t.Parallel()
logger := zerolog.Nop()
encoder := encoder{}
cookieStore := sessions.NewCookieStore([]byte("test"))
@ -335,8 +327,6 @@ func TestAuthHandlerLoginBad(t *testing.T) {
}
func TestAuthHandlerLogout(t *testing.T) {
t.Parallel()
logger := zerolog.Nop()
encoder := encoder{}
cookieStore := sessions.NewCookieStore([]byte("test"))
@ -419,7 +409,7 @@ func TestAuthHandlerLogout(t *testing.T) {
defer resp.Body.Close()
if status := resp.StatusCode; status != http.StatusNoContent {
t.Errorf("validate: handler returned wrong status code: got %v want %v", status, http.StatusNoContent)
t.Errorf("logout: handler returned wrong status code: got %v want %v", status, http.StatusNoContent)
}
//if v := resp.Header.Get("Set-Cookie"); v != "" {

View file

@ -5,6 +5,7 @@ import (
"strings"
"github.com/autobrr/autobrr/internal/domain"
"github.com/dustin/go-humanize"
)
@ -26,12 +27,11 @@ func (b *NotificationBuilderPlainText) BuildBody(payload domain.NotificationPayl
buildPart(payload.Status != "", "\nStatus: %v", payload.Status.String())
buildPart(payload.Indexer != "", "\nIndexer: %v", payload.Indexer)
buildPart(payload.Filter != "", "\nFilter: %v", payload.Filter)
buildPart(payload.Action != "", "\nAction: %v Type: %v", payload.Action, payload.ActionType)
buildPart(len(payload.Rejections) > 0, "\nRejections: %v", strings.Join(payload.Rejections, ", "))
buildPart(payload.Action != "", "\nAction: %v: %v", payload.ActionType, payload.Action)
if payload.Action != "" && payload.ActionClient != "" {
parts = append(parts, fmt.Sprintf(" Client: %v", payload.ActionClient))
}
buildPart(len(payload.Rejections) > 0, "\nRejections: %v", strings.Join(payload.Rejections, ", "))
return strings.Join(parts, "\n")
}
@ -42,7 +42,7 @@ func (b *NotificationBuilderPlainText) BuildTitle(event domain.NotificationEvent
domain.NotificationEventAppUpdateAvailable: "Autobrr update available",
domain.NotificationEventPushApproved: "Push Approved",
domain.NotificationEventPushRejected: "Push Rejected",
domain.NotificationEventPushError: "Error",
domain.NotificationEventPushError: "Push Error",
domain.NotificationEventIRCDisconnected: "IRC Disconnected",
domain.NotificationEventIRCReconnected: "IRC Reconnected",
domain.NotificationEventTest: "Test",

View file

@ -0,0 +1,131 @@
// Copyright (c) 2021 - 2023, Ludvig Lundgren and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later
package notification
import (
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/autobrr/autobrr/internal/domain"
"github.com/autobrr/autobrr/pkg/errors"
"github.com/autobrr/autobrr/pkg/sharedhttp"
"github.com/rs/zerolog"
)
type ntfyMessage struct {
Message string `json:"message"`
Title string `json:"title"`
}
type ntfySender struct {
log zerolog.Logger
Settings domain.Notification
builder NotificationBuilderPlainText
httpClient *http.Client
}
func NewNtfySender(log zerolog.Logger, settings domain.Notification) domain.NotificationSender {
return &ntfySender{
log: log.With().Str("sender", "ntfy").Logger(),
Settings: settings,
builder: NotificationBuilderPlainText{},
httpClient: &http.Client{
Timeout: time.Second * 30,
Transport: sharedhttp.Transport,
},
}
}
func (s *ntfySender) Send(event domain.NotificationEvent, payload domain.NotificationPayload) error {
m := ntfyMessage{
Message: s.builder.BuildBody(payload),
Title: s.builder.BuildTitle(event),
}
req, err := http.NewRequest(http.MethodPost, s.Settings.Host, strings.NewReader(m.Message))
if err != nil {
s.log.Error().Err(err).Msgf("ntfy client request error: %v", event)
return errors.Wrap(err, "could not create request")
}
req.Header.Set("Content-Type", "text/pain")
req.Header.Set("User-Agent", "autobrr")
req.Header.Set("Title", m.Title)
if s.Settings.Priority > 0 {
req.Header.Set("Priority", strconv.Itoa(int(s.Settings.Priority)))
}
// set basic auth or access token
if s.Settings.Username != "" && s.Settings.Password != "" {
req.SetBasicAuth(s.Settings.Username, s.Settings.Password)
} else if s.Settings.Token != "" {
req.Header.Set("Authorization", "Bearer "+s.Settings.Token)
}
res, err := s.httpClient.Do(req)
if err != nil {
s.log.Error().Err(err).Msgf("ntfy client request error: %v", event)
return errors.Wrap(err, "could not make request: %+v", req)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
s.log.Error().Err(err).Msgf("ntfy client request error: %v", event)
return errors.Wrap(err, "could not read data")
}
s.log.Trace().Msgf("ntfy status: %v response: %v", res.StatusCode, string(body))
if res.StatusCode != http.StatusOK {
s.log.Error().Err(err).Msgf("ntfy client request error: %v", string(body))
return errors.New("bad status: %v body: %v", res.StatusCode, string(body))
}
s.log.Debug().Msg("notification successfully sent to ntfy")
return nil
}
func (s *ntfySender) CanSend(event domain.NotificationEvent) bool {
if s.isEnabled() && s.isEnabledEvent(event) {
return true
}
return false
}
func (s *ntfySender) isEnabled() bool {
if s.Settings.Enabled {
if s.Settings.Host == "" {
s.log.Warn().Msg("ntfy missing host")
return false
}
if s.Settings.Token == "" {
s.log.Warn().Msg("ntfy missing application token")
return false
}
return true
}
return false
}
func (s *ntfySender) isEnabledEvent(event domain.NotificationEvent) bool {
for _, e := range s.Settings.Events {
if e == string(event) {
return true
}
}
return false
}

View file

@ -249,6 +249,8 @@ func (s *service) Test(ctx context.Context, notification domain.Notification) er
agent = NewPushoverSender(s.log, notification)
case domain.NotificationTypeGotify:
agent = NewGotifySender(s.log, notification)
case domain.NotificationTypeNtfy:
agent = NewNtfySender(s.log, notification)
case domain.NotificationTypeLunaSea:
agent = NewLunaSeaSender(s.log, notification)
default: