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>
442 lines
10 KiB
Go
442 lines
10 KiB
Go
// Package tui is the interactive view of dibs: a table with one row per
|
|
// URL, a log pane and a status bar.
|
|
package tui
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"charm.land/bubbles/v2/viewport"
|
|
tea "charm.land/bubbletea/v2"
|
|
"github.com/pkg/browser"
|
|
|
|
"git.security-command.org/Overlord/dibs/internal/alert"
|
|
"git.security-command.org/Overlord/dibs/internal/config"
|
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
|
"git.security-command.org/Overlord/dibs/internal/plugin"
|
|
"git.security-command.org/Overlord/dibs/internal/watch"
|
|
)
|
|
|
|
const (
|
|
// tick is how often the table refreshes. It is also the flash rate.
|
|
tick = 500 * time.Millisecond
|
|
flashFor = 30 * time.Second
|
|
noteFor = 10 * time.Second
|
|
)
|
|
|
|
// maxLines is how many lines the log pane keeps.
|
|
const maxLines = 2000
|
|
|
|
// Controller is the running watcher.
|
|
type Controller interface {
|
|
Statuses() []watch.Status
|
|
Pause(item string, paused bool) bool
|
|
PauseAll(paused bool)
|
|
CheckNow(item string) bool
|
|
Reload() ([]string, error)
|
|
// Solve opens a visible browser on fetchURL for the user to pass its
|
|
// bot check. It blocks until the check is passed or the window closes.
|
|
Solve(fetchURL string) error
|
|
}
|
|
|
|
// CheckMsg is one finished check and what the alert engine made of it.
|
|
type CheckMsg struct {
|
|
Result watch.Result
|
|
Decision alert.Decision
|
|
PriceErr error
|
|
}
|
|
|
|
// CartMsg is the outcome of adding an item to the cart in session mode.
|
|
type CartMsg struct {
|
|
Item string
|
|
// URL is the URL as configured.
|
|
URL string
|
|
// Link is the cart page, or the cart link when adding failed. It is
|
|
// what enter opens from now on.
|
|
Link string
|
|
Err error
|
|
}
|
|
|
|
type (
|
|
tickMsg time.Time
|
|
logMsg LogLine
|
|
reloadMsg struct {
|
|
summary []string
|
|
err error
|
|
}
|
|
openMsg struct {
|
|
url string
|
|
err error
|
|
}
|
|
solveMsg struct {
|
|
host string
|
|
err error
|
|
}
|
|
)
|
|
|
|
// Status texts, as the STATUS column shows them.
|
|
const (
|
|
statusWatching = "watching"
|
|
statusAvailable = "AVAILABLE"
|
|
statusBlocked = "blocked"
|
|
statusNeedsHuman = "needs-human"
|
|
statusError = "error"
|
|
statusPaused = "paused"
|
|
)
|
|
|
|
// result is what the last check of a URL found.
|
|
type result struct {
|
|
status string
|
|
price string
|
|
seller string
|
|
cartLink string
|
|
flash time.Time // the row flashes until then
|
|
}
|
|
|
|
type Model struct {
|
|
ctl Controller
|
|
path string
|
|
lines <-chan LogLine
|
|
|
|
now time.Time
|
|
rows []watch.Status
|
|
results map[string]*result // by configured URL
|
|
cursor int
|
|
offset int // the first table row on screen
|
|
widths []int // the column widths, reset by resizes and reloads
|
|
|
|
logs []LogLine
|
|
log viewport.Model
|
|
logFocus bool
|
|
|
|
width, height int
|
|
|
|
note string
|
|
noteError bool
|
|
noteTime time.Time
|
|
reloading bool
|
|
solving string // the host whose bot check is open in a browser
|
|
modal *modal
|
|
}
|
|
|
|
// New returns the TUI for ctl. path is the config file, and logs is the
|
|
// handler the watcher logs to.
|
|
func New(ctl Controller, path string, logs *LogHandler) *Model {
|
|
// The browser's own output would draw over the TUI.
|
|
browser.Stdout, browser.Stderr = io.Discard, io.Discard
|
|
|
|
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(path, home+string(os.PathSeparator)) { path = "~" + path[len(home):] }
|
|
|
|
m := &Model{
|
|
ctl: ctl,
|
|
path: path,
|
|
lines: logs.sink.lines,
|
|
now: time.Now(),
|
|
results: map[string]*result{},
|
|
log: viewport.New(),
|
|
}
|
|
m.rows = ctl.Statuses()
|
|
|
|
return m
|
|
}
|
|
|
|
func (m *Model) Init() tea.Cmd {
|
|
return tea.Batch(m.tick(), m.nextLine())
|
|
}
|
|
|
|
func (m *Model) tick() tea.Cmd {
|
|
return tea.Tick(tick, func(t time.Time) tea.Msg { return tickMsg(t) })
|
|
}
|
|
|
|
func (m *Model) nextLine() tea.Cmd {
|
|
return func() tea.Msg { return logMsg(<-m.lines) }
|
|
}
|
|
|
|
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
switch msg := msg.(type) {
|
|
case tea.WindowSizeMsg:
|
|
m.width, m.height = msg.Width, msg.Height
|
|
m.widths = nil
|
|
m.layout()
|
|
case tickMsg:
|
|
m.now = time.Time(msg)
|
|
m.rows = m.ctl.Statuses()
|
|
m.clampCursor()
|
|
return m, m.tick()
|
|
case logMsg:
|
|
m.addLog(LogLine(msg))
|
|
return m, m.nextLine()
|
|
case CheckMsg:
|
|
return m, m.checked(msg)
|
|
case reloadMsg:
|
|
m.reloading = false
|
|
m.rows = m.ctl.Statuses()
|
|
m.widths = nil
|
|
m.clampCursor()
|
|
if msg.err != nil { m.setNote(reloadError(msg.err), true) } else { m.setNote(reloadNote(msg.summary), false) }
|
|
case solveMsg:
|
|
m.solving = ""
|
|
if msg.err != nil { m.setNote("bot check on "+msg.host+" not solved: "+msg.err.Error(), true) } else { m.setNote("bot check on "+msg.host+" solved, checking again", false) }
|
|
m.rows = m.ctl.Statuses()
|
|
case openMsg:
|
|
if msg.err != nil { m.setNote("cannot open the browser: "+msg.err.Error(), true) } else { m.setNote("opened "+msg.url, false) }
|
|
case CartMsg:
|
|
m.carted(msg)
|
|
case promptMsg:
|
|
if m.modal != nil { m.answer(promptReply{}) }
|
|
|
|
var cmd tea.Cmd
|
|
m.modal, cmd = newModal(msg)
|
|
return m, tea.Batch(cmd, tea.Raw("\a"))
|
|
case closePromptMsg:
|
|
if m.modal != nil && m.modal.msg.id == msg.id { m.modal = nil }
|
|
case tea.KeyPressMsg:
|
|
if m.modal != nil { return m, m.modalKey(msg) }
|
|
|
|
return m, m.key(msg)
|
|
default:
|
|
// The modal's cursor blinks.
|
|
if m.modal != nil {
|
|
var cmd tea.Cmd
|
|
m.modal.input, cmd = m.modal.input.Update(msg)
|
|
return m, cmd
|
|
}
|
|
}
|
|
|
|
return m, nil
|
|
}
|
|
|
|
// carted records the outcome of adding an item to the cart.
|
|
func (m *Model) carted(c CartMsg) {
|
|
r := m.results[c.URL]
|
|
if r == nil {
|
|
r = &result{}
|
|
m.results[c.URL] = r
|
|
}
|
|
|
|
r.cartLink = c.Link
|
|
|
|
if c.Err != nil {
|
|
m.setNote("adding "+c.Item+" to the cart failed: "+c.Err.Error(), true)
|
|
return
|
|
}
|
|
|
|
m.setNote(c.Item+" is in the cart: press enter on its row and finish checkout", false)
|
|
}
|
|
|
|
// checked records a check. A new alert flashes its row and rings the bell.
|
|
func (m *Model) checked(c CheckMsg) tea.Cmd {
|
|
r := m.results[c.Result.URL]
|
|
if r == nil {
|
|
r = &result{}
|
|
m.results[c.Result.URL] = r
|
|
}
|
|
|
|
r.status = statusOf(c)
|
|
|
|
if rep := c.Result.Report; rep != nil {
|
|
r.price, r.seller = "", ""
|
|
if res := rep.Result; res != nil {
|
|
if res.Price != nil { r.price = alert.Money(*res.Price, res.Currency) }
|
|
r.seller = sellerText(res.Seller)
|
|
}
|
|
|
|
if rep.CartLink != "" { r.cartLink = rep.CartLink }
|
|
}
|
|
|
|
m.rows = m.ctl.Statuses()
|
|
|
|
if c.Decision.Alert == nil { return nil }
|
|
|
|
r.flash = m.now.Add(flashFor)
|
|
return tea.Raw("\a")
|
|
}
|
|
|
|
func statusOf(c CheckMsg) string {
|
|
rep := c.Result.Report
|
|
|
|
switch {
|
|
case rep == nil:
|
|
return statusError
|
|
case rep.Verdict == fetch.NeedsHuman.String():
|
|
return statusNeedsHuman
|
|
case rep.Verdict == fetch.Challenge.String() || rep.Verdict == fetch.Blocked.String():
|
|
return statusBlocked
|
|
case c.Result.Err != nil || rep.Verdict == fetch.HTTPError.String():
|
|
return statusError
|
|
case c.Decision.Qualifies:
|
|
return statusAvailable
|
|
default:
|
|
return statusWatching
|
|
}
|
|
}
|
|
|
|
func sellerText(seller string) string {
|
|
switch seller {
|
|
case plugin.SellerFirstParty:
|
|
return "first party"
|
|
case plugin.SellerFulfilled:
|
|
return "fulfilled"
|
|
case plugin.SellerThirdParty:
|
|
return "third party"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func (m *Model) key(msg tea.KeyPressMsg) tea.Cmd {
|
|
k := msg.String()
|
|
|
|
switch k {
|
|
case "q", "ctrl+c":
|
|
return tea.Quit
|
|
case "l", "tab":
|
|
m.logFocus = !m.logFocus
|
|
return nil
|
|
case "r":
|
|
return m.reload()
|
|
}
|
|
|
|
if m.logFocus {
|
|
if k == "esc" {
|
|
m.logFocus = false
|
|
return nil
|
|
}
|
|
|
|
var cmd tea.Cmd
|
|
m.log, cmd = m.log.Update(msg)
|
|
return cmd
|
|
}
|
|
|
|
switch k {
|
|
case "up", "k":
|
|
m.cursor--
|
|
case "down", "j":
|
|
m.cursor++
|
|
case "home", "g":
|
|
m.cursor = 0
|
|
case "end", "G":
|
|
m.cursor = len(m.rows) - 1
|
|
case "P":
|
|
m.pauseAll()
|
|
default:
|
|
return m.rowKey(k)
|
|
}
|
|
|
|
m.clampCursor()
|
|
return nil
|
|
}
|
|
|
|
// rowKey handles the keys that act on the selected row.
|
|
func (m *Model) rowKey(k string) tea.Cmd {
|
|
if m.cursor >= len(m.rows) { return nil }
|
|
|
|
row := m.rows[m.cursor]
|
|
|
|
switch k {
|
|
case "p":
|
|
m.ctl.Pause(row.Item, !row.Paused)
|
|
if row.Paused { m.setNote("resumed "+row.Item, false) } else { m.setNote("paused "+row.Item, false) }
|
|
m.rows = m.ctl.Statuses()
|
|
case "c":
|
|
m.ctl.CheckNow(row.Item)
|
|
m.setNote("checking "+row.Item+" as soon as the rate limits allow", false)
|
|
m.rows = m.ctl.Statuses()
|
|
case "o":
|
|
return open(row.FetchURL)
|
|
case "enter":
|
|
r := m.results[row.URL]
|
|
if r != nil && r.status == statusNeedsHuman { return m.solve(row) }
|
|
if r != nil && r.cartLink != "" { return open(r.cartLink) }
|
|
|
|
m.setNote("no cart link yet, opening the product page", false)
|
|
return open(row.FetchURL)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// solve opens the row's page in a browser for the user. One bot check is
|
|
// open at a time.
|
|
func (m *Model) solve(row watch.Status) tea.Cmd {
|
|
if m.solving != "" {
|
|
m.setNote("a browser is already open for "+m.solving, true)
|
|
return nil
|
|
}
|
|
|
|
m.solving = row.Host
|
|
m.setNote("pass the bot check in the Chrome window; it closes by itself", false)
|
|
|
|
return func() tea.Msg { return solveMsg{host: row.Host, err: m.ctl.Solve(row.FetchURL)} }
|
|
}
|
|
|
|
// pauseAll pauses every URL, or resumes them all if all are paused.
|
|
func (m *Model) pauseAll() {
|
|
pause := false
|
|
for _, row := range m.rows {
|
|
if !row.Paused { pause = true }
|
|
}
|
|
|
|
m.ctl.PauseAll(pause)
|
|
m.rows = m.ctl.Statuses()
|
|
|
|
if pause { m.setNote("paused everything", false) } else { m.setNote("resumed everything", false) }
|
|
}
|
|
|
|
func (m *Model) reload() tea.Cmd {
|
|
if m.reloading { return nil }
|
|
|
|
m.reloading = true
|
|
m.setNote("reloading "+m.path, false)
|
|
|
|
return func() tea.Msg {
|
|
summary, err := m.ctl.Reload()
|
|
return reloadMsg{summary: summary, err: err}
|
|
}
|
|
}
|
|
|
|
func reloadNote(summary []string) string {
|
|
if len(summary) == 1 { return "reloaded: " + summary[0] }
|
|
|
|
return fmt.Sprintf("reloaded: %d changes (see log)", len(summary))
|
|
}
|
|
|
|
// reloadError shows the first problem in the config. The log has them all.
|
|
func reloadError(err error) string {
|
|
var errs config.Errors
|
|
if errors.As(err, &errs) && len(errs) > 0 {
|
|
msg := "reload failed, config unchanged: line " + errs[0].Brief()
|
|
if len(errs) > 1 { msg += fmt.Sprintf(" (+%d more)", len(errs)-1) }
|
|
|
|
return msg
|
|
}
|
|
|
|
return "reload failed, config unchanged: " + err.Error()
|
|
}
|
|
|
|
func open(url string) tea.Cmd {
|
|
return func() tea.Msg { return openMsg{url: url, err: browser.OpenURL(url)} }
|
|
}
|
|
|
|
func (m *Model) setNote(note string, isError bool) {
|
|
m.note, m.noteError, m.noteTime = note, isError, time.Now()
|
|
}
|
|
|
|
func (m *Model) addLog(l LogLine) {
|
|
follow := m.log.AtBottom()
|
|
|
|
m.logs = append(m.logs, l)
|
|
if len(m.logs) > maxLines { m.logs = m.logs[len(m.logs)-maxLines:] }
|
|
|
|
m.log.SetContentLines(m.logLines())
|
|
if follow { m.log.GotoBottom() }
|
|
}
|
|
|
|
func (m *Model) clampCursor() {
|
|
m.cursor = max(0, min(m.cursor, len(m.rows)-1))
|
|
}
|