From 8f0eda5d4dff92c6a1266e71888e1240a214142e Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 14 Oct 2026 11:55:27 +0200 Subject: [PATCH] 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. --- cmd/dibs/main.go | 7 +- cmd/dibs/notify.go | 141 ++++++++++++++++ cmd/dibs/watch.go | 50 +++++- go.mod | 10 ++ go.sum | 30 ++++ internal/alert/alert.go | 257 +++++++++++++++++++++++++++++ internal/alert/alert_test.go | 135 +++++++++++++++ internal/config/config.go | 4 + internal/config/config_test.go | 2 +- internal/config/validate.go | 4 +- internal/fx/fx.go | 266 ++++++++++++++++++++++++++++++ internal/fx/fx_test.go | 28 ++++ internal/notify/notify.go | 291 +++++++++++++++++++++++++++++++++ internal/notify/notify_test.go | 58 +++++++ internal/notify/payload.go | 86 ++++++++++ internal/state/state.go | 55 ++++++- 16 files changed, 1409 insertions(+), 15 deletions(-) create mode 100644 cmd/dibs/notify.go create mode 100644 internal/alert/alert.go create mode 100644 internal/alert/alert_test.go create mode 100644 internal/fx/fx.go create mode 100644 internal/fx/fx_test.go create mode 100644 internal/notify/notify.go create mode 100644 internal/notify/notify_test.go create mode 100644 internal/notify/payload.go diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go index 3a721bd..7e9ed83 100644 --- a/cmd/dibs/main.go +++ b/cmd/dibs/main.go @@ -23,7 +23,8 @@ const usage = `Usage: dibs check [--shop NAME] fetch and parse one URL, print JSON dibs plugin test [--status CODE] [url] dibs config validate [--config FILE] - dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests + dibs notify test [--config FILE] [--item NAME] send a sample alert to every channel + dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests dibs version ` @@ -36,7 +37,7 @@ func run(args []string, stdout, stderr io.Writer) int { switch args[0] { case "config": return runConfig(args[1:], stdout, stderr) - case "version": + case "version", "-v", "--version": printVersion(stdout) return 0 case "check": @@ -45,6 +46,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runPlugin(args[1:], stdout, stderr) case "fixtures": return runFixtures(args[1:], stdout, stderr) + case "notify": + return runNotify(args[1:], stdout, stderr) case "help", "-h", "--help": _, _ = fmt.Fprint(stdout, usage) return 0 diff --git a/cmd/dibs/notify.go b/cmd/dibs/notify.go new file mode 100644 index 0000000..4dc4c48 --- /dev/null +++ b/cmd/dibs/notify.go @@ -0,0 +1,141 @@ +package main + +import ( + "context" + "fmt" + "io" + "log/slog" + "os" + "os/signal" + "sync" + "time" + + "git.security-command.org/Overlord/dibs/internal/alert" + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/notify" + "git.security-command.org/Overlord/dibs/internal/plugin" +) + +// sendTimeout covers every retry of every channel of one alert. +const sendTimeout = time.Minute + +// runNotify implements `dibs notify test [--item NAME]`: it sends a sample +// alert for one item to every configured channel. +func runNotify(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 || args[0] != "test" { + _, _ = fmt.Fprintf(stderr, "dibs notify: expected \"test\"\n\n%s", usage) + return 2 + } + + flags, configPath := newFlagSet("dibs notify test", stderr) + name := flags.String("item", "", "item to build the sample alert from (default: the first)") + + pos, ok := parseArgs(flags, args[1:]) + if !ok { return 2 } + if len(pos) > 0 { + _, _ = fmt.Fprintf(stderr, "dibs notify test: unexpected argument %q\n\n%s", pos[0], usage) + return 2 + } + + cfg, ok := loadConfig(*configPath, stderr) + if !ok { return 1 } + + item, ok := findItem(cfg, *name) + if !ok { + _, _ = fmt.Fprintf(stderr, "dibs notify test: no item named %q\n", *name) + return 1 + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + logger := slog.New(slog.NewTextHandler(stderr, nil)) + + host, err := newHost(cfg, logger) + if err != nil { return fail(stderr, "notify test", err) } + defer host.Close() + + a, err := sampleAlert(ctx, host, item) + if err != nil { return fail(stderr, "notify test", err) } + + n := notify.New(cfg.Notify, userAgent()) + if len(n.Channels()) == 0 { + _, _ = fmt.Fprintln(stderr, "dibs notify test: no webhooks configured and desktop notifications are off") + return 1 + } + + ctx, cancel := context.WithTimeout(ctx, sendTimeout) + defer cancel() + + if err := n.Send(ctx, a); err != nil { return fail(stderr, "notify test", err) } + + _, _ = fmt.Fprintf(stdout, "sent a test alert for %q to: %v\n", item.Name, n.Channels()) + return 0 +} + +func findItem(cfg *config.Config, name string) (config.Item, bool) { + for _, it := range cfg.Items { + if name == "" || it.Name == name { return it, true } + } + + return config.Item{}, false +} + +// sampleAlert is what the item's first URL would send if it fired at its +// max_price. +func sampleAlert(ctx context.Context, host *plugin.Host, item config.Item) (alert.Alert, error) { + p, ok := host.Plugin(item.Shop) + if !ok { return alert.Alert{}, fmt.Errorf("no plugin named %q", item.Shop) } + + pageURL, err := p.Normalize(ctx, item.URLs[0]) + if err != nil { return alert.Alert{}, err } + + cartLink, err := p.CartLink(ctx, pageURL, "") + if err != nil { return alert.Alert{}, err } + + price := 99.99 + if item.MaxPrice != nil { price = *item.MaxPrice } + + currency := item.Currency + if currency == "" { currency = "EUR" } + + return alert.Alert{ + Item: item.Name, + Shop: item.Shop, + URL: pageURL, + Title: "Sample product title", + Price: &price, + Currency: currency, + Seller: plugin.SellerFirstParty, + CartLink: cartLink, + Time: time.Now(), + Test: true, + }, nil +} + +// fire logs an alert, rings the bell and sends the notifications in the +// background. sends tracks the sending so dibs can wait for it on exit. +func fire(logger *slog.Logger, n *notify.Notifier, sends *sync.WaitGroup, bell io.Writer, a alert.Alert) { + attrs := []any{"item", a.Item, "url", a.URL, "title", a.Title, "price", a.PriceText(), "seller", a.Seller} + if a.CartLink != "" { attrs = append(attrs, "cart_link", a.CartLink) } + if a.PreviousPrice != nil { attrs = append(attrs, "previous_price", alert.Money(*a.PreviousPrice, a.PreviousCurrency)) } + + logger.Info("ALERT", attrs...) + + if bell != nil { _, _ = io.WriteString(bell, "\a") } + + sends.Go(func() { + // Alerts still go out when dibs is stopped right after one fires. + ctx, cancel := context.WithTimeout(context.Background(), sendTimeout) + defer cancel() + + if err := n.Send(ctx, a); err != nil { + logger.Warn("notification failed", "item", a.Item, "err", err) + return + } + + logger.Info("notified", "item", a.Item, "channels", n.Channels()) + }) +} + +func userAgent() string { return "dibs/" + version } diff --git a/cmd/dibs/watch.go b/cmd/dibs/watch.go index d28762a..60e5ec5 100644 --- a/cmd/dibs/watch.go +++ b/cmd/dibs/watch.go @@ -6,10 +6,14 @@ import ( "log/slog" "os" "os/signal" + "sync" "syscall" "time" + "git.security-command.org/Overlord/dibs/internal/alert" "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/fx" + "git.security-command.org/Overlord/dibs/internal/notify" "git.security-command.org/Overlord/dibs/internal/watch" ) @@ -37,20 +41,64 @@ func runWatch(cfg *config.Config, headless bool, stdout, stderr io.Writer) int { for _, w := range warnings { logger.Warn(w) } + rates := fx.New(e.store, e.limiter) + if needsRates(cfg) { rates.Warm() } + + alerts := alert.NewEngine(cfg.Notify.Cooldown.Duration, rates, e.store) + notifier := notify.New(cfg.Notify, userAgent()) + + var bell io.Writer + if isTerminal(stderr) { bell = stderr } + statuses := sched.Statuses() - logger.Info("watching", "items", len(cfg.Items), "urls", len(statuses)) + logger.Info("watching", "items", len(cfg.Items), "urls", len(statuses), "notify", notifier.Channels()) go sched.Run(ctx) + var sends sync.WaitGroup + for r := range sched.Results() { logResult(logger, r) e.save(logger) + + if r.Err != nil { continue } + + a, why, err := alerts.Consider(ctx, r.Item, r.Report, r.Time) + switch { + case err != nil: + logger.Warn("available, but the price cannot be checked", "item", r.Item.Name, "url", r.URL, "err", err) + case why != "": + logger.Info("available, not alerting", "item", r.Item.Name, "url", r.URL, "reason", why) + case a != nil: + fire(logger, notifier, &sends, bell, *a) + } } + // A second Ctrl-C stops dibs without waiting for notifications. + stop() + sends.Wait() + logger.Info("stopped") return 0 } +// needsRates reports whether any item may need a currency conversion. +func needsRates(cfg *config.Config) bool { + for _, it := range cfg.Items { + if it.Currency != "" { return true } + } + + return false +} + +func isTerminal(w io.Writer) bool { + f, ok := w.(*os.File) + if !ok { return false } + + info, err := f.Stat() + return err == nil && info.Mode()&os.ModeCharDevice != 0 +} + func logResult(logger *slog.Logger, r watch.Result) { attrs := []any{"item", r.Item.Name, "url", r.URL, "next", r.Next.Format(time.RFC3339)} diff --git a/go.mod b/go.mod index bccf0a7..4f27491 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,7 @@ require ( ) require ( + git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect github.com/andybalholm/brotli v1.2.0 // indirect github.com/bdandy/go-errors v1.2.2 // indirect github.com/bdandy/go-socks4 v1.2.3 // indirect @@ -21,8 +22,17 @@ require ( github.com/bogdanfinn/utls v1.7.8-barnius // indirect github.com/bogdanfinn/websocket v1.5.6-barnius // indirect github.com/cloudflare/circl v1.6.5 // indirect + github.com/esiqveland/notify v0.13.3 // indirect + github.com/gen2brain/beeep v0.11.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/jackmordaunt/icns/v3 v3.0.1 // indirect github.com/klauspost/compress v1.18.2 // indirect + github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect github.com/quic-go/qpack v0.6.0 // indirect + github.com/sergeymakinen/go-bmp v1.0.0 // indirect + github.com/sergeymakinen/go-ico v1.0.0-beta.0 // indirect + github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect golang.org/x/crypto v0.57.0 // indirect golang.org/x/text v0.42.0 // indirect diff --git a/go.sum b/go.sum index 00c4246..5c99e7d 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +git.sr.ht/~jackmordaunt/go-toast v1.1.2 h1:/yrfI55LRt1M7H1vkaw+NaH1+L1CDxrqDltwm5euVuE= +git.sr.ht/~jackmordaunt/go-toast v1.1.2/go.mod h1:jA4OqHKTQ4AFBdwrSnwnskUIIS3HYzlJSgdzCKqfavo= github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM= github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= @@ -20,18 +22,43 @@ github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2Xev github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA= github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/esiqveland/notify v0.13.3 h1:QCMw6o1n+6rl+oLUfg8P1IIDSFsDEb2WlXvVvIJbI/o= +github.com/esiqveland/notify v0.13.3/go.mod h1:hesw/IRYTO0x99u1JPweAl4+5mwXJibQVUcP0Iu5ORE= +github.com/gen2brain/beeep v0.11.2 h1:+KfiKQBbQCuhfJFPANZuJ+oxsSKAYNe88hIpJuyKWDA= +github.com/gen2brain/beeep v0.11.2/go.mod h1:jQVvuwnLuwOcdctHn/uyh8horSBNJ8uGb9Cn2W4tvoc= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8D4S3o= +github.com/jackmordaunt/icns/v3 v3.0.1/go.mod h1:5sHL59nqTd2ynTnowxB/MDQFhKNqkK8X687uKNygaSQ= github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/sergeymakinen/go-bmp v1.0.0 h1:SdGTzp9WvCV0A1V0mBeaS7kQAwNLdVJbmHlqNWq0R+M= +github.com/sergeymakinen/go-bmp v1.0.0/go.mod h1:/mxlAQZRLxSvJFNIEGGLBE/m40f3ZnUifpgVDlcUIEY= +github.com/sergeymakinen/go-ico v1.0.0-beta.0 h1:m5qKH7uPKLdrygMWxbamVn+tl2HfiA3K6MFJw4GfZvQ= +github.com/sergeymakinen/go-ico v1.0.0-beta.0/go.mod h1:wQ47mTczswBO5F0NoDt7O0IXgnV4Xy3ojrroMQzyhUk= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk= +github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o= github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc= github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= @@ -47,6 +74,7 @@ golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -54,5 +82,7 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/alert/alert.go b/internal/alert/alert.go new file mode 100644 index 0000000..42cf882 --- /dev/null +++ b/internal/alert/alert.go @@ -0,0 +1,257 @@ +// Package alert decides when an item fires: when one of its pages offers it +// from an accepted seller at an accepted price, and the item's cooldown +// allows another alert. +package alert + +import ( + "context" + "fmt" + "math" + "strconv" + "sync" + "time" + + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/plugin" +) + +// Alert is one item becoming buyable. +type Alert struct { + Item string + Shop string + // URL is the product page, as the plugin normalized it. + URL string + Title string + Price *float64 + Currency string + // Converted is Price in the item's currency, when the page uses another + // one and the conversion worked. + Converted *float64 + ConvertedCurrency string + Seller string + CartLink string + Time time.Time + // PreviousPrice is the price of the last alert, when this one fires + // during the cooldown because the price dropped below it. + PreviousPrice *float64 + PreviousCurrency string + // Test marks the sample alert of `dibs notify test`. + Test bool +} + +// PriceText is the price as notifications show it, such as "129.99 EUR" or +// "149.99 USD (≈ 133.95 EUR)". +func (a Alert) PriceText() string { + if a.Price == nil { return "price unknown" } + + s := Money(*a.Price, a.Currency) + if a.Converted != nil { s += " (≈ " + Money(*a.Converted, a.ConvertedCurrency) + ")" } + + return s +} + +// SellerText describes the seller for notifications. +func (a Alert) SellerText() string { + switch a.Seller { + case plugin.SellerFirstParty: + return "sold by " + a.Shop + case plugin.SellerFulfilled: + return "shipped by " + a.Shop + case plugin.SellerThirdParty: + return "marketplace seller" + default: + return "seller unknown" + } +} + +func Money(amount float64, currency string) string { + s := strconv.FormatFloat(amount, 'f', 2, 64) + if currency != "" { s += " " + currency } + + return s +} + +// Converter is fx.Service. +type Converter interface { + Convert(ctx context.Context, amount float64, from, to string) (float64, error) +} + +// Sent is what an item's cooldown remembers about its last alert. +type Sent struct { + Time time.Time `json:"time"` + Price *float64 `json:"price,omitempty"` + Currency string `json:"currency,omitempty"` + // ItemPrice is the price in the item's currency, so that pages in + // different currencies compare. + ItemPrice *float64 `json:"item_price,omitempty"` + ItemCurrency string `json:"item_currency,omitempty"` +} + +// Store keeps the cooldowns between runs and shares them with other dibs +// processes. Lock is held from loading an item's last alert until the new +// one is stored, so two processes never both send it. +type Store interface { + Lock() func() + LoadAlert(item string) (Sent, bool) + StoreAlert(item string, s Sent) +} + +// Engine turns check results into alerts. It is safe for concurrent use. +type Engine struct { + cooldown time.Duration + fx Converter + store Store + + mu sync.Mutex + sent map[string]Sent // used when store is nil +} + +// NewEngine returns an engine. store may be nil to keep cooldowns in memory. +func NewEngine(cooldown time.Duration, fx Converter, store Store) *Engine { + return &Engine{cooldown: cooldown, fx: fx, store: store, sent: map[string]Sent{}} +} + +// Consider decides whether a checked page makes its item fire. It returns +// the alert, or why an available page does not fire. A page that is not +// available returns neither. An error means the price could not be checked, +// such as when no current exchange rate is available. +func (e *Engine) Consider(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (*Alert, string, error) { + if rep == nil || rep.Result == nil || !rep.Result.Available { return nil, "", nil } + + a, why, err := e.qualify(ctx, item, rep, now) + if a == nil { return nil, why, err } + + unlock := e.lock() + defer unlock() + + next := a.sent(item.Currency) + + last, ok := e.load(item.Name) + allowed, drop := Allows(last, ok, next, e.cooldown) + + switch { + case !allowed: + return nil, "in cooldown until " + last.Time.Add(e.cooldown).Format(time.TimeOnly), nil + case drop && last.Currency == next.Currency: + a.PreviousPrice, a.PreviousCurrency = last.Price, last.Currency + case drop: + a.PreviousPrice, a.PreviousCurrency = last.ItemPrice, last.ItemCurrency + } + + e.save(item.Name, next) + + return a, "", nil +} + +// sent is what the cooldown remembers of a. +func (a *Alert) sent(itemCurrency string) Sent { + s := Sent{Time: a.Time, Price: a.Price, Currency: a.Currency} + + switch { + case a.Converted != nil: + s.ItemPrice, s.ItemCurrency = a.Converted, a.ConvertedCurrency + case a.Price != nil && (a.Currency == itemCurrency || a.Currency == "" || itemCurrency == ""): + s.ItemPrice, s.ItemCurrency = a.Price, itemCurrency + } + + return s +} + +// qualify checks an available page against the item's seller policy and +// max_price. +func (e *Engine) qualify(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (*Alert, string, error) { + res := rep.Result + + if !item.AcceptsSeller(res.Seller) { return nil, fmt.Sprintf("seller is %s, the item accepts %s", res.Seller, item.Seller), nil } + + a := &Alert{ + Item: item.Name, + Shop: rep.Shop, + URL: rep.FetchURL, + Title: res.Title, + Price: res.Price, + Currency: res.Currency, + Seller: res.Seller, + CartLink: rep.CartLink, + Time: now, + } + + // A page without a currency is taken to use the item's. + foreign := item.Currency != "" && res.Currency != "" && res.Currency != item.Currency + + var convErr error + if foreign && res.Price != nil { + v, err := e.fx.Convert(ctx, *res.Price, res.Currency, item.Currency) + v = math.Round(v*100) / 100 + if err == nil { a.Converted, a.ConvertedCurrency = &v, item.Currency } else { convErr = err } + } + + if item.MaxPrice == nil { return a, "", nil } + + limit := *item.MaxPrice + + switch { + case res.Price == nil: + return nil, "no price on the page to compare with max_price", nil + case foreign && convErr != nil: + return nil, "", fmt.Errorf("cannot compare %s with max_price %s: %w", Money(*res.Price, res.Currency), Money(limit, item.Currency), convErr) + case foreign: + if p := *a.Converted * (1 + item.FXMargin); p > limit { + return nil, fmt.Sprintf("price %s with fx_margin is above max_price %s", Money(p, item.Currency), Money(limit, item.Currency)), nil + } + case *res.Price > limit: + return nil, fmt.Sprintf("price %s is above max_price %s", Money(*res.Price, res.Currency), Money(limit, item.Currency)), nil + } + + return a, "", nil +} + +// Allows applies an item's cooldown: after an alert, the item stays quiet +// for cooldown unless its price drops below the last alert's. It also +// reports whether next is for such a drop. +// +// Prices in the same page currency compare as they are, so that exchange +// rates moving overnight never look like a price drop. Prices in different +// currencies compare in the item's currency. +func Allows(last Sent, hasLast bool, next Sent, cooldown time.Duration) (allowed, drop bool) { + if !hasLast || !next.Time.Before(last.Time.Add(cooldown)) { return true, false } + + switch { + case next.Price != nil && last.Price != nil && next.Currency == last.Currency: + drop = *next.Price < *last.Price + case next.ItemPrice != nil && last.ItemPrice != nil && next.ItemCurrency == last.ItemCurrency: + drop = *next.ItemPrice < *last.ItemPrice + default: + // Without a price in a shared currency, nothing compares. + } + + return drop, drop +} + +func (e *Engine) lock() func() { + if e.store == nil { return func() {} } + + return e.store.Lock() +} + +func (e *Engine) load(item string) (Sent, bool) { + if e.store != nil { return e.store.LoadAlert(item) } + + e.mu.Lock() + defer e.mu.Unlock() + + s, ok := e.sent[item] + return s, ok +} + +func (e *Engine) save(item string, s Sent) { + if e.store != nil { + e.store.StoreAlert(item, s) + return + } + + e.mu.Lock() + defer e.mu.Unlock() + + e.sent[item] = s +} diff --git a/internal/alert/alert_test.go b/internal/alert/alert_test.go new file mode 100644 index 0000000..cbac9f4 --- /dev/null +++ b/internal/alert/alert_test.go @@ -0,0 +1,135 @@ +package alert + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/plugin" +) + +// usdPerEUR converts USD and EUR at a fixed rate, or fails when down. +type usdPerEUR struct { + rate float64 + down bool +} + +func (c usdPerEUR) Convert(_ context.Context, amount float64, from, to string) (float64, error) { + switch { + case c.down: + return 0, errors.New("no rates") + case from == "USD" && to == "EUR": + return amount / c.rate, nil + case from == "EUR" && to == "USD": + return amount * c.rate, nil + default: + return 0, errors.New("unexpected conversion " + from + " to " + to) + } +} + +func page(price float64, currency, seller string) *plugin.Report { + return &plugin.Report{ + Shop: "amazon", + FetchURL: "https://www.amazon.de/dp/B0HMX2FSTF", + Result: &plugin.Result{Title: "Metro", Available: true, Price: &price, Currency: currency, Seller: seller}, + } +} + +func metro(maxPrice float64) config.Item { + return config.Item{Name: "metro", Shop: "amazon", MaxPrice: &maxPrice, Currency: "EUR", Seller: config.SellerFulfilled} +} + +// TestCooldown follows one item through a day of restocks. +func TestCooldown(t *testing.T) { + ctx := context.Background() + start := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + fx := &usdPerEUR{rate: 1.25} + e := NewEngine(30*time.Minute, fx, nil) + it := metro(130) + + steps := []struct { + name string + after time.Duration + report *plugin.Report + fires bool + prev string // the previous price a price-drop alert shows + } { + {"first alert", 0, page(129.99, "EUR", plugin.SellerFirstParty), true, ""}, + {"same price in cooldown", 5 * time.Minute, page(129.99, "EUR", plugin.SellerFirstParty), false, ""}, + {"higher price in cooldown", 10 * time.Minute, page(129.995, "EUR", plugin.SellerFulfilled), false, ""}, + {"price drop in cooldown", 15 * time.Minute, page(119.99, "EUR", plugin.SellerFirstParty), true, "129.99 EUR"}, + {"drop restarted the cooldown", 40 * time.Minute, page(119.99, "EUR", plugin.SellerFirstParty), false, ""}, + {"cooldown over", 45 * time.Minute, page(125, "EUR", plugin.SellerFirstParty), true, ""}, + // 140 USD is 112 EUR, cheaper than 125 EUR. + {"cheaper in another currency", 50 * time.Minute, page(140, "USD", plugin.SellerFirstParty), true, "125.00 EUR"}, + // Same currency as the last alert: compared in USD, so the euro + // strengthening to 1.30 USD does not make it a drop to 107.69 EUR. + {"same USD price, new rate", 55 * time.Minute, page(140, "USD", plugin.SellerFirstParty), false, ""}, + } + + for _, st := range steps { + if strings.HasSuffix(st.name, "new rate") { fx.rate = 1.30 } + + a, why, err := e.Consider(ctx, it, st.report, start.Add(st.after)) + if err != nil { t.Fatalf("%s: %v", st.name, err) } + + if fired := a != nil; fired != st.fires { t.Errorf("%s: fired = %v, want %v (%s)", st.name, fired, st.fires, why) } + if a == nil { continue } + + prev := "" + if a.PreviousPrice != nil { prev = Money(*a.PreviousPrice, a.PreviousCurrency) } + if prev != st.prev { t.Errorf("%s: previous price %q, want %q", st.name, prev, st.prev) } + } +} + +func TestQualify(t *testing.T) { + ctx := context.Background() + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + + noPrice := page(0, "EUR", plugin.SellerFirstParty) + noPrice.Result.Price = nil + + withMargin := metro(120) + withMargin.FXMargin = 0.1 + + anySeller := metro(130) + anySeller.Seller = config.SellerAny + + noLimit := config.Item{Name: "metro", Currency: "EUR", Seller: config.SellerAny} + + cases := []struct { + name string + item config.Item + report *plugin.Report + fx usdPerEUR + want string // "fire", "error" or part of the reason + } { + {"at max_price", metro(129.99), page(129.99, "EUR", plugin.SellerFirstParty), usdPerEUR{}, "fire"}, + {"above max_price", metro(129.99), page(130, "EUR", plugin.SellerFirstParty), usdPerEUR{}, "above max_price"}, + {"marketplace seller", metro(130), page(99, "EUR", plugin.SellerThirdParty), usdPerEUR{}, "seller is third_party"}, + {"unknown seller, any", anySeller, page(99, "EUR", plugin.SellerUnknown), usdPerEUR{}, "fire"}, + {"no price", metro(130), noPrice, usdPerEUR{}, "no price"}, + // 125 USD is 100 EUR, 110 EUR with the margin. + {"converted within", withMargin, page(125, "USD", plugin.SellerFirstParty), usdPerEUR{rate: 1.25}, "fire"}, + // 140 USD is 112 EUR, 123.20 EUR with the margin. + {"margin tips it over", withMargin, page(140, "USD", plugin.SellerFirstParty), usdPerEUR{rate: 1.25}, "with fx_margin is above"}, + {"no rates", metro(130), page(99, "USD", plugin.SellerFirstParty), usdPerEUR{down: true}, "error"}, + {"no rates, no max_price", noLimit, page(99, "USD", plugin.SellerFirstParty), usdPerEUR{down: true}, "fire"}, + } + + for _, c := range cases { + a, why, err := NewEngine(time.Hour, c.fx, nil).Consider(ctx, c.item, c.report, now) + + switch { + case c.want == "fire" && a == nil: + t.Errorf("%s: did not fire: %s %v", c.name, why, err) + case c.want == "error" && err == nil: + t.Errorf("%s: no error (fired: %v, reason %q)", c.name, a != nil, why) + case c.want != "fire" && c.want != "error" && !strings.Contains(why, c.want): + t.Errorf("%s: reason %q, want %q (fired: %v, err %v)", c.name, why, c.want, a != nil, err) + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 1939de4..34e7819 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -18,6 +18,10 @@ import ( // scheduler enforces it too, whatever the config says. const MinInterval = ratelimit.URLFloor +// MaxCooldown is the longest allowed cooldown. The state file forgets alerts +// after it. +const MaxCooldown = 7 * 24 * time.Hour + const ( // The seller policies accept offers sold by the shop itself, offers it // sells or only ships (such as Fulfilled by Amazon), or any offer. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c779fd0..c643f67 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -288,7 +288,7 @@ call_stack = 1 wantErr(t, es, "accounts.ebay", 26, `no plugin named "ebay"`) wantErr(t, es, "notify.webhooks[1].format", 31, `got "slack"`) wantErr(t, es, "notify.webhooks[2].url", 32, "missing required key") - wantErr(t, es, "notify.cooldown", 34, "negative") + wantErr(t, es, "notify.cooldown", 34, "between 0s and 168h") wantErr(t, es, "plugins.Bad Name", 37, "plugin name") wantErr(t, es, "plugins.missing", 38, "cannot read plugin") wantErr(t, es, "sandbox.timeout", 41, "between 100ms and 30s") diff --git a/internal/config/validate.go b/internal/config/validate.go index 9126d95..fb3bcbd 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -314,8 +314,8 @@ func (v *validator) notify(n *Notify) { } } - if n.Cooldown.Duration < 0 { - v.errorf("notify.cooldown", "must not be negative (got %s)", n.Cooldown) + if n.Cooldown.Duration < 0 || n.Cooldown.Duration > MaxCooldown { + v.errorf("notify.cooldown", "must be between 0s and %gh (got %s)", MaxCooldown.Hours(), n.Cooldown) } } diff --git a/internal/fx/fx.go b/internal/fx/fx.go new file mode 100644 index 0000000..7911e6c --- /dev/null +++ b/internal/fx/fx.go @@ -0,0 +1,266 @@ +// Package fx converts prices between currencies with the ECB's daily +// reference rates. +package fx + +import ( + "context" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "sync" + "time" +) + +// RatesURL is the ECB's feed of the latest reference rates. It needs no API +// key and changes once per working day, around 16:00 CET. +const RatesURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" + +const ( + // Rates fetched more than refreshAfter ago are refreshed in the + // background while still in use. + refreshAfter = 6 * time.Hour + // MaxAge is how long rates stay usable without a successful refresh. + MaxAge = 72 * time.Hour + // retryAfter spaces out refreshes after one fails. + retryAfter = 15 * time.Minute + fetchTimeout = 30 * time.Second +) + +// Rates are the ECB reference rates of one day. +type Rates struct { + // Date is the ECB's publication day, as YYYY-MM-DD. + Date string `json:"date"` + // Fetched is when the rates were last downloaded, even if the ECB had + // not published newer ones. + Fetched time.Time `json:"fetched"` + // PerEUR is how much of each currency one euro buys. + PerEUR map[string]float64 `json:"per_eur"` +} + +// Convert converts amount from one currency to another, through the euro. +func (r *Rates) Convert(amount float64, from, to string) (float64, error) { + if from == to { return amount, nil } + + f, err := r.perEUR(from) + if err != nil { return 0, err } + + t, err := r.perEUR(to) + if err != nil { return 0, err } + + return amount / f * t, nil +} + +func (r *Rates) perEUR(currency string) (float64, error) { + if currency == "EUR" { return 1, nil } + + if rate, ok := r.PerEUR[currency]; ok && rate > 0 { return rate, nil } + + return 0, fmt.Errorf("the ECB publishes no rate for %s", currency) +} + +// Store keeps the rates between runs and shares them with other dibs +// processes. +type Store interface { + Lock() func() + LoadRates() (*Rates, bool) + StoreRates(r *Rates) +} + +// Limiter is ratelimit.Limiter, which spaces out the requests to the ECB +// like every other request dibs makes. +type Limiter interface { + WaitCheck(ctx context.Context, url string) error +} + +// Service hands out current rates and refreshes them when they are due. It +// is safe for concurrent use. +type Service struct { + store Store + limiter Limiter + client *http.Client + url string + now func() time.Time + + mu sync.Mutex + rates *Rates + lastTry time.Time + lastErr error + inflight chan struct{} // closed when the running refresh ends +} + +func New(store Store, limiter Limiter) *Service { + return &Service{ + store: store, + limiter: limiter, + client: &http.Client{Timeout: fetchTimeout}, + url: RatesURL, + now: time.Now, + } +} + +// Warm starts a refresh in the background if the rates are due for one, so +// the first conversion does not wait for the network. +func (s *Service) Warm() { + s.mu.Lock() + defer s.mu.Unlock() + + s.load() + if s.due() { s.startRefresh() } +} + +// Convert converts amount with the newest usable rates. When the rates are +// older than MaxAge, it waits for a refresh; if that fails, it fails too. +func (s *Service) Convert(ctx context.Context, amount float64, from, to string) (float64, error) { + if from == to { return amount, nil } + + r, err := s.current(ctx) + if err != nil { return 0, err } + + return r.Convert(amount, from, to) +} + +func (s *Service) current(ctx context.Context) (*Rates, error) { + s.mu.Lock() + + s.load() + if s.due() { s.startRefresh() } + + if s.usable() { + r := s.rates + s.mu.Unlock() + + return r, nil + } + + wait := s.inflight + s.mu.Unlock() + + if wait != nil { + select { + case <-wait: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + + s.mu.Lock() + defer s.mu.Unlock() + + if s.usable() { return s.rates, nil } + + var cause string + if s.lastErr != nil { cause = ": " + s.lastErr.Error() } + + return nil, fmt.Errorf("no exchange rates younger than %s%s", MaxAge, cause) +} + +// load picks up rates another dibs process may have fetched. Callers hold +// mu. +func (s *Service) load() { + if s.store == nil { return } + + if r, ok := s.store.LoadRates(); ok && (s.rates == nil || r.Fetched.After(s.rates.Fetched)) { s.rates = r } +} + +// due reports whether a refresh should start. Callers hold mu. +func (s *Service) due() bool { + now := s.now() + + switch { + case s.inflight != nil: + return false + case !s.lastTry.IsZero() && now.Sub(s.lastTry) < retryAfter: + return false + case s.rates == nil: + return true + default: + return now.Sub(s.rates.Fetched) >= refreshAfter + } +} + +// usable reports whether the rates are young enough to use. Callers hold +// mu. +func (s *Service) usable() bool { + return s.rates != nil && s.now().Sub(s.rates.Fetched) < MaxAge +} + +// startRefresh fetches the rates in the background. Callers hold mu. +func (s *Service) startRefresh() { + done := make(chan struct{}) + s.inflight = done + s.lastTry = s.now() + + go func() { + defer close(done) + + ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout+time.Minute) + defer cancel() + + r, err := s.fetch(ctx) + + s.mu.Lock() + s.inflight, s.lastErr = nil, err + if err == nil { s.rates = r } + s.mu.Unlock() + + if err == nil && s.store != nil { + unlock := s.store.Lock() + s.store.StoreRates(r) + unlock() + } + }() +} + +func (s *Service) fetch(ctx context.Context) (*Rates, error) { + if s.limiter != nil { + if err := s.limiter.WaitCheck(ctx, s.url); err != nil { return nil, err } + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.url, nil) + if err != nil { return nil, err } + + resp, err := s.client.Do(req) + if err != nil { return nil, fmt.Errorf("fetching exchange rates: %w", err) } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetching exchange rates: %s", resp.Status) } + + r, err := Parse(io.LimitReader(resp.Body, 1<<20)) + if err != nil { return nil, err } + + r.Fetched = s.now() + return r, nil +} + +// Parse reads the ECB's eurofxref XML. +func Parse(rd io.Reader) (*Rates, error) { + var doc struct { + Days []struct { + Time string `xml:"time,attr"` + Rates []struct { + Currency string `xml:"currency,attr"` + Rate string `xml:"rate,attr"` + } `xml:"Cube"` + } `xml:"Cube>Cube"` + } + + if err := xml.NewDecoder(rd).Decode(&doc); err != nil { return nil, fmt.Errorf("reading exchange rates: %w", err) } + if len(doc.Days) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") } + + day := doc.Days[0] + r := &Rates{Date: day.Time, PerEUR: map[string]float64{}} + + for _, c := range day.Rates { + rate, err := strconv.ParseFloat(c.Rate, 64) + if err != nil || rate <= 0 { return nil, fmt.Errorf("reading exchange rates: bad rate %q for %s", c.Rate, c.Currency) } + + r.PerEUR[c.Currency] = rate + } + + if len(r.PerEUR) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") } + + return r, nil +} diff --git a/internal/fx/fx_test.go b/internal/fx/fx_test.go new file mode 100644 index 0000000..c022156 --- /dev/null +++ b/internal/fx/fx_test.go @@ -0,0 +1,28 @@ +package fx + +import ( + "math" + "testing" +) + +func TestConvert(t *testing.T) { + r := &Rates{PerEUR: map[string]float64{"USD": 1.25, "GBP": 0.8}} + + cases := []struct { + amount float64 + from, to string + want float64 + } { + {100, "EUR", "USD", 125}, + {125, "USD", "EUR", 100}, + {100, "GBP", "USD", 156.25}, + {100, "GBP", "GBP", 100}, + } + + for _, c := range cases { + got, err := r.Convert(c.amount, c.from, c.to) + if err != nil || math.Abs(got-c.want) > 1e-9 { t.Errorf("%v %s in %s = %v, %v; want %v", c.amount, c.from, c.to, got, err, c.want) } + } + + if _, err := r.Convert(1, "JPY", "EUR"); err == nil { t.Error("converted a currency without a rate") } +} diff --git a/internal/notify/notify.go b/internal/notify/notify.go new file mode 100644 index 0000000..b566946 --- /dev/null +++ b/internal/notify/notify.go @@ -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]) + "…" +} diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go new file mode 100644 index 0000000..21edf70 --- /dev/null +++ b/internal/notify/notify_test.go @@ -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) } + } +} diff --git a/internal/notify/payload.go b/internal/notify/payload.go new file mode 100644 index 0000000..75eab8e --- /dev/null +++ b/internal/notify/payload.go @@ -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 +} diff --git a/internal/state/state.go b/internal/state/state.go index 8d0d3af..2cbdbcf 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -12,20 +12,27 @@ import ( "sync" "time" + "git.security-command.org/Overlord/dibs/internal/alert" + "git.security-command.org/Overlord/dibs/internal/config" "git.security-command.org/Overlord/dibs/internal/fsutil" + "git.security-command.org/Overlord/dibs/internal/fx" "git.security-command.org/Overlord/dibs/internal/ratelimit" ) -// Hosts and URLs untouched for forgetAfter are dropped, such as URLs removed -// from the config. -const forgetAfter = 7 * 24 * time.Hour +// Hosts, URLs and alerts untouched for forgetAfter are dropped, such as URLs +// removed from the config. An alert is kept for as long as the longest +// cooldown lasts. +const forgetAfter = config.MaxCooldown type file struct { - Hosts map[string]ratelimit.HostState `json:"hosts"` - URLs map[string]time.Time `json:"urls"` + Hosts map[string]ratelimit.HostState `json:"hosts"` + URLs map[string]time.Time `json:"urls"` + Alerts map[string]alert.Sent `json:"alerts,omitempty"` + FX *fx.Rates `json:"fx,omitempty"` } -// Store is the state file. It implements ratelimit.Persister. +// Store is the state file. It implements ratelimit.Persister, alert.Store +// and fx.Store. type Store struct { path string lock string @@ -100,10 +107,36 @@ func (s *Store) StoreURL(url string, last time.Time) { }) } +func (s *Store) LoadAlert(item string) (alert.Sent, bool) { + s.mu.Lock() + defer s.mu.Unlock() + + a, ok := s.read().Alerts[item] + return a, ok +} + +func (s *Store) StoreAlert(item string, a alert.Sent) { + s.update(func(f *file) { f.Alerts[item] = a }) +} + +func (s *Store) LoadRates() (*fx.Rates, bool) { + s.mu.Lock() + defer s.mu.Unlock() + + r := s.read().FX + return r, r != nil +} + +func (s *Store) StoreRates(r *fx.Rates) { + s.update(func(f *file) { + if f.FX == nil || r.Fetched.After(f.FX.Fetched) { f.FX = r } + }) +} + // read returns the file's contents, or empty state if there is none yet. // Callers hold mu. func (s *Store) read() *file { - f := &file{Hosts: map[string]ratelimit.HostState{}, URLs: map[string]time.Time{}} + f := &file{Hosts: map[string]ratelimit.HostState{}, URLs: map[string]time.Time{}, Alerts: map[string]alert.Sent{}} data, err := os.ReadFile(s.path) switch { @@ -119,8 +152,9 @@ func (s *Store) read() *file { return f } - if f.Hosts == nil { f.Hosts = map[string]ratelimit.HostState{} } - if f.URLs == nil { f.URLs = map[string]time.Time{} } + if f.Hosts == nil { f.Hosts = map[string]ratelimit.HostState{} } + if f.URLs == nil { f.URLs = map[string]time.Time{} } + if f.Alerts == nil { f.Alerts = map[string]alert.Sent{} } return f } @@ -139,6 +173,9 @@ func (s *Store) update(change func(f *file)) { for url, t := range f.URLs { if t.Before(cutoff) { delete(f.URLs, url) } } + for item, a := range f.Alerts { + if a.Time.Before(cutoff) { delete(f.Alerts, item) } + } data, err := json.MarshalIndent(f, "", " ") if err == nil { err = fsutil.WriteFileAtomic(s.path, data, 0o600) }