-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_agg.go
More file actions
88 lines (76 loc) · 2.01 KB
/
handler_agg.go
File metadata and controls
88 lines (76 loc) · 2.01 KB
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
package main
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
"time"
"gator/internal/database"
"github.com/google/uuid"
)
func handlerAgg(s *state, cmd command) error {
if len(cmd.Args) < 1 || len(cmd.Args) > 2 {
return fmt.Errorf("usage: %v <time_between_reqs>", cmd.Name)
}
timeBetweenRequests, err := time.ParseDuration(cmd.Args[0])
if err != nil {
return fmt.Errorf("invalid duration: %w", err)
}
log.Printf("Collecting feeds every %s...", timeBetweenRequests)
ticker := time.NewTicker(timeBetweenRequests)
for ; ; <-ticker.C {
scrapeFeeds(s)
}
}
func scrapeFeeds(s *state) {
feed, err := s.db.GetNextFeedToFetch(context.Background())
if err != nil {
log.Println("Couldn't get next feeds to fetch", err)
return
}
log.Println("Found a feed to fetch!")
scrapeFeed(s.db, feed)
}
func scrapeFeed(db *database.Queries, feed database.Feed) {
_, err := db.MarkFeedFetched(context.Background(), feed.ID)
if err != nil {
log.Printf("Couldn't mark feed %s fetched: %v", feed.Name, err)
return
}
feedData, err := fetchFeed(context.Background(), feed.Url)
if err != nil {
log.Printf("Couldn't collect feed %s: %v", feed.Name, err)
return
}
for _, item := range feedData.Channel.Item {
publishedAt := sql.NullTime{}
if t, err := time.Parse(time.RFC1123Z, item.PubDate); err == nil {
publishedAt = sql.NullTime{
Time: t,
Valid: true,
}
}
_, err = db.CreatePost(context.Background(), database.CreatePostParams{
ID: uuid.New(),
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
FeedID: feed.ID,
Title: item.Title,
Description: sql.NullString{
String: item.Description,
Valid: true,
},
Url: item.Link,
PublishedAt: publishedAt,
})
if err != nil {
if strings.Contains(err.Error(), "duplicate key value violates unique constraint") {
continue
}
log.Printf("Couldn't create post: %v", err)
continue
}
}
log.Printf("Feed %s collected, %v posts found", feed.Name, len(feedData.Channel.Item))
}