forked from Audionut/Upload-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupload.py
More file actions
2123 lines (1823 loc) · 102 KB
/
upload.py
File metadata and controls
2123 lines (1823 loc) · 102 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
# Upload Assistant © 2025 Audionut & wastaken7 — Licensed under UAPL v1.0
import asyncio
import contextlib
import gc
import json
import os
import platform
import re
import shutil
import signal
import sys
import threading
import time
import traceback
from collections.abc import Iterable, Mapping
from pathlib import Path
from typing import Any, Optional, cast
import aiofiles
import cli_ui
import discord
import requests
from packaging import version
from torf import Torrent
from typing_extensions import TypeAlias
from bin.get_mkbrr import MkbrrBinaryManager
from cogs.redaction import Redaction
from discordbot import DiscordNotifier
from src.add_comparison import ComparisonManager
from src.args import Args
from src.cleanup import cleanup_manager
from src.clients import Clients
from src.console import console
from src.disc_menus import process_disc_menus
from src.dupe_checking import DupeChecker
from src.get_desc import gen_desc
from src.get_name import NameManager
from src.get_tracker_data import TrackerDataManager
from src.languages import languages_manager
from src.nfo_link import NfoLinkManager
from src.qbitwait import Wait
from src.queuemanage import QueueManager
from src.takescreens import TakeScreensManager
from src.torrentcreate import TorrentCreator
from src.trackerhandle import process_trackers
from src.trackers.AR import AR
from src.trackers.COMMON import COMMON
from src.trackers.PTP import PTP
from src.trackersetup import TRACKER_SETUP, api_trackers, http_trackers, other_api_trackers, tracker_class_map
from src.trackerstatus import TrackerStatusManager
from src.uphelper import UploadHelper
from src.uploadscreens import UploadScreensManager
cli_ui.setup(color='always', title="Upload Assistant")
base_dir = os.path.abspath(os.path.dirname(__file__))
# Global state for shutdown handling (reset via _reset_shutdown_state() for in-process runs)
_shutdown_requested = False
_is_webui_mode = False
_webui_server = None # Reference to waitress server for graceful shutdown
_shutdown_event = threading.Event() # Event for coordinating graceful shutdown
def _reset_shutdown_state() -> None:
"""Reset global shutdown state for clean in-process runs from web UI."""
global _shutdown_requested, _is_webui_mode, _webui_server
_shutdown_requested = False
_is_webui_mode = False
_webui_server = None
_shutdown_event.clear()
def _handle_shutdown_signal(signum: int, _frame: Any) -> None:
"""Handle SIGTERM/SIGINT for graceful shutdown."""
global _shutdown_requested, _webui_server
signal_name = 'SIGTERM' if signum == signal.SIGTERM else 'SIGINT'
if not _shutdown_requested:
_shutdown_requested = True
console.print(f"\n[yellow]Received {signal_name}, shutting down gracefully...[/yellow]")
# Signal shutdown event (for webui thread coordination)
_shutdown_event.set()
# If running webui, close the server (main thread handles exit via event)
if _webui_server is not None:
with contextlib.suppress(Exception):
_webui_server.close()
else:
# Non-webui mode: raise to let asyncio handle task cancellation
raise KeyboardInterrupt
else:
# Second signal = force exit
console.print("[red]Forced exit[/red]")
sys.exit(1)
# ── Restore built-in data/ files when a Docker volume mount hides them ──
# The Dockerfile copies the original data/ tree to defaults/data/ so that
# volume mounts over /Upload-Assistant/data/ don't lose critical files
# (__init__.py, version.py, example-config.py, templates/).
_data_dir = os.path.join(base_dir, "data")
_defaults_data_dir = os.path.join(base_dir, "defaults", "data")
# Directories that should never be copied into user-facing data/
_SKIP_DIRS = {"__pycache__", ".mypy_cache", ".ruff_cache"}
if os.path.isdir(_defaults_data_dir):
os.makedirs(_data_dir, exist_ok=True)
_restored_count = 0
_restore_errors: list[str] = []
# Walk the defaults tree and copy anything missing in the live data dir.
# Never overwrite user files (config.py, cookies/, tags.json, etc.).
for dirpath, dirnames, filenames in os.walk(_defaults_data_dir):
# Prune unwanted directories in-place so os.walk skips them entirely
dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS]
rel_dir = os.path.relpath(dirpath, _defaults_data_dir)
target_dir = os.path.join(_data_dir, rel_dir) if rel_dir != "." else _data_dir
try:
os.makedirs(target_dir, exist_ok=True)
except OSError as exc:
_restore_errors.append(f"mkdir {rel_dir}: {exc}")
continue # skip this subtree if we can't create the directory
for fname in filenames:
# Skip bytecode and cache files
if fname.endswith((".pyc", ".pyo")):
continue
target_file = os.path.join(target_dir, fname)
if not os.path.exists(target_file):
src_file = os.path.join(dirpath, fname)
try:
shutil.copy2(src_file, target_file)
_restored_count += 1
except OSError as exc:
_restore_errors.append(f"{os.path.join(rel_dir, fname)}: {exc}")
if _restored_count:
console.print(f"Restored {_restored_count} built-in file(s) into data/ from defaults.", markup=False)
if _restore_errors:
console.print(f"[red]Warning: failed to restore {len(_restore_errors)} file(s) into data/:[/red]")
for _err in _restore_errors[:5]:
console.print(f"[red] {_err}[/red]")
if len(_restore_errors) > 5:
console.print(f"[red] ... and {len(_restore_errors) - 5} more[/red]")
console.print("[yellow]Hint: ensure the mounted data/ directory is writable by the container user.[/yellow]")
console.print("[yellow] e.g. on the host: chown -R 1000:1000 /path/to/data[/yellow]")
_config_path = os.path.join(_data_dir, "config.py")
# Detect -webui or --webui forms, including --webui=host:port
_is_webui_arg = any(
(arg == "-webui" or arg == "--webui" or arg.startswith("-webui=") or arg.startswith("--webui="))
for arg in sys.argv
)
# Auto-create config.py from example on first WebUI start
if _is_webui_arg and not os.path.exists(_config_path):
_example_config_path = os.path.join(_data_dir, "example-config.py")
if os.path.exists(_example_config_path):
console.print("No config.py found. Creating default config from example-config.py...", markup=False)
try:
shutil.copy2(_example_config_path, _config_path)
console.print("Default config created successfully!", markup=False)
except Exception as e:
console.print(f"Failed to create default config: {e}", markup=False)
console.print("Continuing without config file...", markup=False)
Meta: TypeAlias = dict[str, Any]
from src.prep import Prep # noqa: E402
# Enable ANSI colors on Windows
_use_colors = True
if sys.platform == "win32":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
# Enable VIRTUAL_TERMINAL_PROCESSING
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
except Exception:
_use_colors = False
# Color codes (empty strings if colors not supported)
_RED = "\033[91m" if _use_colors else ""
_YELLOW = "\033[93m" if _use_colors else ""
_GREEN = "\033[92m" if _use_colors else ""
_RESET = "\033[0m" if _use_colors else ""
def _print_config_error(error_type: str, message: str, lineno: Optional[int] = None,
text: Optional[str] = None, offset: Optional[int] = None,
suggestion: Optional[str] = None) -> None:
"""Print a formatted config error message."""
console.print(f"{_RED}{error_type} in config.py:{_RESET}", markup=False)
if lineno:
console.print(f"{_RED} Line {lineno}: {message}{_RESET}", markup=False)
if text:
console.print(f"{_YELLOW} {text.rstrip()}{_RESET}", markup=False)
if offset:
console.print(f"{_YELLOW} {' ' * (offset - 1)}^{_RESET}", markup=False)
else:
console.print(f"{_RED} {message}{_RESET}", markup=False)
if suggestion:
console.print(f"{_GREEN} Suggestion: {suggestion}{_RESET}", markup=False)
console.print(f"\n{_RED}Reference: https://github.com/Audionut/Upload-Assistant/blob/master/data/example-config.py{_RESET}", markup=False)
config: dict[str, Any]
if os.path.exists(_config_path):
try:
from data.config import config as _imported_config # pyright: ignore[reportMissingImports,reportUnknownVariableType]
config = cast(dict[str, Any], _imported_config)
parser = Args(config)
client = Clients(config)
name_manager = NameManager(config)
tracker_data_manager = TrackerDataManager(config)
nfo_link_manager = NfoLinkManager(config)
takescreens_manager = TakeScreensManager(config)
uploadscreens_manager = UploadScreensManager(config)
use_discord = False
discord_cfg_obj = config.get('DISCORD')
discord_config: Optional[dict[str, Any]] = cast(dict[str, Any], discord_cfg_obj) if isinstance(discord_cfg_obj, dict) else None
if discord_config is not None:
use_discord = bool(discord_config.get('use_discord', False))
except SyntaxError as e:
_print_config_error(
"Syntax error",
str(e.msg) if e.msg else "Invalid syntax",
lineno=e.lineno,
text=e.text,
offset=e.offset
)
console.print(f"\n{_RED}Common syntax issues:{_RESET}", markup=False)
console.print(f"{_YELLOW} - Missing comma between dictionary items{_RESET}", markup=False)
console.print(f"{_YELLOW} - Missing closing bracket, brace, quote or comma{_RESET}", markup=False)
console.print(f"{_YELLOW} - Unclosed string (missing quote at end){_RESET}", markup=False)
sys.exit(1)
except NameError as e:
# Extract line number from traceback
import traceback
tb = traceback.extract_tb(sys.exc_info()[2])
lineno = tb[-1].lineno if tb else None
text = tb[-1].line if tb else None
# Check for common mistakes
suggestion = None
error_str = str(e)
if "'true'" in error_str.lower():
suggestion = "Use 'True' (capital T) instead of 'true'"
elif "'false'" in error_str.lower():
suggestion = "Use 'False' (capital F) instead of 'false'"
elif "'null'" in error_str.lower() or "'none'" in error_str.lower():
suggestion = "Use 'None' (capital N) instead of 'null' or 'none'"
elif "is not defined" in error_str:
# Extract the undefined name from the error message
import re as _re
match = _re.search(r"name '([^']+)' is not defined", error_str)
if match:
undefined_name = match.group(1)
suggestion = f"Did you forget quotes? Try \"{undefined_name}\" instead of '{undefined_name}'"
_print_config_error(
"Name error",
str(e),
lineno=lineno,
text=text,
suggestion=suggestion
)
sys.exit(1)
except TypeError as e:
import traceback
tb = traceback.extract_tb(sys.exc_info()[2])
lineno = tb[-1].lineno if tb else None
text = tb[-1].line if tb else None
_print_config_error(
"Type error",
str(e),
lineno=lineno,
text=text
)
console.print(f"\n{_RED}Common type issues:{_RESET}", markup=False)
console.print(f"{_YELLOW} - Using unhashable type as dictionary key{_RESET}", markup=False)
console.print(f"{_YELLOW} - Incorrect data structure nesting{_RESET}", markup=False)
sys.exit(1)
except Exception as e:
import traceback
tb = traceback.extract_tb(sys.exc_info()[2])
lineno = tb[-1].lineno if tb else None
text = tb[-1].line if tb else None
_print_config_error(
"Error",
str(e),
lineno=lineno,
text=text
)
sys.exit(1)
else:
console.print(f"{_RED}Configuration file 'config.py' not found.{_RESET}", markup=False)
console.print(f"{_RED}Please ensure the file is located at: {_YELLOW}{_config_path}{_RESET}", markup=False)
console.print(f"{_RED}Follow the setup instructions: https://github.com/Audionut/Upload-Assistant{_RESET}", markup=False)
sys.exit(1)
async def merge_meta(meta: Meta, saved_meta: Meta) -> dict[str, Any]:
"""Merges saved metadata with the current meta, respecting overwrite rules."""
overwrite_list = [
'trackers', 'dupe', 'debug', 'anon', 'category', 'type', 'screens', 'nohash', 'manual_edition', 'imdb', 'tmdb_manual', 'mal', 'manual',
'hdb', 'ptp', 'blu', 'no_season', 'no_aka', 'no_year', 'no_dub', 'no_tag', 'no_seed', 'client', 'description_link', 'description_file', 'desc', 'draft',
'modq', 'region', 'freeleech', 'personalrelease', 'unattended', 'manual_season', 'manual_episode', 'torrent_creation', 'qbit_tag', 'qbit_cat',
'skip_imghost_upload', 'imghost', 'manual_source', 'webdv', 'hardcoded-subs', 'dual_audio', 'manual_type', 'tvmaze_manual'
]
sanitized_saved_meta: dict[str, Any] = {}
for key, value in saved_meta.items():
clean_key = key.strip().strip("'").strip('"')
if clean_key in overwrite_list:
if clean_key in meta and meta.get(clean_key) is not None:
sanitized_saved_meta[clean_key] = meta[clean_key]
if meta.get('debug', False):
console.print(f"Overriding {clean_key} with meta value:", meta[clean_key])
else:
sanitized_saved_meta[clean_key] = value
else:
sanitized_saved_meta[clean_key] = value
meta.update(sanitized_saved_meta)
return sanitized_saved_meta
async def print_progress(message: str, interval: int = 10) -> None:
"""Prints a progress message every `interval` seconds until cancelled."""
try:
while True:
await asyncio.sleep(interval)
console.print(message)
except asyncio.CancelledError:
pass
def update_oeimg_to_onlyimage() -> None:
"""Update all img_host_* values from 'oeimg' to 'onlyimage' in the config file."""
config_path = f"{base_dir}/data/config.py"
with open(config_path, encoding="utf-8") as f:
content = f.read()
new_content = re.sub(
r"(['\"]img_host_\d+['\"]\s*:\s*)['\"]oeimg['\"]",
r"\1'onlyimage'",
content
)
new_content = re.sub(
r"(['\"])(oeimg_api)(['\"]\s*:)",
r"\1onlyimage_api\3",
new_content
)
if new_content != content:
with open(config_path, "w", encoding="utf-8") as f:
f.write(new_content)
console.print("[green]Updated 'oeimg' to 'onlyimage' and 'oeimg_api' to 'onlyimage_api' in config.py[/green]")
else:
console.print("[yellow]No 'oeimg' or 'oeimg_api' found to update in config.py[/yellow]")
async def validate_tracker_logins(meta: Meta, trackers: Optional[list[str]] = None) -> None:
if 'tracker_status' not in meta:
meta['tracker_status'] = {}
if not trackers:
return
# Filter trackers that are in both the list and tracker_class_map
valid_trackers = [tracker for tracker in trackers if tracker in tracker_class_map and tracker in http_trackers]
# RTF/PTP are not HTTP trackers but need validation
if "RTF" in trackers:
valid_trackers.append("RTF")
if "PTP" in trackers:
valid_trackers.append("PTP")
if valid_trackers:
async def validate_single_tracker(tracker_name: str) -> tuple[str, bool]:
"""Validate credentials for a single tracker."""
try:
if tracker_name not in meta['tracker_status']:
meta['tracker_status'][tracker_name] = {}
tracker_class = tracker_class_map[tracker_name](config=config)
if meta['debug']:
console.print(f"[cyan]Validating {tracker_name} credentials...[/cyan]")
if tracker_name == "RTF":
login = await tracker_class.api_test(meta)
elif tracker_name == "PTP":
login = await tracker_class.get_AntiCsrfToken(meta)
else:
login = await tracker_class.validate_credentials(meta)
if not login:
meta['tracker_status'][tracker_name]['skipped'] = True
return tracker_name, login
except Exception as e:
console.print(f"[red]Error validating {tracker_name}: {e}[/red]")
meta['tracker_status'][tracker_name]['skipped'] = True
return tracker_name, False
# Run all tracker validations concurrently
await asyncio.gather(*[validate_single_tracker(tracker) for tracker in valid_trackers])
async def process_meta(meta: Meta, base_dir: str, bot: Any = None) -> None:
"""Process the metadata for each queued path."""
if use_discord and bot:
await DiscordNotifier.send_discord_notification(
config, bot, f"Starting upload process for: {meta['path']}", debug=meta.get('debug', False), meta=meta
)
if meta['imghost'] is None:
meta['imghost'] = config['DEFAULT']['img_host_1']
try:
has_oeimg_config = any(
config['DEFAULT'].get(key) == "oeimg"
for key in config['DEFAULT']
if key.startswith("img_host_")
)
if has_oeimg_config:
console.print("[red]oeimg is now onlyimage, your config is being updated[/red]")
update_oeimg_to_onlyimage()
except Exception as e:
console.print(f"[red]Error checking image hosts: {e}[/red]")
return
if not meta['unattended']:
ua = config['DEFAULT'].get('auto_mode', False)
if str(ua).lower() == "true":
meta['unattended'] = True
console.print("[yellow]Running in Auto Mode")
prep = Prep(screens=meta['screens'], img_host=meta['imghost'], config=config)
try:
meta = await prep.gather_prep(meta=meta, mode='cli')
except Exception as e:
console.print(f"Error in gather_prep: {e}")
console.print(traceback.format_exc())
return
meta['emby_debug'] = meta.get('emby_debug') if meta.get('emby_debug', False) else config['DEFAULT'].get('emby_debug', False)
if meta.get('emby_cat', None) == "movie" and meta.get('category', None) != "MOVIE":
console.print(f"[red]Wrong category detected! Expected 'MOVIE', but found: {meta.get('category', None)}[/red]")
meta['we_are_uploading'] = False
return
elif meta.get('emby_cat', None) == "tv" and meta.get('category', None) != "TV":
console.print("[red]TV content is not supported at this time[/red]")
meta['we_are_uploading'] = False
return
# If unattended confirm and we had to get metadata ids from filename searching, skip the quick return so we can prompt about database information
if meta.get('emby', False) and not meta.get('no_ids', False) and not meta.get('unattended_confirm', False) and meta.get('unattended', False):
await nfo_link_manager.nfo_link(meta)
meta['we_are_uploading'] = False
return
parser = Args(config)
helper = UploadHelper(config)
raw_trackers = meta.get('trackers')
trackers: list[str]
if isinstance(raw_trackers, list):
raw_trackers_list = cast(list[Any], raw_trackers)
trackers = [t for t in raw_trackers_list if isinstance(t, str)]
elif isinstance(raw_trackers, str):
trackers = [t.strip().upper() for t in raw_trackers.split(',') if t.strip()]
meta['trackers'] = trackers
else:
trackers = []
if not meta.get('emby', False):
if meta.get('trackers_remove', False):
remove_list = [t.strip().upper() for t in meta['trackers_remove'].split(',')]
for tracker in remove_list:
if tracker in meta['trackers']:
meta['trackers'].remove(tracker)
meta['name_notag'], meta['name'], meta['clean_name'], meta['potential_missing'] = await name_manager.get_name(meta)
if meta['debug']:
console.print(f"Trackers list before editing: {meta['trackers']}")
async with aiofiles.open(f"{meta['base_dir']}/tmp/{meta['uuid']}/meta.json", 'w', encoding='utf-8') as f:
await f.write(json.dumps(meta, indent=4))
if meta.get('emby_debug', False):
meta['original_imdb'] = meta.get('imdb_id', None)
meta['original_tmdb'] = meta.get('tmdb_id', None)
meta['original_mal'] = meta.get('mal_id', None)
meta['original_tvmaze'] = meta.get('tvmaze_id', None)
meta['original_tvdb'] = meta.get('tvdb_id', None)
meta['original_category'] = meta.get('category', None)
if 'matched_tracker' not in meta:
await client.get_pathed_torrents(meta['path'], meta)
if meta['is_disc']:
search_term = os.path.basename(meta['path'])
search_file_folder = 'folder'
else:
search_term = os.path.basename(meta['filelist'][0]) if meta['filelist'] else None
search_file_folder = 'file'
await tracker_data_manager.get_tracker_data(
meta['video'], meta, search_term, search_file_folder, meta['category'], only_id=meta['only_id']
)
editargs_tracking: tuple[str, ...] = ()
previous_trackers = meta.get('trackers', [])
try:
confirm = await helper.get_confirmation(meta)
except EOFError:
console.print("\n[red]Exiting on user request (Ctrl+C)[/red]")
await cleanup_manager.cleanup()
cleanup_manager.reset_terminal()
sys.exit(1)
while confirm is False:
try:
editargs_str = cli_ui.ask_string("Input args that need correction e.g. (--tag NTb --category tv --tmdb 12345)")
except EOFError:
console.print("\n[red]Exiting on user request (Ctrl+C)[/red]")
await cleanup_manager.cleanup()
cleanup_manager.reset_terminal()
sys.exit(1)
if editargs_str == "continue":
break
if not editargs_str or not editargs_str.strip():
console.print("[yellow]No input provided. Please enter arguments, type `continue` to continue or press Ctrl+C to exit.[/yellow]")
continue
try:
editargs = tuple(editargs_str.split())
except AttributeError:
console.print("[red]Bad input detected[/red]")
confirm = False
continue
# Tracks multiple edits
editargs_tracking = editargs_tracking + editargs
# Carry original args over, let parse handle duplicates
meta, _help, _before_args = cast(
tuple[Meta, Any, Any],
parser.parse(list(' '.join(sys.argv[1:]).split(' ')) + list(editargs_tracking), meta)
)
if not meta.get('trackers'):
meta['trackers'] = previous_trackers
if isinstance(meta.get('trackers'), str):
if "," in meta['trackers']:
meta['trackers'] = [t.strip().upper() for t in meta['trackers'].split(',')]
else:
meta['trackers'] = [meta['trackers'].strip().upper()]
elif isinstance(meta.get('trackers'), list):
meta['trackers'] = [t.strip().upper() for t in meta['trackers'] if isinstance(t, str)]
if meta['debug']:
console.print(f"Trackers list during edit process: {meta['trackers']}")
meta['edit'] = True
meta = await prep.gather_prep(meta=meta, mode='cli')
meta['name_notag'], meta['name'], meta['clean_name'], meta['potential_missing'] = await name_manager.get_name(meta)
try:
confirm = await helper.get_confirmation(meta)
except EOFError:
console.print("\n[red]Exiting on user request (Ctrl+C)[/red]")
await cleanup_manager.cleanup()
cleanup_manager.reset_terminal()
sys.exit(1)
if meta.get('emby', False):
if not meta['debug']:
await nfo_link_manager.nfo_link(meta)
meta['we_are_uploading'] = False
return
if 'remove_trackers' in meta and meta['remove_trackers']:
removed: list[str] = []
remove_trackers_list = (
[t for t in meta['remove_trackers'] if isinstance(t, str)]
if isinstance(meta.get('remove_trackers'), list)
else [str(meta['remove_trackers'])]
)
for tracker in remove_trackers_list:
if tracker in meta['trackers']:
if meta['debug']:
console.print(f"[DEBUG] Would have removed {tracker} found in client")
else:
meta['trackers'].remove(tracker)
removed.append(tracker)
if removed:
console.print(f"[yellow]Removing trackers already in your client: {', '.join(removed)}[/yellow]")
if not meta['trackers']:
console.print("[red]No trackers remain after removal.[/red]")
successful_trackers = 0
meta['skip_uploading'] = 10
else:
console.print(f"[green]Processing {meta['name']} for upload...[/green]")
# reset trackers after any removals
trackers = meta['trackers']
audio_prompted = False
for tracker in ["AITHER", "ASC", "BJS", "BT", "CBR", "DP", "FF", "GPW", "HUNO", "IHD", "LDU", "LT", "OE", "PTS", "SAM", "SHRI", "SPD", "TTR", "TVC", "ULCX"]:
if tracker in trackers:
if not audio_prompted:
await languages_manager.process_desc_language(meta, tracker=tracker)
audio_prompted = True
else:
if 'tracker_status' not in meta:
meta['tracker_status'] = {}
if tracker not in meta['tracker_status']:
meta['tracker_status'][tracker] = {}
if meta.get('unattended_audio_skip', False) or meta.get('unattended_subtitle_skip', False):
meta['tracker_status'][tracker]['skip_upload'] = True
else:
meta['tracker_status'][tracker]['skip_upload'] = False
await asyncio.sleep(0.2)
async with aiofiles.open(f"{meta['base_dir']}/tmp/{meta['uuid']}/meta.json", 'w', encoding='utf-8') as f:
await f.write(json.dumps(meta, indent=4))
await asyncio.sleep(0.2)
try:
await validate_tracker_logins(meta, trackers)
await asyncio.sleep(0.2)
except Exception as e:
console.print(f"[yellow]Warning: Tracker validation encountered an error: {e}[/yellow]")
successful_trackers = await TrackerStatusManager(config=config).process_all_trackers(meta)
if meta.get('trackers_pass') is not None:
meta['skip_uploading'] = meta.get('trackers_pass')
else:
tracker_pass_checks = config['DEFAULT'].get('tracker_pass_checks')
if isinstance(tracker_pass_checks, (int, str)):
meta['skip_uploading'] = int(tracker_pass_checks)
else:
meta['skip_uploading'] = 1
skip_uploading = meta.get('skip_uploading')
skip_uploading_int = int(skip_uploading) if isinstance(skip_uploading, (int, str)) else 0
if successful_trackers < skip_uploading_int and not meta['debug']:
console.print(f"[red]Not enough successful trackers ({successful_trackers}/{skip_uploading_int}). No uploads being processed.[/red]")
else:
meta['we_are_uploading'] = True
common = COMMON(config)
if meta.get('site_check', False):
tracker_status = cast(dict[str, dict[str, Any]], meta.get('tracker_status', {}))
for tracker in meta['trackers']:
upload_status = tracker_status.get(tracker, {}).get('upload', False)
if not upload_status:
if tracker == "AITHER" and meta.get('aither_trumpable') and len(meta.get('aither_trumpable', [])) > 0:
pass
else:
continue
if tracker not in tracker_status:
continue
log_path = f"{base_dir}/tmp/{tracker}_search_results.json"
if not await common.path_exists(log_path):
await common.makedirs(os.path.dirname(log_path))
search_data: list[dict[str, Any]] = []
if os.path.exists(log_path):
try:
async with aiofiles.open(log_path, encoding='utf-8') as f:
content = await f.read()
loaded: Any = json.loads(content) if content.strip() else []
search_data = [e for e in cast(list[Any], loaded) if isinstance(e, dict)] if isinstance(loaded, list) else []
except Exception:
search_data = []
existing_uuids = {entry.get('uuid') for entry in search_data}
if meta['uuid'] not in existing_uuids:
search_entry = {
'uuid': meta['uuid'],
'path': meta.get('path', ''),
'imdb_id': meta.get('imdb_id', 0),
'tmdb_id': meta.get('tmdb_id', 0),
'tvdb_id': meta.get('tvdb_id', 0),
'mal_id': meta.get('mal_id', 0),
'tvmaze_id': meta.get('tvmaze_id', 0),
}
if tracker == "AITHER":
search_entry['trumpable'] = meta.get('aither_trumpable', '')
search_data.append(search_entry)
async with aiofiles.open(log_path, 'w', encoding='utf-8') as f:
await f.write(json.dumps(search_data, indent=4))
meta['we_are_uploading'] = False
return
filename: str = meta.get('title', '')
bdmv_filename = meta.get('filename', '')
bdinfo = meta.get('bdinfo', '')
file_list = [str(p) for p in cast(list[Any], meta.get('filelist', [])) if str(p)]
videopath: str = file_list[0] if file_list else ""
console.print(f"Processing {filename} for upload.....")
meta['frame_overlay'] = config['DEFAULT'].get('frame_overlay', False)
tracker_status_map = cast(dict[str, dict[str, Any]], meta.get('tracker_status', {}))
for tracker in ['AZ', 'CZ', 'PHD']:
upload_status = tracker_status_map.get(tracker, {}).get('upload', False)
if tracker in meta['trackers'] and meta['frame_overlay'] and upload_status is True:
meta['frame_overlay'] = False
console.print("[yellow]AZ, CZ, and PHD do not allow frame overlays. Frame overlay will be disabled for this upload.[/yellow]")
bdmv_mi_created = False
for tracker in ["ANT", "DC", "HUNO", "LCD"]:
upload_status = tracker_status_map.get(tracker, {}).get('upload', False)
if tracker in trackers and upload_status is True and not bdmv_mi_created:
await common.get_bdmv_mediainfo(meta)
bdmv_mi_created = True
progress_task = asyncio.create_task(print_progress("[yellow]Still processing, please wait...", interval=10))
try:
if 'manual_frames' not in meta:
meta['manual_frames'] = ""
manual_frames = meta['manual_frames']
if meta.get('comparison', False):
await ComparisonManager(meta, config).add_comparison()
else:
image_data_file = f"{meta['base_dir']}/tmp/{meta['uuid']}/image_data.json"
if os.path.exists(image_data_file) and not meta.get('image_list'):
try:
async with aiofiles.open(image_data_file, encoding='utf-8') as img_file:
content = await img_file.read()
image_data = cast(dict[str, Any], json.loads(content)) if content.strip() else {}
if 'image_list' in image_data and not meta.get('image_list'):
meta['image_list'] = image_data['image_list']
if meta.get('debug'):
console.print(f"[cyan]Loaded {len(image_data['image_list'])} previously saved image links")
if 'image_sizes' in image_data and not meta.get('image_sizes'):
meta['image_sizes'] = image_data['image_sizes']
if meta.get('debug'):
console.print("[cyan]Loaded previously saved image sizes")
if 'tonemapped' in image_data and not meta.get('tonemapped'):
meta['tonemapped'] = image_data['tonemapped']
if meta.get('debug'):
console.print("[cyan]Loaded previously saved tonemapped status[/cyan]")
except Exception as e:
console.print(f"[yellow]Could not load saved image data: {str(e)}")
if meta.get('is_disc', ""):
menus_data_file = f"{meta['base_dir']}/tmp/{meta['uuid']}/menu_images.json"
if os.path.exists(menus_data_file):
try:
async with aiofiles.open(menus_data_file, encoding='utf-8') as menus_file:
content = await menus_file.read()
menu_image_file = cast(dict[str, Any], json.loads(content)) if content.strip() else {}
if 'menu_images' in menu_image_file and not meta.get('menu_images'):
meta['menu_images'] = menu_image_file['menu_images']
if meta.get('debug'):
console.print(f"[cyan]Loaded {len(menu_image_file['menu_images'])} previously saved disc menus")
except Exception as e:
console.print(f"[yellow]Could not load saved menu image data: {str(e)}")
elif meta.get('path_to_menu_screenshots', ""):
await process_disc_menus(meta, config)
# Take Screenshots
try:
if meta['is_disc'] == "BDMV":
use_vs = meta.get('vapoursynth', False)
try:
await takescreens_manager.disc_screenshots(
meta, bdmv_filename, bdinfo, meta['uuid'], base_dir, use_vs,
meta.get('image_list', []), meta.get('ffdebug', False), 0
)
except asyncio.CancelledError as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception("Error during screenshot capture") from e
except Exception as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception(f"Error during screenshot capture: {e}") from e
elif meta['is_disc'] == "DVD":
try:
await takescreens_manager.dvd_screenshots(
meta,
disc_num=0,
num_screens=0,
retry_cap=False
)
except asyncio.CancelledError as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception("Error during screenshot capture") from e
except Exception as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception(f"Error during screenshot capture: {e}") from e
else:
try:
if meta['debug']:
console.print(f"videopath: {videopath}, filename: {filename}, meta: {meta['uuid']}, base_dir: {base_dir}, manual_frames: {manual_frames}")
await takescreens_manager.screenshots(
videopath, filename, meta['uuid'], base_dir, meta,
manual_frames=manual_frames # Pass additional kwargs directly
)
except asyncio.CancelledError as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception("Error during screenshot capture") from e
except Exception as e:
console.print(traceback.format_exc())
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
if "workers" in str(e):
console.print("[red]max workers issue, see https://github.com/Audionut/Upload-Assistant/wiki/ffmpeg---max-workers-issues[/red]")
raise Exception(f"Error during screenshot capture: {e}") from e
except asyncio.CancelledError as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception("Error during screenshot capture") from e
except Exception as e:
await cleanup_screenshot_temp_files(meta)
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
raise Exception("Error during screenshot capture") from e
finally:
await asyncio.sleep(0.1)
await cleanup_manager.cleanup()
gc.collect()
cleanup_manager.reset_terminal()
if 'image_list' not in meta:
meta['image_list'] = []
manual_frames_str = meta.get('manual_frames', '')
if isinstance(manual_frames_str, str):
manual_frames_list = [f.strip() for f in manual_frames_str.split(',') if f.strip()]
manual_frames_count = len(manual_frames_list)
if meta['debug']:
console.print(f"Manual frames entered: {manual_frames_count}")
else:
manual_frames_count = 0
if manual_frames_count > 0:
meta['screens'] = manual_frames_count
cutoff = int(meta.get('cutoff') or 1)
if len(meta.get('image_list', [])) < cutoff and meta.get('skip_imghost_upload', False) is False:
# Validate and (if needed) rehost images to tracker-approved hosts before uploading any new screenshots.
trackers_with_image_host_requirements = {'A4K', 'BHD', 'DC', 'GPW', 'HUNO', 'MTV', 'OE', 'PTP', 'STC', 'TVC'}
relevant_trackers = [
t for t in cast(list[Any], meta.get('trackers', []))
if isinstance(t, str) and t in trackers_with_image_host_requirements and t in tracker_class_map
]
# If all relevant trackers share exactly one common approved host that the user has configured,
# and it's not the initially selected host, switch meta['imghost'] to that common host.
# If multiple common hosts exist, pick the first by config priority (img_host_1..img_host_9).
allowed_hosts: Optional[list[str]] = None
if relevant_trackers:
try:
tracker_instances = {
tracker_name: tracker_class_map[tracker_name](config=config)
for tracker_name in relevant_trackers
}
if meta.get('debug'):
console.print(f"[cyan]Image host debug: meta['imghost']={meta.get('imghost')} img_host_1={config['DEFAULT'].get('img_host_1')}[/cyan]")
console.print(f"[cyan]Image host debug: relevant_trackers={relevant_trackers}[/cyan]")
default_cfg_obj = config.get('DEFAULT', {})
default_cfg: dict[str, Any] = cast(dict[str, Any], default_cfg_obj) if isinstance(default_cfg_obj, dict) else {}
configured_hosts: list[str] = []
for host_index in range(1, 10):
host_key = f'img_host_{host_index}'
if host_key in default_cfg:
host = default_cfg.get(host_key)
if host and host not in configured_hosts:
configured_hosts.append(str(host))
if meta.get('debug'):
console.print(f"[cyan]Image host debug: configured_hosts={configured_hosts}[/cyan]")
approved_sets: list[set[str]] = []
all_known = True
for tracker_name in relevant_trackers:
tracker_instance = tracker_instances[tracker_name]
approved_hosts = getattr(tracker_instance, 'approved_image_hosts', None)
if not approved_hosts:
all_known = False
break
if isinstance(approved_hosts, (list, set, tuple)):
approved_hosts_list = [
str(host)
for host in cast(Iterable[Any], approved_hosts)
]
approved_sets.append(set(approved_hosts_list))
else:
all_known = False
break
if meta.get('debug'):
console.print(
f"[cyan]Image host debug: {tracker_name}.approved_image_hosts={approved_hosts_list}[/cyan]"
)
if all_known and approved_sets and configured_hosts:
common_hosts: set[str] = set()
for host_set in approved_sets:
if not common_hosts:
common_hosts = set(host_set)
else:
common_hosts &= host_set
common_configured_hosts = [h for h in configured_hosts if h in common_hosts]
if meta.get('debug'):
console.print(f"[cyan]Image host debug: common_hosts={sorted(common_hosts)}[/cyan]")
console.print(f"[cyan]Image host debug: common_configured_hosts={common_configured_hosts}[/cyan]")
# If we have any common hosts, use them as allowed_hosts for upload_screens
if common_configured_hosts:
allowed_hosts = common_configured_hosts
elif common_hosts:
allowed_hosts = sorted(common_hosts)
# Prefer the user-selected host if it's valid for all relevant trackers; otherwise
# fall back to the first common configured host by config priority (img_host_1..img_host_9).
current_img_host = str(meta.get('imghost') or config['DEFAULT'].get('img_host_1') or "")
preferred_host: Optional[str] = None
if common_configured_hosts and current_img_host not in common_configured_hosts:
preferred_host = common_configured_hosts[0]
elif common_hosts and current_img_host not in common_hosts:
preferred_host = sorted(common_hosts)[0]
if preferred_host and preferred_host != meta.get('imghost'):
if meta.get('debug'):
console.print(
f"[cyan]Image host debug: current host '{current_img_host}' is not common to all trackers; "
f"switching meta['imghost'] from '{meta.get('imghost')}' to '{preferred_host}'.[/cyan]"
)
meta['imghost'] = preferred_host
elif meta.get('debug'):
console.print(
f"[cyan]Image host debug: cannot compute common host (all_known={all_known}, approved_sets={len(approved_sets)}, configured_hosts={len(configured_hosts)}).[/cyan]"
)
except Exception as e:
if meta.get('debug'):
console.print(f"[yellow]Could not determine a common approved image host: {e}[/yellow]")
if meta.get('debug'):
image_list_for_debug = cast(list[Any], meta.get('image_list') or [])
console.print(
f"[cyan]Image host debug: pre-upload_screens meta['imghost']={meta.get('imghost')} image_list={len(image_list_for_debug)} cutoff={meta.get('cutoff')} screens={meta.get('screens')}[/cyan]" # noqa: E501
)
return_dict: dict[str, Any] = {}
try:
default_cfg_obj = config.get('DEFAULT', {})
default_cfg = cast(dict[str, Any], default_cfg_obj) if isinstance(default_cfg_obj, dict) else {}
min_successful_uploads = int(default_cfg.get('min_successful_image_uploads', 3))
host_order: list[str] = []
for host_index in range(1, 10):
host_key = f'img_host_{host_index}'
host = default_cfg.get(host_key)