Add Lua plugin host, built-in amazon plugin and dibs check.
Sandboxed gopher-lua with time, memory and call-stack limits from [sandbox], a goquery-backed doc API, price parsing, and the 'check', 'plugin test' and 'fixtures' commands. Sellers are first_party, fulfilled (shipped by the shop) or third_party, and items accept fulfilled by default; used-only offers are not available. Plugin tests run on real pages that 'dibs fixtures' fetches into an untracked directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f90ef18f90
commit
bb010356a0
28 files changed
+2096
-26
No files matched your search
@@ -16,7 +16,10 @@ import (
|
||||
const MinInterval = 60 * time.Second
|
||||
|
||||
const (
|
||||
// Seller policies for an item: sold by the shop itself; sold or at least
|
||||
// shipped by it (e.g. Fulfilled by Amazon); or anyone.
|
||||
SellerFirstParty = "first_party"
|
||||
SellerFulfilled = "fulfilled"
|
||||
SellerAny = "any"
|
||||
|
||||
CartModeDeeplink = "deeplink"
|
||||
@@ -35,6 +38,10 @@ const (
|
||||
DefaultSessionTimeout = 5 * time.Minute
|
||||
DefaultMemoryMB = 64
|
||||
DefaultCallStack = 200
|
||||
|
||||
// DefaultSeller also accepts marketplace offers the shop ships (such as
|
||||
// Fulfilled by Amazon), which is how many listings are sold.
|
||||
DefaultSeller = SellerFulfilled
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -119,6 +126,32 @@ func (d Duration) MarshalText() ([]byte, error) {
|
||||
// IsSet reports whether the value came from the config file.
|
||||
func (d Duration) IsSet() bool { return d.set }
|
||||
|
||||
// sellerRanks orders the sellers a plugin reports, from most to least
|
||||
// trusted. The values match plugin.Seller*.
|
||||
var sellerRanks = map[string]int{
|
||||
"first_party": 0,
|
||||
"fulfilled": 1,
|
||||
"third_party": 2,
|
||||
"unknown": 3,
|
||||
}
|
||||
|
||||
// policyRanks is the least trusted seller each policy still accepts.
|
||||
var policyRanks = map[string]int{
|
||||
SellerFirstParty: 0,
|
||||
SellerFulfilled: 1,
|
||||
SellerAny: 3,
|
||||
}
|
||||
|
||||
// AcceptsSeller reports whether an offer from seller, as a plugin reports it,
|
||||
// passes the item's seller policy. The policies are ordered: "fulfilled"
|
||||
// accepts everything "first_party" does, and "any" accepts every seller.
|
||||
func (it Item) AcceptsSeller(seller string) bool {
|
||||
rank, ok := sellerRanks[seller]
|
||||
if !ok { return false }
|
||||
|
||||
return rank <= policyRanks[it.Seller]
|
||||
}
|
||||
|
||||
// Options control validation that depends on the environment.
|
||||
type Options struct {
|
||||
// Builtins are the names of the embedded plugins.
|
||||
|
||||
@@ -21,9 +21,10 @@ seller = "any"
|
||||
interval = "5m"
|
||||
|
||||
[[item]]
|
||||
name = "Console"
|
||||
shop = "mediamarkt"
|
||||
urls = ["https://www.mediamarkt.de/de/product/_console-123.html"]
|
||||
name = "Console"
|
||||
shop = "mediamarkt"
|
||||
seller = "fulfilled"
|
||||
urls = ["https://www.mediamarkt.de/de/product/_console-123.html"]
|
||||
|
||||
[accounts.amazon]
|
||||
username = "me@example.com"
|
||||
@@ -104,6 +105,8 @@ func TestLoadFull(t *testing.T) {
|
||||
if len(cfg.Items) != 2 {
|
||||
t.Fatalf("items: got %d, want 2", len(cfg.Items))
|
||||
}
|
||||
|
||||
if s := cfg.Items[1].Seller; s != SellerFulfilled { t.Errorf("item[1].seller: got %q, want fulfilled", s) }
|
||||
it := cfg.Items[0]
|
||||
if it.Currency != "EUR" {
|
||||
t.Errorf("currency: got %q, want it uppercased to EUR", it.Currency)
|
||||
@@ -145,7 +148,7 @@ urls = ["https://www.amazon.de/dp/B0HMX2FSTF"]
|
||||
t.Fatal(err)
|
||||
}
|
||||
it := cfg.Items[0]
|
||||
if it.Seller != SellerFirstParty || it.Interval.Duration != DefaultInterval || it.MaxPrice != nil {
|
||||
if it.Seller != SellerFulfilled || it.Interval.Duration != DefaultInterval || it.MaxPrice != nil {
|
||||
t.Errorf("item defaults: got %+v", it)
|
||||
}
|
||||
if cfg.Accounts["amazon"].CartMode != CartModeDeeplink {
|
||||
@@ -273,7 +276,7 @@ call_stack = 1
|
||||
wantErr(t, es, "item[0].urls[0]", 4, "http:// or https://")
|
||||
wantErr(t, es, "item[0].max_price", 5, "positive")
|
||||
wantErr(t, es, "item[0].currency", 6, "ISO 4217")
|
||||
wantErr(t, es, "item[0].seller", 7, `"first_party" or "any"`)
|
||||
wantErr(t, es, "item[0].seller", 7, `"first_party", "fulfilled" or "any"`)
|
||||
wantErr(t, es, "item[0].interval", 8, "at least 1m0s")
|
||||
wantErr(t, es, "item[1].urls[0]", 13, "duplicate URL (also item[0].urls[1])")
|
||||
wantErr(t, es, "item[1].fx_margin", 14, "needs both currency and max_price")
|
||||
@@ -334,3 +337,17 @@ func TestErrorFormat(t *testing.T) {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptsSeller(t *testing.T) {
|
||||
for policy, want := range map[string]map[string]bool{
|
||||
SellerFirstParty: {"first_party": true, "fulfilled": false, "third_party": false, "unknown": false},
|
||||
SellerFulfilled: {"first_party": true, "fulfilled": true, "third_party": false, "unknown": false},
|
||||
SellerAny: {"first_party": true, "fulfilled": true, "third_party": true, "unknown": true},
|
||||
} {
|
||||
for seller, ok := range want {
|
||||
if got := (Item{Seller: policy}).AcceptsSeller(seller); got != ok { t.Errorf("policy %s, seller %s: got %v, want %v", policy, seller, got, ok) }
|
||||
}
|
||||
|
||||
if (Item{Seller: policy}).AcceptsSeller("amazon") { t.Errorf("policy %s accepts an invalid seller", policy) }
|
||||
}
|
||||
}
|
||||
@@ -247,10 +247,10 @@ func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string)
|
||||
|
||||
switch it.Seller {
|
||||
case "":
|
||||
it.Seller = SellerFirstParty
|
||||
case SellerFirstParty, SellerAny:
|
||||
it.Seller = DefaultSeller
|
||||
case SellerFirstParty, SellerFulfilled, SellerAny:
|
||||
default:
|
||||
v.errorf(key+".seller", "must be %q or %q (got %q)", SellerFirstParty, SellerAny, it.Seller)
|
||||
v.errorf(key+".seller", "must be %q, %q or %q (got %q)", SellerFirstParty, SellerFulfilled, SellerAny, it.Seller)
|
||||
}
|
||||
|
||||
switch {
|
||||
|
||||
@@ -102,15 +102,25 @@ func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) {
|
||||
if err != nil { return nil, fmt.Errorf("reading body: %w", err) }
|
||||
if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) }
|
||||
|
||||
r := &Response{
|
||||
URL: rawURL,
|
||||
FinalURL: resp.Request.URL.String(),
|
||||
Status: resp.StatusCode,
|
||||
Header: stdhttp.Header(resp.Header),
|
||||
Body: data,
|
||||
Elapsed: time.Since(start),
|
||||
}
|
||||
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
|
||||
r := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data)
|
||||
r.Elapsed = time.Since(start)
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// NewResponse builds and classifies a Response for a page obtained another
|
||||
// way, such as a saved fixture or the browser fallback.
|
||||
func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response {
|
||||
if header == nil { header = stdhttp.Header{} }
|
||||
|
||||
r := &Response{
|
||||
URL: rawURL,
|
||||
FinalURL: finalURL,
|
||||
Status: status,
|
||||
Header: header,
|
||||
Body: body,
|
||||
}
|
||||
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Package fixtures manages the real product pages the plugin tests run on.
|
||||
//
|
||||
// Which pages to use is tracked, in testdata/<shop>/cases.toml. The pages
|
||||
// themselves change over time and may contain personal data, so they are
|
||||
// not tracked: `dibs fixtures` fetches them into testdata/<shop>/pages/,
|
||||
// next to the report dibs produced for each. The tests then check that the
|
||||
// plugin still reads every saved page the same way.
|
||||
package fixtures
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// Case is one page to test with.
|
||||
type Case struct {
|
||||
Name string `toml:"name"`
|
||||
URL string `toml:"url"`
|
||||
// Note says what the page is for, e.g. "only a used offer".
|
||||
Note string `toml:"note"`
|
||||
}
|
||||
|
||||
// Suite is the cases of one shop.
|
||||
type Suite struct {
|
||||
// Shop is the plugin to use, named after the directory.
|
||||
Shop string
|
||||
Dir string
|
||||
Cases []Case
|
||||
}
|
||||
|
||||
var nameRe = regexp.MustCompile(`^[a-z0-9-]+$`)
|
||||
|
||||
// Load reads every dir/<shop>/cases.toml.
|
||||
func Load(dir string) ([]Suite, error) {
|
||||
files, err := filepath.Glob(filepath.Join(dir, "*", "cases.toml"))
|
||||
if err != nil { return nil, err }
|
||||
|
||||
var suites []Suite
|
||||
|
||||
for _, f := range files {
|
||||
data, err := os.ReadFile(f)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
var doc struct {
|
||||
Cases []Case `toml:"case"`
|
||||
}
|
||||
|
||||
dec := toml.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&doc); err != nil { return nil, fmt.Errorf("%s: %w", f, err) }
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, c := range doc.Cases {
|
||||
switch {
|
||||
case !nameRe.MatchString(c.Name):
|
||||
return nil, fmt.Errorf("%s: case name %q must contain only a-z, 0-9 and -", f, c.Name)
|
||||
case seen[c.Name]:
|
||||
return nil, fmt.Errorf("%s: duplicate case %q", f, c.Name)
|
||||
case c.URL == "":
|
||||
return nil, fmt.Errorf("%s: case %q has no url", f, c.Name)
|
||||
}
|
||||
|
||||
seen[c.Name] = true
|
||||
}
|
||||
|
||||
suiteDir := filepath.Dir(f)
|
||||
suites = append(suites, Suite{Shop: filepath.Base(suiteDir), Dir: suiteDir, Cases: doc.Cases})
|
||||
}
|
||||
|
||||
return suites, nil
|
||||
}
|
||||
|
||||
func (s Suite) PagePath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".html") }
|
||||
func (s Suite) ReportPath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".json") }
|
||||
|
||||
// Save writes a fetched page and its report.
|
||||
func (s Suite) Save(c Case, page []byte, report any) error {
|
||||
data, err := EncodeReport(report)
|
||||
if err != nil { return err }
|
||||
|
||||
if err := os.MkdirAll(filepath.Join(s.Dir, "pages"), 0o700); err != nil { return err }
|
||||
if err := os.WriteFile(s.PagePath(c), page, 0o600); err != nil { return err }
|
||||
|
||||
return os.WriteFile(s.ReportPath(c), data, 0o600)
|
||||
}
|
||||
|
||||
// EncodeReport is the one way reports are written, so saved and fresh ones
|
||||
// compare byte for byte.
|
||||
func EncodeReport(report any) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
enc := json.NewEncoder(&b)
|
||||
enc.SetIndent("", " ")
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(report); err != nil { return nil, err }
|
||||
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
-- Built-in plugin for Amazon product pages (de, co.uk, fr, it, es, nl, com).
|
||||
--
|
||||
-- It uses only the public plugin API, so it doubles as the reference for
|
||||
-- writing your own: see "Writing a plugin" in README.md.
|
||||
|
||||
local tlds = {
|
||||
["de"] = "EUR",
|
||||
["fr"] = "EUR",
|
||||
["it"] = "EUR",
|
||||
["es"] = "EUR",
|
||||
["nl"] = "EUR",
|
||||
["co.uk"] = "GBP",
|
||||
["com"] = "USD",
|
||||
}
|
||||
|
||||
-- Amazon's own merchant IDs. A page sold by Amazon carries one of them in
|
||||
-- the buybox form.
|
||||
local amazon_merchants = {
|
||||
A3JWKAKR8XB7XF = true, -- amazon.de
|
||||
A3P5ROKL5A1OLE = true, -- amazon.co.uk
|
||||
A1X6FK5RDHNB96 = true, -- amazon.fr
|
||||
A11IL2PNWYJU7H = true, -- amazon.it
|
||||
A1AT7YVPFBWXBL = true, -- amazon.es
|
||||
A17D2BRD4YMT0X = true, -- amazon.nl
|
||||
ATVPDKIKX0DER = true, -- amazon.com
|
||||
}
|
||||
|
||||
-- Any of these buttons means a new item can go into the cart. The preorder
|
||||
-- selectors are a best guess until we have a real preorder page.
|
||||
-- "#add-to-cart-button-ubb" is deliberately missing: it belongs to the used
|
||||
-- buybox, which Amazon shows when only used copies are left.
|
||||
local buy_buttons = table.concat({
|
||||
"#add-to-cart-button",
|
||||
"#buy-now-button",
|
||||
"input[name='submit.add-to-cart']",
|
||||
"input[name='submit.buy-now']",
|
||||
"input[name='submit.preorder']",
|
||||
"#preorder-button",
|
||||
}, ", ")
|
||||
|
||||
-- Where Amazon says an item can't be bought.
|
||||
local availability_area = { "#availability", "#outOfStock", "#buybox" }
|
||||
|
||||
local unavailable_phrases = {
|
||||
"currently unavailable",
|
||||
"derzeit nicht verfügbar",
|
||||
"actuellement indisponible",
|
||||
"non disponibile",
|
||||
"no disponible",
|
||||
"momenteel niet verkrijgbaar",
|
||||
}
|
||||
|
||||
-- Older layouts say who sells and ships the item in one sentence, such as
|
||||
-- "Versand und Verkauf durch Amazon." or "Verkauf durch X und Versand durch
|
||||
-- Amazon."
|
||||
local sold_by_amazon_phrases = {
|
||||
"sold by amazon",
|
||||
"verkauf durch amazon",
|
||||
"vendu par amazon",
|
||||
"venduto da amazon",
|
||||
"venduto e spedito da amazon",
|
||||
"vendido por amazon",
|
||||
"vendido y enviado por amazon",
|
||||
"verkocht door amazon",
|
||||
}
|
||||
|
||||
local shipped_by_amazon_phrases = {
|
||||
"fulfilled by amazon",
|
||||
"ships from amazon",
|
||||
"dispatched from amazon",
|
||||
"versand durch amazon",
|
||||
"expédié par amazon",
|
||||
"spedito da amazon",
|
||||
"enviado por amazon",
|
||||
"verzonden door amazon",
|
||||
}
|
||||
|
||||
local price_selectors = {
|
||||
"#corePrice_feature_div .a-price .a-offscreen",
|
||||
"#corePriceDisplay_desktop_feature_div .priceToPay .a-offscreen",
|
||||
"#apex_desktop .priceToPay .a-offscreen",
|
||||
".priceToPay .a-offscreen",
|
||||
"#price_inside_buybox",
|
||||
"#priceblock_ourprice",
|
||||
"#priceblock_dealprice",
|
||||
}
|
||||
|
||||
-- split returns the TLD and ASIN of an Amazon product URL, or nil.
|
||||
local function split(url)
|
||||
local host = url:match("^[Hh][Tt][Tt][Pp][Ss]?://([^/?#]+)")
|
||||
if not host then return nil end
|
||||
|
||||
local tld = host:lower():match("^www%.amazon%.(.+)$") or host:lower():match("^amazon%.(.+)$")
|
||||
if not tld or not tlds[tld] then return nil end
|
||||
|
||||
local m = regex_match(url, "(?i)/(?:dp|gp/product|gp/aw/d|exec/obidos/asin)/([a-z0-9]{10})(?:[/?#]|$)")
|
||||
if not m then return nil end
|
||||
|
||||
return tld, m[1]:upper()
|
||||
end
|
||||
|
||||
-- Amazon itself appears as "Amazon", "Amazon.de", "Amazon EU S.à r.l." and
|
||||
-- similar. Shops called "Amazonas Games" must not count.
|
||||
local function is_amazon(name)
|
||||
if not name then return false end
|
||||
|
||||
local n = name:lower():gsub("^%s+", ""):gsub("[%s%.]+$", "")
|
||||
return n == "amazon" or n:match("^amazon%.[%a%.]+$") ~= nil or n:match("^amazon eu") ~= nil or n:match("^amazon media eu") ~= nil
|
||||
end
|
||||
|
||||
local function legacy_merchant_info(doc)
|
||||
return doc:text("#merchant-info") or doc:text("#merchantInfoFeature_feature_div")
|
||||
end
|
||||
|
||||
-- sold_by_amazon is true or false when the page says who sells the item, and
|
||||
-- nil when it doesn't, e.g. when there is no offer at all.
|
||||
local function sold_by_amazon(doc)
|
||||
-- The buybox form names the merchant whose offer the buttons buy.
|
||||
local id = doc:attr("input#merchantID, input[name='merchantID']", "value")
|
||||
if id and id ~= "" then return amazon_merchants[id] == true end
|
||||
|
||||
-- Newer layout: a "Verkäufer" / "Sold by" row.
|
||||
local name = doc:text("#merchantInfoFeature_feature_div .offer-display-feature-text-message")
|
||||
if name then return is_amazon(name) end
|
||||
|
||||
local info = legacy_merchant_info(doc)
|
||||
if info then return contains_any(info, sold_by_amazon_phrases) end
|
||||
|
||||
if doc:exists("#sellerProfileTriggerId") then return false end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
local function shipped_by_amazon(doc)
|
||||
-- Newer layout: a "Versand" / "Ships from" row.
|
||||
local name = doc:text("#fulfillerInfoFeature_feature_div .offer-display-feature-text-message")
|
||||
if name then return is_amazon(name) end
|
||||
|
||||
return contains_any(legacy_merchant_info(doc), shipped_by_amazon_phrases)
|
||||
end
|
||||
|
||||
local function seller(doc)
|
||||
local sold = sold_by_amazon(doc)
|
||||
|
||||
if sold == nil then return "unknown" end
|
||||
if sold then return "first_party" end
|
||||
if shipped_by_amazon(doc) then return "fulfilled" end
|
||||
|
||||
return "third_party"
|
||||
end
|
||||
|
||||
local function unavailable(doc)
|
||||
for _, sel in ipairs(availability_area) do
|
||||
if contains_any(doc:text(sel), unavailable_phrases) then return true end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
local function find_price(doc)
|
||||
for _, sel in ipairs(price_selectors) do
|
||||
local value, currency = parse_price(doc:text(sel))
|
||||
if value then return value, currency end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
return {
|
||||
name = "amazon",
|
||||
|
||||
matches = function(url)
|
||||
return split(url) ~= nil
|
||||
end,
|
||||
|
||||
-- Every variant of a product URL becomes https://www.amazon.<tld>/dp/<ASIN>,
|
||||
-- so the same item is never watched twice.
|
||||
normalize = function(url)
|
||||
local tld, asin = split(url)
|
||||
if not tld then return url end
|
||||
|
||||
return "https://www.amazon." .. tld .. "/dp/" .. asin
|
||||
end,
|
||||
|
||||
parse = function(doc, url)
|
||||
local tld, asin = split(url)
|
||||
local title = doc:text("#productTitle")
|
||||
local value, currency = find_price(doc)
|
||||
|
||||
return {
|
||||
title = title,
|
||||
-- A dog page or a search result has no product title, so it is
|
||||
-- never available.
|
||||
available = title ~= nil and doc:exists(buy_buttons) and not unavailable(doc),
|
||||
price = value,
|
||||
currency = currency or (tld and tlds[tld]),
|
||||
seller = seller(doc),
|
||||
id = asin,
|
||||
}
|
||||
end,
|
||||
|
||||
cart_link = function(url, id)
|
||||
local tld, asin = split(url)
|
||||
if not tld then return nil end
|
||||
|
||||
return "https://www.amazon." .. tld .. "/gp/aws/cart/add.html?ASIN.1=" .. (id or asin) .. "&Quantity.1=1"
|
||||
end,
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/andybalholm/cascadia"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const nodeType = "dibs.node"
|
||||
|
||||
// The methods of doc and of the nodes doc:all() returns. Each takes an
|
||||
// optional CSS selector: without one it works on the node itself, with one
|
||||
// on the first match inside it.
|
||||
var nodeMethods = map[string]lua.LGFunction{
|
||||
"text": nodeText,
|
||||
"attr": nodeAttr,
|
||||
"exists": nodeExists,
|
||||
"count": nodeCount,
|
||||
"html": nodeHTML,
|
||||
"all": nodeAll,
|
||||
}
|
||||
|
||||
func registerNode(L *lua.LState) {
|
||||
mt := L.NewTypeMetatable(nodeType)
|
||||
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), nodeMethods))
|
||||
}
|
||||
|
||||
func pushNode(L *lua.LState, sel *goquery.Selection) lua.LValue {
|
||||
ud := L.NewUserData()
|
||||
ud.Value = sel
|
||||
L.SetMetatable(ud, L.GetTypeMetatable(nodeType))
|
||||
|
||||
return ud
|
||||
}
|
||||
|
||||
func checkNode(L *lua.LState) *goquery.Selection {
|
||||
if ud, ok := L.Get(1).(*lua.LUserData); ok {
|
||||
if sel, ok := ud.Value.(*goquery.Selection); ok { return sel }
|
||||
}
|
||||
|
||||
L.ArgError(1, "node expected (call methods with a colon, as in doc:text(...))")
|
||||
return nil
|
||||
}
|
||||
|
||||
// target is the node itself, or what the selector in argument arg matches
|
||||
// inside it.
|
||||
func target(L *lua.LState, node *goquery.Selection, arg int) *goquery.Selection {
|
||||
if L.GetTop() < arg || L.Get(arg) == lua.LNil { return node }
|
||||
|
||||
return node.FindMatcher(selector(L, arg))
|
||||
}
|
||||
|
||||
var selectors sync.Map // string -> cascadia.Selector
|
||||
|
||||
func selector(L *lua.LState, arg int) cascadia.Selector {
|
||||
src := L.CheckString(arg)
|
||||
if s, ok := selectors.Load(src); ok { return s.(cascadia.Selector) }
|
||||
|
||||
s, err := cascadia.Compile(src)
|
||||
if err != nil {
|
||||
L.ArgError(arg, "invalid selector "+src+": "+err.Error())
|
||||
return nil
|
||||
}
|
||||
|
||||
selectors.Store(src, s)
|
||||
return s
|
||||
}
|
||||
|
||||
// node:text([sel]) is the visible text of the node or its first match, with
|
||||
// whitespace collapsed. It is nil if nothing matches or the text is empty,
|
||||
// so `if doc:text(sel) then` means "has text". Use exists to test presence.
|
||||
func nodeText(L *lua.LState) int {
|
||||
s := target(L, checkNode(L), 2).First()
|
||||
|
||||
text := ""
|
||||
if s.Length() > 0 { text = visibleText(s) }
|
||||
|
||||
if text == "" { L.Push(lua.LNil) } else { L.Push(lua.LString(text)) }
|
||||
return 1
|
||||
}
|
||||
|
||||
// node:attr(name) or node:attr(sel, name) is an attribute value, or nil.
|
||||
func nodeAttr(L *lua.LState) int {
|
||||
node := checkNode(L)
|
||||
|
||||
s, name := node, L.CheckString(2)
|
||||
if L.GetTop() >= 3 { s, name = target(L, node, 2), L.CheckString(3) }
|
||||
|
||||
if v, ok := s.First().Attr(name); ok { L.Push(lua.LString(v)) } else { L.Push(lua.LNil) }
|
||||
return 1
|
||||
}
|
||||
|
||||
// node:exists(sel) reports whether sel matches anything.
|
||||
func nodeExists(L *lua.LState) int {
|
||||
L.Push(lua.LBool(checkNode(L).FindMatcher(selector(L, 2)).Length() > 0))
|
||||
return 1
|
||||
}
|
||||
|
||||
// node:count(sel) is the number of matches.
|
||||
func nodeCount(L *lua.LState) int {
|
||||
L.Push(lua.LNumber(checkNode(L).FindMatcher(selector(L, 2)).Length()))
|
||||
return 1
|
||||
}
|
||||
|
||||
// node:html([sel]) is the outer HTML of the node or its first match, or nil.
|
||||
func nodeHTML(L *lua.LState) int {
|
||||
s := target(L, checkNode(L), 2).First()
|
||||
if s.Length() == 0 {
|
||||
L.Push(lua.LNil)
|
||||
return 1
|
||||
}
|
||||
|
||||
out, err := goquery.OuterHtml(s)
|
||||
if err != nil { L.RaiseError("html: %v", err) }
|
||||
|
||||
L.Push(lua.LString(out))
|
||||
return 1
|
||||
}
|
||||
|
||||
// node:all(sel) is a list of nodes, one per match.
|
||||
func nodeAll(L *lua.LState) int {
|
||||
t := L.NewTable()
|
||||
checkNode(L).FindMatcher(selector(L, 2)).Each(func(_ int, s *goquery.Selection) { t.Append(pushNode(L, s)) })
|
||||
|
||||
L.Push(t)
|
||||
return 1
|
||||
}
|
||||
|
||||
// hiddenElements never contribute visible text. Amazon puts large inline
|
||||
// scripts inside its availability block, for example.
|
||||
var hiddenElements = map[string]bool{"script": true, "style": true, "noscript": true, "template": true}
|
||||
|
||||
// inlineElements run into the text around them. Other elements are
|
||||
// separated by a space, so "<li>a</li><li>b</li>" reads "a b".
|
||||
var inlineElements = map[string]bool{
|
||||
"a": true, "abbr": true, "b": true, "bdi": true, "bdo": true, "cite": true, "code": true, "data": true,
|
||||
"em": true, "i": true, "kbd": true, "mark": true, "q": true, "s": true, "small": true, "span": true,
|
||||
"strong": true, "sub": true, "sup": true, "time": true, "u": true, "var": true,
|
||||
}
|
||||
|
||||
func visibleText(s *goquery.Selection) string {
|
||||
var b strings.Builder
|
||||
for _, n := range s.Nodes { writeText(&b, n) }
|
||||
|
||||
return strings.Join(strings.Fields(b.String()), " ")
|
||||
}
|
||||
|
||||
func writeText(b *strings.Builder, n *html.Node) {
|
||||
switch n.Type {
|
||||
case html.TextNode:
|
||||
b.WriteString(n.Data)
|
||||
case html.ElementNode:
|
||||
if hiddenElements[n.Data] { return }
|
||||
|
||||
block := !inlineElements[n.Data]
|
||||
if block { b.WriteByte(' ') }
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) }
|
||||
if block { b.WriteByte(' ') }
|
||||
case html.DocumentNode:
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) }
|
||||
default:
|
||||
// Comments and doctypes have no visible text.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/price"
|
||||
)
|
||||
|
||||
func registerHelpers(L *lua.LState, logger *slog.Logger) {
|
||||
logFn := L.NewFunction(func(L *lua.LState) int {
|
||||
parts := make([]string, L.GetTop())
|
||||
for i := range parts { parts[i] = L.ToStringMeta(L.Get(i + 1)).String() }
|
||||
|
||||
logger.Info(strings.Join(parts, " "))
|
||||
return 0
|
||||
})
|
||||
|
||||
L.SetGlobal("log", logFn)
|
||||
L.SetGlobal("print", logFn)
|
||||
L.SetGlobal("contains_any", L.NewFunction(containsAny))
|
||||
L.SetGlobal("parse_price", L.NewFunction(parsePrice))
|
||||
L.SetGlobal("regex_match", L.NewFunction(regexMatch))
|
||||
}
|
||||
|
||||
// contains_any(str, {phrases}) reports whether str contains any of the
|
||||
// phrases, ignoring case. A nil str contains nothing.
|
||||
func containsAny(L *lua.LState) int {
|
||||
phrases := L.CheckTable(2)
|
||||
if L.Get(1) == lua.LNil {
|
||||
L.Push(lua.LFalse)
|
||||
return 1
|
||||
}
|
||||
|
||||
s := strings.ToLower(L.CheckString(1))
|
||||
found := false
|
||||
|
||||
phrases.ForEach(func(_, v lua.LValue) {
|
||||
if p, ok := v.(lua.LString); ok && !found && strings.Contains(s, strings.ToLower(string(p))) { found = true }
|
||||
})
|
||||
|
||||
L.Push(lua.LBool(found))
|
||||
return 1
|
||||
}
|
||||
|
||||
// parse_price(str) returns the price in str and its currency code (or nil),
|
||||
// or nil if str holds no price.
|
||||
func parsePrice(L *lua.LState) int {
|
||||
if L.Get(1) == lua.LNil {
|
||||
L.Push(lua.LNil)
|
||||
return 1
|
||||
}
|
||||
|
||||
v, cur, ok := price.Parse(L.CheckString(1))
|
||||
if !ok {
|
||||
L.Push(lua.LNil)
|
||||
return 1
|
||||
}
|
||||
|
||||
L.Push(lua.LNumber(v))
|
||||
if cur != "" { L.Push(lua.LString(cur)) } else { L.Push(lua.LNil) }
|
||||
return 2
|
||||
}
|
||||
|
||||
var regexps sync.Map // string -> *regexp.Regexp
|
||||
|
||||
// regex_match(str, pattern) matches a Go (RE2) regular expression. It
|
||||
// returns a list of the capture groups, or of the whole match if the
|
||||
// pattern has no groups, or nil if it does not match.
|
||||
func regexMatch(L *lua.LState) int {
|
||||
pattern := L.CheckString(2)
|
||||
if L.Get(1) == lua.LNil {
|
||||
L.Push(lua.LNil)
|
||||
return 1
|
||||
}
|
||||
|
||||
s := L.CheckString(1)
|
||||
|
||||
var re *regexp.Regexp
|
||||
if cached, ok := regexps.Load(pattern); ok {
|
||||
re = cached.(*regexp.Regexp)
|
||||
} else {
|
||||
compiled, err := regexp.Compile(pattern)
|
||||
if err != nil { L.ArgError(2, "invalid pattern: "+err.Error()) }
|
||||
|
||||
re = compiled
|
||||
regexps.Store(pattern, re)
|
||||
}
|
||||
|
||||
m := re.FindStringSubmatch(s)
|
||||
if m == nil {
|
||||
L.Push(lua.LNil)
|
||||
return 1
|
||||
}
|
||||
|
||||
if len(m) > 1 { m = m[1:] }
|
||||
|
||||
t := L.NewTable()
|
||||
for _, g := range m { t.Append(lua.LString(g)) }
|
||||
|
||||
L.Push(t)
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
)
|
||||
|
||||
//go:embed builtin/*.lua
|
||||
var builtinFS embed.FS
|
||||
|
||||
// ErrNoPlugin is returned when no plugin matches a URL.
|
||||
var ErrNoPlugin = errors.New("no plugin matches the URL")
|
||||
|
||||
// Builtins returns the names of the embedded plugins.
|
||||
func Builtins() []string {
|
||||
files, _ := fs.Glob(builtinFS, "builtin/*.lua")
|
||||
|
||||
names := make([]string, len(files))
|
||||
for i, f := range files { names[i] = strings.TrimSuffix(strings.TrimPrefix(f, "builtin/"), ".lua") }
|
||||
|
||||
return names
|
||||
}
|
||||
|
||||
// BuiltinSource returns the code of an embedded plugin.
|
||||
func BuiltinSource(name string) ([]byte, error) {
|
||||
return builtinFS.ReadFile("builtin/" + name + ".lua")
|
||||
}
|
||||
|
||||
// Host holds the loaded plugins.
|
||||
type Host struct {
|
||||
plugins map[string]*Plugin
|
||||
// order is the order ForURL tries plugins in: user plugins first, so
|
||||
// they win over built-ins they don't replace.
|
||||
order []string
|
||||
}
|
||||
|
||||
// NewHost loads the built-in plugins and the user's (name -> file). A user
|
||||
// plugin replaces a built-in one of the same name.
|
||||
func NewHost(user map[string]string, limits Limits, logger *slog.Logger) (*Host, error) {
|
||||
h := &Host{plugins: map[string]*Plugin{}}
|
||||
|
||||
var errs []error
|
||||
|
||||
for _, name := range slices.Sorted(maps.Keys(user)) {
|
||||
code, err := os.ReadFile(user[name])
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("plugin %s: %w", name, err))
|
||||
continue
|
||||
}
|
||||
|
||||
p, err := Load(name, user[name], code, limits, logger)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
|
||||
h.plugins[name] = p
|
||||
h.order = append(h.order, name)
|
||||
}
|
||||
|
||||
for _, name := range Builtins() {
|
||||
if _, replaced := user[name]; replaced { continue }
|
||||
|
||||
code, err := BuiltinSource(name)
|
||||
if err == nil {
|
||||
var p *Plugin
|
||||
if p, err = Load(name, "built-in", code, limits, logger); err == nil {
|
||||
h.plugins[name] = p
|
||||
h.order = append(h.order, name)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
if len(errs) > 0 {
|
||||
h.Close()
|
||||
return nil, errors.Join(errs...)
|
||||
}
|
||||
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// Plugin returns the plugin called name.
|
||||
func (h *Host) Plugin(name string) (*Plugin, bool) {
|
||||
p, ok := h.plugins[name]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// ForURL returns the first plugin whose matches(url) is true.
|
||||
func (h *Host) ForURL(ctx context.Context, url string) (*Plugin, error) {
|
||||
for _, name := range h.order {
|
||||
p := h.plugins[name]
|
||||
|
||||
ok, err := p.Matches(ctx, url)
|
||||
if err != nil { return nil, err }
|
||||
if ok { return p, nil }
|
||||
}
|
||||
|
||||
return nil, ErrNoPlugin
|
||||
}
|
||||
|
||||
func (h *Host) Close() {
|
||||
for _, p := range h.plugins { p.Close() }
|
||||
}
|
||||
|
||||
// Report is the outcome of checking one URL, as `dibs check` prints it.
|
||||
type Report struct {
|
||||
URL string `json:"url"`
|
||||
FetchURL string `json:"fetch_url"`
|
||||
FinalURL string `json:"final_url"`
|
||||
Shop string `json:"shop"`
|
||||
Status int `json:"status"`
|
||||
Verdict string `json:"verdict"`
|
||||
Challenge string `json:"challenge,omitempty"`
|
||||
Result *Result `json:"result,omitempty"`
|
||||
CartLink string `json:"cart_link,omitempty"`
|
||||
ElapsedMS int64 `json:"elapsed_ms"`
|
||||
}
|
||||
|
||||
// Evaluate turns a fetched page into a Report. Only pages with the OK
|
||||
// verdict are parsed. A NotFound page is reported as unavailable without
|
||||
// asking the plugin, and bot checks and errors have no result.
|
||||
func Evaluate(ctx context.Context, p *Plugin, rawURL string, resp *fetch.Response) (*Report, error) {
|
||||
r := &Report{
|
||||
URL: rawURL,
|
||||
FetchURL: resp.URL,
|
||||
FinalURL: resp.FinalURL,
|
||||
Shop: p.Name,
|
||||
Status: resp.Status,
|
||||
Verdict: resp.Verdict.String(),
|
||||
Challenge: resp.Challenge,
|
||||
ElapsedMS: resp.Elapsed.Milliseconds(),
|
||||
}
|
||||
|
||||
switch resp.Verdict {
|
||||
case fetch.OK:
|
||||
res, err := p.Parse(ctx, resp.Body, resp.URL)
|
||||
if err != nil { return r, err }
|
||||
|
||||
r.Result = res
|
||||
|
||||
link, err := p.CartLink(ctx, resp.URL, res.ID)
|
||||
if err != nil { return r, err }
|
||||
|
||||
r.CartLink = link
|
||||
case fetch.NotFound:
|
||||
r.Result = &Result{Seller: SellerUnknown}
|
||||
default:
|
||||
// Challenge, Blocked or HTTPError: nothing to read.
|
||||
}
|
||||
|
||||
return r, nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/fixtures"
|
||||
)
|
||||
|
||||
// testdata is the repository's top-level testdata directory.
|
||||
var testdata = filepath.Join("..", "..", "testdata")
|
||||
|
||||
func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
|
||||
|
||||
func builtin(t *testing.T, name string) *Plugin {
|
||||
t.Helper()
|
||||
|
||||
code, err := BuiltinSource(name)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
p, err := Load(name, "built-in", code, DefaultLimits(), discardLogger())
|
||||
if err != nil { t.Fatal(err) }
|
||||
t.Cleanup(p.Close)
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// TestSavedPages re-reads every page `dibs fixtures` saved and checks the
|
||||
// plugin still reports what it reported when the page was fetched.
|
||||
func TestSavedPages(t *testing.T) {
|
||||
suites, err := fixtures.Load(testdata)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
ran := 0
|
||||
|
||||
for _, suite := range suites {
|
||||
if !slices.Contains(Builtins(), suite.Shop) { continue }
|
||||
|
||||
p := builtin(t, suite.Shop)
|
||||
|
||||
for _, c := range suite.Cases {
|
||||
page, err := os.ReadFile(suite.PagePath(c))
|
||||
if errors.Is(err, fs.ErrNotExist) { continue }
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
ran++
|
||||
|
||||
t.Run(suite.Shop+"/"+c.Name, func(t *testing.T) {
|
||||
want, err := os.ReadFile(suite.ReportPath(c))
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
var saved Report
|
||||
if err := json.Unmarshal(want, &saved); err != nil { t.Fatal(err) }
|
||||
|
||||
report, err := Evaluate(context.Background(), p, saved.URL, fetch.NewResponse(saved.FetchURL, saved.FinalURL, saved.Status, nil, page))
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
got, err := fixtures.EncodeReport(report)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
if !bytes.Equal(got, want) { t.Errorf("%s (%s) now reads differently.\ngot:\n%s\nsaved:\n%s", c.Name, c.Note, got, want) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if ran == 0 { t.Skip("no saved pages: run `dibs fixtures` to fetch them") }
|
||||
}
|
||||
|
||||
func TestAmazonNormalize(t *testing.T) {
|
||||
data, err := os.ReadFile(filepath.Join(testdata, "amazon", "urls.toml"))
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
var urls struct {
|
||||
Normalize []struct {
|
||||
In string `toml:"in"`
|
||||
Out string `toml:"out"`
|
||||
} `toml:"normalize"`
|
||||
}
|
||||
if err := toml.Unmarshal(data, &urls); err != nil { t.Fatal(err) }
|
||||
|
||||
p := builtin(t, "amazon")
|
||||
|
||||
for _, u := range urls.Normalize {
|
||||
got, err := p.Normalize(context.Background(), u.In)
|
||||
if err != nil { t.Fatal(err) }
|
||||
if got != u.Out { t.Errorf("normalize(%q) = %q, want %q", u.In, got, u.Out) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// Package plugin runs shop plugins: sandboxed Lua files that read product
|
||||
// pages.
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
// Who sells the item, as parse reports it.
|
||||
const (
|
||||
// SellerFirstParty: the shop itself sells it.
|
||||
SellerFirstParty = "first_party"
|
||||
// SellerFulfilled: a marketplace seller sells it, but the shop ships it
|
||||
// (e.g. Fulfilled by Amazon).
|
||||
SellerFulfilled = "fulfilled"
|
||||
// SellerThirdParty: a marketplace seller sells and ships it.
|
||||
SellerThirdParty = "third_party"
|
||||
SellerUnknown = "unknown"
|
||||
)
|
||||
|
||||
// Result is what a plugin's parse function read from a page.
|
||||
type Result struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Available bool `json:"available"`
|
||||
Price *float64 `json:"price"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
Seller string `json:"seller"`
|
||||
// ID is the shop's product ID, such as an ASIN. It is passed to
|
||||
// cart_link.
|
||||
ID string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
// hooks are the functions a plugin table may define. Only parse is required.
|
||||
var hooks = []string{"matches", "normalize", "parse", "cart_link", "login", "add_to_cart"}
|
||||
|
||||
var currencyRe = regexp.MustCompile(`^[A-Z]{3}$`)
|
||||
|
||||
// Plugin is a loaded plugin. It is safe for concurrent use; calls into one
|
||||
// plugin run one at a time.
|
||||
type Plugin struct {
|
||||
Name string
|
||||
// Source is the plugin's file, or "built-in".
|
||||
Source string
|
||||
|
||||
chunk string
|
||||
code []byte
|
||||
limits Limits
|
||||
logger *slog.Logger
|
||||
nameFixed bool // the name came from the config, not the table
|
||||
|
||||
mu sync.Mutex
|
||||
state *lua.LState
|
||||
funcs map[string]*lua.LFunction
|
||||
}
|
||||
|
||||
// Load runs a plugin's code and checks the table it returns. An empty name
|
||||
// takes the name from the table, or else from the file name.
|
||||
func Load(name, source string, code []byte, limits Limits, logger *slog.Logger) (*Plugin, error) {
|
||||
chunk := filepath.Base(source)
|
||||
if source == "built-in" { chunk = name + ".lua" }
|
||||
|
||||
p := &Plugin{
|
||||
Name: name,
|
||||
Source: source,
|
||||
chunk: chunk,
|
||||
code: code,
|
||||
limits: limits,
|
||||
logger: logger,
|
||||
nameFixed: name != "",
|
||||
}
|
||||
if !p.nameFixed { p.Name = strings.TrimSuffix(chunk, ".lua") }
|
||||
|
||||
shortCalls.Lock()
|
||||
defer shortCalls.Unlock()
|
||||
|
||||
if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s (%s): %w", name, source, err) }
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// reset loads the plugin into a fresh Lua state. Callers hold shortCalls.
|
||||
func (p *Plugin) reset() error {
|
||||
if p.state != nil {
|
||||
p.state.Close()
|
||||
p.state = nil
|
||||
}
|
||||
|
||||
L := newState(p.limits)
|
||||
registerNode(L)
|
||||
registerHelpers(L, p.logger.With("plugin", p.Name))
|
||||
|
||||
fn, err := L.Load(bytes.NewReader(p.code), p.chunk)
|
||||
if err != nil {
|
||||
L.Close()
|
||||
return luaError(err)
|
||||
}
|
||||
|
||||
var tbl *lua.LTable
|
||||
|
||||
err = run(L, context.Background(), p.limits.Timeout, p.limits.MemoryBytes, func() error {
|
||||
if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}); err != nil { return err }
|
||||
|
||||
ret := L.Get(-1)
|
||||
L.Pop(1)
|
||||
|
||||
t, ok := ret.(*lua.LTable)
|
||||
if !ok { return fmt.Errorf("must return a table, got %s", ret.Type()) }
|
||||
|
||||
tbl = t
|
||||
return nil
|
||||
})
|
||||
if err == nil { err = p.readTable(tbl) }
|
||||
if err != nil {
|
||||
L.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
p.state = L
|
||||
return nil
|
||||
}
|
||||
|
||||
// readTable checks the plugin table and picks up its functions.
|
||||
func (p *Plugin) readTable(tbl *lua.LTable) error {
|
||||
var problems []string
|
||||
|
||||
funcs := map[string]*lua.LFunction{}
|
||||
|
||||
tbl.ForEach(func(k, v lua.LValue) {
|
||||
key := k.String()
|
||||
|
||||
switch {
|
||||
case key == "name":
|
||||
s, ok := v.(lua.LString)
|
||||
switch {
|
||||
case !ok || s == "":
|
||||
problems = append(problems, fmt.Sprintf("name must be a non-empty string, got %s", v.Type()))
|
||||
case !p.nameFixed:
|
||||
p.Name = string(s)
|
||||
case string(s) != p.Name:
|
||||
problems = append(problems, fmt.Sprintf("name is %q, but the plugin is configured as %q", s, p.Name))
|
||||
}
|
||||
case slices.Contains(hooks, key):
|
||||
if fn, ok := v.(*lua.LFunction); ok { funcs[key] = fn } else { problems = append(problems, fmt.Sprintf("%s must be a function, got %s", key, v.Type())) }
|
||||
default:
|
||||
problems = append(problems, fmt.Sprintf("unknown key %q (known: name, %s)", key, strings.Join(hooks, ", ")))
|
||||
}
|
||||
})
|
||||
|
||||
if funcs["parse"] == nil && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "parse ") }) {
|
||||
problems = append(problems, "parse function is missing")
|
||||
}
|
||||
|
||||
if len(problems) > 0 {
|
||||
slices.Sort(problems)
|
||||
return errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
|
||||
p.funcs = funcs
|
||||
return nil
|
||||
}
|
||||
|
||||
// Has reports whether the plugin defines hook.
|
||||
func (p *Plugin) Has(hook string) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
return p.funcs[hook] != nil
|
||||
}
|
||||
|
||||
// call runs a short hook, one of matches, normalize, parse and cart_link.
|
||||
// args builds the arguments in the plugin's Lua state.
|
||||
func (p *Plugin) call(ctx context.Context, hook string, nret int, args func(L *lua.LState) []lua.LValue) ([]lua.LValue, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
shortCalls.Lock()
|
||||
defer shortCalls.Unlock()
|
||||
|
||||
// An earlier call was killed and reloading failed.
|
||||
if p.state == nil {
|
||||
if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s: %w", p.Name, err) }
|
||||
}
|
||||
|
||||
L := p.state
|
||||
|
||||
var out []lua.LValue
|
||||
|
||||
err := run(L, ctx, p.limits.Timeout, p.limits.MemoryBytes, func() error {
|
||||
if err := L.CallByParam(lua.P{Fn: p.funcs[hook], NRet: nret, Protect: true}, args(L)...); err != nil { return err }
|
||||
|
||||
for i := nret; i > 0; i-- { out = append(out, L.Get(-i)) }
|
||||
L.Pop(nret)
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
// A killed call can stop anywhere, so start over with a clean state.
|
||||
if errors.Is(err, ErrTimeout) || errors.Is(err, ErrMemoryLimit) {
|
||||
if rerr := p.reset(); rerr != nil { p.logger.Error("reloading plugin failed", "plugin", p.Name, "err", rerr) }
|
||||
}
|
||||
|
||||
if err != nil { return nil, fmt.Errorf("plugin %s: %s: %w", p.Name, hook, err) }
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Matches runs matches(url). A plugin without it matches nothing.
|
||||
func (p *Plugin) Matches(ctx context.Context, url string) (bool, error) {
|
||||
if !p.Has("matches") { return false, nil }
|
||||
|
||||
out, err := p.call(ctx, "matches", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} })
|
||||
if err != nil { return false, err }
|
||||
|
||||
return lua.LVAsBool(out[0]), nil
|
||||
}
|
||||
|
||||
// Normalize runs normalize(url). Without it, or if it returns nil, the URL
|
||||
// stays as it is.
|
||||
func (p *Plugin) Normalize(ctx context.Context, url string) (string, error) {
|
||||
if !p.Has("normalize") { return url, nil }
|
||||
|
||||
out, err := p.call(ctx, "normalize", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} })
|
||||
if err != nil { return "", err }
|
||||
|
||||
switch v := out[0].(type) {
|
||||
case lua.LString:
|
||||
return string(v), nil
|
||||
case *lua.LNilType:
|
||||
return url, nil
|
||||
default:
|
||||
return "", fmt.Errorf("plugin %s: normalize must return a string, got %s", p.Name, v.Type())
|
||||
}
|
||||
}
|
||||
|
||||
// Parse runs parse(doc, url) on a page.
|
||||
func (p *Plugin) Parse(ctx context.Context, page []byte, url string) (*Result, error) {
|
||||
// Parse the HTML before the call, so it does not count against the
|
||||
// call's time and memory.
|
||||
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page))
|
||||
if err != nil { return nil, fmt.Errorf("parsing HTML: %w", err) }
|
||||
|
||||
out, err := p.call(ctx, "parse", 1, func(L *lua.LState) []lua.LValue { return []lua.LValue{pushNode(L, doc.Selection), lua.LString(url)} })
|
||||
if err != nil { return nil, err }
|
||||
|
||||
r, err := toResult(out[0])
|
||||
if err != nil { return nil, fmt.Errorf("plugin %s: parse: %w", p.Name, err) }
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// CartLink runs cart_link(url, id). It returns "" if the plugin has no
|
||||
// cart_link or it returns nil.
|
||||
func (p *Plugin) CartLink(ctx context.Context, url, id string) (string, error) {
|
||||
if !p.Has("cart_link") { return "", nil }
|
||||
|
||||
out, err := p.call(ctx, "cart_link", 1, func(*lua.LState) []lua.LValue {
|
||||
idArg := lua.LValue(lua.LNil)
|
||||
if id != "" { idArg = lua.LString(id) }
|
||||
|
||||
return []lua.LValue{lua.LString(url), idArg}
|
||||
})
|
||||
if err != nil { return "", err }
|
||||
|
||||
switch v := out[0].(type) {
|
||||
case lua.LString:
|
||||
return string(v), nil
|
||||
case *lua.LNilType:
|
||||
return "", nil
|
||||
default:
|
||||
return "", fmt.Errorf("plugin %s: cart_link must return a string, got %s", p.Name, v.Type())
|
||||
}
|
||||
}
|
||||
|
||||
// Close frees the Lua state.
|
||||
func (p *Plugin) Close() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.state != nil {
|
||||
p.state.Close()
|
||||
p.state = nil
|
||||
}
|
||||
}
|
||||
|
||||
// toResult checks parse's return value field by field.
|
||||
func toResult(v lua.LValue) (*Result, error) {
|
||||
t, ok := v.(*lua.LTable)
|
||||
if !ok { return nil, fmt.Errorf("must return a table, got %s", v.Type()) }
|
||||
|
||||
r := &Result{Seller: SellerUnknown}
|
||||
|
||||
var problems []string
|
||||
|
||||
bad := func(format string, args ...any) { problems = append(problems, fmt.Sprintf(format, args...)) }
|
||||
|
||||
hasAvailable := false
|
||||
|
||||
t.ForEach(func(k, val lua.LValue) {
|
||||
key := k.String()
|
||||
|
||||
switch key {
|
||||
case "title":
|
||||
if s, ok := val.(lua.LString); ok { r.Title = strings.TrimSpace(string(s)) } else { bad("title must be a string or nil, got %s", val.Type()) }
|
||||
case "available":
|
||||
b, ok := val.(lua.LBool)
|
||||
if !ok {
|
||||
bad("available must be true or false, got %s", val.Type())
|
||||
return
|
||||
}
|
||||
|
||||
r.Available, hasAvailable = bool(b), true
|
||||
case "price":
|
||||
n, ok := val.(lua.LNumber)
|
||||
switch f := float64(n); {
|
||||
case !ok:
|
||||
bad("price must be a number or nil, got %s", val.Type())
|
||||
case f < 0 || math.IsInf(f, 0) || math.IsNaN(f):
|
||||
bad("price must be a positive number, got %v", f)
|
||||
default:
|
||||
r.Price = &f
|
||||
}
|
||||
case "currency":
|
||||
s, ok := val.(lua.LString)
|
||||
if c := strings.ToUpper(string(s)); ok && currencyRe.MatchString(c) { r.Currency = c } else { bad("currency must be a 3-letter code such as EUR or nil, got %s", val) }
|
||||
case "seller":
|
||||
s, ok := val.(lua.LString)
|
||||
switch string(s) {
|
||||
case SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown:
|
||||
if ok { r.Seller = string(s) }
|
||||
default:
|
||||
bad("seller must be %q, %q, %q or %q, got %s", SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown, val)
|
||||
}
|
||||
case "id":
|
||||
if s, ok := val.(lua.LString); ok { r.ID = string(s) } else { bad("id must be a string or nil, got %s", val.Type()) }
|
||||
default:
|
||||
bad("unknown field %q", key)
|
||||
}
|
||||
})
|
||||
|
||||
if !hasAvailable && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "available ") }) {
|
||||
bad("available is missing")
|
||||
}
|
||||
|
||||
if len(problems) > 0 {
|
||||
slices.Sort(problems)
|
||||
return nil, errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
|
||||
return r, nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime/metrics"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
)
|
||||
|
||||
// Limits cap every Lua call. They come from [sandbox] in dibs.toml.
|
||||
type Limits struct {
|
||||
// Timeout applies to loading a plugin and to matches, normalize, parse
|
||||
// and cart_link.
|
||||
Timeout time.Duration
|
||||
// SessionTimeout applies to login and add_to_cart.
|
||||
SessionTimeout time.Duration
|
||||
// MemoryBytes is the heap growth one call may cause. It is measured for
|
||||
// the whole process, so it is approximate.
|
||||
MemoryBytes int64
|
||||
// CallStack is the maximum Lua call depth.
|
||||
CallStack int
|
||||
}
|
||||
|
||||
func DefaultLimits() Limits {
|
||||
return Limits{
|
||||
Timeout: config.DefaultSandboxTimeout,
|
||||
SessionTimeout: config.DefaultSessionTimeout,
|
||||
MemoryBytes: config.DefaultMemoryMB << 20,
|
||||
CallStack: config.DefaultCallStack,
|
||||
}
|
||||
}
|
||||
|
||||
func LimitsFrom(s config.Sandbox) Limits {
|
||||
return Limits{
|
||||
Timeout: s.Timeout.Duration,
|
||||
SessionTimeout: s.SessionTimeout.Duration,
|
||||
MemoryBytes: int64(s.MemoryMB) << 20,
|
||||
CallStack: s.CallStack,
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
ErrTimeout = errors.New("timed out")
|
||||
ErrMemoryLimit = errors.New("exceeded the memory limit")
|
||||
)
|
||||
|
||||
// removedGlobals could load code, or reach the interpreter's internals.
|
||||
// The os, io, debug, package and coroutine libraries are never opened.
|
||||
var removedGlobals = []string{
|
||||
"dofile", "loadfile", "load", "loadstring", "require", "module",
|
||||
"collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs",
|
||||
}
|
||||
|
||||
// shortCalls lets one parse-type call run at a time, so the heap growth the
|
||||
// memory watchdog sees is that call's. These calls take milliseconds.
|
||||
var shortCalls sync.Mutex
|
||||
|
||||
const watchInterval = 2 * time.Millisecond
|
||||
|
||||
func newState(limits Limits) *lua.LState {
|
||||
L := lua.NewState(lua.Options{
|
||||
SkipOpenLibs: true,
|
||||
CallStackSize: limits.CallStack,
|
||||
RegistrySize: 16 * 1024,
|
||||
RegistryMaxSize: 256 * 1024,
|
||||
MinimizeStackMemory: true,
|
||||
})
|
||||
|
||||
for _, lib := range []struct {
|
||||
name string
|
||||
open lua.LGFunction
|
||||
} {
|
||||
{lua.BaseLibName, lua.OpenBase},
|
||||
{lua.TabLibName, lua.OpenTable},
|
||||
{lua.StringLibName, lua.OpenString},
|
||||
{lua.MathLibName, lua.OpenMath},
|
||||
} {
|
||||
L.Push(L.NewFunction(lib.open))
|
||||
L.Push(lua.LString(lib.name))
|
||||
L.Call(1, 0)
|
||||
}
|
||||
|
||||
for _, name := range removedGlobals { L.SetGlobal(name, lua.LNil) }
|
||||
|
||||
// string.rep allocates its whole result at once, faster than the
|
||||
// watchdog can react.
|
||||
if str, ok := L.GetGlobal("string").(*lua.LTable); ok { str.RawSetString("rep", L.NewFunction(cappedRep(limits.MemoryBytes))) }
|
||||
|
||||
return L
|
||||
}
|
||||
|
||||
func cappedRep(limit int64) lua.LGFunction {
|
||||
return func(L *lua.LState) int {
|
||||
s := L.CheckString(1)
|
||||
n := L.CheckInt(2)
|
||||
if n <= 0 || s == "" {
|
||||
L.Push(lua.LString(""))
|
||||
return 1
|
||||
}
|
||||
|
||||
if int64(len(s))*int64(n) > limit { L.RaiseError("string.rep: result of %d bytes exceeds the memory limit", int64(len(s))*int64(n)) }
|
||||
|
||||
L.Push(lua.LString(strings.Repeat(s, n)))
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
// run calls fn, which must call into L, under a timeout and the memory
|
||||
// watchdog.
|
||||
func run(L *lua.LState, parent context.Context, timeout time.Duration, memLimit int64, fn func() error) error {
|
||||
ctx, cancel := context.WithTimeout(parent, timeout)
|
||||
defer cancel()
|
||||
|
||||
var overLimit atomic.Bool
|
||||
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
go watchMemory(ctx, done, memLimit, &overLimit, cancel)
|
||||
|
||||
L.SetContext(ctx)
|
||||
defer L.RemoveContext()
|
||||
|
||||
err := fn()
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case overLimit.Load():
|
||||
return ErrMemoryLimit
|
||||
case parent.Err() != nil:
|
||||
return parent.Err()
|
||||
case errors.Is(ctx.Err(), context.DeadlineExceeded):
|
||||
return fmt.Errorf("%w after %s", ErrTimeout, timeout)
|
||||
default:
|
||||
return luaError(err)
|
||||
}
|
||||
}
|
||||
|
||||
// watchMemory cancels the call once the heap has grown by more than limit
|
||||
// since the call started.
|
||||
func watchMemory(ctx context.Context, done <-chan struct{}, limit int64, overLimit *atomic.Bool, cancel context.CancelFunc) {
|
||||
sample := []metrics.Sample{{Name: "/memory/classes/heap/objects:bytes"}}
|
||||
heap := func() int64 {
|
||||
metrics.Read(sample)
|
||||
return int64(sample[0].Value.Uint64())
|
||||
}
|
||||
|
||||
base := heap()
|
||||
ticker := time.NewTicker(watchInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if heap()-base > limit {
|
||||
overLimit.Store(true)
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// luaError turns a Lua error into a one-line error such as
|
||||
// "amazon.lua:12: attempt to index a nil value".
|
||||
func luaError(err error) error {
|
||||
var apiErr *lua.ApiError
|
||||
if errors.As(err, &apiErr) && apiErr.Object != nil { return errors.New(strings.TrimSpace(apiErr.Object.String())) }
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
)
|
||||
|
||||
// sandboxed loads testdata/sandbox/<name>.lua.
|
||||
func sandboxed(t *testing.T, name string, limits Limits) *Plugin {
|
||||
t.Helper()
|
||||
|
||||
path := filepath.Join(testdata, "sandbox", name+".lua")
|
||||
|
||||
code, err := os.ReadFile(path)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
p, err := Load(name, path, code, limits, discardLogger())
|
||||
if err != nil { t.Fatal(err) }
|
||||
t.Cleanup(p.Close)
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func parse(p *Plugin, url string) (*Result, error) {
|
||||
return p.Parse(context.Background(), []byte("<html></html>"), url)
|
||||
}
|
||||
|
||||
func TestSandboxGlobals(t *testing.T) {
|
||||
r, err := parse(sandboxed(t, "globals", DefaultLimits()), "")
|
||||
if err != nil { t.Fatal(err) }
|
||||
if !r.Available { t.Errorf("reachable from the sandbox: %s", r.Title) }
|
||||
}
|
||||
|
||||
func TestSandboxTimeout(t *testing.T) {
|
||||
limits := DefaultLimits()
|
||||
limits.Timeout = 50 * time.Millisecond
|
||||
|
||||
p := sandboxed(t, "timeout", limits)
|
||||
|
||||
for _, url := range []string{"loop", "pcall"} {
|
||||
start := time.Now()
|
||||
if _, err := parse(p, url); !errors.Is(err, ErrTimeout) { t.Errorf("%s: got %v, want ErrTimeout", url, err) }
|
||||
if d := time.Since(start); d > 2*time.Second { t.Errorf("%s: timeout took %s", url, d) }
|
||||
}
|
||||
|
||||
// The plugin was reloaded and still works.
|
||||
if r, err := parse(p, "fine"); err != nil || !r.Available { t.Errorf("after a timeout: %v, %+v", err, r) }
|
||||
}
|
||||
|
||||
func TestSandboxMemoryLimit(t *testing.T) {
|
||||
limits := DefaultLimits()
|
||||
limits.Timeout = 20 * time.Second
|
||||
limits.MemoryBytes = 16 << 20
|
||||
|
||||
if _, err := parse(sandboxed(t, "memory", limits), ""); !errors.Is(err, ErrMemoryLimit) { t.Errorf("got %v, want ErrMemoryLimit", err) }
|
||||
if _, err := parse(sandboxed(t, "string_rep", limits), ""); err == nil || !strings.Contains(err.Error(), "memory limit") { t.Errorf("string.rep: got %v, want a memory limit error", err) }
|
||||
}
|
||||
|
||||
func TestSandboxCallStack(t *testing.T) {
|
||||
limits := DefaultLimits()
|
||||
limits.CallStack = 50
|
||||
|
||||
if _, err := parse(sandboxed(t, "call_stack", limits), ""); err == nil || !strings.Contains(err.Error(), "stack overflow") { t.Errorf("got %v, want a stack overflow", err) }
|
||||
}
|
||||
|
||||
// The config's seller policies rank these values by name, so a renamed
|
||||
// constant would silently never pass a policy.
|
||||
func TestSellersKnownToConfig(t *testing.T) {
|
||||
anyone := config.Item{Seller: config.SellerAny}
|
||||
for _, s := range []string{SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown} {
|
||||
if !anyone.AcceptsSeller(s) { t.Errorf("config does not know seller %q", s) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Package price reads prices as shops print them.
|
||||
package price
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// symbols maps currency signs and local abbreviations to ISO 4217 codes.
|
||||
// Ambiguous ones such as "kr" are left out on purpose.
|
||||
var symbols = []struct{ sign, code string }{
|
||||
{"€", "EUR"},
|
||||
{"£", "GBP"},
|
||||
{"US$", "USD"},
|
||||
{"$", "USD"},
|
||||
{"¥", "JPY"},
|
||||
{"zł", "PLN"},
|
||||
{"Kč", "CZK"},
|
||||
{"Fr.", "CHF"},
|
||||
}
|
||||
|
||||
var (
|
||||
codeRe = regexp.MustCompile(`\b(EUR|GBP|USD|CHF|PLN|SEK|NOK|DKK|CZK|HUF|JPY|CAD|AUD)\b`)
|
||||
numberRe = regexp.MustCompile(`\d[\d.,' \x{00a0}\x{202f}]*`)
|
||||
)
|
||||
|
||||
// Parse reads the first price in s, such as "1.299,99 €", "£1,299.99",
|
||||
// "1 299,99 €" or "EUR 12.50". It returns the amount, the ISO 4217
|
||||
// currency code if `s` names one (or "" if not), and whether a price was
|
||||
// found.
|
||||
func Parse(s string) (float64, string, bool) {
|
||||
num := strings.TrimRight(numberRe.FindString(s), ".,' \u00a0\u202f")
|
||||
if num == "" { return 0, "", false }
|
||||
|
||||
v, err := strconv.ParseFloat(normalize(num), 64)
|
||||
if err != nil { return 0, "", false }
|
||||
|
||||
return v, currency(s), true
|
||||
}
|
||||
|
||||
// normalize turns a localized number into the form ParseFloat accepts.
|
||||
func normalize(num string) string {
|
||||
// Spaces and apostrophes only ever group thousands.
|
||||
num = strings.NewReplacer(" ", "", "\u00a0", "", "\u202f", "", "'", "").Replace(num)
|
||||
|
||||
dot, comma := strings.LastIndex(num, "."), strings.LastIndex(num, ",")
|
||||
|
||||
switch {
|
||||
case dot >= 0 && comma >= 0:
|
||||
// Both present: the last one is the decimal separator.
|
||||
if dot > comma { return strings.ReplaceAll(num, ",", "") }
|
||||
|
||||
return strings.ReplaceAll(strings.ReplaceAll(num, ".", ""), ",", ".")
|
||||
case comma >= 0:
|
||||
return decimalOrGrouping(num, ",")
|
||||
case dot >= 0:
|
||||
return decimalOrGrouping(num, ".")
|
||||
default:
|
||||
return num
|
||||
}
|
||||
}
|
||||
|
||||
// decimalOrGrouping handles a number with only one kind of separator. Used
|
||||
// more than once, or followed by exactly three digits, it groups thousands
|
||||
// ("1.299", "1,299,000"). Otherwise it is the decimal point ("12,5", "9.99").
|
||||
func decimalOrGrouping(num, sep string) string {
|
||||
last := num[strings.LastIndex(num, sep)+1:]
|
||||
if strings.Count(num, sep) > 1 || len(last) == 3 { return strings.ReplaceAll(num, sep, "") }
|
||||
|
||||
return strings.Replace(num, sep, ".", 1)
|
||||
}
|
||||
|
||||
func currency(s string) string {
|
||||
if m := codeRe.FindString(s); m != "" { return m }
|
||||
|
||||
for _, sym := range symbols {
|
||||
if strings.Contains(s, sym.sign) { return sym.code }
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package price
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
for in, want := range map[string]struct {
|
||||
value float64
|
||||
currency string
|
||||
}{
|
||||
"1.299,99 €": {1299.99, "EUR"},
|
||||
"£1,299.99": {1299.99, "GBP"},
|
||||
"1 299,99 €": {1299.99, "EUR"},
|
||||
"1\u00a0299,99\u00a0€": {1299.99, "EUR"},
|
||||
"1\u202f299,99 €": {1299.99, "EUR"},
|
||||
"129,99 €": {129.99, "EUR"},
|
||||
"129,99€": {129.99, "EUR"},
|
||||
"€129.99": {129.99, "EUR"},
|
||||
"$1,299.99": {1299.99, "USD"},
|
||||
"US$ 49.00": {49, "USD"},
|
||||
"EUR 12,50": {12.5, "EUR"},
|
||||
"12.50 GBP": {12.5, "GBP"},
|
||||
"CHF 1'299.90": {1299.9, "CHF"},
|
||||
"1.299 €": {1299, "EUR"},
|
||||
"1,299": {1299, ""},
|
||||
"1.299.000,00 €": {1299000, "EUR"},
|
||||
"12,5": {12.5, ""},
|
||||
"9.99": {9.99, ""},
|
||||
"49": {49, ""},
|
||||
"Preis: 59,99 € inkl. MwSt.": {59.99, "EUR"},
|
||||
" £7. ": {7, "GBP"},
|
||||
"99,00 zł": {99, "PLN"},
|
||||
} {
|
||||
v, c, ok := Parse(in)
|
||||
if !ok || v != want.value || c != want.currency { t.Errorf("Parse(%q) = %v, %q, %v; want %v, %q", in, v, c, ok, want.value, want.currency) }
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNoPrice(t *testing.T) {
|
||||
for _, in := range []string{"", "Derzeit nicht verfügbar", "€", "kostenlos"} {
|
||||
if v, c, ok := Parse(in); ok { t.Errorf("Parse(%q) = %v, %q, true; want no price", in, v, c) }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user