-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdatabase.py
More file actions
1715 lines (1601 loc) · 63.7 KB
/
Copy pathdatabase.py
File metadata and controls
1715 lines (1601 loc) · 63.7 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.py
import sqlite3
import logging
import os
import hashlib
import secrets
import time
from gi.repository import GLib
from datetime import datetime, timezone
import json
_MEMORY_CACHE_PATH = None
user_config_dir = GLib.get_user_config_dir()
APP_CONFIG_DIR = os.path.join(user_config_dir, "EngPlayer")
os.makedirs(APP_CONFIG_DIR, exist_ok=True)
CONFIG_DB_FILE = os.path.join(APP_CONFIG_DIR, "config.db")
LIBRARY_DB_FILE = os.path.join(APP_CONFIG_DIR, "library.db")
CURRENT_PROFILE_DB_FILE = None
def get_config_db_connection():
conn = sqlite3.connect(CONFIG_DB_FILE, timeout=10)
conn.row_factory = sqlite3.Row
return conn
def get_library_db_connection():
conn = sqlite3.connect(LIBRARY_DB_FILE, timeout=10)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
def get_profile_db_connection():
if CURRENT_PROFILE_DB_FILE is None:
logging.error("CRITICAL ERROR: Profile database path is not set. set_active_profile_db must be called first.")
raise Exception("Database path not set. Call set_active_profile_db first.")
conn = sqlite3.connect(CURRENT_PROFILE_DB_FILE, timeout=10)
conn.row_factory = sqlite3.Row
try:
conn.execute("""
CREATE TABLE IF NOT EXISTS custom_channel_edits (
url TEXT PRIMARY KEY,
custom_name TEXT,
custom_group TEXT,
custom_logo TEXT,
custom_epg_id TEXT
)
""")
try:
conn.execute("SELECT custom_epg_id FROM custom_channel_edits LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'custom_channel_edits': adding 'custom_epg_id' column.")
conn.execute("ALTER TABLE custom_channel_edits ADD COLUMN custom_epg_id TEXT")
conn.commit()
except Exception as e:
logging.error(f"SQLite Migration Error (custom_channel_edits): {e}")
return conn
def _initialize_config_db():
try:
conn = get_config_db_connection()
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
""")
conn.commit()
conn.close()
logging.info(f"Global config database ('{CONFIG_DB_FILE}') initialized successfully.")
except sqlite3.Error as e:
logging.error(f"Error initializing global config database: {e}")
def _initialize_library_db():
try:
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS libraries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
path TEXT NOT NULL UNIQUE,
type TEXT NOT NULL CHECK(type IN ('video', 'picture', 'music'))
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS media_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
library_id INTEGER NOT NULL,
file_path TEXT NOT NULL UNIQUE,
title TEXT,
thumbnail_path TEXT,
FOREIGN KEY (library_id) REFERENCES libraries (id) ON DELETE CASCADE
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS media_metadata (
media_path TEXT PRIMARY KEY,
tmdb_id TEXT,
title TEXT,
overview TEXT,
poster_path TEXT,
release_date TEXT,
rating REAL,
director TEXT,
cast_members TEXT,
trailer_key TEXT,
genres TEXT,
countries TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS artists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS albums (
id INTEGER PRIMARY KEY AUTOINCREMENT,
artist_id INTEGER,
name TEXT NOT NULL,
album_art_path TEXT,
FOREIGN KEY (artist_id) REFERENCES artists (id) ON DELETE CASCADE
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS tracks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
album_id INTEGER NOT NULL,
library_id INTEGER,
title TEXT NOT NULL,
track_number INTEGER,
duration INTEGER,
file_path TEXT NOT NULL UNIQUE,
FOREIGN KEY (album_id) REFERENCES albums (id) ON DELETE CASCADE
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS podcasts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
url TEXT NOT NULL UNIQUE,
added_at INTEGER
)
""")
try:
cursor.execute("SELECT sort_order FROM podcasts LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'podcasts' table: adding 'sort_order' column.")
cursor.execute("ALTER TABLE podcasts ADD COLUMN sort_order INTEGER DEFAULT 0")
try:
cursor.execute("SELECT seasons_json FROM media_metadata LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'media_metadata': adding 'seasons_json' column.")
cursor.execute("ALTER TABLE media_metadata ADD COLUMN seasons_json TEXT")
conn.commit()
conn.close()
logging.info(f"Global library database ('{LIBRARY_DB_FILE}') initialized successfully.")
except sqlite3.Error as e:
logging.error(f"Error initializing global library database: {e}")
def _initialize_profile_db():
if CURRENT_PROFILE_DB_FILE is None:
logging.error("Failed to initialize profile database (path not set).")
return
try:
conn = get_profile_db_connection()
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS channel_properties (
channel_url TEXT PRIMARY KEY,
is_locked INTEGER DEFAULT 0
)
""")
try:
cursor.execute("SELECT is_hidden FROM channel_properties LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'channel_properties': adding 'is_hidden' column.")
cursor.execute("ALTER TABLE channel_properties ADD COLUMN is_hidden INTEGER DEFAULT 0")
try:
cursor.execute("SELECT use_external_player FROM channel_properties LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'channel_properties': adding 'use_external_player' column.")
cursor.execute("ALTER TABLE channel_properties ADD COLUMN use_external_player INTEGER DEFAULT 0")
cursor.execute("""
CREATE TABLE IF NOT EXISTS favorite_lists (
list_id INTEGER PRIMARY KEY AUTOINCREMENT,
list_name TEXT NOT NULL UNIQUE,
sort_order INTEGER DEFAULT 0
)
""")
try:
cursor.execute("SELECT sort_order FROM favorite_lists LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'favorite_lists' table: adding 'sort_order' column.")
cursor.execute("ALTER TABLE favorite_lists ADD COLUMN sort_order INTEGER DEFAULT 0")
cursor.execute("""
CREATE TABLE IF NOT EXISTS favorite_channels (
channel_url TEXT NOT NULL,
list_id INTEGER NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY(list_id) REFERENCES favorite_lists(list_id) ON DELETE CASCADE,
PRIMARY KEY(channel_url, list_id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS bouquet_properties (
bouquet_name TEXT PRIMARY KEY,
is_locked INTEGER DEFAULT 0
)
""")
try:
cursor.execute("SELECT is_hidden FROM bouquet_properties LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'bouquet_properties': adding 'is_hidden' column.")
cursor.execute("ALTER TABLE bouquet_properties ADD COLUMN is_hidden INTEGER DEFAULT 0")
cursor.execute("""
CREATE TABLE IF NOT EXISTS favorite_list_properties (
list_id INTEGER PRIMARY KEY,
is_locked INTEGER DEFAULT 0
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS scheduled_recordings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
profile_id TEXT NOT NULL,
channel_name TEXT NOT NULL,
channel_url TEXT NOT NULL,
start_time INTEGER NOT NULL,
end_time INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at INTEGER NOT NULL
)
""")
try:
cursor.execute("SELECT program_name FROM scheduled_recordings LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'scheduled_recordings': adding 'program_name' column.")
cursor.execute("ALTER TABLE scheduled_recordings ADD COLUMN program_name TEXT")
cursor.execute("""
CREATE TABLE IF NOT EXISTS playback_progress (
media_path TEXT PRIMARY KEY,
last_position INTEGER DEFAULT 0,
last_watched INTEGER NOT NULL,
is_finished INTEGER DEFAULT 0 NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS trakt_auth (
id INTEGER PRIMARY KEY,
access_token TEXT NOT NULL,
refresh_token TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_in INTEGER NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS channel_history (
channel_url TEXT PRIMARY KEY,
channel_data_json TEXT NOT NULL,
last_watched INTEGER NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS cache_recent_media (
media_type TEXT,
stream_id TEXT,
added_ts INTEGER,
data_json TEXT,
PRIMARY KEY(media_type, stream_id)
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_cache_recent_time ON cache_recent_media (media_type, added_ts)")
cursor.execute("""
CREATE TABLE IF NOT EXISTS vod_favorites (
stream_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
poster_path TEXT,
added_at INTEGER NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS series_favorites (
series_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
poster_path TEXT,
added_at INTEGER NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS active_downloads (
url TEXT PRIMARY KEY,
output_path TEXT NOT NULL
)
""")
try:
cursor.execute("SELECT speed_limit FROM active_downloads LIMIT 1")
except sqlite3.OperationalError:
logging.info("Migrating 'active_downloads': adding 'speed_limit' column.")
cursor.execute("ALTER TABLE active_downloads ADD COLUMN speed_limit INTEGER")
conn.commit()
conn.close()
logging.info(f"Profile database ('{CURRENT_PROFILE_DB_FILE}') initialized successfully.")
except sqlite3.Error as e:
logging.error(f"Error initializing profile database: {e}")
def initialize_database():
_initialize_config_db()
_initialize_library_db()
init_epg_db()
def set_active_profile_db(profile_id):
global CURRENT_PROFILE_DB_FILE
safe_id = hashlib.md5(profile_id.encode()).hexdigest()
new_db_path = os.path.join(APP_CONFIG_DIR, f"profile_{safe_id}.db")
if CURRENT_PROFILE_DB_FILE == new_db_path:
return
CURRENT_PROFILE_DB_FILE = new_db_path
logging.info(f"Active profile database path set to: {CURRENT_PROFILE_DB_FILE}")
_initialize_profile_db()
def set_config_value(key, value):
conn = get_config_db_connection()
try:
conn.execute("INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, str(value)))
conn.commit()
except sqlite3.Error as e:
logging.error(f"Failed to set config value for key '{key}': {e}")
finally:
conn.close()
def get_config_value(key):
conn = get_config_db_connection()
value = conn.cursor().execute("SELECT value FROM config WHERE key = ?", (key,)).fetchone()
conn.close()
return value[0] if value else None
def set_password(password):
salt = secrets.token_hex(16)
hashed_password = hashlib.sha256((salt + password).encode()).hexdigest()
set_config_value('app_password', f"{salt}:{hashed_password}")
logging.info("Application password has been set/updated.")
def check_password(password):
stored_value = get_config_value('app_password')
if not stored_value:
return False
salt, stored_hash = stored_value.split(':')
hashed_password_to_check = hashlib.sha256((salt + password).encode()).hexdigest()
return hashed_password_to_check == stored_hash
def get_recordings_path():
saved_path = get_config_value('recordings_path')
if saved_path:
return saved_path
else:
videos_path = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_VIDEOS)
return videos_path
def get_cache_path():
global _MEMORY_CACHE_PATH
if _MEMORY_CACHE_PATH:
return _MEMORY_CACHE_PATH
saved_path = get_config_value('cache_path')
if saved_path:
_MEMORY_CACHE_PATH = saved_path
return saved_path
else:
cache_dir = os.path.join(GLib.get_user_cache_dir(), "EngPlayer")
_MEMORY_CACHE_PATH = cache_dir
return cache_dir
def get_use_tmdb_status():
value = get_config_value('use_tmdb_metadata')
return value != '0'
def get_use_poster_disk_cache_status():
value = get_config_value('use_poster_disk_cache')
return value == '1'
def get_show_locked_bouquets_status():
value = get_config_value('show_locked_bouquets')
if value is None:
return True
return bool(int(value))
def add_library(path, library_type, name):
conn = get_library_db_connection()
try:
with conn:
cursor = conn.execute(
"INSERT INTO libraries (path, type, name) VALUES (?, ?, ?)",
(path, library_type, name)
)
logging.info(f"Successfully added '{path}' as a '{library_type}' library named '{name}'.")
return cursor.lastrowid
except sqlite3.IntegrityError:
logging.warning(f"Library path '{path}' already exists in the database.")
return None
except sqlite3.Error as e:
logging.error(f"Failed to add library '{path}': {e}")
return None
finally:
conn.close()
def get_all_libraries():
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM libraries")
libraries = cursor.fetchall()
conn.close()
return libraries
def get_media_files_by_type(library_type):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT mf.file_path, mf.title
FROM media_files mf
JOIN libraries l ON mf.library_id = l.id
WHERE l.type = ?
""", (library_type,))
media_files = cursor.fetchall()
conn.close()
return media_files
def add_media_file(library_id, file_path):
conn = get_library_db_connection()
try:
with conn:
conn.execute(
"INSERT OR IGNORE INTO media_files (library_id, file_path) VALUES (?, ?)",
(library_id, file_path)
)
except sqlite3.Error as e:
logging.error(f"Failed to add media file '{file_path}': {e}")
finally:
conn.close()
def media_library_is_empty(library_type):
conn = get_library_db_connection()
result = conn.execute("""
SELECT EXISTS (
SELECT 1 FROM media_files mf JOIN libraries l ON mf.library_id = l.id WHERE l.type = ?
)
""", (library_type,)).fetchone()
conn.close()
return result[0] == 0
def save_metadata(media_path, metadata):
if not metadata: return
conn = get_library_db_connection()
try:
with conn:
cast_with_pics_json = json.dumps(metadata.get("cast_with_pics", []))
conn.execute("""
INSERT INTO media_metadata (
media_path, tmdb_id, title, overview, poster_path,
release_date, rating, director, cast_members, trailer_key, genres,
countries
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(media_path) DO UPDATE SET
tmdb_id=excluded.tmdb_id, title=excluded.title, overview=excluded.overview,
poster_path=excluded.poster_path, release_date=excluded.release_date,
rating=excluded.rating, director=excluded.director,
cast_members=excluded.cast_members,
trailer_key=excluded.trailer_key,
genres=excluded.genres,
countries=excluded.countries
""", (
media_path, str(metadata.get("id", "")), metadata.get("title"),
metadata.get("overview"), metadata.get("poster_path"), metadata.get("release_date"),
metadata.get("vote_average"),
metadata.get("director"),
cast_with_pics_json,
metadata.get("trailer_key"),
metadata.get("genres"),
metadata.get("countries")
))
except sqlite3.Error as e:
logging.error(f"Failed to save metadata for '{media_path}': {e}")
finally:
conn.close()
def get_metadata(media_path):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM media_metadata WHERE media_path = ?", (media_path,))
data = cursor.fetchone()
conn.close()
return data
def get_media_files_with_metadata_by_type(library_type):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT
mf.file_path,
mf.title,
meta.poster_path
FROM media_files mf
JOIN libraries l ON mf.library_id = l.id
LEFT JOIN media_metadata meta ON mf.file_path = meta.media_path
WHERE l.type = ?
""", (library_type,))
media_files = cursor.fetchall()
conn.close()
return media_files
def clear_metadata_for_path(media_path):
conn = get_library_db_connection()
try:
with conn:
conn.execute("DELETE FROM media_metadata WHERE media_path = ?", (media_path,))
logging.info(f"Cleared cached metadata for '{media_path}'.")
except sqlite3.Error as e:
logging.error(f"Failed to clear metadata for '{media_path}': {e}")
finally:
conn.close()
def get_all_albums():
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT
a.id as album_id, a.name as album_name, a.album_art_path, ar.name as artist_name
FROM albums a
JOIN artists ar ON a.artist_id = ar.id
ORDER BY ar.name, a.name
""")
albums = cursor.fetchall()
conn.close()
return albums
def get_tracks_for_album(album_id):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM tracks
WHERE album_id = ?
ORDER BY track_number
""", (album_id,))
tracks = cursor.fetchall()
conn.close()
return tracks
def get_album_details(album_id):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT a.name as album_name, a.album_art_path, ar.name as artist_name
FROM albums a
JOIN artists ar ON a.artist_id = ar.id
WHERE a.id = ?
""", (album_id,))
album = cursor.fetchone()
conn.close()
return album
def get_libraries_by_type(library_type):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM libraries WHERE type = ? ORDER BY name",
(library_type,)
)
libraries = cursor.fetchall()
conn.close()
return libraries
def get_media_files_by_library_id(library_id):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT
mf.file_path, mf.title, meta.poster_path
FROM media_files mf
JOIN libraries l ON mf.library_id = l.id
LEFT JOIN media_metadata meta ON mf.file_path = meta.media_path
WHERE l.id = ?
""", (library_id,))
media_files = cursor.fetchall()
conn.close()
return media_files
def get_albums_by_library_id(library_id):
conn = get_library_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT DISTINCT
a.id as album_id, a.name as album_name, a.album_art_path, ar.name as artist_name
FROM albums a
JOIN artists ar ON a.artist_id = ar.id
JOIN tracks t ON a.id = t.album_id
WHERE t.library_id = ?
ORDER BY ar.name, a.name
""", (library_id,))
albums = cursor.fetchall()
conn.close()
return albums
def delete_library(library_id):
conn = get_library_db_connection()
try:
with conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM tracks WHERE library_id = ?", (library_id,))
logging.info(f"{cursor.rowcount} track records deleted for library (ID: {library_id}).")
cursor.execute("DELETE FROM libraries WHERE id = ?", (library_id,))
logging.info(f"Library (ID: {library_id}) and associated media files deleted.")
cursor.execute("DELETE FROM albums WHERE id NOT IN (SELECT DISTINCT album_id FROM tracks)")
logging.info(f"{cursor.rowcount} orphan albums cleaned up.")
cursor.execute("DELETE FROM artists WHERE id NOT IN (SELECT DISTINCT artist_id FROM albums)")
logging.info(f"{cursor.rowcount} orphan artists cleaned up.")
return True
except sqlite3.Error as e:
logging.error(f"Error deleting library (ID: {library_id}): {e}")
return False
finally:
conn.close()
def delete_media_file_record(file_path):
conn = get_library_db_connection()
try:
with conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM media_files WHERE file_path = ?", (file_path,))
logging.info(f"Media record deleted: {file_path}")
return True
except sqlite3.Error as e:
logging.error(f"Error deleting media record: {e}")
return False
finally:
conn.close()
def delete_track_record(file_path):
conn = get_library_db_connection()
try:
with conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM tracks WHERE file_path = ?", (file_path,))
cursor.execute("DELETE FROM albums WHERE id NOT IN (SELECT DISTINCT album_id FROM tracks)")
cursor.execute("DELETE FROM artists WHERE id NOT IN (SELECT DISTINCT artist_id FROM albums)")
logging.info(f"Track record deleted and cleaned up: {file_path}")
return True
except sqlite3.Error as e:
logging.error(f"Error deleting track record: {e}")
return False
finally:
conn.close()
def set_channel_lock_status(channel_url, is_locked):
conn = get_profile_db_connection()
try:
conn.execute("""
INSERT INTO channel_properties (channel_url, is_locked) VALUES (?, ?)
ON CONFLICT(channel_url) DO UPDATE SET is_locked = excluded.is_locked
""", (channel_url, int(is_locked)))
conn.commit()
except sqlite3.Error as e:
logging.error(f"Failed to set lock status for channel '{channel_url}': {e}")
finally:
conn.close()
def get_channel_lock_status(channel_url):
conn = get_profile_db_connection()
props = conn.cursor().execute("SELECT is_locked FROM channel_properties WHERE channel_url = ?", (channel_url,)).fetchone()
conn.close()
return bool(props["is_locked"]) if props else False
def set_channel_external_player_status(channel_url, use_external):
conn = get_profile_db_connection()
try:
conn.execute("""
INSERT INTO channel_properties (channel_url, use_external_player) VALUES (?, ?)
ON CONFLICT(channel_url) DO UPDATE SET use_external_player = excluded.use_external_player
""", (channel_url, int(use_external)))
conn.commit()
except sqlite3.Error as e:
logging.error(f"Failed to set external player status for channel '{channel_url}': {e}")
finally:
conn.close()
def get_channel_external_player_status(channel_url):
conn = get_profile_db_connection()
props = conn.cursor().execute("SELECT use_external_player FROM channel_properties WHERE channel_url = ?", (channel_url,)).fetchone()
conn.close()
return bool(props["use_external_player"]) if props else False
def is_channel_in_any_favorite(channel_url):
conn = get_profile_db_connection()
result = conn.cursor().execute("SELECT 1 FROM favorite_channels WHERE channel_url = ? LIMIT 1", (channel_url,)).fetchone()
conn.close()
return result is not None
def get_all_favorite_lists():
conn = get_profile_db_connection()
lists = conn.cursor().execute("SELECT list_id, list_name FROM favorite_lists ORDER BY sort_order ASC, list_name ASC").fetchall()
conn.close()
return lists
def create_favorite_list(list_name):
conn = get_profile_db_connection()
try:
cursor = conn.cursor()
cursor.execute("SELECT MAX(sort_order) as max_order FROM favorite_lists")
row = cursor.fetchone()
new_order = (row['max_order'] or 0) + 1
conn.execute("INSERT INTO favorite_lists (list_name, sort_order) VALUES (?, ?)", (list_name, new_order))
conn.commit()
logging.info(f"Created new favorite list: '{list_name}' with order {new_order}")
return True
except sqlite3.IntegrityError:
logging.warning(f"Favorite list '{list_name}' already exists.")
return False
finally:
conn.close()
def add_channel_to_list(channel_url, list_id):
conn = get_profile_db_connection()
try:
with conn:
cursor = conn.cursor()
cursor.execute("SELECT MAX(sort_order) as max_order FROM favorite_channels WHERE list_id = ?", (list_id,))
result = cursor.fetchone()
new_order = (result['max_order'] or 0) + 1
conn.execute(
"INSERT OR IGNORE INTO favorite_channels (channel_url, list_id, sort_order) VALUES (?, ?, ?)",
(channel_url, list_id, new_order)
)
logging.info(f"Channel '{channel_url}' added to list '{list_id}' with order {new_order}")
except sqlite3.Error as e:
logging.error(f"Failed to add channel '{channel_url}' to list '{list_id}': {e}")
finally:
conn.close()
def get_channels_in_list(list_id):
conn = get_profile_db_connection()
urls = conn.execute(
"SELECT channel_url FROM favorite_channels WHERE list_id = ? ORDER BY sort_order ASC",
(list_id,)
).fetchall()
conn.close()
return [row['channel_url'] for row in urls]
def set_bouquet_lock_status(bouquet_name, is_locked):
conn = get_profile_db_connection()
try:
conn.execute("""
INSERT INTO bouquet_properties (bouquet_name, is_locked) VALUES (?, ?)
ON CONFLICT(bouquet_name) DO UPDATE SET is_locked = excluded.is_locked
""", (bouquet_name, int(is_locked)))
conn.commit()
finally:
conn.close()
def get_bouquet_lock_status(bouquet_name):
conn = get_profile_db_connection()
props = conn.cursor().execute("SELECT is_locked FROM bouquet_properties WHERE bouquet_name = ?", (bouquet_name,)).fetchone()
conn.close()
return bool(props["is_locked"]) if props else False
def set_favorite_list_lock_status(list_id, is_locked):
conn = get_profile_db_connection()
try:
conn.execute("""
INSERT INTO favorite_list_properties (list_id, is_locked) VALUES (?, ?)
ON CONFLICT(list_id) DO UPDATE SET is_locked = excluded.is_locked
""", (list_id, int(is_locked)))
conn.commit()
finally:
conn.close()
def get_favorite_list_lock_status(list_id):
conn = get_profile_db_connection()
props = conn.cursor().execute("SELECT is_locked FROM favorite_list_properties WHERE list_id = ?", (list_id,)).fetchone()
conn.close()
return bool(props["is_locked"]) if props else False
def remove_channel_from_list(channel_url, list_id):
conn = get_profile_db_connection()
try:
conn.execute("DELETE FROM favorite_channels WHERE channel_url = ? AND list_id = ?", (channel_url, list_id))
conn.commit()
except sqlite3.Error as e:
logging.error(f"Failed to remove channel '{channel_url}' from list '{list_id}': {e}")
finally:
conn.close()
def delete_favorite_list(list_id):
conn = get_profile_db_connection()
try:
conn.execute("DELETE FROM favorite_lists WHERE list_id = ?", (list_id,))
conn.commit()
logging.info(f"Deleted favorite list with id: {list_id}")
except sqlite3.Error as e:
logging.error(f"Failed to delete favorite list '{list_id}': {e}")
finally:
conn.close()
def is_channel_in_list(channel_url, list_id):
conn = get_profile_db_connection()
result = conn.cursor().execute("SELECT 1 FROM favorite_channels WHERE channel_url = ? AND list_id = ? LIMIT 1", (channel_url, list_id)).fetchone()
conn.close()
return result is not None
def add_scheduled_recording(profile_id, channel_name, channel_url, start_time, end_time, program_name=None):
conn = get_profile_db_connection()
try:
with conn:
conn.execute(
"""INSERT INTO scheduled_recordings
(profile_id, channel_name, channel_url, start_time, end_time, program_name, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(profile_id, channel_name, channel_url, int(start_time), int(end_time), program_name, int(time.time()))
)
logging.info(f"New scheduled recording added: {program_name or channel_name} @ {start_time}")
return True
except sqlite3.Error as e:
logging.error(f"Failed to add scheduled recording: {e}")
return False
finally:
conn.close()
def get_all_scheduled_recordings():
conn = get_profile_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM scheduled_recordings ORDER BY created_at DESC")
recordings = cursor.fetchall()
conn.close()
return recordings
def get_pending_recordings_to_start():
conn = get_profile_db_connection()
cursor = conn.cursor()
now = int(time.time())
cursor.execute(
"SELECT * FROM scheduled_recordings WHERE status = 'pending' AND start_time <= ?", (now,)
)
recordings = cursor.fetchall()
conn.close()
return recordings
def update_recording_status(recording_id, status):
conn = get_profile_db_connection()
try:
with conn:
conn.execute("UPDATE scheduled_recordings SET status = ? WHERE id = ?", (status, recording_id))
logging.info(f"Recording ID {recording_id} status updated: {status}")
except sqlite3.Error as e:
logging.error(f"Failed to update recording status: {e}")
finally:
conn.close()
def delete_scheduled_recording(recording_id):
conn = get_profile_db_connection()
try:
with conn:
conn.execute("DELETE FROM scheduled_recordings WHERE id = ?", (recording_id,))
logging.info(f"Scheduled recording deleted: ID {recording_id}")
except sqlite3.Error as e:
logging.error(f"Failed to delete scheduled recording: {e}")
finally:
conn.close()
def get_active_recordings():
conn = get_profile_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM scheduled_recordings WHERE status = 'recording'")
recordings = cursor.fetchall()
conn.close()
return recordings
def get_all_favorite_channel_urls():
conn = get_profile_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT DISTINCT channel_url FROM favorite_channels")
urls = {row['channel_url'] for row in cursor.fetchall()}
conn.close()
return urls
def get_all_locked_channel_urls():
conn = get_profile_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT channel_url FROM channel_properties WHERE is_locked = 1")
urls = {row['channel_url'] for row in cursor.fetchall()}
conn.close()
return urls
def save_playback_progress(media_path, position, is_finished=0):
conn = get_profile_db_connection()
try:
with conn:
conn.execute("""
INSERT INTO playback_progress (media_path, last_position, last_watched, is_finished)
VALUES (?, ?, ?, ?)
ON CONFLICT(media_path) DO UPDATE SET
last_position=excluded.last_position,
last_watched=excluded.last_watched,
is_finished=excluded.is_finished
""", (media_path, int(position), int(time.time()), int(is_finished)))
except sqlite3.Error as e:
logging.error(f"Failed to save playback position '{media_path}': {e}")
finally:
conn.close()
def get_playback_position(media_path):
conn = get_profile_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT last_position FROM playback_progress WHERE media_path = ? AND is_finished = 0", (media_path,))
data = cursor.fetchone()
conn.close()
if data and data['last_position'] > 10:
return data['last_position']
return None
def delete_playback_position(media_path):
conn = get_profile_db_connection()
try:
with conn:
conn.execute("DELETE FROM playback_progress WHERE media_path = ?", (media_path,))
logging.info(f"Playback position deleted: {media_path}")
except sqlite3.Error as e:
logging.error(f"Failed to delete playback position: {e}")
finally:
conn.close()
def get_watched_status_batch(media_paths):
if not media_paths:
return set()
conn = get_profile_db_connection()
cursor = conn.cursor()
placeholders = ','.join('?' for _ in media_paths)
query = f"SELECT media_path FROM playback_progress WHERE media_path IN ({placeholders}) AND is_finished = 1"
try:
cursor.execute(query, media_paths)
watched_set = {row['media_path'] for row in cursor.fetchall()}
return watched_set
except sqlite3.Error as e:
logging.error(f"Failed to get batch watched status: {e}")
return set()
finally:
conn.close()
def swap_favorite_channel_order(list_id, channel_url_1, channel_url_2):
conn = get_profile_db_connection()
try:
with conn:
cursor = conn.cursor()
cursor.execute("SELECT sort_order FROM favorite_channels WHERE list_id = ? AND channel_url = ?", (list_id, channel_url_1))
order1_row = cursor.fetchone()
cursor.execute("SELECT sort_order FROM favorite_channels WHERE list_id = ? AND channel_url = ?", (list_id, channel_url_2))
order2_row = cursor.fetchone()
if not order1_row or not order2_row:
logging.error("Failed to swap order: One of the channels was not found.")
return False
order1 = order1_row['sort_order']
order2 = order2_row['sort_order']
cursor.execute(
"UPDATE favorite_channels SET sort_order = ? WHERE list_id = ? AND channel_url = ?",
(order2, list_id, channel_url_1)
)
cursor.execute(
"UPDATE favorite_channels SET sort_order = ? WHERE list_id = ? AND channel_url = ?",
(order1, list_id, channel_url_2)
)
logging.info(f"Order swapped: '{channel_url_1}' (new: {order2}), '{channel_url_2}' (new: {order1})")
return True
except sqlite3.Error as e:
logging.error(f"Error swapping channel order: {e}")
return False
finally:
conn.close()
def save_trakt_token(token_data):
conn = get_profile_db_connection()
try:
with conn:
conn.execute("DELETE FROM trakt_auth")
conn.execute(
"""INSERT INTO trakt_auth
(access_token, refresh_token, created_at, expires_in)
VALUES (?, ?, ?, ?)""",
(
token_data['access_token'],
token_data['refresh_token'],
int(token_data['created_at']),
int(token_data['expires_in'])
)
)
logging.info("Trakt.tv token successfully saved to database.")
return True
except sqlite3.Error as e:
logging.error(f"Failed to save Trakt.tv token: {e}")
return False
finally:
conn.close()