summaryrefslogtreecommitdiff
path: root/rss.go
blob: a4450543cd243de49beb809ca130cfb32b907a54 (plain)
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
package main

import (
	"fmt"
	"io"
	"log"
	"time"

	"dim13.org/rss"
)

type Feed struct {
	Name  string
	URL   string
	Every time.Duration
}

type News struct {
	Feed
	rss.Item
}

func (n News) String() string {
	s := fmt.Sprintf("%v: %v", n.Name, n.Title)
	if n.Author != "" {
		s += fmt.Sprintf(" (%v) ", n.Author)
	} else {
		s += " - "
	}
	s += fmt.Sprintf("%v", n.Link)
	return s
}

func (f Feed) watch(w io.Writer) {
	ticker := time.NewTicker(f.Every)
	defer ticker.Stop()
	for t := range ticker.C {
		r, err := rss.Fetch(f.URL)
		if err != nil {
			log.Println(f.Name, err)
			return
		}
		last := t.Add(-f.Every)
		for _, i := range r.Channel.Items {
			if i.PubDate.After(last) {
				fmt.Fprint(w, News{f, i})
			}
		}
	}
}

func Watch(w io.Writer, feeds []Feed) {
	for _, feed := range feeds {
		go feed.watch(w)
	}
}