-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpersistence.go
More file actions
163 lines (147 loc) · 4.18 KB
/
persistence.go
File metadata and controls
163 lines (147 loc) · 4.18 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
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
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"os"
"path/filepath"
"strings"
"time"
)
type Article struct {
URL string `gorm:"type:varchar(2048);primaryKey"`
Agent string `gorm:"type:varchar(128)"`
SavedToReadwise bool `gorm:"type:boolean"`
SaveTime string `gorm:"type:varchar(128)"`
ReadwiseResp string `gorm:"type:varchar(1024)"`
// Content string `gorm:"type:varchar"`
ActualURL string
PublishTime time.Time `gorm:"type:datetime"`
CreateTime time.Time `gorm:"type:datetime;autoCreateTime"`
UpdateTime time.Time `gorm:"type:datetime;autoUpdateTime"`
}
var db *gorm.DB
func initDB() {
var err error
db, err = gorm.Open(sqlite.Open("data/readform.db"), &gorm.Config{NamingStrategy: schema.NamingStrategy{
SingularTable: true,
}})
if err != nil {
panic("failed to connect database")
}
err = db.AutoMigrate(&Article{})
if err != nil {
panic(err)
}
}
func addArticle(url string, agent string, actualURL string) error {
var articles []*Article
err := db.Find(&articles, "url = ?", url).Error
if err != nil {
return err
}
if len(articles) == 0 {
// Article does not exist, create a new one
article := Article{
URL: url,
ActualURL: actualURL,
Agent: agent,
}
return db.Create(&article).Error
} else {
// Article exists, update it
return db.Model(&articles[0]).Updates(Article{Agent: agent}).Error
}
}
func markURLAsSaved(url string, agent string, resp string) error {
var article Article
if err := db.First(&article, "url = ?", url).Error; err != nil {
// Article does not exist, create a new one
article = Article{
URL: url,
Agent: agent,
SavedToReadwise: true,
SaveTime: time.Now().Format("2006-01-02 15:04:05"),
ReadwiseResp: resp,
}
return db.Create(&article).Error
} else {
// Article exists, update it
return db.Model(&article).Updates(Article{
SavedToReadwise: true,
SaveTime: time.Now().Format("2006-01-02 15:04:05"),
Agent: agent,
ReadwiseResp: resp,
}).Error
}
}
// findArticle finds article from database. Legacy versions of Readform does not have ActualURL field,
// so hasActualURL=true can filter out items created by legacy version.
func findArticle(urlList []string, onlySaved bool, onlyNotSaved bool, hasActualURL bool) ([]Article, error) {
var articles []Article
tx := db
if urlList != nil {
tx = tx.Where("url IN (?)", urlList)
}
if onlySaved {
tx = tx.Where("saved_to_readwise = ?", true)
}
if onlyNotSaved {
tx = tx.Where("saved_to_readwise = ?", false)
}
if hasActualURL {
tx = tx.Where("actual_url != ''")
}
if err := tx.Find(&articles).Error; err != nil {
return nil, err
}
return articles, nil
}
// filterOldURLs filter out saved URLs, returning unsaved URLs.
func filterOldURLs(urls []string) ([]string, error) {
articles, err := findArticle(urls, true, false, false)
if err != nil {
return nil, fmt.Errorf("findArticle failed: %w", err)
}
existURLs := make(map[string]struct{}, len(articles))
for _, a := range articles {
existURLs[a.URL] = struct{}{}
}
var unsavedURLs []string
for _, url := range urls {
if _, exist := existURLs[url]; !exist {
unsavedURLs = append(unsavedURLs, url)
}
}
unsavedURLs = UniqStringSlice(unsavedURLs)
return unsavedURLs, nil
}
func urlToLocalFilePath(url string) string {
fileName := strings.ReplaceAll(url, "/", "_")
fileName = strings.ReplaceAll(fileName, ":", "")
filePath := "data/html/" + fileName + ".html"
return filePath
}
// saveHTMLToLocalFile saves URL content to local file.
func saveHTMLToLocalFile(url, htmlContent string) error {
filePath := urlToLocalFilePath(url)
dir := filepath.Dir(filePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("creating directory failed: %w", err)
}
err := os.WriteFile(filePath, []byte(htmlContent), 0644)
if err != nil {
return fmt.Errorf("WriteFile failed: %w", err)
}
return nil
}
// readLocalHTMLFile gets URL content from local file.
func readLocalHTMLFile(url string) (string, error) {
filePath := urlToLocalFilePath(url)
data, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
return string(data), nil
}