~chrisppy/beagles

ref: 175af2c65fd91aa2084dde988f7dfe536eb760bc beagles/db.go -rw-r--r-- 10.3 KiB
175af2c6Chris Palmer Re-add badge in README 1 year, 10 months ago
                                                                                
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// This file is part of beagles.
//
// Copyright © 2020 Chris Palmer <chris@red-oxide.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"encoding/json"
	"fmt"
	"path/filepath"
	"sort"

	bolt "go.etcd.io/bbolt"
)

const (
	queueTbl = "queue"
	itemTbl  = "item"
	feedTbl  = "feed"
)

// Storage contains the main data needed to run the app.
type Storage struct {
	Feeds Feeds
	Items Items
	Queue Queue
	Path  string
}

func openDB(path string) (*bolt.DB, error) {
	if path == "" {
		return nil, fmt.Errorf("path is empty")
	}

	return bolt.Open(filepath.Clean(path), 0600, nil)
}

// ReadDB will grab all data from the database to use while running the app.
func ReadDB(path string) (*Storage, error) {
	db, err := openDB(path)
	if err != nil {
		return nil, err
	}
	defer db.Close()

	s := &Storage{
		Feeds: make(Feeds),
		Items: make(Items),
		Queue: make(Queue, 0),
		Path:  path,
	}

	if err := db.View(func(tx *bolt.Tx) error {
		pb := tx.Bucket([]byte(feedTbl))
		if pb != nil {
			if err := pb.ForEach(func(k, v []byte) error {
				feed := &Feed{}
				if err := json.Unmarshal(v, feed); err != nil {
					return fmt.Errorf("unable to unmarshal feed: %s", err.Error())
				}
				s.Feeds[string(k)] = feed

				return nil
			}); err != nil {
				return fmt.Errorf("error reading from the feed table: %s", err.Error())
			}
		}

		eb := tx.Bucket([]byte(itemTbl))
		if eb != nil {
			if err := eb.ForEach(func(k, v []byte) error {
				item := &Item{}
				if err := json.Unmarshal(v, item); err != nil {
					return fmt.Errorf("unable to unmarshal item: %s", err.Error())
				}
				s.Items[string(k)] = item

				return nil
			}); err != nil {
				return fmt.Errorf("error reading from the item table: %s", err.Error())
			}
		}

		qb := tx.Bucket([]byte(queueTbl))
		if qb != nil {
			s.Queue = make([]*QueueItem, 0)
			if err := qb.ForEach(func(k, v []byte) error {
				queue := &QueueItem{}
				if err := json.Unmarshal(v, queue); err != nil {
					return fmt.Errorf("unable to unmarshal queueitem: %s", err.Error())
				}

				s.Queue = append(s.Queue, queue)

				return nil
			}); err != nil {
				return fmt.Errorf("error reading from the queue table: %s", err.Error())
			}

			sort.Slice(s.Queue, func(i, j int) bool { return s.Queue[i].Compare(s.Queue[j]) })
		}

		return nil
	}); err != nil {
		return nil, fmt.Errorf("unable to read db: %s", err.Error())
	}

	return s, nil
}

// CreateFeed will collect the rss feed and process through the elements
// and add the relevant data elements to the database
func (s *Storage) CreateFeed(url string) error {
	f, err := parseFeed(url)
	if err != nil {
		return fmt.Errorf("unable to fetch url: %s", err.Error())
	}

	feed := convertFromFeed(f, url)
	if feed == nil {
		return fmt.Errorf("failed getting rss feed for url: %s", url)
	}
	key := feed.UpdateURL

	db, err := openDB(s.Path)
	if err != nil {
		return fmt.Errorf("unable to open db: %s", err.Error())
	}
	defer db.Close()

	for i, it := range f.Items {
		item := convertFromItem(it)
		if item == nil {
			return fmt.Errorf("failure while processing title: %s", item.Title)
		}
		item.FeedURL = key
		itemJSON, err := json.Marshal(item)
		if err != nil {
			return fmt.Errorf("unable to marshal item: %s", err.Error())
		}

		queue := &QueueItem{
			Item:        *item,
			PlaybackPOS: 0,
		}
		queueJSON, err := json.Marshal(queue)
		if err != nil {
			return fmt.Errorf("unable to marshal queue: %s", err.Error())
		}
		s.Queue = append(s.Queue, queue)

		ekey := item.Link
		s.Items[ekey] = item
		feed.Items[i] = ekey
		if err := db.Update(func(tx *bolt.Tx) error {
			eb, err := tx.CreateBucketIfNotExists([]byte(itemTbl))
			if err != nil {
				return fmt.Errorf("error creating item bucket: %s", err.Error())
			}

			if err := eb.Put([]byte(ekey), itemJSON); err != nil {
				return fmt.Errorf("error during item `%s` put: %s", ekey, err.Error())
			}

			qb, err := tx.CreateBucketIfNotExists([]byte(queueTbl))
			if err != nil {
				return fmt.Errorf("error creating queue bucket: %s", err.Error())
			}

			if err := qb.Put([]byte(ekey), queueJSON); err != nil {
				return fmt.Errorf("error during queue put: %s", err.Error())
			}

			return nil
		}); err != nil {
			return fmt.Errorf("unable to add item and queue: %s", err.Error())
		}

	}
	sort.Slice(s.Queue, func(i, j int) bool { return s.Queue[i].Compare(s.Queue[j]) })

	feedJSON, err := json.Marshal(feed)
	if err != nil {
		return fmt.Errorf("unable to marshal feed: %s", err.Error())
	}
	if err := db.Update(func(tx *bolt.Tx) error {
		eb, err := tx.CreateBucketIfNotExists([]byte(feedTbl))
		if err != nil {
			return fmt.Errorf("error creating feed bucket: %s", err.Error())
		}

		if err := eb.Put([]byte(key), feedJSON); err != nil {
			return fmt.Errorf("error during feed put: %s", err.Error())
		}

		return nil
	}); err != nil {
		return fmt.Errorf("unable to add feed: %s", err.Error())
	}
	s.Feeds[key] = feed

	return nil
}

// DeleteFeed will delete the Feed, Items, and relevant items it the queue.
func (s *Storage) DeleteFeed(url string) error {
	if url == "" {
		return fmt.Errorf("url was empty, unable to delete")
	}

	db, err := openDB(s.Path)
	if err != nil {
		return fmt.Errorf("unable to open db: %s", err.Error())
	}
	defer db.Close()

	items := s.Feeds[url].Items
	for _, key := range items {
		// Delete from item database
		if err := db.Update(func(tx *bolt.Tx) error {
			if err := tx.Bucket([]byte(queueTbl)).Delete([]byte(key)); err != nil {
				return fmt.Errorf("error deleting from queue bucket: %s", err.Error())
			}
			if err := tx.Bucket([]byte(itemTbl)).Delete([]byte(key)); err != nil {
				return fmt.Errorf("error deleting from item bucket: %s", err.Error())
			}
			return nil

		}); err != nil {
			return fmt.Errorf("unable to delete queue and item: %s", err.Error())
		}

		// check if queue is affected by the delete
		index := -1
		for i, e := range s.Queue {
			if e.Item.Location == key {
				index = i
				break
			}
		}

		if index > -1 {
			s.Queue = append(s.Queue[:index], s.Queue[index+1:]...)
		}

		delete(s.Items, key)
	}

	if err := db.Update(func(tx *bolt.Tx) error {
		return tx.Bucket([]byte(feedTbl)).Delete([]byte(url))
	}); err != nil {
		return fmt.Errorf("unable to delete feed: %s", err.Error())
	}
	delete(s.Feeds, url)

	sort.Slice(s.Queue, func(i, j int) bool { return s.Queue[i].Compare(s.Queue[j]) })

	return nil
}

// Update will check for rss updates
func (s *Storage) Update() error {
	db, err := openDB(s.Path)
	if err != nil {
		return fmt.Errorf("unable to open db: %s", err.Error())
	}
	defer db.Close()

	for _, f := range s.Feeds {
		updateURL := f.UpdateURL

		items, err := findNewItems(f)
		if err != nil {
			return fmt.Errorf("error finding new items for `%s`: %s", updateURL, err.Error())
		}

		for _, item := range items {
			link := item.Link

			q := &QueueItem{
				Item: *item,
			}
			itemJSON, err := json.Marshal(item)
			if err != nil {
				return fmt.Errorf("unable to marshal item `%s` for `%s`: %s", link, updateURL, err.Error())
			}
			queueJSON, err := json.Marshal(q)
			if err != nil {
				return fmt.Errorf("unable to marshal queue item `%s` for `%s`: %s", link, updateURL, err.Error())
			}

			if err := db.Update(func(tx *bolt.Tx) error {
				// Add to Queue Database
				if err := tx.Bucket([]byte(queueTbl)).Put([]byte(link), queueJSON); err != nil {
					return fmt.Errorf("error putting `%s` into queue bucket for `%s`: %s", link, updateURL, err.Error())
				}

				// Add to Item Database
				if err := tx.Bucket([]byte(itemTbl)).Put([]byte(link), itemJSON); err != nil {
					return fmt.Errorf("error putting `%s` into item bucket for `%s`: %s", link, updateURL, err.Error())
				}

				return nil

			}); err != nil {
				return fmt.Errorf("unable to update queue and item `%s` for `%s`: %s", link, updateURL, err.Error())
			}

			s.Items[link] = item
			s.Queue = append(s.Queue, q)

			s.Feeds[updateURL].Items = append(s.Feeds[updateURL].Items, link)
		}

		if len(items) != 0 {
			feedJSON, err := json.Marshal(s.Feeds[updateURL])
			if err != nil {
				return fmt.Errorf("unable to marshal feed for `%s`: %s", updateURL, err.Error())
			}

			if err := db.Update(func(tx *bolt.Tx) error {
				// Update Feed Database
				if err := tx.Bucket([]byte(feedTbl)).Put([]byte(updateURL), feedJSON); err != nil {
					return fmt.Errorf("error putting into feed bucket for `%s`: %s", updateURL, err.Error())
				}

				return nil

			}); err != nil {
				return fmt.Errorf("unable to update feed for `%s`: %s", updateURL, err.Error())
			}
		}
	}

	sort.Slice(s.Queue, func(i, j int) bool { return s.Queue[i].Compare(s.Queue[j]) })

	return nil
}

// MarkRead wil update the Storage to note the an item has been read,
// remove the item from the list.
func (s *Storage) MarkRead(qitem *QueueItem) error {
	if qitem == nil || qitem.Item.Link == "" {
		return fmt.Errorf("location was empty, unable to mark played")
	}

	db, err := openDB(s.Path)
	if err != nil {
		return fmt.Errorf("unable to open db: %s", err.Error())
	}
	defer db.Close()

	link := qitem.Item.Link
	item := s.Items[link]
	item.Read = true

	index := -1
	for i, e := range s.Queue {
		if e.Item.Link == link {
			index = i
			break
		}
	}

	if index > -1 {
		s.Queue = append(s.Queue[:index], s.Queue[index+1:]...)
	}

	itemJSON, err := json.Marshal(item)
	if err != nil {
		return fmt.Errorf("unable to marshal item: %s", err.Error())
	}

	if err := db.Update(func(tx *bolt.Tx) error {
		// Remove from Queue Database
		if err := tx.Bucket([]byte(queueTbl)).Delete([]byte(link)); err != nil {
			return fmt.Errorf("error deleting from queue bucket: %s", err.Error())
		}

		// Mark read in Item Database
		if err := tx.Bucket([]byte(itemTbl)).Put([]byte(link), itemJSON); err != nil {
			return fmt.Errorf("error putting into item bucket: %s", err.Error())
		}

		return nil

	}); err != nil {
		return fmt.Errorf("item, and queue: %s", err.Error())
	}

	return nil
}