feat(notifications): add Pushover (#598)

* feat(notifications): add pushover

* add db migration

* fix lint error

* some small corrections

* fixed README

* added missing columns to postgres_migrate.go

* use token for user_key

* refactor(notifications): change priority to int

* fix: only test selected events

---------

Co-authored-by: soup <soup@r4tio.dev>
Co-authored-by: ze0s <ze0s@riseup.net>
This commit is contained in:
Nelson Pecora 2023-04-29 11:07:15 -04:00 committed by GitHub
parent 1b8f2fce3c
commit da5492febb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 290 additions and 37 deletions

View file

@ -26,7 +26,7 @@ Installation guide and documentation can be found at https://autobrr.com
- Built on Go and React making autobrr lightweight and perfect for supporting multiple platforms (Linux, FreeBSD, Windows, macOS) on different architectures (e.g. x86, ARM)
- Great container support (Docker, k8s/Kubernetes)
- Database engine supporting both PostgreSQL and SQLite
- Notifications (Discord, Telegram, Notifiarr)
- Notifications (Discord, Telegram, Notifiarr, Pushover)
- One autobrr instance can communicate with multiple clients (torrent, usenet and \*arr) on remote servers
- Base path / Subfolder (and subdomain) support for convenient reverse-proxy support

View file

@ -28,7 +28,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", "created_at", "updated_at", "COUNT(*) OVER() AS total_count").
Select("id", "name", "type", "enabled", "events", "webhook", "token", "api_key", "channel", "priority", "created_at", "updated_at", "COUNT(*) OVER() AS total_count").
From("notification").
OrderBy("name")
@ -50,10 +50,8 @@ func (r *NotificationRepo) Find(ctx context.Context, params domain.NotificationQ
var n domain.Notification
var webhook, token, apiKey, channel sql.NullString
//var token, apiKey, webhook, title, icon, host, username, password, channel, targets, devices sql.NullString
//if err := rows.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &token, &apiKey, &webhook, &title, &icon, &host, &username, &password, &channel, &targets, &devices, &n.CreatedAt, &n.UpdatedAt); err != nil {
//var token, apiKey, webhook, title, icon, host, username, password, channel, targets, devices sql.NullString
if err := rows.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &webhook, &token, &apiKey, &channel, &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, &n.CreatedAt, &n.UpdatedAt, &totalCount); err != nil {
return nil, 0, errors.Wrap(err, "error scanning row")
}
@ -61,14 +59,6 @@ func (r *NotificationRepo) Find(ctx context.Context, params domain.NotificationQ
n.Webhook = webhook.String
n.Token = token.String
n.Channel = channel.String
//n.Title = title.String
//n.Icon = icon.String
//n.Host = host.String
//n.Username = username.String
//n.Password = password.String
//n.Channel = channel.String
//n.Targets = targets.String
//n.Devices = devices.String
notifications = append(notifications, n)
}
@ -81,7 +71,7 @@ func (r *NotificationRepo) Find(ctx context.Context, params domain.NotificationQ
func (r *NotificationRepo) List(ctx context.Context) ([]domain.Notification, error) {
rows, err := r.db.handler.QueryContext(ctx, "SELECT id, name, type, enabled, events, token, api_key, webhook, title, icon, host, username, password, channel, targets, devices, created_at, updated_at FROM notification ORDER BY name ASC")
rows, err := r.db.handler.QueryContext(ctx, "SELECT id, name, type, enabled, events, token, api_key, webhook, title, icon, host, username, password, channel, targets, devices, priority,created_at, updated_at FROM notification ORDER BY name ASC")
if err != nil {
return nil, errors.Wrap(err, "error executing query")
}
@ -94,7 +84,7 @@ func (r *NotificationRepo) List(ctx context.Context) ([]domain.Notification, err
//var eventsSlice []string
var token, apiKey, webhook, title, icon, host, username, password, channel, targets, devices sql.NullString
if err := rows.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &token, &apiKey, &webhook, &title, &icon, &host, &username, &password, &channel, &targets, &devices, &n.CreatedAt, &n.UpdatedAt); err != nil {
if err := rows.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &token, &apiKey, &webhook, &title, &icon, &host, &username, &password, &channel, &targets, &devices, &n.Priority, &n.CreatedAt, &n.UpdatedAt); err != nil {
return nil, errors.Wrap(err, "error scanning row")
}
@ -140,6 +130,7 @@ func (r *NotificationRepo) FindByID(ctx context.Context, id int) (*domain.Notifi
"channel",
"targets",
"devices",
"priority",
"created_at",
"updated_at",
).
@ -151,7 +142,6 @@ func (r *NotificationRepo) FindByID(ctx context.Context, id int) (*domain.Notifi
return nil, errors.Wrap(err, "error building query")
}
//row := r.db.handler.QueryRowContext(ctx, "SELECT id, name, type, enabled, events, token, api_key, webhook, title, icon, host, username, password, channel, targets, devices, created_at, updated_at FROM notification WHERE id = ?", id)
row := r.db.handler.QueryRowContext(ctx, query, args...)
if err := row.Err(); err != nil {
return nil, errors.Wrap(err, "error executing query")
@ -160,7 +150,7 @@ func (r *NotificationRepo) FindByID(ctx context.Context, id int) (*domain.Notifi
var n domain.Notification
var token, apiKey, webhook, title, icon, host, username, password, channel, targets, devices sql.NullString
if err := row.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &token, &apiKey, &webhook, &title, &icon, &host, &username, &password, &channel, &targets, &devices, &n.CreatedAt, &n.UpdatedAt); err != nil {
if err := row.Scan(&n.ID, &n.Name, &n.Type, &n.Enabled, pq.Array(&n.Events), &token, &apiKey, &webhook, &title, &icon, &host, &username, &password, &channel, &targets, &devices, &n.Priority, &n.CreatedAt, &n.UpdatedAt); err != nil {
return nil, errors.Wrap(err, "error scanning row")
}
@ -196,6 +186,7 @@ func (r *NotificationRepo) Store(ctx context.Context, notification domain.Notifi
"token",
"api_key",
"channel",
"priority",
).
Values(
notification.Name,
@ -206,14 +197,14 @@ func (r *NotificationRepo) Store(ctx context.Context, notification domain.Notifi
token,
apiKey,
channel,
notification.Priority,
).
Suffix("RETURNING id").RunWith(r.db.handler)
// return values
var retID int64
err := queryBuilder.QueryRowContext(ctx).Scan(&retID)
if err != nil {
if err := queryBuilder.QueryRowContext(ctx).Scan(&retID); err != nil {
return nil, errors.Wrap(err, "error executing query")
}
@ -239,6 +230,7 @@ func (r *NotificationRepo) Update(ctx context.Context, notification domain.Notif
Set("token", token).
Set("api_key", apiKey).
Set("channel", channel).
Set("priority", notification.Priority).
Set("updated_at", sq.Expr("CURRENT_TIMESTAMP")).
Where(sq.Eq{"id": notification.ID})
@ -247,8 +239,7 @@ func (r *NotificationRepo) Update(ctx context.Context, notification domain.Notif
return nil, errors.Wrap(err, "error building query")
}
_, err = r.db.handler.ExecContext(ctx, query, args...)
if err != nil {
if _, err = r.db.handler.ExecContext(ctx, query, args...); err != nil {
return nil, errors.Wrap(err, "error executing query")
}
@ -267,8 +258,7 @@ func (r *NotificationRepo) Delete(ctx context.Context, notificationID int) error
return errors.Wrap(err, "error building query")
}
_, err = r.db.handler.ExecContext(ctx, query, args...)
if err != nil {
if _, err = r.db.handler.ExecContext(ctx, query, args...); err != nil {
return errors.Wrap(err, "error executing query")
}

View file

@ -300,6 +300,7 @@ CREATE TABLE notification
rooms TEXT,
targets TEXT,
devices TEXT,
priority INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@ -671,4 +672,6 @@ ADD COLUMN download_url TEXT;
SET except_tags_match_logic = 'ANY'
WHERE except_tags IS NOT NULL;
`,
`ALTER TABLE notification
ADD COLUMN priority INTEGER DEFAULT 0;`,
}

View file

@ -292,6 +292,7 @@ CREATE TABLE notification
rooms TEXT,
targets TEXT,
devices TEXT,
priority INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@ -1064,4 +1065,6 @@ ADD COLUMN download_url TEXT;
SET except_tags_match_logic = 'ANY'
WHERE except_tags IS NOT NULL;
`,
`ALTER TABLE notification
ADD COLUMN priority INTEGER DEFAULT 0;`,
}

View file

@ -37,6 +37,7 @@ type Notification struct {
Rooms string `json:"rooms"`
Targets string `json:"targets"`
Devices string `json:"devices"`
Priority int32 `json:"priority"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

View file

@ -114,13 +114,11 @@ func (h notificationHandler) test(w http.ResponseWriter, r *http.Request) {
)
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
// encode error
h.encoder.Error(w, err)
return
}
err := h.service.Test(ctx, data)
if err != nil {
if err := h.service.Test(ctx, data); err != nil {
h.encoder.Error(w, err)
return
}

View file

@ -0,0 +1,192 @@
package notification
import (
"fmt"
"html"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/autobrr/autobrr/internal/domain"
"github.com/autobrr/autobrr/pkg/errors"
"github.com/rs/zerolog"
)
type pushoverMessage struct {
Token string `json:"api_key"`
User string `json:"token"`
Message string `json:"message"`
Priority int32 `json:"priority"`
Title string `json:"title"`
Timestamp time.Time `json:"timestamp"`
Html int `json:"html,omitempty"`
}
type pushoverSender struct {
log zerolog.Logger
Settings domain.Notification
baseUrl string
}
func NewPushoverSender(log zerolog.Logger, settings domain.Notification) domain.NotificationSender {
return &pushoverSender{
log: log.With().Str("sender", "pushover").Logger(),
Settings: settings,
baseUrl: "https://api.pushover.net/1/messages.json",
}
}
func (s *pushoverSender) Send(event domain.NotificationEvent, payload domain.NotificationPayload) error {
m := pushoverMessage{
Token: s.Settings.APIKey,
User: s.Settings.Token,
Priority: s.Settings.Priority,
Message: s.buildMessage(payload),
Title: s.buildTitle(event),
Timestamp: time.Now(),
Html: 1,
}
data := url.Values{}
data.Set("token", m.Token)
data.Set("user", m.User)
data.Set("message", m.Message)
data.Set("priority", strconv.Itoa(int(m.Priority)))
data.Set("title", m.Title)
data.Set("timestamp", fmt.Sprintf("%v", m.Timestamp.Unix()))
data.Set("html", fmt.Sprintf("%v", m.Html))
if m.Priority == 2 {
data.Set("expire", "3600")
data.Set("retry", "60")
}
req, err := http.NewRequest(http.MethodPost, s.baseUrl, strings.NewReader(data.Encode()))
if err != nil {
s.log.Error().Err(err).Msgf("pushover 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("pushover 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("pushover client request error: %v", event)
return errors.Wrap(err, "could not read data")
}
defer res.Body.Close()
s.log.Trace().Msgf("pushover status: %v response: %v", res.StatusCode, string(body))
if res.StatusCode != http.StatusOK {
s.log.Error().Err(err).Msgf("pushover 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 pushover")
return nil
}
func (s *pushoverSender) CanSend(event domain.NotificationEvent) bool {
if s.isEnabled() && s.isEnabledEvent(event) {
return true
}
return false
}
func (s *pushoverSender) isEnabled() bool {
if s.Settings.Enabled {
if s.Settings.APIKey == "" {
s.log.Warn().Msg("pushover missing api key")
return false
}
if s.Settings.Token == "" {
s.log.Warn().Msg("pushover missing user key")
return false
}
return true
}
return false
}
func (s *pushoverSender) isEnabledEvent(event domain.NotificationEvent) bool {
for _, e := range s.Settings.Events {
if e == string(event) {
return true
}
}
return false
}
func (s *pushoverSender) buildMessage(payload domain.NotificationPayload) string {
msg := ""
if payload.Subject != "" && payload.Message != "" {
msg += fmt.Sprintf("%v\n<b>%v</b>", payload.Subject, html.EscapeString(payload.Message))
}
if payload.ReleaseName != "" {
msg += fmt.Sprintf("\n<b>New release:</b> %v", html.EscapeString(payload.ReleaseName))
}
if payload.Status != "" {
msg += fmt.Sprintf("\n<b>Status:</b> %v", payload.Status.String())
}
if payload.Indexer != "" {
msg += fmt.Sprintf("\n<b>Indexer:</b> %v", payload.Indexer)
}
if payload.Filter != "" {
msg += fmt.Sprintf("\n<b>Filter:</b> %v", html.EscapeString(payload.Filter))
}
if payload.Action != "" {
action := fmt.Sprintf("\n<b>Action:</b> %v <b>Type:</b> %v", html.EscapeString(payload.Action), payload.ActionType)
if payload.ActionClient != "" {
action += fmt.Sprintf(" <b>Client:</b> %v", html.EscapeString(payload.ActionClient))
}
msg += action
}
if len(payload.Rejections) > 0 {
msg += fmt.Sprintf("\nRejections: %v", strings.Join(payload.Rejections, ", "))
}
return msg
}
func (s *pushoverSender) 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
}

View file

@ -125,6 +125,8 @@ func (s *service) registerSenders() {
s.senders = append(s.senders, NewNotifiarrSender(s.log, n))
case domain.NotificationTypeTelegram:
s.senders = append(s.senders, NewTelegramSender(s.log, n))
case domain.NotificationTypePushover:
s.senders = append(s.senders, NewPushoverSender(s.log, n))
}
}
}
@ -236,6 +238,8 @@ func (s *service) Test(ctx context.Context, notification domain.Notification) er
agent = NewNotifiarrSender(s.log, notification)
case domain.NotificationTypeTelegram:
agent = NewTelegramSender(s.log, notification)
case domain.NotificationTypePushover:
agent = NewPushoverSender(s.log, notification)
default:
s.log.Error().Msgf("unsupported notification type: %v", notification.Type)
return errors.New("unsupported notification type")
@ -245,9 +249,15 @@ func (s *service) Test(ctx context.Context, notification domain.Notification) er
for _, event := range events {
e := event
g.Go(func() error {
return agent.Send(e.Event, e)
})
if !enabledEvent(notification.Events, e.Event) {
continue
}
if err := agent.Send(e.Event, e); err != nil {
s.log.Error().Err(err).Msgf("error sending test notification: %#v", notification)
return err
}
time.Sleep(1 * time.Second)
}
@ -259,3 +269,13 @@ func (s *service) Test(ctx context.Context, notification domain.Notification) er
return nil
}
func enabledEvent(events []string, e domain.NotificationEvent) bool {
for _, v := range events {
if v == string(e) {
return true
}
}
return false
}

View file

@ -386,6 +386,10 @@ export const NotificationTypeOptions: OptionBasicTyped<NotificationType>[] = [
{
label: "Telegram",
value: "TELEGRAM"
},
{
label: "Pushover",
value: "PUSHOVER"
}
];

View file

@ -7,7 +7,7 @@ import Select, { components, ControlProps, InputProps, MenuProps, OptionProps }
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "react-hot-toast";
import { PasswordFieldWide, SwitchGroupWide, TextFieldWide } from "@components/inputs";
import { NumberFieldWide, PasswordFieldWide, SwitchGroupWide, TextFieldWide } from "@components/inputs";
import DEBUG from "@components/debug";
import { EventOptions, NotificationTypeOptions, SelectOption } from "@domain/constants";
import { APIClient } from "@api/APIClient";
@ -120,10 +120,41 @@ function FormFieldsTelegram() {
);
}
function FormFieldsPushover() {
return (
<div className="border-t border-gray-200 dark:border-gray-700 py-4">
<div className="px-4 space-y-1">
<Dialog.Title className="text-lg font-medium text-gray-900 dark:text-white">Settings</Dialog.Title>
<p className="text-sm text-gray-500 dark:text-gray-400">
Register a new <a href="https://support.pushover.net/i175-how-do-i-get-an-api-or-application-token" rel="noopener noreferrer" target="_blank" className="font-medium text-blue-500 underline underline-offset-1 hover:text-blue-400">application</a> and add its API Token here.
</p>
</div>
<PasswordFieldWide
name="api_key"
label="API Token"
help="API Token"
/>
<PasswordFieldWide
name="token"
label="User Key"
help="User Key"
/>
<NumberFieldWide
name="priority"
label="Priority"
help="-2, -1, 0 (default), 1, or 2"
required={true}
/>
</div>
);
}
const componentMap: componentMapType = {
DISCORD: <FormFieldsDiscord />,
NOTIFIARR: <FormFieldsNotifiarr />,
TELEGRAM: <FormFieldsTelegram />
TELEGRAM: <FormFieldsTelegram />,
PUSHOVER: <FormFieldsPushover />
};
interface NotificationAddFormValues {
@ -398,6 +429,7 @@ interface InitialValues {
webhook?: string;
token?: string;
api_key?: string;
priority?: number;
channel?: string;
events: NotificationEvent[];
}
@ -445,6 +477,7 @@ export function NotificationUpdateForm({ isOpen, toggle, notification }: UpdateP
webhook: notification.webhook,
token: notification.token,
api_key: notification.api_key,
priority: notification.priority,
channel: notification.channel,
events: notification.events || []
};
@ -529,4 +562,4 @@ export function NotificationUpdateForm({ isOpen, toggle, notification }: UpdateP
)}
</SlideOver>
);
}
}

View file

@ -85,11 +85,19 @@ const TelegramIcon = () => (
</svg>
);
const PushoverIcon = () => (
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" className="mr-2 h-4">
<path d="m495.6 319.4 104-13.7-101.3 228.6c17.8-1.4 35.2-7.4 52.3-18.1 17.1-10.7 32.9-24.2 47.2-40.4 14.4-16.2 26.8-34.2 37.3-54.1 10.5-19.8 18-39.4 22.6-58.5 2.7-11.9 4-23.3 3.8-34.2-.2-10.9-3.1-20.5-8.6-28.7s-13.8-14.8-25-19.8-26.3-7.5-45.5-7.5c-22.4 0-44.4 3.6-66 10.9-21.7 7.3-41.7 17.9-60.2 31.8-18.5 13.9-34.5 31.2-48.2 52-13.7 20.8-23.5 44.4-29.4 70.8-2.3 8.7-3.6 15.6-4.1 20.9-.5 5.3-.6 9.6-.3 13 .2 3.4.7 6.1 1.4 7.9.7 1.8 1.3 3.6 1.7 5.5-23.3 0-40.3-4.7-51-14-10.7-9.3-13.3-25.7-7.9-48.9 5.5-24.2 17.9-47.2 37.3-69.1 19.4-21.9 42.4-41.2 69.1-57.8 26.7-16.6 55.9-29.9 87.6-39.7 31.7-9.8 62.6-14.7 92.7-14.7 26.5 0 48.7 3.8 66.7 11.3 18 7.5 32.1 17.5 42.1 29.8s16.3 26.7 18.8 43.1c2.5 16.4 1.7 33.5-2.4 51.3-5 21.4-14.5 43-28.4 64.7-13.9 21.7-31.4 41.3-52.3 58.8-21 17.6-45 31.8-72.2 42.8-27.1 10.9-56 16.4-86.6 16.4h-3.4l-86.9 195H302l193.6-435.4z"
clipRule="evenodd" fill="currentColor" fillRule="evenodd"/>
</svg>
);
const iconComponentMap: componentMapType = {
DISCORD: <span className="flex items-center px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-400"><DiscordIcon /> Discord</span>,
NOTIFIARR: <span className="flex items-center px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-400"><DiscordIcon /> Notifiarr</span>,
TELEGRAM: <span className="flex items-center px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-400"><TelegramIcon /> Telegram</span>
TELEGRAM: <span className="flex items-center px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-400"><TelegramIcon /> Telegram</span>,
PUSHOVER: <span className="flex items-center px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-400"><PushoverIcon /> Pushover</span>
};
interface ListItemProps {
@ -151,4 +159,4 @@ function ListItem({ notification }: ListItemProps) {
);
}
export default NotificationSettings;
export default NotificationSettings;

View file

@ -1,4 +1,4 @@
type NotificationType = "DISCORD" | "NOTIFIARR" | "TELEGRAM";
type NotificationType = "DISCORD" | "NOTIFIARR" | "TELEGRAM" | "PUSHOVER";
type NotificationEvent = "PUSH_APPROVED" | "PUSH_REJECTED" | "PUSH_ERROR" | "IRC_DISCONNECTED" | "IRC_RECONNECTED" | "APP_UPDATE_AVAILABLE";
interface Notification {
@ -11,4 +11,5 @@ interface Notification {
token?: string;
api_key?: string;
channel?: string;
}
priority?: number;
}