Add alerts, currency conversion and notifications.
Items fire when a page is available from an accepted seller at or below max_price, converted with the ECB's daily rates when the page uses another currency. A per-item cooldown, kept in the state file, holds back repeat alerts unless the price drops. Alerts go to Discord, ntfy and JSON webhooks with retries, and to the desktop; 'dibs notify test' sends a sample.
This commit is contained in:
1 parent
2175c0e5aa
commit
8f0eda5d4d
16 files changed
+1409
-15
No files matched your search
@@ -0,0 +1,291 @@
|
||||
// Package notify delivers alerts to webhooks and the desktop.
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gen2brain/beeep"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
// retries follow the first attempt, with waits of 1s, 2s and 4s.
|
||||
retries = 3
|
||||
retryBase = 1 * time.Second
|
||||
maxRetryAfter = 30 * time.Second
|
||||
requestTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// Notifier sends alerts to every configured channel.
|
||||
type Notifier struct {
|
||||
webhooks []config.Webhook
|
||||
desktop bool
|
||||
userAgent string
|
||||
client *http.Client
|
||||
wait func(ctx context.Context, d time.Duration) error
|
||||
showToast func(title, message string) error
|
||||
}
|
||||
|
||||
// New returns a notifier for the [notify] config. Webhook requests are not
|
||||
// rate limited: they go to the user's own services, and only when an item
|
||||
// fires.
|
||||
func New(cfg config.Notify, userAgent string) *Notifier {
|
||||
beeep.AppName = "dibs"
|
||||
|
||||
return &Notifier{
|
||||
webhooks: cfg.Webhooks,
|
||||
desktop: cfg.Desktop,
|
||||
userAgent: userAgent,
|
||||
client: &http.Client{Timeout: requestTimeout},
|
||||
wait: sleep,
|
||||
showToast: func(title, message string) error { return beeep.Notify(title, message, "") },
|
||||
}
|
||||
}
|
||||
|
||||
// Send delivers a to every webhook and the desktop at once and returns when
|
||||
// all are done. The error joins one error per failed channel.
|
||||
func (n *Notifier) Send(ctx context.Context, a alert.Alert) error {
|
||||
errs := make([]error, len(n.webhooks)+1)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i, wh := range n.webhooks {
|
||||
wg.Go(func() {
|
||||
if err := n.webhook(ctx, wh, a); err != nil { errs[i] = fmt.Errorf("webhook %d (%s, %s): %w", i, wh.Format, hostOf(wh.URL), err) }
|
||||
})
|
||||
}
|
||||
|
||||
if n.desktop {
|
||||
wg.Go(func() {
|
||||
title, message := desktopText(a)
|
||||
if err := n.showToast(title, message); err != nil { errs[len(n.webhooks)] = fmt.Errorf("desktop notification: %w", err) }
|
||||
})
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// Channels says where alerts go, for the startup log.
|
||||
func (n *Notifier) Channels() []string {
|
||||
var out []string
|
||||
for _, wh := range n.webhooks { out = append(out, wh.Format+" "+hostOf(wh.URL)) }
|
||||
if n.desktop { out = append(out, "desktop") }
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// hostOf names a webhook in logs and errors. Its full URL often contains a
|
||||
// secret token.
|
||||
func hostOf(raw string) string {
|
||||
if u, err := url.Parse(raw); err == nil { return u.Host }
|
||||
|
||||
return "invalid URL"
|
||||
}
|
||||
|
||||
func (n *Notifier) webhook(ctx context.Context, wh config.Webhook, a alert.Alert) error {
|
||||
var (
|
||||
body []byte
|
||||
header = http.Header{}
|
||||
err error
|
||||
)
|
||||
|
||||
switch wh.Format {
|
||||
case config.FormatDiscord:
|
||||
body, err = json.Marshal(discordPayload(a))
|
||||
header.Set("Content-Type", "application/json")
|
||||
case config.FormatNtfy:
|
||||
body = []byte(ntfyMessage(a))
|
||||
ntfyHeaders(header, a)
|
||||
default:
|
||||
body, err = json.Marshal(NewPayload(a))
|
||||
header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
if err != nil { return err }
|
||||
|
||||
header.Set("User-Agent", n.userAgent)
|
||||
|
||||
return n.post(ctx, wh.URL, header, body)
|
||||
}
|
||||
|
||||
// post sends body, retrying network errors, 429 and 5xx answers.
|
||||
func (n *Notifier) post(ctx context.Context, rawURL string, header http.Header, body []byte) error {
|
||||
var last error
|
||||
|
||||
for attempt := 0; ; attempt++ {
|
||||
retryAfter, err := n.try(ctx, rawURL, header, body)
|
||||
if err == nil { return nil }
|
||||
|
||||
last = err
|
||||
if retryAfter < 0 || attempt == retries || ctx.Err() != nil { return last }
|
||||
|
||||
d := retryBase << attempt
|
||||
if retryAfter > d { d = min(retryAfter, maxRetryAfter) }
|
||||
|
||||
if err := n.wait(ctx, d); err != nil { return last }
|
||||
}
|
||||
}
|
||||
|
||||
// try makes one request. A failed request returns how long the server asked
|
||||
// to wait before the next one, 0 if it did not say, or -1 if retrying is
|
||||
// pointless.
|
||||
func (n *Notifier) try(ctx context.Context, rawURL string, header http.Header, body []byte) (time.Duration, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, bytes.NewReader(body))
|
||||
if err != nil { return -1, err }
|
||||
|
||||
req.Header = header.Clone()
|
||||
|
||||
resp, err := n.client.Do(req)
|
||||
if err != nil { return 0, err }
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
|
||||
if resp.StatusCode < 300 { return 0, nil }
|
||||
|
||||
err = fmt.Errorf("%s", resp.Status)
|
||||
if text := strings.TrimSpace(string(msg)); text != "" { err = fmt.Errorf("%s: %s", resp.Status, text) }
|
||||
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500:
|
||||
secs, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
|
||||
return time.Duration(max(secs, 0)) * time.Second, err
|
||||
default:
|
||||
return -1, err
|
||||
}
|
||||
}
|
||||
|
||||
func sleep(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// link is where tapping a notification leads: the cart link if the shop has
|
||||
// one, otherwise the product page.
|
||||
func link(a alert.Alert) string {
|
||||
if a.CartLink != "" { return a.CartLink }
|
||||
|
||||
return a.URL
|
||||
}
|
||||
|
||||
func headline(a alert.Alert) string {
|
||||
h := "In stock: " + a.Item
|
||||
if a.Test { h = "Test alert: " + a.Item }
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// summary is the price and seller line, with the price drop if there is one.
|
||||
func summary(a alert.Alert) string {
|
||||
s := a.PriceText() + ", " + a.SellerText()
|
||||
if a.PreviousPrice != nil { s += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) }
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func desktopText(a alert.Alert) (string, string) {
|
||||
lines := []string{summary(a)}
|
||||
if a.Title != "" { lines = append(lines, a.Title) }
|
||||
|
||||
return headline(a), strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func ntfyMessage(a alert.Alert) string {
|
||||
lines := []string{summary(a)}
|
||||
if a.Title != "" { lines = append(lines, a.Title) }
|
||||
if a.CartLink != "" { lines = append(lines, "Cart: "+a.CartLink) }
|
||||
lines = append(lines, "Page: "+a.URL)
|
||||
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func ntfyHeaders(h http.Header, a alert.Alert) {
|
||||
// HTTP headers are ASCII. ntfy decodes RFC 2047 encoded words, which
|
||||
// carry titles such as "Édition Limitée".
|
||||
h.Set("Title", mime.BEncoding.Encode("utf-8", headline(a)))
|
||||
h.Set("Click", link(a))
|
||||
h.Set("Priority", "high")
|
||||
h.Set("Tags", "shopping_cart")
|
||||
}
|
||||
|
||||
type discordMessage struct {
|
||||
Username string `json:"username"`
|
||||
Content string `json:"content"`
|
||||
Embeds []discordEmbed `json:"embeds"`
|
||||
AllowedMentions map[string][]string `json:"allowed_mentions"`
|
||||
}
|
||||
|
||||
type discordEmbed struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Color int `json:"color"`
|
||||
Fields []discordField `json:"fields"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}
|
||||
|
||||
type discordField struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Inline bool `json:"inline"`
|
||||
}
|
||||
|
||||
func discordPayload(a alert.Alert) discordMessage {
|
||||
title := a.Title
|
||||
if title == "" { title = a.Item }
|
||||
|
||||
price := a.PriceText()
|
||||
if a.PreviousPrice != nil { price += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) }
|
||||
|
||||
desc := "[Product page](" + a.URL + ")"
|
||||
if a.CartLink != "" { desc = "[Add to cart](" + a.CartLink + ") · " + desc }
|
||||
|
||||
return discordMessage{
|
||||
Username: "dibs",
|
||||
// The angle brackets keep Discord from adding a preview of the link.
|
||||
Content: "**" + headline(a) + "** <" + link(a) + ">",
|
||||
Embeds: []discordEmbed{{
|
||||
Title: truncate(title, 256),
|
||||
URL: link(a),
|
||||
Description: desc,
|
||||
Color: 0x2ecc71,
|
||||
Fields: []discordField{
|
||||
{Name: "Price", Value: price, Inline: true},
|
||||
{Name: "Seller", Value: a.SellerText(), Inline: true},
|
||||
},
|
||||
Timestamp: a.Time.UTC().Format(time.RFC3339),
|
||||
}},
|
||||
// Page titles never ping anyone.
|
||||
AllowedMentions: map[string][]string{"parse": {}},
|
||||
}
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if utf8.RuneCountInString(s) <= n { return s }
|
||||
|
||||
r := []rune(s)
|
||||
return string(r[:n-1]) + "…"
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
)
|
||||
|
||||
// TestRetries sends one alert to a webhook that fails with each status
|
||||
// until the last attempt.
|
||||
func TestRetries(t *testing.T) {
|
||||
price := 129.99
|
||||
a := alert.Alert{Item: "metro", Shop: "amazon", URL: "https://www.amazon.de/dp/B0HMX2FSTF", Price: &price, Currency: "EUR", Time: time.Now()}
|
||||
|
||||
cases := []struct {
|
||||
status int
|
||||
requests int32
|
||||
ok bool
|
||||
} {
|
||||
{http.StatusServiceUnavailable, retries + 1, false},
|
||||
{http.StatusTooManyRequests, retries + 1, false},
|
||||
{http.StatusNotFound, 1, false},
|
||||
{http.StatusNoContent, 1, true},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var requests atomic.Int32
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
w.WriteHeader(c.status)
|
||||
}))
|
||||
|
||||
// The path stands in for a webhook token.
|
||||
n := New(config.Notify{Webhooks: []config.Webhook{{URL: srv.URL + "/secret-token", Format: config.FormatJSON}}}, "dibs/test")
|
||||
|
||||
var waited time.Duration
|
||||
n.wait = func(_ context.Context, d time.Duration) error {
|
||||
waited += d
|
||||
return nil
|
||||
}
|
||||
|
||||
err := n.Send(context.Background(), a)
|
||||
srv.Close()
|
||||
|
||||
if got := requests.Load(); got != c.requests { t.Errorf("%d: %d requests, want %d", c.status, got, c.requests) }
|
||||
if (err == nil) != c.ok { t.Errorf("%d: err = %v", c.status, err) }
|
||||
if err != nil && strings.Contains(err.Error(), "secret-token") { t.Errorf("%d: error shows the webhook URL: %v", c.status, err) }
|
||||
if c.requests > 1 && waited != 7*time.Second { t.Errorf("%d: waited %s between attempts, want 7s", c.status, waited) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||
)
|
||||
|
||||
// PayloadVersion changes only when a field is removed or changes meaning.
|
||||
// New fields may appear in any version.
|
||||
const PayloadVersion = 1
|
||||
|
||||
// Payload is the body of a "json" webhook, POSTed as application/json.
|
||||
//
|
||||
// {
|
||||
// "version": 1,
|
||||
// "test": false,
|
||||
// "item": "Metro 2039 CE",
|
||||
// "shop": "amazon",
|
||||
// "url": "https://www.amazon.de/dp/B0HMX2FSTF",
|
||||
// "title": "Metro 2039 Collector's Edition (PS5)",
|
||||
// "price": 129.99,
|
||||
// "currency": "EUR",
|
||||
// "converted_price": null,
|
||||
// "converted_currency": null,
|
||||
// "previous_price": null,
|
||||
// "previous_currency": null,
|
||||
// "seller": "first_party",
|
||||
// "cart_link": "https://www.amazon.de/gp/aws/cart/add.html?ASIN.1=B0HMX2FSTF&Quantity.1=1",
|
||||
// "time": "2026-10-14T09:30:00Z"
|
||||
// }
|
||||
//
|
||||
// Every key is always present; values that do not apply are null.
|
||||
type Payload struct {
|
||||
Version int `json:"version"`
|
||||
// Test is true for the sample alert of `dibs notify test`.
|
||||
Test bool `json:"test"`
|
||||
Item string `json:"item"`
|
||||
Shop string `json:"shop"`
|
||||
// URL is the product page.
|
||||
URL string `json:"url"`
|
||||
Title *string `json:"title"`
|
||||
// Price is null when the page shows none, which only fires items without
|
||||
// max_price.
|
||||
Price *float64 `json:"price"`
|
||||
Currency *string `json:"currency"`
|
||||
// ConvertedPrice is the price in the item's currency, when the page uses
|
||||
// another one.
|
||||
ConvertedPrice *float64 `json:"converted_price"`
|
||||
ConvertedCurrency *string `json:"converted_currency"`
|
||||
// PreviousPrice is set when the item fires again during its cooldown
|
||||
// because the price dropped below the previous alert's.
|
||||
PreviousPrice *float64 `json:"previous_price"`
|
||||
PreviousCurrency *string `json:"previous_currency"`
|
||||
// Seller is "first_party", "fulfilled", "third_party" or "unknown".
|
||||
Seller string `json:"seller"`
|
||||
CartLink *string `json:"cart_link"`
|
||||
// Time is when the page was checked, in UTC.
|
||||
Time time.Time `json:"time"`
|
||||
}
|
||||
|
||||
func NewPayload(a alert.Alert) Payload {
|
||||
return Payload{
|
||||
Version: PayloadVersion,
|
||||
Test: a.Test,
|
||||
Item: a.Item,
|
||||
Shop: a.Shop,
|
||||
URL: a.URL,
|
||||
Title: orNull(a.Title),
|
||||
Price: a.Price,
|
||||
Currency: orNull(a.Currency),
|
||||
ConvertedPrice: a.Converted,
|
||||
ConvertedCurrency: orNull(a.ConvertedCurrency),
|
||||
PreviousPrice: a.PreviousPrice,
|
||||
PreviousCurrency: orNull(a.PreviousCurrency),
|
||||
Seller: a.Seller,
|
||||
CartLink: orNull(a.CartLink),
|
||||
Time: a.Time.UTC().Truncate(time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
func orNull(s string) *string {
|
||||
if s == "" { return nil }
|
||||
|
||||
return &s
|
||||
}
|
||||
Reference in new issue
Block a user