package main
// Pedigree lookup: resolve a dog by chip / registration number / name against
// SKK (Svenska Kennelklubben) HUNDDATA, then crawl its ancestry and expose it as
// an ahnentafel-positioned tree. SKK has no public API, so this scrapes the
// interactive ASP.NET WebForms app the same way a browser drives it:
//
// 1. Resolve — POST Hund_sok.aspx/HundData (a JSON page-method) → hundid.
// 2. Fetch — GET Hund_Stamtavla.aspx?hundid=X, then POST ddlGenerationer=7
// to render 7 generations in one page; parse its rowspan grid.
// 3. Deepen — each generation-7 leaf links via __doPostBack; POST that link
// and read the ancestor's hundid out of the response __VIEWSTATE,
// then recurse. BFS terminates when the ancestry runs out.
//
// A deep crawl is dozens of sequential requests, so a lookup returns the first
// 7 generations immediately and keeps crawling in the background; the finished
// tree is cached per hundid (pedigrees don't change) so a dog is crawled once.
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/net/html"
)
const (
skkBase = "https://hundar.skk.se/hunddata/"
skkUA = "Mozilla/5.0 (X11; Linux x86_64) puppy-tracker pedigree lookup"
skkDelay = 250 * time.Millisecond // politeness between upstream requests
crawlGens = 7 // generations SKK renders per page
maxCrawlPages = 400 // hard caps so a crawl can never run away
maxCrawlRequests = 3000
crawlDeadline = 5 * time.Minute
maxActiveJobs = 4 // concurrent background crawls, total
firstPageWait = 20 * time.Second
)
// pedNode is one dog at an ahnentafel position (1 = subject, sire = 2n, dam = 2n+1).
type pedNode struct {
Reg string `json:"reg,omitempty"`
Name string `json:"name,omitempty"`
Titles string `json:"titles,omitempty"`
Hundid string `json:"hundid,omitempty"`
}
// pedSubject is the looked-up dog's headline info, from the resolver row.
type pedSubject struct {
Hundid string `json:"hundid"`
Reg string `json:"reg"`
Name string `json:"name"`
Breed string `json:"breed"`
Chip string `json:"chip"`
Sex string `json:"sex,omitempty"`
}
// skkClient is a single browser-like session against SKK (cookie jar + UA).
type skkClient struct {
hc *http.Client
}
func newSKKClient() (*skkClient, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &skkClient{hc: &http.Client{Jar: jar, Timeout: 30 * time.Second}}, nil
}
func (c *skkClient) do(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", skkUA)
return c.hc.Do(req)
}
// warm establishes an ASP.NET session (SessionId + anti-XSRF cookies) that the
// resolver and pedigree pages both require.
func (c *skkClient) warm(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, skkBase+"Hund_sok.aspx", nil)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
return nil
}
// hundDataRow mirrors the fields the resolver page-method returns.
type hundDataRow struct {
Hundid string `json:"hundid"`
Regnr string `json:"Regnr"`
Hundnamn string `json:"hundnamn"`
Chipnr string `json:"chipnr"`
Rastext string `json:"rastext"`
Kon string `json:"Kon"`
IDnummer string `json:"IDnummer"`
Antal string `json:"Antal"`
IsError bool `json:"IsError"`
ErrorText string `json:"ErrorText"`
}
var digitsRE = regexp.MustCompile(`^\d+$`)
// resolve turns a user query (chip number, registration number, or name) into
// matching dogs. The field is chosen by shape: a long all-digit string is a
// chip; anything with a letter or slash is a registration number; otherwise a
// name search (which may return several rows to disambiguate).
func (c *skkClient) resolve(ctx context.Context, q string) ([]hundDataRow, error) {
body := map[string]string{
"txtRegnr": "", "txtIDnummer": "", "txtChipnr": "",
"txtHundnamn": "", "ddlRasIn": "", "ddlKon": "", "txtLicensnr": "",
}
switch {
case digitsRE.MatchString(q) && len(q) >= 10:
body["txtChipnr"] = q
case strings.ContainsAny(q, "/") || strings.IndexFunc(q, isLetter) >= 0:
body["txtRegnr"] = q
default:
body["txtHundnamn"] = q
}
buf, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
skkBase+"Hund_sok.aspx/HundData", bytes.NewReader(buf))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=utf-8")
req.Header.Set("Referer", skkBase+"Hund_sok.aspx")
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("resolver HTTP %d", resp.StatusCode)
}
var wrap struct {
D []hundDataRow `json:"d"`
}
if err := json.Unmarshal(raw, &wrap); err != nil {
return nil, fmt.Errorf("resolver response: %w", err)
}
// SKK signals "no matches" (and other soft failures like a query needing more
// input) via a single IsError row rather than an HTTP error. Treat it as an
// empty result so the caller reports a clean "not found" instead of a 502.
if len(wrap.D) == 1 && wrap.D[0].IsError {
return nil, nil
}
return wrap.D, nil
}
func isLetter(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}
// fetchPage GETs a dog's pedigree then POSTs ddlGenerationer=7 (with titles on)
// to render 7 generations, returning that page's HTML. The returned HTML is used
// for both grid parsing and the __doPostBack calls that resolve its leaf dogs,
// so its hidden fields (viewstate / event validation) match its ctl ids.
func (c *skkClient) fetchPage(ctx context.Context, hundid string) (string, string, error) {
pageURL := skkBase + "Hund_Stamtavla.aspx?hundid=" + url.QueryEscape(hundid)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, pageURL, nil)
if err != nil {
return "", pageURL, err
}
req.Header.Set("Referer", skkBase+"Hund_sok.aspx")
resp, err := c.do(req)
if err != nil {
return "", pageURL, err
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
resp.Body.Close()
if err != nil {
return "", pageURL, err
}
first := string(raw)
form := hiddenFields(first)
form.Set("ctl00$bodyContent$ddlGenerationer", strconv.Itoa(crawlGens))
form.Set("ctl00$bodyContent$ddlTitlar", "J")
form.Set("__EVENTTARGET", "ctl00$bodyContent$ddlGenerationer")
form.Set("__EVENTARGUMENT", "")
html7, err := c.postForm(ctx, pageURL, form)
if err != nil {
return "", pageURL, err
}
return html7, pageURL, nil
}
func (c *skkClient) postForm(ctx context.Context, pageURL string, form url.Values) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, pageURL,
strings.NewReader(form.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", pageURL)
resp, err := c.do(req)
if err != nil {
return "", err
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
resp.Body.Close()
if err != nil {
return "", err
}
return string(raw), nil
}
var (
viewstateRE = regexp.MustCompile(`name="__VIEWSTATE" id="__VIEWSTATE" value="([^"]+)"`)
// The clicked dog's internal hundid, encoded in the response viewstate as the
// string "hundid", a type byte (\x05), a length byte, then ASCII digits.
vsHundidRE = regexp.MustCompile(`(?s)hundid\x05.(\d+)`)
)
// postbackHundid clicks an ancestor's __doPostBack link on the given page and
// recovers that ancestor's hundid from the response viewstate. The rendered
// pedigree table never re-roots on such a click, but the viewstate carries the
// clicked dog's id — which is exactly the handle needed to fetch its own page.
func (c *skkClient) postbackHundid(ctx context.Context, pageHTML, ctlid, pageURL string) (string, error) {
form := hiddenFields(pageHTML)
form.Set("ctl00$bodyContent$ddlGenerationer", strconv.Itoa(crawlGens))
form.Set("ctl00$bodyContent$ddlTitlar", "J")
form.Set("__EVENTTARGET", ctlid)
form.Set("__EVENTARGUMENT", "")
resp, err := c.postForm(ctx, pageURL, form)
if err != nil {
return "", err
}
m := viewstateRE.FindStringSubmatch(resp)
if m == nil {
return "", nil
}
dec := decodeB64(m[1])
mm := vsHundidRE.FindSubmatch(dec)
if mm == nil {
return "", nil
}
return string(mm[1]), nil
}
func decodeB64(s string) []byte {
if m := len(s) % 4; m != 0 {
s += strings.Repeat("=", 4-m)
}
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return nil
}
return b
}
// hiddenFields collects every on a page into a form value
// set, so an ASP.NET postback can echo back __VIEWSTATE / __EVENTVALIDATION etc.
func hiddenFields(pageHTML string) url.Values {
vals := url.Values{}
node, err := html.Parse(strings.NewReader(pageHTML))
if err != nil {
return vals
}
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "input" {
var typ, name, val string
for _, a := range n.Attr {
switch a.Key {
case "type":
typ = a.Val
case "name":
name = a.Val
case "value":
val = a.Val
}
}
if typ == "hidden" && name != "" {
vals.Set(name, val)
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(node)
return vals
}
// gridCell is a parsed pedigree table cell.
type gridCell struct {
reg, name, titles, ctlid string
occupied bool
}
var doPostBackRE = regexp.MustCompile(`__doPostBack\('([^']+)'`)
var wsRE = regexp.MustCompile(`\s+`)
// parseGrid reconstructs the rowspan-based pedigree table into columns. Column c
// holds 2^c cells top-to-bottom; a cell's index within its column is its
// ahnentafel offset. Returns column index -> ordered cells.
func parseGrid(pageHTML string) map[int][]gridCell {
node, err := html.Parse(strings.NewReader(pageHTML))
if err != nil {
return nil
}
tbl := findByID(node, "bodyContent_tblStamtavla")
if tbl == nil {
return nil
}
occ := map[[2]int]bool{}
type placed struct {
r, c int
cell gridCell
}
var placedCells []placed
r := 0
for _, tr := range descendants(tbl, "tr") {
c := 0
for _, td := range directChildElements(tr, "td") {
for occ[[2]int{r, c}] {
c++
}
rs := 1
if v := attr(td, "rowspan"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
rs = n
}
}
for dr := 0; dr < rs; dr++ {
occ[[2]int{r + dr, c}] = true
}
placedCells = append(placedCells, placed{r, c, parseCell(td)})
c++
}
r++
}
byCol := map[int][]placed{}
for _, p := range placedCells {
byCol[p.c] = append(byCol[p.c], p)
}
out := map[int][]gridCell{}
for col, lst := range byCol {
sort.SliceStable(lst, func(i, j int) bool { return lst[i].r < lst[j].r })
cells := make([]gridCell, len(lst))
for i, p := range lst {
cells[i] = p.cell
}
out[col] = cells
}
return out
}
// parseCell extracts reg / name / titles / ctlid from one