/
besticon.go
571 lines (471 loc) · 11.3 KB
/
besticon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// Package besticon includes functions
// finding icons for a given web site.
package besticon
import (
"bytes"
"crypto/sha1"
"errors"
"fmt"
"image"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"sort"
"strings"
"time"
"image/color"
// Load supported image formats.
_ "image/gif"
_ "image/png"
_ "github.com/mat/besticon/ico"
"github.com/mat/besticon/colorfinder"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html/charset"
"golang.org/x/net/idna"
"golang.org/x/net/publicsuffix"
)
var defaultFormats []string
const MinIconSize = 0
// TODO: Turn into env var: https://github.com/rendomnet/besticon/commit/c85867cc80c00c898053ce8daf40d51a93b9d39f#diff-37b57e3fdbe4246771791e86deb4d69dL41
const MaxIconSize = 500
// Icon holds icon information.
type Icon struct {
URL string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
Format string `json:"format"`
Bytes int `json:"bytes"`
Error error `json:"error"`
Sha1sum string `json:"sha1sum"`
ImageData []byte `json:",omitempty"`
}
type IconFinder struct {
FormatsAllowed []string
HostOnlyDomains []string
KeepImageBytes bool
icons []Icon
}
func (f *IconFinder) FetchIcons(url string) ([]Icon, error) {
url = strings.TrimSpace(url)
if !strings.HasPrefix(url, "http:") && !strings.HasPrefix(url, "https:") {
url = "http://" + url
}
url = f.stripIfNecessary(url)
var err error
if CacheEnabled() {
f.icons, err = resultFromCache(url)
} else {
f.icons, err = fetchIcons(url)
}
return f.Icons(), err
}
// stripIfNecessary removes everything from URL but the Scheme and Host
// part if URL.Host is found in HostOnlyDomains.
// This can be used for very popular domains like youtube.com where throttling is
// an issue.
func (f *IconFinder) stripIfNecessary(URL string) string {
u, e := url.Parse(URL)
if e != nil {
return URL
}
for _, h := range f.HostOnlyDomains {
if h == u.Host || h == "*" {
domainOnlyURL := url.URL{Scheme: u.Scheme, Host: u.Host}
return domainOnlyURL.String()
}
}
return URL
}
func (f *IconFinder) IconInSizeRange(r SizeRange) *Icon {
icons := f.Icons()
// Try to return smallest in range perfect..max
sortIcons(icons, false)
for _, ico := range icons {
if (ico.Width >= r.Perfect && ico.Height >= r.Perfect) && (ico.Width <= r.Max && ico.Height <= r.Max) {
return &ico
}
}
// Try to return biggest in range perfect..min
sortIcons(icons, true)
for _, ico := range icons {
if (ico.Width >= r.Min && ico.Height >= r.Min) && (ico.Width <= r.Perfect && ico.Height <= r.Perfect) {
return &ico
}
}
return nil
}
func (f *IconFinder) MainColorForIcons() *color.RGBA {
return MainColorForIcons(f.icons)
}
func (f *IconFinder) Icons() []Icon {
return discardUnwantedFormats(f.icons, f.FormatsAllowed)
}
func (ico *Icon) Image() (*image.Image, error) {
img, _, err := image.Decode(bytes.NewReader(ico.ImageData))
return &img, err
}
func discardUnwantedFormats(icons []Icon, wantedFormats []string) []Icon {
formats := defaultFormats
if len(wantedFormats) > 0 {
formats = wantedFormats
}
return filterIcons(icons, func(ico Icon) bool {
return includesString(formats, ico.Format)
})
}
type iconPredicate func(Icon) bool
func filterIcons(icons []Icon, pred iconPredicate) []Icon {
var result []Icon
for _, ico := range icons {
if pred(ico) {
result = append(result, ico)
}
}
return result
}
func includesString(arr []string, str string) bool {
for _, e := range arr {
if e == str {
return true
}
}
return false
}
func fetchIcons(siteURL string) ([]Icon, error) {
html, urlAfterRedirect, e := fetchHTML(siteURL)
if e != nil {
return nil, e
}
links, e := findIconLinks(urlAfterRedirect, html)
if e != nil {
return nil, e
}
icons := fetchAllIcons(links)
icons = rejectBrokenIcons(icons)
sortIcons(icons, true)
return icons, nil
}
const maxResponseBodySize = 10485760 // 10MB
func fetchHTML(url string) ([]byte, *url.URL, error) {
r, e := Get(url)
if e != nil {
return nil, nil, e
}
if !(r.StatusCode >= 200 && r.StatusCode < 300) {
return nil, nil, errors.New("besticon: not found")
}
b, e := GetBodyBytes(r)
if e != nil {
return nil, nil, e
}
if len(b) == 0 {
return nil, nil, errors.New("besticon: empty response")
}
reader := bytes.NewReader(b)
contentType := r.Header.Get("Content-Type")
utf8reader, e := charset.NewReader(reader, contentType)
if e != nil {
return nil, nil, e
}
utf8bytes, e := ioutil.ReadAll(utf8reader)
if e != nil {
return nil, nil, e
}
return utf8bytes, r.Request.URL, nil
}
var iconPaths = []string{
"/favicon.ico",
"/apple-touch-icon.png",
"/apple-touch-icon-precomposed.png",
}
type empty struct{}
func findIconLinks(siteURL *url.URL, html []byte) ([]string, error) {
doc, e := docFromHTML(html)
if e != nil {
return nil, e
}
baseURL := determineBaseURL(siteURL, doc)
links := make(map[string]empty)
// Add common, hard coded icon paths
for _, path := range iconPaths {
links[urlFromBase(baseURL, path)] = empty{}
}
// Add icons found in page
urls := extractIconTags(doc)
for _, u := range urls {
absoluteURL, e := absoluteURL(baseURL, u)
if e == nil {
links[absoluteURL] = empty{}
}
}
// Turn unique keys into array
var result []string
for u := range links {
result = append(result, u)
}
sort.Strings(result)
return result, nil
}
func determineBaseURL(siteURL *url.URL, doc *goquery.Document) *url.URL {
baseTagHref := extractBaseTag(doc)
if baseTagHref != "" {
baseTagURL, e := url.Parse(baseTagHref)
if e != nil {
return siteURL
}
return baseTagURL
}
return siteURL
}
func docFromHTML(html []byte) (*goquery.Document, error) {
doc, e := goquery.NewDocumentFromReader(bytes.NewReader(html))
if e != nil || doc == nil {
return nil, errParseHTML
}
return doc, nil
}
var csspaths = strings.Join([]string{
"link[rel='icon']",
"link[rel='shortcut icon']",
"link[rel='apple-touch-icon']",
"link[rel='apple-touch-icon-precomposed']",
// Capitalized variants, TODO: refactor
"link[rel='ICON']",
"link[rel='SHORTCUT ICON']",
"link[rel='APPLE-TOUCH-ICON']",
"link[rel='APPLE-TOUCH-ICON-PRECOMPOSED']",
}, ", ")
var errParseHTML = errors.New("besticon: could not parse html")
func extractBaseTag(doc *goquery.Document) string {
href := ""
doc.Find("head base[href]").First().Each(func(i int, s *goquery.Selection) {
href, _ = s.Attr("href")
})
return href
}
func extractIconTags(doc *goquery.Document) []string {
var hits []string
doc.Find(csspaths).Each(func(i int, s *goquery.Selection) {
href, ok := s.Attr("href")
if ok && href != "" {
hits = append(hits, href)
}
})
return hits
}
func MainColorForIcons(icons []Icon) *color.RGBA {
if len(icons) == 0 {
return nil
}
var icon *Icon
// Prefer .png and .gif
for _, ico := range icons {
if ico.Format == "png" || ico.Format == "gif" {
icon = &ico
break
}
}
// Try .ico else
if icon == nil {
for _, ico := range icons {
if ico.Format == "ico" {
icon = &ico
break
}
}
}
if icon == nil {
return nil
}
img, err := icon.Image()
if err != nil {
return nil
}
cf := colorfinder.ColorFinder{}
mainColor, err := cf.FindMainColor(*img)
if err != nil {
return nil
}
return &mainColor
}
func fetchAllIcons(urls []string) []Icon {
ch := make(chan Icon)
for _, u := range urls {
go func(u string) { ch <- fetchIconDetails(u) }(u)
}
var icons []Icon
for range urls {
icon := <-ch
icons = append(icons, icon)
}
return icons
}
func fetchIconDetails(url string) Icon {
i := Icon{URL: url}
response, e := Get(url)
if e != nil {
i.Error = e
return i
}
b, e := GetBodyBytes(response)
if e != nil {
i.Error = e
return i
}
cfg, format, e := image.DecodeConfig(bytes.NewReader(b))
if e != nil {
i.Error = fmt.Errorf("besticon: unknown image format: %s", e)
return i
}
i.Width = cfg.Width
i.Height = cfg.Height
i.Format = format
i.Bytes = len(b)
i.Sha1sum = sha1Sum(b)
if keepImageBytes {
i.ImageData = b
}
return i
}
func Get(urlstring string) (*http.Response, error) {
u, e := url.Parse(urlstring)
if e != nil {
return nil, e
}
// Maybe we can get rid of this conversion someday
// https://github.com/golang/go/issues/13835
u.Host, e = idna.ToASCII(u.Host)
if e != nil {
return nil, e
}
req, e := http.NewRequest("GET", u.String(), nil)
if e != nil {
return nil, e
}
setDefaultHeaders(req)
start := time.Now()
resp, err := client.Do(req)
end := time.Now()
duration := end.Sub(start)
if err != nil {
logger.Printf("Error: %s %s %s %.2fms",
req.Method,
req.URL,
err,
float64(duration)/float64(time.Millisecond),
)
} else {
logger.Printf("%s %s %d %.2fms %d",
req.Method,
req.URL,
resp.StatusCode,
float64(duration)/float64(time.Millisecond),
resp.ContentLength,
)
}
return resp, err
}
func GetBodyBytes(r *http.Response) ([]byte, error) {
limitReader := io.LimitReader(r.Body, maxResponseBodySize)
b, e := ioutil.ReadAll(limitReader)
r.Body.Close()
if len(b) >= maxResponseBodySize {
return nil, errors.New("body too large")
}
return b, e
}
func setDefaultHeaders(req *http.Request) {
req.Header.Set("Accept", "*/*")
req.Header.Set("User-Agent", getenvOrFallback("HTTP_USER_AGENT", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1"))
}
func mustInitCookieJar() *cookiejar.Jar {
options := cookiejar.Options{
PublicSuffixList: publicsuffix.List,
}
jar, e := cookiejar.New(&options)
if e != nil {
panic(e)
}
return jar
}
func checkRedirect(req *http.Request, via []*http.Request) error {
setDefaultHeaders(req)
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
return nil
}
func absoluteURL(baseURL *url.URL, path string) (string, error) {
u, e := url.Parse(path)
if e != nil {
return "", e
}
u.Scheme = baseURL.Scheme
if u.Scheme == "" {
u.Scheme = "http"
}
if u.Host == "" {
u.Host = baseURL.Host
}
return baseURL.ResolveReference(u).String(), nil
}
func urlFromBase(baseURL *url.URL, path string) string {
u := *baseURL
u.Path = path
if u.Scheme == "" {
u.Scheme = "http"
}
return u.String()
}
func rejectBrokenIcons(icons []Icon) []Icon {
var result []Icon
for _, img := range icons {
if img.Error == nil && (img.Width > 1 && img.Height > 1) {
result = append(result, img)
}
}
return result
}
func sha1Sum(b []byte) string {
hash := sha1.New()
hash.Write(b)
bs := hash.Sum(nil)
return fmt.Sprintf("%x", bs)
}
var client *http.Client
var keepImageBytes bool
func init() {
duration, e := time.ParseDuration(getenvOrFallback("HTTP_CLIENT_TIMEOUT", "5s"))
if e != nil {
panic(e)
}
setHTTPClient(&http.Client{Timeout: duration})
// Needs to be kept in sync with those image/... imports
defaultFormats = []string{"png", "gif", "ico"}
}
func setHTTPClient(c *http.Client) {
c.Jar = mustInitCookieJar()
c.CheckRedirect = checkRedirect
client = c
}
var logger *log.Logger
// SetLogOutput sets the output for the package's logger.
func SetLogOutput(w io.Writer) {
logger = log.New(w, "http: ", log.LstdFlags|log.Lmicroseconds)
}
func init() {
SetLogOutput(os.Stdout)
keepImageBytes = true
}
func getenvOrFallback(key string, fallbackValue string) string {
value := os.Getenv(key)
if len(strings.TrimSpace(value)) != 0 {
return value
}
return fallbackValue
}
var BuildDate string // set via ldflags on Make