Просмотр исходного кода

add `fetch-background` command to fetch feeds periodically

(this is old code, not absolutely sure what it does...)
Lucas Stadler лет назад: 11
Родитель
Сommit
55c1f8b5ef
1 измененных файлов с 76 добавлено и 1 удалено
  1. 76 1
      go/feeds/feeds.go

+ 76 - 1
go/feeds/feeds.go

@ -2,6 +2,7 @@ package main
2 2
3 3
import (
4 4
	"bufio"
5
	"encoding/json"
5 6
	"errors"
6 7
	"flag"
7 8
	"fmt"
@ -9,6 +10,7 @@ import (
9 10
	"net/url"
10 11
	"os"
11 12
	"strings"
13
	"time"
12 14
13 15
	"code.google.com/p/cascadia"
14 16
	"code.google.com/p/go.net/html"
@ -28,7 +30,7 @@ import (
28 30
// - support json and edn output (and transit?)
29 31
// test (see feeds_test.go)
30 32
31
var commands = []string{"fetch-all", "fetch-one", "help"}
33
var commands = []string{"fetch-all", "fetch-one", "fetch-background", "help"}
32 34
33 35
func main() {
34 36
	if len(os.Args) == 1 {
@ -49,6 +51,14 @@ func main() {
49 51
		}
50 52
51 53
		FetchOne(flag.Args()[0])
54
	case "fetch-background":
55
		feeds, err := ReadConfig("config.txt")
56
		if err != nil {
57
			fmt.Println(err)
58
			os.Exit(1)
59
		}
60
61
		FetchBackground(feeds)
52 62
	case "help":
53 63
		printUsage()
54 64
		flag.PrintDefaults()
@ -109,6 +119,71 @@ func FetchAll() {
109 119
	}
110 120
}
111 121
122
type FeedResult struct {
123
	*feed.Feed
124
	URL string
125
}
126
127
func FetchBackground(us *[]string) {
128
	canFetchCh := make(chan bool, 10)
129
	for i := 0; i < 10; i++ {
130
		canFetchCh <- true
131
	}
132
133
	resultCh := make(chan FeedResult, 10)
134
	for _, u := range *us {
135
		go Fetcher(u, canFetchCh, resultCh)
136
	}
137
138
	feeds := make(map[string](*feed.Feed))
139
	go func() {
140
		for {
141
			fmt.Printf("storing %d feeds\n", len(feeds))
142
			StoreFeeds("feeds.json", feeds)
143
			time.Sleep(1 * time.Minute)
144
		}
145
	}()
146
147
	for {
148
		f := <-resultCh
149
		canFetchCh <- true
150
151
		if f.Feed == nil {
152
			fmt.Printf("%s: empty feed\n", f.URL)
153
		} else {
154
			fmt.Printf("%s - %d entries\n", f.UpdateURL, len(f.Items))
155
			feeds[f.URL] = f.Feed
156
		}
157
	}
158
}
159
160
func StoreFeeds(n string, feeds map[string](*feed.Feed)) {
161
	f, err := os.Create(n)
162
	defer f.Close()
163
164
	if err != nil {
165
		fmt.Println(err)
166
		return
167
	}
168
169
	enc := json.NewEncoder(f)
170
	if err = enc.Encode(feeds); err != nil {
171
		fmt.Println(err)
172
	}
173
}
174
175
func Fetcher(u string, canFetchCh chan bool, resultCh chan FeedResult) {
176
	for {
177
		<- canFetchCh
178
179
		fmt.Printf("fetching %s\n", u)
180
		f, _ := Fetch(u)
181
		resultCh <- FeedResult{f, u}
182
183
		time.Sleep(1 * time.Minute)
184
	}
185
}
186
112 187
func Fetch(fn string) (*feed.Feed, error) {
113 188
	fu, err := GetFeedUrl(fn)
114 189
	if err != nil {