-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube.go
88 lines (67 loc) · 1.56 KB
/
youtube.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
package main
import (
"log"
"net/url"
"strings"
"github.com/mmcdole/gofeed"
)
func parseYoutubeFeeds(feed *gofeed.Feed) {
parsedUrl, err := url.Parse(feed.Link)
if err != nil {
log.Printf("Error parsing URL due to: %v", err)
return
}
// I trim the prefix www. because I don't know if youtube will use always the www. CNAME
if strings.TrimPrefix(parsedUrl.Hostname(), "www.") != "youtube.com" {
return
}
for index := range feed.Items {
addThumbnailToYoutubeItems(feed.Items[index])
}
}
func addThumbnailToYoutubeItems(item *gofeed.Item) {
// If I already have an image, I don't add it
if item.Image != nil && item.Image.URL != "" {
return
}
var url string
// Checking if there are Extensions since it's there that I have the thumbnail
if item.Extensions == nil {
return
}
// Checking media -> group, then since I have multiple []Extensions I use for and map access to retrieve (finally) the thumbnail
media, ok := item.Extensions["media"]
if !ok {
return
}
group, ok := media["group"]
if !ok {
return
}
for _, groupElem := range group {
if groupElem.Name != "group" {
continue
}
if groupElem.Children == nil {
continue
}
thumbnail, ok := groupElem.Children["thumbnail"]
if !ok {
continue
}
for _, thumbElem := range thumbnail {
if thumbElem.Name != "thumbnail" {
continue
}
if thumbElem.Attrs == nil {
continue
}
url = thumbElem.Attrs["url"]
}
}
// When finally I have an URL, I add the Image directly into the feed
item.Image = &gofeed.Image{
URL: url,
Title: "thumbnail",
}
}