-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
137 lines (83 loc) · 2.17 KB
/
parser.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
package main
import "github.com/PuerkitoBio/goquery"
import "strings"
import "log"
import "github.com/kennygrant/sanitize"
type parser struct {
feeds [](*feed)
feeds_config []FeedSchema
config Config
fetcher fetcher
}
//NewParser constructor
func NewParser(config_file string, feeds_schema_file string) (*parser, error) {
//Read config data
config, err := readConfig(config_file)
if(err != nil) {
return nil,err
}
fetcher,err := NewFetcher(config)
if err != nil {
return nil,err
}
schemas, err := readFeedsConfig(feeds_schema_file)
if err != nil {
return nil,err
}
p := new(parser)
p.fetcher = *fetcher
p.feeds_config = *schemas
p.config = *config
return p,nil
}
//Run the parser
func (p *parser) Run() {
for _,schema := range p.feeds_config {
feed := NewFeed(schema.Title, schema.Description)
p.feeds = append(p.feeds, feed)
log.Println("BEGIN: Parsing " + schema.Title)
p.parseFeed(&schema, feed)
log.Println("END: Parsing " + schema.Title)
}
}
//GetFeeds returns all parsed feeds
//this function must of-course be called after the 'Run' function
func (p *parser) GetFeeds() ( *[](*feed) ) {
return &p.feeds
}
//Save all feeds
func (p *parser) Save() {
for _,feed := range p.feeds {
if nil != feed.Save( p.config.SaveDir + "/" + sanitize.Name(feed.Title) + ".json" ) {
log.Println("Could not save feed '" + feed.Title + "'")
}
}
}
//getDocument retrieves the url from the fetcher
//the fetcher will cache the url content
func (p *parser) getDocument(url string) (*goquery.Document, error) {
//Fetch the url
content, err := p.fetcher.Get(url)
if err != nil {
return nil, err
}
//Create GoQuery document
reader := strings.NewReader(content)
document, err := goquery.NewDocumentFromReader(reader)
if err != nil {
return nil, err
}
return document, err
}
//CountFeeds will count all parsed feeds
func (p *parser) CountFeeds() uint {
return uint( len(p.feeds) )
}
//CountArticles counts all the articles of all the feeds
func (p *parser) CountArticles() uint {
var count uint = 0
for _,feed := range p.feeds {
count += feed.CountArticles()
}
return count
}