-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
213 lines (184 loc) · 4.43 KB
/
Copy pathmain.go
File metadata and controls
213 lines (184 loc) · 4.43 KB
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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"os"
"sort"
"sync"
"time"
"github.com/ejholmes/kiterss/internal/config"
"github.com/mmcdole/gofeed"
"github.com/spf13/cobra"
_ "modernc.org/sqlite"
)
// Version is set at build time via ldflags.
var Version = "dev"
type Item struct {
ID string `json:"id"`
Title string `json:"title"`
Link string `json:"link"`
Date string `json:"date"`
DateParsed time.Time `json:"-"` // Used for sorting, not serialized
Description string `json:"description,omitempty"`
Content string `json:"content,omitempty"`
Source string `json:"source"`
}
// FeedFetcher abstracts feed fetching for testability.
type FeedFetcher interface {
Fetch(url string) (*gofeed.Feed, error)
}
// HTTPFeedFetcher fetches feeds over HTTP.
type HTTPFeedFetcher struct {
parser *gofeed.Parser
}
func NewHTTPFeedFetcher() *HTTPFeedFetcher {
return &HTTPFeedFetcher{parser: gofeed.NewParser()}
}
func (f *HTTPFeedFetcher) Fetch(url string) (*gofeed.Feed, error) {
return f.parser.ParseURL(url)
}
// KiteRSS holds dependencies for the application.
type KiteRSS struct {
DB *sql.DB
Fetcher FeedFetcher
Out io.Writer
ErrOut io.Writer
}
func main() {
if err := config.EnsureDirs(); err != nil {
log.Fatal(err)
}
configPath, err := config.ConfigPath()
if err != nil {
log.Fatal(err)
}
dbPath, err := config.DBPath()
if err != nil {
log.Fatal(err)
}
db, err := sql.Open("sqlite", dbPath)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS read_items (id TEXT PRIMARY KEY)"); err != nil {
log.Fatal(err)
}
app := &KiteRSS{
DB: db,
Fetcher: NewHTTPFeedFetcher(),
Out: os.Stdout,
ErrOut: os.Stderr,
}
rootCmd := &cobra.Command{
Use: "kiterss",
Short: "A simple CLI RSS reader",
}
listCmd := &cobra.Command{
Use: "list",
Short: "List unread items",
Run: func(cmd *cobra.Command, args []string) {
app.List(configPath)
},
}
readCmd := &cobra.Command{
Use: "read <id>...",
Short: "Mark items as read",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := app.MarkRead(args); err != nil {
log.Fatal(err)
}
fmt.Fprintf(app.Out, "Marked %d items as read.\n", len(args))
},
}
versionCmd := &cobra.Command{
Use: "version",
Short: "Print the version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(Version)
},
}
rootCmd.AddCommand(listCmd, readCmd, versionCmd)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
// List fetches all feeds and returns unread items.
func (k *KiteRSS) List(configPath string) {
cfg, err := config.Parse(configPath)
if err != nil {
log.Fatal(err)
}
items := k.ListItems(cfg.URLs)
enc := json.NewEncoder(k.Out)
enc.SetIndent("", " ")
enc.Encode(items)
}
// ListItems fetches feeds from the given URLs and returns unread items.
func (k *KiteRSS) ListItems(urls []string) []Item {
allItems := []Item{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()
feed, err := k.Fetcher.Fetch(url)
if err != nil {
fmt.Fprintf(k.ErrOut, "Error parsing %s: %v\n", url, err)
return
}
for _, item := range feed.Items {
id := item.GUID
if id == "" {
id = item.Link
}
if !k.isRead(id) {
var dateParsed time.Time
if item.PublishedParsed != nil {
dateParsed = *item.PublishedParsed
}
mu.Lock()
allItems = append(allItems, Item{
ID: id,
Title: item.Title,
Link: item.Link,
Date: item.Published,
DateParsed: dateParsed,
Source: url,
})
mu.Unlock()
}
}
}(url)
}
wg.Wait()
// Sort by date, newest first
sort.Slice(allItems, func(i, j int) bool {
return allItems[i].DateParsed.After(allItems[j].DateParsed)
})
return allItems
}
func (k *KiteRSS) isRead(id string) bool {
var exists bool
_ = k.DB.QueryRow("SELECT EXISTS(SELECT 1 FROM read_items WHERE id = ?)", id).Scan(&exists)
return exists
}
// MarkRead marks the given IDs as read in the database.
func (k *KiteRSS) MarkRead(ids []string) error {
stmt, err := k.DB.Prepare("INSERT OR IGNORE INTO read_items (id) VALUES (?)")
if err != nil {
return err
}
defer stmt.Close()
for _, id := range ids {
if _, err := stmt.Exec(id); err != nil {
return err
}
}
return nil
}