forked from indes/flowerss-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.go
117 lines (98 loc) · 2.3 KB
/
source.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
package model
import (
"fmt"
"sort"
"github.com/SlyMarbo/rss"
"github.com/jinzhu/gorm"
"github.com/nerdneilsfield/flowerss-bot/internal/config"
"github.com/nerdneilsfield/flowerss-bot/internal/fetch"
)
type Source struct {
ID uint `gorm:"primary_key;AUTO_INCREMENT"`
Link string
Title string
ErrorCount uint
Content []Content
EditTime
}
func (s *Source) appendContents(items []*rss.Item) error {
for _, item := range items {
c, _ := getContentByFeedItem(s, item)
s.Content = append(s.Content, c)
}
// 开启task更新
s.ErrorCount = 0
db.Save(&s)
return nil
}
func FindOrNewSourceByUrl(url string) (*Source, error) {
var source Source
if err := db.Where("link=?", url).Find(&source).Error; err != nil {
if err == gorm.ErrRecordNotFound {
source.Link = url
// parsing task
feed, err := rss.FetchByFunc(fetch.FetchFunc(httpClient), url)
if err != nil {
return nil, fmt.Errorf("Feed 抓取错误 %v", err)
}
source.Title = feed.Title
// 避免task更新
source.ErrorCount = config.ErrorThreshold + 1
// Get contents and insert
items := feed.Items
db.Create(&source)
go source.appendContents(items)
return &source, nil
}
return nil, err
}
return &source, nil
}
func GetSources() (sources []*Source) {
db.Find(&sources)
return sources
}
func GetSubscribedNormalSources() []*Source {
var subscribedSources []*Source
sources := GetSources()
for _, source := range sources {
if source.IsSubscribed() && source.ErrorCount < config.ErrorThreshold {
subscribedSources = append(subscribedSources, source)
}
}
sort.SliceStable(
subscribedSources, func(i, j int) bool {
return subscribedSources[i].ID < subscribedSources[j].ID
},
)
return subscribedSources
}
func (s *Source) IsSubscribed() bool {
var sub Subscribe
db.Where("source_id=?", s.ID).First(&sub)
return sub.SourceID == s.ID
}
func (s *Source) NeedUpdate() bool {
var sub Subscribe
db.Where("source_id=?", s.ID).First(&sub)
sub.WaitTime += config.UpdateInterval
if sub.Interval <= sub.WaitTime {
sub.WaitTime = 0
db.Save(&sub)
return true
} else {
db.Save(&sub)
return false
}
}
func (s *Source) AddErrorCount() {
s.ErrorCount++
s.Save()
}
func (s *Source) EraseErrorCount() {
s.ErrorCount = 0
s.Save()
}
func (s *Source) Save() {
db.Save(&s)
}