Coverage for downtify/integration_check.py: 92%
185 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"""Try a slskd or Navidrome configuration and say what is wrong with it.
3Both integrations are set up by pasting an address and a credential, and
4a typo shows up much later: a download that quietly falls back to YouTube,
5a playlist that never appears. The checks here run the same first requests
6those features would make, so the Settings page can answer "is this
7right?" while the values are still in the form.
9A result is a list of checks, each ``{id, status, code, detail}``. Codes
10are stable identifiers the UI translates; ``detail`` is only ever a short
11fact (a path, a state name, an HTTP status). Nothing from an exception
12message is passed on: httpx puts the request URL in them, and a Subsonic
13URL carries the login token.
14"""
16from __future__ import annotations
18import os
19import re
20import ssl
21from pathlib import Path
22from typing import Any, Optional
23from urllib.parse import urlsplit
24from urllib.request import proxy_bypass
26import httpx
27from loguru import logger
29from .navidrome import SUBSONIC_AUTH_FAILED, NavidromeClient, SubsonicError
30from .proxy_config import outbound_proxy_config
31from .slskd_provider import SlskdClient
33#: Seconds each request may take. A test that hangs is worse than one
34#: that says "no answer".
35PROBE_TIMEOUT = 8.0
37STATUS_OK = 'ok'
38STATUS_WARN = 'warn'
39STATUS_FAIL = 'fail'
41_VERSION = re.compile(r'^\d+(\.\d+)+')
42_PROXY_TEST_URL = 'https://check.torproject.org/api/ip'
45def _get(url: str, **kwargs: Any) -> httpx.Response:
46 """The one place a slskd probe touches the network (tests replace it)."""
48 return httpx.get(url, follow_redirects=True, **kwargs)
51def _check(
52 check_id: str, status: str, code: str = '', detail: str = ''
53) -> dict[str, str]:
54 return {'id': check_id, 'status': status, 'code': code, 'detail': detail}
57def _result(checks: list[dict[str, str]], server: str = '') -> dict[str, Any]:
58 return {
59 'ok': all(check['status'] != STATUS_FAIL for check in checks),
60 'server': server,
61 'checks': checks,
62 }
65def _transport_code(exc: BaseException) -> str:
66 """Why a request never got an answer, without quoting the error."""
68 if isinstance(exc, httpx.TimeoutException):
69 return 'timeout'
70 if isinstance(exc, (httpx.InvalidURL, httpx.UnsupportedProtocol)):
71 return 'bad_url'
72 seen: set[int] = set()
73 cause: Optional[BaseException] = exc
74 while cause is not None and id(cause) not in seen:
75 seen.add(id(cause))
76 if isinstance(cause, ssl.SSLError):
77 return 'tls'
78 cause = cause.__cause__ or cause.__context__
79 return 'unreachable'
82def _log_failure(what: str, exc: BaseException) -> None:
83 # The type only: the message may carry the URL, and with it a token.
84 logger.info('{} check failed: {}', what, type(exc).__name__)
87def check_outbound_proxy() -> dict[str, Any]:
88 """Check proxy reachability and whether the exit is a Tor relay.
90 The response deliberately omits the public IP returned by the check
91 service. A configured bypass for that host is reported without making a
92 direct request.
93 """
95 config = outbound_proxy_config()
96 proxy_url = config.proxy_urls.get('https') or config.proxy_urls.get('all')
97 result: dict[str, Any] = {
98 'ok': False,
99 'configured': bool(proxy_url),
100 'strict': config.strict,
101 'proxy_scheme': urlsplit(proxy_url).scheme if proxy_url else '',
102 'tor_exit': None,
103 'checks': [],
104 }
105 if not proxy_url:
106 result['checks'] = [
107 _check('connection', STATUS_FAIL, 'not_configured')
108 ]
109 return result
110 if proxy_bypass('check.torproject.org'):
111 result['checks'] = [_check('connection', STATUS_FAIL, 'bypassed')]
112 return result
114 try:
115 response = httpx.get(_PROXY_TEST_URL, timeout=PROBE_TIMEOUT)
116 except Exception as exc:
117 _log_failure('outbound proxy', exc)
118 result['checks'] = [
119 _check('connection', STATUS_FAIL, _transport_code(exc))
120 ]
121 return result
122 if response.status_code != 200:
123 result['checks'] = [
124 _check(
125 'connection',
126 STATUS_FAIL,
127 'http_error',
128 str(response.status_code),
129 )
130 ]
131 return result
132 try:
133 payload = response.json()
134 except ValueError:
135 payload = None
136 if not isinstance(payload, dict) or not isinstance(
137 payload.get('IsTor'), bool
138 ):
139 result['checks'] = [
140 _check('connection', STATUS_FAIL, 'invalid_response')
141 ]
142 return result
144 tor_exit = payload['IsTor']
145 result['ok'] = True
146 result['tor_exit'] = tor_exit
147 result['checks'] = [
148 _check('connection', STATUS_OK, 'reachable'),
149 _check(
150 'tor',
151 STATUS_OK if tor_exit else STATUS_WARN,
152 'tor_exit' if tor_exit else 'not_tor',
153 ),
154 ]
155 return result
158# ── slskd ────────────────────────────────────────────────────────────
159def _slskd_version(resp: httpx.Response) -> Optional[str]:
160 """The version slskd reports, or ``None`` if this isn't slskd."""
162 try:
163 body = resp.json()
164 except ValueError:
165 body = resp.text
166 text = str(body).strip().strip('"') if isinstance(body, str) else ''
167 return text if _VERSION.match(text) else None
170def _slskd_soulseek(
171 base_url: str, headers: dict[str, str]
172) -> Optional[dict[str, str]]:
173 """Whether slskd is logged in to the Soulseek network."""
175 try:
176 resp = _get(
177 f'{base_url}/api/v0/server', headers=headers, timeout=PROBE_TIMEOUT
178 )
179 resp.raise_for_status()
180 data = resp.json()
181 except Exception as exc:
182 _log_failure('slskd server state', exc)
183 return None
184 if not isinstance(data, dict) or 'isLoggedIn' not in data:
185 return None
186 if data.get('isLoggedIn'):
187 return _check(
188 'soulseek', STATUS_OK, 'ok', str(data.get('username') or '')
189 )
190 return _check(
191 'soulseek', STATUS_WARN, 'offline', str(data.get('state') or '')
192 )
195def _slskd_folder(cfg: dict[str, Any]) -> dict[str, str]:
196 """Whether Downtify can read the folder slskd's files end up in."""
198 source = str(cfg.get('source_dir') or '')
199 probe_cfg = {**cfg, 'timeout_seconds': int(PROBE_TIMEOUT)}
200 candidates = [source]
201 try:
202 # slskd's own idea of where it downloads, in case it is mounted
203 # here at the same path.
204 candidates += SlskdClient(probe_cfg).remote_download_directories()
205 except Exception as exc:
206 _log_failure('slskd folders', exc)
207 for raw in candidates:
208 path = Path(raw) if raw else None
209 if path is not None and path.is_dir() and os.access(path, os.R_OK):
210 return _check('folder', STATUS_OK, 'ok', str(path))
211 return _check('folder', STATUS_WARN, 'missing', source)
214def check_slskd(cfg: dict[str, Any]) -> dict[str, Any]:
215 """Test a normalized slskd configuration (see ``_effective_slskd_settings``)."""
217 base_url = str(cfg.get('base_url') or '')
218 api_key = str(cfg.get('api_key') or '')
219 if not base_url or not api_key:
220 return _result([_check('config', STATUS_FAIL, 'missing')])
222 headers = {'X-API-Key': api_key}
223 try:
224 resp = _get(
225 f'{base_url}/api/v0/application/version',
226 headers=headers,
227 timeout=PROBE_TIMEOUT,
228 )
229 except Exception as exc:
230 _log_failure('slskd connection', exc)
231 return _result([
232 _check('connection', STATUS_FAIL, _transport_code(exc))
233 ])
235 if resp.status_code in {401, 403}:
236 return _result([
237 _check('connection', STATUS_OK),
238 _check('auth', STATUS_FAIL, 'bad_key'),
239 ])
240 if resp.status_code == 404:
241 return _result([_check('connection', STATUS_FAIL, 'not_slskd')])
242 if resp.status_code >= 400:
243 return _result([
244 _check(
245 'connection',
246 STATUS_FAIL,
247 'http_error',
248 str(resp.status_code),
249 )
250 ])
251 version = _slskd_version(resp)
252 if version is None:
253 return _result([_check('connection', STATUS_FAIL, 'not_slskd')])
255 checks = [_check('connection', STATUS_OK), _check('auth', STATUS_OK)]
256 soulseek = _slskd_soulseek(base_url, headers)
257 if soulseek is not None:
258 checks.append(soulseek)
259 checks.append(_slskd_folder(cfg))
260 return _result(checks, f'slskd {version}')
263# ── Navidrome ────────────────────────────────────────────────────────
264def _navidrome_failure(exc: BaseException) -> dict[str, str]:
265 """The connection/auth check that an exception from a request means."""
267 if isinstance(exc, SubsonicError):
268 if exc.code == SUBSONIC_AUTH_FAILED:
269 return _check('auth', STATUS_FAIL, 'bad_credentials')
270 # The server's own words, never a URL.
271 return _check('auth', STATUS_FAIL, 'api_error', str(exc)[:160])
272 if isinstance(exc, httpx.HTTPStatusError):
273 status = exc.response.status_code
274 if status in {401, 403}:
275 return _check('auth', STATUS_FAIL, 'bad_credentials')
276 if status in {404, 405}:
277 return _check('connection', STATUS_FAIL, 'not_navidrome')
278 return _check('connection', STATUS_FAIL, 'http_error', str(status))
279 if isinstance(exc, (httpx.HTTPError, httpx.InvalidURL)):
280 return _check('connection', STATUS_FAIL, _transport_code(exc))
281 # A page that isn't JSON, or JSON that isn't a Subsonic reply.
282 return _check('connection', STATUS_FAIL, 'not_navidrome')
285def _navidrome_scan(
286 client: NavidromeClient, cfg: dict[str, Any]
287) -> Optional[dict[str, str]]:
288 """Whether the account used for library scans is allowed to start one.
290 ``startScan`` is admin-only in Navidrome, and a refusal there is only
291 ever logged, so a scan account that can't scan looks like it works.
292 ``getUser`` on oneself tells without starting a scan.
293 """
295 user, password = client._scan_credentials()
296 separate = bool(cfg.get('admin_username') and cfg.get('admin_password'))
297 try:
298 body = client._request(
299 'getUser', {'username': user}, username=user, password=password
300 )
301 except SubsonicError as exc:
302 if separate and exc.code == SUBSONIC_AUTH_FAILED:
303 return _check('scan', STATUS_FAIL, 'bad_admin')
304 return None
305 except Exception as exc:
306 _log_failure('navidrome scan account', exc)
307 return None
308 info = body.get('user')
309 admin = info.get('adminRole') if isinstance(info, dict) else None
310 if admin is True:
311 return _check('scan', STATUS_OK, 'ok')
312 if admin is False:
313 return _check(
314 'scan',
315 STATUS_WARN,
316 'not_admin_separate' if separate else 'not_admin',
317 )
318 return None
321def check_navidrome(cfg: dict[str, Any]) -> dict[str, Any]:
322 """Test a normalized Navidrome configuration (see ``_effective_navidrome_settings``)."""
324 if not (cfg.get('url') and cfg.get('username') and cfg.get('password')):
325 return _result([_check('config', STATUS_FAIL, 'missing')])
327 client = NavidromeClient(cfg)
328 client.timeout = PROBE_TIMEOUT
329 try:
330 body = client._request('ping')
331 except Exception as exc:
332 _log_failure('navidrome connection', exc)
333 failure = _navidrome_failure(exc)
334 if failure['id'] == 'auth':
335 return _result([_check('connection', STATUS_OK), failure])
336 return _result([failure])
338 checks = [_check('connection', STATUS_OK), _check('auth', STATUS_OK)]
339 if cfg.get('scan_after_download', True):
340 scan = _navidrome_scan(client, cfg)
341 if scan is not None:
342 checks.append(scan)
343 name = str(body.get('type') or 'Subsonic')
344 version = str(body.get('serverVersion') or '')
345 return _result(checks, f'{name} {version}'.strip())