-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.go
83 lines (73 loc) · 2.09 KB
/
scraper.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
package main
import (
"context"
"database/sql"
"log"
"sync"
"time"
"github.com/google/uuid"
"github.com/sandepten/go-rss-aggregator/internal/database"
)
func startScraping(
db *database.Queries, // database connection
concurrency int, // number of goroutines to use
timeBetweenScrapes time.Duration, // time in seconds between scrapes
) {
log.Printf("Starting scraping with %d goroutines and %v seconds between scrapes", concurrency, timeBetweenScrapes)
ticker := time.NewTicker(timeBetweenScrapes)
for ; ; <-ticker.C {
feeds, err := db.GetNextFeedsToFetch(context.Background(), int32(concurrency))
if err != nil {
log.Printf("Error getting feeds to fetch: %v", err)
continue
}
wg := &sync.WaitGroup{}
for _, feed := range feeds {
wg.Add(1)
go func(feed database.Feed) {
defer wg.Done()
_, err := db.MarkFeedAsFetched(context.Background(), feed.ID)
if err != nil {
log.Printf("Error marking feed as fetched: %v", err)
return
}
rssFeed, err := urlToFeed(feed.Url)
if err != nil {
log.Printf("Error fetching feed: %v", err)
return
}
for _, item := range rssFeed.Channel.Item {
description := sql.NullString{}
if item.Description != "" {
description.String = item.Description
description.Valid = true
}
pubAt, err := time.Parse(time.RFC1123Z, item.PubDate)
if err != nil {
log.Printf("Error parsing date: %v", err)
continue
}
_, err = db.CreatePost(context.Background(), database.CreatePostParams{
ID: uuid.New(),
FeedID: feed.ID,
Title: item.Title,
Url: item.Link,
Description: description,
PublishedAt: pubAt,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
})
if err != nil {
if err.Error() == "pq: duplicate key value violates unique constraint \"posts_url_key\"" {
continue
}
log.Printf("Error creating item: %v", err)
continue
}
}
log.Printf("Feed %s collected, %d items", feed.Url, len(rssFeed.Channel.Item))
}(feed)
}
wg.Wait()
}
}