Coverage for src/dashboard_view.py: 100%
167 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 the dashboard says, worked out from what ``/api/status`` already has.
3The dashboard answers one question, "is everyone's iCloud safely copied?",
4and offers one tap when it isn't. Everything here is a view of the status
5payload (``web._build_status``) and the log tail the page already reads:
6no disk, network or lock is added to the page load.
8- ``people``: one entry per Apple ID, the main account first, each with a
9 tone, one sentence, and at most one action.
10- ``headline``: the sentence at the top, from the people.
11- ``log_summary``: warnings and errors in the tail, so the log can stay
12 folded unless it has something to say.
13"""
15import re
16from typing import Any
18# Severity, most urgent first. A person's tone is the worst of their parts;
19# the headline is the worst of the people.
20TONES = ("err", "warn", "busy", "idle", "ok")
22_LEVEL = re.compile(r":: (WARNING|ERROR|CRITICAL) ::")
25def _worst(*tones: str) -> str:
26 return min(tones, key=TONES.index)
29def library_label(name: str) -> str:
30 """The person's name for a photo library, not Apple's zone name."""
31 if name == "PrimarySync":
32 return "Personal library"
33 if name == "SharedLibrary" or name.startswith("SharedSync-"):
34 return "Shared Library"
35 return name
38def every(seconds: Any) -> str:
39 """``43200`` -> ``every 12 h``; the schedule as a person says it."""
40 try:
41 seconds = int(seconds)
42 except TypeError, ValueError:
43 return ""
44 if seconds <= 0:
45 return "once, then stops"
46 if seconds % 86400 == 0:
47 days = seconds // 86400
48 return "every day" if days == 1 else f"every {days} days"
49 if seconds % 3600 == 0:
50 return f"every {seconds // 3600} h"
51 if seconds % 60 == 0:
52 return f"every {seconds // 60} min"
53 return f"every {seconds} s"
56def _hue(name: str) -> int:
57 """An avatar colour that comes from the name, so it never changes."""
58 return sum(ord(c) * (i + 1) for i, c in enumerate(name.lower())) * 37 % 360
61def _count(n: Any) -> str:
62 return f"{int(n):,}"
65def _service_view(service: dict) -> dict[str, Any]:
66 stats = service.get("stats") or {}
67 facts = []
68 if stats.get("files_downloaded") is not None:
69 facts.append(f"{_count(stats['files_downloaded'])} new")
70 if stats.get("files_skipped") is not None:
71 facts.append(f"{_count(stats['files_skipped'])} already here")
72 if stats.get("files_removed"):
73 facts.append(f"{_count(stats['files_removed'])} removed")
74 if stats.get("errors"):
75 facts.append(f"{_count(stats['errors'])} failed")
76 marker_missing = bool(service.get("require_mount_marker") and not service.get("marker_present"))
77 libraries = [{**lib, "label": library_label(lib.get("name", ""))} for lib in service.get("libraries") or []]
78 # Said once for the service when it is true of every library.
79 all_indexing = bool(libraries) and all(lib.get("indexing") for lib in libraries)
80 name = service.get("name")
81 # What the person's line says when this service is the trouble.
82 problem = None
83 if service.get("syncing_since_relative"):
84 tone, when = (
85 "busy",
86 f"Syncing now · started {service['syncing_since_relative']}",
87 )
88 elif marker_missing:
89 tone, when = "err", "Paused: the folder isn't mounted"
90 problem = f"{name} is paused: its folder isn't mounted"
91 elif any(lib.get("state") == "failed" for lib in libraries):
92 tone, when = (
93 "warn",
94 f"Last backup {stats.get('last_sync_relative') or 'not finished'}",
95 )
96 problem = f"A {name} library failed"
97 elif stats.get("last_sync_relative"):
98 tone, when = "ok", f"Backed up {stats['last_sync_relative']}"
99 else:
100 tone, when = "idle", "Waiting for the first backup"
101 return {
102 **service,
103 "tone": tone,
104 "when": when,
105 "facts": " · ".join(facts),
106 "schedule": every(service.get("sync_interval_s")),
107 "marker_missing": marker_missing,
108 "libraries": libraries,
109 "all_indexing": all_indexing,
110 "problem": problem,
111 }
114def _primary(status: dict) -> dict[str, Any]:
115 services = [_service_view(s) for s in status.get("services") or []]
116 auth = status.get("auth_state") or "not_configured"
117 username = status.get("username")
118 trust = status.get("trust_days_remaining")
119 action = None
120 detail = None
121 if auth == "not_configured":
122 tone, sentence = "err", "No Apple ID set up yet"
123 action = {"label": "Set up", "href": "/auth"}
124 elif auth == "setup_needed":
125 tone, sentence = "warn", "Waiting for the first sign-in"
126 action = {"label": "Sign in", "href": "/auth"}
127 elif auth == "reauth_needed":
128 tone, sentence = "err", "Backups are stopped"
129 detail = {
130 "session_unusable": "The saved session is no longer valid and no password is stored.",
131 "sign_in_failed": "Apple refused the sign-in. This can be an outage; it keeps retrying.",
132 }.get(
133 status.get("auth_blocked_reason") or "",
134 "Apple is asking for a second factor.",
135 )
136 action = {"label": "Sign in again", "href": "/auth"}
137 else:
138 busy = [s for s in services if s["tone"] == "busy"]
139 broken = [s for s in services if s["tone"] in ("err", "warn")]
140 if busy:
141 tone, sentence = "busy", "Backing up now"
142 detail = " · ".join(f"{s['name']} started {s['syncing_since_relative']}" for s in busy)
143 elif broken:
144 tone = _worst(*(s["tone"] for s in broken))
145 sentence = "; ".join(s["problem"] for s in broken)
146 elif services and all(s["tone"] == "ok" for s in services):
147 tone = "ok"
148 # The stalest service bounds how safe everything is.
149 oldest = min(services, key=lambda s: (s.get("stats") or {}).get("completed_at") or 0)
150 sentence = oldest["when"]
151 else:
152 tone, sentence = "idle", "Waiting for the first backup"
153 if trust is not None and trust <= 0:
154 tone = _worst(tone, "warn")
155 detail = "Apple's trust for this sign-in has run out. Refresh it to keep backups running."
156 action = {"label": "Refresh trust", "post": "/auth/refresh-trust"}
157 elif trust is not None and trust < 7 and tone != "err":
158 tone = _worst(tone, "warn")
159 detail = f"Apple's trust for this sign-in runs out in {trust} day{'' if trust == 1 else 's'}."
160 action = {"label": "Refresh trust", "post": "/auth/refresh-trust"}
161 return {
162 "kind": "primary",
163 "id": None,
164 "name": username or "Main account",
165 "initial": (username or "?")[0].upper(),
166 "hue": _hue(username or ""),
167 "tone": tone,
168 "sentence": sentence,
169 "detail": detail,
170 "action": action,
171 "services": services,
172 "trust_days_remaining": trust,
173 "signed_in": auth == "ready",
174 }
177def refreshing(status: dict, everyone: list[dict]) -> bool:
178 """Whether the page should keep itself current: something is running."""
179 return any(p["tone"] == "busy" for p in everyone) or any(
180 s.get("syncing_since_relative") for s in status.get("services") or []
181 )
184def people(status: dict) -> list[dict[str, Any]]:
185 """Everyone this container backs up: today, the one Apple ID."""
186 return [_primary(status)]
189def _plainly(person: dict) -> str:
190 """One person's state as a sentence that stands alone at the top.
192 The card already says the state; the headline says what to do.
193 """
194 action = (person.get("action") or {}).get("label")
195 trust = person.get("trust_days_remaining")
196 if action == "Sign in again":
197 return "Sign in again to restart backups"
198 if action in ("Sign in", "Set up"):
199 return "Sign in to start backing up"
200 if action == "Refresh trust":
201 if trust is not None and trust > 0:
202 return f"Refresh trust: it runs out in {trust} day{'' if trust == 1 else 's'}"
203 return "Refresh trust to keep backups running"
204 return person["sentence"]
207def headline(everyone: list[dict]) -> dict[str, str]:
208 """The sentence at the top: the one thing that needs you, or that all is well.
210 Plain words, the fact itself. The cards below carry the detail, so the
211 headline never repeats a time or a count from them.
212 """
213 if not everyone:
214 return {"tone": "idle", "title": "Nothing set up yet"}
215 needs = [p for p in everyone if p["action"] and p["tone"] in ("err", "warn")]
216 if needs:
217 worst = min(needs, key=lambda p: TONES.index(p["tone"]))
218 return {"tone": worst["tone"], "title": _plainly(worst)}
219 if any(p["tone"] == "busy" for p in everyone):
220 return {"tone": "busy", "title": "Backing up"}
221 if all(p["tone"] == "ok" for p in everyone):
222 return {"tone": "ok", "title": "Everything is backed up"}
223 waiting = next(p for p in everyone if p["tone"] != "ok")
224 return {"tone": waiting["tone"], "title": _plainly(waiting)}
227# What the config says when a key is left out and its default applies. Every
228# pass logs these, and they are the config working as designed. Matched on the
229# message, so a real config warning from the same module still counts.
230_DEFAULT_NOTICE = re.compile(r"not found\. (?:Using default|Downloading|Not removing)|is missing\. Using default")
233def _problem(line: str) -> str | None:
234 """What an app log line is about, without the file, id or numbers.
236 ``[alex] File not found in iCloud Drive - /icloud/drive/...`` becomes
237 ``File not found in iCloud Drive``. Library lines (``icloudpy.*``) give
238 None: the app logs the same failure in its own words.
239 """
240 parts = line.split(" :: ", 5)
241 if len(parts) < 6 or parts[2].strip() != "root":
242 return None
243 message = re.sub(r"^\[[^\]]*\]\s*", "", parts[5].strip())
244 message = re.split(r" - |: | /|\(", message, maxsplit=1)[0]
245 message = re.sub(r"SharedSync-[0-9A-Fa-f-]+", "the Shared Library", message)
246 message = re.sub(r"\d[\d,.]*", "N", message).strip(" .")
247 return message[:70] or None
250def log_summary(lines: list[str]) -> dict[str, Any]:
251 """Warnings and errors in the log tail, the most recent one, and what
252 most of them are about (``top``), so a count never stands alone."""
253 warnings = errors = 0
254 last = None
255 seen: dict[str, int] = {}
256 for line in lines or []:
257 match = _LEVEL.search(line)
258 if not match:
259 continue
260 if match.group(1) == "WARNING" and _DEFAULT_NOTICE.search(line):
261 continue
262 if match.group(1) == "WARNING":
263 warnings += 1
264 else:
265 errors += 1
266 last = line
267 problem = _problem(line)
268 if problem:
269 seen[problem] = seen.get(problem, 0) + 1
270 if errors or warnings:
271 parts = []
272 if errors:
273 parts.append(f"{errors} error{'' if errors == 1 else 's'}")
274 if warnings:
275 parts.append(f"{warnings} warning{'' if warnings == 1 else 's'}")
276 text = " and ".join(parts) + " recently"
277 else:
278 text = "Nothing unusual recently"
279 top = None
280 if seen:
281 problem, count = max(seen.items(), key=lambda item: item[1])
282 top = f"Mostly: {problem} ({count})" if len(seen) > 1 else f"{problem} ({count})"
283 return {"warnings": warnings, "errors": errors, "text": text, "last": last, "top": top}