5 "golang.org/x/net/html"
8 "github.com/terorie/yt-mango/util"
11 const descriptionSelector
= "#eow-description"
13 func (p
*parseVideoInfo
) parseDescription() error
{
14 // Find description root
15 descNode
:= p
.doc
.Find(descriptionSelector
).First()
16 if len(descNode
.Nodes
) == 0 { return errors
.New("could not find description") }
19 var buffer bytes
.Buffer
22 for c
:= descNode
.Nodes
[0].FirstChild
; c
!= nil; c
= c
.NextSibling
{
25 // FIXME: "&lt;" gets parsed to => "<"
26 // Write text to buffer, escaping markdown
27 err
:= util
.MarkdownTextEscape
.ToBuffer(c
.Data
, &buffer
)
28 if err
!= nil { return err
}
29 case html
.ElementNode
:
33 err
:= buffer
.WriteByte(0x0a)
34 if err
!= nil { return err
}
37 err
:= parseLink(c
, &buffer
)
38 if err
!= nil { return err
}
44 p
.v
.Description
= buffer
.String()
49 func parseLink(c
*html
.Node
, dest
*bytes
.Buffer
) error
{
51 if c
.FirstChild
== nil { return nil } // Empty link
52 if c
.FirstChild
.Type
!= html
.TextNode
{
53 return errors
.New("unexpected non-text node")
55 text
:= c
.FirstChild
.Data
58 for _
, attr
:= range c
.Attr
{
59 if attr
.Key
== "href" {
62 case strings
.HasPrefix(attr
.Val
, "/results"):
63 dest
.WriteString(text
)
66 case strings
.HasPrefix(attr
.Val
, "/redirect"):
69 // Decode link from href
70 link, err := decodeLink(attr.Val)
71 if err != nil { return err }
73 link, err = net.MarkdownLinkEscape.ToString(link)
74 if err != nil { return err }
76 dest.WriteString(fmt.Sprintf("[%s](%s)\n", text, link))
78 dest
.WriteString(text
)
81 return errors
.New("unknown link")
91 func decodeLink(href string) (string, error) {
92 url, err := url2.Parse(href)
93 if err != nil { return "", err }
96 link := query.Get("q")
97 if link == "" { return "", errors.New("empty link") }