forked from StudioNirin/PlexCache-D
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings_service.py
More file actions
1735 lines (1501 loc) · 75.2 KB
/
Copy pathsettings_service.py
File metadata and controls
1735 lines (1501 loc) · 75.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
"""Settings service - load and save PlexCache settings"""
import json
import logging
import os
import threading
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional, List
from dataclasses import dataclass, field, asdict
from web.config import DATA_DIR, SETTINGS_FILE, IS_DOCKER
from web.dependencies import get_system_detector
logger = logging.getLogger(__name__)
# File cache for Plex data (web UI) - use DATA_DIR for Docker compatibility
WEB_PLEX_CACHE_FILE = DATA_DIR / "web_plex_cache.json"
@dataclass
class PathMapping:
"""Represents a path mapping configuration"""
name: str
plex_path: str
real_path: str
cache_path: Optional[str] = None
cacheable: bool = True
enabled: bool = True
section_id: Optional[int] = None
@dataclass
class PlexSettings:
"""Plex server settings"""
plex_url: str = ""
plex_token: str = ""
valid_sections: List[int] = field(default_factory=list)
days_to_monitor: int = 183
number_episodes: int = 5
@dataclass
class CacheSettings:
"""Cache behavior settings"""
watchlist_toggle: bool = True
watchlist_episodes: int = 3
watchlist_retention_days: int = 0
watched_move: bool = True
cache_retention_hours: int = 12
cache_drive_size: str = "" # Manual override for drive size (for ZFS)
cache_limit: str = "250GB"
min_free_space: str = ""
plexcache_quota: str = ""
cache_eviction_mode: str = "none"
cache_eviction_threshold_percent: int = 95
eviction_min_priority: int = 60
remote_watchlist_toggle: bool = False
remote_watchlist_rss_url: str = ""
@dataclass
class NotificationSettings:
"""Notification settings"""
notification_type: str = "system"
unraid_level: str = "summary"
webhook_url: str = ""
webhook_level: str = "summary"
class SettingsService:
"""Service for loading and saving PlexCache settings"""
def __init__(self):
self.settings_file = SETTINGS_FILE
self._cached_settings: Optional[Dict] = None
self._last_loaded: Optional[datetime] = None
# Cache for Plex data (libraries, users) - expires after 1 hour
self._plex_libraries_cache: Optional[List[Dict]] = None
self._plex_users_cache: Optional[List[Dict]] = None
self._plex_cache_time: Optional[datetime] = None
self._plex_cache_ttl = 3600 # 1 hour
self._cache_lock = threading.Lock()
self._last_plex_error: Optional[str] = None # Last Plex connection error
# Load from file cache on startup
self._load_plex_cache_from_file()
def _load_raw(self) -> Dict[str, Any]:
"""Load raw settings from file"""
if not self.settings_file.exists():
return {}
try:
with open(self.settings_file, 'r', encoding='utf-8') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return {}
def _save_raw(self, settings: Dict[str, Any]) -> bool:
"""Save raw settings to file atomically (write-temp-then-replace).
An in-place truncating write (open 'w') lets concurrent readers — e.g.
get_time_format() during a dashboard render — observe an empty/partial
file and silently fall back to defaults. The atomic replace prevents
that: readers always see either the old or the new complete file.
"""
from core.file_operations import save_json_atomically
try:
if not save_json_atomically(str(self.settings_file), settings, label="settings"):
return False
# Restrict permissions — settings contain secrets (Plex token, password hashes)
try:
os.chmod(self.settings_file, 0o600)
except OSError:
pass # Non-fatal (Windows, Docker with different uid)
self._cached_settings = None # Invalidate cache
return True
except (IOError, OSError):
return False
def _sanitize_path(self, path: Optional[str]) -> Optional[str]:
"""Strip whitespace from path to prevent issues like '/mnt/user0 ' creating bogus directories"""
if path is None:
return None
return path.strip()
def _sanitize_path_mapping(self, mapping: Dict[str, Any]) -> Dict[str, Any]:
"""Sanitize all path fields in a path mapping"""
sanitized = mapping.copy()
path_fields = ["plex_path", "real_path", "cache_path", "host_cache_path"]
for field in path_fields:
if field in sanitized and sanitized[field]:
sanitized[field] = self._sanitize_path(sanitized[field])
return sanitized
def _load_plex_cache_from_file(self):
"""Load Plex data cache from file on startup"""
try:
if WEB_PLEX_CACHE_FILE.exists():
with open(WEB_PLEX_CACHE_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
# Check if cache is still valid
cache_time_str = data.get("cache_time")
if cache_time_str:
cache_time = datetime.fromisoformat(cache_time_str)
elapsed = (datetime.now() - cache_time).total_seconds()
if elapsed < self._plex_cache_ttl:
self._plex_libraries_cache = data.get("libraries", [])
self._plex_users_cache = data.get("users", [])
self._plex_cache_time = cache_time
except (json.JSONDecodeError, IOError, ValueError):
pass
def _save_plex_cache_to_file(self):
"""Save Plex data cache to file"""
try:
# Ensure data directory exists
WEB_PLEX_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
data = {
"cache_time": self._plex_cache_time.isoformat() if self._plex_cache_time else None,
"libraries": self._plex_libraries_cache or [],
"users": self._plex_users_cache or []
}
with open(WEB_PLEX_CACHE_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
except IOError:
pass
def get_all(self) -> Dict[str, Any]:
"""Get all settings as a dictionary"""
return self._load_raw()
def get_plex_settings(self) -> Dict[str, Any]:
"""Get Plex-related settings"""
raw = self._load_raw()
return {
"plex_url": raw.get("PLEX_URL", ""),
"plex_token": raw.get("PLEX_TOKEN", ""),
"valid_sections": raw.get("valid_sections", []),
"days_to_monitor": raw.get("days_to_monitor", 183),
"number_episodes": raw.get("number_episodes", 5),
"users_toggle": raw.get("users_toggle", True),
"skip_ondeck": raw.get("skip_ondeck", []),
"skip_watchlist": raw.get("skip_watchlist", [])
}
def save_plex_settings(self, settings: Dict[str, Any]) -> bool:
"""Save Plex settings"""
raw = self._load_raw()
# Check if URL or token changed - if so, invalidate cache
old_url = raw.get("PLEX_URL", "")
old_token = raw.get("PLEX_TOKEN", "")
new_url = settings.get("plex_url", old_url)
new_token = settings.get("plex_token", old_token)
raw["PLEX_URL"] = new_url
raw["PLEX_TOKEN"] = new_token
if "valid_sections" in settings:
raw["valid_sections"] = settings["valid_sections"]
if "days_to_monitor" in settings:
raw["days_to_monitor"] = int(float(settings["days_to_monitor"]))
if "number_episodes" in settings:
raw["number_episodes"] = int(float(settings["number_episodes"]))
if "users_toggle" in settings:
raw["users_toggle"] = settings["users_toggle"]
if "skip_ondeck" in settings:
raw["skip_ondeck"] = settings["skip_ondeck"]
if "skip_watchlist" in settings:
raw["skip_watchlist"] = settings["skip_watchlist"]
result = self._save_raw(raw)
# Invalidate cache if credentials changed to force fresh fetch
if result and (old_url != new_url or old_token != new_token):
self.invalidate_plex_cache()
return result
def get_path_mappings(self) -> List[Dict[str, Any]]:
"""Get path mappings"""
raw = self._load_raw()
return raw.get("path_mappings", [])
def save_path_mappings(self, mappings: List[Dict[str, Any]]) -> bool:
"""Save path mappings (sanitizes paths to strip whitespace)"""
raw = self._load_raw()
raw["path_mappings"] = [self._sanitize_path_mapping(m) for m in mappings]
return self._save_raw(raw)
def add_path_mapping(self, mapping: Dict[str, Any]) -> bool:
"""Add a new path mapping (sanitizes paths to strip whitespace)"""
raw = self._load_raw()
mappings = raw.get("path_mappings", [])
mappings.append(self._sanitize_path_mapping(mapping))
raw["path_mappings"] = mappings
return self._save_raw(raw)
def update_path_mapping(self, index: int, mapping: Dict[str, Any]) -> bool:
"""Update an existing path mapping by index (sanitizes paths to strip whitespace).
Preserves section_id from the existing mapping if not in the update dict.
"""
raw = self._load_raw()
mappings = raw.get("path_mappings", [])
if 0 <= index < len(mappings):
# Preserve section_id from existing mapping if not provided
existing = mappings[index]
if "section_id" not in mapping and "section_id" in existing:
mapping["section_id"] = existing["section_id"]
mappings[index] = self._sanitize_path_mapping(mapping)
raw["path_mappings"] = mappings
return self._save_raw(raw)
return False
def delete_path_mapping(self, index: int) -> bool:
"""Delete a path mapping by index"""
raw = self._load_raw()
mappings = raw.get("path_mappings", [])
if 0 <= index < len(mappings):
mappings.pop(index)
raw["path_mappings"] = mappings
return self._save_raw(raw)
return False
def _rebuild_valid_sections(self, raw: Dict[str, Any]) -> None:
"""Rebuild valid_sections from enabled path_mappings with section_id.
Scans all enabled path_mappings that have a section_id set,
collects unique IDs, and writes them sorted to raw["valid_sections"].
"""
mappings = raw.get("path_mappings", [])
section_ids = set()
for m in mappings:
sid = m.get("section_id")
if sid is not None and m.get("enabled", True):
section_ids.add(int(sid))
raw["valid_sections"] = sorted(section_ids)
@staticmethod
def warn_cache_path(cache_path: Optional[str]) -> Optional[str]:
"""Return a warning string if a cache_path looks risky, else None.
Non-blocking — this helper only produces human-readable warnings.
Callers log them or surface them in the UI. Some configurations
(e.g. a dedicated cache drive with media at the drive root, or a
container where /mnt/cache isn't mounted and /mnt/user is the only
available path) legitimately use these values, so we never reject.
The two patterns that *usually* indicate misconfiguration from
issue #136:
- cache_path set to the bare cache drive root. Makes audits walk
the entire SSD including appdata, docker, and other shares.
- cache_path pointing at the Unraid FUSE merged view
('/mnt/user/...', but not /mnt/user0/). Audits go through shfs
and the cache-vs-array logic can't distinguish the two layers.
Docker-specific check (issue #139):
- cache_path not backed by a real bind mount. Writes go to
the overlay filesystem (docker.img) instead of the host drive.
"""
if not cache_path:
return None
normalized = cache_path.rstrip("/\\")
if not normalized:
return None
# Docker mount validation (issue #139) — highest priority check
if IS_DOCKER:
detector = get_system_detector()
is_mounted, _ = detector.is_path_bind_mounted(normalized)
if not is_mounted:
return (
f"This path is not backed by a Docker bind mount — "
f"files written here will go into the container's "
f"overlay filesystem (docker.img), not your host drive. "
f"Check your container's volume configuration and use "
f"the path as seen inside the container (e.g., "
f"/mnt/cache/...), not the host path."
)
if normalized == "/mnt/cache":
return (
"cache_path is set to the bare cache drive root. On most "
"Unraid setups this makes audits walk your entire cache "
"drive (appdata, docker, every share). If that's not what "
"you want, point it at a specific media subfolder like "
"/mnt/cache/Media/Movies/."
)
if normalized.startswith("/mnt/user/") and not normalized.startswith("/mnt/user0/"):
suggestion = normalized.replace("/mnt/user/", "/mnt/cache/", 1)
return (
f"cache_path points at the Unraid FUSE merged view "
f"('{cache_path}'). This is slower than a cache-direct "
f"path and can confuse cache-vs-array detection during "
f"audits. If /mnt/cache/ is available in your container, "
f"consider using '{suggestion}/' instead."
)
return None
def detect_path_mapping_health_issues(self) -> List[Dict[str, str]]:
"""Scan path_mappings for known-bad configurations and return warnings.
Issue #136 taught us two failure modes that crater audit performance
on Unraid:
1. A legacy-migrated "Default (migrated)" mapping whose cache_path
is the bare cache drive root ("/mnt/cache/" or "/mnt/cache").
This makes MaintenanceService.run_full_audit() walk the entire
SSD — appdata, docker, every other share.
2. A mapping whose cache_path points at the Unraid FUSE merged view
("/mnt/user/...") instead of the cache drive directly
("/mnt/cache/..."). FUSE reads are 3-5x slower than cache-direct
and the audit's cache-vs-array logic can't distinguish the two.
Issue #139 added a third failure mode specific to Docker:
3. A mapping whose cache_path or real_path is not backed by a real
bind mount. Writes go to the overlay filesystem (docker.img)
instead of the host drive.
Returns a list of dicts with keys: mapping_name, issue_type, message.
Empty list means no issues detected. This is a read-only check —
fixes must be performed by the user via Settings -> Libraries.
"""
raw = self._load_raw()
mappings = raw.get("path_mappings", [])
issues: List[Dict[str, str]] = []
# Docker mount validation (issue #139)
if IS_DOCKER:
detector = get_system_detector()
# Container switched the default from /mnt/user/ to /mnt/user0/.
# If the user updated their Docker template but still has legacy
# /mnt/user/... paths in their mappings, point them at the exact
# replacement instead of the generic "check your mounts" message.
user0_mounted, _ = detector.is_path_bind_mounted("/mnt/user0")
for m in mappings:
if not m.get("enabled", True):
continue
name = m.get("name", "(unnamed)")
for field_name, label in [("cache_path", "cache_path"), ("real_path", "real_path")]:
path_val = (m.get(field_name) or "").rstrip("/\\")
if not path_val:
continue
# host_cache_path is intentionally a host path — do NOT validate it
is_mounted, _ = detector.is_path_bind_mounted(path_val)
if is_mounted:
continue
# Specific case: legacy /mnt/user/... path while /mnt/user0
# IS mounted. Recommend the array-direct replacement.
if (
user0_mounted
and label == "real_path"
and path_val.startswith("/mnt/user/")
and not path_val.startswith("/mnt/user0/")
):
suggestion = "/mnt/user0/" + path_val[len("/mnt/user/"):]
issues.append({
"mapping_name": name,
"issue_type": "legacy_user_real_path",
"message": (
f"Mapping '{name}' has real_path '{m.get(field_name)}' "
f"but /mnt/user/ is no longer mounted in this container. "
f"Update the Array Path to '{suggestion}/' in "
f"Settings → Paths. /mnt/user0/ is the array-direct "
f"path and the new default — it avoids the FUSE layer "
f"entirely."
),
})
continue
issues.append({
"mapping_name": name,
"issue_type": "overlay_path",
"message": (
f"Mapping '{name}' has {label} set to "
f"'{m.get(field_name)}' which is not backed by "
f"a Docker bind mount. Writes to this path will "
f"go into the container's overlay filesystem "
f"(docker.img), not your host drive. Check your "
f"container's volume configuration."
),
})
for m in mappings:
if not m.get("enabled", True):
continue
name = m.get("name", "(unnamed)")
cache_path = (m.get("cache_path") or "").rstrip("/\\")
if not cache_path:
continue
# Issue 1: bare cache drive root
if cache_path in ("/mnt/cache", "/mnt/cache/"):
issues.append({
"mapping_name": name,
"issue_type": "cache_root",
"message": (
f"Mapping '{name}' has cache_path set to the cache drive "
f"root ('{m.get('cache_path')}'). On most Unraid setups "
f"this makes audits walk your entire cache drive "
f"(appdata, docker, every share). If you meant to target "
f"a specific media subfolder, edit it in Settings → "
f"Libraries. If you really do store media at the drive "
f"root, this warning can be ignored."
),
})
continue
# Issue 2: FUSE path instead of cache-direct
if cache_path.startswith("/mnt/user/") and not cache_path.startswith("/mnt/user0/"):
issues.append({
"mapping_name": name,
"issue_type": "fuse_cache_path",
"message": (
f"Mapping '{name}' has cache_path set to a FUSE merged "
f"path ('{m.get('cache_path')}'). This is slower than "
f"cache-direct and can confuse audit logic. If /mnt/cache "
f"is mounted in your container, consider switching to "
f"'/mnt/cache/...' in Settings → Libraries → {name}."
),
})
return issues
def migrate_link_path_mappings_to_libraries(self) -> bool:
"""One-time migration: match existing path_mappings to Plex libraries by plex_path.
Sets section_id on mappings whose plex_path matches a Plex library location.
Skips if any mapping already has a section_id (already migrated).
Returns True if migration was performed.
"""
raw = self._load_raw()
mappings = raw.get("path_mappings", [])
if not mappings:
return False
# Skip if any mapping already has section_id
if any(m.get("section_id") is not None for m in mappings):
return False
# Get Plex libraries to match against
libraries = self.get_plex_libraries()
if not libraries:
return False
# Build lookup: normalized plex_path → section_id
path_to_section = {}
for lib in libraries:
for loc in lib.get("locations", []):
normalized = loc.rstrip("/") + "/"
path_to_section[normalized] = lib["id"]
migrated = False
for m in mappings:
plex_path = m.get("plex_path", "").rstrip("/") + "/" if m.get("plex_path") else ""
if plex_path in path_to_section:
m["section_id"] = path_to_section[plex_path]
migrated = True
if migrated:
raw["path_mappings"] = mappings
self._rebuild_valid_sections(raw)
self._save_raw(raw)
logger.info("Migrated path mappings: linked to Plex library section IDs")
return migrated
def auto_fill_mapping(self, library: Dict, plex_location: str, settings: Dict[str, Any]) -> Dict[str, Any]:
"""Generate a pre-filled path mapping from a Plex library location.
Args:
library: Plex library dict with id, title, type, locations
plex_location: The specific Plex path for this location
settings: Current raw settings (for cache_dir)
Returns:
Dict suitable for adding to path_mappings
"""
# cache_dir is used as the cache-drive root for derivation. We never
# allow it to be a /mnt/user/ (FUSE) path — that's the bug condition
# in issue #136 where a misconfigured legacy setting produced
# cache_path='/mnt/user/Media/Movies/' instead of '/mnt/cache/...'.
raw_cache_dir = settings.get("cache_dir", "/mnt/cache").rstrip("/")
if raw_cache_dir.startswith("/mnt/user/") or raw_cache_dir in ("/mnt/user", "/mnt/user0"):
cache_dir = "/mnt/cache"
else:
cache_dir = raw_cache_dir or "/mnt/cache"
plex_path = plex_location if plex_location.endswith("/") else plex_location + "/"
# Derive display name — use folder name suffix when library has multiple locations
name = library["title"]
locations = library.get("locations", [])
if len(locations) > 1:
folder_name = plex_path.rstrip("/").rsplit("/", 1)[-1]
if folder_name and folder_name.lower() != name.lower():
name = f"{name} ({folder_name})"
# Suggest real_path based on common Docker path patterns
real_path = plex_path
path_recognized = False
for docker_prefix, host_prefix in [("/data/", "/mnt/user/"), ("/media/", "/mnt/user/")]:
if plex_path.startswith(docker_prefix):
real_path = plex_path.replace(docker_prefix, host_prefix, 1)
path_recognized = True
break
# Derive cache_path using prefix swap to preserve full structure
# e.g., /data/GUEST/Movies/ -> /mnt/cache/GUEST/Movies/
cache_path = plex_path
for docker_prefix in ["/data/", "/media/"]:
if plex_path.startswith(docker_prefix):
cache_path = plex_path.replace(docker_prefix, cache_dir + "/", 1)
break
return {
"name": name,
"plex_path": plex_path,
"real_path": real_path,
"cache_path": cache_path,
"host_cache_path": cache_path,
"cacheable": True,
"enabled": True,
"section_id": library["id"],
"auto_fill_recognized": path_recognized,
}
def get_cache_settings(self) -> Dict[str, Any]:
"""Get cache behavior settings"""
raw = self._load_raw()
return {
# Content discovery (moved from Plex tab)
"number_episodes": raw.get("number_episodes", 5),
"days_to_monitor": raw.get("days_to_monitor", 183),
"watchlist_toggle": raw.get("watchlist_toggle", True),
"watchlist_episodes": raw.get("watchlist_episodes", 3),
"prefetch_minimum_minutes": raw.get("prefetch_minimum_minutes", 0),
"watchlist_retention_days": raw.get("watchlist_retention_days", 0),
"ondeck_retention_days": raw.get("ondeck_retention_days", 0),
"watched_move": raw.get("watched_move", True),
"create_plexcached_backups": raw.get("create_plexcached_backups", True),
"cleanup_empty_folders": raw.get("cleanup_empty_folders", True),
"use_symlinks": raw.get("use_symlinks", False),
"hardlinked_files": raw.get("hardlinked_files", "skip"),
"check_hardlinks_on_restore": raw.get("check_hardlinks_on_restore", False),
"cache_associated_files": raw.get("cache_associated_files", "subtitles"),
"cache_retention_hours": raw.get("cache_retention_hours", 12),
"cache_drive_size": raw.get("cache_drive_size", ""),
"cache_limit": raw.get("cache_limit", "250GB"),
"min_free_space": raw.get("min_free_space", ""),
"plexcache_quota": raw.get("plexcache_quota", ""),
"cache_eviction_mode": raw.get("cache_eviction_mode", "none"),
"cache_eviction_threshold_percent": raw.get("cache_eviction_threshold_percent", 95),
"eviction_min_priority": raw.get("eviction_min_priority", 60),
"pinned_preferred_resolution": raw.get("pinned_preferred_resolution", "highest"),
"remote_watchlist_toggle": raw.get("remote_watchlist_toggle", False),
"remote_watchlist_rss_url": raw.get("remote_watchlist_rss_url", ""),
# Upgrade tracking
"auto_transfer_upgrades": raw.get("auto_transfer_upgrades", True),
"backup_upgraded_files": raw.get("backup_upgraded_files", True),
# Scanning
"excluded_folders": raw.get("excluded_folders", []),
# Advanced settings
"max_concurrent_moves_array": raw.get("max_concurrent_moves_array", 2),
"max_concurrent_moves_cache": raw.get("max_concurrent_moves_cache", 5),
"exit_if_active_session": raw.get("exit_if_active_session", False)
}
def save_cache_settings(self, settings: Dict[str, Any]) -> bool:
"""Save cache settings"""
raw = self._load_raw()
# Safe int converter that handles float strings like "365.0"
safe_int = lambda x: int(float(x))
# Map form field names to settings keys
field_mapping = {
# Content discovery (moved from Plex tab)
"number_episodes": ("number_episodes", safe_int),
"days_to_monitor": ("days_to_monitor", safe_int),
"watchlist_toggle": ("watchlist_toggle", lambda x: x == "on" or x is True),
"watchlist_episodes": ("watchlist_episodes", safe_int),
"prefetch_minimum_minutes": ("prefetch_minimum_minutes", safe_int),
"watchlist_retention_days": ("watchlist_retention_days", float),
"ondeck_retention_days": ("ondeck_retention_days", float),
"watched_move": ("watched_move", lambda x: x == "on" or x is True),
"create_plexcached_backups": ("create_plexcached_backups", lambda x: x == "on" or x is True),
"cleanup_empty_folders": ("cleanup_empty_folders", lambda x: x == "on" or x is True),
"use_symlinks": ("use_symlinks", lambda x: x == "on" or x is True),
"hardlinked_files": ("hardlinked_files", str),
"check_hardlinks_on_restore": ("check_hardlinks_on_restore", lambda x: x == "on" or x is True),
"cache_associated_files": ("cache_associated_files", str),
"cache_retention_hours": ("cache_retention_hours", safe_int),
"cache_drive_size": ("cache_drive_size", str),
"cache_limit": ("cache_limit", str),
"min_free_space": ("min_free_space", str),
"plexcache_quota": ("plexcache_quota", str),
"cache_eviction_mode": ("cache_eviction_mode", str),
"cache_eviction_threshold_percent": ("cache_eviction_threshold_percent", safe_int),
"eviction_min_priority": ("eviction_min_priority", safe_int),
"pinned_preferred_resolution": ("pinned_preferred_resolution", str),
"remote_watchlist_toggle": ("remote_watchlist_toggle", lambda x: x == "on" or x is True),
"remote_watchlist_rss_url": ("remote_watchlist_rss_url", str),
# Upgrade tracking
"auto_transfer_upgrades": ("auto_transfer_upgrades", lambda x: x == "on" or x is True),
"backup_upgraded_files": ("backup_upgraded_files", lambda x: x == "on" or x is True),
# Advanced settings
"max_concurrent_moves_array": ("max_concurrent_moves_array", safe_int),
"max_concurrent_moves_cache": ("max_concurrent_moves_cache", safe_int),
"exit_if_active_session": ("exit_if_active_session", lambda x: x == "on" or x is True)
}
# Boolean fields that come from checkboxes (absent = unchecked = False)
boolean_fields = {
"watchlist_toggle", "watched_move", "create_plexcached_backups",
"cleanup_empty_folders", "use_symlinks", "auto_transfer_upgrades",
"backup_upgraded_files", "remote_watchlist_toggle", "exit_if_active_session",
"check_hardlinks_on_restore"
}
for form_field, (setting_key, converter) in field_mapping.items():
if form_field in settings:
try:
raw[setting_key] = converter(settings[form_field])
except (ValueError, TypeError):
pass # Keep existing value on conversion error
elif form_field in boolean_fields:
raw[setting_key] = False
# Handle list fields separately (not through field_mapping)
if "excluded_folders" in settings:
folders = settings["excluded_folders"]
if isinstance(folders, list):
# Filter out empty strings
raw["excluded_folders"] = [f.strip() for f in folders if f and f.strip()]
else:
raw["excluded_folders"] = []
return self._save_raw(raw)
def get_notification_settings(self) -> Dict[str, Any]:
"""Get notification settings"""
raw = self._load_raw()
return {
"notification_type": raw.get("notification_type", "system"),
"unraid_level": raw.get("unraid_level", "summary"),
"webhook_url": raw.get("webhook_url", ""),
"webhook_level": raw.get("webhook_level", "summary"),
# New list-based levels
"unraid_levels": raw.get("unraid_levels", []),
"webhook_levels": raw.get("webhook_levels", [])
}
def save_notification_settings(self, settings: Dict[str, Any]) -> bool:
"""Save notification settings"""
raw = self._load_raw()
raw["notification_type"] = settings.get("notification_type", raw.get("notification_type", "system"))
raw["webhook_url"] = settings.get("webhook_url", raw.get("webhook_url", ""))
# New list-based levels
raw["unraid_levels"] = settings.get("unraid_levels", raw.get("unraid_levels", []))
raw["webhook_levels"] = settings.get("webhook_levels", raw.get("webhook_levels", []))
# Legacy fields for backward compatibility
raw["unraid_level"] = settings.get("unraid_level", raw.get("unraid_level", "summary"))
raw["webhook_level"] = settings.get("webhook_level", raw.get("webhook_level", "summary"))
return self._save_raw(raw)
def get_arr_instances(self) -> List[Dict[str, Any]]:
"""Get Sonarr/Radarr integration instances.
Auto-migrates old flat keys (sonarr_url, radarr_url, etc.) on first access.
"""
raw = self._load_raw()
# Auto-migrate old flat keys → arr_instances list
if "arr_instances" not in raw:
instances = []
sonarr_url = raw.get("sonarr_url", "").strip()
sonarr_key = raw.get("sonarr_api_key", "").strip()
if sonarr_url or sonarr_key:
instances.append({
"name": "Sonarr",
"type": "sonarr",
"url": sonarr_url,
"api_key": sonarr_key,
"enabled": bool(raw.get("sonarr_enabled", False)),
})
radarr_url = raw.get("radarr_url", "").strip()
radarr_key = raw.get("radarr_api_key", "").strip()
if radarr_url or radarr_key:
instances.append({
"name": "Radarr",
"type": "radarr",
"url": radarr_url,
"api_key": radarr_key,
"enabled": bool(raw.get("radarr_enabled", False)),
})
if instances:
raw["arr_instances"] = instances
# Remove old flat keys
for key in ("sonarr_enabled", "sonarr_url", "sonarr_api_key",
"radarr_enabled", "radarr_url", "radarr_api_key"):
raw.pop(key, None)
self._save_raw(raw)
return instances
return raw.get("arr_instances", [])
def add_arr_instance(self, instance: Dict[str, Any]) -> bool:
"""Add a new Sonarr/Radarr instance"""
raw = self._load_raw()
instances = raw.get("arr_instances", [])
instances.append({
"name": instance.get("name", "").strip(),
"type": instance.get("type", "sonarr"),
"url": instance.get("url", "").strip(),
"api_key": instance.get("api_key", "").strip(),
"enabled": instance.get("enabled", True),
})
raw["arr_instances"] = instances
return self._save_raw(raw)
def update_arr_instance(self, index: int, instance: Dict[str, Any]) -> bool:
"""Update an existing Sonarr/Radarr instance by index"""
raw = self._load_raw()
instances = raw.get("arr_instances", [])
if 0 <= index < len(instances):
instances[index] = {
"name": instance.get("name", "").strip(),
"type": instance.get("type", "sonarr"),
"url": instance.get("url", "").strip(),
"api_key": instance.get("api_key", "").strip(),
"enabled": instance.get("enabled", True),
}
raw["arr_instances"] = instances
return self._save_raw(raw)
return False
def delete_arr_instance(self, index: int) -> bool:
"""Delete a Sonarr/Radarr instance by index"""
raw = self._load_raw()
instances = raw.get("arr_instances", [])
if 0 <= index < len(instances):
instances.pop(index)
raw["arr_instances"] = instances
return self._save_raw(raw)
return False
def get_logging_settings(self) -> Dict[str, Any]:
"""Get logging settings"""
raw = self._load_raw()
return {
"max_log_files": raw.get("max_log_files", 24),
"keep_error_logs_days": raw.get("keep_error_logs_days", 7),
"time_format": raw.get("time_format", "24h"),
"activity_retention_hours": raw.get("activity_retention_hours", 24)
}
def save_logging_settings(self, settings: Dict[str, Any]) -> bool:
"""Save logging settings"""
raw = self._load_raw()
# Validate and save max_log_files (int(float()) handles "5.0" strings)
if "max_log_files" in settings:
try:
max_log_files = int(float(settings["max_log_files"]))
if max_log_files >= 1:
raw["max_log_files"] = max_log_files
except (ValueError, TypeError):
pass
# Validate and save keep_error_logs_days
if "keep_error_logs_days" in settings:
try:
keep_error_logs_days = int(float(settings["keep_error_logs_days"]))
if keep_error_logs_days >= 0:
raw["keep_error_logs_days"] = keep_error_logs_days
except (ValueError, TypeError):
pass
# Validate and save time_format
if "time_format" in settings:
time_format = settings["time_format"]
if time_format in ("12h", "24h"):
raw["time_format"] = time_format
# Validate and save activity_retention_hours
if "activity_retention_hours" in settings:
try:
activity_retention_hours = int(float(settings["activity_retention_hours"]))
if activity_retention_hours >= 1:
raw["activity_retention_hours"] = activity_retention_hours
except (ValueError, TypeError):
pass
return self._save_raw(raw)
def get_security_settings(self) -> Dict[str, Any]:
"""Get security/auth settings"""
raw = self._load_raw()
return {
"auth_enabled": raw.get("auth_enabled", False),
"auth_admin_plex_id": raw.get("auth_admin_plex_id", ""),
"auth_admin_username": raw.get("auth_admin_username", ""),
"auth_password_enabled": raw.get("auth_password_enabled", False),
"auth_password_username": raw.get("auth_password_username", ""),
"auth_session_hours": raw.get("auth_session_hours", 24),
}
def save_security_settings(self, settings: Dict[str, Any]) -> bool:
"""Save security/auth settings"""
raw = self._load_raw()
if "auth_enabled" in settings:
raw["auth_enabled"] = bool(settings["auth_enabled"])
if "auth_session_hours" in settings:
try:
hours = int(float(settings["auth_session_hours"]))
if 1 <= hours <= 720:
raw["auth_session_hours"] = hours
except (ValueError, TypeError):
pass
if "auth_password_enabled" in settings:
raw["auth_password_enabled"] = bool(settings["auth_password_enabled"])
if "auth_password_username" in settings:
raw["auth_password_username"] = str(settings["auth_password_username"]).strip()
if "auth_password_hash" in settings:
raw["auth_password_hash"] = settings["auth_password_hash"]
if "auth_password_salt" in settings:
raw["auth_password_salt"] = settings["auth_password_salt"]
if "auth_admin_plex_id" in settings:
raw["auth_admin_plex_id"] = settings["auth_admin_plex_id"]
if "auth_admin_username" in settings:
raw["auth_admin_username"] = settings["auth_admin_username"]
return self._save_raw(raw)
def check_plex_connection(self) -> bool:
"""Check if Plex server is reachable"""
settings = self.get_plex_settings()
plex_url = settings.get("plex_url", "")
plex_token = settings.get("plex_token", "")
if not plex_url or not plex_token:
return False
try:
import requests
# Simple health check
url = plex_url.rstrip('/') + '/'
response = requests.get(
url,
headers={"X-Plex-Token": plex_token},
timeout=5
)
return response.status_code == 200
except (requests.RequestException, OSError):
return False
def _is_plex_cache_valid(self) -> bool:
"""Check if Plex cache is still valid"""
if self._plex_cache_time is None:
return False
elapsed = (datetime.now() - self._plex_cache_time).total_seconds()
return elapsed < self._plex_cache_ttl
def invalidate_plex_cache(self):
"""Invalidate the Plex data cache"""
self._plex_libraries_cache = None
self._plex_users_cache = None
self._plex_cache_time = None
def get_plex_libraries(self, plex_url: Optional[str] = None, plex_token: Optional[str] = None) -> List[Dict[str, Any]]:
"""Fetch library sections from Plex server (cached)
Args:
plex_url: Optional Plex URL (uses saved settings if not provided)
plex_token: Optional Plex token (uses saved settings if not provided)
"""
with self._cache_lock:
# Return cached data if valid (only when using saved credentials)
if plex_url is None and plex_token is None:
if self._is_plex_cache_valid() and self._plex_libraries_cache is not None:
return self._plex_libraries_cache
# Use provided credentials or fall back to saved settings
if plex_url is None or plex_token is None:
settings = self.get_plex_settings()
plex_url = plex_url or settings.get("plex_url", "")
plex_token = plex_token or settings.get("plex_token", "")
if not plex_url or not plex_token:
return []
try:
from plexapi.server import PlexServer
plex = PlexServer(plex_url, plex_token, timeout=10)
libraries = []
for section in plex.library.sections():
# Get library locations (paths) for path mapping generation
locations = []
try:
locations = list(section.locations) if hasattr(section, 'locations') else []
except (AttributeError, TypeError):
pass
libraries.append({
"id": int(section.key),
"title": section.title,
"type": section.type, # 'movie', 'show', 'artist', 'photo'
"type_label": {
"movie": "Movies",
"show": "TV Shows",
"artist": "Music",
"photo": "Photos"
}.get(section.type, section.type.title()),
"locations": locations # Plex paths for this library
})
with self._cache_lock:
self._plex_libraries_cache = sorted(libraries, key=lambda x: x["id"])
self._plex_cache_time = datetime.now()
self._save_plex_cache_to_file()
return self._plex_libraries_cache
except Exception:
# Return empty but also return file cache if available
with self._cache_lock:
if self._plex_libraries_cache:
return self._plex_libraries_cache
return []
def get_plex_users(self, plex_url: Optional[str] = None, plex_token: Optional[str] = None) -> List[Dict[str, Any]]:
"""Fetch users from Plex server (cached, including main account)
Args:
plex_url: Optional Plex URL (uses saved settings if not provided)
plex_token: Optional Plex token (uses saved settings if not provided)
"""
# Check for prefetched users from setup wizard (background fetch)
if hasattr(self, '_prefetched_users') and self._prefetched_users:
prefetched = self._prefetched_users