Coverage for src/settings_view.py: 100%
169 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
1"""What this container is configured to do, for the web UI's Settings page.
3Each row names a config.yaml key, the value in effect, and where it came
4from: the file, the built-in default, or an environment variable. Secrets
5are reported as set or not set, never shown.
7A few keys can be changed from the page. Only keys whose change cannot
8delete, move or re-download anything are editable; the rest say to edit
9config.yaml. A write keeps the file's comments (ruamel round trip), backs
10the file up first and replaces it atomically. The sync loop re-reads the
11config every cycle, so a change applies from the next one.
12"""
14import datetime
15import glob
16import os
17import re
18import shutil
19import tempfile
20from dataclasses import dataclass
21from typing import Any
23from ruamel.yaml import YAML
25from src import (
26 DEFAULT_CONFIG_FILE_PATH,
27 DEFAULT_DRIVE_DESTINATION,
28 DEFAULT_ENUMERATION_CHUNK_SIZE,
29 DEFAULT_LOGGER_LEVEL,
30 DEFAULT_OBSOLETE_DELETE_LIMIT_PERCENT,
31 DEFAULT_PHOTOS_DESTINATION,
32 DEFAULT_REQUEST_TIMEOUT_SEC,
33 DEFAULT_RETRY_LOGIN_INTERVAL_SEC,
34 DEFAULT_ROOT_DESTINATION,
35 DEFAULT_SYNC_INTERVAL_SEC,
36 ENV_CONFIG_FILE_PATH_KEY,
37 ENV_ICLOUD_PASSWORD_KEY,
38 read_config,
39)
41_MISSING = object()
44@dataclass(frozen=True)
45class Setting:
46 """One config.yaml key as the Settings page shows it.
48 ``kind`` is ``text``, ``int``, ``bool``, ``list``, ``map`` or
49 ``secret``. ``editable`` keys accept a new value from the page.
50 """
52 group: str
53 path: tuple[str, ...]
54 label: str
55 default: Any = None
56 kind: str = "text"
57 editable: bool = False
58 note: str = ""
59 unit: str = ""
61 @property
62 def key(self) -> str:
63 return ".".join(self.path)
66# Editable keys are limited to ones whose change cannot delete, move or
67# re-download a file. Intervals, notification switches and hardlinks
68# (turning it off only stops new links) qualify. Destinations, formats,
69# filters and remove_obsolete do not: each of those changes which files
70# belong where, so a slip from a phone would cost a re-download or a
71# cleanup.
72SETTINGS: tuple[Setting, ...] = (
73 Setting("Account", ("app", "credentials", "username"), "Apple ID"),
74 Setting("Account", ("app", "region"), "Region", "global"),
75 Setting(
76 "Account",
77 ("app", "credentials", "retry_login_interval"),
78 "Sign-in retry",
79 DEFAULT_RETRY_LOGIN_INTERVAL_SEC,
80 "int",
81 unit="s",
82 ),
83 Setting(
84 "Account",
85 ("app", "trust_expiry_warn_days"),
86 "Warn before trust expires (days)",
87 7,
88 "int",
89 ),
90 Setting(
91 "Account",
92 ("app", "trust_refresh_days"),
93 "Refresh trust at (days left)",
94 14,
95 "int",
96 ),
97 Setting("App", ("app", "root"), "Root folder", DEFAULT_ROOT_DESTINATION),
98 Setting("App", ("app", "max_threads"), "Download threads", "auto"),
99 Setting("App", ("app", "mount_marker_filename"), "Mount marker file", ".mounted"),
100 Setting("App", ("app", "logger", "level"), "Log level", DEFAULT_LOGGER_LEVEL),
101 Setting("App", ("app", "logger", "filename"), "Log file"),
102 Setting("App", ("app", "recycle_bin", "enabled"), "Recycle bin", False, "bool"),
103 Setting(
104 "App",
105 ("app", "recycle_bin", "retention_days"),
106 "Recycle bin keeps (days)",
107 None,
108 "int",
109 ),
110 Setting("App", ("app", "web_ui", "host"), "Web UI host", "127.0.0.1"),
111 Setting("App", ("app", "web_ui", "port"), "Web UI port", 8080, "int"),
112 Setting("App", ("app", "web_ui", "public_url"), "Web UI public URL"),
113 Setting("App", ("app", "usage_tracking", "enabled"), "Usage tracking", True, "bool"),
114 Setting("iCloud Drive", ("drive", "destination"), "Folder", DEFAULT_DRIVE_DESTINATION),
115 Setting(
116 "iCloud Drive",
117 ("drive", "sync_interval"),
118 "Back up every",
119 DEFAULT_SYNC_INTERVAL_SEC,
120 "int",
121 editable=True,
122 note="In seconds. Negative runs once and stops.",
123 unit="s",
124 ),
125 Setting(
126 "iCloud Drive",
127 ("drive", "remove_obsolete"),
128 "Delete files removed from iCloud",
129 False,
130 "bool",
131 ),
132 Setting(
133 "iCloud Drive",
134 ("drive", "flatten_packages"),
135 "Keep packages as one file",
136 False,
137 "bool",
138 ),
139 Setting(
140 "iCloud Drive",
141 ("drive", "require_mount_marker"),
142 "Require mount marker",
143 False,
144 "bool",
145 ),
146 Setting(
147 "iCloud Drive",
148 ("drive", "request_timeout"),
149 "Request timeout",
150 DEFAULT_REQUEST_TIMEOUT_SEC,
151 "int",
152 unit="s",
153 ),
154 Setting("iCloud Drive", ("drive", "filters", "folders"), "Only these folders", None, "list"),
155 Setting(
156 "iCloud Drive",
157 ("drive", "filters", "file_extensions"),
158 "Only these extensions",
159 None,
160 "list",
161 ),
162 Setting("iCloud Drive", ("drive", "ignore"), "Ignore", None, "list"),
163 Setting("Photos", ("photos", "destination"), "Folder", DEFAULT_PHOTOS_DESTINATION),
164 Setting(
165 "Photos",
166 ("photos", "sync_interval"),
167 "Back up every",
168 DEFAULT_SYNC_INTERVAL_SEC,
169 "int",
170 editable=True,
171 note="In seconds. Negative runs once and stops.",
172 unit="s",
173 ),
174 Setting(
175 "Photos",
176 ("photos", "remove_obsolete"),
177 "Delete photos removed from iCloud",
178 False,
179 "bool",
180 ),
181 Setting(
182 "Photos",
183 ("photos", "obsolete_delete_limit_percent"),
184 "Cleanup limit (%)",
185 DEFAULT_OBSOLETE_DELETE_LIMIT_PERCENT,
186 "int",
187 ),
188 Setting("Photos", ("photos", "all_albums"), "Albums as folders", False, "bool"),
189 Setting(
190 "Photos",
191 ("photos", "use_hardlinks"),
192 "Hardlink duplicates",
193 False,
194 "bool",
195 editable=True,
196 note="Turning it off only stops new links.",
197 ),
198 Setting("Photos", ("photos", "folder_format"), "Folder format"),
199 Setting(
200 "Photos",
201 ("photos", "folder_format_in_albums"),
202 "Folder format in albums",
203 True,
204 "bool",
205 note="Only when Folder format is set. All Photos keeps its folders.",
206 ),
207 Setting("Photos", ("photos", "filename_format"), "Filename format", "metadata"),
208 Setting("Photos", ("photos", "file_format"), "File format template"),
209 Setting("Photos", ("photos", "variant_separator"), "Variant separator", "_"),
210 Setting(
211 "Photos",
212 ("photos", "preserve_originals_as_bak"),
213 "Keep originals as .bak",
214 False,
215 "bool",
216 ),
217 Setting(
218 "Photos",
219 ("photos", "require_mount_marker"),
220 "Require mount marker",
221 False,
222 "bool",
223 ),
224 Setting(
225 "Photos",
226 ("photos", "request_timeout"),
227 "Request timeout",
228 DEFAULT_REQUEST_TIMEOUT_SEC,
229 "int",
230 unit="s",
231 ),
232 Setting(
233 "Photos",
234 ("photos", "enumeration_chunk_size"),
235 "Enumeration chunk",
236 DEFAULT_ENUMERATION_CHUNK_SIZE,
237 "int",
238 ),
239 Setting("Photos", ("photos", "library_destinations"), "Library folders", None, "map"),
240 Setting(
241 "Photos",
242 ("photos", "filters", "libraries"),
243 "Only these libraries",
244 None,
245 "list",
246 ),
247 Setting("Photos", ("photos", "filters", "albums"), "Albums filter", None, "list"),
248 Setting("Photos", ("photos", "filters", "file_sizes"), "Versions", ["original"], "list"),
249 Setting(
250 "Photos",
251 ("photos", "filters", "extensions"),
252 "Only these extensions",
253 None,
254 "list",
255 ),
256 Setting(
257 "Photos",
258 ("photos", "filters", "fallback_to_original"),
259 "Fall back to original",
260 False,
261 "bool",
262 ),
263 Setting(
264 "Notifications",
265 ("app", "notifications", "sync_summary", "enabled"),
266 "Sync summary",
267 False,
268 "bool",
269 editable=True,
270 ),
271 Setting(
272 "Notifications",
273 ("app", "notifications", "sync_summary", "on_success"),
274 "Summary on success",
275 True,
276 "bool",
277 editable=True,
278 ),
279 Setting(
280 "Notifications",
281 ("app", "notifications", "sync_summary", "on_error"),
282 "Summary on error",
283 True,
284 "bool",
285 editable=True,
286 ),
287 Setting(
288 "Notifications",
289 ("app", "notifications", "sync_summary", "min_downloads"),
290 "Summary needs downloads",
291 1,
292 "int",
293 editable=True,
294 ),
295 Setting(
296 "Notifications",
297 ("app", "telegram", "bot_token"),
298 "Telegram bot",
299 None,
300 "secret",
301 ),
302 Setting("Notifications", ("app", "telegram", "chat_id"), "Telegram chat", None, "secret"),
303 Setting(
304 "Notifications",
305 ("app", "telegram", "listen"),
306 "Telegram 2FA replies",
307 False,
308 "bool",
309 ),
310 Setting("Notifications", ("app", "discord", "webhook_url"), "Discord", None, "secret"),
311 Setting("Notifications", ("app", "pushover", "api_token"), "Pushover", None, "secret"),
312 Setting("Notifications", ("app", "smtp", "email"), "Email from", None, "secret"),
313 Setting("Notifications", ("app", "smtp", "to"), "Email to", None, "secret"),
314 Setting("Notifications", ("app", "smtp", "password"), "Email password", None, "secret"),
315 Setting("Notifications", ("app", "webhooks", "url"), "Webhook", None, "secret"),
316 Setting("Notifications", ("app", "webhooks", "start"), "Ping on start", None, "secret"),
317 Setting(
318 "Notifications",
319 ("app", "webhooks", "success"),
320 "Ping on success",
321 None,
322 "secret",
323 ),
324 Setting(
325 "Notifications",
326 ("app", "webhooks", "failure"),
327 "Ping on failure",
328 None,
329 "secret",
330 ),
331)
333SETTINGS_BY_KEY = {setting.key: setting for setting in SETTINGS}
335# Shown up front; everything else waits under Advanced.
336COMMON = frozenset(
337 {
338 "photos.destination",
339 "photos.sync_interval",
340 "photos.remove_obsolete",
341 "drive.destination",
342 "drive.sync_interval",
343 "drive.remove_obsolete",
344 "app.notifications.sync_summary.enabled",
345 "app.recycle_bin.enabled",
346 },
347)
349# Where alerts can go, by the key that turns each one on.
350_ALERT_CHANNELS = (
351 ("app.telegram.bot_token", "Telegram"),
352 ("app.discord.webhook_url", "Discord"),
353 ("app.pushover.api_token", "Pushover"),
354 ("app.smtp.email", "Email"),
355 ("app.webhooks.url", "Webhook"),
356)
358# Variables the container reads. Values are shown except for the password,
359# which is only reported as set.
360ENVIRONMENT = (
361 (ENV_ICLOUD_PASSWORD_KEY, "Apple ID password", True),
362 (ENV_CONFIG_FILE_PATH_KEY, "Config file", False),
363 ("ICLOUD_DOCKER_CONFIG_DIR", "Config folder", False),
364 ("PUID", "File owner (user id)", False),
365 ("PGID", "File owner (group id)", False),
366 ("TZ", "Time zone", False),
367 ("APP_VERSION", "Version", False),
368)
371def lookup(config: dict | None, path: tuple[str, ...]) -> Any:
372 """The value at ``path``, or ``_MISSING`` when any part is absent.
374 A key present with an empty value (``telegram:`` with nothing under
375 it) counts as absent: the app treats it as unset.
376 """
377 node: Any = config
378 for part in path:
379 if not isinstance(node, dict) or part not in node:
380 return _MISSING
381 node = node[part]
382 return _MISSING if node is None else node
385def _is_set(raw: Any) -> bool:
386 return raw is not _MISSING and bool(str(raw).strip())
389def _duration(seconds: int) -> str:
390 """``3600`` -> ``1 h``, ``500`` -> ``8 min 20 s``: an interval as a person says it."""
391 if seconds < 0:
392 return "Once"
393 if seconds >= 86400 and seconds % 86400 == 0:
394 days = seconds // 86400
395 return f"{days} day{'s' if days != 1 else ''}"
396 parts = []
397 for size, unit in ((3600, "h"), (60, "min"), (1, "s")):
398 if seconds >= size:
399 parts.append(f"{seconds // size} {unit}")
400 seconds %= size
401 return " ".join(parts) or "0 s"
404def _display(setting: Setting, value: Any) -> str:
405 if setting.unit == "s" and isinstance(value, int) and not isinstance(value, bool):
406 return _duration(value)
407 if setting.kind == "bool":
408 return "on" if value else "off"
409 if setting.kind == "list":
410 if isinstance(value, str):
411 return value
412 return ", ".join(str(v) for v in value) if value else "none"
413 if setting.kind == "map":
414 return ", ".join(f"{k} → {v}" for k, v in value.items()) if value else "none"
415 return "" if value is None else str(value)
418def build_rows(config: dict | None) -> list[dict[str, Any]]:
419 """One row per setting, grouped in ``SETTINGS`` order."""
420 rows = []
421 for setting in SETTINGS:
422 raw = lookup(config, setting.path)
423 from_file = raw is not _MISSING
424 value = raw if from_file else setting.default
425 row = {
426 "group": setting.group,
427 "key": setting.key,
428 "label": setting.label,
429 "kind": setting.kind,
430 "editable": setting.editable,
431 "note": setting.note,
432 "source": "config.yaml" if from_file else "default",
433 "value": value,
434 "common": setting.key in COMMON,
435 }
436 if setting.kind == "secret":
437 row["display"] = "set" if _is_set(raw) else "not set"
438 row["value"] = None
439 else:
440 row["display"] = _display(setting, value) if value is not None else "not set"
441 rows.append(row)
442 if os.environ.get(ENV_ICLOUD_PASSWORD_KEY):
443 rows.insert(
444 1,
445 {
446 "group": "Account",
447 "key": "password",
448 "label": "Password",
449 "kind": "secret",
450 "editable": False,
451 "note": "",
452 "source": "env",
453 "value": None,
454 "display": "set",
455 "common": False,
456 },
457 )
458 channels = [name for key, name in _ALERT_CHANNELS if _is_set(lookup(config, tuple(key.split("."))))]
459 rows.append(
460 {
461 "group": "Notifications",
462 "key": "",
463 "label": "Alerts",
464 "kind": "text",
465 "editable": False,
466 "note": "Set up in config.yaml: "
467 + ", ".join(
468 f"{name} under {key.rsplit('.', 1)[0]}{' (on)' if name in channels else ''}"
469 for key, name in _ALERT_CHANNELS
470 )
471 + ".",
472 "source": "config.yaml" if channels else "default",
473 "value": None,
474 "display": ", ".join(channels) or "None set",
475 "common": True,
476 },
477 )
478 return rows
481def build_environment() -> list[dict[str, Any]]:
482 """The environment variables the container reads, and their values."""
483 rows = []
484 for name, label, secret in ENVIRONMENT:
485 value = os.environ.get(name)
486 if name == ENV_CONFIG_FILE_PATH_KEY and not value:
487 display, source = DEFAULT_CONFIG_FILE_PATH, "default"
488 elif value is None or value == "":
489 display, source = "not set", "default"
490 else:
491 display, source = ("set" if secret else value), "env"
492 rows.append({"name": name, "label": label, "display": display, "source": source})
493 return rows
496class SettingError(ValueError):
497 """A submitted value the page refuses, with a message for the user."""
500def parse_value(setting: Setting, submitted: str) -> Any:
501 """Turn a form value into what config.yaml should hold."""
502 text = (submitted or "").strip()
503 if setting.kind == "bool":
504 if text in ("on", "true", "1"):
505 return True
506 if text in ("off", "false", "0", ""):
507 return False
508 msg = f"{setting.label}: expected on or off"
509 raise SettingError(msg)
510 if setting.kind == "int":
511 try:
512 number = int(text)
513 except ValueError as e:
514 msg = f"{setting.label}: expected a whole number"
515 raise SettingError(msg) from e
516 if setting.path[-1] == "sync_interval" and number == 0:
517 msg = f"{setting.label}: 0 is not allowed; use a negative number to run once"
518 raise SettingError(msg)
519 if setting.path[-1] == "min_downloads" and number < 0:
520 msg = f"{setting.label}: must be 0 or more"
521 raise SettingError(msg)
522 return number
523 msg = f"{setting.label} can't be changed here"
524 raise SettingError(msg)
527def _yaml() -> YAML:
528 yaml = YAML()
529 yaml.preserve_quotes = True
530 return yaml
533def _load_document(config_path: str) -> tuple[YAML, Any]:
534 yaml = _yaml()
535 with open(config_path, encoding="utf-8") as f:
536 document = yaml.load(f)
537 if document is None:
538 msg = "config.yaml is empty"
539 raise SettingError(msg)
540 return yaml, document
543_KEEP_BACKUPS = 5
544_BACKUP_STAMP = re.compile(r"\.bak-\d{8}-\d{6}(?:-\d{6})?$")
547def _prune_backups(config_path: str) -> None:
548 """Keep the newest ``_KEEP_BACKUPS`` backups this page wrote. A backup
549 someone made by hand has a different name and is never touched."""
550 backups = sorted(p for p in glob.glob(f"{glob.escape(config_path)}.bak-*") if _BACKUP_STAMP.search(p))
551 for old in backups[:-_KEEP_BACKUPS]:
552 os.unlink(old)
555def _save_document(config_path: str, yaml: YAML, document: Any) -> None:
556 """Back up config.yaml, then replace it atomically with ``document``.
558 The new file is read back with the app's own reader before it replaces
559 the old one, so a write that would break the config never lands.
560 """
561 directory = os.path.dirname(os.path.abspath(config_path))
562 stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
563 shutil.copy2(config_path, f"{config_path}.bak-{stamp}")
564 _prune_backups(config_path)
565 fd, temp_path = tempfile.mkstemp(dir=directory, prefix=".config-", suffix=".yaml")
566 try:
567 with os.fdopen(fd, "w", encoding="utf-8") as f:
568 yaml.dump(document, f)
569 read_config(config_path=temp_path)
570 shutil.copymode(config_path, temp_path)
571 os.replace(temp_path, config_path)
572 except Exception:
573 if os.path.exists(temp_path):
574 os.unlink(temp_path)
575 raise
578def write_setting(config_path: str, key: str, submitted: str) -> Any:
579 """Set one editable key in config.yaml; return the value written.
581 Keeps the file's comments and writes ``<config>.bak-<timestamp>``
582 first, keeping the newest five; see ``_save_document``.
583 """
584 setting = SETTINGS_BY_KEY.get(key)
585 if setting is None or not setting.editable:
586 msg = "That setting can't be changed here; edit config.yaml"
587 raise SettingError(msg)
588 value = parse_value(setting, submitted)
589 yaml, document = _load_document(config_path)
591 node = document
592 for part in setting.path[:-1]:
593 child = node.get(part)
594 if child is None:
595 child = {}
596 node[part] = child
597 child = node[part]
598 if not isinstance(child, dict):
599 msg = f"{'.'.join(setting.path)}: {part} is not a section in config.yaml"
600 raise SettingError(msg)
601 node = child
602 if node.get(setting.path[-1]) == value and isinstance(node.get(setting.path[-1]), type(value)):
603 return value
604 node[setting.path[-1]] = value
605 _save_document(config_path, yaml, document)
606 return value