-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
295 lines (254 loc) · 7.56 KB
/
main.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"database/sql"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/feeds"
log "github.com/sirupsen/logrus"
_ "modernc.org/sqlite" // Pure Go SQLite driver
)
type HackerNewsItem struct {
Title string
Link string
CommentsLink string
Points string
CommentCount string
Author string
CreatedAt time.Time
UpdatedAt time.Time
}
func initDB() *sql.DB {
// Get the directory of the executable
exePath, err := os.Executable()
if err != nil {
log.Fatalf("Error getting executable path: %v", err)
}
exeDir := filepath.Dir(exePath)
dbPath := filepath.Join(exeDir, "hackernews.db")
// Open database in the executable's directory
db, err := sql.Open("sqlite", dbPath) // Use "sqlite" driver name
if err != nil {
log.Fatal(err)
}
// Create table if it doesn't exist
createTable := `
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
link TEXT NOT NULL UNIQUE,
comments_link TEXT,
points TEXT,
comment_count TEXT,
author TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`
_, err = db.Exec(createTable)
if err != nil {
log.Fatal(err)
}
return db
}
func fetchHackerNewsItems() []HackerNewsItem {
res, err := http.Get("https://news.ycombinator.com")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
}
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
var items []HackerNewsItem
now := time.Now()
doc.Find(".athing").Each(func(i int, s *goquery.Selection) {
title := s.Find(".titleline > a:first-child").Text()
link, _ := s.Find(".titleline > a:first-child").Attr("href")
// Get the comments link from the subtext row
itemId := s.AttrOr("id", "")
commentsLink := fmt.Sprintf("https://news.ycombinator.com/item?id=%s", itemId)
subtext := s.Next()
points := subtext.Find(".score").Text()
commentCount := subtext.Find("a").Last().Text()
author := subtext.Find(".hnuser").Text()
// Parse the timestamp from the age span's title attribute
updatedAt := now
if ageSpan := subtext.Find(".age"); ageSpan.Length() > 0 {
if timestamp, exists := ageSpan.Attr("title"); exists {
// Parse the Unix timestamp from the title attribute
if unixTime, err := strconv.ParseInt(strings.Split(timestamp, " ")[1], 10, 64); err == nil {
updatedAt = time.Unix(unixTime, 0)
}
}
}
log.WithFields(log.Fields{
"title": title,
"link": link,
"commentsLink": commentsLink,
"points": points,
"comments": commentCount,
"author": author,
"updatedAt": updatedAt,
}).Debug("Found item")
items = append(items, HackerNewsItem{
Title: title,
Link: link,
CommentsLink: commentsLink,
Points: points,
CommentCount: commentCount,
Author: author,
CreatedAt: updatedAt,
UpdatedAt: updatedAt,
})
})
return items
}
func updateStoredItems(db *sql.DB, newItems []HackerNewsItem) {
for _, item := range newItems {
result, err := db.Exec(`
INSERT INTO items (title, link, comments_link, points, comment_count, author, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(link) DO UPDATE SET
title = excluded.title,
comments_link = excluded.comments_link,
points = excluded.points,
comment_count = excluded.comment_count,
author = excluded.author,
updated_at = excluded.updated_at`,
item.Title, item.Link, item.CommentsLink, item.Points, item.CommentCount, item.Author, item.CreatedAt, item.UpdatedAt)
if err != nil {
log.WithError(err).WithField("link", item.Link).Error("Error updating item")
continue
}
rowsAffected, _ := result.RowsAffected()
if rowsAffected > 0 {
log.WithField("title", item.Title).Info("Added/Updated item")
}
}
}
func getAllItems(db *sql.DB) []HackerNewsItem {
rows, err := db.Query("SELECT title, link, comments_link, points, comment_count, author, created_at, updated_at FROM items ORDER BY created_at DESC LIMIT 30")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var items []HackerNewsItem
for rows.Next() {
var item HackerNewsItem
err := rows.Scan(&item.Title, &item.Link, &item.CommentsLink, &item.Points, &item.CommentCount, &item.Author, &item.CreatedAt, &item.UpdatedAt)
if err != nil {
log.WithError(err).Error("Error scanning row")
continue
}
items = append(items, item)
}
return items
}
func generateRSSFeed(items []HackerNewsItem) string {
now := time.Now()
feed := &feeds.Feed{
Title: "Hacker News RSS Feed",
Description: "Latest stories from Hacker News",
Link: &feeds.Link{Href: "https://news.ycombinator.com/", Rel: "self", Type: "text/html"},
Id: "tag:news.ycombinator.com,2024:feed",
Created: now,
Updated: now,
}
// idRegex := regexp.MustCompile(`id=(\d+)`)
domainRegex := regexp.MustCompile(`^https?://([^/]+)`)
commentRegex := regexp.MustCompile(`(\d+)`)
for _, item := range items {
// Extract item ID from the comments link
// itemID := ""
// if matches := idRegex.FindStringSubmatch(item.CommentsLink); len(matches) > 1 {
// itemID = matches[1]
// }
// Extract domain from the article link
domain := ""
if matches := domainRegex.FindStringSubmatch(item.Link); len(matches) > 1 {
domain = matches[1]
}
// Format points (remove "points" suffix if present)
points := strings.TrimSuffix(item.Points, " points")
points = strings.TrimSuffix(points, " point")
// Format comment count - just extract the digits portion
comments := item.CommentCount
if matches := commentRegex.FindStringSubmatch(item.CommentCount); len(matches) > 1 {
comments = matches[1]
}
feed.Items = append(feed.Items, &feeds.Item{
Title: item.Title,
Link: &feeds.Link{Href: item.CommentsLink, Rel: "alternate", Type: "text/html"},
Id: item.CommentsLink,
Author: &feeds.Author{
Name: item.Author,
},
Description: fmt.Sprintf(`<p>
<strong>%s points</strong> |
<strong>%s comments</strong><br/>
Source: %s<br/>
<a href="%s">View Comments</a> |
<a href="%s">Read Article</a>
</p>`,
points,
comments,
domain,
item.CommentsLink,
item.Link),
Updated: item.CreatedAt,
})
}
rss, err := feed.ToAtom()
if err != nil {
log.Fatal(err)
}
return rss
}
func updateAndSaveFeed(outDir string) {
db := initDB()
defer db.Close()
// Fetch current front page items
newItems := fetchHackerNewsItems()
// Update database with new items
updateStoredItems(db, newItems)
// Get all items from database
allItems := getAllItems(db)
// Ensure output directory exists
err := os.MkdirAll(outDir, 0755)
if err != nil {
log.Fatalf("Error creating output directory: %v", err)
}
// Generate and save the feed
filename := filepath.Join(outDir, "hntop30.xml")
rss := generateRSSFeed(allItems)
err = os.WriteFile(filename, []byte(rss), 0644)
if err != nil {
log.Fatalf("Error writing RSS feed to file: %v", err)
}
log.WithFields(log.Fields{
"count": len(allItems),
"filename": filename,
}).Info("RSS feed saved")
}
func main() {
// Configure log
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
log.SetLevel(log.WarnLevel) // Only show warnings and above by default
// Define and parse the outdir flag
outDir := flag.String("outdir", ".", "directory where the RSS feed file will be saved")
flag.Parse()
updateAndSaveFeed(*outDir)
}