-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
287 lines (236 loc) · 5.75 KB
/
main.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
package main
import (
"crypto/md5"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/user"
"path"
"strings"
"sync"
"time"
"github.com/mmcdole/gofeed"
)
func main() {
var feed string
var destination string
start := time.Now()
flag.StringVar(&feed, "f", "", "The rss feed to inspect")
flag.StringVar(&destination, "d", "", "The destination directory")
flag.Parse()
if len(feed) == 0 {
fmt.Println("No feed provided.")
return
}
if len(destination) == 0 {
destination = getUserConfigDirectory()
}
// Make sure the destination directory exists
_, err := os.Stat(destination)
if os.IsNotExist(err) {
os.MkdirAll(destination, 0755)
}
// Read the contents of the file
contents, err := readFeed(feed, destination)
if err != nil {
panic(err)
}
fmt.Println("Checking feed contents...")
feedName := snakeCase(contents.Title)
// Add jobs to the queue
var jobs []Job
for i := len(contents.Items) - 1; i >= 0; i-- {
job := Job{
ID: i,
Item: contents.Items[i],
Destination: destination + "/" + feedName,
}
jobs = append(jobs, job)
}
const NumberOfWorkers = 5
var (
wg sync.WaitGroup
jobChannel = make(chan Job)
)
wg.Add(NumberOfWorkers)
// start the workers
for i := 0; i < NumberOfWorkers; i++ {
go worker(i, &wg, jobChannel)
}
// Send jobs to workers
for _, job := range jobs {
jobChannel <- job
}
close(jobChannel)
wg.Wait()
fmt.Printf("Took %s\n", time.Since(start))
}
func generateFeedHash(feed string) string {
h := md5.New()
io.WriteString(h, feed)
return fmt.Sprintf("%x", h.Sum(nil))
}
// Read the contents of an rss file into memory. If the file
// has not been cached locally it will be downloaded.
func readFeed(feed string, destination string) (*gofeed.Feed, error) {
feedsFolder := destination + "/feeds"
filePath := feedsFolder + "/" + generateFeedHash(feed)
// Make sure the "feeds" folder exists
_, err := os.Stat(feedsFolder)
if os.IsNotExist(err) {
os.MkdirAll(feedsFolder, 0755)
}
fileInfo, err := os.Stat(filePath)
if os.IsNotExist(err) {
fmt.Println("Downloading feed contents: ", filePath)
downloadFile(feed, filePath)
}
// Is the locally cached file older than seven days?
currentTime := time.Now()
diff := currentTime.Sub(fileInfo.ModTime())
if diff.Minutes() > (60 * 24 * 7) {
fmt.Println("Refreshing feed contents: ", filePath)
downloadFile(feed, filePath)
}
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
fp := gofeed.NewParser()
return fp.Parse(file)
}
// https://progolang.com/how-to-download-files-in-go/
func downloadFile(url string, filepath string) error {
// create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// How can we determine if a download has not completed?
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return errors.New("Could not reach " + url)
}
// Write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
// Get the user's "config" directory
func getUserConfigDirectory() string {
usr, err := user.Current()
if err != nil {
return ""
}
return usr.HomeDir + "/.config/snarf"
}
// https://twinnation.org/articles/39/go-concurrency-goroutines-worker-pools-and-throttling-made-simple
func worker(id int, wg *sync.WaitGroup, jobChannel <-chan Job) {
defer wg.Done()
for job := range jobChannel {
result := maybeDownloadItem(id, job)
if result.Important {
fmt.Printf("%s\n", result.Message)
}
if result.Downloaded {
time.Sleep(5 * time.Second)
}
}
}
// Download the contents of an Item enclosure if it does not already
// exist in the destination folder.
func maybeDownloadItem(id int, job Job) JobResult {
// If no enclosures are listed we will skip this item
if len(job.Item.Enclosures) == 0 {
return JobResult{
Message: "No file to download",
Important: false,
Downloaded: false,
}
}
enclosure := job.Item.Enclosures[0]
// Extract the file extension from the download URL
extension, err := fileExtensionFromURL(enclosure.URL)
if err != nil {
return JobResult{
Message: "No file to download",
Important: false,
Downloaded: false,
}
}
// Make sure our destination folder exists
if !fileExists(job.Destination) {
os.MkdirAll(job.Destination, 0755)
}
// Generate a path for our download destination
fileName := snakeCase(job.Item.Title)
path := job.Destination + "/" + fileName + extension
if fileExists(path) {
return JobResult{
Message: "Already Downloaded " + path,
Important: false,
Downloaded: false,
}
}
err = downloadFile(enclosure.URL, path)
if err != nil {
return JobResult{
Message: err.Error(),
Important: true,
Downloaded: false,
}
}
return JobResult{
Message: fmt.Sprintf("downloaded: %s", job.Item.Title),
Important: true,
Downloaded: true,
}
}
func fileExtensionFromURL(href string) (string, error) {
// Parse the URL
u, err := url.Parse(href)
if err != nil {
return "", err
}
// Remove the query parameters
u.RawQuery = ""
// Extract the file name from the URL
filename := path.Base(u.String())
// Find the location of the "."
pivot := strings.Index(filename, ".")
// Return the file extension as a string
return filename[pivot:], nil
}
func snakeCase(name string) string {
name = strings.ToLower(name)
name = strings.Replace(name, " ", "_", -1)
name = strings.Replace(name, ":", "", -1)
return name
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
type Job struct {
ID int
Item *gofeed.Item
Destination string
}
type JobResult struct {
Message string
Important bool
Downloaded bool
}