-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathnotion_dao.go
254 lines (230 loc) · 7.24 KB
/
notion_dao.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
package main
import (
"context"
"fmt"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/jomei/notionapi"
)
type NotionDao struct {
feedDatabaseId notionapi.DatabaseID
contentDatabaseId notionapi.DatabaseID
client *notionapi.Client
}
// ConstructNotionDaoFromEnv given environment variables: NOTION_RSS_KEY,
// NOTION_RSS_CONTENT_DATABASE_ID, NOTION_RSS_FEEDS_DATABASE_ID
func ConstructNotionDaoFromEnv() (*NotionDao, error) {
integrationKey, exists := os.LookupEnv("NOTION_RSS_KEY")
if !exists {
return &NotionDao{}, fmt.Errorf("`NOTION_RSS_KEY` not set")
}
contentDatabaseId, exists := os.LookupEnv("NOTION_RSS_CONTENT_DATABASE_ID")
if !exists {
return &NotionDao{}, fmt.Errorf("`NOTION_RSS_CONTENT_DATABASE_ID` not set")
}
feedDatabaseId, exists := os.LookupEnv("NOTION_RSS_FEEDS_DATABASE_ID")
if !exists {
return &NotionDao{}, fmt.Errorf("`NOTION_RSS_FEEDS_DATABASE_ID` not set")
}
return ConstructNotionDao(feedDatabaseId, contentDatabaseId, integrationKey), nil
}
func ConstructNotionDao(feedDatabaseId string, contentDatabaseId string, integrationKey string) *NotionDao {
return &NotionDao{
feedDatabaseId: notionapi.DatabaseID(feedDatabaseId),
contentDatabaseId: notionapi.DatabaseID(contentDatabaseId),
client: notionapi.NewClient(notionapi.Token(integrationKey)),
}
}
// GetOldUnstarredRSSItems that were created strictly before olderThan and are not starred.
func (dao NotionDao) GetOldUnstarredRSSItems(olderThan time.Time) []notionapi.Page {
resp, err := dao.client.Database.Query(context.TODO(), dao.contentDatabaseId, ¬ionapi.DatabaseQueryRequest{
Filter: (notionapi.AndCompoundFilter)([]notionapi.Filter{
// Use `Created`, not `Published` as to avoid deleting cold-started RSS feeds.
notionapi.PropertyFilter{
Property: "Created",
Date: ¬ionapi.DateFilterCondition{
Before: (*notionapi.Date)(&olderThan),
},
},
notionapi.PropertyFilter{
Property: "Starred",
Checkbox: ¬ionapi.CheckboxFilterCondition{
Equals: false,
DoesNotEqual: true,
},
},
}),
// TODO: pagination
//StartCursor: "",
//PageSize: 0,
})
if err != nil {
fmt.Printf("error occurred in GetOldUnstarredRSSItems. Error: %s\n", err.Error())
return []notionapi.Page{}
}
return resp.Results
}
func (dao NotionDao) GetOldUnstarredRSSItemIds(olderThan time.Time) []notionapi.PageID {
pages := dao.GetOldUnstarredRSSItems(olderThan)
result := make([]notionapi.PageID, len(pages))
for i, page := range pages {
result[i] = notionapi.PageID(page.ID)
}
return result
}
// ArchivePages for a list of pageIds. Will archive each page even if other pages fail.
func (dao *NotionDao) ArchivePages(pageIds []notionapi.PageID) error {
failedCount := 0
for _, p := range pageIds {
_, err := dao.client.Page.Update(
context.TODO(),
p,
¬ionapi.PageUpdateRequest{
Archived: true,
Properties: notionapi.Properties{}, // Must be provided, even if empty
},
)
if err != nil {
fmt.Printf("Failed to archive page: %s. Error: %s\n", p.String(), err.Error())
failedCount++
}
}
if failedCount > 0 {
return fmt.Errorf("failed to archive %d pages", failedCount)
}
return nil
}
// GetEnabledRssFeeds from the Feed Database. Results filtered on property "Enabled"=true
func (dao *NotionDao) GetEnabledRssFeeds() chan *FeedDatabaseItem {
rssFeeds := make(chan *FeedDatabaseItem)
go func(dao *NotionDao, output chan *FeedDatabaseItem) {
defer close(output)
req := ¬ionapi.DatabaseQueryRequest{
Filter: notionapi.PropertyFilter{
Property: "Enabled",
Checkbox: ¬ionapi.CheckboxFilterCondition{
Equals: true,
},
},
}
//TODO: Get multi-page pagination results from resp.HasMore
resp, err := dao.client.Database.Query(context.Background(), dao.feedDatabaseId, req)
if err != nil {
return
}
for _, r := range resp.Results {
feed, err := GetRssFeedFromDatabaseObject(&r)
if err == nil {
rssFeeds <- feed
}
}
}(dao, rssFeeds)
return rssFeeds
}
func GetRssFeedFromDatabaseObject(p *notionapi.Page) (*FeedDatabaseItem, error) {
if p.Properties["Link"] == nil || p.Properties["Title"] == nil {
return &FeedDatabaseItem{}, fmt.Errorf("notion page is expected to have `Link` and `Title` properties. Properties: %s", p.Properties)
}
urlProperty := p.Properties["Link"].(*notionapi.URLProperty).URL
rssUrl, err := url.Parse(urlProperty)
if err != nil {
return &FeedDatabaseItem{}, err
}
nameRichTexts := p.Properties["Title"].(*notionapi.TitleProperty).Title
if len(nameRichTexts) == 0 {
return &FeedDatabaseItem{}, fmt.Errorf("RSS Feed database entry does not have any Title in 'Title' field")
}
return &FeedDatabaseItem{
FeedLink: rssUrl,
Created: p.CreatedTime,
LastModified: p.LastEditedTime,
Name: nameRichTexts[0].PlainText,
}, nil
}
func GetImageUrl(x string) *string {
// Extract the first image src from the document to use as cover
re := regexp.MustCompile(`(?m)<img\b[^>]+?src\s*=\s*['"]?([^\s'"?#>]+)`)
match := re.FindSubmatch([]byte(x))
if match != nil {
v := string(match[1])
if strings.HasPrefix(v, "http") {
return &v
} else {
fmt.Printf("[ERROR]: Invalid image url found in <img> url=%s\n", string(match[1]))
return nil
}
}
return nil
}
// AddRssItem to Notion database as a single new page with Block content. On failure, no retry is attempted.
func (dao NotionDao) AddRssItem(item RssItem) error {
categories := make([]notionapi.Option, len(item.categories))
for i, c := range item.categories {
categories[i] = notionapi.Option{
Name: c,
}
}
var imageProp *notionapi.Image
// TODO: Currently notionapi.URLProperty is not nullable, which is needed
// to use thumbnail properly (i.e. handle the case when no image in RSS item).
//thumbnailProp := ¬ionapi.URLProperty{
// Type: "url",
// URL: ,
//}
image := GetImageUrl(strings.Join(item.content, " "))
if image != nil {
imageProp = ¬ionapi.Image{
Type: "external",
External: ¬ionapi.FileObject{
URL: *image,
},
}
}
_, err := dao.client.Page.Create(context.Background(), ¬ionapi.PageCreateRequest{
Parent: notionapi.Parent{
Type: "database_id",
DatabaseID: dao.contentDatabaseId,
},
Properties: map[string]notionapi.Property{
"Title": notionapi.TitleProperty{
Type: "title",
Title: []notionapi.RichText{{
Type: "text",
Text: notionapi.Text{
Content: item.title,
},
}},
},
"Description": notionapi.RichTextProperty{
Type: "rich_text",
RichText: []notionapi.RichText{{
Type: notionapi.ObjectTypeText,
Text: notionapi.Text{
Content: *item.description,
},
PlainText: *item.description,
},
},
},
"Link": notionapi.URLProperty{
Type: "url",
URL: item.link.String(),
},
"Categories": notionapi.MultiSelectProperty{
MultiSelect: categories,
},
"From": notionapi.SelectProperty{Select: notionapi.Option{Name: item.feedName}},
"Published": notionapi.DateProperty{Date: ¬ionapi.DateObject{Start: (*notionapi.Date)(item.published)}},
},
Children: RssContentToBlocks(item),
Cover: imageProp,
})
return err
}
func RssContentToBlocks(item RssItem) []notionapi.Block {
// TODO: implement when we know RssItem struct better
return []notionapi.Block{}
}