-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
103 lines (85 loc) · 1.94 KB
/
state.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
package feedcrawler
import (
"bytes"
"encoding/json"
"errors"
"io"
"os"
"time"
)
// State is feed's crawling state.
type State struct {
CrawledAt time.Time `json:"crawled_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
// States is a list of State.
type States map[FeedID]*State
// UpdateState updates states by the result.
func (s States) UpdateState(result Result) {
id := result.Subscription.ID()
st, ok := s[id]
if !ok {
st = &State{}
s[id] = st
}
st.CrawledAt = time.Now().Local()
if result.Err == nil && result.Feed != nil {
published := latestFeedTime(result.Feed)
if published != nil {
st.UpdatedAt = published.Local()
}
}
}
// LoadStates loads states from io.Reader.
func LoadStates(r io.Reader) (States, error) {
states := make(States, 0)
var buf bytes.Buffer
n, e := buf.ReadFrom(r)
if e == nil && n == 0 {
return states, nil
}
decoder := json.NewDecoder(&buf)
if err := decoder.Decode(&states); err != nil {
return nil, err
}
return states, nil
}
// LoadStatesFile loads states from JSON file.
func LoadStatesFile(file string) (States, error) {
if file == "" {
return nil, errors.New("Invalid state file path")
}
f, err := os.Open(file)
if err != nil {
if os.IsNotExist(err) {
return make(States, 0), nil
}
return nil, err
}
defer f.Close()
return LoadStates(f)
}
// SaveStates writes current states to io.Writer.
func SaveStates(states States, w io.Writer) error {
buf, err := json.MarshalIndent(states, "", " ")
if err != nil {
return err
}
n, e := w.Write(buf)
if e == nil && n < len(buf) {
err = io.ErrShortWrite
}
return err
}
// SaveStatesFile save current states into JSON file.
func SaveStatesFile(states States, file string) error {
if file == "" {
return errors.New("Invalid state file path")
}
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer f.Close()
return SaveStates(states, f)
}