-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathquickstart.py
More file actions
7049 lines (6357 loc) · 304 KB
/
Copy pathquickstart.py
File metadata and controls
7049 lines (6357 loc) · 304 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
# ruff: noqa: E402
#
# We intentionally run enforce_preflight() before all other imports so
# that broken Python builds (missing _sqlite3, _ssl, etc.) surface a
# friendly error instead of a confusing stdlib traceback. That makes
# this file's import-order-vs-code arrangement look like an E402 to
# ruff for every subsequent import, so we suppress E402 file-wide!
# Startup preflight: probe stdlib C-extensions (sqlite3, _ssl) BEFORE
# any third-party import runs. Broken Python builds (usually pyenv/asdf
# on hosts missing libsqlite3-dev / libssl-dev) would otherwise die
# with a confusing traceback deep inside stdlib the moment `requests`
# touches ssl or `modules.database` touches sqlite3. This surfaces a
# friendly message instead. See modules/_preflight.py.
from modules._preflight import enforce_preflight
enforce_preflight()
import argparse
import gzip
import inspect
import io
import json
import os
import platform
import psutil
import re
import shutil
import socket
import subprocess
import sys
import threading
import time
import uuid
import webbrowser
import secrets
from threading import Thread
from pathlib import Path
from collections import deque
import namesgenerator
import requests
from cachelib.file import FileSystemCache
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
from ruamel.yaml import YAML
from flask import (
Flask,
jsonify,
render_template,
request,
redirect,
url_for,
session,
send_file,
abort,
has_request_context,
)
from waitress import serve
from werkzeug.datastructures import MultiDict
from werkzeug.wrappers import Request
from flask_session import Session
from modules import validations, output, persistence, helpers, database, logscan, path_validation, url_validation
from modules import importer # noqa: F401 (load-bearing: tests do monkeypatch.setattr(qs_module.importer, ...))
from modules.dependency_reasons import ( # noqa: F401 (re-exports for tests/legacy in-module callers)
QS_ANIDB_DEP_SOURCE_PREFIXES,
QS_ANIDB_OVERLAY_IMAGE_VALUES,
QS_ANIDB_REQUIRED_STEP_KEY,
QS_FLOPPY_DEP_SOURCE_PREFIXES,
QS_FLOPPY_OVERLAY_SOURCE_VALUES,
QS_FLOPPY_REQUIRED_STEP_KEY,
QS_MAL_DEP_ATTRIBUTE_OPERATIONS,
QS_MAL_DEP_ATTRIBUTE_VALUES,
QS_MAL_DEP_COLLECTION_IDS,
QS_MAL_OVERLAY_IMAGE_VALUES,
QS_MAL_REQUIRED_STEP_KEY,
QS_MDBLIST_DEP_SOURCE_PREFIXES,
QS_MDBLIST_OVERLAY_IMAGE_VALUES,
QS_MDBLIST_REQUIRED_STEP_KEY,
QS_OMDB_DEP_SOURCE_PREFIXES,
QS_OMDB_REQUIRED_STEP_KEY,
QS_RADARR_DEP_ATTRIBUTE_PREFIXES,
QS_RADARR_DEP_COLLECTION_PREFIXES,
QS_RADARR_DEP_TEMPLATE_COLLECTION_PREFIXES,
QS_RADARR_REQUIRED_STEP_KEY,
QS_SONARR_DEP_ATTRIBUTE_PREFIXES,
QS_SONARR_DEP_COLLECTION_PREFIXES,
QS_SONARR_DEP_TEMPLATE_COLLECTION_PREFIXES,
QS_SONARR_REQUIRED_STEP_KEY,
QS_TAUTULLI_DEP_COLLECTION_IDS,
QS_TAUTULLI_REQUIRED_STEP_KEY,
QS_TRACEARR_DEP_COLLECTION_IDS,
QS_TRACEARR_REQUIRED_STEP_KEY,
QS_TRAKT_DEP_COLLECTION_IDS,
QS_TRAKT_OVERLAY_IMAGE_VALUES,
QS_TRAKT_REQUIRED_STEP_KEY,
_active_library_prefixes,
_append_dependency_reason,
_attribute_dependency_source_reasons,
_config_anidb_dependency_reasons,
_config_floppy_dependency_reasons,
_config_dependency_reasons,
_config_mal_dependency_reasons,
_config_mdblist_dependency_reasons,
_config_omdb_dependency_reasons,
_config_radarr_dependency_reasons,
_config_requires_mal,
_config_sonarr_dependency_reasons,
_config_tautulli_dependency_reasons,
_config_tracearr_dependency_reasons,
_config_trakt_dependency_reasons,
_dependency_reason_label,
_is_truthy_setting_value,
_libraries_data_anidb_dependency_reasons,
_libraries_data_floppy_dependency_reasons,
_libraries_data_collection_dependency_reasons,
_libraries_data_mal_dependency_reasons,
_libraries_data_mdblist_dependency_reasons,
_libraries_data_omdb_dependency_reasons,
_libraries_data_overlay_rating_dependency_reasons,
_libraries_data_overlay_rating_source_dependency_reasons,
_libraries_data_radarr_dependency_reasons,
_libraries_data_requires_mal,
_libraries_data_service_dependency_reasons,
_libraries_data_sonarr_dependency_reasons,
_libraries_data_tautulli_dependency_reasons,
_libraries_data_tracearr_dependency_reasons,
_libraries_data_template_collection_dependency_reasons,
_libraries_data_trakt_dependency_reasons,
_library_prefix_from_key,
_normalize_status,
_parse_json_array,
_selected_library_ids_from_libraries_data,
)
from modules.workspace_status import ( # noqa: F401 (re-exports for tests/legacy in-module callers)
QS_ERROR_REASONS,
QS_FINAL_VALIDATION_TTL_HOURS,
QS_REQUIRED_STEP_KEYS,
QS_REVIEW_STEP_KEYS,
QS_STATUS_ORDER,
QS_VALIDATION_STEP_KEYS,
QS_WARN_REASONS,
_build_final_gate,
_build_live_validation_rollup,
_build_workspace_app_readiness,
_build_workspace_app_readiness_from_status,
_build_workspace_status_context,
_bulk_validation_is_fresh,
_derive_live_final_validation_status,
_derive_step_status,
_format_validation_age,
_has_meaningful_optional_input,
_is_meaningful_optional_status_input,
_is_nonblank_setting,
_latest_bulk_validation_timestamp,
_latest_iso_timestamp,
_parse_iso_datetime,
_step_href,
_workspace_step_status_from_app_readiness,
_worst_status,
)
from modules.library_file_entries import ( # noqa: F401 (re-exports for tests/legacy in-module callers)
LIBRARY_FILE_KINDS,
LIBRARY_FILE_PARSE_FUNCTIONS,
LIBRARY_FILE_VALIDATORS,
LOCAL_LIBRARY_FILE_TYPES,
SETTINGS_AUTO_SORT_HUBS_VALUES,
_clone_library_file_entries_for_target,
_copy_library_artifact_to_managed_store,
_display_library_managed_location,
_format_library_file_validation_error,
_is_bundled_library_archive_member,
_managed_library_config_root,
_managed_library_file_root,
_managed_library_folder_slug,
_normalize_imported_libraries_payload,
_normalize_library_external_entry,
_normalize_library_file_entries_payload,
_normalized_managed_library_relative_path,
_parse_collection_file_entries,
_parse_managed_library_relative_path,
_parse_metadata_file_entries,
_parse_overlay_file_entries,
_remove_managed_path,
_resolve_local_library_source,
_safe_external_artifact_slug,
_validate_library_auto_sort_hubs,
_validate_library_collection_files,
_validate_library_file_entry,
_validate_library_metadata_files,
_validate_library_overlay_files,
)
from modules.background_jobs import (
JOB_TARGET_PAGES,
create_background_job as _create_background_job, # noqa: F401 (used directly by tests as qs_module._create_background_job)
get_background_job as _get_background_job,
get_active_background_job as _get_active_background_job,
get_active_background_jobs as _get_active_background_jobs,
update_background_job as _update_background_job,
clear_active_background_job as _clear_active_background_job,
ensure_background_job as _ensure_background_job,
complete_background_job as _complete_background_job, # noqa: F401 (used directly by tests as qs_module._complete_background_job)
)
from blueprints.validation_routes import bp as validation_routes_bp, refresh_plex_libraries
from blueprints.asset_routes import bp as asset_routes_bp
from blueprints.kometa_updates import bp as kometa_updates_bp
from blueprints.imagemaid_updates import bp as imagemaid_updates_bp
from blueprints.config_routes import bp as config_routes_bp
from blueprints.download_routes import bp as download_routes_bp
from blueprints.test_libraries_routes import bp as test_libraries_routes_bp
from blueprints.external_yaml_routes import bp as external_yaml_routes_bp
from blueprints import app_config_routes
from blueprints.app_config_routes import bp as app_config_routes_bp
from blueprints.library_routes import (
bp as library_routes_bp,
_build_library_lists, # noqa: F401 (used by tests as qs_module._build_library_lists)
_configured_library_ids, # noqa: F401 (used internally + by tests)
_legacy_playlist_library_names, # noqa: F401
_migrate_legacy_playlist_libraries_to_library_toggles, # noqa: F401 (patched in tests)
_build_merged_libraries_hint_payload, # noqa: F401
_libraries_dependency_hint_response, # noqa: F401
)
from blueprints.import_config_routes import ( # noqa: F401 (re-exports for tests/legacy in-module callers)
bp as import_config_routes_bp,
_coerce_validation_response_payload,
_import_preview_json_default,
_map_playlist_libraries,
count_annotated_lines,
import_config_confirm,
import_config_preview,
import_config_preview_mapped,
import_config_report,
)
from blueprints.imagemaid_routes import ( # noqa: F401 (re-exports for tests/legacy in-module callers)
bp as imagemaid_routes_bp,
IMAGEMAID_STARTUP_GRACE_SECONDS,
_schedule_quickstart_imagemaid_run_marker,
autosave_imagemaid,
imagemaid_status,
start_imagemaid,
stop_imagemaid,
validate_imagemaid,
)
from modules.assets import build_preview_image_data as _build_preview_image_data, list_overlay_fonts
from modules.bundle_artifacts import dump_yaml_text as _dump_yaml_text
from modules.tmdb_lookup import (
get_active_tmdb_api_key as _get_active_tmdb_api_key,
lookup_tmdb_by_imdb_id as _lookup_tmdb_by_imdb_id,
lookup_tmdb_numeric_id as _lookup_tmdb_numeric_id,
build_tmdb_library_type_warning as _build_tmdb_library_type_warning,
)
from modules.test_libraries import (
resolve_test_libraries_paths as _resolve_test_libraries_paths, # noqa: F401 (used directly by tests as qs_module._resolve_test_libraries_paths)
paths_overlap as _paths_overlap, # noqa: F401 (used directly by tests as qs_module._paths_overlap)
safe_to_replace_test_libraries as _safe_to_replace_test_libraries, # noqa: F401 (used directly by tests as qs_module._safe_to_replace_test_libraries)
)
from modules.logscan_cache import (
get_logscan_cache_dir as _get_logscan_cache_dir,
normalize_logscan_tool_name as _normalize_logscan_tool_name,
get_logscan_live_dir as _get_logscan_live_dir,
get_logscan_archive_root_dir as _get_logscan_archive_root_dir,
get_logscan_archive_dir as _get_logscan_archive_dir,
detect_logscan_tool_from_path as _detect_logscan_tool_from_path,
build_logscan_archive_destination as _build_logscan_archive_destination,
iter_logscan_candidate_files as _iter_logscan_candidate_files,
get_logscan_log_files as _get_logscan_log_files,
calculate_logscan_file_md5 as _calculate_logscan_file_md5,
find_logscan_cache_entry_by_md5 as _find_logscan_cache_entry_by_md5,
logscan_cache_entry_matches as _logscan_cache_entry_matches,
get_logscan_delta_files as _get_logscan_delta_files,
classify_logscan_file_location as _classify_logscan_file_location,
format_archived_log_retention_label as _format_archived_log_retention_label,
get_logscan_keep_limit as _get_logscan_keep_limit,
load_logscan_ingest_cache as _load_logscan_ingest_cache, # noqa: F401 (used directly by tests as qs_module._load_logscan_ingest_cache)
save_logscan_ingest_cache as _save_logscan_ingest_cache, # noqa: F401 (used directly by tests as qs_module._save_logscan_ingest_cache)
clear_logscan_ingest_cache as _clear_logscan_ingest_cache,
remove_logscan_ingest_cache_entries as _remove_logscan_ingest_cache_entries,
)
from modules.logscan_resume import (
build_resume_library_scope as _build_resume_library_scope, # noqa: F401 (used directly by tests as qs_module._build_resume_library_scope)
extract_first_log_timestamp as _extract_first_log_timestamp,
build_incomplete_run_timing_summary as _build_incomplete_run_timing_summary, # noqa: F401 (used directly by tests as qs_module._build_incomplete_run_timing_summary)
build_incomplete_scope_summary as _build_incomplete_scope_summary, # noqa: F401 (used directly by tests as qs_module._build_incomplete_scope_summary)
build_completed_scope_resume_message as _build_completed_scope_resume_message, # noqa: F401 (used directly by tests as qs_module._build_completed_scope_resume_message)
build_recovery_suggestions as _build_recovery_suggestions, # noqa: F401 (used directly by tests as qs_module._build_recovery_suggestions)
build_resume_explanation as _build_resume_explanation, # noqa: F401 (used directly by tests as qs_module._build_resume_explanation)
)
from modules.logscan_imagemaid_analysis import (
resolve_imagemaid_run_config_name as _resolve_imagemaid_run_config_name,
)
from modules.logscan_imagemaid_analyzer import (
analyze_imagemaid_log_content as _analyze_imagemaid_log_content,
)
from modules.logscan_progress import (
load_progress_config as _load_progress_config, # noqa: F401 (used directly by tests as qs_module._load_progress_config)
get_progress_run_order as _get_progress_run_order,
get_progress_library_list as _get_progress_library_list,
build_incomplete_progress_snapshot as _build_incomplete_progress_snapshot, # noqa: F401 (used directly by tests as qs_module._build_incomplete_progress_snapshot)
build_completed_log_progress_snapshot as _build_completed_log_progress_snapshot,
)
from modules.logscan_incomplete_resume import (
analyze_incomplete_log_for_resume as _analyze_incomplete_log_for_resume, # noqa: F401 (used directly by tests as qs_module._analyze_incomplete_log_for_resume)
build_incomplete_run_from_cache_entry as _build_incomplete_run_from_cache_entry, # noqa: F401 (used directly by tests as qs_module._build_incomplete_run_from_cache_entry)
build_incomplete_resume_cache_fields as _build_incomplete_resume_cache_fields,
get_logscan_incomplete_runs as _get_logscan_incomplete_runs, # noqa: F401 (used directly by tests as qs_module._get_logscan_incomplete_runs)
get_logscan_incomplete_run as _get_logscan_incomplete_run, # noqa: F401 (used directly by tests as qs_module._get_logscan_incomplete_run)
get_incomplete_resume_runs as _get_incomplete_resume_runs, # noqa: F401 (used directly by tests as qs_module._get_incomplete_resume_runs)
build_latest_incomplete_resume_hint as _build_latest_incomplete_resume_hint,
)
from modules.kometa_install import (
KOMETA_INSTALL_MODE_EXTERNAL,
validate_saved_kometa_selection as _validate_saved_kometa_selection,
build_kometa_install_context as _build_kometa_install_context,
get_kometa_settings_section as _get_kometa_settings_section,
resolve_kometa_selection as _resolve_kometa_selection,
probe_kometa_root_state as _probe_kometa_root_state, # noqa: F401 (used directly by tests as qs_module._probe_kometa_root_state)
)
from modules.imagemaid import (
probe_imagemaid_root_state as _probe_imagemaid_root_state,
imagemaid_settings_to_form_payload as _imagemaid_settings_to_form_payload, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module._imagemaid_settings_to_form_payload)
get_stored_plex_credentials_for_config as _get_stored_plex_credentials_for_config, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
save_imagemaid_settings_for_config as _save_imagemaid_settings_for_config,
get_imagemaid_settings_section as _get_imagemaid_settings_section,
persist_imagemaid_validation as _persist_imagemaid_validation,
build_imagemaid_command_parts as _build_imagemaid_command_parts, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
build_imagemaid_command as _build_imagemaid_command, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
validate_imagemaid_settings as _validate_imagemaid_settings, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
get_latest_imagemaid_log_path as _get_latest_imagemaid_log_path, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
get_imagemaid_supported_options as _get_imagemaid_supported_options, # noqa: F401 (used directly by tests as qs_module._get_imagemaid_supported_options)
)
from modules.process_control import (
MAINTENANCE_STATE,
MAINTENANCE_STATE_LOCK,
RUN_CONTEXT,
RUN_CONTEXT_LOCK,
IMAGEMAID_RUN_CONTEXT, # noqa: F401 (used directly by tests as qs_module.IMAGEMAID_RUN_CONTEXT)
IMAGEMAID_RUN_CONTEXT_LOCK, # noqa: F401 (used directly by tests as qs_module.IMAGEMAID_RUN_CONTEXT_LOCK)
calculate_process_cpu_percent as _calculate_process_cpu_percent,
calculate_system_cpu_percent as _calculate_system_cpu_percent,
calculate_process_io_stats as _calculate_process_io_stats,
clear_process_metric_cache as _clear_process_metric_cache,
is_within_maintenance_window as _is_within_maintenance_window,
get_maintenance_window_from_db as _get_maintenance_window_from_db, # noqa: F401 (used directly by tests as qs_module._get_maintenance_window_from_db)
get_maintenance_window_live as _get_maintenance_window_live, # noqa: F401 (used directly by tests as qs_module._get_maintenance_window_live)
resolve_maintenance_window_live as _resolve_maintenance_window_live,
resolve_maintenance_window_from_db as _resolve_maintenance_window_from_db,
refresh_maintenance_window_availability as _refresh_maintenance_window_availability, # noqa: F401 (used directly by tests as qs_module._refresh_maintenance_window_availability)
normalize_kometa_start_mode as _normalize_kometa_start_mode,
set_pending_kometa_start as _set_pending_kometa_start, # noqa: F401 (used directly by tests as qs_module._set_pending_kometa_start)
peek_pending_kometa_start as _peek_pending_kometa_start,
pop_pending_kometa_start as _pop_pending_kometa_start, # noqa: F401 (used directly by tests as qs_module._pop_pending_kometa_start)
clear_pending_kometa_start as _clear_pending_kometa_start, # noqa: F401 (used directly by tests as qs_module._clear_pending_kometa_start)
find_running_kometa_processes as _find_running_kometa_processes, # noqa: F401 (used directly by tests as qs_module._find_running_kometa_processes)
find_running_kometa_process as _find_running_kometa_process,
find_running_imagemaid_processes as _find_running_imagemaid_processes, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
find_running_imagemaid_process as _find_running_imagemaid_process, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
stop_process_tree as _stop_process_tree,
launch_kometa_command as _launch_kometa_command,
launch_imagemaid_command as _launch_imagemaid_command, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
reset_imagemaid_runtime_env as _reset_imagemaid_runtime_env, # noqa: F401 (used directly by tests as qs_module._reset_imagemaid_runtime_env)
update_run_context as _update_run_context,
get_run_context as _get_run_context,
clear_run_context as _clear_run_context,
get_imagemaid_run_context as _get_imagemaid_run_context, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
clear_imagemaid_run_context as _clear_imagemaid_run_context, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
suspend_process_tree as _suspend_process_tree, # noqa: F401 (used directly by tests as qs_module._suspend_process_tree)
resume_process_tree as _resume_process_tree, # noqa: F401 (used directly by tests as qs_module._resume_process_tree)
maintenance_guard_loop as _maintenance_guard_loop,
append_quickstart_meta_log_line as _append_quickstart_meta_log_line, # noqa: F401 (used directly by tests as qs_module._append_quickstart_meta_log_line)
get_kometa_maintenance_sidecar_path as _get_kometa_maintenance_sidecar_path, # noqa: F401 (used directly by tests as qs_module._get_kometa_maintenance_sidecar_path)
get_kometa_pending_marker_path as _get_kometa_pending_marker_path, # noqa: F401 (used directly by tests as qs_module._get_kometa_pending_marker_path)
get_imagemaid_pending_marker_path as _get_imagemaid_pending_marker_path, # noqa: F401 (used directly by tests as qs_module._get_imagemaid_pending_marker_path)
is_logscan_maintenance_sidecar as _is_logscan_maintenance_sidecar,
flush_quickstart_pending_markers as _flush_quickstart_pending_markers, # noqa: F401 (used directly by tests as qs_module._flush_quickstart_pending_markers)
flush_imagemaid_pending_markers as _flush_imagemaid_pending_markers, # noqa: F401 (used directly by tests as qs_module._flush_imagemaid_pending_markers)
write_quickstart_maintenance_marker as _write_quickstart_maintenance_marker, # noqa: F401 (used directly by tests as qs_module._write_quickstart_maintenance_marker)
write_quickstart_imagemaid_run_marker as _write_quickstart_imagemaid_run_marker, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
write_quickstart_stop_marker as _write_quickstart_stop_marker,
write_quickstart_imagemaid_stop_marker as _write_quickstart_imagemaid_stop_marker, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
write_quickstart_imagemaid_maintenance_marker as _write_quickstart_imagemaid_maintenance_marker, # noqa: F401 (load-bearing: tests + blueprints/imagemaid_routes.py access via qs_module)
)
Request.max_form_parts = 100000 # Allow more form fields if needed
_resolve_request_config_name = persistence.resolve_request_config_name
utc_now_iso = helpers.utc_now_iso
_safe_join = helpers.safe_join
_safe_rel_path = helpers.safe_rel_path
_resolve_user_dir = helpers.resolve_user_dir
_retrieve_settings_for_config = persistence.retrieve_settings_for_config
apply_validation_metadata = persistence.apply_validation_metadata
_is_logscan_gzip_path = helpers.is_logscan_gzip_path
_read_logscan_text = helpers.read_logscan_text
ACTIVE_WORK_POLICIES = {
"kometa_run": [
{
"kind": "process",
"id": "imagemaid_run",
"message": "Cannot start Kometa while ImageMaid is running.",
"target_page": JOB_TARGET_PAGES.get("imagemaid_update"),
},
{
"kind": "job",
"id": "kometa_update",
"message": "Cannot start Kometa while a Kometa update is running.",
"target_page": JOB_TARGET_PAGES.get("kometa_update"),
},
],
"kometa_update": [
{
"kind": "process",
"id": "kometa_run",
"message": "Cannot update Kometa while Kometa is running.",
"target_page": JOB_TARGET_PAGES.get("kometa_update"),
}
],
"imagemaid_run": [
{
"kind": "process",
"id": "kometa_run",
"message": "Cannot start ImageMaid while Kometa is running.",
"target_page": JOB_TARGET_PAGES.get("kometa_update"),
},
{
"kind": "job",
"id": "imagemaid_update",
"message": "Cannot start ImageMaid while an ImageMaid update is running.",
"target_page": JOB_TARGET_PAGES.get("imagemaid_update"),
},
],
"imagemaid_update": [
{
"kind": "process",
"id": "imagemaid_run",
"message": "Cannot update ImageMaid while ImageMaid is running.",
"target_page": JOB_TARGET_PAGES.get("imagemaid_update"),
}
],
}
LOG_STATS_CACHE = {"mtime": None, "size": None, "stats": None}
LOGSCAN_ANALYSIS_CACHE_VERSION = 3
LOGSCAN_ANALYSIS_CACHE = {"mtime": None, "size": None, "version": LOGSCAN_ANALYSIS_CACHE_VERSION, "data": None}
LOGSCAN_PROGRESS_CACHE = {"mtime": None, "size": None, "aux_signature": None, "data": None}
VALIDATION_DOC_BASE = "/step/"
VALIDATION_DOC_FALLBACK = "/step/900-kometa"
# Page scripts that have been migrated to ES modules (roadmap step 2,
# issue #1346). The template renders <script type="module"> for these and
# stays on classic <script defer> for everything else. Add a template name
# here when its JS file becomes a module.
MODULE_PAGE_SCRIPTS = frozenset(
{
"001-start",
"010-plex",
"020-tmdb",
"027-playlist_files",
"030-tautulli",
"035-tracearr",
"040-github",
"050-omdb",
"060-mdblist",
"065-serializd",
"067-floppy",
"070-notifiarr",
"080-gotify",
"085-ntfy",
"087-apprise",
"088-yamtrack",
"090-webhooks",
"100-anidb",
"110-radarr",
"120-sonarr",
"130-trakt",
"140-mal",
"150-settings",
"150-settings",
"900-kometa",
"905-analytics",
"915-imagemaid",
"025-libraries",
}
)
VALIDATION_DOCS = {
"settings": f"{VALIDATION_DOC_BASE}150-settings",
"libraries": f"{VALIDATION_DOC_BASE}025-libraries",
"plex": f"{VALIDATION_DOC_BASE}010-plex",
"tmdb": f"{VALIDATION_DOC_BASE}020-tmdb",
"trakt": f"{VALIDATION_DOC_BASE}130-trakt",
"radarr": f"{VALIDATION_DOC_BASE}110-radarr",
"sonarr": f"{VALIDATION_DOC_BASE}120-sonarr",
"tautulli": f"{VALIDATION_DOC_BASE}030-tautulli",
"tracearr": f"{VALIDATION_DOC_BASE}035-tracearr",
"omdb": f"{VALIDATION_DOC_BASE}050-omdb",
"mdblist": f"{VALIDATION_DOC_BASE}060-mdblist",
"serializd": f"{VALIDATION_DOC_BASE}065-serializd",
"floppy": f"{VALIDATION_DOC_BASE}067-floppy",
"notifiarr": f"{VALIDATION_DOC_BASE}070-notifiarr",
"github": f"{VALIDATION_DOC_BASE}040-github",
"gotify": f"{VALIDATION_DOC_BASE}080-gotify",
"ntfy": f"{VALIDATION_DOC_BASE}085-ntfy",
"apprise": f"{VALIDATION_DOC_BASE}087-apprise",
"yamtrack": f"{VALIDATION_DOC_BASE}088-yamtrack",
"mal": f"{VALIDATION_DOC_BASE}140-mal",
"anidb": f"{VALIDATION_DOC_BASE}100-anidb",
"webhooks": f"{VALIDATION_DOC_BASE}090-webhooks",
"collections": f"{VALIDATION_DOC_BASE}025-libraries",
"overlays": f"{VALIDATION_DOC_BASE}025-libraries",
"playlist_files": f"{VALIDATION_DOC_BASE}025-libraries",
}
VALIDATION_REASON_LABELS = {
"missing_credentials": "Missing credentials",
"missing_plex_validation": "Plex not validated",
"no_libraries": "No libraries selected",
"invalid_paths": "Invalid paths",
"invalid_arr_overrides": "Invalid Arr overrides",
"missing_library_defaults": "Missing library defaults",
"missing_separator_placeholder": "Missing separator placeholder",
"invalid_metadata_files": "Invalid metadata files",
"invalid_collection_files": "Invalid collection files",
"invalid_overlay_files": "Invalid overlay files",
"invalid_fields": "Invalid fields",
"no_webhooks": "No webhooks configured",
"disabled": "Disabled",
"missing_settings": "Settings missing",
"missing_location": "Missing location",
"missing_tokens": "Missing tokens",
"token_invalid": "Invalid tokens",
"account_locked": "Account locked",
"validation_error": "Validation error",
}
def _get_active_work_blocker(subject):
normalized_subject = str(subject or "").strip()
if not normalized_subject:
return None
for rule in ACTIVE_WORK_POLICIES.get(normalized_subject, []):
kind = str(rule.get("kind") or "").strip().lower()
identifier = str(rule.get("id") or "").strip()
if not identifier:
continue
if kind == "job":
active_job = _get_active_background_job(identifier)
if active_job:
blocker = dict(rule)
blocker["job"] = active_job
blocker["blocked_by"] = identifier
blocker["status"] = active_job.get("status")
blocker["phase"] = active_job.get("phase")
blocker["job_id"] = active_job.get("job_id")
return blocker
elif kind == "process":
process_lookup = {
"kometa_run": (helpers.is_kometa_running, helpers.get_kometa_pid),
"imagemaid_run": (helpers.is_imagemaid_running, helpers.get_imagemaid_pid),
}
resolver = process_lookup.get(identifier)
if resolver:
is_running, get_pid = resolver
if is_running():
blocker = dict(rule)
blocker["blocked_by"] = identifier
blocker["pid"] = get_pid()
return blocker
return None
VALIDATION_KEY_SUGGESTIONS = {
"settings": {
"playlist_sync_to_user": "playlist_sync_to_users",
}
}
LIBRARY_RADARR_FIELDS = [
"url",
"token",
"root_folder_path",
"quality_profile",
"availability",
"tag",
"monitor",
"search",
"add_missing",
"add_existing",
"upgrade_existing",
"monitor_existing",
"ignore_cache",
"radarr_path",
"plex_path",
]
LIBRARY_RADARR_BOOL_FIELDS = {
"monitor",
"search",
"add_missing",
"add_existing",
"upgrade_existing",
"monitor_existing",
"ignore_cache",
}
LIBRARY_RADARR_AVAILABILITY_VALUES = {"announced", "cinemas", "released", "db"}
LIBRARY_SONARR_FIELDS = [
"url",
"token",
"root_folder_path",
"quality_profile",
"language_profile",
"series_type",
"season_folder",
"monitor",
"tag",
"search",
"cutoff_search",
"add_missing",
"add_existing",
"upgrade_existing",
"monitor_existing",
"ignore_cache",
"sonarr_path",
"plex_path",
]
LIBRARY_SONARR_BOOL_FIELDS = {
"season_folder",
"search",
"cutoff_search",
"add_missing",
"add_existing",
"upgrade_existing",
"monitor_existing",
"ignore_cache",
}
LIBRARY_SONARR_MONITOR_VALUES = {"all", "none", "future", "missing", "existing", "pilot", "first", "latest"}
LIBRARY_SONARR_SERIES_TYPE_VALUES = {"standard", "daily", "anime"}
def _normalize_auto_sort_hubs_value(value):
text = str(value or "").strip()
return text or None
def _is_valid_auto_sort_hubs_value(value):
normalized = _normalize_auto_sort_hubs_value(value)
if normalized is None:
return True
return normalized in SETTINGS_AUTO_SORT_HUBS_VALUES
def build_validation_summary(errors):
def infer_section_from_text(text):
lowered = str(text or "").strip().lower()
if any(token in lowered for token in ("metadata_files[", "collection_files[", "overlay_files[")):
return "libraries"
if "playlist_files[" in lowered:
return "playlist_files"
if lowered.startswith("plex"):
return "plex"
if lowered.startswith("tmdb"):
return "tmdb"
if lowered.startswith("settings"):
return "settings"
return "config"
summary = []
if not errors:
return summary
for err in errors[:20]:
if isinstance(err, str):
section = infer_section_from_text(err)
summary.append(
{
"title": err,
"details": "",
"doc_url": VALIDATION_DOCS.get(section, VALIDATION_DOC_FALLBACK),
"section": section,
"suggestions": [],
}
)
continue
if isinstance(err, dict):
section = str(err.get("section") or infer_section_from_text(err.get("title") or err.get("message") or "") or "config")
summary.append(
{
"title": str(err.get("title") or err.get("message") or "Validation error"),
"details": str(err.get("details") or ""),
"doc_url": err.get("doc_url") or VALIDATION_DOCS.get(section, VALIDATION_DOC_FALLBACK),
"section": section,
"suggestions": list(err.get("suggestions") or []),
}
)
continue
path_parts = [str(p) for p in getattr(err, "path", [])]
section = path_parts[0] if path_parts else ""
path_display = ".".join(path_parts) if path_parts else (section or "config")
doc_url = VALIDATION_DOCS.get(section, VALIDATION_DOC_FALLBACK)
message = str(getattr(err, "message", err) or "Validation error")
title = f"{path_display}: {message}"
details = ""
suggestions = []
validator = getattr(err, "validator", "")
validator_value = getattr(err, "validator_value", None)
if validator == "additionalProperties":
extras = []
try:
extras = list(err.params.get("additionalProperties") or [])
except Exception:
extras = []
if extras:
title = f"{section or 'config'}: Unexpected key(s)"
details = f"Unknown keys: {', '.join(extras)}."
for key in extras:
suggestion = VALIDATION_KEY_SUGGESTIONS.get(section, {}).get(key)
if suggestion:
suggestions.append(f"{key} → {suggestion}")
elif validator == "type":
expected = validator_value
details = f"Expected type: {expected}."
elif validator == "enum":
values = validator_value or []
details = f"Expected one of: {', '.join(map(str, values))}."
elif validator == "minimum":
details = f"Minimum allowed: {validator_value}."
elif validator == "maximum":
details = f"Maximum allowed: {validator_value}."
elif validator == "pattern":
details = "Value does not match the expected format."
summary.append(
{
"title": title,
"details": details,
"doc_url": doc_url,
"section": section or "config",
"suggestions": suggestions,
}
)
return summary
def _safe_int(value, default=0):
try:
return int(value)
except (TypeError, ValueError):
return default
def _normalize_generated_config_library_files(config_data, config_name):
if not isinstance(config_data, dict):
return config_data, False, []
libraries = config_data.get("libraries")
if not isinstance(libraries, dict):
return config_data, False, []
changed = False
errors = []
for library_name, lib_cfg in libraries.items():
if not isinstance(lib_cfg, dict):
continue
for kind in LIBRARY_FILE_KINDS:
entries = lib_cfg.get(kind)
if not isinstance(entries, list):
continue
new_entries = []
for idx, entry in enumerate(entries, start=1):
if not isinstance(entry, dict):
new_entries.append(entry)
continue
handled = False
for entry_type in LOCAL_LIBRARY_FILE_TYPES:
location = entry.get(entry_type)
if not location:
continue
normalized_entry, entry_changed, entry_error = _normalize_library_external_entry(
kind,
{"type": entry_type, "location": location},
config_name,
library_name,
validate_local=True,
require_managed_context=True,
)
if entry_error:
errors.append(
_format_library_file_validation_error(
library_name,
kind,
idx,
entry_error,
{"type": entry_type, "location": location},
)
)
new_entries.append(entry)
else:
new_entries.append({entry_type: normalized_entry["location"]})
changed = changed or bool(entry_changed)
handled = True
break
if not handled:
new_entries.append(entry)
lib_cfg[kind] = new_entries
return config_data, changed, errors
def _is_blank_override_value(value):
if value is None:
return True
if isinstance(value, str):
text = value.strip()
return text == "" or text.lower() == "none"
return False
def _coerce_override_bool(value):
if value is None or value == "":
return None
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
lowered = value.strip().lower()
if lowered in {"true", "yes", "1", "on"}:
return True
if lowered in {"false", "no", "0", "off"}:
return False
return None
def _library_service_definition(service_name):
if service_name == "radarr":
return {
"template_key": "110-radarr",
"section_name": "radarr",
"fields": LIBRARY_RADARR_FIELDS,
"bool_fields": LIBRARY_RADARR_BOOL_FIELDS,
"label": "Radarr",
}
if service_name == "sonarr":
return {
"template_key": "120-sonarr",
"section_name": "sonarr",
"fields": LIBRARY_SONARR_FIELDS,
"bool_fields": LIBRARY_SONARR_BOOL_FIELDS,
"label": "Sonarr",
}
return None
def _extract_library_service_overrides(libraries_data, library_id, service_name):
definition = _library_service_definition(service_name)
if not definition or not isinstance(libraries_data, dict):
return {}
overrides = {}
for field in definition["fields"]:
value = libraries_data.get(f"{library_id}-attribute_{service_name}_{field}")
if field in definition["bool_fields"]:
bool_value = _coerce_override_bool(value)
if bool_value is not None:
overrides[field] = bool_value
continue
if not _is_blank_override_value(value):
overrides[field] = str(value).strip() if isinstance(value, str) else value
return overrides
def _validate_library_service_overrides(library_id, libraries_data, force_validate=False):
service_name = "radarr" if str(library_id or "").startswith("mov-library_") else "sonarr" if str(library_id or "").startswith("sho-library_") else None
definition = _library_service_definition(service_name)
if not definition:
return {"valid": True, "skipped": True, "service": None, "errors": []}
overrides = _extract_library_service_overrides(libraries_data, library_id, service_name)
if not overrides and not force_validate:
return {"valid": True, "skipped": True, "service": service_name, "overrides": {}, "errors": []}
settings = persistence.retrieve_settings(definition["template_key"]) or {}
global_section = settings.get(definition["section_name"], {}) if isinstance(settings, dict) else {}
if not isinstance(global_section, dict):
global_section = {}
effective_url = overrides.get("url") or global_section.get("url")
effective_token = overrides.get("token") or global_section.get("token")
library_name = libraries_data.get(f"{library_id}-library") if isinstance(libraries_data, dict) else None
display_name = str(library_name or library_id or "").strip() or str(library_id or "")
scoped_label = f"{display_name} {definition['label']}"
if _is_blank_override_value(effective_url) or _is_blank_override_value(effective_token):
return {
"valid": False,
"skipped": False,
"service": service_name,
"overrides": overrides,
"errors": [f"{scoped_label}: URL and token are required after applying overrides."],
}
if service_name == "radarr":
response_data, _status = validations.validate_radarr_payload({"url": effective_url, "token": effective_token})
else:
response_data, _status = validations.validate_sonarr_payload({"url": effective_url, "token": effective_token})
if not response_data.get("valid"):
return {
"valid": False,
"skipped": False,
"service": service_name,
"overrides": overrides,
"errors": [f"{scoped_label}: {response_data.get('error') or 'Validation failed.'}"],
}
errors = []
root_folders = response_data.get("root_folders", []) if isinstance(response_data, dict) else []
quality_profiles = response_data.get("quality_profiles", []) if isinstance(response_data, dict) else []
language_profiles = response_data.get("language_profiles", []) if isinstance(response_data, dict) else []
root_folder_names = {str(item.get("path") or "").strip() for item in root_folders if isinstance(item, dict)}
quality_profile_names = {str(item.get("name") or "").strip() for item in quality_profiles if isinstance(item, dict)}
language_profile_names = {str(item.get("name") or "").strip() for item in language_profiles if isinstance(item, dict)}
root_folder_path = overrides.get("root_folder_path")
if root_folder_path and root_folder_path not in root_folder_names:
errors.append(f"{scoped_label}: unknown root folder path '{root_folder_path}'.")
quality_profile = overrides.get("quality_profile")
if quality_profile and quality_profile not in quality_profile_names:
errors.append(f"{scoped_label}: unknown quality profile '{quality_profile}'.")
if service_name == "radarr":
availability = overrides.get("availability")
if availability and availability not in LIBRARY_RADARR_AVAILABILITY_VALUES:
errors.append(f"{scoped_label}: unsupported availability '{availability}'.")
else:
language_profile = overrides.get("language_profile")
if language_profile and language_profile not in language_profile_names:
errors.append(f"{scoped_label}: unknown language profile '{language_profile}'.")
series_type = overrides.get("series_type")
if series_type and series_type not in LIBRARY_SONARR_SERIES_TYPE_VALUES:
errors.append(f"{scoped_label}: unsupported series_type '{series_type}'.")
monitor_value = overrides.get("monitor")
if monitor_value and monitor_value not in LIBRARY_SONARR_MONITOR_VALUES:
errors.append(f"{scoped_label}: unsupported monitor value '{monitor_value}'.")
return {
"valid": not errors,
"skipped": False,
"service": service_name,
"overrides": overrides,
"errors": errors,
"root_folders": root_folders,
"quality_profiles": quality_profiles,
"language_profiles": language_profiles,
}
def _validate_and_organize_library_file_request(kind, data, type_key, location_key):
validator_info = LIBRARY_FILE_VALIDATORS.get(kind)
if not validator_info:
return jsonify({"valid": False, "error": f"Unsupported library file kind: {kind}"}), 400
_payload_type_key, _payload_location_key, validator = validator_info
valid, message, details = validations._normalize_metadata_validation_result(validator(data))
if not valid:
payload = {"valid": False, "error": message}
if details.get("message") or isinstance(details.get("files"), list):
payload["error_details"] = {
"text": details.get("message") or message,
"files": details.get("files") if isinstance(details.get("files"), list) else [],
}
if isinstance(details.get("files"), list):
payload["files"] = details["files"]
return jsonify(payload), 400
payload = {"valid": True}
if details.get("message"):
payload["message"] = details["message"]
if "validated_files" in details:
payload["validated_files"] = details["validated_files"]
if isinstance(details.get("files"), list):
payload["files"] = details["files"]
config_name = _resolve_request_config_name(data if isinstance(data, dict) else {})
library_scope = str((data or {}).get("library_id") or (data or {}).get("library_scope") or "").strip()
entry_type = str((data or {}).get(type_key) or "").strip().lower()
entry_location = str((data or {}).get(location_key) or "").strip()
if entry_type in LOCAL_LIBRARY_FILE_TYPES and entry_location and config_name and library_scope:
normalized_entry, changed, normalize_error = _normalize_library_external_entry(
kind,
{"type": entry_type, "location": entry_location},
config_name,
library_scope,
validate_local=False,
)
if normalize_error: