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:
Overlord committed 2026-10-14 11:55:27 +02:00
1 parent 2175c0e5aa
commit 8f0eda5d4d
16 files changed
+1409 -15

No files matched your search

+5 -2
View File
@@ -23,7 +23,8 @@ const usage = `Usage:
dibs check [--shop NAME] <url> fetch and parse one URL, print JSON
dibs plugin test [--status CODE] <file.lua> <fixture.html> [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
+141
View File
@@ -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 }
+49 -1
View File
@@ -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)}