From 77948d7654eadc223e63259c25adf171adde0477 Mon Sep 17 00:00:00 2001 From: MouldWarpMole <147707334+MouldWarpMole@users.noreply.github.com> Date: Sat, 14 Oct 2023 12:08:12 +0200 Subject: [PATCH] feat(notifications): Add Gotify (#1180) feat(notifications): Add Gotify (resolves #513) --- internal/database/notification.go | 12 +- internal/domain/notification.go | 1 + internal/notification/gotify.go | 176 +++++++++++++++++++ internal/notification/service.go | 4 + web/src/domain/constants.ts | 4 + web/src/forms/settings/NotificationForms.tsx | 29 ++- web/src/screens/settings/Notifications.tsx | 10 +- web/src/types/Notification.d.ts | 3 +- 8 files changed, 233 insertions(+), 6 deletions(-) create mode 100644 internal/notification/gotify.go diff --git a/internal/database/notification.go b/internal/database/notification.go index d05b8f0..57c2b5d 100644 --- a/internal/database/notification.go +++ b/internal/database/notification.go @@ -31,7 +31,7 @@ func NewNotificationRepo(log logger.Logger, db *DB) domain.NotificationRepo { func (r *NotificationRepo) Find(ctx context.Context, params domain.NotificationQueryParams) ([]domain.Notification, int, error) { queryBuilder := r.db.squirrel. - Select("id", "name", "type", "enabled", "events", "webhook", "token", "api_key", "channel", "priority", "topic", "created_at", "updated_at", "COUNT(*) OVER() AS total_count"). + Select("id", "name", "type", "enabled", "events", "webhook", "token", "api_key", "channel", "priority", "topic", "host", "created_at", "updated_at", "COUNT(*) OVER() AS total_count"). From("notification"). OrderBy("name") @@ -52,9 +52,9 @@ func (r *NotificationRepo) Find(ctx context.Context, params domain.NotificationQ for rows.Next() { var n domain.Notification - var webhook, token, apiKey, channel, topic sql.NullString + var webhook, token, apiKey, channel, host, topic sql.NullString - if err := rows.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &webhook, &token, &apiKey, &channel, &n.Priority, &topic, &n.CreatedAt, &n.UpdatedAt, &totalCount); err != nil { + if err := rows.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &webhook, &token, &apiKey, &channel, &n.Priority, &topic, &host, &n.CreatedAt, &n.UpdatedAt, &totalCount); err != nil { return nil, 0, errors.Wrap(err, "error scanning row") } @@ -63,6 +63,7 @@ func (r *NotificationRepo) Find(ctx context.Context, params domain.NotificationQ n.Token = token.String n.Channel = channel.String n.Topic = topic.String + n.Host = host.String notifications = append(notifications, n) } @@ -182,6 +183,7 @@ func (r *NotificationRepo) Store(ctx context.Context, notification domain.Notifi apiKey := toNullString(notification.APIKey) channel := toNullString(notification.Channel) topic := toNullString(notification.Topic) + host := toNullString(notification.Host) queryBuilder := r.db.squirrel. Insert("notification"). @@ -196,6 +198,7 @@ func (r *NotificationRepo) Store(ctx context.Context, notification domain.Notifi "channel", "priority", "topic", + "host", ). Values( notification.Name, @@ -208,6 +211,7 @@ func (r *NotificationRepo) Store(ctx context.Context, notification domain.Notifi channel, notification.Priority, topic, + host, ). Suffix("RETURNING id").RunWith(r.db.handler) @@ -230,6 +234,7 @@ func (r *NotificationRepo) Update(ctx context.Context, notification domain.Notif apiKey := toNullString(notification.APIKey) channel := toNullString(notification.Channel) topic := toNullString(notification.Topic) + host := toNullString(notification.Host) queryBuilder := r.db.squirrel. Update("notification"). @@ -243,6 +248,7 @@ func (r *NotificationRepo) Update(ctx context.Context, notification domain.Notif Set("channel", channel). Set("priority", notification.Priority). Set("topic", topic). + Set("host", host). Set("updated_at", sq.Expr("CURRENT_TIMESTAMP")). Where(sq.Eq{"id": notification.ID}) diff --git a/internal/domain/notification.go b/internal/domain/notification.go index 91fd50f..8455df6 100644 --- a/internal/domain/notification.go +++ b/internal/domain/notification.go @@ -79,6 +79,7 @@ const ( NotificationTypeRocketChat NotificationType = "ROCKETCHAT" NotificationTypeSlack NotificationType = "SLACK" NotificationTypeTelegram NotificationType = "TELEGRAM" + NotificationTypeGotify NotificationType = "GOTIFY" ) type NotificationEvent string diff --git a/internal/notification/gotify.go b/internal/notification/gotify.go new file mode 100644 index 0000000..a3c578d --- /dev/null +++ b/internal/notification/gotify.go @@ -0,0 +1,176 @@ +// Copyright (c) 2021 - 2023, Ludvig Lundgren and the autobrr contributors. +// SPDX-License-Identifier: GPL-2.0-or-later + +package notification + +import ( + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/autobrr/autobrr/internal/domain" + "github.com/autobrr/autobrr/pkg/errors" + + "github.com/dustin/go-humanize" + "github.com/rs/zerolog" +) + +type gotifyMessage struct { + Message string `json:"message"` + Title string `json:"title"` +} + +type gotifySender struct { + log zerolog.Logger + Settings domain.Notification +} + +func NewGotifySender(log zerolog.Logger, settings domain.Notification) domain.NotificationSender { + return &gotifySender{ + log: log.With().Str("sender", "gotify").Logger(), + Settings: settings, + } +} + +func (s *gotifySender) Send(event domain.NotificationEvent, payload domain.NotificationPayload) error { + m := gotifyMessage{ + Message: s.buildMessage(payload), + Title: s.buildTitle(event), + } + + data := url.Values{} + data.Set("message", m.Message) + data.Set("title", m.Title) + + url := fmt.Sprintf("%v/message?token=%v", s.Settings.Host, s.Settings.Token); + req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data.Encode())) + if err != nil { + s.log.Error().Err(err).Msgf("gotify client request error: %v", event) + return errors.Wrap(err, "could not create request") + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("User-Agent", "autobrr") + + client := http.Client{Timeout: 30 * time.Second} + res, err := client.Do(req) + if err != nil { + s.log.Error().Err(err).Msgf("gotify client request error: %v", event) + return errors.Wrap(err, "could not make request: %+v", req) + } + + body, err := io.ReadAll(res.Body) + if err != nil { + s.log.Error().Err(err).Msgf("gotify client request error: %v", event) + return errors.Wrap(err, "could not read data") + } + + defer res.Body.Close() + + s.log.Trace().Msgf("gotify status: %v response: %v", res.StatusCode, string(body)) + + if res.StatusCode != http.StatusOK { + s.log.Error().Err(err).Msgf("gotify 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 gotify") + + return nil +} + +func (s *gotifySender) CanSend(event domain.NotificationEvent) bool { + if s.isEnabled() && s.isEnabledEvent(event) { + return true + } + return false +} + +func (s *gotifySender) isEnabled() bool { + if s.Settings.Enabled { + if s.Settings.Host == "" { + s.log.Warn().Msg("gotify missing host") + return false + } + + if s.Settings.Token == "" { + s.log.Warn().Msg("gotify missing application token") + return false + } + + return true + } + + return false +} + +func (s *gotifySender) isEnabledEvent(event domain.NotificationEvent) bool { + for _, e := range s.Settings.Events { + if e == string(event) { + return true + } + } + + return false +} + +func (s *gotifySender) buildMessage(payload domain.NotificationPayload) string { + msg := "" + + if payload.Subject != "" && payload.Message != "" { + msg += fmt.Sprintf("%v\n%v", payload.Subject, payload.Message) + } + if payload.ReleaseName != "" { + msg += fmt.Sprintf("\nNew release: %v", payload.ReleaseName) + } + if payload.Size > 0 { + msg += fmt.Sprintf("\nSize: %v", humanize.Bytes(payload.Size)) + } + if payload.Status != "" { + msg += fmt.Sprintf("\nStatus: %v", payload.Status.String()) + } + if payload.Indexer != "" { + msg += fmt.Sprintf("\nIndexer: %v", payload.Indexer) + } + if payload.Filter != "" { + msg += fmt.Sprintf("\nFilter: %v", payload.Filter) + } + if payload.Action != "" { + action := fmt.Sprintf("\nAction: %v Type: %v", payload.Action, payload.ActionType) + if payload.ActionClient != "" { + action += fmt.Sprintf(" Client: %v", payload.ActionClient) + } + msg += action + } + if len(payload.Rejections) > 0 { + msg += fmt.Sprintf("\nRejections: %v", strings.Join(payload.Rejections, ", ")) + } + + return msg +} + +func (s *gotifySender) buildTitle(event domain.NotificationEvent) string { + title := "" + + switch event { + case domain.NotificationEventAppUpdateAvailable: + title = "Autobrr update available" + case domain.NotificationEventPushApproved: + title = "Push Approved" + case domain.NotificationEventPushRejected: + title = "Push Rejected" + case domain.NotificationEventPushError: + title = "Error" + case domain.NotificationEventIRCDisconnected: + title = "IRC Disconnected" + case domain.NotificationEventIRCReconnected: + title = "IRC Reconnected" + case domain.NotificationEventTest: + title = "Test" + } + + return title +} diff --git a/internal/notification/service.go b/internal/notification/service.go index df51ebd..b98bedb 100644 --- a/internal/notification/service.go +++ b/internal/notification/service.go @@ -130,6 +130,8 @@ func (s *service) registerSenders() { s.senders = append(s.senders, NewTelegramSender(s.log, n)) case domain.NotificationTypePushover: s.senders = append(s.senders, NewPushoverSender(s.log, n)) + case domain.NotificationTypeGotify: + s.senders = append(s.senders, NewGotifySender(s.log, n)) } } } @@ -243,6 +245,8 @@ func (s *service) Test(ctx context.Context, notification domain.Notification) er agent = NewTelegramSender(s.log, notification) case domain.NotificationTypePushover: agent = NewPushoverSender(s.log, notification) + case domain.NotificationTypeGotify: + agent = NewGotifySender(s.log, notification) default: s.log.Error().Msgf("unsupported notification type: %v", notification.Type) return errors.New("unsupported notification type") diff --git a/web/src/domain/constants.ts b/web/src/domain/constants.ts index 5fd35a9..6587a9d 100644 --- a/web/src/domain/constants.ts +++ b/web/src/domain/constants.ts @@ -395,6 +395,10 @@ export const NotificationTypeOptions: OptionBasicTyped[] = [ { label: "Pushover", value: "PUSHOVER" + }, + { + label: "Gotify", + value: "GOTIFY" } ]; diff --git a/web/src/forms/settings/NotificationForms.tsx b/web/src/forms/settings/NotificationForms.tsx index c47c124..52bffd6 100644 --- a/web/src/forms/settings/NotificationForms.tsx +++ b/web/src/forms/settings/NotificationForms.tsx @@ -182,11 +182,36 @@ function FormFieldsPushover() { ); } +function FormFieldsGotify() { + return ( +
+
+ Settings +
+ + + +
+ ); +} + const componentMap: componentMapType = { DISCORD: , NOTIFIARR: , TELEGRAM: , - PUSHOVER: + PUSHOVER: , + GOTIFY: }; interface NotificationAddFormValues { @@ -464,6 +489,7 @@ interface InitialValues { priority?: number; channel?: string; topic?: string; + host?: string; events: NotificationEvent[]; } @@ -513,6 +539,7 @@ export function NotificationUpdateForm({ isOpen, toggle, notification }: UpdateP priority: notification.priority, channel: notification.channel, topic: notification.topic, + host: notification.host, events: notification.events || [] }; diff --git a/web/src/screens/settings/Notifications.tsx b/web/src/screens/settings/Notifications.tsx index f1dfbb3..a73a4b1 100644 --- a/web/src/screens/settings/Notifications.tsx +++ b/web/src/screens/settings/Notifications.tsx @@ -99,12 +99,20 @@ const PushoverIcon = () => ( ); +const GotifyIcon = () => ( + + + +); + const iconComponentMap: componentMapType = { DISCORD: Discord, NOTIFIARR: Notifiarr, TELEGRAM: Telegram, - PUSHOVER: Pushover + PUSHOVER: Pushover, + GOTIFY: Gotify }; interface ListItemProps { diff --git a/web/src/types/Notification.d.ts b/web/src/types/Notification.d.ts index e29d2dd..3344798 100644 --- a/web/src/types/Notification.d.ts +++ b/web/src/types/Notification.d.ts @@ -3,7 +3,7 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ -type NotificationType = "DISCORD" | "NOTIFIARR" | "TELEGRAM" | "PUSHOVER"; +type NotificationType = "DISCORD" | "NOTIFIARR" | "TELEGRAM" | "PUSHOVER" | "GOTIFY"; type NotificationEvent = "PUSH_APPROVED" | "PUSH_REJECTED" @@ -24,4 +24,5 @@ interface ServiceNotification { channel?: string; priority?: number; topic?: string; + host?: string; }