-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.go
More file actions
84 lines (73 loc) · 1.91 KB
/
scraper.go
File metadata and controls
84 lines (73 loc) · 1.91 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
package main
import (
"context"
"database/sql"
"log"
"strings"
"sync"
"time"
"github.com/Ayushlm10/rssAgg/internal/database"
"github.com/google/uuid"
)
func scraper(concurrency int, timeBetweenRequests time.Duration, db *database.Queries) {
log.Printf("Scraping %d feeds, at interval %v", concurrency, timeBetweenRequests)
ticker := time.NewTicker(timeBetweenRequests)
for ; ; <-ticker.C {
feeds, err := db.GetNextFeedToFetch(context.Background(), int32(concurrency))
if err != nil {
log.Println(err)
continue
}
wg := &sync.WaitGroup{}
for _, feed := range feeds {
wg.Add(1)
go scrapeFeed(feed, db, wg)
}
wg.Wait()
}
}
func scrapeFeed(feed database.Feed, db *database.Queries, wg *sync.WaitGroup) {
defer wg.Done()
//fetch feed
rssFeed, err := urlToRssFeed(feed.Url)
if err != nil {
log.Println("Error fetchign feed:", err)
return
}
_, err = db.MarkFeedAsFetched(context.Background(), feed.ID)
if err != nil {
log.Println("Error Fetching feed:", err)
return
}
for _, item := range rssFeed.Channel.Item {
//description is a null string.
description := sql.NullString{}
if item.Description != "" {
description.String = item.Description
description.Valid = true
}
// parse the date as it is a string
pubDate, err := time.Parse(time.RFC1123Z, item.PubDate)
if err != nil {
log.Printf("Cant't parse date: %v", err)
continue
}
_, err = db.CreatePost(context.Background(), database.CreatePostParams{
ID: uuid.New(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Title: item.Title,
Url: item.Link,
FeedID: feed.ID,
PublishedAt: pubDate,
Description: description,
})
if err != nil {
if strings.Contains(err.Error(), "duplicate key") {
continue
}
log.Printf("failed to create post: %v\n", err)
}
}
log.Printf("Found %s collected , %v posts found", feed.Name, len(rssFeed.Channel.Item))
}