forked from wastaken7/Upload-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.py
More file actions
2578 lines (2224 loc) · 124 KB
/
Copy pathupload.py
File metadata and controls
2578 lines (2224 loc) · 124 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 filecmp
import gc
import glob
import json
import os
import platform
import re
import shlex
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, cast
from src.check_requirements import check_dependencies
check_dependencies()
import logging
import aiofiles
import cli_ui
import discord
import requests
from packaging import version
from torf import Torrent
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.audio_spectrogram import process_audio_spectrograms
from src.book_prep import _resolve_book_language, detect_newspaper, is_valid_book_language
from src.cleanup import cleanup_manager
from src.clients import Clients
from src.console import current_release_log_path, logger
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.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
logger.info(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
logger.info("[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"}
# Built-in metadata files that should track the image version even when
# /Upload-Assistant/data is a persistent volume from an older container.
_ALWAYS_SYNC_ROOT_FILES = {"version.py"}
if os.path.isdir(_defaults_data_dir):
os.makedirs(_data_dir, exist_ok=True)
_restored_count = 0
_synced_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.).
# Root version.py is image metadata, not user config, so keep it current.
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)
src_file = os.path.join(dirpath, fname)
should_sync = False
if rel_dir == "." and fname in _ALWAYS_SYNC_ROOT_FILES and os.path.exists(target_file):
try:
should_sync = not filecmp.cmp(src_file, target_file, shallow=False)
except OSError:
should_sync = True
if not os.path.exists(target_file) or should_sync:
try:
shutil.copy2(src_file, target_file)
if should_sync:
_synced_count += 1
else:
_restored_count += 1
except OSError as exc:
_restore_errors.append(f"{os.path.join(rel_dir, fname)}: {exc}")
if _restored_count:
logger.info(f"Restored {_restored_count} built-in file(s) into data/ from defaults.", extra={"markup": False})
if _synced_count:
logger.info(f"Synced {_synced_count} built-in metadata file(s) into data/ from defaults.", extra={"markup": False})
if _restore_errors:
logger.warning(f"[red]Warning: failed to restore {len(_restore_errors)} file(s) into data/:[/red]")
for _err in _restore_errors[:5]:
logger.info(f"[red] {_err}[/red]")
if len(_restore_errors) > 5:
logger.info(f"[red] ... and {len(_restore_errors) - 5} more[/red]")
logger.info("[yellow]Hint: ensure the mounted data/ directory is writable by the container user.[/yellow]")
logger.info("[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):
logger.info("No config.py found. Creating default config from example_config.py...", extra={"markup": False})
try:
shutil.copy2(_example_config_path, _config_path)
logger.info("Default config created successfully!", extra={"markup": False})
except Exception as e:
logger.info(f"Failed to create default config: {e}", extra={"markup": False})
logger.info("Continuing without config file...", extra={"markup": False})
from src.book_prep import sanitize_book_author, sanitize_book_language # noqa: E402
from src.meta import Meta # noqa: E402
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: int | None = None,
text: str | None = None, offset: int | None = None,
suggestion: str | None = None) -> None:
"""Print a formatted config error message."""
logger.info(f"{_RED}{error_type} in config.py:{_RESET}", extra={"markup": False})
if lineno:
logger.info(f"{_RED} Line {lineno}: {message}{_RESET}", extra={"markup": False})
if text:
logger.info(f"{_YELLOW} {text.rstrip()}{_RESET}", extra={"markup": False})
if offset:
logger.info(f"{_YELLOW} {' ' * (offset - 1)}^{_RESET}", extra={"markup": False})
else:
logger.info(f"{_RED} {message}{_RESET}", extra={"markup": False})
if suggestion:
logger.info(f"{_GREEN} Suggestion: {suggestion}{_RESET}", extra={"markup": False})
logger.info(f"\n{_RED}Reference: https://github.com/Audionut/Upload-Assistant/blob/master/data/example_config.py{_RESET}", extra={"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)
takescreens_manager = TakeScreensManager(config)
uploadscreens_manager = UploadScreensManager(config)
use_discord = False
discord_cfg_obj = config.get('DISCORD')
discord_config: dict[str, Any] | None = 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", e.msg if e.msg else "Invalid syntax", lineno=e.lineno, text=e.text, offset=e.offset)
logger.info(f"\n{_RED}Common syntax issues:{_RESET}", extra={"markup": False})
logger.info(f"{_YELLOW} - Missing comma between dictionary items{_RESET}", extra={"markup": False})
logger.info(f"{_YELLOW} - Missing closing bracket, brace, quote or comma{_RESET}", extra={"markup": False})
logger.info(f"{_YELLOW} - Unclosed string (missing quote at end){_RESET}", extra={"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
)
logger.info(f"\n{_RED}Common type issues:{_RESET}", extra={"markup": False})
logger.info(f"{_YELLOW} - Using unhashable type as dictionary key{_RESET}", extra={"markup": False})
logger.info(f"{_YELLOW} - Incorrect data structure nesting{_RESET}", extra={"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:
logger.info(f"{_RED}Configuration file 'config.py' not found.{_RESET}", extra={"markup": False})
logger.info(f"{_RED}Please ensure the file is located at: {_YELLOW}{_config_path}{_RESET}", extra={"markup": False})
logger.info(f"{_RED}Follow the setup instructions: https://github.com/Audionut/Upload-Assistant{_RESET}", extra={"markup": False})
sys.exit(1)
async def merge_meta(meta: Meta, saved_meta: dict[str, Any]) -> dict[str, Any]:
"""Merges saved metadata with the current meta, respecting overwrite rules."""
overwrite_list = [
"anon", "asin", "audiobook_bitrate", "audiobook_duration_formatted", "audiobook_duration", "author", "blu", "book_asin",
"book_author", "book_isbn", "book_language_iso", "book_language", "book_publisher", "book_title", "category", "client",
"comic", "debug", "desc", "description_file", "description_link", "draft", "dual_audio", "dupe", "freeleech", "game_region",
"game_subcategory", "game_system", "game_version", "hardcoded-subs", "hdb", "igdb_manual", "imdb", "imghost", "isbn",
"keywords", "magazine", "mal", "manga", "manual_edition", "manual_episode", "manual_platform", "manual_season", "manual_source",
"manual_type", "manual_year", "manual", "modq", "narrator", "newspaper", "no_aka", "no_dub", "no_season", "no_seed", "no_tag",
"no_year", "nohash", "openlibrary", "personalrelease", "platform", "ptp", "qbit_cat", "qbit_tag", "region", "screens", "skip_imghost_upload",
"steam_manual", "title", "tmdb_manual", "torrent_creation", "trackers", "tvmaze_manual", "type", "unattended", "webdv", "year",
] # fmt: off
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 getattr(meta, clean_key, None) is not None:
sanitized_saved_meta[clean_key] = meta[clean_key]
logger.debug(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)
sanitize_book_language(meta)
sanitize_book_author(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)
logger.info(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)
logger.info("[green]Updated 'oeimg' to 'onlyimage' and 'oeimg_api' to 'onlyimage_api' in config.py[/green]")
else:
logger.info("[yellow]No 'oeimg' or 'oeimg_api' found to update in config.py[/yellow]")
async def validate_tracker_logins(meta: Meta, trackers: list[str] | None = 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:
status_dict = meta.tracker_status
if tracker_name not in status_dict:
status_dict[tracker_name] = {}
tracker_class = tracker_class_map[tracker_name](config=config)
logger.debug(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:
status_dict[tracker_name]["skipped"] = True
return tracker_name, login
except Exception as e:
status_dict = meta.tracker_status
logger.error(f"[red]Error validating {tracker_name}: {e}[/red]")
status_dict[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 _prompt_book_meta(meta: Meta) -> None:
"""Prompt the user to fill in missing BOOK metadata fields (title, author, year, language).
Runs only in interactive (attended) mode. When any field is filled in the
torrent name is rebuilt so the confirmation screen and the per-tracker
uploads reflect the new values.
"""
book_required_fields = ["title", "author", "year", "book_language"]
if meta.audiobook and ("CBR" in meta.trackers or "ZNTH" in meta.trackers):
book_required_fields.append("narrator")
book_missing = []
for f in book_required_fields:
val = getattr(meta, f, None)
if not val or str(val).strip().lower() in ("", "none", "null"):
book_missing.append(f)
elif f == "book_language":
iso = meta.book_language_iso
if not is_valid_book_language(str(val), iso):
book_missing.append(f)
if not book_missing:
return
if meta.unattended:
logger.info(
f"[yellow]BOOK upload: the following required fields are missing: "
f"{', '.join(book_missing)}. "
f"Re-run with -btitle / -author / -year / -blang to supply them, "
f"or trackers that require them will be skipped.[/yellow]"
)
return
logger.info("\n[bold yellow]The following fields are required:[/bold yellow]")
name_needs_rebuild = False
try:
for field in book_missing:
prompt_label = "language" if field == "book_language" else field
if field == "book_language":
while True:
value = (cli_ui.ask_string("Enter language (leave blank to skip): ") or "").strip()
if not value:
break
full, iso = _resolve_book_language(value)
if is_valid_book_language(full, iso):
meta.book_language = full
meta.book_language_iso = iso
name_needs_rebuild = True
break
else:
logger.info("[red]Invalid language. Please try again.[/red]")
elif field == "year":
while True:
value = (cli_ui.ask_string("Enter year (leave blank to skip): ") or "").strip()
if not value:
break
if value.isdigit() and len(value) == 4 and 1000 <= int(value) <= 3000:
meta.year = int(value)
meta.search_year = value
name_needs_rebuild = True
break
else:
logger.info("[red]Invalid year (must be a 4-digit number between 1000 and 3000). Please try again.[/red]")
else:
value = (cli_ui.ask_string(f"Enter {prompt_label} (leave blank to skip): ") or "").strip()
if value:
meta[field] = value
name_needs_rebuild = True
except EOFError:
logger.info("[yellow]Input cancelled — continuing with missing book fields.[/yellow]")
name_needs_rebuild = False
sanitize_book_language(meta)
sanitize_book_author(meta)
# Rebuild the torrent name so the confirmation screen and upload reflect the new values
if name_needs_rebuild:
detect_newspaper(meta)
meta.name_notag, meta.name, meta.clean_name, meta.potential_missing = await name_manager.get_name(meta)
async def _prompt_game_meta(meta: Meta) -> None:
"""Prompt the user to fill in missing GAME metadata fields (title, year, platform).
Runs only in interactive (attended) mode. When any field is filled, the
torrent name is rebuilt so the confirmation screen and the per-tracker
uploads reflect the new values.
"""
game_required_fields = ["title", "year", "platform", "game_version", "game_subcategory"]
game_missing = []
for f in game_required_fields:
val = getattr(meta, f, None)
if not val or str(val).strip().lower() in ("", "none", "null") or f == "platform" and "," in str(val):
game_missing.append(f)
if not game_missing:
pass
elif meta.unattended:
logger.info(
f"[yellow]GAME upload: the following required fields are missing: "
f"{', '.join(game_missing)}. "
f"Re-run with appropriate CLI arguments, "
f"or trackers that require them will be skipped.[/yellow]"
)
return
else:
logger.info("\n[bold yellow]The following fields are required:[/bold yellow]")
name_needs_rebuild = False
try:
for field in game_missing:
if field == "year":
while True:
value = (cli_ui.ask_string("Enter year (leave blank to skip): ") or "").strip()
if not value:
break
if value.isdigit() and len(value) == 4 and 1000 <= int(value) <= 3000:
meta.year = int(value)
meta.search_year = value
name_needs_rebuild = True
break
else:
logger.info("[red]Invalid year (must be a 4-digit number between 1000 and 3000). Please try again.[/red]")
elif field == "platform":
try:
value = cli_ui.ask_choice(
"Select target platform: (can be manually set with -plat / --platform)",
choices=["pc", "mac", "linux", "ps5", "ps4", "ps3", "ps2", "xbox", "x360", "xone", "xsx", "switch", "3ds", "nds", "wiiu", "wii"],
sort=False,
)
except EOFError:
value = ""
if value:
meta[field] = value
name_needs_rebuild = True
elif field == "game_version":
value = (cli_ui.ask_string("Enter game version (e.g., 1.15) (leave blank to skip): ") or "").strip()
if value:
from src.prep_game import normalize_version
meta[field] = normalize_version(value)
name_needs_rebuild = True
elif field == "game_subcategory":
subcategory_choices = ["full_game (Full Game)", "full_game_dlc (Full Game + DLC)", "dlc (DLC only)", "update (Update only)"]
subcategory_values = {"Full Game": "full_game", "Full Game + DLC": "full_game_dlc", "DLC": "dlc", "Update": "update"}
choice = cli_ui.ask_choice("Select game subcategory (can be manually set with -gsc / --game-subcategory):", choices=subcategory_choices, sort=False)
meta.game_subcategory = subcategory_values.get(choice, "full_game")
name_needs_rebuild = True
else:
value = (cli_ui.ask_string(f"Enter {field} (leave blank to skip): ") or "").strip()
if value:
meta[field] = value
name_needs_rebuild = True
except EOFError:
logger.info("[yellow]Input cancelled — continuing with missing game fields.[/yellow]")
name_needs_rebuild = False
# Rebuild the torrent name so the confirmation screen and upload reflect the new values
if name_needs_rebuild:
meta.name_notag, meta.name, meta.clean_name, meta.potential_missing = await name_manager.get_name(meta)
# BJS-specific game metadata prompts
trackers = [t.upper() for t in meta.trackers]
if "BJS" not in trackers or meta.unattended:
return
try:
# Console-specific fields
pc_platforms = {"PC", "MAC", "LINUX", "EMULATOR", ""}
platform = meta.platform.upper().strip()
is_console = platform not in pc_platforms
if is_console:
needs_game_system = meta.game_system in ("PS1", "PS2", "PSP", "WII", "WIIU", "X360")
needs_game_region = meta.game_system in (
"3DS",
"NDS",
"PSVITA",
"PS1",
"PS2",
"PS3",
)
needs_container = meta.game_system in ("SWITCH")
if needs_game_system and not meta.game_system:
system_choices = ["PAL", "NTSC-U", "NTSC-J", "Skip"]
if meta.platform.upper() == "PSP":
system_choices = ["FREE", "NTSC", "PAL", "Skip"]
try:
choice = cli_ui.ask_choice(
"BJS: Select game system (TV standard):",
choices=system_choices,
)
if choice != "Skip":
meta.game_system = choice
except EOFError:
pass
if needs_game_region and not meta.game_region:
region_choices = ["USA", "EUR", "JPN", "Skip"]
try:
choice = cli_ui.ask_choice(
"BJS: Select game region:",
choices=region_choices,
)
if choice != "Skip":
meta.game_region = choice
except EOFError:
pass
if needs_container:
container_choices = ["NSP", "XCI", "NSZ", "XCZ", "Skip"]
if meta.game_system == "X360":
container_choices = ["LT", "JTAG/RGH", "Skip"]
if meta.container.upper() not in container_choices:
try:
choice = cli_ui.ask_choice(
"BJS: Select container format ('Destravamento'):",
choices=container_choices,
)
if choice != "Skip":
meta.container = choice
except EOFError:
pass
except EOFError:
logger.info("[yellow]Input cancelled — continuing with current game fields.[/yellow]")
def book_screens(meta: Meta, min_successful_uploads: int) -> tuple[int, int]:
"""Count non-poster PNG screenshots for a BOOK upload and cap the upload minimum.
Args:
meta: The metadata dictionary (needs ``base_dir`` and ``uuid``).
min_successful_uploads: The configured minimum number of successful image uploads.
Returns:
A ``(actual_screens, capped_min)`` tuple where *actual_screens* is the
number of non-poster PNGs found and *capped_min* is
``min(min_successful_uploads, actual_screens)`` so the upload loop never
requires more images than actually exist.
"""
tmp_dir = f"{meta.base_dir}/tmp/{meta.uuid}"
img_files = glob.glob(glob.escape(tmp_dir) + "/*.png")
screenshot_files = [f for f in img_files if not os.path.basename(f).startswith("POSTER")]
actual_screens = len(screenshot_files)
capped_min = min(min_successful_uploads, actual_screens)
return actual_screens, capped_min
async def process_meta(meta: Meta, base_dir: str, bot: Any = None) -> bool:
"""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}", meta=meta)
if not meta.imghost or 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:
logger.info("[red]oeimg is now onlyimage, your config is being updated[/red]")
update_oeimg_to_onlyimage()
except Exception as e:
logger.error(f"[red]Error checking image hosts: {e}[/red]")
return False
if not meta.unattended:
ua = config['DEFAULT'].get('auto_mode', False)
if str(ua).lower() == "true":
meta.unattended = True
logger.info("[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:
logger.info(f"Error in gather_prep: {e}")
logger.info(traceback.format_exc())
return False
# Load covers.json if it exists and not already present in meta
covers_file = f"{meta.base_dir}/tmp/{meta.uuid}/covers.json"
if os.path.exists(covers_file) and not meta.covers:
try:
async with aiofiles.open(covers_file, encoding="utf-8") as f:
content = await f.read()
loaded_covers = json.loads(content)
if isinstance(loaded_covers, list):
meta.covers = loaded_covers
logger.debug(f"[green]Loaded {len(loaded_covers)} covers from covers.json into meta.covers")
except Exception as e:
logger.debug(f"[red]Error loading covers.json into meta.covers: {e}")
parser = Args(config)
helper = UploadHelper(config)
raw_trackers = meta.trackers
trackers: list[str]
if isinstance(raw_trackers, list):
raw_trackers_list = raw_trackers
trackers = [t for t in raw_trackers_list if isinstance(t, str)]
elif isinstance(raw_trackers, str):
if raw_trackers != "":
trackers = [t.strip().upper() for t in raw_trackers.split(",") if t.strip()] # type: ignore
meta.trackers = trackers
else:
trackers = []
else:
trackers = []
if isinstance(meta.trackers_remove, str) and meta.trackers_remove:
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)
logger.debug(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.to_dict(), indent=4))
# For BOOK category, certain trackers (e.g. CBR) require title, author, year and language.
# Prompt here - on the shared meta - so the data flows into every tracker's upload
# and into get_name (which runs again below if any field was filled in).
if meta.category == "BOOK":
await _prompt_book_meta(meta)
if meta.category == "GAME":
await _prompt_game_meta(meta)
meta = await gen_desc(meta, takescreens_manager, uploadscreens_manager)
editargs_tracking: tuple[str, ...] = ()
previous_trackers = meta.trackers
try:
confirm = await helper.get_confirmation(meta)
except EOFError:
logger.info("\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:
logger.info("\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():
logger.info("[yellow]No input provided. Please enter arguments, type `continue` to continue or press Ctrl+C to exit.[/yellow]")
continue
try:
editargs = tuple(shlex.split(editargs_str))
except Exception:
logger.info("[red]Bad input detected[/red]")
confirm = False
continue
# Tracks multiple edits
editargs_tracking = editargs_tracking + editargs
# Carry original args over, let parse handle duplicates
original_args = meta.item_args if meta.item_args is not None else list(sys.argv[1:])
meta, _help, _before_args = cast(tuple[Meta, Any, Any], parser.parse(list(original_args) + list(editargs_tracking), meta))
if not meta.trackers:
meta.trackers = previous_trackers
if isinstance(meta.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.trackers, list):
meta.trackers = [t.strip().upper() for t in meta.trackers if isinstance(t, str)]
logger.debug(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:
logger.info("\n[red]Exiting on user request (Ctrl+C)[/red]")
await cleanup_manager.cleanup()
cleanup_manager.reset_terminal()
sys.exit(1)
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.remove_trackers, list) else [str(meta.remove_trackers)]
for tracker in remove_trackers_list:
if tracker in meta.trackers:
if meta.debug:
logger.debug(f"[DEBUG] Would have removed {tracker} found in client")
else:
meta.trackers.remove(tracker)
removed.append(tracker)
if removed:
logger.info(f"[yellow]Removing trackers already in your client: {', '.join(removed)}[/yellow]")
if not meta.trackers:
logger.info("[red]No trackers remain after removal.[/red]")
successful_trackers = 0
meta.skip_uploading = 10
else:
logger.info(f"[green]Processing {meta.name} for upload...[/green]")
# reset trackers after any removals
trackers = meta.trackers
audio_prompted = False
for tracker in [
"ACM",
"AITHER",
"ASC",
"BJS",
"BT",
"CBR",
"CRP",
"DP",
"FF",
"GPW",
"HUNO",
"IHD",
"LAJIDUI",
"LDU",
"LPT",
"LT",
"MKO",
"OE",
"PTCAFE",
"PTGTK",
"PTS",
"RPT",
"SAM",
"SHRI",
"SPD",
"SUIO",
"TTR",
"TVC",
"ULCX",
]:
if tracker in trackers:
if not audio_prompted:
await languages_manager.process_desc_language(meta, tracker=tracker)
audio_prompted = True
else:
status_dict = meta.tracker_status
if tracker not in status_dict:
status_dict[tracker] = {}
if meta.unattended_audio_skip or meta.unattended_subtitle_skip:
status_dict[tracker]["skip_upload"] = True
else:
status_dict[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.to_dict(), indent=4))
await asyncio.sleep(0.2)
try:
await validate_tracker_logins(meta, trackers)
await asyncio.sleep(0.2)
except Exception as e:
logger.warning(f"[yellow]Warning: Tracker validation encountered an error: {e}[/yellow]")
successful_trackers = await TrackerStatusManager(config=config).process_all_trackers(meta)
if meta.trackers_pass is not None:
meta.skip_uploading = meta.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.skip_uploading
skip_uploading_int = skip_uploading if isinstance(skip_uploading, (int, str)) else 0
if successful_trackers < skip_uploading_int and not meta.debug:
logger.info(f"[red]Not enough successful trackers ({successful_trackers}/{skip_uploading_int}). No uploads being processed.[/red]")
return True
else:
meta.we_are_uploading = True
common = COMMON(config)
if meta.site_check:
tracker_status = cast(dict[str, dict[str, Any]], meta.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.aither_trumpable and len(meta.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 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: dict[str, Any] = {
"uuid": meta.uuid,
"path": meta.path,
"imdb_id": meta.imdb_id,
"tmdb_id": meta.tmdb_id,
"tvdb_id": meta.tvdb_id,
"mal_id": meta.mal_id,
"tvmaze_id": meta.tvmaze_id,
}
if tracker == "AITHER":
search_entry["trumpable"] = meta.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 True
filename: str = meta.title
bdmv_filename = meta.filename
bdinfo = meta.bdinfo
file_list = [str(p) for p in meta.filelist if str(p)]
videopath: str = ""
if file_list:
videopath = file_list[0]
elif meta.is_disc == "HDDVD" and meta.discs:
videopath = meta.discs[0].get("largest_evo", "")
logger.info(f"Processing {filename} for upload.....")
meta.frame_overlay = config["DEFAULT"].get("frame_overlay", False)
tracker_status_map = cast(dict[str, dict[str, Any]], meta.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
logger.info("[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)