openvideo-server 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. openvideo_server/__init__.py +5 -0
  2. openvideo_server/_version.py +24 -0
  3. openvideo_server/admin/__init__.py +1 -0
  4. openvideo_server/admin/bridge.py +85 -0
  5. openvideo_server/admin/client.py +142 -0
  6. openvideo_server/admin/server.py +73 -0
  7. openvideo_server/admin/service.py +363 -0
  8. openvideo_server/admin/ui.py +692 -0
  9. openvideo_server/api/__init__.py +1 -0
  10. openvideo_server/api/capabilities.py +25 -0
  11. openvideo_server/api/dependencies.py +172 -0
  12. openvideo_server/api/ranges.py +64 -0
  13. openvideo_server/api/routes_auth.py +298 -0
  14. openvideo_server/api/routes_downloads.py +340 -0
  15. openvideo_server/api/routes_history.py +188 -0
  16. openvideo_server/api/routes_media.py +238 -0
  17. openvideo_server/api/routes_playback.py +436 -0
  18. openvideo_server/api/routes_server.py +171 -0
  19. openvideo_server/api/routes_sources.py +225 -0
  20. openvideo_server/api/routes_subtitles.py +133 -0
  21. openvideo_server/cli.py +793 -0
  22. openvideo_server/config.py +201 -0
  23. openvideo_server/core/__init__.py +1 -0
  24. openvideo_server/core/browser.py +501 -0
  25. openvideo_server/core/download_manager.py +655 -0
  26. openvideo_server/core/security.py +176 -0
  27. openvideo_server/core/session_manager.py +1085 -0
  28. openvideo_server/discovery/__init__.py +1 -0
  29. openvideo_server/discovery/bonjour.py +256 -0
  30. openvideo_server/macos/__init__.py +1 -0
  31. openvideo_server/macos/launch_agent.py +168 -0
  32. openvideo_server/main.py +281 -0
  33. openvideo_server/media/__init__.py +1 -0
  34. openvideo_server/media/binaries.py +264 -0
  35. openvideo_server/media/cache.py +51 -0
  36. openvideo_server/media/downloads.py +308 -0
  37. openvideo_server/media/probe.py +280 -0
  38. openvideo_server/media/subtitles.py +303 -0
  39. openvideo_server/media/thumbnails.py +273 -0
  40. openvideo_server/redaction.py +13 -0
  41. openvideo_server/runtime.py +103 -0
  42. openvideo_server/storage/__init__.py +1 -0
  43. openvideo_server/storage/db.py +47 -0
  44. openvideo_server/storage/disk.py +20 -0
  45. openvideo_server/storage/migrations.py +58 -0
  46. openvideo_server/storage/repository.py +722 -0
  47. openvideo_server-0.1.0.dist-info/METADATA +146 -0
  48. openvideo_server-0.1.0.dist-info/RECORD +52 -0
  49. openvideo_server-0.1.0.dist-info/WHEEL +4 -0
  50. openvideo_server-0.1.0.dist-info/entry_points.txt +2 -0
  51. openvideo_server-0.1.0.dist-info/licenses/LICENSE +201 -0
  52. openvideo_server-0.1.0.dist-info/licenses/NOTICE +2 -0
@@ -0,0 +1,5 @@
1
+ """OpenVideo Server."""
2
+
3
+ from openvideo_server._version import __version__ as __version__
4
+
5
+ __all__ = ["__version__"]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1 @@
1
+ """Local administration service for the running server."""
@@ -0,0 +1,85 @@
1
+ """Methods exposed to the admin window's JavaScript context."""
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from openvideo_server.admin.client import AdminClient, AdminError
8
+
9
+
10
+ def _source_id(name: str) -> str:
11
+ """Derive a stable source id from a folder name."""
12
+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
13
+ return slug or "source"
14
+
15
+
16
+ class AdminBridge:
17
+ """Wrap client calls in an envelope that JavaScript can display safely."""
18
+
19
+ def __init__(self, client: AdminClient | None = None, webview: Any = None) -> None:
20
+ self._client = client or AdminClient()
21
+ self._webview = webview
22
+ self._window: Any = None
23
+
24
+ def attach_window(self, window: Any) -> None:
25
+ """Remember the window so the page can open native dialogs."""
26
+ self._window = window
27
+
28
+ def get_status(self) -> dict[str, Any]:
29
+ return self._call(self._client.status)
30
+
31
+ def get_settings(self) -> dict[str, Any]:
32
+ return self._call(self._client.settings)
33
+
34
+ def save_settings(self, values: dict[str, Any]) -> dict[str, Any]:
35
+ return self._call(self._client.save_settings, values)
36
+
37
+ def choose_source_folder(self) -> dict[str, Any]:
38
+ """Open a native folder picker and describe the chosen directory."""
39
+ if self._webview is None or self._window is None:
40
+ return {
41
+ "ok": False,
42
+ "error": "Folder selection is only available in the admin window.",
43
+ }
44
+ try:
45
+ selection = self._window.create_file_dialog(
46
+ self._webview.FileDialog.FOLDER,
47
+ allow_multiple=False,
48
+ )
49
+ except Exception as exc:
50
+ return {"ok": False, "error": f"Could not open the folder picker: {exc}"}
51
+ if not selection:
52
+ return {"ok": True, "data": None}
53
+ selected = selection if isinstance(selection, str) else str(selection[0])
54
+ name = Path(selected).name or selected
55
+ return {
56
+ "ok": True,
57
+ "data": {"id": _source_id(name), "name": name, "path": selected},
58
+ }
59
+
60
+ def list_devices(self) -> dict[str, Any]:
61
+ return self._call(self._client.devices)
62
+
63
+ def revoke_device(self, device_id: str) -> dict[str, Any]:
64
+ return self._call(self._client.revoke_device, device_id)
65
+
66
+ def create_pin(self) -> dict[str, Any]:
67
+ return self._call(self._client.create_pin)
68
+
69
+ def clear_cache(self) -> dict[str, Any]:
70
+ return self._call(self._client.clear_cache)
71
+
72
+ def optimize_database(self) -> dict[str, Any]:
73
+ return self._call(self._client.optimize_database)
74
+
75
+ def reset_database(self, confirm: str) -> dict[str, Any]:
76
+ return self._call(self._client.reset_database, confirm)
77
+
78
+ def restart(self) -> dict[str, Any]:
79
+ return self._call(self._client.restart)
80
+
81
+ def _call(self, operation: Any, *arguments: Any) -> dict[str, Any]:
82
+ try:
83
+ return {"ok": True, "data": operation(*arguments)}
84
+ except AdminError as exc:
85
+ return {"ok": False, "error": str(exc)}
@@ -0,0 +1,142 @@
1
+ """Stdlib JSON client for the admin Unix-socket API."""
2
+
3
+ import http.client
4
+ import json
5
+ import socket
6
+ from collections.abc import Callable
7
+ from pathlib import Path
8
+ from typing import Any
9
+ from urllib.parse import quote
10
+
11
+ from openvideo_server import runtime
12
+
13
+ DEFAULT_TIMEOUT_SECONDS = 10.0
14
+
15
+
16
+ class AdminError(Exception):
17
+ """Raised when the admin service cannot be reached or rejects a request."""
18
+
19
+ def __init__(self, message: str, status: int | None = None) -> None:
20
+ super().__init__(message)
21
+ self.status = status
22
+
23
+
24
+ class UnixHTTPConnection(http.client.HTTPConnection):
25
+ """An HTTP connection whose transport is a Unix domain socket."""
26
+
27
+ def __init__(
28
+ self, socket_path: str, timeout: float = DEFAULT_TIMEOUT_SECONDS
29
+ ) -> None:
30
+ super().__init__("localhost", timeout=timeout)
31
+ self._socket_path = socket_path
32
+
33
+ def connect(self) -> None:
34
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
35
+ connection.settimeout(self.timeout)
36
+ try:
37
+ connection.connect(self._socket_path)
38
+ except OSError:
39
+ connection.close()
40
+ raise
41
+ self.sock = connection
42
+
43
+
44
+ class AdminClient:
45
+ """Call the admin endpoints exposed on the server's Unix socket."""
46
+
47
+ def __init__(
48
+ self,
49
+ socket_path: str | Path | None = None,
50
+ *,
51
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
52
+ connection_factory: Callable[[], http.client.HTTPConnection] | None = None,
53
+ ) -> None:
54
+ self._socket_path = (
55
+ Path(socket_path).expanduser()
56
+ if socket_path is not None
57
+ else runtime.admin_socket_path()
58
+ )
59
+ self._timeout = timeout
60
+ self._connection_factory = connection_factory
61
+
62
+ @property
63
+ def socket_path(self) -> Path:
64
+ return self._socket_path
65
+
66
+ def request(
67
+ self,
68
+ method: str,
69
+ path: str,
70
+ payload: dict[str, Any] | None = None,
71
+ ) -> Any:
72
+ connection = None
73
+ body = None if payload is None else json.dumps(payload).encode("utf-8")
74
+ headers = {"Accept": "application/json"}
75
+ if body is not None:
76
+ headers["Content-Type"] = "application/json"
77
+ try:
78
+ connection = self._connect()
79
+ connection.request(method, path, body=body, headers=headers)
80
+ response = connection.getresponse()
81
+ data = response.read()
82
+ except OSError as exc:
83
+ raise AdminError(f"Could not reach the admin service: {exc}") from exc
84
+ finally:
85
+ if connection is not None:
86
+ connection.close()
87
+ if response.status >= 400:
88
+ raise AdminError(_error_detail(data), status=response.status)
89
+ if not data:
90
+ return None
91
+ return json.loads(data)
92
+
93
+ def _connect(self) -> http.client.HTTPConnection:
94
+ if self._connection_factory is not None:
95
+ return self._connection_factory()
96
+ return UnixHTTPConnection(str(self._socket_path), timeout=self._timeout)
97
+
98
+ def status(self) -> dict[str, Any]:
99
+ return self.request("GET", "/admin/api/status")
100
+
101
+ def settings(self) -> dict[str, Any]:
102
+ return self.request("GET", "/admin/api/settings")
103
+
104
+ def save_settings(self, values: dict[str, Any]) -> dict[str, Any]:
105
+ return self.request("PUT", "/admin/api/settings", values)
106
+
107
+ def devices(self) -> list[dict[str, Any]]:
108
+ return self.request("GET", "/admin/api/devices")
109
+
110
+ def revoke_device(self, device_id: str) -> dict[str, Any]:
111
+ return self.request("DELETE", f"/admin/api/devices/{quote(device_id, safe='')}")
112
+
113
+ def create_pin(self) -> dict[str, Any]:
114
+ return self.request("POST", "/admin/api/pairing/pin")
115
+
116
+ def clear_cache(self) -> dict[str, Any]:
117
+ return self.request("POST", "/admin/api/maintenance/cache/clear")
118
+
119
+ def optimize_database(self) -> dict[str, Any]:
120
+ return self.request("POST", "/admin/api/maintenance/database/optimize")
121
+
122
+ def reset_database(self, confirm: str) -> dict[str, Any]:
123
+ return self.request(
124
+ "POST",
125
+ "/admin/api/maintenance/database/reset",
126
+ {"confirm": confirm},
127
+ )
128
+
129
+ def restart(self) -> dict[str, Any]:
130
+ return self.request("POST", "/admin/api/restart")
131
+
132
+
133
+ def _error_detail(payload: bytes) -> str:
134
+ try:
135
+ data = json.loads(payload)
136
+ except (ValueError, UnicodeDecodeError):
137
+ text = payload.decode("utf-8", "replace").strip()
138
+ return text or "The admin request failed"
139
+ if isinstance(data, dict) and "detail" in data:
140
+ detail = data["detail"]
141
+ return detail if isinstance(detail, str) else json.dumps(detail)
142
+ return json.dumps(data)
@@ -0,0 +1,73 @@
1
+ """Host the admin ASGI app on a private Unix domain socket."""
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import os
6
+ from pathlib import Path
7
+
8
+ import uvicorn
9
+ from fastapi import FastAPI
10
+
11
+ from openvideo_server import runtime
12
+
13
+ SOCKET_MODE = 0o600
14
+ STARTUP_POLL_SECONDS = 0.05
15
+ STARTUP_ATTEMPTS = 200
16
+
17
+
18
+ class _AdminUvicornServer(uvicorn.Server):
19
+ """Keep signal handling with the outer server process."""
20
+
21
+ def install_signal_handlers(self) -> None:
22
+ return None
23
+
24
+
25
+ class AdminServer:
26
+ """Run a second ASGI app alongside the public API on a Unix socket."""
27
+
28
+ def __init__(
29
+ self,
30
+ app: FastAPI,
31
+ socket_path: str | Path | None = None,
32
+ ) -> None:
33
+ self._socket_path = (
34
+ Path(socket_path).expanduser()
35
+ if socket_path is not None
36
+ else runtime.admin_socket_path()
37
+ )
38
+ self._server = _AdminUvicornServer(
39
+ uvicorn.Config(
40
+ app,
41
+ uds=str(self._socket_path),
42
+ log_level="warning",
43
+ access_log=False,
44
+ )
45
+ )
46
+ self._task: asyncio.Task[None] | None = None
47
+
48
+ @property
49
+ def socket_path(self) -> Path:
50
+ return self._socket_path
51
+
52
+ async def start(self) -> None:
53
+ runtime.ensure_directory(self._socket_path.parent)
54
+ with contextlib.suppress(FileNotFoundError):
55
+ self._socket_path.unlink()
56
+ self._task = asyncio.create_task(self._server.serve())
57
+ for _ in range(STARTUP_ATTEMPTS):
58
+ if self._server.started:
59
+ os.chmod(self._socket_path, SOCKET_MODE)
60
+ return
61
+ if self._task.done():
62
+ self._task.result()
63
+ await asyncio.sleep(STARTUP_POLL_SECONDS)
64
+ raise RuntimeError("The admin server did not start")
65
+
66
+ async def stop(self) -> None:
67
+ self._server.should_exit = True
68
+ if self._task is not None:
69
+ with contextlib.suppress(asyncio.CancelledError):
70
+ await self._task
71
+ self._task = None
72
+ with contextlib.suppress(FileNotFoundError):
73
+ self._socket_path.unlink()
@@ -0,0 +1,363 @@
1
+ """Presentation-facing admin API served over a private Unix socket.
2
+
3
+ The server process remains the only writer of configuration, the database, and
4
+ the caches. This module exposes narrow endpoints that the local admin UI can
5
+ call; it never opens the database for arbitrary queries and never listens on a
6
+ TCP port.
7
+ """
8
+
9
+ import asyncio
10
+ import json
11
+ import logging
12
+ import os
13
+ import shutil
14
+ import time
15
+ from collections.abc import Callable, Sequence
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import yaml
21
+ from fastapi import BackgroundTasks, FastAPI, HTTPException
22
+ from pydantic import BaseModel, ValidationError
23
+
24
+ from openvideo_server import __version__, runtime
25
+ from openvideo_server.api.dependencies import DeviceAuthCache
26
+ from openvideo_server.config import AppConfig, ConfigError, load_config
27
+ from openvideo_server.core.security import PairingManager
28
+ from openvideo_server.macos.launch_agent import LaunchAgentError, restart_launch_agent
29
+ from openvideo_server.media.binaries import BinaryPaths, resolve_binary_paths
30
+ from openvideo_server.storage.db import connect_database
31
+ from openvideo_server.storage.migrations import INITIAL_SCHEMA
32
+ from openvideo_server.storage.repository import (
33
+ delete_paired_device,
34
+ expire_download_jobs,
35
+ list_paired_devices,
36
+ list_ready_download_jobs,
37
+ purge_orphaned_playback_history,
38
+ )
39
+
40
+ logger = logging.getLogger(__name__)
41
+ RESET_CONFIRMATION = "RESET"
42
+
43
+
44
+ class DeviceResponse(BaseModel):
45
+ """A paired device as shown to the administrator."""
46
+
47
+ id: str
48
+ name: str
49
+ paired_at: int
50
+ last_seen_at: int
51
+
52
+
53
+ class PinResponse(BaseModel):
54
+ """A freshly issued pairing PIN."""
55
+
56
+ pin: str
57
+ expires_at: float
58
+
59
+
60
+ class MaintenanceResult(BaseModel):
61
+ """Outcome of a maintenance operation."""
62
+
63
+ message: str
64
+ removed_files: int = 0
65
+ removed_records: int = 0
66
+
67
+
68
+ class ResetRequest(BaseModel):
69
+ """Confirmation payload for a destructive database reset."""
70
+
71
+ confirm: str
72
+
73
+
74
+ class StatusResponse(BaseModel):
75
+ """High-level state for the admin dashboard."""
76
+
77
+ name: str
78
+ version: str
79
+ config_path: str
80
+ database_path: str
81
+ bind_address: str
82
+ port: int
83
+ require_pairing: bool
84
+ restart_required: bool
85
+ paired_devices: int
86
+ ffmpeg: str
87
+ ffprobe: str
88
+
89
+
90
+ class SettingsResponse(BaseModel):
91
+ """The configuration on disk, the values in use, and restart state."""
92
+
93
+ config_path: str
94
+ valid: bool
95
+ values: dict[str, Any] | None
96
+ raw: str | None
97
+ error: str | None
98
+ restart_required: bool
99
+
100
+
101
+ @dataclass
102
+ class _AdminState:
103
+ running_config: AppConfig
104
+ config_path: Path
105
+ database_path: Path
106
+ pairing_manager: PairingManager
107
+ cache_directories: Sequence[Path]
108
+ binaries: BinaryPaths
109
+ restart_runner: Callable[[], None]
110
+ restart_delay_seconds: float = 0.5
111
+ auth_cache: DeviceAuthCache | None = None
112
+ maintenance_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
113
+ write_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
114
+
115
+
116
+ def create_admin_app(
117
+ *,
118
+ config: AppConfig,
119
+ config_path: str | Path,
120
+ database_path: str | Path,
121
+ pairing_manager: PairingManager,
122
+ cache_directories: Sequence[Path] = (),
123
+ binaries: BinaryPaths | None = None,
124
+ restart_runner: Callable[[], None] = restart_launch_agent,
125
+ restart_delay_seconds: float = 0.5,
126
+ auth_cache: DeviceAuthCache | None = None,
127
+ ) -> FastAPI:
128
+ """Build the ASGI app that the server hosts on its Unix socket."""
129
+ state = _AdminState(
130
+ running_config=config,
131
+ config_path=Path(config_path).expanduser(),
132
+ database_path=Path(database_path).expanduser(),
133
+ pairing_manager=pairing_manager,
134
+ cache_directories=list(cache_directories),
135
+ binaries=binaries or resolve_binary_paths(),
136
+ restart_runner=restart_runner,
137
+ restart_delay_seconds=restart_delay_seconds,
138
+ auth_cache=auth_cache,
139
+ )
140
+ app = FastAPI(title="OpenVideo Admin", version=__version__)
141
+ app.state.admin = state
142
+
143
+ @app.get("/admin/api/status")
144
+ async def status() -> StatusResponse:
145
+ snapshot = _settings_snapshot(state)
146
+ return StatusResponse(
147
+ name=state.running_config.server.name,
148
+ version=__version__,
149
+ config_path=str(state.config_path),
150
+ database_path=str(state.database_path),
151
+ bind_address=state.running_config.server.bind_address,
152
+ port=state.running_config.server.port,
153
+ require_pairing=state.running_config.network.require_pairing,
154
+ restart_required=snapshot.restart_required,
155
+ paired_devices=await _count_devices(state.database_path),
156
+ ffmpeg=state.binaries.ffmpeg,
157
+ ffprobe=state.binaries.ffprobe,
158
+ )
159
+
160
+ @app.get("/admin/api/settings")
161
+ async def read_settings() -> SettingsResponse:
162
+ return _settings_snapshot(state)
163
+
164
+ @app.put("/admin/api/settings")
165
+ async def write_settings(body: dict[str, Any]) -> SettingsResponse:
166
+ try:
167
+ candidate = AppConfig.model_validate(body)
168
+ except ValidationError as exc:
169
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
170
+ async with state.write_lock:
171
+ try:
172
+ await asyncio.to_thread(_write_config, state.config_path, candidate)
173
+ except OSError as exc:
174
+ raise HTTPException(
175
+ status_code=500,
176
+ detail=f"Could not write configuration: {exc}",
177
+ ) from exc
178
+ return _settings_snapshot(state)
179
+
180
+ @app.get("/admin/api/devices")
181
+ async def read_devices() -> list[DeviceResponse]:
182
+ async with connect_database(state.database_path) as database:
183
+ devices = await list_paired_devices(database)
184
+ return [
185
+ DeviceResponse(
186
+ id=device.id,
187
+ name=device.device_name,
188
+ paired_at=device.paired_at,
189
+ last_seen_at=device.last_seen_at,
190
+ )
191
+ for device in devices
192
+ ]
193
+
194
+ @app.delete("/admin/api/devices/{device_id}")
195
+ async def revoke_device(device_id: str) -> MaintenanceResult:
196
+ async with connect_database(state.database_path) as database:
197
+ removed = await delete_paired_device(database, device_id)
198
+ if not removed:
199
+ raise HTTPException(status_code=404, detail="Unknown device")
200
+ if state.auth_cache is not None:
201
+ state.auth_cache.invalidate_device(device_id)
202
+ return MaintenanceResult(message="Device revoked")
203
+
204
+ @app.post("/admin/api/pairing/pin")
205
+ async def issue_pin() -> PinResponse:
206
+ active = await state.pairing_manager.issue_pin()
207
+ return PinResponse(pin=active.pin, expires_at=active.expires_at)
208
+
209
+ @app.post("/admin/api/maintenance/cache/clear")
210
+ async def clear_cache() -> MaintenanceResult:
211
+ async with state.maintenance_lock:
212
+ removed = 0
213
+ for directory in state.cache_directories:
214
+ removed += await asyncio.to_thread(_clear_directory, directory)
215
+ await _expire_missing_download_artifacts(state.database_path)
216
+ return MaintenanceResult(message="Cache cleared", removed_files=removed)
217
+
218
+ @app.post("/admin/api/maintenance/database/optimize")
219
+ async def optimize_database() -> MaintenanceResult:
220
+ async with state.maintenance_lock:
221
+ removed = await _optimize_database(state.database_path)
222
+ return MaintenanceResult(message="Database optimized", removed_records=removed)
223
+
224
+ @app.post("/admin/api/maintenance/database/reset")
225
+ async def reset_database(request: ResetRequest) -> MaintenanceResult:
226
+ if request.confirm != RESET_CONFIRMATION:
227
+ raise HTTPException(
228
+ status_code=400,
229
+ detail=f"Type {RESET_CONFIRMATION} to confirm the reset",
230
+ )
231
+ async with state.maintenance_lock:
232
+ await _reset_database(state.database_path)
233
+ if state.auth_cache is not None:
234
+ state.auth_cache.clear()
235
+ return MaintenanceResult(message="Database reset")
236
+
237
+ @app.post("/admin/api/restart", status_code=202)
238
+ async def restart(background: BackgroundTasks) -> MaintenanceResult:
239
+ background.add_task(
240
+ _request_restart,
241
+ state,
242
+ state.restart_delay_seconds,
243
+ )
244
+ return MaintenanceResult(message="Restart requested")
245
+
246
+ return app
247
+
248
+
249
+ def _settings_snapshot(state: _AdminState) -> SettingsResponse:
250
+ raw: str | None
251
+ try:
252
+ raw = state.config_path.read_text(encoding="utf-8")
253
+ except OSError:
254
+ raw = None
255
+ try:
256
+ file_config = load_config(state.config_path)
257
+ except (ConfigError, ValidationError, OSError) as exc:
258
+ return SettingsResponse(
259
+ config_path=str(state.config_path),
260
+ valid=False,
261
+ values=None,
262
+ raw=raw,
263
+ error=str(exc),
264
+ restart_required=False,
265
+ )
266
+ return SettingsResponse(
267
+ config_path=str(state.config_path),
268
+ valid=True,
269
+ values=_config_values(file_config),
270
+ raw=raw,
271
+ error=None,
272
+ restart_required=file_config != state.running_config,
273
+ )
274
+
275
+
276
+ def _config_values(config: AppConfig) -> dict[str, Any]:
277
+ values: dict[str, Any] = json.loads(
278
+ config.model_dump_json(exclude_none=True),
279
+ )
280
+ return values
281
+
282
+
283
+ def _write_config(config_path: Path, config: AppConfig) -> None:
284
+ runtime.ensure_directory(config_path.parent)
285
+ if config_path.is_file():
286
+ shutil.copy2(config_path, config_path.with_name(f"{config_path.name}.bak"))
287
+ payload = yaml.safe_dump(_config_values(config), sort_keys=False)
288
+ temporary = config_path.with_name(f"{config_path.name}.tmp")
289
+ with temporary.open("w", encoding="utf-8") as handle:
290
+ handle.write(payload)
291
+ handle.flush()
292
+ os.fsync(handle.fileno())
293
+ os.replace(temporary, config_path)
294
+
295
+
296
+ async def _count_devices(database_path: Path) -> int:
297
+ async with connect_database(database_path) as database:
298
+ async with database.execute("SELECT COUNT(*) FROM paired_devices") as cursor:
299
+ row = await cursor.fetchone()
300
+ return 0 if row is None else int(row[0])
301
+
302
+
303
+ async def _expire_missing_download_artifacts(database_path: Path) -> None:
304
+ async with connect_database(database_path) as database:
305
+ jobs = await list_ready_download_jobs(database)
306
+ missing = [
307
+ job.id
308
+ for job in jobs
309
+ if job.output_path is None or not Path(job.output_path).is_file()
310
+ ]
311
+ await expire_download_jobs(database, missing, int(time.time()))
312
+
313
+
314
+ def _clear_directory(root: Path) -> int:
315
+ directory = Path(root).expanduser()
316
+ if not directory.is_dir():
317
+ return 0
318
+ removed = 0
319
+ for child in list(directory.iterdir()):
320
+ try:
321
+ if child.is_dir() and not child.is_symlink():
322
+ removed += sum(1 for item in child.rglob("*") if item.is_file())
323
+ shutil.rmtree(child, ignore_errors=True)
324
+ else:
325
+ child.unlink(missing_ok=True)
326
+ removed += 1
327
+ except OSError:
328
+ continue
329
+ return removed
330
+
331
+
332
+ async def _optimize_database(database_path: Path) -> int:
333
+ async with connect_database(database_path) as database:
334
+ removed = await purge_orphaned_playback_history(database)
335
+ await database.execute("PRAGMA optimize")
336
+ await database.execute("PRAGMA wal_checkpoint(TRUNCATE)")
337
+ await database.commit()
338
+ await database.execute("VACUUM")
339
+ await database.commit()
340
+ return removed
341
+
342
+
343
+ async def _reset_database(database_path: Path) -> None:
344
+ async with connect_database(database_path) as database:
345
+ async with database.execute(
346
+ "SELECT name FROM sqlite_master "
347
+ "WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
348
+ ) as cursor:
349
+ tables = [row[0] for row in await cursor.fetchall()]
350
+ for table in tables:
351
+ await database.execute(f'DROP TABLE IF EXISTS "{table}"')
352
+ await database.commit()
353
+ await database.executescript(INITIAL_SCHEMA)
354
+ await database.commit()
355
+
356
+
357
+ def _request_restart(state: _AdminState, delay_seconds: float) -> None:
358
+ if delay_seconds > 0:
359
+ time.sleep(delay_seconds)
360
+ try:
361
+ state.restart_runner()
362
+ except LaunchAgentError:
363
+ logger.warning("Could not restart the LaunchAgent", exc_info=True)