/
main.go
174 lines (156 loc) · 4.48 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
package main
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/emirpasic/gods/sets/hashset"
"github.com/mmcdole/gofeed"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"os"
"time"
)
type FeedProgress struct {
URL string `json:"url"`
FetchedGuids *hashset.Set `json:"fetchedGuids"`
}
func main() {
log.SetLevel(log.InfoLevel)
app := &cli.App{
Name: "FeedFlux (ff)",
Usage: "FeedFlux is a lightweight tool developed in Go that parses various feeds such as RSS and Atom into a unified JSON format, with the ability to record and resume fetching progress.",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "record",
Aliases: []string{"r"},
Value: "",
Usage: "to record fetching progress, specify a progress directory",
Required: false,
},
&cli.BoolFlag{
Name: "continue",
Aliases: []string{"c"},
Usage: "to continue fetching from a previous record, record directory must be specified",
Required: false,
},
&cli.IntFlag{
Name: "timeout",
Usage: "timeout in seconds for fetching a feed",
Value: 10,
Required: false,
},
},
Action: func(c *cli.Context) error {
recordDirPath := c.String("record")
continueFetch := c.Bool("continue")
if continueFetch && recordDirPath == "" {
log.Fatal("record directory must be specified when continuing fetching")
}
urls := c.Args().Slice()
if len(urls) == 0 {
log.Fatal("no feed url specified")
}
results := make(chan *gofeed.Item)
for _, url := range urls {
go fetchFeed(url, results, recordDirPath, continueFetch, c.Int("timeout"))
}
for item := range results {
jsonFeed, _ := json.Marshal(item)
fmt.Println(string(jsonFeed))
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func urlToFileName(url string) string {
fileName := sha256.Sum256([]byte(url))
return fmt.Sprintf("%x.json", fileName)
}
func readRecordFile(url string, recordDirPath string) (*FeedProgress, error) {
fileName := urlToFileName(url)
recordFilePath := fmt.Sprintf("%s/%s", recordDirPath, fileName)
recordFile, err := os.Open(recordFilePath)
// If record file does not exist, return nil with error
if os.IsNotExist(err) {
return nil, err
}
// If other error occurs, return nil with error
if err != nil {
return nil, err
}
defer recordFile.Close()
decoder := json.NewDecoder(recordFile)
var record FeedProgress
if err := decoder.Decode(&record); err != nil {
return nil, err
}
if record.FetchedGuids == nil {
return nil, fmt.Errorf("fetchedGuids is nil")
}
return &record, nil
}
func fetchFeed(url string, results chan *gofeed.Item, recordDirPath string, continueFetch bool, timeoutSeconds int) {
defer close(results)
fp := gofeed.NewParser()
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds)*time.Second)
defer cancel()
feed, err := fp.ParseURLWithContext(url, ctx)
if err != nil {
log.Errorf("error fetching %s: %s", url, err)
return
}
// FetchedUntil is the largest published timestamp of all items
record := FeedProgress{
URL: url,
FetchedGuids: hashset.New(),
}
// record file path is sha256 of url
fileName := sha256.Sum256([]byte(url))
recordFilePath := fmt.Sprintf("%s/%x.json", recordDirPath, fileName)
// log feed info
log.WithFields(log.Fields{
"title": feed.Title,
"link": feed.Link,
"items": len(feed.Items),
}).Infof("fetched %s", url)
if continueFetch {
// If continue fetching, read record file
recordFile, err := readRecordFile(url, recordDirPath)
if err != nil {
log.Warnf("error reading record file %s: %s, continue fetching from scratch", recordFilePath, err)
} else {
log.Infof("continue fetching %s", url)
record = *recordFile
}
}
for _, item := range feed.Items {
// If continue fetching, skip items that are fetched before
if continueFetch && record.FetchedGuids.Contains(item.GUID) {
continue
}
results <- item
record.FetchedGuids.Add(item.GUID)
}
if recordDirPath != "" {
// Create record directory if not exists
if _, err := os.Stat(recordDirPath); os.IsNotExist(err) {
if err := os.Mkdir(recordDirPath, 0755); err != nil {
log.Fatal(err)
}
}
// Write record file
recordFile, err := os.OpenFile(recordFilePath, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer recordFile.Close()
encoder := json.NewEncoder(recordFile)
if err := encoder.Encode(record); err != nil {
log.Fatal(err)
}
}
}