-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
1984 lines (1738 loc) · 75.2 KB
/
database.py
File metadata and controls
1984 lines (1738 loc) · 75.2 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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Database Manager Module
Provides database operations for the audiobook player application.
"""
import os
import sqlite3
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Callable
def init_database(db_file: Path, log_func: Callable[[str], None] = print):
"""
Initialize the database - create tables and indexes.
Called from scanner.py during library scanning.
Args:
db_file: Path to the database file
log_func: Function for logging output (default is print)
"""
with sqlite3.connect(db_file) as conn:
c = conn.cursor()
c.execute("PRAGMA foreign_keys = ON")
# Audiobooks table
c.execute("""
CREATE TABLE IF NOT EXISTS audiobooks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT UNIQUE NOT NULL,
parent_path TEXT,
name TEXT NOT NULL,
author TEXT,
title TEXT,
narrator TEXT,
tag_author TEXT,
tag_title TEXT,
tag_narrator TEXT,
tag_year TEXT,
cover_path TEXT,
file_count INTEGER DEFAULT 0,
duration REAL DEFAULT 0,
listened_duration REAL DEFAULT 0,
is_folder INTEGER NOT NULL,
current_file_index INTEGER DEFAULT 0,
current_position REAL DEFAULT 0,
playback_speed REAL DEFAULT 1.0,
progress_percent INTEGER DEFAULT 0,
is_started INTEGER DEFAULT 0,
is_completed INTEGER DEFAULT 0,
is_available INTEGER DEFAULT 1,
use_id3_tags INTEGER DEFAULT 1,
is_expanded INTEGER DEFAULT 0,
state_hash TEXT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_favorite INTEGER DEFAULT 0,
is_merged INTEGER DEFAULT 0,
total_size INTEGER DEFAULT 0
)
""")
# Audiobook files table
c.execute("""
CREATE TABLE IF NOT EXISTS audiobook_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
audiobook_id INTEGER NOT NULL,
file_path TEXT NOT NULL,
file_name TEXT,
track_number INTEGER,
duration REAL DEFAULT 0,
start_offset REAL DEFAULT 0,
tag_title TEXT,
tag_artist TEXT,
tag_album TEXT,
tag_genre TEXT,
tag_comment TEXT,
FOREIGN KEY(audiobook_id) REFERENCES audiobooks(id)
ON DELETE CASCADE
)
""")
# Tags table
c.execute("""
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
color TEXT
)
""")
# Audiobooks-Tags Link Table
c.execute("""
CREATE TABLE IF NOT EXISTS audiobook_tags (
audiobook_id INTEGER,
tag_id INTEGER,
PRIMARY KEY (audiobook_id, tag_id),
FOREIGN KEY (audiobook_id) REFERENCES audiobooks(id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
)
""")
# Bookmarks table
c.execute("""
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
audiobook_id INTEGER NOT NULL,
file_name TEXT NOT NULL,
time_position REAL NOT NULL,
title TEXT,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(audiobook_id) REFERENCES audiobooks(id)
ON DELETE CASCADE
)
""")
# Indexes
c.execute("CREATE INDEX IF NOT EXISTS idx_parent_path ON audiobooks(parent_path)")
c.execute("CREATE INDEX IF NOT EXISTS idx_is_folder ON audiobooks(is_folder)")
c.execute("CREATE INDEX IF NOT EXISTS idx_is_started ON audiobooks(is_started)")
c.execute("CREATE INDEX IF NOT EXISTS idx_is_completed ON audiobooks(is_completed)")
c.execute("CREATE INDEX IF NOT EXISTS idx_audiobook_id ON audiobook_files(audiobook_id)")
c.execute("CREATE INDEX IF NOT EXISTS idx_bookmarks_audiobook_id ON bookmarks(audiobook_id)")
# Migration: add is_expanded column if it doesn't exist
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN is_expanded INTEGER DEFAULT 0")
if log_func:
log_func("scanner.db_added_expanded")
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add state_hash column if it doesn't exist
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN state_hash TEXT")
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add start_offset column to audiobook_files if it doesn't exist
try:
c.execute("ALTER TABLE audiobook_files ADD COLUMN start_offset REAL DEFAULT 0")
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add technical info columns
new_columns = {
'codec': 'TEXT',
'bitrate_min': 'INTEGER',
'bitrate_max': 'INTEGER',
'bitrate_mode': 'TEXT',
'container': 'TEXT',
'time_added': 'TIMESTAMP',
'time_started': 'TIMESTAMP',
'time_finished': 'TIMESTAMP'
}
for col, type_ in new_columns.items():
try:
c.execute(f"ALTER TABLE audiobooks ADD COLUMN {col} {type_}")
if log_func:
log_func(f"scanner.db_added_{col}")
except sqlite3.OperationalError:
pass
# Migration: add is_favorite column
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN is_favorite INTEGER DEFAULT 0")
if log_func:
log_func("scanner.db_added_is_favorite")
except sqlite3.OperationalError:
pass # Column already exists
# Migration: create tags tables if they don't exist (handled by CREATE TABLE IF NOT EXISTS above)
# Migration: add is_merged column
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN is_merged INTEGER DEFAULT 0")
if log_func:
log_func("scanner.db_added_is_merged")
except sqlite3.OperationalError:
pass
# Migration: add cached_cover_path column
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN cached_cover_path TEXT")
if log_func:
log_func("scanner.db_added_cached_cover_path")
except sqlite3.OperationalError:
pass
# Migration: add description column
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN description TEXT")
if log_func:
log_func("scanner.db_added_description")
except sqlite3.OperationalError:
pass
# Migration: add total_size column
try:
c.execute("ALTER TABLE audiobooks ADD COLUMN total_size INTEGER DEFAULT 0")
if log_func:
log_func("scanner.db_added_total_size")
except sqlite3.OperationalError:
pass
# Table: audiobook_covers
c.execute("""
CREATE TABLE IF NOT EXISTS audiobook_covers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
audiobook_id INTEGER NOT NULL,
original_path TEXT,
cached_path TEXT NOT NULL,
is_selected INTEGER DEFAULT 0,
source_type TEXT NOT NULL,
FOREIGN KEY(audiobook_id) REFERENCES audiobooks(id) ON DELETE CASCADE
)
""")
c.execute("CREATE INDEX IF NOT EXISTS idx_covers_book_id ON audiobook_covers(audiobook_id)")
# Migration: populate audiobook_covers with existing covers
try:
c.execute("SELECT COUNT(*) FROM audiobook_covers")
if c.fetchone()[0] == 0:
c.execute("""
INSERT INTO audiobook_covers (audiobook_id, original_path, cached_path, is_selected, source_type)
SELECT id, cover_path, cached_cover_path, 1, 'file'
FROM audiobooks
WHERE (cover_path IS NOT NULL AND cover_path != '') OR (cached_cover_path IS NOT NULL AND cached_cover_path != '')
""")
except sqlite3.OperationalError:
pass
# File Metadata Cache table for faster rescanning
c.execute("""
CREATE TABLE IF NOT EXISTS file_metadata_cache (
file_path TEXT PRIMARY KEY,
file_size INTEGER NOT NULL,
mtime REAL NOT NULL,
duration REAL NOT NULL DEFAULT 0,
bitrate INTEGER NOT NULL DEFAULT 0,
codec TEXT DEFAULT '',
is_vbr INTEGER DEFAULT 0,
cached_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
c.execute("CREATE INDEX IF NOT EXISTS idx_file_cache_path ON file_metadata_cache(file_path)")
# Migration: Create listening_sessions table for tracking actual listening time
c.execute("""
CREATE TABLE IF NOT EXISTS listening_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
audiobook_id INTEGER NOT NULL,
session_date DATE NOT NULL,
session_start TIMESTAMP NOT NULL,
session_end TIMESTAMP,
duration_seconds REAL DEFAULT 0,
playback_speed REAL DEFAULT 1.0,
is_active INTEGER DEFAULT 1,
FOREIGN KEY(audiobook_id) REFERENCES audiobooks(id) ON DELETE CASCADE
)
""")
c.execute("CREATE INDEX IF NOT EXISTS idx_sessions_audiobook_date ON listening_sessions(audiobook_id, session_date)")
c.execute("CREATE INDEX IF NOT EXISTS idx_sessions_date ON listening_sessions(session_date)")
c.execute("CREATE INDEX IF NOT EXISTS idx_sessions_active ON listening_sessions(is_active)")
# Migration: Create daily_listening_stats table for aggregated statistics
c.execute("""
CREATE TABLE IF NOT EXISTS daily_listening_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
audiobook_id INTEGER NOT NULL,
listen_date DATE NOT NULL,
total_seconds REAL DEFAULT 0,
session_count INTEGER DEFAULT 0,
UNIQUE(audiobook_id, listen_date),
FOREIGN KEY(audiobook_id) REFERENCES audiobooks(id) ON DELETE CASCADE
)
""")
c.execute("CREATE INDEX IF NOT EXISTS idx_daily_stats_date ON daily_listening_stats(listen_date)")
c.execute("CREATE INDEX IF NOT EXISTS idx_daily_stats_audiobook ON daily_listening_stats(audiobook_id)")
conn.commit()
class DatabaseManager:
"""Manager for audiobook database operations"""
def __init__(self, db_file: Path):
"""Initialize with database file path"""
self.db_file = db_file
# Ensure database and migrations are initialized on startup for backward compatibility
try:
init_database(self.db_file, log_func=None)
except Exception as e:
print(f"Error during DatabaseManager startup migration: {e}")
self.recover_crashed_sessions()
def recover_crashed_sessions(self):
"""Find any sessions that were left active (e.g. due to app crash) and close them properly, updating daily stats"""
import datetime
conn = sqlite3.connect(self.db_file)
active_sessions = []
try:
cursor = conn.cursor()
cursor.execute("""
SELECT id, session_start, duration_seconds
FROM listening_sessions
WHERE is_active = 1
""")
active_sessions = cursor.fetchall()
except sqlite3.Error as e:
# Table might not exist yet on fresh install
print(f"Database error finding crashed sessions (or table missing): {e}")
finally:
conn.close()
for session_id, session_start, duration_seconds in active_sessions:
try:
start_dt = datetime.datetime.strptime(session_start, '%Y-%m-%d %H:%M:%S')
except:
start_dt = datetime.datetime.now()
end_dt = start_dt + datetime.timedelta(seconds=int(duration_seconds))
self.close_listening_session(session_id, end_dt)
# --- Bookmarks Methods ---
def add_bookmark(self, audiobook_id: int, file_name: str, time_position: float, title: str = None, description: str = None) -> Optional[int]:
"""Add a new bookmark"""
if not audiobook_id:
return None
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO bookmarks (audiobook_id, file_name, time_position, title, description)
VALUES (?, ?, ?, ?, ?)
''', (audiobook_id, file_name, time_position, title, description))
bookmark_id = cursor.lastrowid
conn.commit()
return bookmark_id
except sqlite3.Error as e:
print(f"Database error in add_bookmark: {e}")
return None
finally:
conn.close()
def get_bookmarks(self, audiobook_id: int) -> List[Dict]:
"""Get all bookmarks for a specific audiobook"""
if not audiobook_id:
return []
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
SELECT id, file_name, time_position, title, description, created_at
FROM bookmarks
WHERE audiobook_id = ?
ORDER BY time_position ASC
''', (audiobook_id,))
bookmarks = []
for row in cursor.fetchall():
bookmarks.append({
'id': row[0],
'file_name': row[1],
'time_position': row[2],
'title': row[3],
'description': row[4],
'created_at': row[5]
})
return bookmarks
except sqlite3.Error as e:
print(f"Database error in get_bookmarks: {e}")
return []
finally:
conn.close()
def update_bookmark(self, bookmark_id: int, title: str, description: str) -> bool:
"""Update a bookmark's title and description"""
if not bookmark_id:
return False
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE bookmarks
SET title = ?, description = ?
WHERE id = ?
''', (title, description, bookmark_id))
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
print(f"Database error in update_bookmark: {e}")
return False
finally:
conn.close()
def delete_bookmark(self, bookmark_id: int) -> bool:
"""Delete a bookmark"""
if not bookmark_id:
return False
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('DELETE FROM bookmarks WHERE id = ?', (bookmark_id,))
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
print(f"Database error in delete_bookmark: {e}")
return False
finally:
conn.close()
def clear_all_data(self):
"""Completely clear all database tables"""
if not self.db_file.exists():
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute("PRAGMA foreign_keys = OFF")
cursor.execute("DELETE FROM audiobook_files")
cursor.execute("DELETE FROM audiobooks")
conn.commit()
except sqlite3.Error as e:
print(f"Error clearing database: {e}")
raise e
finally:
conn.close()
def load_audiobooks_from_db(self, filter_type: str = 'all') -> Dict:
"""Load audiobooks from database with specified filter"""
if not self.db_file.exists():
return {}
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
columns = '''
path, parent_path, name, author, title, narrator, cover_path, cached_cover_path,
is_folder, file_count, duration, listened_duration, progress_percent,
is_started, is_completed, is_available, is_expanded, last_updated,
codec, bitrate_min, bitrate_max, bitrate_mode, container,
time_added, time_started, time_finished, is_favorite, is_merged, description, total_size, id
'''
columns_with_prefix = '''
p.path, p.parent_path, p.name, p.author, p.title, p.narrator, p.cover_path, p.cached_cover_path,
p.is_folder, p.file_count, p.duration, p.listened_duration, p.progress_percent,
p.is_started, p.is_completed, p.is_available, p.is_expanded, p.last_updated,
p.codec, p.bitrate_min, p.bitrate_max, p.bitrate_mode, p.container,
p.time_added, p.time_started, p.time_finished, p.is_favorite, p.is_merged, p.description, p.total_size, p.id
'''
if filter_type == 'all':
query = f'SELECT {columns} FROM audiobooks WHERE is_available = 1 ORDER BY is_folder DESC, name'
cursor.execute(query)
else:
# Filter condition for audiobooks (not folders)
filter_condition = 'is_folder = 0'
order_by = 'is_folder DESC, name'
if filter_type == 'completed':
filter_condition += ' AND is_completed = 1'
order_by = 'is_folder DESC, time_finished DESC, name'
elif filter_type == 'in_progress':
filter_condition += ' AND is_started = 1 AND is_completed = 0'
# Sort primarily by recency, so active books (and their folders) jump to top
# is_folder DESC is removed from primary sort so folders don't artificially float to top
order_by = 'last_updated DESC, is_folder DESC, name'
elif filter_type == 'not_started':
# "New" filter: Not started, sorted by time_added
filter_condition += ' AND is_started = 0'
order_by = 'is_folder DESC, time_added DESC, name'
elif filter_type == 'favorites':
filter_condition += ' AND is_favorite = 1'
order_by = 'is_folder DESC, name'
# Always filter by availability
filter_condition += ' AND is_available = 1'
# Recursive query to get all levels of parent folders
query = f'''
WITH RECURSIVE
-- 1. Filtered audiobooks
filtered_audiobooks AS (
SELECT {columns}
FROM audiobooks
WHERE {filter_condition}
),
-- 2. Recursive search for ALL parent folders
all_parent_folders AS (
-- Base case: direct parents of filtered audiobooks
SELECT {columns_with_prefix}
FROM audiobooks p
WHERE p.is_folder = 1
AND p.path IN (SELECT parent_path FROM filtered_audiobooks)
UNION
-- Recursion: parents of parents
SELECT {columns_with_prefix}
FROM audiobooks p
INNER JOIN all_parent_folders apf ON p.path = apf.parent_path
WHERE p.is_folder = 1
)
-- 3. Combine audiobooks and ALL their parent folders
SELECT * FROM (
SELECT * FROM filtered_audiobooks
UNION
SELECT * FROM all_parent_folders
)
ORDER BY {order_by}
'''
cursor.execute(query)
rows = cursor.fetchall()
data_by_parent = {}
for row in rows:
path, parent_path, name, author, title, narrator, cover_path, cached_cover_path, \
is_folder, file_count, duration, listened_duration, progress_percent, \
is_started, is_completed, is_available, is_expanded, last_updated, \
codec, bitrate_min, bitrate_max, bitrate_mode, container, \
time_added, time_started, time_finished, is_favorite, is_merged, description, total_size, audiobook_id = row
data_by_parent.setdefault(parent_path, []).append({
'path': path,
'name': name,
'author': author,
'title': title,
'narrator': narrator,
'cover_path': cover_path,
'cached_cover_path': cached_cover_path,
'is_folder': bool(is_folder),
'file_count': file_count or 0,
'duration': duration or 0,
'listened_duration': listened_duration or 0,
'progress_percent': progress_percent or 0,
'is_started': bool(is_started),
'is_completed': bool(is_completed),
'is_available': bool(is_available),
'is_expanded': bool(is_expanded),
'last_updated': last_updated,
'codec': codec,
'bitrate_min': bitrate_min,
'bitrate_max': bitrate_max,
'bitrate_mode': bitrate_mode,
'container': container,
'time_added': time_added,
'time_started': time_started,
'time_finished': time_finished,
'is_favorite': bool(is_favorite),
'is_merged': bool(is_merged),
'description': description,
'total_size': total_size or 0,
'id': audiobook_id
})
return data_by_parent
except sqlite3.Error as e:
print(f"Database error in load_audiobooks_from_db: {e}")
return {}
finally:
conn.close()
def update_last_updated(self, audiobook_id: int):
"""Update the last_updated timestamp for an audiobook"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET last_updated = CURRENT_TIMESTAMP
WHERE id = ?
''', (audiobook_id,))
# Propagate update to parents
self._propagate_last_updated(cursor, audiobook_id)
conn.commit()
except sqlite3.Error as e:
print(f"Database error in update_last_updated: {e}")
finally:
conn.close()
def mark_audiobook_started(self, audiobook_id: int):
"""Mark an audiobook as started"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET is_started = 1, is_completed = 0,
time_started = COALESCE(time_started, CURRENT_TIMESTAMP),
last_updated = CURRENT_TIMESTAMP
WHERE id = ?
''', (audiobook_id,))
# Propagate update to parents
self._propagate_last_updated(cursor, audiobook_id)
conn.commit()
except sqlite3.Error as e:
print(f"Database error in mark_audiobook_started: {e}")
finally:
conn.close()
def mark_audiobook_completed(self, audiobook_id: int, total_duration: float):
"""Mark an audiobook as completely listened"""
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET listened_duration = ?, progress_percent = 100,
is_completed = 1, is_started = 1,
time_started = COALESCE(time_started, CURRENT_TIMESTAMP),
time_finished = COALESCE(time_finished, CURRENT_TIMESTAMP),
last_updated = CURRENT_TIMESTAMP
WHERE id = ?
''', (total_duration, audiobook_id))
# Propagate update to parents
self._propagate_last_updated(cursor, audiobook_id)
conn.commit()
except sqlite3.Error as e:
print(f"Database error in mark_audiobook_completed: {e}")
finally:
conn.close()
def reset_audiobook_status(self, audiobook_id: int):
"""Reset audiobook status to 'not started'"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET listened_duration = 0, progress_percent = 0,
current_file_index = 0, current_position = 0,
is_started = 0, is_completed = 0,
time_started = NULL, time_finished = NULL,
last_updated = CURRENT_TIMESTAMP
WHERE id = ?
''', (audiobook_id,))
# Propagate update to parents
self._propagate_last_updated(cursor, audiobook_id)
conn.commit()
except sqlite3.Error as e:
print(f"Database error in reset_audiobook_status: {e}")
finally:
conn.close()
def _propagate_last_updated(self, cursor, audiobook_id):
"""Helper to recursively update last_updated for parent folders"""
cursor.execute("SELECT path FROM audiobooks WHERE id = ?", (audiobook_id,))
row = cursor.fetchone()
if not row:
return
current_path = row[0]
from pathlib import Path
path_obj = Path(current_path)
while True:
parent = path_obj.parent
if str(parent) == '.' or str(parent) == str(path_obj):
break
path_obj = parent
parent_str = str(path_obj).replace('\\', '/')
cursor.execute('''
UPDATE audiobooks
SET last_updated = CURRENT_TIMESTAMP
WHERE path = ? AND is_folder = 1
''', (parent_str,))
if cursor.rowcount == 0:
pass
def get_audiobook_info(self, audiobook_path: str) -> Optional[Tuple]:
"""Get information about a specific audiobook by path"""
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
SELECT id, name, author, title, current_file_index, current_position, duration,
COALESCE(playback_speed, 1.0), COALESCE(use_id3_tags, 1),
cover_path, cached_cover_path, description
FROM audiobooks WHERE path = ? AND is_folder = 0
''', (audiobook_path,))
return cursor.fetchone()
except sqlite3.Error as e:
print(f"Database error in get_audiobook_info: {e}")
return None
finally:
conn.close()
def get_audiobook_files(self, audiobook_id: int) -> List[Tuple]:
"""Get list of files for a specific audiobook by ID"""
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
SELECT file_path, file_name, duration, track_number, tag_title, start_offset
FROM audiobook_files WHERE audiobook_id = ?
ORDER BY track_number, start_offset, file_name
''', (audiobook_id,))
return cursor.fetchall()
except sqlite3.Error as e:
print(f"Database error in get_audiobook_files: {e}")
return []
finally:
conn.close()
def save_progress(self, audiobook_id: int, file_index: int, position: float,
speed: float, listened_duration: float, progress_percent: int,
update_timestamp: bool = True):
"""Save playback progress for an audiobook"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
try:
# Determine status
# Do not reset is_started or is_completed to 0 if they are already 1
cursor.execute("SELECT is_started, is_completed FROM audiobooks WHERE id = ?", (audiobook_id,))
row = cursor.fetchone()
old_is_started = row[0] if (row and len(row) > 0) else 0
old_is_completed = row[1] if (row and len(row) > 1) else 0
is_started = 1 if (old_is_started or progress_percent > 0) else 0
is_completed = 1 if (old_is_completed or progress_percent >= 100) else 0
update_sql = '''
UPDATE audiobooks
SET current_file_index = ?, current_position = ?, playback_speed = ?,
listened_duration = ?, progress_percent = ?,
is_started = ?, is_completed = ?,
time_started = CASE WHEN ? = 1 AND time_started IS NULL THEN CURRENT_TIMESTAMP ELSE time_started END,
time_finished = CASE WHEN ? = 1 AND time_finished IS NULL THEN CURRENT_TIMESTAMP ELSE time_finished END
'''
params = [file_index, position, speed, listened_duration, progress_percent,
is_started, is_completed, is_started, is_completed]
if update_timestamp:
update_sql += ", last_updated = CURRENT_TIMESTAMP "
update_sql += " WHERE id = ?"
params.append(audiobook_id)
cursor.execute(update_sql, tuple(params))
if update_timestamp:
# Recursively update last_updated for all parent folders
self._propagate_last_updated(cursor, audiobook_id)
conn.commit()
except sqlite3.Error as e:
print(f"Database error in save_progress: {e}")
finally:
conn.close()
def delete_audiobook(self, audiobook_id: int):
"""Delete an audiobook and its associated files from the database"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute("PRAGMA foreign_keys = ON")
cursor.execute("DELETE FROM audiobooks WHERE id = ?", (audiobook_id,))
conn.commit()
except sqlite3.Error as e:
print(f"Database error in delete_audiobook: {e}")
raise e
finally:
conn.close()
def delete_folder(self, folder_path: str):
"""Recursively delete a folder and all its contents (audiobooks and subfolders) from the database"""
if not folder_path:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute("PRAGMA foreign_keys = ON")
# Delete the folder itself and everything starting with 'folder_path\'
pattern = folder_path + os.sep + '%'
cursor.execute('''
DELETE FROM audiobooks
WHERE path = ? OR path LIKE ?
''', (folder_path, pattern))
conn.commit()
except sqlite3.Error as e:
print(f"Database error in delete_folder: {e}")
raise e
finally:
conn.close()
def get_folder_contents(self, folder_path: str) -> List[Tuple[str, bool]]:
"""Get names of all nested audiobooks and subfolders for a given folder path"""
if not folder_path:
return []
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
pattern = folder_path + os.sep + '%'
cursor.execute('''
SELECT name, is_folder FROM audiobooks
WHERE path LIKE ?
ORDER BY is_folder DESC, name ASC
''', (pattern,))
return cursor.fetchall()
except sqlite3.Error as e:
print(f"Database error in get_folder_contents: {e}")
return []
finally:
conn.close()
def update_audiobook_speed(self, audiobook_id: int, speed: float):
"""Update playback speed for an audiobook"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET playback_speed = ?
WHERE id = ?
''', (speed, audiobook_id))
conn.commit()
except sqlite3.Error as e:
print(f"Database error in update_audiobook_speed: {e}")
finally:
conn.close()
def update_audiobook_id3_state(self, audiobook_id: int, state: bool):
"""Update ID3 tags usage state for an audiobook"""
if not audiobook_id:
return
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET use_id3_tags = ?
WHERE id = ?
''', (1 if state else 0, audiobook_id))
conn.commit()
except sqlite3.Error as e:
print(f"Database error in update_audiobook_id3_state: {e}")
finally:
conn.close()
def get_audiobook_count(self) -> int:
"""Get total number of audiobooks in the library"""
if not self.db_file.exists():
return 0
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM audiobooks WHERE is_folder = 0')
return cursor.fetchone()[0]
except sqlite3.Error as e:
print(f"Database error in get_audiobook_count: {e}")
return 0
finally:
conn.close()
def get_audiobook_by_path(self, path: str) -> Optional[Dict]:
"""Get audiobook data by its path for tree updates"""
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
SELECT author, title, narrator, file_count, duration,
listened_duration, progress_percent, is_started, is_completed,
codec, bitrate_min, bitrate_max, bitrate_mode, container,
time_added, time_started, time_finished, is_favorite, description,
cover_path, cached_cover_path, total_size
FROM audiobooks
WHERE path = ? AND is_folder = 0
''', (path,))
row = cursor.fetchone()
if row:
return {
'author': row[0],
'title': row[1],
'narrator': row[2],
'file_count': row[3],
'duration': row[4],
'listened_duration': row[5],
'progress_percent': row[6],
'is_started': bool(row[7]),
'is_completed': bool(row[8]),
'codec': row[9],
'bitrate_min': row[10],
'bitrate_max': row[11],
'bitrate_mode': row[12],
'container': row[13],
'time_added': row[14],
'time_started': row[15],
'time_finished': row[16],
'is_favorite': bool(row[17]),
'description': row[18],
'cover_path': row[19],
'cached_cover_path': row[20],
'total_size': row[21]
}
return None
except sqlite3.Error as e:
print(f"Database error in get_audiobook_by_path: {e}")
return None
finally:
conn.close()
def update_folder_expanded_state(self, path: str, is_expanded: bool):
"""Update the is_expanded state for a folder"""
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET is_expanded = ?
WHERE path = ? AND is_folder = 1
''', (1 if is_expanded else 0, path))
conn.commit()
except sqlite3.Error as e:
print(f"Database error in update_folder_expanded_state: {e}")
finally:
conn.close()
def set_folder_merged(self, path: str, is_merged: bool):
"""Update the is_merged state for a folder"""
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
cursor.execute('''
UPDATE audiobooks
SET is_merged = ?
WHERE path = ? AND is_folder = 1
''', (1 if is_merged else 0, path))
conn.commit()
except sqlite3.Error as e:
print(f"Database error in set_folder_merged: {e}")
finally:
conn.close()
# --- Favorites & Tags Methods ---
def toggle_favorite(self, audiobook_id: int) -> bool:
"""Toggle the favorite status of an audiobook. Returns the new state."""
if not audiobook_id:
return False
conn = sqlite3.connect(self.db_file)
try:
cursor = conn.cursor()
# Get current state
cursor.execute("SELECT is_favorite FROM audiobooks WHERE id = ?", (audiobook_id,))
row = cursor.fetchone()
if not row:
return False