-
Notifications
You must be signed in to change notification settings - Fork 1
/
feed-helpers.go
273 lines (222 loc) · 7.08 KB
/
feed-helpers.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
package main
import (
"bytes"
"encoding/gob"
"fmt"
"regexp"
"sort"
"time"
"github.com/kyokomi/emoji"
"github.com/mmcdole/gofeed"
"jaytaylor.com/html2text"
)
type ByTitle []*gofeed.Item
func (a ByTitle) Len() int { return len(a) }
func (a ByTitle) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTitle) Less(i, j int) bool {
return fileNameClean(a[i].Title) < fileNameClean(a[j].Title)
}
func CleanupCacheTime(key string, mins time.Duration) {
timer := time.NewTimer(mins * time.Minute)
go func() {
<-timer.C
feedcache.Erase(key)
}()
}
func getItemTimestamp(item *gofeed.Item) time.Time {
if item.UpdatedParsed != nil {
return *(item.UpdatedParsed)
}
if item.PublishedParsed != nil {
return *(item.PublishedParsed)
}
return time.Now()
}
func UpdateSingleFeed(feed *Feed, nodeCount uint64) ([]*IndexedFile, uint64, *gofeed.Feed) {
// Updates a single feed. Returns the new list of IndexedFiles,
// an updated nodecount and a feed data object (usually feeddata).
var feeddata *gofeed.Feed
if feed.Cache {
var feedbytes bytes.Buffer
reNonAlNum, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
panic("Regex failed. Oops.")
}
cacheentry := fmt.Sprintf("feed-%s", reNonAlNum.ReplaceAllString(feed.URL, ""))
cached, found := feedcache.Read(cacheentry)
if found != nil {
// Retrieve the feed and put it into our cache:
fp := gofeed.NewParser()
feeddata, _ = fp.ParseURL(feed.URL)
emoji.Printf(":floppy_disk: Caching the feed from '%s'.\n", feed.URL)
var mins int32
if feed.CacheMins == 0 {
mins = 60
} else {
mins = feed.CacheMins
}
// Convert to and store as bytes:
enc := gob.NewEncoder(&feedbytes)
store := enc.Encode(feeddata)
if store != nil {
emoji.Printf(":bangbang: Encoding the cache entry for '%s' failed: %v\n", feed.URL, store)
} else {
feedcache.Write(cacheentry, feedbytes.Bytes())
CleanupCacheTime(cacheentry, time.Duration(mins))
}
} else {
// Use the cached copy of the feed:
feedbytes = *bytes.NewBuffer(cached)
dec := gob.NewDecoder(&feedbytes)
emoji.Printf(":floppy_disk: Loading '%s' from the cache.\n", feed.URL)
decoderr := dec.Decode(&feeddata)
if decoderr != nil {
emoji.Printf(":bangbang: Decoding the cache entry for '%s' failed: %v\n", feed.URL, decoderr)
// Return to no caching:
fp := gofeed.NewParser()
feeddata, _ = fp.ParseURL(feed.URL)
}
}
} else {
// No caching.
// emoji.Printf(":arrows_counterclockwise: Updating feed contents for '%s'.\n", feed.URL)
fp := gofeed.NewParser()
feeddata, _ = fp.ParseURL(feed.URL)
}
sort.Sort(ByTitle(feeddata.Items))
fname, prev_fname := "", ""
// File collision counter
col_cnt := 0
// Add files to the feeds:
feedFiles := make([]*IndexedFile, 0)
for _, item := range feeddata.Items {
itemTimestamp := getItemTimestamp(item)
// Checking collision
fname = fileNameClean(item.Title)
if fname == prev_fname {
col_cnt += 1
} else {
col_cnt = 0
}
prev_fname = fname
extension, content := GenerateOutputData(feed, item)
if col_cnt > 0 {
fname = fmt.Sprintf("%s [%d].%s", fname, col_cnt, extension)
} else {
fname = fmt.Sprintf("%s.%s", fname, extension)
}
feedFiles = append(feedFiles, &IndexedFile{
Filename: fname,
Timestamp: itemTimestamp,
Inode: nodeCount,
Data: []byte(content),
})
nodeCount++
}
return feedFiles, nodeCount, feeddata
}
func PopulateFeedTree(cfg RssfsConfig) map[string][]*IndexedFile {
// Generates a file system, returns a tree of folders and files.
// This updates each feed in the tree, it can be a relatively
// slow operation on more than just a handful of feeds...
retval := make(map[string][]*IndexedFile)
nodeCount := uint64(1001)
feedFiles := make([]*IndexedFile, 0)
var feeddata *gofeed.Feed
rootItems := make([]*IndexedFile, 0)
fp := gofeed.NewParser()
for _, category := range cfg.Categories {
// Add each category as a subdirectory.
catsFeeds := make([]*IndexedFile, 0)
// Descend into them and add the feeds.
for _, subfeed := range category.Feeds {
feedFiles, nodeCount, feeddata = UpdateSingleFeed(subfeed, nodeCount)
var nodeTimestamp time.Time
// Note: Certain blogs won't send a valid time stamp. Urgh.
if feeddata.UpdatedParsed != nil {
nodeTimestamp = *(feeddata.UpdatedParsed)
} else {
if feeddata.PublishedParsed != nil {
nodeTimestamp = *(feeddata.PublishedParsed)
} else {
nodeTimestamp = time.Now()
}
}
catsFeeds = append(catsFeeds, &IndexedFile{
Filename: fileNameClean(feeddata.Title),
IsDirectory: true,
Timestamp: nodeTimestamp,
Inode: nodeCount,
Feed: subfeed,
})
nodeCount += 100
retval["/"+fileNameClean(category.Name)+"/"+fileNameClean(feeddata.Title)] = feedFiles
}
retval["/"+fileNameClean(category.Name)] = catsFeeds
// Finally, append this category to our root structure:
rootItems = append(rootItems, &IndexedFile{
Filename: fileNameClean(category.Name),
IsDirectory: true,
Timestamp: time.Now(),
Inode: nodeCount,
})
nodeCount++
}
for _, feed := range cfg.Feeds {
// Add the feeds in the root structure as well.
feeddata, _ := fp.ParseURL(feed.URL)
var nodeTimestamp time.Time
// Note: Certain blogs won't send a valid time stamp. Urgh.
if feeddata.UpdatedParsed != nil {
nodeTimestamp = *(feeddata.UpdatedParsed)
} else {
if feeddata.PublishedParsed != nil {
nodeTimestamp = *(feeddata.PublishedParsed)
} else {
nodeTimestamp = time.Now()
}
}
rootItems = append(rootItems, &IndexedFile{
Filename: fileNameClean(feeddata.Title),
IsDirectory: true,
Timestamp: nodeTimestamp,
Inode: nodeCount,
Feed: feed,
})
nodeCount += 100
// Add files to the feeds:
feedFiles := make([]*IndexedFile, 0)
feedFiles, nodeCount, feeddata = UpdateSingleFeed(feed, nodeCount)
retval["/"+fileNameClean(feeddata.Title)] = feedFiles
}
// Finalize the tree:
retval["/"] = rootItems
return retval
}
func GenerateOutputData(feedopts *Feed, item *gofeed.Item) (ext string, content string) {
// Generates the output file (extension and content) for an item.
// Takes the feed's options as the first parameter to determine
// whether to use plain text and to add the link.
if feedopts.PlainText {
// Parse into plain text:
outContent, _ := html2text.FromString(item.Content, html2text.Options{PrettyTables: true, OmitLinks: false})
// Prepend the title and the link (if wanted):
link := ""
if feedopts.ShowLink && item.Link != "" {
link = fmt.Sprintf("%s%s", LineBreak, item.Link)
}
content = fmt.Sprintf("%s%s%s%s%s", item.Title, link, LineBreak, LineBreak, outContent)
ext = "txt"
} else {
outTitle := ""
// Prepend the title and link (if wanted):
if feedopts.ShowLink && item.Link != "" {
outTitle = fmt.Sprintf("<h1><a href=\"%s\">%s</a></h1>", item.Link, item.Title)
} else {
outTitle = fmt.Sprintf("<h1>%s</h1>", item.Title)
}
content = fmt.Sprintf("%s%s%s", outTitle, LineBreak, item.Content)
ext = "html"
}
return ext, content
}