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,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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user