-
Notifications
You must be signed in to change notification settings - Fork 0
/
extractTitle.go
executable file
·99 lines (79 loc) · 1.81 KB
/
extractTitle.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
package actions
import (
"github.com/PuerkitoBio/goquery"
log "github.com/sirupsen/logrus"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/andybalholm/cascadia"
"github.com/zaibon/ircbot"
)
type TitleExtract struct {
selector cascadia.Selector
}
func NewTitleExtract() *TitleExtract {
return &TitleExtract{
selector: cascadia.MustCompile("title"),
}
}
func (u *TitleExtract) Command() []string {
return []string{
"PRIVMSG",
}
}
func (u *TitleExtract) Usage() string {
return ""
}
func (u *TitleExtract) Do(b *ircbot.IrcBot, m *ircbot.IrcMsg) {
u.do(b, m)
}
func (u *TitleExtract) do(b *ircbot.IrcBot, m *ircbot.IrcMsg) {
for _, word := range m.Trailing {
if !strings.Contains(word, "http") {
continue
}
URL, err := url.Parse(word)
if err != nil {
log.WithField("url", word).Errorln("error parsing url")
continue
}
go func() {
log.WithField("url", URL.String()).Debugln("Start extract title")
title, err := extractTitle(URL.String(), u.selector)
if err == nil {
b.Say(m.Channel(), title)
}
log.WithFields(log.Fields{
"url": URL.String(),
"title": title,
}).Debugln("title found")
}()
}
}
func extractTitle(url string, selector cascadia.Selector) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
contentType := resp.Header.Get("Content-Type")
switch {
case strings.Contains(contentType, "text/html"):
return cssSelectHTML(resp.Body, selector)
default:
return "", fmt.Errorf("mime not supported")
}
}
func cssSelectHTML(r io.Reader, selector cascadia.Selector) (string, error) {
doc, err := goquery.NewDocumentFromReader(r)
if err != nil {
return "", err
}
title := ""
doc.Find("title").Each(func(i int, s *goquery.Selection) {
title = title + s.Text()
})
return title, nil
}