-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
973 lines (807 loc) · 35.1 KB
/
Copy pathdatabase.py
File metadata and controls
973 lines (807 loc) · 35.1 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
#!/usr/bin/env python3
"""
Módulo de gestión de base de datos SQLite para el sistema de descarga de música.
"""
import sqlite3
import os
import sys
import threading
import json
from pathlib import Path
from typing import Optional, Dict, List, Tuple
from datetime import datetime
def get_default_db_path() -> Path:
"""
Devuelve la ruta por defecto del archivo de base de datos.
En ejecutable empaquetado: junto al .exe. En desarrollo: en el home del usuario.
"""
if getattr(sys, 'frozen', False):
base_dir = Path(sys.executable).parent.resolve()
return base_dir / 'youtube_music.db'
return Path.home() / '.youtube_music.db'
def _ask_user_for_db_folder(suggested_path: Path) -> Optional[Path]:
"""
Muestra un diálogo para que el usuario elija la carpeta donde crear la base de datos.
suggested_path: ruta por defecto (se usará su directorio padre como sugerencia).
Devuelve la ruta completa (carpeta/youtube_music.db) o None si cancela.
"""
try:
import tkinter as tk
from tkinter import filedialog, messagebox
except ImportError:
return None
root = tk.Tk()
root.withdraw()
root.attributes('-topmost', True)
initial_dir = suggested_path.parent if suggested_path else Path.home()
if not initial_dir.exists():
initial_dir = Path.home()
messagebox.showinfo(
"Ubicación de la base de datos",
"No se pudo crear la base de datos en la ubicación por defecto.\n\n"
"Elija una carpeta donde guardarla (por ejemplo, Documentos o la carpeta del programa).\n\n"
f"Ubicación por defecto sugerida:\n{suggested_path}"
)
folder = filedialog.askdirectory(
title="Seleccione la carpeta para la base de datos",
initialdir=str(initial_dir)
)
root.destroy()
if folder:
return Path(folder) / 'youtube_music.db'
return None
def get_or_choose_db_path() -> Optional[str]:
"""
Obtiene una ruta de base de datos válida: usa DB_PATH del entorno, o la ruta por defecto.
Si no se puede crear/abrir el archivo (p. ej. permisos en OneDrive), muestra un diálogo
para que el usuario elija la carpeta y sugiere la ubicación por defecto.
Establece os.environ['DB_PATH'] con la ruta elegida y la devuelve.
Devuelve None si el usuario cancela el diálogo.
"""
path_str = os.environ.get('DB_PATH', '').strip()
if path_str:
path = Path(path_str)
else:
path = get_default_db_path()
path = path.resolve()
# Asegurar que el directorio padre exista (sqlite no crea directorios)
try:
path.parent.mkdir(parents=True, exist_ok=True)
except OSError:
pass
try:
conn = sqlite3.connect(str(path))
conn.close()
os.environ['DB_PATH'] = str(path)
return str(path)
except sqlite3.OperationalError as e:
if 'unable to open database file' not in str(e).lower():
raise
chosen = _ask_user_for_db_folder(path)
if not chosen:
return None
try:
chosen.parent.mkdir(parents=True, exist_ok=True)
except OSError:
pass
try:
conn = sqlite3.connect(str(chosen))
conn.close()
os.environ['DB_PATH'] = str(chosen)
return str(chosen)
except sqlite3.OperationalError:
return None
return None
class MusicDatabase:
"""Clase para gestionar la base de datos de música."""
def __init__(self, db_path: Optional[str] = None):
"""
Inicializa la conexión a la base de datos.
Args:
db_path: Ruta al archivo de base de datos. Si es None, usa la ruta por defecto.
"""
if db_path is None:
if getattr(sys, 'frozen', False):
# Ejecutable empaquetado (PyInstaller): base de datos junto al .exe
# Evita "unable to open database file" en Windows (OneDrive, permisos, etc.)
base_dir = Path(sys.executable).parent.resolve()
db_path = base_dir / 'youtube_music.db'
else:
db_path = Path.home() / '.youtube_music.db'
self.db_path = Path(db_path)
# Usar threading.local() para tener una conexión por thread
self._local = threading.local()
self._lock = threading.Lock()
self._init_database()
def _get_connection(self):
"""
Obtiene una conexión a la base de datos.
Crea una conexión por thread para evitar problemas de concurrencia.
"""
# Obtener o crear conexión para el thread actual
if not hasattr(self._local, 'conn') or self._local.conn is None:
# Usar check_same_thread=False para permitir uso desde diferentes threads
self._local.conn = sqlite3.connect(
str(self.db_path),
check_same_thread=False
)
self._local.conn.row_factory = sqlite3.Row # Permite acceso por nombre de columna
# Habilitar WAL mode para mejor concurrencia
self._local.conn.execute('PRAGMA journal_mode=WAL')
return self._local.conn
def _init_database(self):
"""Inicializa las tablas de la base de datos si no existen."""
conn = self._get_connection()
cursor = conn.cursor()
# Tabla de canciones descargadas
cursor.execute('''
CREATE TABLE IF NOT EXISTS songs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id TEXT UNIQUE NOT NULL,
url TEXT NOT NULL,
title TEXT NOT NULL,
artist TEXT,
year TEXT,
genre TEXT,
decade TEXT,
file_path TEXT UNIQUE NOT NULL,
file_size INTEGER,
file_type TEXT,
duration REAL,
thumbnail_url TEXT,
description TEXT,
downloaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
download_source TEXT
)
''')
# Migraciones: añadir columnas si no existen (para bases de datos existentes)
try:
cursor.execute('ALTER TABLE songs ADD COLUMN download_source TEXT')
except sqlite3.OperationalError:
# La columna ya existe, no hacer nada
pass
try:
cursor.execute('ALTER TABLE songs ADD COLUMN file_type TEXT')
except sqlite3.OperationalError:
# La columna ya existe, no hacer nada
pass
try:
cursor.execute('ALTER TABLE songs ADD COLUMN bitrate_kbps INTEGER')
except sqlite3.OperationalError:
# La columna ya existe, no hacer nada
pass
try:
cursor.execute('ALTER TABLE songs ADD COLUMN volume_lufs REAL')
except sqlite3.OperationalError:
pass
try:
cursor.execute('ALTER TABLE songs ADD COLUMN volume_offset_db REAL DEFAULT 0')
except sqlite3.OperationalError:
pass
try:
cursor.execute('ALTER TABLE songs ADD COLUMN waveform_data TEXT')
except sqlite3.OperationalError:
pass
# Índices para búsquedas rápidas
cursor.execute('CREATE INDEX IF NOT EXISTS idx_video_id ON songs(video_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_artist ON songs(artist)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_genre ON songs(genre)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_year ON songs(year)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_file_path ON songs(file_path)')
# Tabla de videos rechazados
cursor.execute('''
CREATE TABLE IF NOT EXISTS rejected_videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id TEXT UNIQUE NOT NULL,
url TEXT,
title TEXT,
rejected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
reason TEXT
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_rejected_video_id ON rejected_videos(video_id)')
# Tabla de historial de descargas (opcional, para estadísticas)
cursor.execute('''
CREATE TABLE IF NOT EXISTS download_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id TEXT NOT NULL,
action TEXT NOT NULL, -- 'downloaded', 'rejected', 'skipped', 'failed'
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
notes TEXT
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_history_video_id ON download_history(video_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_history_timestamp ON download_history(timestamp)')
# Tabla de caché para datos de videos y clasificaciones
cursor.execute('''
CREATE TABLE IF NOT EXISTS video_cache (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id TEXT UNIQUE NOT NULL,
video_info TEXT, -- JSON con información del video
metadata TEXT, -- JSON con metadatos extraídos
genre TEXT, -- Género detectado
cached_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cache_video_id ON video_cache(video_id)')
conn.commit()
def add_song(self, video_id: str, url: str, title: str, file_path: str,
artist: Optional[str] = None, year: Optional[str] = None,
genre: Optional[str] = None, decade: Optional[str] = None,
file_size: Optional[int] = None, file_type: Optional[str] = None,
duration: Optional[float] = None,
thumbnail_url: Optional[str] = None, description: Optional[str] = None,
download_source: Optional[str] = None, bitrate_kbps: Optional[int] = None,
volume_lufs: Optional[float] = None, volume_offset_db: Optional[float] = None) -> bool:
"""
Añade una canción a la base de datos.
Returns:
True si se añadió correctamente, False si ya existe.
"""
with self._lock: # Proteger operaciones de escritura
conn = self._get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO songs (
video_id, url, title, artist, year, genre, decade,
file_path, file_size, file_type, duration, thumbnail_url, description, download_source, bitrate_kbps, volume_lufs, volume_offset_db
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (video_id, url, title, artist, year, genre, decade,
str(file_path), file_size, file_type, duration, thumbnail_url, description, download_source, bitrate_kbps,
volume_lufs, volume_offset_db if volume_offset_db is not None else 0))
# Registrar en historial
cursor.execute('''
INSERT INTO download_history (video_id, action, notes)
VALUES (?, 'downloaded', ?)
''', (video_id, f"Downloaded: {title}"))
conn.commit()
return True
except sqlite3.IntegrityError as e:
# Ya existe (video_id o file_path duplicado)
conn.rollback()
# Verificar qué causó el error
error_msg = str(e)
if 'video_id' in error_msg.lower() or 'UNIQUE constraint failed: songs.video_id' in error_msg:
# Verificar si existe por video_id
existing = self.get_song_by_video_id(video_id)
if existing:
print(f" ⚠️ Ya existe una canción con video_id '{video_id}': {existing.get('title', 'N/A')}")
elif 'file_path' in error_msg.lower() or 'UNIQUE constraint failed: songs.file_path' in error_msg:
# Verificar si existe por file_path
existing = self.get_song_by_file_path(str(file_path))
if existing:
print(f" ⚠️ Ya existe una canción con file_path '{file_path}': video_id={existing.get('video_id', 'N/A')}")
return False
def update_song(self, video_id: str, **kwargs) -> bool:
"""
Actualiza los datos de una canción existente.
Args:
video_id: ID del video
**kwargs: Campos a actualizar (artist, year, genre, etc.)
"""
if not kwargs:
return False
with self._lock: # Proteger operaciones de escritura
conn = self._get_connection()
cursor = conn.cursor()
# Construir query de actualización
allowed_fields = ['title', 'artist', 'year', 'genre', 'decade', 'file_path',
'file_size', 'file_type', 'duration', 'thumbnail_url', 'description', 'download_source', 'bitrate_kbps', 'volume_lufs', 'volume_offset_db', 'waveform_data']
updates = []
values = []
for key, value in kwargs.items():
if key in allowed_fields:
updates.append(f"{key} = ?")
values.append(value)
if not updates:
return False
updates.append("updated_at = CURRENT_TIMESTAMP")
values.append(video_id)
query = f"UPDATE songs SET {', '.join(updates)} WHERE video_id = ?"
try:
cursor.execute(query, values)
conn.commit()
return cursor.rowcount > 0
except Exception as e:
conn.rollback()
print(f"Error al actualizar canción: {e}")
return False
def update_song_video_id(self, old_video_id: str, new_video_id: str, **kwargs) -> bool:
"""
Actualiza el video_id de una canción y opcionalmente otros campos.
Útil para actualizar canciones importadas con el video_id real de YouTube.
Args:
old_video_id: Video ID actual (ej: imported_xxx)
new_video_id: Nuevo video ID (ej: video_id real de YouTube)
**kwargs: Campos adicionales a actualizar
"""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
# Construir query de actualización
allowed_fields = ['url', 'title', 'artist', 'year', 'genre', 'decade', 'file_path',
'file_size', 'file_type', 'duration', 'thumbnail_url', 'description', 'download_source', 'bitrate_kbps', 'volume_lufs', 'volume_offset_db', 'waveform_data']
updates = ['video_id = ?']
values = [new_video_id]
for key, value in kwargs.items():
if key in allowed_fields:
updates.append(f"{key} = ?")
values.append(value)
updates.append("updated_at = CURRENT_TIMESTAMP")
values.append(old_video_id)
query = f"UPDATE songs SET {', '.join(updates)} WHERE video_id = ?"
try:
cursor.execute(query, values)
# También actualizar el historial si existe
cursor.execute('''
UPDATE download_history
SET video_id = ?
WHERE video_id = ?
''', (new_video_id, old_video_id))
conn.commit()
return cursor.rowcount > 0
except Exception as e:
conn.rollback()
print(f"Error al actualizar video_id de canción: {e}")
return False
def get_song_by_video_id(self, video_id: str) -> Optional[Dict]:
"""Obtiene una canción por su video_id."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM songs WHERE video_id = ?', (video_id,))
row = cursor.fetchone()
if row:
return dict(row)
return None
def get_song_by_file_path(self, file_path: str) -> Optional[Dict]:
"""Obtiene una canción por su ruta de archivo."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM songs WHERE file_path = ?', (str(file_path),))
row = cursor.fetchone()
if row:
return dict(row)
return None
def find_song(self, artist: Optional[str] = None, title: Optional[str] = None,
video_id: Optional[str] = None) -> List[Dict]:
"""
Busca canciones por artista, título o video_id.
Returns:
Lista de canciones que coinciden.
"""
conn = self._get_connection()
cursor = conn.cursor()
conditions = []
params = []
if video_id:
conditions.append("video_id = ?")
params.append(video_id)
if artist:
conditions.append("artist LIKE ?")
params.append(f"%{artist}%")
if title:
conditions.append("title LIKE ?")
params.append(f"%{title}%")
if not conditions:
return []
query = f"SELECT * FROM songs WHERE {' AND '.join(conditions)}"
cursor.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
def song_exists(self, video_id: Optional[str] = None,
artist: Optional[str] = None,
title: Optional[str] = None) -> bool:
"""
Verifica si una canción ya existe en la base de datos.
Args:
video_id: ID del video (más preciso)
artist: Nombre del artista
title: Título de la canción
Returns:
True si existe, False si no.
"""
if video_id:
song = self.get_song_by_video_id(video_id)
if song:
return True
if artist and title:
songs = self.find_song(artist=artist, title=title)
if songs:
return True
return False
def add_rejected_video(self, video_id: str, url: Optional[str] = None,
title: Optional[str] = None, reason: Optional[str] = None) -> bool:
"""Añade un video a la lista de rechazados."""
with self._lock: # Proteger operaciones de escritura
conn = self._get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO rejected_videos (video_id, url, title, reason)
VALUES (?, ?, ?, ?)
''', (video_id, url, title, reason))
# Registrar en historial
cursor.execute('''
INSERT INTO download_history (video_id, action, notes)
VALUES (?, 'rejected', ?)
''', (video_id, reason or "User rejected"))
conn.commit()
return True
except sqlite3.IntegrityError:
# Ya existe
conn.rollback()
return False
def is_rejected(self, video_id: str) -> bool:
"""Verifica si un video está rechazado."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('SELECT 1 FROM rejected_videos WHERE video_id = ?', (video_id,))
return cursor.fetchone() is not None
def get_all_rejected_videos(self, limit: Optional[int] = None) -> List[Dict]:
"""
Obtiene todas las canciones ignoradas/rechazadas.
Args:
limit: Número máximo de resultados
"""
conn = self._get_connection()
cursor = conn.cursor()
query = "SELECT * FROM rejected_videos ORDER BY rejected_at DESC"
if limit:
query += f" LIMIT {limit}"
cursor.execute(query)
return [dict(row) for row in cursor.fetchall()]
def remove_rejected_video(self, video_id: str) -> bool:
"""
Elimina un video de la lista de rechazados (designorar).
Args:
video_id: ID del video a designorar
Returns:
True si se eliminó correctamente, False si no se encontró.
"""
with self._lock: # Proteger operaciones de escritura
conn = self._get_connection()
cursor = conn.cursor()
try:
# Verificar si existe
cursor.execute('SELECT 1 FROM rejected_videos WHERE video_id = ?', (video_id,))
if not cursor.fetchone():
return False
# Eliminar de la tabla de rechazados
cursor.execute('DELETE FROM rejected_videos WHERE video_id = ?', (video_id,))
# Registrar en historial
cursor.execute('''
INSERT INTO download_history (video_id, action, notes)
VALUES (?, 'unrejected', ?)
''', (video_id, "Video unmarked as rejected"))
conn.commit()
return True
except Exception as e:
conn.rollback()
print(f"Error al designorar video: {e}")
return False
def get_all_songs(self, limit: Optional[int] = None,
genre: Optional[str] = None,
decade: Optional[str] = None,
search: Optional[str] = None) -> List[Dict]:
"""
Obtiene todas las canciones, opcionalmente filtradas.
Args:
limit: Número máximo de resultados
genre: Filtrar por género
decade: Filtrar por década
search: Texto libre a buscar en título, artista o género
"""
conn = self._get_connection()
cursor = conn.cursor()
conditions = []
params = []
if genre:
conditions.append("genre = ?")
params.append(genre)
if decade:
conditions.append("decade = ?")
params.append(decade)
if search:
conditions.append("(LOWER(title) LIKE ? OR LOWER(artist) LIKE ? OR LOWER(genre) LIKE ?)")
like = f"%{search.lower()}%"
params.extend([like, like, like])
query = "SELECT * FROM songs"
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY downloaded_at DESC"
if limit:
query += f" LIMIT {limit}"
cursor.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
def get_duplicate_songs(self) -> List[Dict]:
"""
Busca canciones duplicadas por título + artista (normalizado).
Devuelve una lista de grupos; cada grupo tiene 'key' (artista - título) y 'songs' (lista de canciones).
Solo se incluyen grupos con más de una canción.
"""
songs = self.get_all_songs(limit=None)
key_to_songs: Dict[str, List[Dict]] = {}
for song in songs:
title = (song.get('title') or '').strip()
artist = (song.get('artist') or '').strip()
norm_title = title.lower()
norm_artist = artist.lower()
key = f"{norm_artist}|||{norm_title}" if (norm_title or norm_artist) else f"_sin_metadato_{song.get('video_id', '')}"
if key not in key_to_songs:
key_to_songs[key] = []
key_to_songs[key].append(song)
groups = []
for key, group_songs in key_to_songs.items():
if len(group_songs) < 2:
continue
# Mostrar clave legible (artista - título) usando el primer elemento
first = group_songs[0]
label = f"{first.get('artist') or '(sin artista)'} - {first.get('title') or '(sin título)'}"
groups.append({
'key': label,
'count': len(group_songs),
'songs': group_songs
})
return groups
def get_statistics(self) -> Dict:
"""Obtiene estadísticas de la base de datos."""
conn = self._get_connection()
cursor = conn.cursor()
stats = {}
# Total de canciones
cursor.execute('SELECT COUNT(*) FROM songs')
stats['total_songs'] = cursor.fetchone()[0]
# Canciones por género
cursor.execute('''
SELECT genre, COUNT(*) as count
FROM songs
WHERE genre IS NOT NULL
GROUP BY genre
ORDER BY count DESC
''')
stats['by_genre'] = {row[0]: row[1] for row in cursor.fetchall()}
# Canciones por década
cursor.execute('''
SELECT decade, COUNT(*) as count
FROM songs
WHERE decade IS NOT NULL
GROUP BY decade
ORDER BY decade DESC
''')
stats['by_decade'] = {row[0]: row[1] for row in cursor.fetchall()}
# Total de rechazados
cursor.execute('SELECT COUNT(*) FROM rejected_videos')
stats['rejected_count'] = cursor.fetchone()[0]
# Tamaño total de archivos
cursor.execute('SELECT SUM(file_size) FROM songs WHERE file_size IS NOT NULL')
result = cursor.fetchone()[0]
stats['total_size_bytes'] = result if result else 0
return stats
def delete_song(self, video_id: str) -> Optional[Dict]:
"""
Elimina una canción de la base de datos.
Args:
video_id: ID del video a eliminar
Returns:
Diccionario con los datos de la canción eliminada (incluyendo file_path) si existe,
None si no se encontró.
"""
with self._lock: # Proteger operaciones de escritura
conn = self._get_connection()
cursor = conn.cursor()
# Primero obtener los datos de la canción antes de eliminarla
song = self.get_song_by_video_id(video_id)
if not song:
return None
try:
# Eliminar de la tabla de canciones
cursor.execute('DELETE FROM songs WHERE video_id = ?', (video_id,))
# Registrar en historial
cursor.execute('''
INSERT INTO download_history (video_id, action, notes)
VALUES (?, 'deleted', ?)
''', (video_id, f"Deleted: {song.get('title', 'Unknown')}"))
conn.commit()
return dict(song) # Devolver los datos de la canción eliminada
except Exception as e:
conn.rollback()
print(f"Error al eliminar canción: {e}")
return None
def get_cached_video_info(self, video_id: str) -> Optional[Dict]:
"""
Obtiene la información del video desde la caché.
Args:
video_id: ID del video de YouTube
Returns:
Diccionario con información del video o None si no está en caché
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('SELECT video_info FROM video_cache WHERE video_id = ?', (video_id,))
row = cursor.fetchone()
if row and row[0]:
try:
return json.loads(row[0])
except json.JSONDecodeError:
return None
return None
def get_cached_metadata(self, video_id: str) -> Optional[Dict]:
"""
Obtiene los metadatos desde la caché.
Args:
video_id: ID del video de YouTube
Returns:
Diccionario con metadatos o None si no está en caché
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('SELECT metadata FROM video_cache WHERE video_id = ?', (video_id,))
row = cursor.fetchone()
if row and row[0]:
try:
return json.loads(row[0])
except json.JSONDecodeError:
return None
return None
def get_cached_genre(self, video_id: str) -> Optional[str]:
"""
Obtiene el género desde la caché.
Args:
video_id: ID del video de YouTube
Returns:
Género como string o None si no está en caché
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('SELECT genre FROM video_cache WHERE video_id = ?', (video_id,))
row = cursor.fetchone()
if row and row[0]:
return row[0]
return None
def set_cached_video_info(self, video_id: str, video_info: Dict) -> bool:
"""
Guarda la información del video en la caché.
Args:
video_id: ID del video de YouTube
video_info: Diccionario con información del video
Returns:
True si se guardó correctamente
"""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
try:
video_info_json = json.dumps(video_info, default=str)
cursor.execute('''
INSERT INTO video_cache (video_id, video_info, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(video_id) DO UPDATE SET
video_info = excluded.video_info,
updated_at = CURRENT_TIMESTAMP
''', (video_id, video_info_json))
conn.commit()
return True
except Exception as e:
conn.rollback()
print(f"Error al guardar video_info en caché: {e}")
return False
def set_cached_metadata(self, video_id: str, metadata: Dict) -> bool:
"""
Guarda los metadatos en la caché.
Args:
video_id: ID del video de YouTube
metadata: Diccionario con metadatos
Returns:
True si se guardó correctamente
"""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
try:
metadata_json = json.dumps(metadata, default=str)
cursor.execute('''
INSERT INTO video_cache (video_id, metadata, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(video_id) DO UPDATE SET
metadata = excluded.metadata,
updated_at = CURRENT_TIMESTAMP
''', (video_id, metadata_json))
conn.commit()
return True
except Exception as e:
conn.rollback()
print(f"Error al guardar metadata en caché: {e}")
return False
def set_cached_genre(self, video_id: str, genre: str) -> bool:
"""
Guarda el género en la caché.
Args:
video_id: ID del video de YouTube
genre: Género como string
Returns:
True si se guardó correctamente
"""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO video_cache (video_id, genre, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(video_id) DO UPDATE SET
genre = excluded.genre,
updated_at = CURRENT_TIMESTAMP
''', (video_id, genre))
conn.commit()
return True
except Exception as e:
conn.rollback()
print(f"Error al guardar género en caché: {e}")
return False
def get_all_cached_data(self, video_id: str) -> Optional[Dict]:
"""
Obtiene todos los datos en caché para un video (info, metadata, genre).
Args:
video_id: ID del video de YouTube
Returns:
Diccionario con 'video_info', 'metadata', 'genre' o None si no está en caché
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT video_info, metadata, genre
FROM video_cache
WHERE video_id = ?
''', (video_id,))
row = cursor.fetchone()
if not row:
return None
result = {}
if row[0]: # video_info
try:
result['video_info'] = json.loads(row[0])
except json.JSONDecodeError:
pass
if row[1]: # metadata
try:
result['metadata'] = json.loads(row[1])
except json.JSONDecodeError:
pass
if row[2]: # genre
result['genre'] = row[2]
return result if result else None
def clear_cache(self, video_id: Optional[str] = None) -> bool:
"""
Limpia la caché. Si se proporciona video_id, solo limpia ese video.
Args:
video_id: ID del video específico o None para limpiar toda la caché
Returns:
True si se limpió correctamente
"""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
try:
if video_id:
cursor.execute('DELETE FROM video_cache WHERE video_id = ?', (video_id,))
else:
cursor.execute('DELETE FROM video_cache')
conn.commit()
return True
except Exception as e:
conn.rollback()
print(f"Error al limpiar caché: {e}")
return False
def close(self):
"""Cierra la conexión a la base de datos del thread actual."""
if hasattr(self._local, 'conn') and self._local.conn:
self._local.conn.close()
self._local.conn = None
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.close()