forked from StudioNirin/PlexCache-D
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplexcache_app.py
More file actions
executable file
·1491 lines (1218 loc) · 62.2 KB
/
Copy pathplexcache_app.py
File metadata and controls
executable file
·1491 lines (1218 loc) · 62.2 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
"""
Main JellyCache application.
Orchestrates all components and provides the main business logic.
"""
import sys
import time
import logging
import re
import shutil
import subprocess
from pathlib import Path
from typing import List, Set, Optional, Tuple
import os
from config import ConfigManager
from logging_config import LoggingManager
from system_utils import SystemDetector, FileUtils, SingleInstanceLock
from jellyfin_api import JellyfinManager, OnDeckItem
from file_operations import MultiPathModifier, SubtitleFinder, FileFilter, FileMover, CacheCleanup, PlexcachedRestorer, CacheTimestampTracker, WatchlistTracker, OnDeckTracker, CachePriorityManager, PlexcachedMigration
class JellyCacheApp:
"""Main JellyCache application class."""
def __init__(self, config_file: str, dry_run: bool = False,
quiet: bool = False, verbose: bool = False):
self.config_file = config_file
self.dry_run = dry_run # Don't move files, just simulate
self.quiet = quiet # Override notification level to errors-only
self.verbose = verbose # Enable DEBUG level logging
self.start_time = time.time()
# Initialize components
self.config_manager = ConfigManager(config_file)
self.system_detector = SystemDetector()
self.file_utils = FileUtils(self.system_detector.is_linux)
# Will be initialized after config loading
self.logging_manager = None
self.jellyfin_manager = None
self.file_path_modifier = None
self.subtitle_finder = None
self.file_filter = None
self.file_mover = None
# State variables
self.files_to_skip = []
self.media_to_cache = []
self.media_to_array = []
self.ondeck_items = set()
self.watchlist_items = set()
self.source_map = {} # Maps file paths to source ('ondeck' or 'watchlist')
# Tracking for restore vs move operations (for summary)
self.restored_count = 0
self.restored_bytes = 0
self.moved_to_array_count = 0
self.moved_to_array_bytes = 0
self.cached_bytes = 0
def run(self) -> None:
"""Run the main application."""
try:
# Setup logging first before any log messages
self._setup_logging()
if self.dry_run:
logging.warning("DRY-RUN MODE - No files will be moved")
if self.verbose:
logging.info("VERBOSE MODE - Showing DEBUG level logs")
# Prevent multiple instances from running simultaneously
script_folder = os.path.dirname(os.path.abspath(__file__))
lock_file = os.path.join(script_folder, "plexcache.lock")
self.instance_lock = SingleInstanceLock(lock_file)
if not self.instance_lock.acquire():
logging.critical("Another instance of PlexCache is already running. Exiting.")
print("ERROR: Another instance of PlexCache is already running. Exiting.")
return
# Check if Unraid mover is running (prevents race condition)
if self._is_mover_running():
logging.warning("Unraid mover is currently running. Exiting to prevent race condition.")
logging.warning("PlexCache will run on the next scheduled execution after mover completes.")
print("WARNING: Unraid mover is running. Exiting to avoid conflicts.")
return
# Load configuration
logging.debug("Loading configuration...")
self.config_manager.load_config()
# Set up notification handlers now that config is loaded
self._setup_notification_handlers()
# Set debug mode early so all debug messages show
self._set_debug_mode()
# Log startup diagnostics after log level is configured
if self.verbose:
self._log_startup_diagnostics()
# Initialize components that depend on config
logging.debug("Initializing components...")
self._initialize_components()
# Clean up stale exclude list entries (self-healing)
self.file_filter.clean_stale_exclude_entries()
# Check paths
logging.debug("Validating paths...")
self._check_paths()
# Connect to Jellyfin
self._connect_to_jellyfin()
# Check for active sessions
self._check_active_sessions()
# Process media
self._process_media()
# Move files
self._move_files()
# Update Unraid mover exclusion file
logging.debug("Updating Unraid mover exclusions...")
try:
self._update_unraid_mover_exclusions()
logging.debug("Unraid mover exclusions updated.")
except Exception as e:
logging.error(f"Failed to update Unraid mover exclusions: {e}")
# Log summary and cleanup
self._finish()
except Exception as e:
if self.logging_manager:
logging.critical(f"Application error: {type(e).__name__}: {e}", exc_info=True)
else:
print(f"Application error: {type(e).__name__}: {e}")
raise
def _update_unraid_mover_exclusions(self, tag_line: str = "### Plexcache exclusions below this line") -> None:
"""
Update the Unraid mover exclusions file by inserting or updating the
PlexCache exclusions section. Paths are retrieved from the config.
"""
# Get paths from config
exclusion_path = self.config_manager.get_unraid_mover_exclusions_file()
plexcache_path = self.config_manager.get_mover_exclude_file()
# Ensure the main file exists
if not exclusion_path.exists():
exclusion_path.parent.mkdir(parents=True, exist_ok=True)
exclusion_path.touch()
# Read current exclusion file
with open(exclusion_path, "r", encoding="utf-8") as f:
lines = f.read().splitlines()
# Ensure the tag line exists
if tag_line not in lines:
if lines and lines[-1].strip() != "":
lines.append("") # pad newline if last line isn't empty
lines.append(tag_line)
# Keep only content above the tag (inclusive)
tag_index = lines.index(tag_line)
lines = lines[:tag_index + 1]
# Load new exclusion entries from plexcache file
if plexcache_path.exists():
with open(plexcache_path, "r", encoding="utf-8") as f:
new_entries = [ln.strip() for ln in f if ln.strip()]
else:
new_entries = []
# Append the new entries
lines.extend(new_entries)
# Write updated file back
with open(exclusion_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
def _setup_logging(self) -> None:
"""Set up logging system (basic logging only, notifications set up after config load)."""
self.logging_manager = LoggingManager(
logs_folder=self.config_manager.paths.logs_folder,
log_level="", # Will be set from config
max_log_files=5
)
self.logging_manager.setup_logging()
logging.info("")
logging.info("=== JellyCache-R ===")
def _setup_notification_handlers(self) -> None:
"""Set up notification handlers after config is loaded."""
# Override notification level if --quiet flag is used
notification_config = self.config_manager.notification
if self.quiet:
notification_config.unraid_level = "error"
notification_config.webhook_level = "error"
self.logging_manager.setup_notification_handlers(
notification_config,
self.system_detector.is_unraid,
self.system_detector.is_docker
)
def _log_startup_diagnostics(self) -> None:
"""Log system diagnostics at startup in verbose mode for debugging."""
import platform
logging.debug("=== Startup Diagnostics ===")
logging.debug(f"Platform: {platform.system()} {platform.release()}")
logging.debug(f"Python: {platform.python_version()}")
if self.system_detector.is_linux:
try:
import pwd
uid = os.getuid()
gid = os.getgid()
username = pwd.getpwuid(uid).pw_name
logging.debug(f"Running as: {username} (uid={uid}, gid={gid})")
except Exception as e:
logging.debug(f"Could not get user info: {e}")
else:
logging.debug(f"Running as: {os.getlogin() if hasattr(os, 'getlogin') else 'unknown'}")
logging.debug(f"Unraid detected: {self.system_detector.is_unraid}")
logging.debug(f"Docker detected: {self.system_detector.is_docker}")
logging.debug("===========================")
def _log_diagnostic_summary(self, folders_cleaned: int, folders_failed: int) -> None:
"""Log diagnostic summary at end of run in verbose mode."""
logging.debug("")
logging.debug("=== Diagnostic Summary ===")
logging.debug(f"Files moved to cache: {len(self.media_to_cache)}")
logging.debug(f"Files moved to array: {len(self.media_to_array)}")
logging.debug(f"Empty folders removed: {folders_cleaned}")
if folders_failed > 0:
logging.debug(f"Empty folders failed: {folders_failed}")
logging.debug("==========================")
def _is_mover_running(self) -> bool:
"""Check if the Unraid mover is currently running.
This prevents race conditions where PlexCache caches files while
the mover is actively moving files, which can result in files
being moved back to the array before they're added to the exclude list.
Returns:
True if mover is running, False otherwise.
"""
if not self.system_detector.is_unraid:
return False
try:
# Check for mover process using pgrep
result = subprocess.run(
['pgrep', '-f', '/usr/local/sbin/mover'],
capture_output=True,
text=True
)
if result.returncode == 0 and result.stdout.strip():
return True
# Also check for the age_mover script (CA Mover Tuning plugin)
result = subprocess.run(
['pgrep', '-f', 'age_mover'],
capture_output=True,
text=True
)
return result.returncode == 0 and result.stdout.strip() != ''
except (subprocess.SubprocessError, FileNotFoundError):
# If we can't check, assume mover is not running
return False
def _init_jellyfin_manager(self) -> None:
"""Initialize the Jellyfin manager."""
logging.debug("Initializing Jellyfin manager...")
self.jellyfin_manager = JellyfinManager(
jellyfin_url=self.config_manager.jellyfin.jellyfin_url,
api_key=self.config_manager.jellyfin.api_key,
retry_limit=self.config_manager.performance.retry_limit,
delay=self.config_manager.performance.delay
)
def _init_path_modifier(self) -> None:
"""Initialize path modifier and subtitle finder."""
logging.debug("Initializing file operation components...")
all_mappings = self.config_manager.paths.path_mappings or []
enabled_mappings = [m for m in all_mappings if m.enabled]
logging.info(f"Using multi-path mode with {len(all_mappings)} mappings ({len(enabled_mappings)} enabled)")
self.file_path_modifier = MultiPathModifier(mappings=all_mappings)
if self.config_manager.has_legacy_path_arrays():
legacy_info = self.config_manager.get_legacy_array_info()
logging.info(f"Legacy path arrays detected: {legacy_info}")
logging.info("These are deprecated and can be removed from your settings file.")
logging.info("Path conversion now uses path_mappings exclusively.")
self.subtitle_finder = SubtitleFinder()
def _init_trackers(self, mover_exclude, timestamp_file) -> None:
"""Initialize timestamp, watchlist, and OnDeck trackers."""
# Run one-time migration to create .plexcached backups
migration = PlexcachedMigration(
exclude_file=str(mover_exclude),
cache_dir=self.config_manager.paths.cache_dir,
real_source=self.config_manager.paths.real_source,
script_folder=self.config_manager.paths.script_folder,
is_unraid=self.system_detector.is_unraid,
path_modifier=self.file_path_modifier
)
if migration.needs_migration():
logging.info("Running one-time migration for .plexcached backups...")
max_concurrent = self.config_manager.performance.max_concurrent_moves_array
migration.run_migration(dry_run=self.dry_run, max_concurrent=max_concurrent)
self.timestamp_tracker = CacheTimestampTracker(str(timestamp_file))
watchlist_tracker_file = self.config_manager.get_watchlist_tracker_file()
self.watchlist_tracker = WatchlistTracker(str(watchlist_tracker_file))
ondeck_tracker_file = os.path.join(
self.config_manager.paths.script_folder,
"plexcache_ondeck_tracker.json"
)
self.ondeck_tracker = OnDeckTracker(ondeck_tracker_file)
def _init_file_operations(self, mover_exclude) -> None:
"""Initialize file filter and file mover."""
self.file_filter = FileFilter(
real_source=self.config_manager.paths.real_source,
cache_dir=self.config_manager.paths.cache_dir,
is_unraid=self.system_detector.is_unraid,
mover_cache_exclude_file=str(mover_exclude),
timestamp_tracker=self.timestamp_tracker,
cache_retention_hours=self.config_manager.cache.cache_retention_hours,
ondeck_tracker=self.ondeck_tracker,
watchlist_tracker=self.watchlist_tracker,
path_modifier=self.file_path_modifier
)
self.file_mover = FileMover(
real_source=self.config_manager.paths.real_source,
cache_dir=self.config_manager.paths.cache_dir,
is_unraid=self.system_detector.is_unraid,
file_utils=self.file_utils,
debug=self.dry_run,
mover_cache_exclude_file=str(mover_exclude),
timestamp_tracker=self.timestamp_tracker,
path_modifier=self.file_path_modifier
)
def _init_cache_management(self) -> None:
"""Initialize cache cleanup and priority manager."""
cache_folders = []
cache_dir = self.config_manager.paths.cache_dir
for mapping in self.config_manager.paths.path_mappings or []:
if mapping.cacheable and mapping.enabled and mapping.cache_path:
cache_path = mapping.cache_path.rstrip('/')
if cache_path.startswith(cache_dir.rstrip('/')):
rel_path = cache_path[len(cache_dir.rstrip('/')):].lstrip('/')
if rel_path and rel_path not in cache_folders:
cache_folders.append(rel_path)
else:
folder_name = os.path.basename(cache_path)
if folder_name and folder_name not in cache_folders:
cache_folders.append(folder_name)
self.cache_cleanup = CacheCleanup(
self.config_manager.paths.cache_dir,
cache_folders
)
self.priority_manager = CachePriorityManager(
timestamp_tracker=self.timestamp_tracker,
watchlist_tracker=self.watchlist_tracker,
ondeck_tracker=self.ondeck_tracker,
eviction_min_priority=self.config_manager.cache.eviction_min_priority,
number_episodes=self.config_manager.jellyfin.number_episodes
)
def _initialize_components(self) -> None:
"""Initialize components that depend on configuration."""
logging.debug("Initializing application components...")
# Initialize Jellyfin manager
self._init_jellyfin_manager()
# Initialize path modifier and subtitle finder
self._init_path_modifier()
# Get file paths for trackers
mover_exclude = self.config_manager.get_mover_exclude_file()
timestamp_file = self.config_manager.get_timestamp_file()
logging.debug(f"Mover exclude file: {mover_exclude}")
logging.debug(f"Timestamp file: {timestamp_file}")
# Create exclude file on startup if it doesn't exist
if not mover_exclude.exists():
mover_exclude.touch()
logging.info(f"Created mover exclude file: {mover_exclude}")
# Initialize trackers
self._init_trackers(mover_exclude, timestamp_file)
# Initialize file filter and mover
self._init_file_operations(mover_exclude)
# Initialize cache cleanup and priority manager
self._init_cache_management()
logging.debug("All components initialized successfully")
def _ensure_cache_path_exists(self, cache_path: str) -> None:
"""Ensure a cache directory exists, creating it if necessary."""
if not os.path.exists(cache_path):
try:
os.makedirs(cache_path, exist_ok=True)
logging.info(f"Created missing cache directory: {cache_path}")
except OSError as e:
raise FileNotFoundError(f"Cannot create cache directory {cache_path}: {e}")
def _check_paths(self) -> None:
"""Check that required paths exist and are accessible."""
if self.config_manager.paths.path_mappings:
# Multi-path mode: check paths from enabled mappings
for mapping in self.config_manager.paths.path_mappings:
if mapping.enabled:
if mapping.real_path:
self.file_utils.check_path_exists(mapping.real_path)
if mapping.cacheable and mapping.cache_path:
# Create cache directory if it doesn't exist
self._ensure_cache_path_exists(mapping.cache_path)
else:
# Legacy single-path mode
if self.config_manager.paths.real_source:
self.file_utils.check_path_exists(self.config_manager.paths.real_source)
if self.config_manager.paths.cache_dir:
# Create cache directory if it doesn't exist
self._ensure_cache_path_exists(self.config_manager.paths.cache_dir)
def _connect_to_jellyfin(self) -> None:
"""Connect to the Jellyfin server and load user information."""
self.jellyfin_manager.connect()
# Load user information once at startup
if self.config_manager.jellyfin.users_toggle:
# Combine all skip lists for user loading
skip_users = list(set(
(self.config_manager.jellyfin.skip_ondeck or []) +
(self.config_manager.jellyfin.skip_favorites or [])
))
# Load user information
self.jellyfin_manager.load_user_tokens(
skip_users=skip_users,
settings_users=self.config_manager.jellyfin.users
)
def _check_active_sessions(self) -> None:
"""Check for active Jellyfin sessions."""
sessions = self.jellyfin_manager.get_active_sessions()
if sessions:
if self.config_manager.exit_if_active_session:
logging.warning('There is an active session. Exiting...')
sys.exit('There is an active session. Exiting...')
else:
self._process_active_sessions(sessions)
if self.files_to_skip:
logging.info(f"Skipped {len(self.files_to_skip)} active session(s)")
def _process_active_sessions(self, sessions: List) -> None:
"""Process active sessions and add files to skip list."""
for session in sessions:
try:
media_path = self._get_media_path_from_session(session)
if media_path:
# Convert Plex path to real path so it matches during filtering
converted_paths = self.file_path_modifier.modify_file_paths([media_path])
if converted_paths:
converted_path = converted_paths[0]
logging.debug(f"Skipping active session file: {converted_path}")
self.files_to_skip.append(converted_path)
except Exception as e:
logging.error(f"Error processing session {session}: {type(e).__name__}: {e}")
def _get_media_path_from_session(self, session) -> Optional[str]:
"""Extract media file path from a Jellyfin session. Returns None if unable to extract."""
try:
# Get the currently playing item from the session
now_playing = session.get("NowPlayingItem")
if not now_playing:
return None
item_id = now_playing.get("Id")
if not item_id:
return None
# Get the file path for this item
file_path = self.jellyfin_manager.get_media_file_path(item_id)
if file_path:
media_title = now_playing.get("Name", "Unknown")
media_type = now_playing.get("Type", "Unknown")
if media_type == "Episode":
show_title = now_playing.get("SeriesName", "")
logging.debug(f"Active session detected, skipping: {show_title} - {media_title}")
elif media_type == "Movie":
logging.debug(f"Active session detected, skipping: {media_title}")
return file_path
return None
except Exception as e:
logging.error(f"Error extracting media path: {type(e).__name__}: {e}")
return None
def _set_debug_mode(self) -> None:
"""Set logging level based on verbose flag."""
if self.verbose:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
def _process_media(self) -> None:
"""Process all media types (onDeck, watchlist, watched)."""
logging.info("")
logging.info("--- Fetching Media ---")
# Use a set to collect already-modified paths (real source paths)
modified_paths_set = set()
# Clear OnDeck tracker at start of each run (OnDeck status is ephemeral)
self.ondeck_tracker.clear_for_run()
# Fetch Continue Watching Media (Jellyfin equivalent of OnDeck) - returns List[OnDeckItem] with file path, username, and episode metadata
logging.debug("Fetching Continue Watching media...")
ondeck_items_list = self.jellyfin_manager.get_on_deck_media(
self.config_manager.jellyfin.valid_sections or [],
self.config_manager.jellyfin.days_to_monitor,
self.config_manager.jellyfin.number_episodes,
self.config_manager.jellyfin.users_toggle,
self.config_manager.jellyfin.skip_ondeck or []
)
# Extract just the file paths for path modification
ondeck_files = [item.file_path for item in ondeck_items_list]
# Log Continue Watching summary (count users with items)
ondeck_users = set(item.username for item in ondeck_items_list)
if ondeck_items_list:
logging.info(f"Continue Watching: {len(ondeck_items_list)} items from {len(ondeck_users)} users")
else:
logging.info("Continue Watching: 0 items")
# Edit file paths for Continue Watching media (convert jellyfin paths to real paths)
logging.debug("Modifying file paths for Continue Watching media...")
modified_ondeck = self.file_path_modifier.modify_file_paths(ondeck_files)
# Build a mapping from original jellyfin path to modified real path
jellyfin_to_real = dict(zip(ondeck_files, modified_ondeck))
# Populate OnDeck tracker with user info and episode metadata using modified paths
for item in ondeck_items_list:
real_path = jellyfin_to_real.get(item.file_path, item.file_path)
self.ondeck_tracker.update_entry(
real_path,
item.username,
episode_info=item.episode_info,
is_current_ondeck=item.is_current_ondeck
)
# Store modified OnDeck items for filtering later
self.ondeck_items = set(modified_ondeck)
modified_paths_set.update(self.ondeck_items)
# Track source for OnDeck items
for item in self.ondeck_items:
self.source_map[item] = "ondeck"
# Fetch subtitles for Continue Watching media (already using real paths)
logging.debug("Finding subtitles for Continue Watching media...")
ondeck_with_subtitles = self.subtitle_finder.get_media_subtitles(list(self.ondeck_items), files_to_skip=set(self.files_to_skip))
subtitle_count = len(ondeck_with_subtitles) - len(self.ondeck_items)
modified_paths_set.update(ondeck_with_subtitles)
logging.debug(f"Found {subtitle_count} subtitle files for Continue Watching media")
# Track source for OnDeck subtitles
for item in ondeck_with_subtitles:
if item not in self.source_map:
self.source_map[item] = "ondeck"
# Process favorites (Jellyfin equivalent of watchlist) (returns already-modified paths)
if self.config_manager.cache.favorites_toggle:
logging.debug("Processing favorites media...")
favorites_items = self._process_favorites()
if favorites_items:
# Store favorites items (don't override ondeck source for items in both)
self.watchlist_items = favorites_items
modified_paths_set.update(favorites_items)
# Track source for favorites items (only if not already tracked as ondeck)
for item in favorites_items:
if item not in self.source_map:
self.source_map[item] = "favorites"
# Run modify_file_paths on all collected paths to ensure consistent path format
logging.debug("Finalizing media to cache list...")
self.media_to_cache = self.file_path_modifier.modify_file_paths(list(modified_paths_set))
# Log consolidated summary of skipped disabled libraries
self.file_path_modifier.log_disabled_skips_summary()
# Log total media to cache
logging.info(f"Total media to cache: {len(self.media_to_cache)} files")
# Check for files that should be moved back to array (no longer needed in cache)
# Only check if watched_move is enabled - otherwise files stay on cache indefinitely
# Skip if favorites data is incomplete (jellyfin unreachable) to prevent accidental moves
if self.config_manager.cache.watched_move:
if not self.jellyfin_manager.is_favorites_data_complete():
logging.warning("Skipping array restore - favorites data incomplete (Jellyfin unreachable)")
logging.warning("Files will remain on cache until next successful run")
else:
logging.debug("Checking for files to move back to array...")
self._check_files_to_move_back_to_array()
def _process_favorites(self) -> set:
"""Process favorites media (Jellyfin equivalent of Plex watchlist) and return a set of modified file paths and subtitles.
Also updates the watchlist tracker with favorited timestamps for retention tracking.
"""
result_set = set()
retention_days = self.config_manager.cache.favorites_retention_days
expired_count = 0
try:
if retention_days > 0:
logging.debug(f"Favorites retention enabled: {retention_days} days")
# --- Fetch favorites from Jellyfin ---
# API returns (file_path, username, favorited_at) tuples
fetched_favorites = list(self.jellyfin_manager.get_favorites_media(
self.config_manager.jellyfin.valid_sections,
self.config_manager.cache.favorites_episodes,
self.config_manager.jellyfin.users_toggle,
self.config_manager.jellyfin.skip_favorites
))
for item in fetched_favorites:
file_path, username, favorited_at = item
# Update watchlist tracker with timestamp (keeping same tracker for compatibility)
self.watchlist_tracker.update_entry(file_path, username, favorited_at)
# Check favorites retention (skip expired items)
if retention_days > 0:
if self.watchlist_tracker.is_expired(file_path, retention_days):
expired_count += 1
continue
result_set.add(file_path)
if expired_count > 0:
logging.debug(f"Skipped {expired_count} favorites items due to retention expiry ({retention_days} days)")
# Log favorites summary
total_favorites = len(result_set)
logging.info(f"Favorites: {total_favorites} items")
# Modify file paths and fetch subtitles
modified_items = self.file_path_modifier.modify_file_paths(list(result_set))
result_set.update(modified_items)
subtitles = self.subtitle_finder.get_media_subtitles(modified_items, files_to_skip=set(self.files_to_skip))
result_set.update(subtitles)
except Exception as e:
logging.exception(f"An error occurred while processing favorites: {type(e).__name__}: {e}")
return result_set
def _extract_display_name(self, file_path: str) -> str:
"""Extract a human-readable display name from a file path.
Returns clean filename without quality/codec info.
"""
try:
filename = os.path.basename(file_path)
name = os.path.splitext(filename)[0]
# Remove quality/codec info in brackets
if '[' in name:
name = name[:name.index('[')].strip()
# Clean up trailing dashes
name = name.rstrip(' -').rstrip('-').strip()
return name if name else filename
except Exception:
return os.path.basename(file_path)
def _separate_restore_and_move(self, files_to_array: List[str]) -> Tuple[List[str], List[str]]:
"""Separate files into restore (.plexcached exists) vs actual move.
Args:
files_to_array: List of array paths to process
Returns:
Tuple of (files_to_restore, files_to_move)
"""
to_restore = []
to_move = []
for array_path in files_to_array:
plexcached_path = array_path + ".plexcached"
if os.path.exists(plexcached_path):
to_restore.append(array_path)
else:
to_move.append(array_path)
return to_restore, to_move
def _log_restore_and_move_summary(self, files_to_restore: List[str], files_to_move: List[str]) -> None:
"""Log summary of restore vs move operations at INFO level.
Also tracks counts and bytes for the final summary message.
"""
# Track counts and bytes for summary
self.restored_count = len(files_to_restore)
self.restored_bytes = 0
if files_to_restore:
# Calculate total size for restores (from .plexcached files)
for f in files_to_restore:
plexcached_path = f + ".plexcached"
if os.path.exists(plexcached_path):
try:
self.restored_bytes += os.path.getsize(plexcached_path)
except OSError:
pass
# These files have .plexcached backups on array - instant restore via rename
count = len(files_to_restore)
unit = "episode" if count == 1 else "episodes"
logging.info(f"Returning to array ({count} {unit}, instant via .plexcached):")
for f in files_to_restore[:6]: # Show first 6
display_name = self._extract_display_name(f)
logging.info(f" {display_name}")
if len(files_to_restore) > 6:
logging.info(f" ...and {len(files_to_restore) - 6} more")
if files_to_move:
# Calculate total size for actual moves
total_size = 0
for f in files_to_move:
# For moves, the file is on cache - need to get cache path
cache_path = f.replace(
self.config_manager.paths.real_source,
self.config_manager.paths.cache_dir, 1
)
if os.path.exists(cache_path):
try:
total_size += os.path.getsize(cache_path)
except OSError:
pass
# Track for summary
self.moved_to_array_count = len(files_to_move)
self.moved_to_array_bytes = total_size
# These files need actual data transfer from cache to array
count = len(files_to_move)
unit = "episode" if count == 1 else "episodes"
size_str = f"{total_size / (1024**3):.2f} GB" if total_size > 0 else ""
size_part = f", {size_str}" if size_str else ""
logging.info(f"Copying to array ({count} {unit}{size_part}):")
for f in files_to_move[:6]: # Show first 6
display_name = self._extract_display_name(f)
logging.info(f" {display_name}")
if len(files_to_move) > 6:
logging.info(f" ...and {len(files_to_move) - 6} more")
def _move_files(self) -> None:
"""Move files to their destinations."""
logging.info("")
logging.info("--- Moving Files ---")
# Move watched files to array
if self.config_manager.cache.watched_move and self.media_to_array:
# Log restore vs move summary before processing
files_to_restore, files_to_move = self._separate_restore_and_move(self.media_to_array)
if files_to_restore or files_to_move:
self._log_restore_and_move_summary(files_to_restore, files_to_move)
self._safe_move_files(self.media_to_array, 'array')
# Move files to cache
logging.debug(f"Files being passed to cache move: {self.media_to_cache}")
self._safe_move_files(self.media_to_cache, 'cache')
def _safe_move_files(self, files: List[str], destination: str) -> None:
"""Safely move files with consistent error handling."""
try:
# Pass source map only when moving to cache
source_map = self.source_map if destination == 'cache' else None
# Get real_source - in multi-path mode, use first enabled mapping's real_path
real_source = self.config_manager.paths.real_source
if not real_source and self.config_manager.paths.path_mappings:
for mapping in self.config_manager.paths.path_mappings:
if mapping.enabled and mapping.real_path:
real_source = mapping.real_path
break
# Get cache_dir - in multi-path mode, use first cacheable mapping's cache_path
cache_dir = self.config_manager.paths.cache_dir
if not cache_dir and self.config_manager.paths.path_mappings:
for mapping in self.config_manager.paths.path_mappings:
if mapping.enabled and mapping.cacheable and mapping.cache_path:
cache_dir = mapping.cache_path
break
self._check_free_space_and_move_files(
files, destination,
real_source,
cache_dir,
source_map
)
except Exception as e:
error_msg = f"Error moving media files to {destination}: {type(e).__name__}: {e}"
if self.dry_run:
logging.error(error_msg)
else:
logging.critical(error_msg)
sys.exit(1)
def _get_effective_cache_limit(self, cache_dir: str) -> tuple:
"""Calculate effective cache limit in bytes, handling percentage-based limits.
Args:
cache_dir: Path to the cache directory.
Returns:
Tuple of (limit_bytes, limit_readable_str). Returns (0, None) if no limit set.
"""
cache_limit_bytes = self.config_manager.cache.cache_limit_bytes
if cache_limit_bytes == 0:
return (0, None)
if cache_limit_bytes < 0:
# Negative value indicates percentage
percent = abs(cache_limit_bytes)
try:
total_drive_size = self.file_utils.get_total_drive_size(cache_dir)
limit_bytes = int(total_drive_size * percent / 100)
limit_readable = f"{percent}% of {total_drive_size / (1024**3):.1f}GB = {limit_bytes / (1024**3):.1f}GB"
return (limit_bytes, limit_readable)
except Exception as e:
logging.warning(f"Could not calculate cache drive size for percentage limit: {e}")
return (0, None)
else:
limit_readable = f"{cache_limit_bytes / (1024**3):.1f}GB"
return (cache_limit_bytes, limit_readable)
def _get_plexcache_tracked_size(self) -> tuple:
"""Calculate current PlexCache tracked size from exclude file.
Returns:
Tuple of (total_bytes, cached_files_list). Returns (0, []) on error.
"""
exclude_file = self.config_manager.get_mover_exclude_file()
if not exclude_file.exists():
return (0, [])
plexcache_tracked = 0
cached_files = []
try:
with open(exclude_file, 'r') as f:
cached_files = [line.strip() for line in f if line.strip()]
for cached_file in cached_files:
try:
if os.path.exists(cached_file):
plexcache_tracked += os.path.getsize(cached_file)
except (OSError, FileNotFoundError):
pass
except Exception as e:
logging.warning(f"Error reading exclude file: {e}")
return (0, [])
return (plexcache_tracked, cached_files)
def _apply_cache_limit(self, media_files: List[str], cache_dir: str) -> List[str]:
"""Apply cache size limit, filtering out files that would exceed the limit.
Returns the list of files that fit within the cache limit.
Files are prioritized in the order they appear (OnDeck items should come first).
"""
cache_limit_bytes, limit_readable = self._get_effective_cache_limit(cache_dir)
# No limit set or error calculating
if cache_limit_bytes == 0:
return media_files
# Get current PlexCache tracked size
plexcache_tracked, _ = self._get_plexcache_tracked_size()
# Get total cache drive usage
try:
disk_usage = shutil.disk_usage(cache_dir)
drive_usage_gb = disk_usage.used / (1024**3)
except Exception:
drive_usage_gb = 0
plexcache_tracked_gb = plexcache_tracked / (1024**3)
logging.info(f"Cache limit: {limit_readable}")
logging.info(f"Cache drive usage: {drive_usage_gb:.2f}GB, PlexCache tracked: {plexcache_tracked_gb:.2f}GB")
# Filter files that fit within limit
available_space = cache_limit_bytes - plexcache_tracked
files_to_cache = []
skipped_count = 0
skipped_size = 0
for file in media_files:
try:
file_size = os.path.getsize(file)
if file_size <= available_space:
files_to_cache.append(file)
available_space -= file_size
else:
skipped_count += 1
skipped_size += file_size
except (OSError, FileNotFoundError):
# File doesn't exist or can't be accessed, skip it
pass
if skipped_count > 0:
skipped_gb = skipped_size / (1024**3)
logging.warning(f"Cache limit reached: skipped {skipped_count} files ({skipped_gb:.2f}GB) that would exceed the {limit_readable} limit")
return files_to_cache
def _run_smart_eviction(self, needed_space_bytes: int = 0) -> tuple:
"""Run smart eviction to free cache space for higher-priority items.
Evicts lowest-priority cached items that fall below the minimum priority
threshold. Restores their .plexcached backup files on the array.
Args:
needed_space_bytes: Additional space needed (0 = just evict low-priority items)
Returns:
Tuple of (files_evicted_count, bytes_freed)
"""
eviction_mode = self.config_manager.cache.cache_eviction_mode
if eviction_mode == "none":
return (0, 0)
cache_dir = self.config_manager.paths.cache_dir
cache_limit_bytes, _ = self._get_effective_cache_limit(cache_dir)
if cache_limit_bytes == 0:
return (0, 0)
# Get current PlexCache tracked size and file list
plexcache_tracked, cached_files = self._get_plexcache_tracked_size()
if not cached_files:
return (0, 0)
# Check if we need to evict
threshold_percent = self.config_manager.cache.cache_eviction_threshold_percent
threshold_bytes = cache_limit_bytes * threshold_percent / 100
if plexcache_tracked < threshold_bytes and needed_space_bytes == 0:
logging.debug(f"Cache usage ({plexcache_tracked/1e9:.1f}GB) below threshold ({threshold_bytes/1e9:.1f}GB), skipping eviction")
return (0, 0)
# Calculate how much space to free
space_to_free = max(needed_space_bytes, plexcache_tracked - threshold_bytes)
if space_to_free <= 0:
return (0, 0)
logging.info(f"Smart eviction: need to free {space_to_free/1e9:.2f}GB")
# Get eviction candidates based on mode
if eviction_mode == "smart":
candidates = self.priority_manager.get_eviction_candidates(cached_files, int(space_to_free))
elif eviction_mode == "fifo":
# FIFO: evict oldest cached files first (by timestamp)
candidates = self._get_fifo_eviction_candidates(cached_files, int(space_to_free))