-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextto_web.py
More file actions
9995 lines (8794 loc) · 432 KB
/
Copy pathextto_web.py
File metadata and controls
9995 lines (8794 loc) · 432 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
#!/usr/bin/env python3
"""
EXTTO Web Interface v1.4 - FULL RESTORED (Original Features + Killswitch + Smart Search)
Backend Flask per la gestione via web di EXTTO
"""
from flask import Flask, render_template, jsonify, request, Response, stream_with_context
from flask_cors import CORS
import sqlite3
import os
import json
import re
import shutil
import time
import requests
import psutil
import socket
import threading # <--- AGGIUNGI QUESTA RIGA QUI
from urllib.parse import unquote
from datetime import datetime
from typing import List, Dict, Optional, Tuple
from threading import Thread
import queue
# ... resto degli import
try:
# Riusa parser/quality dell'engine per coerenza di riconoscimento
from core.models import Parser, Quality
except Exception as e:
print(f"⚠️ import core.models fallback: {e}")
Parser = None
Quality = None
import subprocess
import warnings
try:
from core.models import Parser, Quality
from core.constants import PORT as DEFAULT_ENGINE_PORT
import core.config_db as _cdb
except Exception as e:
print(f"⚠️ import core.constants fallback: {e}")
Parser = None
Quality = None
DEFAULT_ENGINE_PORT = 8889
def get_engine_port():
"""Legge la porta del motore dal file di configurazione, con salvagente."""
try:
cfg = parse_series_config()
return int(cfg.get('settings', {}).get('engine_port', DEFAULT_ENGINE_PORT))
except Exception as e:
logger.debug(f"get_engine_port: {e}")
return DEFAULT_ENGINE_PORT
app = Flask(__name__)
CORS(app)
RENAME_PROGRESS = {"status": "idle", "current": 0, "total": 0, "msg": ""}
_rename_progress_lock = threading.Lock()
_config_write_lock = threading.Lock() # Protegge operazioni read-modify-write sulla config
# Configurazione
# --- CONFIGURAZIONE PERCORSI ASSOLUTI ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_FILE = os.path.join(BASE_DIR, "extto_series.db")
ARCHIVE_FILE = os.path.join(BASE_DIR, "extto_archive.db")
CONFIG_FILE = os.path.join(BASE_DIR, "extto.conf")
SERIES_FILE = os.path.join(BASE_DIR, "series.txt")
MOVIES_FILE = os.path.join(BASE_DIR, "movies.txt")
LOG_FILE = os.path.join(BASE_DIR, "extto.log")
_LEGACY_FILE = os.path.join(BASE_DIR, "series_config.txt")
LANGUAGES_DIR = os.path.join(BASE_DIR, "languages")
POSTERS_DIR = os.path.join(BASE_DIR, "static", "posters")
TMDB_IMAGE_BASE = "https://image.tmdb.org/t/p/w300"
def _poster_file(item_type: str, item_id: int) -> str:
"""Restituisce il path assoluto del file poster su disco."""
prefix = {'series': 's', 'movie': 'm', 'comic': 'c'}.get(item_type, 'x')
return os.path.join(POSTERS_DIR, f"{prefix}_{item_id}.jpg")
def _poster_url(item_type: str, item_id: int) -> str:
"""Restituisce l'URL relativo del poster da servire al browser."""
prefix = {'series': 's', 'movie': 'm', 'comic': 'c'}.get(item_type, 'x')
return f"/static/posters/{prefix}_{item_id}.jpg"
def _save_poster(item_type: str, item_id: int, tmdb_poster_path: str) -> bool:
"""Scarica e salva il poster da TMDB se non esiste già. Ritorna True se salvato."""
if not tmdb_poster_path or not item_id:
return False
dest = _poster_file(item_type, item_id)
if os.path.exists(dest):
return True # già presente, non riscaricare
try:
os.makedirs(POSTERS_DIR, exist_ok=True)
url = f"{TMDB_IMAGE_BASE}{tmdb_poster_path}"
resp = requests.get(url, timeout=10)
if resp.status_code == 200 and resp.content:
with open(dest, 'wb') as f:
f.write(resp.content)
logger.debug(f"🖼️ Poster salvato: {dest}")
return True
except Exception as e:
logger.debug(f"_save_poster {item_type}/{item_id}: {e}")
return False
def _delete_poster(item_type: str, item_id: int) -> None:
"""Elimina il poster dal disco quando si cancella la serie/film."""
dest = _poster_file(item_type, item_id)
try:
if os.path.exists(dest):
os.remove(dest)
logger.debug(f"🗑️ Poster eliminato: {dest}")
except Exception as e:
logger.debug(f"_delete_poster {item_type}/{item_id}: {e}")
def _default_lang() -> str:
"""
Restituisce la lingua audio di default per nuove serie/film.
Legge 'default_language' dalla config DB.
Se non impostata (stringa vuota o assente) restituisce '' = nessun filtro lingua.
Configurabile dalla pagina Configurazione → Avanzate.
"""
try:
v = str(_cdb.get_setting('default_language', '')).strip().lower()
return v if v else 'ita'
except Exception:
return 'ita'
BACKUP_DIR = "backups"
# Queue per log streaming
log_queue = queue.Queue()
# ============================================================================
# DATABASE UTILITIES
# ============================================================================
import threading
import logging
# ---------------------------------------------------------------------------
# LOGGING SETUP — configura root logger + propaga a tutti i sottomoduli
# (core.comics, core.models, ecc.) così i loro logger.info/error appaiono
# ---------------------------------------------------------------------------
_log_formatter = logging.Formatter(
'[%(asctime)s] %(levelname)s %(name)s: %(message)s',
datefmt='%H:%M:%S'
)
_root_logger = logging.getLogger()
if not _root_logger.handlers:
# stderr — visibile in terminale/journalctl/supervisord
_sh = logging.StreamHandler()
_sh.setFormatter(_log_formatter)
_root_logger.addHandler(_sh)
# File handler aggiunto separatamente (sempre, anche se c'erano già handler)
# WatchedFileHandler: rileva se il file viene rinominato (es. da logrotate o dall'altro
# processo) e riapre extto.log, evitando che i log finiscano nel file rinominato.
_log_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'extto.log')
if not any(isinstance(h, logging.FileHandler) and getattr(h, 'baseFilename', '') == _log_file_path
for h in _root_logger.handlers):
try:
from logging.handlers import WatchedFileHandler as _WFH
_fh = _WFH(_log_file_path, encoding='utf-8')
_fh.setFormatter(_log_formatter)
_root_logger.addHandler(_fh)
except Exception as e:
print(f"⚠️ WatchedFileHandler setup: {e}")
pass
# Assicura che tutti i logger figli (core.*) propaghino al root
logging.getLogger('core').setLevel(logging.DEBUG)
logging.getLogger('core').propagate = True
_root_logger.setLevel(logging.INFO)
logger = logging.getLogger(__name__)
class ExtToDB:
"""Gestione database EXTTO - thread-safe via threading.local()
Ogni thread Flask ottiene la propria connessione SQLite, evitando
la condivisione di una singola connessione tra thread multipli.
WAL mode permette letture concorrenti senza bloccare le scritture.
"""
_local = threading.local()
def _get_conn(self):
if not getattr(self._local, 'conn', None):
if not os.path.exists(DB_FILE):
self._local.conn = None
return None
# Fix Bolla Temporale: aggiunto isolation_level=None
conn = sqlite3.connect(DB_FILE, check_same_thread=False, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=5000")
conn.execute("PRAGMA synchronous=NORMAL")
self._local.conn = conn
return self._local.conn
def _get_conn_archive(self):
"""Restituisce la connessione archivio del thread corrente."""
if not getattr(self._local, 'conn_archive', None):
if not os.path.exists(ARCHIVE_FILE):
self._local.conn_archive = None
return None
try:
# Fix Bolla Temporale: aggiunto isolation_level=None
conn = sqlite3.connect(ARCHIVE_FILE, check_same_thread=False, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=5000")
conn.execute("PRAGMA synchronous=NORMAL")
def regexp(expr, item):
try:
return 1 if re.search(expr, str(item), re.IGNORECASE) else 0
except Exception:
return 0 # regex malformata, tratta come no-match
conn.create_function("REGEXP", 2, regexp)
self._local.conn_archive = conn
except Exception as e:
logger.debug(f"conn_archive REGEXP setup: {e}")
logger.exception("Unable to open Archive DB")
self._local.conn_archive = None
return self._local.conn_archive
@property
def conn(self):
return self._get_conn()
@property
def conn_archive(self):
return self._get_conn_archive()
def __init__(self):
pass # Connessione creata al primo uso per thread
def connect(self):
"""Mantenuto per compatibilita', non fa nulla."""
pass
def get_stats(self) -> dict:
"""Statistiche generali"""
if not self.conn:
return {}
c = self.conn.cursor()
stats = {}
c.execute("SELECT COUNT(*) FROM series")
stats['series'] = c.fetchone()[0]
c.execute("SELECT COUNT(*) FROM movies WHERE removed_at IS NULL")
stats['movies'] = c.fetchone()[0]
c.execute("SELECT COUNT(*) FROM episodes")
stats['episodes'] = c.fetchone()[0]
c.execute("SELECT COUNT(*) FROM movies WHERE magnet_link IS NOT NULL")
stats['movie_downloads'] = c.fetchone()[0]
stats['downloads'] = stats['episodes'] + stats['movie_downloads']
# Ultima attività
c.execute("""
SELECT MAX(d) FROM (
SELECT MAX(downloaded_at) as d FROM episodes
UNION
SELECT MAX(downloaded_at) as d FROM movies
)
""")
last = c.fetchone()[0]
stats['last_activity'] = last if last else "N/A"
# Archivio
if self.conn_archive:
c_arch = self.conn_archive.cursor()
c_arch.execute("SELECT COUNT(*) FROM archive")
stats['archive_size'] = c_arch.fetchone()[0]
else:
stats['archive_size'] = 0
return stats
def get_all_series(self) -> List[dict]:
"""Lista di tutte le serie"""
if not self.conn:
return []
c = self.conn.cursor()
c.execute("""
SELECT s.id, s.name, s.quality_requirement,
COUNT(e.id) as episodes_count,
MAX(e.downloaded_at) as last_download,
(SELECT season FROM episodes
WHERE series_id=s.id
ORDER BY downloaded_at DESC LIMIT 1) as last_season,
(SELECT episode FROM episodes
WHERE series_id=s.id
ORDER BY downloaded_at DESC LIMIT 1) as last_episode
FROM series s
LEFT JOIN episodes e ON s.id = e.series_id
GROUP BY s.id
ORDER BY s.name COLLATE NOCASE
""")
return [dict(row) for row in c.fetchall()]
def get_series_episodes(self, series_id: int) -> List[dict]:
"""Episodi di una serie"""
if not self.conn:
return []
c = self.conn.cursor()
c.execute(
"""
SELECT e.id, e.season, e.episode, e.title, e.quality_score,
e.downloaded_at, e.is_repack, e.magnet_link,
CASE WHEN ap.series_id IS NOT NULL THEN 1 ELSE 0 END AS present_in_archive,
ap.best_quality_score AS archive_quality_score
FROM episodes e
LEFT JOIN episode_archive_presence ap
ON ap.series_id = e.series_id
AND ap.season = e.season
AND ap.episode = e.episode
WHERE e.series_id = ? AND e.episode > 0
ORDER BY e.season DESC, e.episode DESC
""",
(series_id,)
)
return [dict(row) for row in c.fetchall()]
def get_all_movies(self) -> List[dict]:
"""Lista di tutti i film scaricati/storico"""
if not self.conn:
return []
try:
c = self.conn.cursor()
c.execute("""
SELECT m.id, m.name, m.year, m.title,
CASE WHEN m.magnet_link IS NOT NULL THEN 1 ELSE 0 END as downloaded,
m.downloaded_at, m.quality_score
FROM movies m
WHERE m.removed_at IS NULL
ORDER BY m.downloaded_at DESC NULLS LAST, m.name COLLATE NOCASE
""")
return [dict(row) for row in c.fetchall()]
except Exception as e:
logger.error(f"Error reading movies table (old schema?): {e}")
# Fallback in caso manchi la colonna magnet_link in vecchi DB
try:
c.execute("SELECT * FROM movies ORDER BY id DESC")
return [dict(row) for row in c.fetchall()]
except Exception as e:
logger.debug(f"get_all_movies: {e}")
return []
def search_archive(self, query: str = "", offset: int = 0, limit: int = 50) -> Tuple[List[dict], int]:
"""Ricerca nell'archivio con supporto filtri avanzati (+/-)"""
if not self.conn_archive:
return [], 0
c = self.conn_archive.cursor()
conditions = []
params = []
if query:
query = query.strip()
# OPZIONE 1: Regex pura (se inizia con "rx:")
if query.startswith("rx:"):
conditions.append("title REGEXP ?")
params.append(query[3:].strip())
# OPZIONE 2: Ricerca "Smart" (+/- e Wildcards)
else:
keywords = query.split()
for kw in keywords:
exclude = False
if kw.startswith('-') and len(kw) > 1:
exclude = True
kw = kw[1:]
elif kw.startswith('+') and len(kw) > 1:
kw = kw[1:]
if '*' in kw or '?' in kw:
clean_kw = kw.replace('*', '%').replace('?', '_')
if exclude:
conditions.append("title NOT LIKE ?")
else:
conditions.append("title LIKE ?")
params.append(clean_kw)
else:
if exclude:
conditions.append("title NOT LIKE ?")
else:
conditions.append("title LIKE ?")
params.append(f"%{kw}%")
where_clause = ("WHERE " + " AND ".join(conditions)) if conditions else ""
try:
# 1. Conta totale
count_sql = f"SELECT COUNT(*) FROM archive {where_clause}"
c.execute(count_sql, tuple(params))
total = c.fetchone()[0]
# 2. Prendi risultati paginati
data_sql = f"""
SELECT id, title, magnet, added_at
FROM archive
{where_clause}
ORDER BY added_at DESC
LIMIT ? OFFSET ?
"""
query_params = tuple(params) + (limit, offset)
c.execute(data_sql, query_params)
items = [dict(row) for row in c.fetchall()]
return items, total
except Exception as e:
print(f"Errore ricerca archivio: {e}")
return [], 0
def delete_episode(self, episode_id: int):
"""Elimina un episodio"""
if not self.conn:
return
c = self.conn.cursor()
c.execute("DELETE FROM episodes WHERE id=?", (episode_id,))
self.conn.commit()
def delete_series(self, series_id: int):
"""Elimina una serie e tutti i suoi episodi"""
if not self.conn:
return
c = self.conn.cursor()
c.execute("DELETE FROM episodes WHERE series_id=?", (series_id,))
c.execute("DELETE FROM series WHERE id=?", (series_id,))
self.conn.commit()
def delete_movie(self, movie_id: int):
"""Soft-delete: marca il film come rimosso senza cancellarlo fisicamente,
così rimane visibile in Ultimi Download con il badge 'Rimosso dall'archivio'."""
if not self.conn:
return
from datetime import datetime, timezone
c = self.conn.cursor()
c.execute("UPDATE movies SET removed_at=? WHERE id=?",
(datetime.now(timezone.utc).isoformat(), movie_id))
self.conn.commit()
def get_series_stats(self) -> dict:
"""Statistiche aggregate per serie: ep scaricati, ultimo episodio, is_ended, is_completed."""
if not self.conn:
return {}
try:
from core.database import Database
with Database() as _db:
return _db.get_series_stats()
except Exception as e:
logger.error(f"get_series_stats: {e}")
return {}
def record_feed_match(self, series_id: int, season: int, episode: int,
title: str, quality_score: int,
fail_reason, magnet: str):
"""Delega a core.database.Database.record_feed_match."""
if not self.conn:
return
try:
from core.database import Database as _CoreDB
_CoreDB().record_feed_match(series_id, season, episode,
title, quality_score, fail_reason, magnet)
except Exception as e:
logger.warning(f"ExtToDB.record_feed_match: {e}")
def get_feed_matches(self, series_id: int, season: int, episode: int):
"""Delega a core.database.Database.get_feed_matches."""
try:
from core.database import Database as _CoreDB
return _CoreDB().get_feed_matches(series_id, season, episode)
except Exception as e:
logger.warning(f"ExtToDB.get_feed_matches: {e}")
return []
def record_movie_feed_match(self, movie_id: int, title: str,
quality_score: int, lang_bonus: int,
fail_reason, magnet: str):
"""Delega a core.database.Database.record_movie_feed_match."""
if not self.conn:
return
try:
from core.database import Database as _CoreDB
_CoreDB().record_movie_feed_match(movie_id, title, quality_score,
lang_bonus, fail_reason, magnet)
except Exception as e:
logger.warning(f"ExtToDB.record_movie_feed_match: {e}")
def get_movie_feed_matches(self, movie_name: str):
"""Delega a core.database.Database.get_movie_feed_matches."""
try:
from core.database import Database as _CoreDB
return _CoreDB().get_movie_feed_matches(movie_name)
except Exception as e:
logger.warning(f"ExtToDB.get_movie_feed_matches: {e}")
return []
def has_movie_feed_matches(self, movie_name: str):
"""Delega a core.database.Database.has_movie_feed_matches."""
try:
from core.database import Database as _CoreDB
return _CoreDB().has_movie_feed_matches(movie_name)
except Exception as e:
logger.warning(f"ExtToDB.has_movie_feed_matches: {e}")
return False
db = ExtToDB()
# ============================================================================
# CONFIG MANAGEMENT
# ============================================================================
def parse_series_config() -> dict:
"""Legge la configurazione da extto_config.db e dalla tabella series del DB operativo.
Mantiene l'interfaccia originale: restituisce {'settings': {...}, 'series': [...]}.
"""
settings = _cdb.get_all_settings()
series = _load_series_from_db_web()
return {'settings': settings, 'series': series}
def _load_series_from_db_web() -> list:
"""Carica le serie dalla tabella series del DB operativo."""
import sqlite3 as _sq
try:
with _sq.connect(DB_FILE) as conn:
conn.row_factory = _sq.Row
rows = conn.execute(
"""SELECT name, quality_requirement, seasons, language, enabled,
archive_path, timeframe, aliases, ignored_seasons,
tmdb_id, subtitle, season_subfolders, exclude
FROM series ORDER BY name"""
).fetchall()
result = []
for r in rows:
try:
aliases = json.loads(r['aliases'] or '[]')
except Exception:
aliases = []
try:
ignored = json.loads(r['ignored_seasons'] or '[]')
except Exception:
ignored = []
result.append({
'name': r['name'],
'seasons': r['seasons'] or '1+',
'quality': r['quality_requirement'] or 'any',
'language': r['language'] or _default_lang(),
'enabled': bool(r['enabled']) if r['enabled'] is not None else True,
'archive_path': r['archive_path'] or '',
'timeframe': int(r['timeframe'] or 0),
'aliases': aliases,
'ignored_seasons': ignored,
'tmdb_id': r['tmdb_id'] or '',
'subtitle': r['subtitle'] or '',
'season_subfolders': bool(r['season_subfolders']) if r['season_subfolders'] is not None else False,
'exclude': r['exclude'] or '',
})
return result
except Exception as e:
logger.warning(f"_load_series_from_db_web: {e}")
return []
def _save_series_to_db(series_list: list, sync_delete: bool = False) -> None:
"""Salva/aggiorna le serie nel DB operativo (tabella series).
sync_delete=True: rimuove anche le serie non presenti nella lista.
Usare SOLO per operazioni di eliminazione esplicita.
"""
import sqlite3 as _sq
conn = _sq.connect(DB_FILE)
conn.row_factory = _sq.Row
try:
for s in series_list:
aliases_json = json.dumps(s.get('aliases', []), ensure_ascii=False)
ignored_json = json.dumps(s.get('ignored_seasons', []), ensure_ascii=False)
conn.execute(
"""INSERT INTO series
(name, quality_requirement, seasons, language, enabled,
archive_path, timeframe, aliases, ignored_seasons, tmdb_id, subtitle,
season_subfolders, exclude)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(name) DO UPDATE SET
quality_requirement = excluded.quality_requirement,
seasons = excluded.seasons,
language = excluded.language,
enabled = excluded.enabled,
archive_path = excluded.archive_path,
timeframe = excluded.timeframe,
aliases = excluded.aliases,
ignored_seasons = excluded.ignored_seasons,
tmdb_id = excluded.tmdb_id,
subtitle = excluded.subtitle,
season_subfolders = excluded.season_subfolders,
exclude = excluded.exclude
""",
(
s['name'],
s.get('quality', s.get('qual', 'any')),
s.get('seasons', '1+'),
s.get('language', s.get('lang', 'ita')),
1 if s.get('enabled', True) else 0,
s.get('archive_path', ''),
int(s.get('timeframe', 0) or 0),
aliases_json,
ignored_json,
str(s.get('tmdb_id', '') or ''),
str(s.get('subtitle', '') or ''),
1 if s.get('season_subfolders', False) else 0,
str(s.get('exclude', '') or ''),
)
)
# Rimuove le serie non più presenti (solo se sync_delete=True)
if sync_delete and series_list:
names_in_list = [s['name'] for s in series_list]
placeholders = ','.join('?' * len(names_in_list))
conn.execute(
f"DELETE FROM series WHERE name NOT IN ({placeholders})",
names_in_list
)
conn.commit()
finally:
conn.close()
def _parse_series_line_into(line: str, series_list: list):
"""Parsa una riga serie e la appende a series_list."""
parts = [p.strip() for p in line.split('|')]
if len(parts) < 5:
return
item = {
'name': parts[0],
'seasons': parts[1],
'quality': parts[2],
'language': parts[3],
'enabled': parts[4] == 'yes',
}
for ex in parts[5:]:
ex = ex.strip()
if not ex:
continue
if ex.startswith('timeframe:'):
m = re.search(r'timeframe:(\d+)h', ex)
if m:
try:
item['timeframe'] = int(m.group(1))
except Exception:
pass # timeframe non numerico, ignorato
elif ex.startswith('alias='):
item['aliases'] = [a.strip() for a in ex.split('=', 1)[1].split(',') if a.strip()]
elif ex.startswith('ignored:'):
item['ignored_seasons'] = [
int(x.strip()) for x in ex.split(':', 1)[1].split(',')
if x.strip().isdigit()
]
# AGGIUNGI QUESTE DUE RIGHE:
elif ex.startswith('tmdb='):
item['tmdb_id'] = ex.split('=', 1)[1].strip()
elif ex.startswith('subtitle='):
item['subtitle'] = ex.split('=', 1)[1].strip()
# -------------------------
elif 'archive_path' not in item:
item['archive_path'] = ex
series_list.append(item)
def save_series_config(config: dict) -> bool:
"""Salva la configurazione su extto_config.db e sulla tabella series del DB operativo.
NON scrive più su extto.conf o series.txt (migrazione a DB completata in v40).
"""
try:
settings = config.get('settings', {})
_cdb.set_settings_bulk(settings)
except Exception as e:
logger.error(f"save_series_config settings: {e}")
return False
try:
_save_series_to_db(config.get('series', []))
except Exception as e:
logger.error(f"save_series_config series: {e}")
return False
return True
def _qbt_ok(r) -> bool:
"""Verifica che una risposta qBittorrent indichi successo.
Compatibile con tutte le versioni:
- qBittorrent < 5.2.0: HTTP 200 con body 'Ok.'
- qBittorrent ≥ 5.2.0: HTTP 204 con body vuoto (WEBAPI: Send 204 when WebAPI
response contains no data — introdotto in 5.2.0)
"""
if r is None:
return False
if r.status_code == 204:
return True
if r.status_code == 200 and r.text.strip() in ('Ok.', 'Ok', ''):
return True
return False
def _atomic_write(path: str, content: str) -> None:
"""Scrive content su path in modo atomico tramite file temporaneo."""
import tempfile
dir_path = os.path.dirname(os.path.abspath(path))
fd, tmp = tempfile.mkstemp(dir=dir_path, prefix='.extto_', suffix='.tmp')
try:
with os.fdopen(fd, 'w', encoding='utf-8') as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
except Exception as e:
logger.warning(f"safe_save_config: {e}")
try:
os.unlink(tmp)
except OSError:
pass
raise
def _save_extto_conf(config: dict) -> bool:
"""Scrive extto.conf con tutte le impostazioni (senza le serie)."""
try:
settings = config.get('settings', {})
written_keys = set()
lines = []
lines.append("# " + "=" * 76)
lines.append("# EXTTO - Configurazione")
lines.append("# " + "=" * 76)
lines.append("")
groups = [
("CLIENT TORRENT: LIBTORRENT (EMBEDDED)", ["libtorrent_"]),
("CLIENT ESTERNI: QBITTORRENT, TRANSMISSION, ARIA2, RQBIT",
["qbittorrent_", "transmission_", "aria2_", "rqbit_"]),
("NOTIFICHE: TELEGRAM & EMAIL", ["notify_", "telegram_", "email_"]),
("NOTIFICHE: JELLYFIN, PLEX & EMBY", ["jellyfin_", "plex_", "emby_"]),
("MOTORE: JACKETT, RICERCA E AVANZATE",
["jackett_", "prowlarr_", "flaresolverr_", "websearch_", "min_free_space", "gap_filling", "max_age",
"stop_on_", "debug_", "archive_", "rename_episodes", "rename_format", "move_episodes",
"jackett_save_to_archive", "prowlarr_save_to_archive", "tmdb_language",
"backup_dir", "backup_retention", "backup_schedule", "refresh_interval",
"comics_", "web_port", "engine_port", "cleanup_upgrades", "trash_path", "cleanup_min_score_diff", "trash_retention_days"]),
("PUNTEGGI E QUALITÀ (SCORES)", ["score_", "auto_remove_completed"]), # <--- AGGIUNGI QUESTA RIGA
]
for group_name, prefixes in groups:
# Abbiamo rimosso 'and k in KNOWN_SETTINGS' per permettere il salvataggio
# dinamico di opzioni nuove inviate dall'interfaccia web.
keys_to_write = sorted(
k for k, v in settings.items()
if k not in written_keys
and not isinstance(v, list)
and any(k.startswith(p) for p in prefixes)
)
if keys_to_write:
lines.append(f"# --- {group_name} ---")
for k in keys_to_write:
lines.append(f"@{k} = {settings[k]}")
lines.append("")
written_keys.update(keys_to_write)
# Qualsiasi altra opzione che non rientra nei prefissi precedenti finisce qui,
# senza essere scartata, grazie alla rimozione di 'KNOWN_SETTINGS'
leftover = sorted(
k for k, v in settings.items()
if k not in written_keys
and not isinstance(v, list)
)
if leftover:
lines.append("# --- ALTRE IMPOSTAZIONI ---")
for k in leftover:
lines.append(f"@{k} = {settings[k]}")
lines.append("")
lines.append("# " + "=" * 76)
lines.append("# SORGENTI, REGOLE E CARTELLE RADICE")
lines.append("# " + "=" * 76)
list_keys = [
("archive_root", "Cartelle radice dell'archivio (opzionali)"),
("archive_cred", "Credenziali per montaggi remoti (PREFIX|user|pass)"),
("url", "URL Sorgenti (ExtTo, Corsaro)"),
("blacklist", "Parole vietate nei titoli (es: cam, ts)"),
("wantedlist", "Parole obbligatorie nei titoli"),
("content_filter", "Filtro categorie contenuti (es: xxx, anime, hentai)"),
("custom_score", "Punteggi Personalizzati (Parola:Punti)"),
]
for key, desc in list_keys:
vals = settings.get(key, [])
if isinstance(vals, list) and vals:
lines.append(f"\n# {desc}")
for item in vals:
lines.append(f"@{key} = {item}")
lines.append("")
# NON scrive più su file — configurazione migrata a extto_config.db (v40)
# _atomic_write(CONFIG_FILE, "\n".join(lines) + "\n")
return True
except Exception as e:
logger.error(f"Error saving extto.conf: {e}")
return False
def _save_series_list(config: dict) -> bool:
"""Scrive series.txt con il solo elenco delle serie TV."""
try:
lines = []
lines.append("# " + "=" * 76)
lines.append("# EXTTO - Serie TV monitorate")
lines.append("# Formato: Nome | Stagioni | Qualità | Lingua | Enabled"
" | Path (opzionale) | timeframe:Xh | alias=... | ignored:N,M | tmdb=ID | subtitle=SIGLA")
lines.append("# " + "=" * 76)
lines.append("")
for serie in sorted(config.get('series', []), key=lambda s: s.get('name', '').lower()):
enabled = 'yes' if serie.get('enabled', True) else 'no'
archive_path = serie.get('archive_path', '').strip()
timeframe = int(serie.get('timeframe', 0) or 0)
aliases = serie.get('aliases', [])
ignored = serie.get('ignored_seasons', [])
line = (f"{serie['name']} | {serie['seasons']} | "
f"{serie['quality']} | {serie['language']} | {enabled}")
if archive_path:
line += f" | {archive_path}"
if timeframe > 0:
line += f" | timeframe:{timeframe}h"
if aliases:
line += f" | alias={','.join(aliases)}"
if ignored:
line += f" | ignored:{','.join(map(str, ignored))}"
# AGGIUNGI QUESTE DUE RIGHE:
if serie.get('tmdb_id'):
line += f" | tmdb={serie['tmdb_id']}"
if serie.get('subtitle'):
line += f" | subtitle={serie['subtitle']}"
# -------------------------
lines.append(line)
lines.append("")
# NON scrive più su file — serie migrate a extto_series.db (v40)
# _atomic_write(SERIES_FILE, "\n".join(lines) + "\n")
# Sync aliases nel DB
try:
import sqlite3 as _sqlite3
_conn = _sqlite3.connect(DB_FILE)
_c2 = _conn.cursor()
for serie in config.get('series', []):
_aliases_json = json.dumps(serie.get('aliases', []), ensure_ascii=False)
_c2.execute(
"UPDATE series SET aliases=? WHERE LOWER(name)=LOWER(?)",
(_aliases_json, serie['name'])
)
_conn.commit()
except Exception as _e:
logger.warning(f"Sync aliases DB: {_e}")
finally:
try: _conn.close()
except Exception: pass
return True
except Exception as e:
logger.error(f"Error saving series.txt: {e}")
return False
def parse_movies_config() -> List[dict]:
"""Legge i film configurati da extto_config.db."""
raw = _cdb.get_movies_config()
return [
{
'name': m['name'],
'year': m['year'],
'quality': m['quality'],
'language': m['language'],
'enabled': bool(m['enabled']),
'subtitle': m['subtitle'],
'exclude': m.get('exclude', ''),
}
for m in raw
]
def save_movies_config(movies: List[dict]) -> bool:
"""Salva i film in extto_config.db."""
try:
_cdb.save_movies_config(movies)
return True
except Exception as e:
logger.error(f"save_movies_config: {e}")
return False
# ============================================================================
# LOG STREAMING & UTILS
# ============================================================================
def tail_log_file():
"""Tail del file di log per streaming"""
if not os.path.exists(LOG_FILE):
return
with open(LOG_FILE, 'r', encoding='utf-8') as f:
# Vai alla fine
f.seek(0, 2)
while True:
line = f.readline()
if line:
log_queue.put(line)
else:
time.sleep(0.5)
# --- MODIFICA: API per interfacce di rete (Killswitch) ---
@app.route('/api/network/interfaces')
def get_network_interfaces():
"""Rileva le interfacce di rete del sistema (Cross-Platform)"""
interfaces = {}
try:
# Usa psutil che funziona su Windows, Mac e Linux!
net_if_addrs = psutil.net_if_addrs()
for iface_name, addrs in net_if_addrs.items():
itype = 'Ethernet'
iface_lower = iface_name.lower()
# Deduzione del tipo dal nome (valido per la maggior parte dei sistemi)
if iface_lower.startswith(('wl', 'wi-fi', 'airport')): itype = 'WiFi'
elif iface_lower.startswith(('tun', 'wg', 'ppp', 'utun')): itype = 'VPN'
elif iface_lower.startswith('lo'): itype = 'Loopback'
ip = 'N/A'
# Cerca l'indirizzo IPv4 (AF_INET)
for addr in addrs:
if addr.family == socket.AF_INET:
ip = addr.address
break
if ip != 'N/A' and itype != 'Loopback': # Opzionale: puoi escludere il Loopback
interfaces[iface_name] = {'ip': ip, 'type': itype}
except Exception as e:
logger.exception("Error detecting network interfaces")
return jsonify({'error': str(e)}), 500
return jsonify({'interfaces': interfaces})
@app.route('/api/manual-search', methods=['GET'])
def manual_search():
try:
query = request.args.get('q', '').strip()
if not query:
return jsonify({'success': False, 'error': 'Query vuota'}), 400
from core.engine import Engine
from core.config import Config
from core.models import Parser as _Parser
_parser = Parser or _Parser
eng = Engine()
cfg = Config()
# 1. Ricerca Live (Jackett/Scraper esterni)
live_results = eng.perform_manual_search(query, cfg.urls)
# 2. Ricerca "Smart" nell'Archivio Locale (Supporto +/-)
archive_items, _ = db.search_archive(query, limit=100)
archive_results = []
for row in archive_items:
# Calcola il quality score dal titolo (evita score=0 fisso che
# impedisce l'inserimento in episode_feed_matches quando i 4 slot sono pieni)
try:
_aq = _Parser.parse_quality(row['title'])
_ascore = _aq.score() if _aq else 0
except Exception as e:
logger.debug(f"parse_quality archive row: {e}")
_ascore = 0
archive_results.append({
'title': row['title'],
'magnet': row['magnet'],
'source': 'Archivio Locale',
'score': _ascore
})