-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkibner.go
1779 lines (1410 loc) · 34.5 KB
/
kibner.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"database/sql"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"unicode"
kibner "github.com/deepilla/kibner/internal/types"
"github.com/mmcdole/gofeed"
)
func initDB(db *sql.DB) error {
sql := []string{
`DROP TABLE IF EXISTS items`,
`DROP TABLE IF EXISTS feeds`,
// The feeds table has an AUTOINCREMENT id which means
// that the ids of deleted rows are not reused. This
// gives us an immutable id which we can use to uniquely
// identify a feed. So we can select a feed, store its
// id, and operate on it some time later without fear
// of modifying a different row with the same id.
`CREATE TABLE feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
desc TEXT,
type TEXT NOT NULL,
url TEXT NOT NULL,
image TEXT,
link TEXT,
timestamp DATETIME NOT NULL
)`,
// We could create the following index by adding a UNIQUE
// constraint to the url field. But creating it explicitly
// allows us to specify the index name (which makes unit
// tests more robust).
`CREATE UNIQUE INDEX unique_feed_url ON feeds(url)`,
`CREATE TABLE items (
feedid INTEGER NOT NULL REFERENCES feeds(id),
title TEXT NOT NULL,
desc TEXT,
pubdate DATETIME NOT NULL,
url TEXT NOT NULL,
filesize INTEGER DEFAULT 0,
duration INTEGER DEFAULT 0,
guid TEXT NOT NULL,
unplayed BOOLEAN DEFAULT 0,
timestamp DATETIME NOT NULL
)`,
// TODO: Do we need to rely on the GUID given that an item
// is uniquely identified by its URL?
`CREATE UNIQUE INDEX unique_item_guid ON items(feedid, guid)`,
}
tx, err := db.Begin()
if err != nil {
return err
}
for _, q := range sql {
if _, err := tx.Exec(q); err != nil {
return rollback(tx, err)
}
}
return tx.Commit()
}
type syncResult struct {
ID int64
URL string
Title string
Items int
Err error
}
func addFeed(db *sql.DB, url string) (*syncResult, error) {
feed, err := fetchAndParse(url)
if err != nil {
return nil, errors.New("could not fetch feed: " + err.Error())
}
id, err := saveFeed(db, feed, time.Now())
if err != nil {
return nil, errors.New("could not save feed: " + err.Error())
}
return &syncResult{
ID: id,
URL: feed.URL,
Title: feed.Title,
Items: len(feed.Items),
}, nil
}
func addFeedMultiple(db *sql.DB, urls []string) []*syncResult {
feeds, errs := fetchAndParseMultiple(urls, defaults.MaxWorkers)
i := 0
now := time.Now()
results := make([]*syncResult, 0, len(urls))
for url, feed := range feeds {
i++
fmt.Printf("Adding %d of %d feeds\r", i, len(feeds))
id, err := saveFeed(db, feed, now)
if err != nil {
errs[url] = err
continue
}
results = append(results, &syncResult{
ID: id,
URL: feed.URL,
Title: feed.Title,
Items: len(feed.Items),
})
}
for url, err := range errs {
results = append(results, &syncResult{
URL: url,
Err: err,
})
}
return results
}
func removeFeed(db *sql.DB, id int64) error {
tx, err := db.Begin()
if err != nil {
return err
}
err = deleteItems(tx, id)
if err != nil {
return rollback(tx, err)
}
err = deleteFeed(tx, id)
if err != nil {
return rollback(tx, err)
}
return tx.Commit()
}
func syncOne(db *sql.DB, id int64) (*syncResult, error) {
infos, err := loadSyncInfo(db, id)
if err != nil {
return nil, err
}
if n := len(infos); n != 1 {
if n == 0 {
return nil, errNoFeedFound
}
return nil, errors.New("could not retrieve feed")
}
info := &infos[0]
feed, err := fetchAndParse(info.URL)
if err != nil {
return nil, err
}
items, err := syncItems(db, info, feed.Items)
if err != nil {
return nil, err
}
err = syncFeed(db, info, feed)
if err != nil {
// Swallow this error
log.Println(err)
}
return &syncResult{
ID: info.ID,
URL: info.URL,
Title: info.Title,
Items: items,
}, nil
}
func syncAll(db *sql.DB) ([]*syncResult, error) {
infos, err := loadSyncInfo(db, 0)
if err != nil {
return nil, err
}
if len(infos) == 0 {
return nil, errors.New("no feeds to sync")
}
urls := make([]string, len(infos))
mURLToInfo := make(map[string]*syncInfo, len(infos))
results := make([]*syncResult, 0, len(infos))
for i := range infos {
urls[i] = infos[i].URL
mURLToInfo[infos[i].URL] = &infos[i]
}
feeds, errs := fetchAndParseMultiple(urls, defaults.MaxWorkers)
i := 0
for url, feed := range feeds {
i++
fmt.Printf("Syncing %d of %d feeds\r", i, len(feeds))
info := mURLToInfo[url]
if err := syncFeed(db, info, feed); err != nil {
// Swallow this error.
log.Println(err)
}
items, err := syncItems(db, info, feed.Items)
if err != nil {
errs[url] = err
continue
}
results = append(results, &syncResult{
ID: info.ID,
URL: info.URL,
Title: info.Title,
Items: items,
})
}
for url, err := range errs {
info := mURLToInfo[url]
results = append(results, &syncResult{
ID: info.ID,
URL: info.URL,
Title: info.Title,
Err: err,
})
}
return results, nil
}
type listFeedOptions struct {
SortBy sortFeedsBy
SortOrder sortOrder
Limit uint
Title string
Author string
ShowDesc bool
}
func listFeeds(db *sql.DB, w io.Writer, tmpl *template.Template, opts listFeedOptions) error {
feeds, err := loadFeedViews(db, opts)
if err != nil {
return err
}
return tmpl.Execute(w, map[string]interface{}{
"Feeds": feeds,
"ShowDesc": opts.ShowDesc,
})
}
type feedView struct {
Title string
Author string
Desc string
Items int64
UnplayedItems int64
LastPubdate time.Time
}
func loadFeedViews(db *sql.DB, opts listFeedOptions) ([]feedView, error) {
// ORDER BY clause
var order string
switch opts.SortOrder {
case sortOrderAsc:
order = "ASC"
case sortOrderDesc:
order = "DESC"
case sortOrderDefault:
switch opts.SortBy {
case sortFeedsByTitle:
order = "ASC"
default:
order = "DESC"
}
}
secondaryFields := "f.title COLLATE NOCASE ASC, f.ROWID DESC"
var sortFields string
switch opts.SortBy {
case sortFeedsByPubdate:
sortFields = fmt.Sprintf("max_pubdate %s, %s", order, secondaryFields)
case sortFeedsByTitle:
sortFields = fmt.Sprintf("f.title COLLATE NOCASE %s, f.ROWID DESC", order)
case sortFeedsByItemCount:
sortFields = fmt.Sprintf("item_count %s, %s", order, secondaryFields)
case sortFeedsByUnplayedCount:
sortFields = fmt.Sprintf("unplayed_count %s, %s", order, secondaryFields)
case sortFeedsByTimestamp:
sortFields = fmt.Sprintf("f.timestamp %s, %s", order, secondaryFields)
default:
return nil, errors.New("unsupported sort order")
}
// WHERE clause
var params []interface{}
var conditions []string
params = append(params, time.Time{}.Unix()) // Default value for NULL pubdates
if title := opts.Title; title != "" {
conditions = append(conditions, "f.title LIKE ?")
params = append(params, "%"+title+"%")
}
if author := opts.Author; author != "" {
conditions = append(conditions, "f.author LIKE ?")
params = append(params, "%"+author+"%")
}
whereClause := "1=1"
if len(conditions) > 0 {
whereClause = strings.Join(conditions, " AND ")
}
// LIMIT
limit := int(opts.Limit)
if limit <= 0 {
limit = -1
}
// Build and execute query
// A few points about this query.
//
// 1. The join between the feeds and items tables is an
// outer join, just in case we have any feeds with zero
// items. I haven't seen any empty feeds in the wild but
// the RSS spec allows them and there's no reason not to
// support them.
//
// 2. COUNT(i.ROWID) gives the number of items for each
// feed. ROWID is a convenient value to count because it
// can never be NULL. Using COUNT(*) would not work as
// that would include the feed row in the count, reporting
// 1 instead of 0 for feeds with no items.
//
// 3. i.unplayed is a BOOLEAN field with values 1 (True)
// or 0 (False). So SUM(i.unplayed) gives the number of
// unplayed items for each feed. SUM will return NULL
// if a feed has zero items (hence the IFNULL).
//
// 4. i.pubdate is a DATETIME field with integer values
// representing the Unix time in seconds. MAX(i.pubdate)
// gives the date of the most recent feed item. Like SUM,
// MAX will return NULL if a feed has zero items (hence
// the IFNULL).
//
// TODO: Can we rewrite this query so that MAX(i.pubdate)
// can be scanned directly into a date?
q :=
`SELECT
f.title,
f.author,
f.desc,
COUNT(i.ROWID) AS item_count,
IFNULL(SUM(i.unplayed), 0) AS unplayed_count,
IFNULL(MAX(i.pubdate), ?) AS max_pubdate
FROM
feeds f
LEFT OUTER JOIN
items i ON i.feedid = f.id
WHERE
` + whereClause + `
GROUP BY
f.id
ORDER BY
` + sortFields + `
LIMIT ?`
var rows []struct {
Title string
Author string
Desc string
Items int64
UnplayedItems int64
LastPubdateUnix int64
}
err := queryRows(&rows, db, q, append(params, limit)...)
if err != nil {
return nil, err
}
feeds := make([]feedView, len(rows))
for i, r := range rows {
feeds[i] = feedView{
Title: r.Title,
Author: r.Author,
Desc: r.Desc,
Items: r.Items,
UnplayedItems: r.UnplayedItems,
LastPubdate: time.Unix(r.LastPubdateUnix, 0),
}
}
return feeds, nil
}
func defaultFeedTemplate(now time.Time) *template.Template {
layout := `
{{- with len .Feeds -}}
Showing {{.}} feed{{if ne . 1}}s{{end}}:
{{range $index, $feed := $.Feeds}}{{println -}}
{{$index | plus 1 | printf "%*d" 7}}. {{$feed.Title}}
{{$feed.Author}}
{{if $.ShowDesc}}{{range $feed.Desc | lines 70}}{{.}}
{{end}}{{end -}}
{{$feed.Items}} item{{if ne $feed.Items 1}}s{{end}}{{with $feed.UnplayedItems}}, {{.}} unplayed{{end}}{{with $feed.LastPubdate}}{{if not .IsZero}} (updated {{. | ago}}){{end}}{{end}}
{{end -}}
{{else -}}
No feeds found
{{end}}`
funcs := template.FuncMap{
"lines": formatLines,
"ago": func(t time.Time) string {
return timeRelativeTo(now, t)
},
"plus": func(i, j int) int {
return i + j
},
}
return template.Must(
template.New("feed").Funcs(funcs).Parse(layout),
)
}
type listItemAction uint
const (
actionNone listItemAction = iota
actionPlay
actionRun
actionMark
actionUnmark
)
type listItemOptions struct {
SortBy sortItemsBy
SortOrder sortOrder
Limit uint
Unplayed bool
StartDate time.Time
Title string
FeedID int64
ShowDesc bool
Action listItemAction
Use string
}
func listItems(db *sql.DB, w io.Writer, tmpl *template.Template, opts listItemOptions) error {
app := opts.Use
if opts.Action == actionPlay || opts.Action == actionRun {
_, err := parseCommand(app)
if err != nil {
return err
}
}
items, err := loadItemViews(db, opts)
if err != nil {
return err
}
t := tmpl
var urls []string
if opts.Action != actionNone {
t, err = addCallbackTemplate(t, "prompt", listItemCallback(opts.Action, app, items, &urls))
if err != nil {
return err
}
}
err = t.Execute(w, map[string]interface{}{
"Items": items,
"SingleFeed": opts.FeedID != 0,
"ShowDesc": opts.ShowDesc,
"ShowPrompt": opts.Action != actionNone,
})
if err != nil {
switch {
case strings.Contains(err.Error(), errListItemsDone.Error()):
case strings.Contains(err.Error(), errListItemsAborted.Error()):
return nil
default:
return err
}
}
if opts.Action == actionNone || len(urls) == 0 {
return nil
}
if opts.Action == actionMark {
return updatePlayedStatus(db, true, urls...)
}
if opts.Action == actionUnmark {
return updatePlayedStatus(db, false, urls...)
}
for _, url := range urls {
cmd, err := parseCommand(app, url)
if err != nil {
return err
}
if err := cmd.Run(); err != nil {
return err
}
if opts.Action == actionPlay {
if err := updatePlayedStatus(db, true, url); err != nil {
return err
}
}
}
return nil
}
var errListItemsDone = errors.New("__list_items_exit_loop__")
var errListItemsAborted = errors.New("__list_items_exit_function__")
func listItemCallback(action listItemAction, app string, items []itemView, urls *[]string) func(i int) error {
var prompt string
switch action {
case actionPlay:
prompt = "Play"
case actionMark:
prompt = "Mark as played"
case actionUnmark:
prompt = "Unmark as played"
case actionRun:
_, name := filepath.Split(strings.Fields(app)[0])
prompt = "Run " + name
default:
return func(int) error {
return nil
}
}
prompt += "? Yes, No, All, Done, Quit"
return func(i int) error {
c, err := ask(prompt, "ynadq")
if err != nil {
return err
}
switch c {
case 'y':
*urls = append(*urls, items[i].url)
case 'a':
for i := range items[i:] {
*urls = append(*urls, items[i].url)
}
return errListItemsDone
case 'd':
return errListItemsDone
case 'q':
return errListItemsAborted
}
return nil
}
}
func addCallbackTemplate(t *template.Template, name string, callback func(int) error) (*template.Template, error) {
layout := "{{with __callback__ .}}{{end}}"
funcs := template.FuncMap{
"__callback__": func(i int) (bool, error) {
return false, callback(i)
},
}
t, err := t.Clone()
if err != nil {
return nil, err
}
_, err = t.New(name).Funcs(funcs).Parse(layout)
if err != nil {
return nil, err
}
return t, nil
}
type itemView struct {
Title string
Desc string
Duration int64
Pubdate time.Time
IsUnplayed bool
FeedTitle string
feedID int64
url string
}
func loadItemViews(db *sql.DB, opts listItemOptions) ([]itemView, error) {
// ORDER BY clause
var order string
switch opts.SortOrder {
case sortOrderAsc:
order = "ASC"
case sortOrderDesc:
order = "DESC"
case sortOrderDefault:
switch opts.SortBy {
case sortItemsByTitle, sortItemsByFeed:
order = "ASC"
default:
order = "DESC"
}
}
secondaryFields := "i.pubdate DESC, i.ROWID DESC"
var sortFields string
switch opts.SortBy {
case sortItemsByPubdate:
sortFields = fmt.Sprintf("i.pubdate %s, i.ROWID DESC", order)
case sortItemsByTitle:
sortFields = fmt.Sprintf("i.title COLLATE NOCASE %s, %s", order, secondaryFields)
case sortItemsByFeed:
sortFields = fmt.Sprintf("f.title COLLATE NOCASE %s, %s", order, secondaryFields)
case sortItemsByDuration:
sortFields = fmt.Sprintf("i.duration %s, %s", order, secondaryFields)
case sortItemsByTimestamp:
sortFields = fmt.Sprintf("i.timestamp %s, %s", order, secondaryFields)
default:
return nil, errors.New("unsupported sort type")
}
// WHERE clause
var params []interface{}
var conditions []string
if opts.Unplayed {
conditions = append(conditions, "i.unplayed = 1")
}
if t := opts.StartDate; !t.IsZero() {
conditions = append(conditions, "i.pubdate >= ?")
params = append(params, t.Unix())
}
if title := opts.Title; title != "" {
conditions = append(conditions, "i.title LIKE ?")
params = append(params, "%"+title+"%")
}
if id := opts.FeedID; id != 0 {
conditions = append(conditions, "i.feedid = ?")
params = append(params, id)
}
whereClause := "1=1"
if len(conditions) > 0 {
whereClause = strings.Join(conditions, " AND ")
}
// Limit
limit := int(opts.Limit)
if limit <= 0 {
limit = -1
}
// Build and execute query
q :=
`SELECT
i.title,
i.desc,
i.url,
i.duration,
i.pubdate,
i.unplayed,
f.id,
f.title
FROM
items i
INNER JOIN
feeds f ON f.id = i.feedid
WHERE
` + whereClause + `
ORDER BY
` + sortFields + `
LIMIT ?`
var rows []struct {
Title string
Desc string
URL string
Duration int64
Pubdate time.Time
Unplayed bool
FeedID int64
FeedTitle string
}
err := queryRows(&rows, db, q, append(params, limit)...)
if err != nil {
return nil, err
}
items := make([]itemView, len(rows))
for i, r := range rows {
items[i] = itemView{
Title: r.Title,
FeedTitle: r.FeedTitle,
Desc: r.Desc,
Duration: r.Duration,
Pubdate: r.Pubdate,
IsUnplayed: r.Unplayed,
url: r.URL,
feedID: r.FeedID,
}
}
return items, nil
}
func defaultItemTemplate(now time.Time) *template.Template {
layout := `
{{- with len .Items -}}
Showing {{.}} item{{if ne . 1}}s{{end}}:
{{range $index, $item := $.Items}}{{println -}}
{{if $item.IsUnplayed}}{{$index | plus 1 | printf "* %d" | printf "%*s" 7}}{{else}}{{$index | plus 1 | printf "%*d" 7}}{{end}}. {{$item.Title}}
{{if $.SingleFeed}}Released{{else}}From {{$item.FeedTitle}},{{end}} {{if $item.Pubdate.IsZero}}Date unknown{{else}}{{$item.Pubdate.Local | ago}}{{end}}
{{if $.ShowDesc}}{{range $item.Desc | lines 70}}{{.}}
{{end}}{{end -}}
Duration: {{with $item.Duration}}{{. | duration}}{{else}}Unknown{{end}}{{if $.ShowPrompt}}
{{template "prompt" $index}}{{else}}{{println}}{{end -}}
{{end -}}
{{else -}}
No items found
{{end}}`
funcs := template.FuncMap{
"lines": formatLines,
"ago": func(t time.Time) string {
return timeRelativeTo(now, t)
},
"plus": func(i, j int) int {
return i + j
},
"duration": formatSeconds,
}
return template.Must(
template.New("item").Funcs(funcs).Parse(layout),
)
}
func exportList(db *sql.DB, w io.Writer) error {
q := `SELECT url FROM feeds ORDER BY url COLLATE NOCASE`
var rows []struct {
URL string
}
err := queryRows(&rows, db, q)
if err != nil {
return err
}
if len(rows) == 0 {
return errors.New("no feeds to export")
}
for _, r := range rows {
fmt.Fprintln(w, r.URL)
}
return nil
}
func exportOPML(db *sql.DB, w io.Writer, timestamp time.Time) error {
q := `SELECT type, title, desc, url FROM feeds ORDER BY title COLLATE NOCASE, url COLLATE NOCASE`
var rows []struct {
Type string
Title string
Desc string
URL string
}
err := queryRows(&rows, db, q)
if err != nil {
return err
}
if len(rows) == 0 {
return errors.New("no feeds to export")
}
data := newOPML("Kibner subscriptions")
data.Pubdate = opmltime(timestamp)
data.Entries = make([]*entry, len(rows))
for i, r := range rows {
data.Entries[i] = &entry{
Type: r.Type,
Text: r.Title,
Title: r.Title,
Desc: r.Desc,
URL: r.URL,
}
}
return data.writeTo(w)
}
var errInvalidTarget = errors.New("invalid target")
func loadFeedURL(db *sql.DB, feedID int64, target target) (string, error) {
var url string
var image, link sql.NullString
q := "SELECT url, link, image FROM feeds WHERE id = ?"
err := db.QueryRow(q, feedID).Scan(&url, &link, &image)
if err != nil {
if err == sql.ErrNoRows {
return "", errNoFeedFound
}
return "", err
}
switch target {
case targetFeed:
return url, nil
case targetLink:
return link.String, nil
case targetImage:
return image.String, nil
default:
return "", errInvalidTarget
}
}
func syncItems(db *sql.DB, info *syncInfo, items []*kibner.Item) (int, error) {
var newItems []*kibner.Item
for _, item := range items {
if !info.guids[item.GUID] {
newItems = append(newItems, item)
}
}
if len(newItems) == 0 {
return 0, nil
}
return len(newItems), saveNewItems(db, info.ID, newItems)
}
func syncFeed(db *sql.DB, info *syncInfo, feed *kibner.Feed) error {
if info.URL == feed.URL {
return nil
}
return updateFeed(db, info.ID, map[string]interface{}{
"url": feed.URL,
})
}
type syncInfo struct {
ID int64
Title string
URL string
guids map[string]bool
}
func loadSyncInfo(db *sql.DB, id int64) ([]syncInfo, error) {
infos, err := loadSyncInfoFeeds(db, id)
if err != nil {
return nil, err
}
guids, err := loadSyncInfoGUIDs(db, id)
if err != nil {
return nil, err
}
for i := range infos {
info := &infos[i]
for _, g := range guids[info.ID] {
if info.guids == nil {
info.guids = make(map[string]bool)
}
info.guids[g] = true
}
}
return infos, nil
}
func loadSyncInfoFeeds(db *sql.DB, id int64) ([]syncInfo, error) {
var rows []syncInfo
var params []interface{}
q := "SELECT id, title, url FROM feeds"
if id > 0 {
q += " WHERE id = ?"
params = append(params, id)
}