| 1 | package websource |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "html" |
| 6 | "net/url" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // A small HTML reader, shared by Research's fetcher (internal/runner/ |
| 11 | // webread) and the instance's lookups (Readable): enough for a page's |
| 12 | // title, meta, readable text and the URLs it names, with every loop |
| 13 | // bounded by the input. It never builds a tree and never runs anything a |
| 14 | // page carries. |
| 15 | |
| 16 | // HTMLRefKind is what a URL a page names is for. |
| 17 | type HTMLRefKind int |
| 18 | |
| 19 | // The kinds of URL a page names. |
| 20 | const ( |
| 21 | RefLink HTMLRefKind = iota |
| 22 | RefStylesheet |
| 23 | RefIcon |
| 24 | RefOG |
| 25 | RefImage |
| 26 | ) |
| 27 | |
| 28 | // HTMLRef is a URL a page names, resolved against the page (or its base), or |
| 29 | // the refusal resolving it met. logo marks an img whose src, alt, id or |
| 30 | // class says "logo". |
| 31 | type HTMLRef struct { |
| 32 | Kind HTMLRefKind |
| 33 | URL URL |
| 34 | Raw string |
| 35 | Err error |
| 36 | Logo bool |
| 37 | Alt string |
| 38 | } |
| 39 | |
| 40 | // HTMLMeta is one of a page's meta tags. |
| 41 | type HTMLMeta struct{ Name, Content string } |
| 42 | |
| 43 | // HTMLPage is what ExtractHTML read from a page. |
| 44 | type HTMLPage struct { |
| 45 | Title string |
| 46 | Metas []HTMLMeta |
| 47 | Text string |
| 48 | Styles string |
| 49 | Refs []HTMLRef |
| 50 | } |
| 51 | |
| 52 | // Bounds on what one page contributes. |
| 53 | const ( |
| 54 | maxMetas = 32 |
| 55 | maxMetaValue = 1024 |
| 56 | maxStyles = 32 << 10 |
| 57 | maxAttributes = 64 |
| 58 | maxAttrValue = 4096 |
| 59 | ) |
| 60 | |
| 61 | // rawText elements hold text that is not markup; their content runs to |
| 62 | // the matching end tag. |
| 63 | var rawText = map[string]bool{"script": true, "style": true, "title": true, "textarea": true, "noscript": true, "xmp": true, "template": true, "iframe": true, "noembed": true, "noframes": true, "plaintext": true} |
| 64 | |
| 65 | var blockTags = map[string]bool{"p": true, "div": true, "br": true, "li": true, "ul": true, "ol": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "tr": true, "td": true, "th": true, "table": true, "section": true, "article": true, "header": true, "footer": true, "nav": true, "main": true, "aside": true, "blockquote": true, "pre": true, "hr": true, "dt": true, "dd": true, "figcaption": true, "address": true} |
| 66 | |
| 67 | func asciiLower(b []byte) []byte { |
| 68 | out := make([]byte, len(b)) |
| 69 | for i, c := range b { |
| 70 | if c >= 'A' && c <= 'Z' { |
| 71 | c += 'a' - 'A' |
| 72 | } |
| 73 | out[i] = c |
| 74 | } |
| 75 | return out |
| 76 | } |
| 77 | |
| 78 | func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } |
| 79 | func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' } |
| 80 | |
| 81 | type extractor struct { |
| 82 | HTMLPage |
| 83 | base URL |
| 84 | based bool |
| 85 | buf bytes.Buffer |
| 86 | // maxText bounds the text, maxRefs the URLs named. |
| 87 | maxText, maxRefs int |
| 88 | } |
| 89 | |
| 90 | // maxRawText bounds a page's text before whitespace collapses. |
| 91 | func (x *extractor) maxRawText() int { return 4 * x.maxText } |
| 92 | |
| 93 | // ExtractHTML reads src, an HTML page fetched from base: its title, |
| 94 | // meta, readable text (at most maxText bytes) and up to maxRefs of the |
| 95 | // URLs it names. Every loop is bounded by the input; it never builds a |
| 96 | // tree and never runs anything a page carries. Scripts' and styles' |
| 97 | // contents are never text. |
| 98 | func ExtractHTML(src []byte, base URL, maxText, maxRefs int) HTMLPage { |
| 99 | x := &extractor{base: base, maxText: maxText, maxRefs: maxRefs} |
| 100 | lower := asciiLower(src) |
| 101 | n := len(src) |
| 102 | for i := 0; i < n; { |
| 103 | if src[i] != '<' { |
| 104 | j := bytes.IndexByte(src[i:], '<') |
| 105 | if j < 0 { |
| 106 | j = n - i |
| 107 | } |
| 108 | x.addText(src[i : i+j]) |
| 109 | i += j |
| 110 | continue |
| 111 | } |
| 112 | switch { |
| 113 | case bytes.HasPrefix(lower[i:], []byte("<!--")): |
| 114 | end := bytes.Index(lower[i+4:], []byte("-->")) |
| 115 | if end < 0 { |
| 116 | return x.finish() |
| 117 | } |
| 118 | i += 4 + end + 3 |
| 119 | case i+1 < n && (src[i+1] == '!' || src[i+1] == '?'): |
| 120 | end := bytes.IndexByte(src[i:], '>') |
| 121 | if end < 0 { |
| 122 | return x.finish() |
| 123 | } |
| 124 | i += end + 1 |
| 125 | case i+1 < n && src[i+1] == '/': |
| 126 | j := i + 2 |
| 127 | for j < n && (isLetter(src[j]) || src[j] >= '0' && src[j] <= '9') { |
| 128 | j++ |
| 129 | } |
| 130 | if blockTags[string(lower[i+2:j])] { |
| 131 | x.buf.WriteByte('\n') |
| 132 | } |
| 133 | end := bytes.IndexByte(src[j:], '>') |
| 134 | if end < 0 { |
| 135 | return x.finish() |
| 136 | } |
| 137 | i = j + end + 1 |
| 138 | case i+1 < n && isLetter(src[i+1]): |
| 139 | name, attrs, next, ok := parseTag(src, lower, i+1) |
| 140 | if !ok { |
| 141 | return x.finish() |
| 142 | } |
| 143 | i = next |
| 144 | x.start(name, attrs) |
| 145 | if rawText[name] { |
| 146 | end := bytes.Index(lower[i:], []byte("</"+name)) |
| 147 | if end < 0 { |
| 148 | end = n - i |
| 149 | } |
| 150 | x.raw(name, src[i:i+end]) |
| 151 | i += end |
| 152 | if close := bytes.IndexByte(src[i:], '>'); close >= 0 { |
| 153 | i += close + 1 |
| 154 | } else { |
| 155 | i = n |
| 156 | } |
| 157 | } |
| 158 | default: |
| 159 | x.addText(src[i : i+1]) |
| 160 | i++ |
| 161 | } |
| 162 | } |
| 163 | return x.finish() |
| 164 | } |
| 165 | |
| 166 | type attr struct{ name, value string } |
| 167 | |
| 168 | // parseTag reads a start tag from its name at i to its closing '>'. |
| 169 | func parseTag(src, lower []byte, i int) (name string, attrs []attr, next int, ok bool) { |
| 170 | n := len(src) |
| 171 | j := i |
| 172 | for j < n && !isSpace(src[j]) && src[j] != '>' && src[j] != '/' { |
| 173 | j++ |
| 174 | } |
| 175 | name = string(lower[i:j]) |
| 176 | for { |
| 177 | for j < n && (isSpace(src[j]) || src[j] == '/') { |
| 178 | j++ |
| 179 | } |
| 180 | if j >= n { |
| 181 | return "", nil, n, false |
| 182 | } |
| 183 | if src[j] == '>' { |
| 184 | return name, attrs, j + 1, true |
| 185 | } |
| 186 | k := j |
| 187 | for k < n && !isSpace(src[k]) && src[k] != '=' && src[k] != '>' && src[k] != '/' { |
| 188 | k++ |
| 189 | } |
| 190 | key := string(lower[j:k]) |
| 191 | if k == j { |
| 192 | k++ // a stray '=' with no name |
| 193 | } |
| 194 | j = k |
| 195 | for j < n && isSpace(src[j]) { |
| 196 | j++ |
| 197 | } |
| 198 | var value []byte |
| 199 | if j < n && src[j] == '=' { |
| 200 | j++ |
| 201 | for j < n && isSpace(src[j]) { |
| 202 | j++ |
| 203 | } |
| 204 | if j < n && (src[j] == '"' || src[j] == '\'') { |
| 205 | q := src[j] |
| 206 | end := bytes.IndexByte(src[j+1:], q) |
| 207 | if end < 0 { |
| 208 | return "", nil, n, false |
| 209 | } |
| 210 | value = src[j+1 : j+1+end] |
| 211 | j += end + 2 |
| 212 | } else { |
| 213 | k = j |
| 214 | for k < n && !isSpace(src[k]) && src[k] != '>' { |
| 215 | k++ |
| 216 | } |
| 217 | value = src[j:k] |
| 218 | j = k |
| 219 | } |
| 220 | } |
| 221 | if key != "" && len(attrs) < maxAttributes { |
| 222 | if len(value) > maxAttrValue { |
| 223 | value = value[:maxAttrValue] |
| 224 | } |
| 225 | attrs = append(attrs, attr{key, html.UnescapeString(string(value))}) |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | func get(attrs []attr, name string) (string, bool) { |
| 231 | for _, a := range attrs { |
| 232 | if a.name == name { |
| 233 | return a.value, true |
| 234 | } |
| 235 | } |
| 236 | return "", false |
| 237 | } |
| 238 | |
| 239 | func (x *extractor) addText(b []byte) { |
| 240 | room := x.maxRawText() - x.buf.Len() |
| 241 | if room <= 0 { |
| 242 | return |
| 243 | } |
| 244 | if len(b) > room { |
| 245 | b = b[:room] |
| 246 | } |
| 247 | // A run of text's own line breaks are layout; block tags make lines. |
| 248 | space := false |
| 249 | for _, r := range html.UnescapeString(string(b)) { |
| 250 | if r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\f' || r == '\u00a0' { |
| 251 | if !space { |
| 252 | x.buf.WriteByte(' ') |
| 253 | } |
| 254 | space = true |
| 255 | continue |
| 256 | } |
| 257 | space = false |
| 258 | x.buf.WriteRune(r) |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | func (x *extractor) addRef(kind HTMLRefKind, raw string, logo bool, alt string) { |
| 263 | if len(x.Refs) >= x.maxRefs { |
| 264 | return |
| 265 | } |
| 266 | raw = strings.TrimSpace(raw) |
| 267 | if raw == "" { |
| 268 | return |
| 269 | } |
| 270 | if p, err := url.Parse(raw); err == nil && p.Scheme != "" && p.Scheme != "http" && p.Scheme != "https" { |
| 271 | return // data:, javascript:, mailto: name nothing to fetch |
| 272 | } |
| 273 | u, err := Resolve(x.base, raw) |
| 274 | x.Refs = append(x.Refs, HTMLRef{Kind: kind, URL: u, Raw: raw, Err: err, Logo: logo, Alt: alt}) |
| 275 | } |
| 276 | |
| 277 | func (x *extractor) start(name string, attrs []attr) { |
| 278 | if blockTags[name] { |
| 279 | x.buf.WriteByte('\n') |
| 280 | } |
| 281 | switch name { |
| 282 | case "base": |
| 283 | if href, ok := get(attrs, "href"); ok && !x.based { |
| 284 | x.based = true |
| 285 | if u, err := Resolve(x.base, strings.TrimSpace(href)); err == nil { |
| 286 | x.base = u |
| 287 | } |
| 288 | } |
| 289 | case "meta": |
| 290 | key, ok := get(attrs, "name") |
| 291 | if !ok { |
| 292 | key, _ = get(attrs, "property") |
| 293 | } |
| 294 | key = strings.ToLower(strings.TrimSpace(key)) |
| 295 | content, _ := get(attrs, "content") |
| 296 | if key == "description" || key == "theme-color" || strings.HasPrefix(key, "og:") { |
| 297 | if len(x.Metas) < maxMetas { |
| 298 | x.Metas = append(x.Metas, HTMLMeta{key, clip(oneLine(content), maxMetaValue)}) |
| 299 | } |
| 300 | if key == "og:image" || key == "og:image:url" || key == "og:image:secure_url" { |
| 301 | x.addRef(RefOG, content, false, "") |
| 302 | } |
| 303 | } |
| 304 | case "link": |
| 305 | href, _ := get(attrs, "href") |
| 306 | rel, _ := get(attrs, "rel") |
| 307 | for _, r := range strings.Fields(strings.ToLower(rel)) { |
| 308 | switch r { |
| 309 | case "stylesheet": |
| 310 | x.addRef(RefStylesheet, href, false, "") |
| 311 | return |
| 312 | case "icon", "apple-touch-icon", "apple-touch-icon-precomposed", "mask-icon": |
| 313 | x.addRef(RefIcon, href, false, "") |
| 314 | return |
| 315 | } |
| 316 | } |
| 317 | case "img": |
| 318 | src, _ := get(attrs, "src") |
| 319 | alt, _ := get(attrs, "alt") |
| 320 | id, _ := get(attrs, "id") |
| 321 | class, _ := get(attrs, "class") |
| 322 | logo := strings.Contains(strings.ToLower(src+" "+alt+" "+id+" "+class), "logo") |
| 323 | x.addRef(RefImage, src, logo, clip(oneLine(alt), 200)) |
| 324 | if alt = oneLine(alt); alt != "" && x.buf.Len() < x.maxRawText() { |
| 325 | x.buf.WriteString(" [image: " + clip(alt, 200) + "] ") |
| 326 | } |
| 327 | case "a": |
| 328 | if href, ok := get(attrs, "href"); ok { |
| 329 | x.addRef(RefLink, href, false, "") |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | func (x *extractor) raw(name string, content []byte) { |
| 335 | switch name { |
| 336 | case "title": |
| 337 | if x.Title == "" { |
| 338 | x.Title = clip(oneLine(html.UnescapeString(string(content))), maxMetaValue) |
| 339 | } |
| 340 | case "style": |
| 341 | if room := maxStyles - len(x.Styles); room > 0 { |
| 342 | x.Styles += clip(string(content), room) |
| 343 | } |
| 344 | case "textarea": |
| 345 | x.addText(content) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | func (x *extractor) finish() HTMLPage { |
| 350 | p := x.HTMLPage |
| 351 | var lines []string |
| 352 | for _, line := range strings.Split(x.buf.String(), "\n") { |
| 353 | if line = oneLine(line); line != "" { |
| 354 | lines = append(lines, line) |
| 355 | } |
| 356 | } |
| 357 | p.Text = clip(strings.Join(lines, "\n"), x.maxText) |
| 358 | p.Styles = strings.TrimSpace(p.Styles) |
| 359 | return p |
| 360 | } |
| 361 | |
| 362 | // oneLine collapses whitespace, including line breaks, to single spaces. |
| 363 | func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") } |
| 364 | |
| 365 | // Clip cuts s to at most n bytes on a UTF-8 boundary. |
| 366 | func Clip(s string, n int) string { return clip(s, n) } |
| 367 | |
| 368 | func clip(s string, n int) string { |
| 369 | if len(s) <= n { |
| 370 | return s |
| 371 | } |
| 372 | s = s[:n] |
| 373 | for len(s) > 0 && !utf8Start(s[len(s)-1]) { |
| 374 | s = s[:len(s)-1] |
| 375 | } |
| 376 | if len(s) > 0 && s[len(s)-1] >= 0x80 { |
| 377 | s = s[:len(s)-1] // a lead byte whose continuation was cut |
| 378 | } |
| 379 | return s |
| 380 | } |
| 381 | |
| 382 | func utf8Start(b byte) bool { return b < 0x80 || b >= 0xc0 } |
| 383 | |