-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
325 lines (281 loc) · 7.18 KB
/
db.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package main
import (
"database/sql"
"time"
)
type Podcast struct {
Id int
UserId int
Text string `xml:"text,attr"`
XMLUrl string `xml:"xmlUrl,attr"`
HTMLUrl string `xml:"htmlUrl,attr"`
ImageUrl string `xml:"imageUrl,attr"`
Title string
Description string
Language string
}
type Episode struct {
Id int
PodcastName string
PodcastId int
URL string
Title string
Description string
PubDate time.Time
Link string
ImageURL string
FileName string
Downloaded int
}
type DB struct {
database *sql.DB
}
var localDB *DB
func init() {
localDB = NewDB()
}
func CloseDB() {
localDB.database.Close()
}
func NewDB() *DB {
sqliteDB, err := sql.Open("sqlite3", AppConfig.DatabaseFile)
if err != nil {
log.Sugar().Fatalf("Could not open SQLite database: %v", err)
}
InitializeDatabase(sqliteDB)
return &DB{
database: sqliteDB,
}
}
func InitializeDatabase(db *sql.DB) error {
createPodcastTableQuery := `
CREATE TABLE IF NOT EXISTS podcasts(
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
name TEXT NOT NULL,
xml_url TEXT NOT NULL,
html_url TEXT,
image_url TEXT,
title TEXT,
description TEXT,
language TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, name),
FOREIGN KEY(user_id) REFERENCES users(id)
)
`
_, err := db.Exec(createPodcastTableQuery)
if err != nil {
return err
}
createEpisodesTableQuery := `
CREATE TABLE IF NOT EXISTS episodes(
id INTEGER PRIMARY KEY AUTOINCREMENT,
podcast_id INTEGER,
url TEXT NOT NULL,
file_name TEXT,
title TEXT,
description TEXT,
pub_date DATETIME,
link TEXT,
image_url TEXT,
downloaded INTEGER NOT NULL DEFAULT 0,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME,
FOREIGN KEY(podcast_id) REFERENCES podcasts(id)
)
`
_, err = db.Exec(createEpisodesTableQuery)
if err != nil {
return err
}
createEpisodesArchiveTableQuery := `
CREATE TABLE IF NOT EXISTS archived_episodes(
id INTEGER PRIMARY KEY AUTOINCREMENT,
original_episode_id INTEGER,
podcast_id INTEGER,
url TEXT NOT NULL,
downloaded INTEGER NOT NULL,
timestamp DATETIME,
FOREIGN KEY(original_episode_id) REFERENCES episodes(id)
)
`
_, err = db.Exec(createEpisodesArchiveTableQuery)
if err != nil {
return err
}
createUsersTableQuery := `
CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
`
_, err = db.Exec(createUsersTableQuery)
return err
}
func (db *DB) InsertPodcastsToDB(userID int, podcasts []Podcast) error {
for _, podcast := range podcasts {
// Check if the podcast already exists
var existingID sql.NullInt64
err := db.database.QueryRow("SELECT id FROM podcasts WHERE user_id = ? AND name = ?", userID, podcast.Text).Scan(&existingID)
if err != nil && err != sql.ErrNoRows {
return err
}
if err == sql.ErrNoRows { // Insert new podcast
// Find the maximum id
var maxID sql.NullInt64
err = db.database.QueryRow("SELECT MAX(id) FROM podcasts").Scan(&maxID)
if err != nil {
return err
}
nextID := 1
if maxID.Valid {
nextID = int(maxID.Int64) + 1
}
_, err = db.database.Exec(`
INSERT INTO podcasts(id, user_id, name, xml_url, html_url, image_url)
VALUES (?, ?, ?, ?, ?, ?)`,
nextID,
userID,
podcast.Text,
podcast.XMLUrl,
podcast.HTMLUrl,
podcast.ImageUrl,
)
} else { // Update existing podcast
_, err = db.database.Exec(`
UPDATE podcasts SET xml_url = ?, html_url = ?, image_url = ? WHERE id = ?`,
podcast.XMLUrl,
podcast.HTMLUrl,
podcast.ImageUrl,
existingID.Int64,
)
}
if err != nil {
return err
}
}
return nil
}
func (db *DB) GetPodcastsFromDB(userID int) ([]Podcast, error) {
rows, err := db.database.Query("SELECT id, xml_url FROM podcasts WHERE user_id = ?", userID)
if err != nil {
return nil, err
}
defer rows.Close()
podcasts := make([]Podcast, 0)
for rows.Next() {
var p Podcast
if err := rows.Scan(&p.Id, &p.XMLUrl); err != nil {
return nil, err
}
podcasts = append(podcasts, p)
}
return podcasts, nil
}
func (db *DB) InsertEpisodesToDB(podcastId int, episodes []Item) (int, error) {
newEpisodesCount := 0 // Counter for new episodes
for _, item := range episodes {
// Check if the episode already exists
var existingEpisode struct {
ID int
URL string
Downloaded int
}
err := db.database.QueryRow("SELECT id, url, downloaded FROM episodes WHERE podcast_id = ? AND url = ?", podcastId, item.Enclosure.Url).Scan(&existingEpisode.ID, &existingEpisode.URL, &existingEpisode.Downloaded)
if err != nil && err != sql.ErrNoRows {
return newEpisodesCount, err
}
if err == sql.ErrNoRows { // Insert new episode
_, err = db.database.Exec(`
INSERT INTO episodes(podcast_id, url, title, description, pub_date, link, image_url)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
podcastId,
item.Enclosure.Url,
item.Title,
item.Description,
item.PubDate,
item.Link,
item.Image.Url,
)
if err == nil {
newEpisodesCount++ // Increment the counter if a new episode was inserted
}
} else if existingEpisode.URL != item.Enclosure.Url {
// URL has changed, update existing episode
// Archive the existing episode
_, err = db.database.Exec(`
INSERT INTO archived_episodes(original_episode_id, podcast_id, url, downloaded, timestamp)
VALUES (?, ?, ?, ?, ?)`,
existingEpisode.ID,
podcastId,
existingEpisode.URL,
existingEpisode.Downloaded,
time.Now(),
)
if err != nil {
return newEpisodesCount, err
}
// Update the current episode
_, err = db.database.Exec(`
UPDATE episodes SET url = ?, title = ?, description = ?, pub_date = ?, link = ?, image_url = ? WHERE id = ?`,
item.Enclosure.Url,
item.Title,
item.Description,
item.PubDate,
item.Link,
item.Image.Url,
existingEpisode.ID,
)
}
if err != nil {
return newEpisodesCount, err
}
}
return newEpisodesCount, nil
}
func (db *DB) MarkEpisodeAsDownloaded(episodeId int, fileName string) error {
_, err := db.database.Exec(`
UPDATE episodes
SET downloaded = 1, file_name = ?
WHERE id = ?`,
fileName,
episodeId,
)
log.Sugar().Debugf("*** id: %d file name: %s", episodeId, fileName)
return err
}
func (db *DB) GetNewEpisodesFromDB() ([]Episode, error) {
rows, err := db.database.Query(`
SELECT e.id, p.name as podcast_name, e.url
FROM episodes e
JOIN podcasts p ON e.podcast_id = p.id
WHERE e.downloaded = 0
`)
if err != nil {
return nil, err
}
defer rows.Close()
episodes := make([]Episode, 0)
for rows.Next() {
var episode Episode
if err := rows.Scan(&episode.Id, &episode.PodcastName, &episode.URL); err != nil {
return nil, err
}
episodes = append(episodes, episode)
}
return episodes, nil
}
func (db *DB) UpdatePodcastInfo(podcastId int, title string, description string, language string) error {
_, err := db.database.Exec(`
UPDATE podcasts SET title = ?, description = ?, language = ? WHERE id = ?`,
title,
description,
language,
podcastId,
)
return err
}