-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
310 lines (270 loc) · 7.74 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"sync"
"time"
md "github.com/JohannesKaufmann/html-to-markdown"
"github.com/jomei/notionapi"
"github.com/mmcdole/gofeed"
"golang.org/x/time/rate"
"gopkg.in/yaml.v3"
)
// Config holds the application configuration settings.
// It includes RSS feed URLs and Notion API credentials.
type Config struct {
Feeds []string `yaml:"feeds"`
NotionDBID string `yaml:"notion_db_id"`
NotionAPIKey string `yaml:"notion_api_key"`
}
// Validate checks if the Config struct has all required fields populated.
// It returns an error if any required field is missing or empty.
func (c *Config) Validate() error {
// Check if any feeds are specified
if len(c.Feeds) == 0 {
return fmt.Errorf("no feeds specified")
}
// Verify Notion database ID is provided
if c.NotionDBID == "" {
return fmt.Errorf("notion_db_id is required")
}
// Verify Notion API key is provided
if c.NotionAPIKey == "" {
return fmt.Errorf("notion_api_key is required")
}
return nil
}
func main() {
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
}
switch os.Args[1] {
case "help":
printUsage()
case "run":
runCmd := flag.NewFlagSet("run", flag.ExitOnError)
configFile := runCmd.String("config", "feeds.yaml", "path to config file")
if err := runCmd.Parse(os.Args[2:]); err != nil {
log.Fatalf("Error parsing flags: %v", err)
}
runSync(*configFile)
default:
fmt.Printf("Unknown command: %s\n", os.Args[1])
printUsage()
os.Exit(1)
}
}
func printUsage() {
fmt.Printf(`RSS to Notion Sync Tool
Usage:
%s <command> [flags]
Commands:
run Execute the RSS to Notion synchronization
Flags:
-config string Path to config file (default "feeds.yaml")
help Show this help message
Configuration:
Create a YAML config file with the following structure:
feeds:
- https://example.com/feed.xml
notion_db_id: your_notion_database_id
notion_api_key: your_notion_api_key
`, os.Args[0])
}
func runSync(configFile string) {
config, err := loadConfig(configFile)
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
if err := config.Validate(); err != nil {
log.Fatalf("Invalid config: %v", err)
}
notionClient := notionapi.NewClient(notionapi.Token(config.NotionAPIKey))
// 3 requests per second
// https://developers.notion.com/reference/request-limits#rate-limits
limiter := rate.NewLimiter(rate.Every(time.Second/3), 1)
var wg sync.WaitGroup
for _, feedURL := range config.Feeds {
wg.Add(1)
go func(url string) {
defer wg.Done()
processFeed(url, notionClient, config.NotionDBID, limiter)
}(feedURL)
}
wg.Wait()
}
// processFeed fetches RSS feed items from the given URL and adds them to a Notion database.
// It uses a rate limiter to control API requests and checks for existing entries to avoid duplicates.
// Parameters:
// - feedURL: URL of the RSS feed to process
// - client: Notion API client instance
// - dbID: ID of the target Notion database
// - limiter: Rate limiter to control API request frequency
func processFeed(feedURL string, client *notionapi.Client, dbID string, limiter *rate.Limiter) {
log.Printf("Fetching: %s\n", feedURL)
items, err := fetchFeed(feedURL)
if err != nil {
log.Printf("Error fetching feed %s: %v\n", feedURL, err)
return
}
for _, item := range items {
if err := limiter.Wait(context.Background()); err != nil {
log.Printf("Rate limiter error: %v\n", err)
continue
}
exists, err := checkIfExists(client, dbID, item.Link)
if err != nil {
log.Printf("Error checking if item exists: %v\n", err)
continue
}
if exists {
log.Printf("Skipping existing item: %s\n", item.Title)
continue
}
if err := addToNotion(client, dbID, item); err != nil {
log.Printf("Error adding item to Notion: %v\n", err)
continue
}
log.Printf("Added: %s\n", item.Title)
}
}
// loadConfig reads and parses the YAML configuration file.
// Parameters:
// - filename: path to the YAML configuration file
//
// Returns:
// - *Config: pointer to the parsed configuration struct
// - error: any error that occurred during reading or parsing
func loadConfig(filename string) (*Config, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
var config Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, err
}
return &config, nil
}
// fetchFeed retrieves RSS feed items from a given URL.
// Parameters:
// - url: the URL of the RSS feed to fetch
//
// Returns:
// - []*gofeed.Item: slice of feed items
// - error: any error that occurred during fetching
func fetchFeed(url string) ([]*gofeed.Item, error) {
// Create a context with timeout to prevent hanging
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Initialize feed parser with custom user agent
fp := gofeed.NewParser()
fp.UserAgent = "rss-to-notion/1.0 (https://github.com/virtualroot/rss-to-notion)"
// Parse the feed URL with context
feed, err := fp.ParseURLWithContext(url, ctx)
if err != nil {
return nil, err
}
// Return the feed items
return feed.Items, nil
}
// checkIfExists checks if a URL already exists in the Notion database.
// Parameters:
// - client: Notion API client
// - dbID: ID of the Notion database
// - url: URL to check for existence
//
// Returns:
// - bool: true if URL exists, false otherwise
// - error: any error that occurred during the check
func checkIfExists(client *notionapi.Client, dbID string, url string) (bool, error) {
// Create filter to search for URL in database
filter := ¬ionapi.DatabaseQueryRequest{
Filter: notionapi.PropertyFilter{
Property: "URL",
RichText: ¬ionapi.TextFilterCondition{
Equals: url,
},
},
}
// Query the database with the filter
result, err := client.Database.Query(context.Background(), notionapi.DatabaseID(dbID), filter)
if err != nil {
return false, err
}
// Return true if any results found, false otherwise
return len(result.Results) > 0, nil
}
// convertToMarkdown converts HTML content to markdown format.
// Parameters:
// - htmlContent: HTML string to convert
//
// Returns:
// - string: converted markdown text
// - error: any error that occurred during conversion
func convertToMarkdown(htmlContent string) (string, error) {
converter := md.NewConverter("", true, nil)
markdown, err := converter.ConvertString(htmlContent)
if err != nil {
return "", fmt.Errorf("error converting HTML to markdown: %v", err)
}
return markdown, nil
}
func addToNotion(client *notionapi.Client, dbID string, item *gofeed.Item) error {
properties := notionapi.Properties{
"Name": notionapi.TitleProperty{
Title: []notionapi.RichText{
{Text: ¬ionapi.Text{Content: item.Title}},
},
},
"URL": notionapi.URLProperty{
URL: item.Link,
},
}
// Add published date if available
if item.PublishedParsed != nil {
properties["Published"] = notionapi.DateProperty{
Date: ¬ionapi.DateObject{
Start: (*notionapi.Date)(item.PublishedParsed),
},
}
}
markdown, err := convertToMarkdown(item.Content)
if err != nil {
return err
}
content := markdown
var children []notionapi.Block
for len(content) > 0 {
chunk := content
if len(chunk) > 2000 {
chunk = content[:2000]
content = content[2000:]
} else {
content = ""
}
children = append(children, ¬ionapi.ParagraphBlock{
BasicBlock: notionapi.BasicBlock{
Object: "block",
Type: "paragraph",
},
Paragraph: notionapi.Paragraph{
RichText: []notionapi.RichText{
{Text: ¬ionapi.Text{Content: chunk}},
},
},
})
}
_, err = client.Page.Create(context.Background(), ¬ionapi.PageCreateRequest{
Parent: notionapi.Parent{
DatabaseID: notionapi.DatabaseID(dbID),
},
Properties: properties,
Children: children,
})
return err
}