Files
dibs/internal/notify/notify.go
T
Overlord e2cbc1a55c Add the Chrome fallback and the needs-human flow.
Bot checks escalate to headless Chrome with stealth, which claims the
same identity as tls-client and hands its cookies back to the jar. The
visit counts against the rate limits. If Chrome can't clear a check,
the URL is marked needs-human. Pressing Enter on it in the TUI, or
running 'dibs solve', opens a visible window; dibs carries on once the
page loads. Processes now merge the cookie file on save, with the
newest cookie winning.
2026-10-14 14:08:56 +02:00

301 lines
8.2 KiB
Go

// 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...)
}
// Notice shows a desktop notification that is not an alert, such as a
// request to solve a captcha. It does nothing when desktop notifications
// are off.
func (n *Notifier) Notice(title, message string) error {
if !n.desktop { return nil }
return n.showToast(title, message)
}
// 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]) + "…"
}