Coverage for downtify/server_identity.py: 93%
84 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Who this Downtify server is, for the apps that connect to it.
3A client (the Android app) tells servers apart, and recognises one it has
4paired with before, by a **server ID**: a random value made once and kept
5in ``/data/server.json``, so it survives restarts, upgrades and a changed
6address. The file also holds the **server name** people see in the app's
7server list and in LAN discovery - editable in Settings > Apps, and the
8machine's hostname until someone changes it - and the port chosen in
9Settings > Server, if any (see :mod:`downtify.server_port`).
11:func:`server_info` is what ``GET /api/server/info`` returns. That route
12is public even when sign-in is required (an app must be able to check an
13address before it has any credentials), so it says nothing more than an
14app needs to decide how to talk to the server.
15"""
17from __future__ import annotations
19import json
20import os
21import secrets
22import socket
23import tempfile
24import threading
25from pathlib import Path
26from typing import Any, Optional
28#: The version of the ``/api/v1`` surface mobile clients use. Bump it only
29#: for a change that would break an app built against the previous one;
30#: additions (new fields, new endpoints) keep it.
31API_VERSION = 1
33#: Longest server name accepted, in characters.
34MAX_NAME_LENGTH = 64
36_FILE_NAME = 'server.json'
39def _default_name() -> str:
40 try:
41 name = socket.gethostname().strip()
42 except OSError:
43 name = ''
44 return (name or 'Downtify')[:MAX_NAME_LENGTH]
47def clean_name(value: Any) -> str:
48 """*value* as a server name: trimmed, one line, at most
49 :data:`MAX_NAME_LENGTH` characters. ``''`` when nothing is left."""
51 text = ' '.join(str(value or '').split())
52 return text[:MAX_NAME_LENGTH]
55class ServerIdentity:
56 """The server's ID and name, persisted in ``<data>/server.json``."""
58 def __init__(self, data_dir: Path) -> None:
59 self._path = Path(data_dir) / _FILE_NAME
60 self._lock = threading.Lock()
61 self._data = self._load()
63 def _load(self) -> dict[str, Any]:
64 try:
65 data = json.loads(self._path.read_text(encoding='utf-8'))
66 except (OSError, ValueError):
67 data = {}
68 if not isinstance(data, dict):
69 data = {}
70 changed = False
71 server_id = str(data.get('server_id') or '')
72 if len(server_id) < 16:
73 server_id = secrets.token_hex(16)
74 changed = True
75 name = clean_name(data.get('name'))
76 if not name:
77 name = _default_name()
78 changed = True
79 result: dict[str, Any] = {'server_id': server_id, 'name': name}
80 port = data.get('port')
81 if isinstance(port, int) and not isinstance(port, bool) and port > 0:
82 result['port'] = port
83 if changed:
84 self._write(result)
85 return result
87 def _write(self, data: dict[str, Any]) -> None:
88 self._path.parent.mkdir(parents=True, exist_ok=True)
89 fd, tmp = tempfile.mkstemp(
90 dir=self._path.parent, prefix='.server.', suffix='.json'
91 )
92 try:
93 with os.fdopen(fd, 'w', encoding='utf-8') as handle:
94 json.dump(data, handle)
95 os.replace(tmp, self._path)
96 except BaseException:
97 Path(tmp).unlink(missing_ok=True)
98 raise
100 @property
101 def server_id(self) -> str:
102 return self._data['server_id']
104 @property
105 def name(self) -> str:
106 return self._data['name']
108 @property
109 def port(self) -> Optional[int]:
110 """The port chosen in Settings > Server, or ``None``."""
112 return self._data.get('port')
114 def set_port(self, port: int) -> None:
115 with self._lock:
116 data = {**self._data, 'port': int(port)}
117 self._write(data)
118 self._data = data
120 def set_name(self, value: Any) -> str:
121 """Rename the server. Raises :class:`ValueError` for an empty name."""
123 name = clean_name(value)
124 if not name:
125 raise ValueError('The server name cannot be empty')
126 with self._lock:
127 data = {**self._data, 'name': name}
128 self._write(data)
129 self._data = data
130 return name
133def server_info(
134 identity: ServerIdentity,
135 *,
136 version: str,
137 require_sign_in: bool,
138 password_sign_in: Optional[bool] = None,
139 transcoding: Optional[dict[str, Any]],
140) -> dict[str, Any]:
141 """The public description of this server (``GET /api/server/info``).
143 *transcoding* is :meth:`downtify.transcode.Transcoder.capability`, or
144 ``None`` when ffmpeg isn't available - the app then only offers
145 original quality. ``password_sign_in`` says an app may sign in with a
146 username and password (``POST /api/auth/token``): not while sign-in
147 or local password login is turned off, when it pairs with a code.
148 """
150 return {
151 'server_id': identity.server_id,
152 'name': identity.name,
153 'product': 'Downtify',
154 'version': version,
155 'api_version': API_VERSION,
156 'require_sign_in': require_sign_in,
157 'capabilities': {
158 'transcoding': transcoding
159 or {'available': False, 'formats': [], 'bitrates': []},
160 'signed_urls': True,
161 'pairing': True,
162 'password_sign_in': (
163 require_sign_in
164 if password_sign_in is None
165 else password_sign_in
166 ),
167 'podcasts': True,
168 'discover': True,
169 'lyrics': True,
170 'library_sync': True,
171 },
172 }