Repository navigation
Expand file tree
/
Copy pathdb_store.py
More file actions
854 lines (805 loc) · 30.4 KB
/
Copy pathdb_store.py
File metadata and controls
854 lines (805 loc) · 30.4 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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
import datetime
import sqlite3
from pathlib import Path
from typing import Any, Dict, List, Optional
DEFAULT_UPDATE_FREQUENCY = 1 # days
DEFAULT_FREE_ONLY = False
_DEFAULT_CATEGORIES = [
("main", 1),
]
class ChapterDatabase:
"""SQLite-backed store for links and scraped entries."""
def __init__(self, db_path: Path):
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._ensure_schema()
def _connect(self):
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA synchronous = NORMAL")
return conn
def _ensure_schema(self):
with self._connect() as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY,
url TEXT UNIQUE NOT NULL,
name TEXT,
category TEXT NOT NULL,
update_frequency INTEGER NOT NULL DEFAULT 1,
free_only INTEGER NOT NULL DEFAULT 0,
last_saved TEXT NOT NULL DEFAULT 'N/A',
added_at TEXT NOT NULL DEFAULT 'N/A',
favorite INTEGER NOT NULL DEFAULT 0,
last_attempt TEXT,
last_error TEXT
)
"""
)
self._ensure_links_columns(conn)
self._ensure_scraped_entries_table(conn)
self._ensure_categories_table(conn)
self._ensure_settings_table(conn)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_links_category ON links(category)")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_scraped_entries_link ON scraped_entries(link_id)"
)
def _ensure_scraped_entries_table(self, conn):
conn.execute(
"""
CREATE TABLE IF NOT EXISTS scraped_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
link_id INTEGER,
last_found TEXT,
last_found_url TEXT,
timestamp TEXT,
retrieved_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY(link_id) REFERENCES links(id) ON DELETE CASCADE
)
"""
)
columns = [row["name"] for row in conn.execute(
"PRAGMA table_info(scraped_entries)").fetchall()]
if "last_found_url" not in columns:
conn.execute("ALTER TABLE scraped_entries ADD COLUMN last_found_url TEXT")
if "id" not in columns:
conn.execute(
"ALTER TABLE scraped_entries RENAME TO scraped_entries_old")
conn.execute(
"""
CREATE TABLE scraped_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
link_id INTEGER,
last_found TEXT,
timestamp TEXT,
retrieved_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY(link_id) REFERENCES links(id) ON DELETE CASCADE
)
"""
)
conn.execute(
"""
INSERT INTO scraped_entries (link_id, last_found, timestamp, retrieved_at)
SELECT link_id, last_found, timestamp, COALESCE(retrieved_at, datetime('now'))
FROM scraped_entries_old
"""
)
conn.execute("DROP TABLE scraped_entries_old")
def _ensure_categories_table(self, conn):
conn.execute(
"""
CREATE TABLE IF NOT EXISTS categories (
name TEXT PRIMARY KEY,
update_interval_hours INTEGER NOT NULL DEFAULT 1,
last_checked TEXT,
display_name TEXT,
include_in_nav INTEGER NOT NULL DEFAULT 1
)
"""
)
self._ensure_category_columns(conn)
self._seed_categories(conn)
def _ensure_settings_table(self, conn):
conn.execute(
"""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
"""
)
# Seed default settings if they don't exist
defaults = {
"password_protected": "0",
"password_hash": "",
"share_local": "0",
"port": "555",
"start_on_startup": "0"
}
for key, val in defaults.items():
conn.execute(
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
(key, val)
)
def _ensure_category_columns(self, conn):
columns = {
row["name"]: row for row in conn.execute("PRAGMA table_info(categories)").fetchall()
}
if "display_name" not in columns:
conn.execute("ALTER TABLE categories ADD COLUMN display_name TEXT")
if "include_in_nav" not in columns:
conn.execute(
"ALTER TABLE categories ADD COLUMN include_in_nav INTEGER NOT NULL DEFAULT 1"
)
if "sort_order" not in columns:
conn.execute(
"ALTER TABLE categories ADD COLUMN sort_order INTEGER")
rows = conn.execute(
"SELECT name, display_name FROM categories").fetchall()
for row in rows:
current = (row["display_name"] or "").strip()
fallback = (row["name"][:1] or "M").upper()
if current and current != fallback:
continue
conn.execute(
"UPDATE categories SET display_name = ? WHERE name = ?",
(self._default_display_name(row["name"]), row["name"]),
)
conn.execute(
"""
UPDATE categories
SET include_in_nav = 1
WHERE include_in_nav IS NULL
"""
)
self._ensure_category_sort_orders(conn)
def _ensure_category_sort_orders(self, conn):
rows = conn.execute(
"""
SELECT name, sort_order
FROM categories
ORDER BY sort_order IS NULL,
sort_order,
CASE WHEN name = 'main' THEN 0 ELSE 1 END,
name
"""
).fetchall()
needs_update = any(row["sort_order"] is None for row in rows)
if not needs_update:
return
for index, row in enumerate(rows):
conn.execute(
"UPDATE categories SET sort_order = ? WHERE name = ?",
(index, row["name"]),
)
def _get_next_sort_value(self, conn) -> int:
row = conn.execute(
"SELECT COALESCE(MAX(sort_order), -1) AS max_order FROM categories"
).fetchone()
max_value = row["max_order"] if row and row["max_order"] is not None else -1
return max_value + 1
def _seed_categories(self, conn):
existing = {
row["name"] for row in conn.execute("SELECT name FROM categories").fetchall()
}
for name, hours in _DEFAULT_CATEGORIES:
if name not in existing:
conn.execute(
"""
INSERT INTO categories (
name,
update_interval_hours,
display_name,
include_in_nav,
sort_order
) VALUES (?, ?, ?, 1, ?)
""",
(
name,
hours,
self._default_display_name(name),
self._get_next_sort_value(conn),
),
)
def _ensure_links_columns(self, conn):
columns = [row["name"] for row in conn.execute(
"PRAGMA table_info(links)").fetchall()]
needed = {"added_at", "favorite", "last_attempt", "last_error", "last_saved_url"}
missing = needed - set(columns)
for col in missing:
if col == "last_attempt":
conn.execute("ALTER TABLE links ADD COLUMN last_attempt TEXT")
elif col == "last_error":
conn.execute("ALTER TABLE links ADD COLUMN last_error TEXT")
elif col == "added_at":
conn.execute(
"ALTER TABLE links ADD COLUMN added_at TEXT NOT NULL DEFAULT 'N/A'")
elif col == "favorite":
conn.execute(
"ALTER TABLE links ADD COLUMN favorite INTEGER NOT NULL DEFAULT 0")
elif col == "last_saved_url":
conn.execute("ALTER TABLE links ADD COLUMN last_saved_url TEXT")
@staticmethod
def _normalize_frequency(value):
try:
freq = float(value)
rounded = int(freq) if freq.is_integer() else int(freq) + 1
return max(1, rounded)
except (TypeError, ValueError):
return DEFAULT_UPDATE_FREQUENCY
@staticmethod
def _to_flag(value):
return 1 if bool(value) else 0
def _default_display_name(self, name: str) -> str:
if not name:
return "Main"
normalized = (name or "").strip()
if not normalized:
return "Main"
if normalized.lower() == "main":
return "Main"
human = normalized.replace("_", " ").replace("-", " ").strip()
return human.title() or "Main"
def _normalize_category(self, value: str) -> str:
return (value or "").strip().lower()
def _sanitize_interval(self, value: Any) -> int:
try:
return max(1, int(value))
except (TypeError, ValueError):
return 1
def _get_link_id(self, url: str) -> Optional[int]:
with self._connect() as conn:
row = conn.execute(
"SELECT id FROM links WHERE url = ?", (url,)).fetchone()
return row["id"] if row else None
def get_links(self, category: str) -> List[Dict]:
with self._connect() as conn:
rows = conn.execute(
"SELECT url, name, update_frequency, free_only, favorite FROM links WHERE category = ? ORDER BY id",
(category,),
).fetchall()
return [
{
"url": row["url"],
"name": row["name"],
"update_frequency": row["update_frequency"],
"free_only": bool(row["free_only"]),
"favorite": bool(row["favorite"]),
}
for row in rows
]
def add_link(
self,
name: str,
url: str,
category: str,
update_frequency: int,
free_only: bool,
favorite: bool = False,
):
freq = self._normalize_frequency(update_frequency)
flag = self._to_flag(free_only)
added_at = datetime.datetime.now().isoformat()
favorite_flag = self._to_flag(favorite)
with self._connect() as conn:
conn.execute(
"""
INSERT INTO links (url, name, category, update_frequency, free_only, added_at, favorite)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(url) DO UPDATE SET
name=excluded.name,
category=excluded.category,
update_frequency=excluded.update_frequency,
free_only=excluded.free_only
""",
(url, name, category, freq, flag, added_at, favorite_flag),
)
def update_link(
self,
original_url: str,
new_url: str,
name: str,
update_frequency: int,
free_only: bool,
category: Optional[str] = None,
):
freq = self._normalize_frequency(update_frequency)
flag = self._to_flag(free_only)
updates = [
("url = ?", new_url),
("name = ?", name),
("update_frequency = ?", freq),
("free_only = ?", flag),
]
if category:
updates.append(("category = ?", category))
set_clause = ", ".join(clause for clause, _ in updates)
params = [value for _, value in updates]
params.append(original_url)
with self._connect() as conn:
conn.execute(
f"""
UPDATE links
SET {set_clause}
WHERE url = ?
""",
params,
)
def remove_link(self, url: str):
with self._connect() as conn:
conn.execute("DELETE FROM links WHERE url = ?", (url,))
def get_scraped_data(self, category: str) -> Dict[str, Dict]:
with self._connect() as conn:
rows = conn.execute(
"""
SELECT
l.url,
l.name,
l.update_frequency,
l.free_only,
l.last_saved,
l.last_saved_url,
l.last_attempt,
l.last_error,
l.added_at,
l.favorite,
(
SELECT last_found
FROM scraped_entries se2
WHERE se2.link_id = l.id
ORDER BY se2.id DESC
LIMIT 1
) AS last_found,
(
SELECT last_found_url
FROM scraped_entries se2
WHERE se2.link_id = l.id
ORDER BY se2.id DESC
LIMIT 1
) AS last_found_url,
(
SELECT timestamp
FROM scraped_entries se2
WHERE se2.link_id = l.id
ORDER BY se2.id DESC
LIMIT 1
) AS timestamp
FROM links l
WHERE l.category = ?
""",
(category,),
).fetchall()
result = {}
for row in rows:
result[row["url"]] = {
"name": row["name"],
"update_frequency": row["update_frequency"],
"free_only": bool(row["free_only"]),
"last_saved": row["last_saved"],
"last_saved_url": row["last_saved_url"],
"last_attempt": row["last_attempt"],
"last_error": row["last_error"],
"added_at": row["added_at"],
"favorite": bool(row["favorite"]),
"last_found": row["last_found"] or "No data",
"last_found_url": row["last_found_url"],
"timestamp": row["timestamp"] or datetime.datetime.now().strftime("%Y/%m/%d"),
}
return result
def get_link_history(self, url: str) -> Optional[Dict[str, Any]]:
with self._connect() as conn:
link = conn.execute(
"""
SELECT id, url, name, last_saved, last_saved_url, last_attempt, added_at, update_frequency, free_only
FROM links
WHERE url = ?
""",
(url,),
).fetchone()
if not link:
return None
entries = conn.execute(
"""
SELECT id, last_found, last_found_url, timestamp, retrieved_at
FROM scraped_entries
WHERE link_id = ?
ORDER BY id DESC
""",
(link["id"],),
).fetchall()
latest_id = entries[0]["id"] if entries else None
return {
"url": link["url"],
"name": link["name"],
"last_saved": link["last_saved"],
"last_saved_url": link["last_saved_url"],
"last_attempt": link["last_attempt"],
"added_at": link["added_at"],
"update_frequency": link["update_frequency"],
"free_only": bool(link["free_only"]),
"history": [
{
"entry_id": row["id"],
"last_found": row["last_found"],
"last_found_url": row["last_found_url"],
"timestamp": row["timestamp"],
"retrieved_at": row["retrieved_at"],
"is_latest": row["id"] == latest_id,
}
for row in entries
],
}
def get_history_entry(self, url: str, entry_id: int) -> Optional[Dict[str, Any]]:
link_id = self._get_link_id(url)
if not link_id:
return None
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, last_found, last_found_url
FROM scraped_entries
WHERE link_id = ? AND id = ?
""",
(link_id, entry_id),
).fetchone()
return dict(row) if row else None
def delete_history_entry(self, url: str, entry_id: int) -> bool:
link_id = self._get_link_id(url)
if not link_id:
return False
with self._connect() as conn:
latest = conn.execute(
"""
SELECT id
FROM scraped_entries
WHERE link_id = ?
ORDER BY id DESC
LIMIT 1
""",
(link_id,),
).fetchone()
if latest and latest["id"] == entry_id:
raise ValueError("Cannot delete the latest history entry")
result = conn.execute(
"""
DELETE FROM scraped_entries
WHERE link_id = ? AND id = ?
""",
(link_id, entry_id),
)
return result.rowcount > 0
def update_scraped_entry(
self,
url: str,
last_found: str,
timestamp: str,
retrieved_at: Optional[str] = None,
last_found_url: Optional[str] = None,
):
link_id = self._get_link_id(url)
if not link_id:
return
retrieved_at = retrieved_at or datetime.datetime.now().isoformat()
with self._connect() as conn:
existing = conn.execute(
"SELECT last_found, timestamp, last_found_url FROM scraped_entries WHERE link_id = ? ORDER BY id DESC LIMIT 1",
(link_id,),
).fetchone()
if (
existing
and existing["last_found"] == last_found
and existing["timestamp"] == timestamp
and existing["last_found_url"] == last_found_url
):
return
conn.execute(
"""
INSERT INTO scraped_entries (link_id, last_found, last_found_url, timestamp, retrieved_at)
VALUES (?, ?, ?, ?, ?)
""",
(link_id, last_found, last_found_url, timestamp, retrieved_at),
)
def record_failures(self, failures: Dict[str, Dict]):
if not failures:
return
with self._connect() as conn:
for url, info in failures.items():
now = datetime.datetime.now().isoformat()
conn.execute(
"""
UPDATE links
SET last_attempt = ?, last_error = ?
WHERE url = ?
""",
(now, info.get("error"), url),
)
def record_success(self, url: str, when: Optional[str] = None):
when = when or datetime.datetime.now().isoformat()
with self._connect() as conn:
conn.execute(
"""
UPDATE links
SET last_attempt = ?, last_error = NULL
WHERE url = ?
""",
(when, url),
)
def mark_saved(self, url: str):
with self._connect() as conn:
conn.execute(
"""
UPDATE links
SET last_saved = (
SELECT IFNULL(last_found, 'N/A')
FROM scraped_entries
WHERE link_id = links.id
ORDER BY id DESC
LIMIT 1
),
last_saved_url = (
SELECT last_found_url
FROM scraped_entries
WHERE link_id = links.id
ORDER BY id DESC
LIMIT 1
)
WHERE url = ?
""",
(url,),
)
def set_last_saved(self, url: str, value: str, chapter_url: Optional[str] = None):
with self._connect() as conn:
conn.execute(
"UPDATE links SET last_saved = ?, last_saved_url = ? WHERE url = ?",
(value or "N/A", chapter_url, url),
)
def update_link_metadata(
self,
url: str,
name: Optional[str] = None,
free_only: Optional[bool] = None,
favorite: Optional[bool] = None,
):
updates = []
params = []
if name is not None:
updates.append("name = ?")
params.append(name)
if free_only is not None:
updates.append("free_only = ?")
params.append(self._to_flag(free_only))
if favorite is not None:
updates.append("favorite = ?")
params.append(self._to_flag(favorite))
if not updates:
return
params.append(url)
with self._connect() as conn:
conn.execute(
f"UPDATE links SET {', '.join(updates)} WHERE url = ?", tuple(
params)
)
def merge_scraped(self, entries: Dict[str, Dict]):
for url, entry in entries.items():
if not entry.get("last_found"):
continue
if entry.get("name"):
self.update_link_metadata(url, name=entry["name"])
if "free_only" in entry:
self.update_link_metadata(url, free_only=entry["free_only"])
self.update_scraped_entry(
url,
entry["last_found"],
entry["timestamp"],
last_found_url=entry.get("last_found_url"),
)
self.record_success(url, entry.get("retrieved_at"))
def get_categories(self) -> List[Dict[str, Any]]:
with self._connect() as conn:
rows = conn.execute(
"""
SELECT name,
update_interval_hours,
last_checked,
display_name,
include_in_nav,
sort_order
FROM categories
ORDER BY sort_order ASC,
CASE name WHEN 'main' THEN 0 ELSE 1 END,
name
"""
).fetchall()
return [
{
"name": row["name"],
"update_interval_hours": row["update_interval_hours"],
"last_checked": row["last_checked"],
"display_name": row["display_name"] or self._default_display_name(row["name"]),
"include_in_nav": bool(row["include_in_nav"]),
"sort_order": row["sort_order"],
}
for row in rows
]
def get_category(self, name: str) -> Optional[Dict[str, Any]]:
with self._connect() as conn:
row = conn.execute(
"""
SELECT name, update_interval_hours, last_checked, display_name, include_in_nav
FROM categories
WHERE name = ?
""",
(name,),
).fetchone()
if not row:
return None
return {
"name": row["name"],
"update_interval_hours": row["update_interval_hours"],
"last_checked": row["last_checked"],
"display_name": row["display_name"] or self._default_display_name(row["name"]),
"include_in_nav": bool(row["include_in_nav"]),
}
def get_category_names(self) -> List[str]:
return [cat["name"] for cat in self.get_categories()]
def set_category_last_checked(self, name: str, timestamp: str):
with self._connect() as conn:
conn.execute(
"UPDATE categories SET last_checked = ? WHERE name = ?",
(timestamp, name),
)
def get_category_unsaved_counts(self) -> Dict[str, int]:
with self._connect() as conn:
rows = conn.execute(
"""
SELECT
category,
SUM(
CASE
WHEN latest_last_found IS NOT NULL
AND latest_last_found <> IFNULL(last_saved, '')
THEN 1
ELSE 0
END
) AS unsaved
FROM (
SELECT
l.category AS category,
l.last_saved AS last_saved,
(
SELECT last_found
FROM scraped_entries se
WHERE se.link_id = l.id
ORDER BY se.id DESC
LIMIT 1
) AS latest_last_found
FROM links l
) data
GROUP BY category
"""
).fetchall()
return {row["category"]: row["unsaved"] or 0 for row in rows}
def create_category(
self,
name: str,
update_interval_hours: int = 1,
display_name: Optional[str] = None,
include_in_nav: bool = True,
) -> Dict[str, Any]:
normalized = self._normalize_category(name)
if not normalized:
raise ValueError("Category name is required")
display = (display_name or "").strip(
) or self._default_display_name(normalized)
interval = self._sanitize_interval(update_interval_hours or 1)
with self._connect() as conn:
conn.execute(
"""
INSERT INTO categories (name, update_interval_hours, display_name, include_in_nav, sort_order)
VALUES (?, ?, ?, ?, ?)
""",
(
normalized,
interval,
display,
self._to_flag(include_in_nav),
self._get_next_sort_value(conn),
),
)
return self.get_category(normalized) or {}
def update_category_entry(
self,
name: str,
new_name: Optional[str] = None,
update_interval_hours: Optional[int] = None,
display_name: Optional[str] = None,
include_in_nav: Optional[bool] = None,
) -> Optional[Dict[str, Any]]:
current = self.get_category(name)
if not current:
return None
updates = []
params: List[Any] = []
normalized_new_name = self._normalize_category(
new_name) if new_name else None
if normalized_new_name and normalized_new_name != name:
updates.append("name = ?")
params.append(normalized_new_name)
if update_interval_hours is not None:
updates.append("update_interval_hours = ?")
params.append(self._sanitize_interval(update_interval_hours))
if display_name is not None:
base_name = normalized_new_name or name
cleaned = (display_name or "").strip(
) or self._default_display_name(base_name)
updates.append("display_name = ?")
params.append(cleaned)
if include_in_nav is not None:
updates.append("include_in_nav = ?")
params.append(self._to_flag(include_in_nav))
if not updates:
return current
with self._connect() as conn:
conn.execute(
f"UPDATE categories SET {', '.join(updates)} WHERE name = ?",
(*params, name),
)
if normalized_new_name and normalized_new_name != name:
conn.execute(
"UPDATE links SET category = ? WHERE category = ?",
(normalized_new_name, name),
)
target_name = normalized_new_name or name
return self.get_category(target_name)
def delete_category(self, name: str) -> bool:
normalized = self._normalize_category(name)
if normalized == "main":
raise ValueError("Main category cannot be removed")
with self._connect() as conn:
conn.execute("DELETE FROM links WHERE category = ?", (normalized,))
result = conn.execute(
"DELETE FROM categories WHERE name = ?",
(normalized,),
)
return result.rowcount > 0
def reorder_categories(self, ordered_names: List[str]) -> List[Dict[str, Any]]:
current = self.get_categories()
existing_names = [cat["name"] for cat in current]
existing_set = set(existing_names)
order_map: Dict[str, int] = {}
index = 0
for name in ordered_names:
normalized = self._normalize_category(name)
if (
not normalized
or normalized not in existing_set
or normalized in order_map
):
continue
order_map[normalized] = index
index += 1
for name in existing_names:
if name not in order_map:
order_map[name] = index
index += 1
with self._connect() as conn:
for name, position in order_map.items():
conn.execute(
"UPDATE categories SET sort_order = ? WHERE name = ?",
(position, name),
)
return self.get_categories()
def get_settings(self) -> Dict[str, str]:
with self._connect() as conn:
rows = conn.execute("SELECT key, value FROM settings").fetchall()
return {row["key"]: row["value"] for row in rows}
def update_setting(self, key: str, value: str):
with self._connect() as conn:
conn.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
(key, str(value))
)