-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetcher.go
57 lines (51 loc) · 1.37 KB
/
fetcher.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
package fetcher
import (
"context"
"github.com/d-ashesss/news-feed-bot/pkg/model"
"github.com/mmcdole/gofeed"
"log"
)
// Fetcher reads the feed and extracts posts from it.
type Fetcher struct {
subscriptionModel model.SubscriptionModel
}
// New instantiates new Fetcher.
func New(subscriptionModel model.SubscriptionModel) *Fetcher {
return &Fetcher{subscriptionModel: subscriptionModel}
}
func (f Fetcher) GetTitle(ctx context.Context, URL string) (string, error) {
fp := gofeed.NewParser()
feed, err := fp.ParseURLWithContext(URL, ctx)
if err != nil {
return "", err
}
return feed.Title, nil
}
// Fetch reads posts from the feed into subscriptions.
func (f Fetcher) Fetch(ctx context.Context, fd *model.Feed, cat *model.Category) error {
fp := gofeed.NewParser()
feed, err := fp.ParseURLWithContext(fd.URL, ctx)
if err != nil {
return err
}
log.Printf("[fetcher] fetching updates from feed %q [%s] for category %q", feed.Title, feed.Language, cat.Name)
for _, i := range feed.Items {
if i.PublishedParsed == nil {
continue
}
up := model.Update{
Category: cat,
FeedID: i.GUID,
Title: i.Title,
Date: i.PublishedParsed.UTC(),
URL: i.Link,
}
if fd.LastUpdate.After(up.Date) {
continue
}
if err := f.subscriptionModel.AddUpdate(ctx, up); err != nil {
log.Printf("[fetcher] failed to save update: %v", err)
}
}
return nil
}