package webread import ( "amadan.net/oficina/equipo/internal/websource" ) // The page reader is websource.ExtractHTML, shared with the instance's // lookups; webread keeps its own view of what it read. type refKind = websource.HTMLRefKind const ( refLink = websource.RefLink refStylesheet = websource.RefStylesheet refIcon = websource.RefIcon refOG = websource.RefOG refImage = websource.RefImage ) var kindName = map[refKind]string{refLink: "link", refStylesheet: "stylesheet", refIcon: "icon", refOG: "og", refImage: "img"} // ref is a URL a page names, resolved against the page (or its base), or // the refusal resolving it met. logo marks an img whose src, alt, id or // class says "logo". type ref struct { kind refKind url websource.URL raw string err error logo bool alt string } type meta struct{ name, content string } type page struct { title string metas []meta text string styles string refs []ref } // extractHTML reads src, an HTML page fetched from base. func extractHTML(src []byte, base websource.URL) page { h := websource.ExtractHTML(src, base, MaxPageText, MaxLinks) p := page{title: h.Title, text: h.Text, styles: h.Styles} for _, m := range h.Metas { p.metas = append(p.metas, meta{m.Name, m.Content}) } for _, r := range h.Refs { p.refs = append(p.refs, ref{kind: r.Kind, url: r.URL, raw: r.Raw, err: r.Err, logo: r.Logo, alt: r.Alt}) } return p } // clip cuts s to at most n bytes on a UTF-8 boundary. func clip(s string, n int) string { return websource.Clip(s, n) } // Expansion caps per approved page (spec ยง3.2). const ( maxStylesheets = 5 maxIcons = 5 maxOG = 1 maxLogos = 3 maxSameHost = 5 ) type candidate struct { kind refKind url websource.URL raw string err error } // expansions is what an approved HTML page at pageURL adds to the fetch, // in document order: stylesheets, icons, og:image, logo images and links // on the same host, each within its cap. A URL that fails the contract is // kept, as a refusal to log, and counts against its cap; a link to another // host, or one that fails, is not a candidate at all. func expansions(p page, pageURL websource.URL) []candidate { caps := map[refKind]int{refStylesheet: maxStylesheets, refIcon: maxIcons, refOG: maxOG, refImage: maxLogos, refLink: maxSameHost} seen := map[string]bool{pageURL.String(): true} var out []candidate for _, r := range p.refs { if caps[r.kind] == 0 || (r.kind == refImage && !r.logo) { continue } if r.kind == refLink && (r.err != nil || r.url.Host != pageURL.Host) { continue } if r.err == nil { if seen[r.url.String()] { continue } seen[r.url.String()] = true } caps[r.kind]-- out = append(out, candidate{kind: r.kind, url: r.url, raw: r.raw, err: r.err}) } return out }