Add session mode: signing in and adding to the cart.

With cart_mode = "session", dibs signs in to the shop's account and puts
an item in the cart when it fires. The account's cookies are kept apart
from the watcher's and stored encrypted, with the key in the OS keyring.
Without a keyring, they're stored in a file only you can read.

An alert now goes out right away, without a cart link, and a second one
follows once the item is in the cart. If adding fails, the second alert
carries the cart link instead.

Amazon only accepts additions its page scripts have seen, so plugins can
now press a button in headless Chrome with ctx:click.

The TUI asks for one-time codes and shows the plugin's warning about
account locks in a modal. 'dibs login' signs in from a terminal, or
with --browser in a Chrome window, and 'dibs logout' deletes the cookies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-14 17:26:26 +02:00
1 parent e2cbc1a55c
commit 15a34e1f84
39 files changed
+3529 -163

No files matched your search

+1 -2
View File
@@ -12,7 +12,6 @@ import (
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
"git.security-command.org/Overlord/dibs/internal/state"
"git.security-command.org/Overlord/dibs/internal/watch"
)
// env is what every command that talks to shops shares with every other
@@ -89,7 +88,7 @@ func (e *env) fetch(ctx context.Context, fetchURL string, get getter, logger *sl
resp, err := get(ctx, fetchURL)
if ctx.Err() == nil {
if u, perr := url.Parse(fetchURL); perr == nil {
if d := watch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) }
if d := fetch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) }
}
e.save(logger)
+181
View File
@@ -0,0 +1,181 @@
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"os/signal"
"slices"
"strings"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/plugin"
"git.security-command.org/Overlord/dibs/internal/session"
)
// runLogin implements `dibs login [--browser] <shop> [url]`: it signs in to
// the shop's account for session mode, on the site of url, or else on every
// site of the shop's URLs in the config.
func runLogin(args []string, stdout, stderr io.Writer) int {
flags, configPath := newFlagSet("dibs login", stderr)
browser := flags.Bool("browser", false, "sign in yourself in a Chrome window instead of letting the plugin sign in")
pos, ok := parseArgs(flags, args)
if !ok { return 2 }
if len(pos) < 1 || len(pos) > 2 {
_, _ = fmt.Fprintf(stderr, "dibs login: expected a shop and at most one URL\n\n%s", usage)
return 2
}
cfg, ok := loadConfig(*configPath, stderr)
if !ok { return 1 }
shop := pos[0]
acc, err := sessionAccount(cfg, shop)
if err != nil { return fail(stderr, "login", err) }
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, "login", err) }
defer host.Close()
if err := checkSessions(cfg, host); err != nil { return fail(stderr, "login", err) }
p, _ := host.Plugin(shop)
var sites []string
if len(pos) == 2 {
u, err := url.Parse(pos[1])
if err != nil || u.Hostname() == "" { return fail(stderr, "login", fmt.Errorf("not a URL: %q", pos[1])) }
sites = []string{u.Scheme + "://" + u.Host + "/"}
} else {
for _, it := range cfg.Items {
if it.Shop != shop { continue }
for _, raw := range it.URLs {
fetchURL, err := p.Normalize(ctx, raw)
if err != nil { return fail(stderr, "login", err) }
u, err := url.Parse(fetchURL)
if err != nil { continue }
if s := u.Scheme + "://" + u.Host + "/"; !slices.Contains(sites, s) { sites = append(sites, s) }
}
}
}
if len(sites) == 0 { return fail(stderr, "login", fmt.Errorf("the config has no URLs for %s: pass a URL on the site to sign in to", shop)) }
m, e, err := openSession(shop, logger)
if err != nil { return fail(stderr, "login", err) }
m.Update(acc, newTerminalPrompter(stderr))
failed := 0
for _, site := range sites {
u, _ := url.Parse(site)
if *browser {
// The configured login_url is for one site; any other starts
// from its home page.
loginURL := ""
if lu, err := url.Parse(acc.LoginURL); err == nil && strings.EqualFold(lu.Host, u.Host) { loginURL = acc.LoginURL }
_, _ = fmt.Fprintf(stdout, "Sign in to %s in the Chrome window, then close it.\n", u.Host)
err = m.BrowserLogin(ctx, site, loginURL)
} else {
err = m.Login(ctx, p, site)
}
switch {
case errors.Is(err, session.ErrDeclined):
_, _ = fmt.Fprintln(stdout, "Not signing in.")
return 1
case ctx.Err() != nil:
return 1
case err != nil:
_, _ = fmt.Fprintf(stderr, "dibs login: %s: %v\n", u.Host, err)
failed++
default:
_, _ = fmt.Fprintf(stdout, "Signed in to %s. A running dibs uses the session from its next addition to the cart.\n", u.Host)
}
}
e.save(logger)
if failed > 0 { return 1 }
return 0
}
// runLogout implements `dibs logout <shop>`: it deletes the shop's
// signed-in cookies, in running dibs processes too.
func runLogout(args []string, stdout, stderr io.Writer) int {
flags, configPath := newFlagSet("dibs logout", stderr)
pos, ok := parseArgs(flags, args)
if !ok { return 2 }
if len(pos) != 1 {
_, _ = fmt.Fprintf(stderr, "dibs logout: expected a shop\n\n%s", usage)
return 2
}
cfg, ok := loadOptionalConfig(*configPath, stderr)
if !ok { return 1 }
// The shop names a file, so it must be a plugin's name, which the
// config keeps to safe characters. Logging out needs no account in
// the config.
shop := pos[0]
if !slices.Contains(plugin.Builtins(), shop) && (cfg == nil || cfg.Plugins[shop] == "") { return fail(stderr, "logout", fmt.Errorf("no plugin named %q", shop)) }
logger := slog.New(slog.NewTextHandler(stderr, nil))
m, _, err := openSession(shop, logger)
if err != nil { return fail(stderr, "logout", err) }
if err := m.Logout(); err != nil { return fail(stderr, "logout", err) }
_, _ = fmt.Fprintf(stdout, "Signed out of %s: dibs deleted the account's cookies.\n", shop)
return 0
}
// sessionAccount returns the account of shop, which must be in session
// mode.
func sessionAccount(cfg *config.Config, shop string) (config.Account, error) {
acc, ok := cfg.Accounts[shop]
switch {
case !ok:
return acc, fmt.Errorf("the config has no [accounts.%s]", shop)
case acc.CartMode != config.CartModeSession:
return acc, fmt.Errorf("accounts.%s.cart_mode is %q: signing in is only for %q", shop, acc.CartMode, config.CartModeSession)
}
return acc, nil
}
func openSession(shop string, logger *slog.Logger) (*session.Manager, *env, error) {
e, err := openEnv(logger)
if err != nil { return nil, nil, err }
vault, err := session.OpenVault(e.dir)
if err != nil { logger.Warn(err.Error()) }
m, err := session.New(shop, vault, e.limiter, e.store, logger)
if err != nil { return nil, nil, err }
return m, e, nil
}
+36 -2
View File
@@ -10,6 +10,8 @@ import (
"os"
"runtime"
"runtime/debug"
"slices"
"strings"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/plugin"
@@ -19,9 +21,11 @@ import (
var version = "dev"
const usage = `Usage:
dibs [--config FILE] [--headless] watch items (TUI unless --headless)
dibs check [--shop NAME] [--chrome] <url> fetch and parse one URL, print JSON
dibs [--config FILE] [--headless] watch items (TUI unless --headless)
dibs check [--shop NAME] [--chrome] <url> fetch and parse one URL, print JSON
dibs solve [--shop NAME] <url> pass a bot check in a Chrome window
dibs login [--browser] <shop> [url] sign in to a shop for cart_mode = "session"
dibs logout <shop> delete a shop's signed-in cookies
dibs plugin test [--status CODE] <file.lua> <fixture.html> [url]
dibs config validate [--config FILE]
dibs notify test [--config FILE] [--item NAME] send a sample alert to every channel
@@ -33,7 +37,33 @@ func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
// commands are the subcommands run dispatches on.
var commands = []string{"config", "version", "check", "plugin", "fixtures", "notify", "solve", "login", "logout", "help"}
// commandFirst moves a --config given before the command behind it, so
// that "dibs --config f.toml logout amazon" works like "dibs logout
// --config f.toml amazon".
func commandFirst(args []string) []string {
n := 0
switch {
case len(args) > 0 && (strings.HasPrefix(args[0], "--config=") || strings.HasPrefix(args[0], "-config=")):
n = 1
case len(args) > 1 && (args[0] == "--config" || args[0] == "-config"):
n = 2
}
if n == 0 || len(args) <= n || !slices.Contains(commands, args[n]) { return args }
out := []string{args[n]}
out = append(out, args[:n]...)
return append(out, args[n+1:]...)
}
func run(args []string, stdout, stderr io.Writer) int {
args = commandFirst(args)
if len(args) > 0 {
switch args[0] {
case "config":
@@ -51,6 +81,10 @@ func run(args []string, stdout, stderr io.Writer) int {
return runNotify(args[1:], stdout, stderr)
case "solve":
return runSolve(args[1:], stdout, stderr)
case "login":
return runLogin(args[1:], stdout, stderr)
case "logout":
return runLogout(args[1:], stdout, stderr)
case "help", "-h", "--help":
_, _ = fmt.Fprint(stdout, usage)
return 0
+18
View File
@@ -0,0 +1,18 @@
package main
import (
"slices"
"testing"
)
func TestCommandFirst(t *testing.T) {
for _, tc := range []struct{ in, want []string } {
{[]string{"--config", "f.toml", "logout", "amazon"}, []string{"logout", "--config", "f.toml", "amazon"}},
{[]string{"--config=f.toml", "check", "URL"}, []string{"check", "--config=f.toml", "URL"}},
{[]string{"--config", "f.toml", "--headless"}, []string{"--config", "f.toml", "--headless"}},
{[]string{"--config", "f.toml"}, []string{"--config", "f.toml"}},
{[]string{"logout", "--config", "f.toml", "amazon"}, []string{"logout", "--config", "f.toml", "amazon"}},
} {
if got := commandFirst(tc.in); !slices.Equal(got, tc.want) { t.Errorf("commandFirst(%q) = %q, want %q", tc.in, got, tc.want) }
}
}
+92
View File
@@ -0,0 +1,92 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"github.com/charmbracelet/x/term"
"git.security-command.org/Overlord/dibs/internal/session"
)
// noPrompter is the prompter until the TUI or the terminal takes over.
type noPrompter struct{}
func (noPrompter) Prompt(context.Context, string, string, bool) (string, error) { return "", session.ErrNoPrompt }
func (noPrompter) Confirm(context.Context, string, string) (bool, error) { return false, session.ErrNoPrompt }
// terminalPrompter asks on stderr and reads the answer from stdin. Without
// a terminal on stdin, nobody is there to answer.
type terminalPrompter struct {
in *os.File
out io.Writer
lines *bufio.Reader
mu sync.Mutex
}
func newTerminalPrompter(stderr io.Writer) *terminalPrompter {
return &terminalPrompter{in: os.Stdin, out: stderr, lines: bufio.NewReader(os.Stdin)}
}
func (t *terminalPrompter) Prompt(ctx context.Context, title, label string, secret bool) (string, error) {
if !term.IsTerminal(t.in.Fd()) { return "", session.ErrNoPrompt }
t.mu.Lock()
defer t.mu.Unlock()
_, _ = fmt.Fprintf(t.out, "%s: %s: ", title, label)
return t.read(ctx, secret)
}
func (t *terminalPrompter) Confirm(ctx context.Context, title, message string) (bool, error) {
if !term.IsTerminal(t.in.Fd()) { return false, session.ErrNoPrompt }
t.mu.Lock()
defer t.mu.Unlock()
_, _ = fmt.Fprintf(t.out, "%s\n\n%s\n\nContinue? [y/N] ", title, message)
answer, err := t.read(ctx, false)
if err != nil { return false, err }
answer = strings.ToLower(strings.TrimSpace(answer))
return answer == "y" || answer == "yes", nil
}
// read reads one line. A read cannot be interrupted, so when ctx ends first,
// the line typed next is lost.
func (t *terminalPrompter) read(ctx context.Context, secret bool) (string, error) {
type answer struct {
text string
err error
}
done := make(chan answer, 1)
go func() {
if secret {
b, err := term.ReadPassword(t.in.Fd())
_, _ = fmt.Fprintln(t.out)
done <- answer{string(b), err}
return
}
line, err := t.lines.ReadString('\n')
done <- answer{strings.TrimRight(line, "\r\n"), err}
}()
select {
case a := <-done:
return a.text, a.err
case <-ctx.Done():
_, _ = fmt.Fprintln(t.out)
return "", ctx.Err()
}
}
+239
View File
@@ -0,0 +1,239 @@
package main
import (
"context"
"errors"
"fmt"
"maps"
"net/url"
"slices"
"strings"
"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"
"git.security-command.org/Overlord/dibs/internal/session"
)
// cartResult is the outcome of adding an item to the cart.
type cartResult struct {
Item string
// URL is the URL as configured.
URL string
// Link is the cart page, or the cart link if adding failed.
Link string
Err error
}
// checkSessions makes sure every shop in session mode has a plugin that can
// take it.
func checkSessions(cfg *config.Config, host *plugin.Host) error {
var errs []error
for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) {
acc := cfg.Accounts[shop]
if acc.CartMode != config.CartModeSession { continue }
p, ok := host.Plugin(shop)
switch {
case !ok:
errs = append(errs, fmt.Errorf("accounts.%s: no plugin named %q", shop, shop))
case !p.Has("add_to_cart"):
errs = append(errs, fmt.Errorf("accounts.%s: cart_mode is session, but plugin %s has no add_to_cart", shop, shop))
case acc.PasswordEnv != "" && !p.Has("login"):
errs = append(errs, fmt.Errorf("accounts.%s: password_env is set, but plugin %s has no login", shop, shop))
}
}
return errors.Join(errs...)
}
// applySessions sets up a session for every shop in session mode and drops
// the others. Reloads retry failed and declined logins.
func (w *watcher) applySessions(cfg *config.Config) {
// Opening the vault may wait for the user to unlock the keyring, so it
// happens before taking the lock.
if w.vault == nil && usesSessions(cfg) {
vault, err := session.OpenVault(w.env.dir)
if err != nil { w.logger.Warn(err.Error()) }
w.vault = vault
}
w.mu.Lock()
defer w.mu.Unlock()
w.failed, w.declined = map[string]bool{}, map[string]bool{}
for shop := range w.managers {
if cfg.Accounts[shop].CartMode != config.CartModeSession { delete(w.managers, shop) }
}
for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) {
acc := cfg.Accounts[shop]
if acc.CartMode != config.CartModeSession { continue }
m := w.managers[shop]
if m == nil {
var err error
if m, err = session.New(shop, w.vault, w.env.limiter, w.env.store, w.logger); err != nil {
w.logger.Warn("session mode unavailable, alerts carry cart links", "shop", shop, "err", err)
continue
}
w.managers[shop] = m
}
m.Update(acc, w)
}
}
func usesSessions(cfg *config.Config) bool {
for _, acc := range cfg.Accounts {
if acc.CartMode == config.CartModeSession { return true }
}
return false
}
// site is a shop site to sign in to.
type site struct {
shop string
host string
url string // such as https://www.amazon.de/
}
// sites are the sites of the watched URLs of shops in session mode.
func (w *watcher) sites() []site {
w.mu.Lock()
shops := slices.Collect(maps.Keys(w.managers))
w.mu.Unlock()
var out []site
for _, st := range w.sched.Statuses() {
if !slices.Contains(shops, st.Shop) { continue }
u, err := url.Parse(st.FetchURL)
if err != nil { continue }
s := site{shop: st.Shop, host: strings.ToLower(u.Hostname()), url: u.Scheme + "://" + u.Host + "/"}
if !slices.Contains(out, s) { out = append(out, s) }
}
return out
}
// signIn signs in to every site in session mode that has no session yet.
// A failed login is not retried until the next reload, since repeated
// failed logins are what gets accounts locked.
func (w *watcher) signIn() {
w.signingIn.Lock()
defer w.signingIn.Unlock()
for _, s := range w.sites() {
key := s.shop + " " + s.host
w.mu.Lock()
m, skip := w.managers[s.shop], w.declined[s.shop] || w.failed[key]
p, _ := w.host.Plugin(s.shop)
w.mu.Unlock()
if m == nil || skip || m.SignedIn(s.host) { continue }
if !m.HasPassword() {
w.logger.Warn("not signed in, so alerts carry cart links: sign in with dibs login "+s.shop+" --browser", "shop", s.shop, "host", s.host)
continue
}
err := m.Login(w.ctx, p, s.url)
switch {
case w.ctx.Err() != nil:
return
case errors.Is(err, session.ErrDeclined):
w.mu.Lock()
w.declined[s.shop] = true
w.mu.Unlock()
w.logger.Info("session mode off until the next reload, alerts carry cart links", "shop", s.shop)
case err != nil:
w.mu.Lock()
w.failed[key] = true
w.mu.Unlock()
w.logger.Warn("signing in failed, so alerts carry cart links until you sign in with dibs login "+s.shop, "shop", s.shop, "host", s.host, "err", err)
}
}
}
// sessionFor returns the session that puts items from rawURL's site in the
// cart, if session mode applies to it: the shop uses it, the user did not
// decline it, and dibs is signed in to the site.
func (w *watcher) sessionFor(shop, rawURL string) (*session.Manager, *plugin.Plugin) {
u, err := url.Parse(rawURL)
if err != nil { return nil, nil }
w.mu.Lock()
m, declined := w.managers[shop], w.declined[shop]
p, _ := w.host.Plugin(shop)
w.mu.Unlock()
if m == nil || declined || !m.SignedIn(u.Hostname()) { return nil, nil }
return m, p
}
// cart sends a fired item's alert at once, without a cart link, then adds
// the item to the cart and sends a second alert with the outcome.
func (w *watcher) cart(n *notify.Notifier, m *session.Manager, p *plugin.Plugin, configured string, a alert.Alert) {
first := a
first.Cart, first.CartLink = alert.CartAdding, ""
w.fire(n, first)
w.carts.Go(func() {
cartURL, err := m.AddToCart(w.ctx, p, a.URL)
next := a
res := cartResult{Item: a.Item, URL: configured}
switch {
case err == nil:
next.Cart, next.CartURL, next.CartLink = alert.CartAdded, cartURL, ""
res.Link = cartURL
case w.ctx.Err() != nil:
next.Cart, next.CartError = alert.CartFailed, "dibs was stopped before it finished"
default:
next.Cart, next.CartError = alert.CartFailed, err.Error()
}
if err != nil {
res.Link, res.Err = a.CartLink, err
w.logger.Warn("adding to the cart failed", "item", a.Item, "url", a.URL, "err", err)
}
w.fire(n, next)
w.onCart(res)
if errors.Is(err, plugin.ErrSignedOut) { go w.signIn() }
})
}
// Prompt asks the user for a login, and sends a desktop notification with
// the question: a login after the session runs out may ask long after the
// user last looked.
func (w *watcher) Prompt(ctx context.Context, title, label string, secret bool) (string, error) {
w.mu.Lock()
n := w.notifier
w.mu.Unlock()
if err := n.Notice("dibs needs you: "+title, label); err != nil { w.logger.Warn("desktop notification failed", "err", err) }
return w.prompter.Prompt(ctx, title, label, secret)
}
func (w *watcher) Confirm(ctx context.Context, title, message string) (bool, error) {
return w.prompter.Confirm(ctx, title, message)
}
+3
View File
@@ -31,6 +31,9 @@ func runTUI(cfg *config.Config, stderr io.Writer) int {
p := tea.NewProgram(tui.New(w, cfg.Path, logs), append(terminalOptions(), tea.WithContext(ctx))...)
w.prompter = tui.NewPrompter(p)
w.onCart = func(c cartResult) { p.Send(tui.CartMsg{Item: c.Item, URL: c.URL, Link: c.Link, Err: c.Err}) }
done := make(chan struct{})
go func() {
defer close(done)
+58 -5
View File
@@ -19,6 +19,7 @@ import (
"git.security-command.org/Overlord/dibs/internal/fx"
"git.security-command.org/Overlord/dibs/internal/notify"
"git.security-command.org/Overlord/dibs/internal/plugin"
"git.security-command.org/Overlord/dibs/internal/session"
"git.security-command.org/Overlord/dibs/internal/watch"
)
@@ -34,6 +35,8 @@ func runWatch(cfg *config.Config, headless bool, stdout, stderr io.Writer) int {
w, err := newWatcher(ctx, cfg, logger, slog.LevelInfo)
if err != nil { return fail(stderr, "watch", err) }
w.prompter = newTerminalPrompter(stderr)
ring := isTerminal(stderr)
w.run(func(c check) {
@@ -83,7 +86,22 @@ type watcher struct {
// told once, not on every retry.
humans map[string]bool
sends sync.WaitGroup
// Session mode. managers has a session per shop in session mode. The
// declined shops and the failed "shop host" logins fall back to cart
// links until the next reload.
vault *session.Vault
managers map[string]*session.Manager
declined map[string]bool
failed map[string]bool
// prompter reaches the user, and onCart sees the outcome of each
// addition to the cart. Both are set before run.
prompter session.Prompter
onCart func(cartResult)
signingIn sync.Mutex
sends sync.WaitGroup
carts sync.WaitGroup
}
func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, checkLevel slog.Level) (*watcher, error) {
@@ -93,6 +111,11 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch
host, err := newHost(cfg, logger)
if err != nil { return nil, err }
if err := checkSessions(cfg, host); err != nil {
host.Close()
return nil, err
}
sched, warnings, err := watch.New(ctx, cfg, host, e.client, e.limiter)
if err != nil {
host.Close()
@@ -109,6 +132,9 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch
rates: fx.New(e.store, e.limiter),
checkLevel: checkLevel,
humans: map[string]bool{},
managers: map[string]*session.Manager{},
prompter: noPrompter{},
onCart: func(cartResult) {},
}
w.apply(cfg, host)
@@ -117,25 +143,27 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch
return w, nil
}
// apply switches the alert settings and plugins to cfg's.
// apply switches the alert settings, plugins and sessions to cfg's.
func (w *watcher) apply(cfg *config.Config, host *plugin.Host) {
if needsRates(cfg) { w.rates.Warm() }
w.mu.Lock()
defer w.mu.Unlock()
if w.host != nil { w.retired = append(w.retired, w.host) }
w.cfg = cfg
w.host = host
w.alerts = alert.NewEngine(cfg.Notify.Cooldown.Duration, w.rates, w.env.store)
w.notifier = notify.New(cfg.Notify, userAgent())
w.mu.Unlock()
w.applySessions(cfg)
}
// run handles every check until the watcher's context ends. observe sees
// each check after it is logged and its alert is on its way.
func (w *watcher) run(observe func(check)) {
go w.sched.Run(w.ctx)
go w.signIn()
// Saving also takes in the cookies other dibs processes saved, such as
// those of a `dibs solve` for a host that is backed off here.
@@ -173,9 +201,19 @@ func (w *watcher) consider(r watch.Result) check {
c.Decision, c.PriceErr = alerts.Consider(w.ctx, r.Item, r.Report, r.Time)
m, p := w.sessionFor(r.Item.Shop, r.Report.FetchURL)
// In session mode, the cart link would add a second copy.
if m != nil && r.Report.CartLink != "" {
rep := *r.Report
rep.CartLink, c.Report = "", &rep
}
switch {
case c.PriceErr != nil:
w.logger.Warn("available, but the price cannot be checked", "item", r.Item.Name, "url", r.URL, "err", c.PriceErr)
case c.Decision.Alert != nil && m != nil:
w.cart(notifier, m, p, r.URL, *c.Decision.Alert)
case c.Decision.Alert != nil:
w.fire(notifier, *c.Decision.Alert)
case c.Decision.Reason != "":
@@ -190,8 +228,14 @@ func (w *watcher) fire(n *notify.Notifier, 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)) }
if a.Cart != "" { attrs = append(attrs, "cart", a.Cart) }
if a.CartURL != "" { attrs = append(attrs, "cart_url", a.CartURL) }
if a.CartError != "" { attrs = append(attrs, "cart_error", a.CartError) }
w.logger.Info("ALERT", attrs...)
msg := "ALERT"
if a.Cart == alert.CartAdded { msg = "IN CART" }
w.logger.Info(msg, attrs...)
if len(n.Channels()) == 0 { return }
@@ -266,6 +310,7 @@ func (w *watcher) Solve(fetchURL string) error {
// close waits for the notifications still being sent and releases the
// plugins.
func (w *watcher) close() {
w.carts.Wait()
w.sends.Wait()
w.mu.Lock()
@@ -306,6 +351,12 @@ func (w *watcher) Reload() ([]string, error) {
host, err := newHost(cfg, w.logger)
if err != nil { return nil, err }
if err := checkSessions(cfg, host); err != nil {
host.Close()
w.logger.Warn("config reload failed", "err", err)
return nil, err
}
warnings, err := w.sched.Reload(w.ctx, cfg, host)
if err != nil {
host.Close()
@@ -320,6 +371,8 @@ func (w *watcher) Reload() ([]string, error) {
for _, line := range summary { w.logger.Info("config reloaded", "change", line) }
for _, msg := range warnings { w.logger.Warn(msg) }
go w.signIn()
return summary, nil
}