qnap-client 1.0.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.
@@ -0,0 +1,55 @@
1
+ """qnap-client — Async Python client for QNAP NAS."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .client import QnapClient
6
+ from .container_station import ContainerStationClient
7
+ from .exceptions import (
8
+ QnapAPIError,
9
+ QnapAuthError,
10
+ QnapConnectionError,
11
+ QnapError,
12
+ QnapTimeoutError,
13
+ )
14
+ from .models import (
15
+ Container,
16
+ CpuStats,
17
+ DriveHealth,
18
+ ExternalDrive,
19
+ FanStatus,
20
+ FirmwareUpdate,
21
+ MemoryStats,
22
+ NasData,
23
+ NetworkInterface,
24
+ SystemHealth,
25
+ SystemInfo,
26
+ VolumeStats,
27
+ )
28
+
29
+ __version__ = "1.0.0"
30
+
31
+ __all__ = [
32
+ "QnapClient",
33
+ "ContainerStationClient",
34
+ # Exceptions
35
+ "QnapError",
36
+ "QnapAuthError",
37
+ "QnapConnectionError",
38
+ "QnapTimeoutError",
39
+ "QnapAPIError",
40
+ # Models
41
+ "SystemInfo",
42
+ "SystemHealth",
43
+ "CpuStats",
44
+ "MemoryStats",
45
+ "NetworkInterface",
46
+ "DriveHealth",
47
+ "VolumeStats",
48
+ "FirmwareUpdate",
49
+ "FanStatus",
50
+ "ExternalDrive",
51
+ "Container",
52
+ "NasData",
53
+ # Version
54
+ "__version__",
55
+ ]
qnap_client/client.py ADDED
@@ -0,0 +1,459 @@
1
+ """Main QnapClient — async Python client for QNAP NAS."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import base64
7
+ import logging
8
+ from typing import Any
9
+
10
+ import aiohttp
11
+ import xmltodict
12
+
13
+ from .exceptions import (
14
+ QnapAPIError,
15
+ QnapAuthError,
16
+ QnapConnectionError,
17
+ QnapTimeoutError,
18
+ )
19
+ from .models import (
20
+ CpuStats,
21
+ DriveHealth,
22
+ ExternalDrive,
23
+ FanStatus,
24
+ FirmwareUpdate,
25
+ MemoryStats,
26
+ NasData,
27
+ NetworkInterface,
28
+ SystemHealth,
29
+ SystemInfo,
30
+ VolumeStats,
31
+ )
32
+
33
+ _LOGGER = logging.getLogger(__name__)
34
+
35
+
36
+ class QnapClient:
37
+ """Async client for the QNAP NAS CGI API.
38
+
39
+ Designed for use in Home Assistant custom integrations but general-purpose.
40
+
41
+ Usage::
42
+
43
+ async with QnapClient("192.168.1.10", 8080, "admin", "pass") as client:
44
+ data = await client.get_all()
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ host: str,
50
+ port: int,
51
+ username: str,
52
+ password: str,
53
+ *,
54
+ ssl: bool = False,
55
+ verify_ssl: bool = True,
56
+ timeout: int = 10,
57
+ session: aiohttp.ClientSession | None = None,
58
+ ) -> None:
59
+ self._host = host
60
+ self._port = port
61
+ self._username = username
62
+ self._password = password
63
+ self._ssl = ssl
64
+ self._verify_ssl = verify_ssl
65
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
66
+ self._provided_session = session
67
+
68
+ self._scheme = "https" if ssl else "http"
69
+ self._base = f"{self._scheme}://{host}:{port}"
70
+ self._session: aiohttp.ClientSession | None = None
71
+ self._sid: str | None = None
72
+
73
+ # ------------------------------------------------------------------
74
+ # Context manager
75
+ # ------------------------------------------------------------------
76
+
77
+ async def __aenter__(self) -> "QnapClient":
78
+ await self._ensure_session()
79
+ await self.login()
80
+ return self
81
+
82
+ async def __aexit__(self, *args: Any) -> None:
83
+ await self.logout()
84
+ if self._provided_session is None and self._session is not None:
85
+ await self._session.close()
86
+ self._session = None
87
+
88
+ # ------------------------------------------------------------------
89
+ # Session / auth
90
+ # ------------------------------------------------------------------
91
+
92
+ async def _ensure_session(self) -> aiohttp.ClientSession:
93
+ if self._provided_session is not None:
94
+ return self._provided_session
95
+ if self._session is None or self._session.closed:
96
+ connector = aiohttp.TCPConnector(ssl=self._verify_ssl)
97
+ self._session = aiohttp.ClientSession(
98
+ connector=connector, timeout=self._timeout
99
+ )
100
+ return self._session
101
+
102
+ @property
103
+ def _active_session(self) -> aiohttp.ClientSession:
104
+ session = self._provided_session or self._session
105
+ if session is None or session.closed:
106
+ raise QnapConnectionError("No active HTTP session — call login() first")
107
+ return session
108
+
109
+ async def login(self) -> None:
110
+ """Authenticate and store the session ID (authSid)."""
111
+ session = await self._ensure_session()
112
+ pwd_b64 = base64.b64encode(self._password.encode()).decode()
113
+ url = f"{self._base}/cgi-bin/authLogin.cgi"
114
+ data = {"user": self._username, "pwd": pwd_b64}
115
+ try:
116
+ async with session.post(url, data=data) as resp:
117
+ text = await resp.text()
118
+ except aiohttp.ClientConnectorError as exc:
119
+ raise QnapConnectionError(f"Cannot connect to {self._base}: {exc}") from exc
120
+ except asyncio.TimeoutError as exc:
121
+ raise QnapTimeoutError(f"Login timed out for {self._base}") from exc
122
+
123
+ parsed = self._parse_xml(text)
124
+ auth_passed = parsed.get("QDocRoot", {}).get("authPassed", "0")
125
+ if str(auth_passed) != "1":
126
+ raise QnapAuthError("Login failed — check username and password")
127
+
128
+ sid = parsed.get("QDocRoot", {}).get("authSid")
129
+ if not sid:
130
+ raise QnapAuthError("Login succeeded but no authSid in response")
131
+
132
+ self._sid = sid
133
+ _LOGGER.debug("Logged in; sid=%s", self._sid)
134
+
135
+ async def logout(self) -> None:
136
+ """Invalidate the current session."""
137
+ if self._sid is None:
138
+ return
139
+ try:
140
+ await self._get("/cgi-bin/authLogin.cgi", params={"logout": "1"})
141
+ except Exception: # noqa: BLE001
142
+ pass
143
+ finally:
144
+ self._sid = None
145
+
146
+ # ------------------------------------------------------------------
147
+ # HTTP helpers
148
+ # ------------------------------------------------------------------
149
+
150
+ async def _get(self, path: str, params: dict[str, str] | None = None) -> str:
151
+ """GET a URL, appending the session SID, return response text."""
152
+ if self._sid is None:
153
+ raise QnapAuthError("Not logged in — call login() first")
154
+ all_params = dict(params or {})
155
+ all_params["sid"] = self._sid
156
+
157
+ url = f"{self._base}{path}"
158
+ try:
159
+ async with self._active_session.get(url, params=all_params) as resp:
160
+ if resp.status == 401:
161
+ self._sid = None
162
+ raise QnapAuthError("Session expired (HTTP 401)")
163
+ resp.raise_for_status()
164
+ return await resp.text()
165
+ except aiohttp.ClientConnectorError as exc:
166
+ raise QnapConnectionError(f"Connection error: {exc}") from exc
167
+ except asyncio.TimeoutError as exc:
168
+ raise QnapTimeoutError("Request timed out") from exc
169
+
170
+ @staticmethod
171
+ def _parse_xml(text: str) -> dict[str, Any]:
172
+ try:
173
+ return xmltodict.parse(text) # type: ignore[no-any-return]
174
+ except Exception as exc:
175
+ raise QnapAPIError(f"Failed to parse XML response: {exc}") from exc
176
+
177
+ def _root(self, text: str) -> dict[str, Any]:
178
+ return self._parse_xml(text).get("QDocRoot", {})
179
+
180
+ # ------------------------------------------------------------------
181
+ # Public API
182
+ # ------------------------------------------------------------------
183
+
184
+ async def get_system_info(self) -> SystemInfo:
185
+ """Return basic NAS system information."""
186
+ text = await self._get(
187
+ "/cgi-bin/management/manaRequest.cgi", {"subfunc": "sysinfo"}
188
+ )
189
+ root = self._root(text)
190
+
191
+ model = root.get("model", {})
192
+ uptime_raw = root.get("uptime", "0")
193
+ try:
194
+ uptime_seconds = int(uptime_raw)
195
+ except (ValueError, TypeError):
196
+ uptime_seconds = 0
197
+
198
+ return SystemInfo(
199
+ model=model.get("displayModelName", ""),
200
+ name=root.get("hostname", ""),
201
+ serial_number=root.get("serialNumber", ""),
202
+ firmware_version=root.get("version", ""),
203
+ uptime_seconds=uptime_seconds,
204
+ )
205
+
206
+ async def get_system_health(self) -> SystemHealth:
207
+ """Return overall system health status."""
208
+ text = await self._get(
209
+ "/cgi-bin/management/manaRequest.cgi",
210
+ {"subfunc": "sysinfo", "sysHealth": "1"},
211
+ )
212
+ root = self._root(text)
213
+ status = root.get("sysHealth", {}).get("status", "Unknown")
214
+ return SystemHealth(status=status)
215
+
216
+ async def get_cpu_stats(self) -> CpuStats:
217
+ """Return current CPU usage percentage."""
218
+ text = await self._get(
219
+ "/cgi-bin/management/manaRequest.cgi", {"subfunc": "sysinfo"}
220
+ )
221
+ root = self._root(text)
222
+ cpu_usage_str = root.get("cpu", {}).get("cpu_usage", "0")
223
+ try:
224
+ cpu_usage = float(str(cpu_usage_str).rstrip("%"))
225
+ except (ValueError, TypeError):
226
+ cpu_usage = 0.0
227
+ return CpuStats(usage_percent=cpu_usage)
228
+
229
+ async def get_memory_stats(self) -> MemoryStats:
230
+ """Return RAM stats in megabytes."""
231
+ text = await self._get(
232
+ "/cgi-bin/management/manaRequest.cgi", {"subfunc": "sysinfo"}
233
+ )
234
+ root = self._root(text)
235
+ mem = root.get("memory_status", {})
236
+
237
+ def _mb(key: str) -> int:
238
+ raw = mem.get(key, "0")
239
+ try:
240
+ return int(raw)
241
+ except (ValueError, TypeError):
242
+ return 0
243
+
244
+ total = _mb("total")
245
+ free = _mb("free")
246
+ used = total - free if total >= free else _mb("used")
247
+ return MemoryStats(total_mb=total, free_mb=free, used_mb=used)
248
+
249
+ async def get_network_interfaces(self) -> list[NetworkInterface]:
250
+ """Return stats for all active network interfaces."""
251
+ text = await self._get(
252
+ "/cgi-bin/management/chartReq.cgi",
253
+ {"chart_func": "net_usage", "disk_select": "all"},
254
+ )
255
+ root = self._root(text)
256
+ ifaces_raw = root.get("net", {})
257
+ results: list[NetworkInterface] = []
258
+
259
+ if not isinstance(ifaces_raw, dict):
260
+ return results
261
+
262
+ for key, val in ifaces_raw.items():
263
+ if not isinstance(val, dict):
264
+ continue
265
+ try:
266
+ results.append(
267
+ NetworkInterface(
268
+ name=key,
269
+ mac=val.get("mac", ""),
270
+ ip=val.get("ip", ""),
271
+ rx_bytes_per_sec=float(val.get("rx", 0)),
272
+ tx_bytes_per_sec=float(val.get("tx", 0)),
273
+ )
274
+ )
275
+ except (ValueError, TypeError) as exc:
276
+ _LOGGER.debug("Skipping interface %s: %s", key, exc)
277
+
278
+ return results
279
+
280
+ async def get_drive_health(self) -> list[DriveHealth]:
281
+ """Return SMART/health info for all drives."""
282
+ text = await self._get(
283
+ "/cgi-bin/management/manaRequest.cgi",
284
+ {"subfunc": "sysinfo", "hd_smart": "1"},
285
+ )
286
+ root = self._root(text)
287
+ drives_raw = root.get("func", {}).get("ownContent", {}).get("hdList", {}).get("hdInfo", [])
288
+
289
+ if isinstance(drives_raw, dict):
290
+ drives_raw = [drives_raw]
291
+
292
+ results: list[DriveHealth] = []
293
+ for i, drive in enumerate(drives_raw):
294
+ if not isinstance(drive, dict):
295
+ continue
296
+ temp_raw = drive.get("hd_temperature")
297
+ try:
298
+ temp: int | None = int(temp_raw) if temp_raw else None
299
+ except (ValueError, TypeError):
300
+ temp = None
301
+
302
+ results.append(
303
+ DriveHealth(
304
+ drive_number=i + 1,
305
+ model=drive.get("hd_model", ""),
306
+ health=drive.get("hd_health", ""),
307
+ temperature=temp,
308
+ )
309
+ )
310
+ return results
311
+
312
+ async def get_volumes(self) -> list[VolumeStats]:
313
+ """Return storage volume statistics."""
314
+ text = await self._get(
315
+ "/cgi-bin/management/chartReq.cgi",
316
+ {"chart_func": "disk_usage", "disk_select": "all", "include": "all"},
317
+ )
318
+ root = self._root(text)
319
+ vols_raw = root.get("volumeList", {}).get("volume", [])
320
+
321
+ if isinstance(vols_raw, dict):
322
+ vols_raw = [vols_raw]
323
+
324
+ results: list[VolumeStats] = []
325
+ for vol in vols_raw:
326
+ if not isinstance(vol, dict):
327
+ continue
328
+
329
+ def _bytes(key: str) -> int:
330
+ raw = vol.get(key, "0")
331
+ try:
332
+ return int(raw)
333
+ except (ValueError, TypeError):
334
+ return 0
335
+
336
+ results.append(
337
+ VolumeStats(
338
+ name=vol.get("volumeLabel", vol.get("label", "")),
339
+ total_bytes=_bytes("sizeTotal"),
340
+ used_bytes=_bytes("sizeUsed"),
341
+ free_bytes=_bytes("sizeFree"),
342
+ status=vol.get("status", ""),
343
+ )
344
+ )
345
+ return results
346
+
347
+ async def get_firmware_update(self) -> FirmwareUpdate:
348
+ """Return current and available firmware version."""
349
+ text = await self._get(
350
+ "/cgi-bin/sys/sysRequest.cgi", {"subfunc": "firm_update"}
351
+ )
352
+ root = self._root(text)
353
+ firm = root.get("firmware", root)
354
+ current = firm.get("curVersion", firm.get("version", ""))
355
+ latest = firm.get("newVersion") or None # None if missing or empty string
356
+ return FirmwareUpdate(current_version=current, latest_version=latest)
357
+
358
+ async def get_fans(self) -> list[FanStatus]:
359
+ """Return fan speed readings (empty list if unsupported)."""
360
+ text = await self._get(
361
+ "/cgi-bin/management/manaRequest.cgi",
362
+ {"subfunc": "sysinfo", "sysfans": "1"},
363
+ )
364
+ root = self._root(text)
365
+ fans_raw = root.get("sysfan", {})
366
+
367
+ if not isinstance(fans_raw, dict):
368
+ return []
369
+
370
+ results: list[FanStatus] = []
371
+ for i, (_, val) in enumerate(fans_raw.items()):
372
+ if not isinstance(val, dict):
373
+ continue
374
+ try:
375
+ rpm = int(val.get("speed_rpm", val.get("rpm", 0)))
376
+ results.append(FanStatus(fan_number=i + 1, speed_rpm=rpm))
377
+ except (ValueError, TypeError) as exc:
378
+ _LOGGER.debug("Skipping fan entry %d: %s", i, exc)
379
+
380
+ return results
381
+
382
+ async def get_external_drives(self) -> list[ExternalDrive]:
383
+ """Return stats for externally-connected drives (empty list if none)."""
384
+ text = await self._get(
385
+ "/cgi-bin/management/chartReq.cgi",
386
+ {"chart_func": "disk_usage", "disk_select": "all", "include": "all"},
387
+ )
388
+ root = self._root(text)
389
+ ext_raw = root.get("externalDriveList", {}).get("drive", [])
390
+
391
+ if isinstance(ext_raw, dict):
392
+ ext_raw = [ext_raw]
393
+
394
+ results: list[ExternalDrive] = []
395
+ for drv in ext_raw:
396
+ if not isinstance(drv, dict):
397
+ continue
398
+
399
+ def _bytes(key: str) -> int:
400
+ raw = drv.get(key, "0")
401
+ try:
402
+ return int(raw)
403
+ except (ValueError, TypeError):
404
+ return 0
405
+
406
+ results.append(
407
+ ExternalDrive(
408
+ name=drv.get("name", ""),
409
+ total_bytes=_bytes("sizeTotal"),
410
+ used_bytes=_bytes("sizeUsed"),
411
+ )
412
+ )
413
+ return results
414
+
415
+ async def get_all(self) -> NasData:
416
+ """Fetch all NAS data in parallel and return a NasData aggregate."""
417
+ (
418
+ system_info,
419
+ system_health,
420
+ cpu,
421
+ memory,
422
+ network_interfaces,
423
+ drives,
424
+ volumes,
425
+ firmware,
426
+ fans,
427
+ external_drives,
428
+ ) = await asyncio.gather(
429
+ self.get_system_info(),
430
+ self.get_system_health(),
431
+ self.get_cpu_stats(),
432
+ self.get_memory_stats(),
433
+ self.get_network_interfaces(),
434
+ self.get_drive_health(),
435
+ self.get_volumes(),
436
+ self.get_firmware_update(),
437
+ self.get_fans(),
438
+ self.get_external_drives(),
439
+ return_exceptions=True,
440
+ )
441
+
442
+ def _unwrap(result: Any, default: Any) -> Any:
443
+ if isinstance(result, Exception):
444
+ _LOGGER.warning("get_all partial failure: %s", result)
445
+ return default
446
+ return result
447
+
448
+ return NasData(
449
+ system_info=_unwrap(system_info, SystemInfo("", "", "", "", 0)),
450
+ system_health=_unwrap(system_health, SystemHealth("Unknown")),
451
+ cpu=_unwrap(cpu, CpuStats(0.0)),
452
+ memory=_unwrap(memory, MemoryStats(0, 0, 0)),
453
+ network_interfaces=_unwrap(network_interfaces, []),
454
+ drives=_unwrap(drives, []),
455
+ volumes=_unwrap(volumes, []),
456
+ firmware=_unwrap(firmware, None),
457
+ fans=_unwrap(fans, []),
458
+ external_drives=_unwrap(external_drives, []),
459
+ )
@@ -0,0 +1,186 @@
1
+ """Container Station async client for QNAP NAS.
2
+
3
+ Uses the QNAP Container Station REST API:
4
+ - v3 API (list containers): QTS SID as Bearer token
5
+ - v1 API (start/stop/restart): CS_SESS_ID cookie via separate CS login
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ import aiohttp
14
+
15
+ from .exceptions import QnapAPIError, QnapAuthError, QnapConnectionError
16
+ from .models import Container
17
+
18
+ if TYPE_CHECKING:
19
+ from .client import QnapClient
20
+
21
+ _LOGGER = logging.getLogger(__name__)
22
+
23
+
24
+ class ContainerStationClient:
25
+ """Client for QNAP Container Station API.
26
+
27
+ Requires an authenticated QnapClient instance — reuses its aiohttp
28
+ session and host/port/ssl configuration.
29
+
30
+ Usage::
31
+
32
+ async with QnapClient(...) as client:
33
+ cs = ContainerStationClient(client)
34
+ containers = await cs.get_containers()
35
+ await cs.stop_container("my-container-id", "docker")
36
+ """
37
+
38
+ def __init__(self, client: QnapClient) -> None:
39
+ """Initialize using an authenticated QnapClient."""
40
+ self._client = client
41
+ self._cs_session_cookie: str | None = None
42
+
43
+ scheme = "https" if client._ssl else "http" # noqa: SLF001
44
+ base = f"{scheme}://{client._host}:{client._port}/container-station/api" # noqa: SLF001
45
+ self._base_v3 = f"{base}/v3"
46
+ self._base_v1 = f"{base}/v1"
47
+
48
+ # ------------------------------------------------------------------
49
+ # CS cookie auth (for v1 action endpoints)
50
+ # ------------------------------------------------------------------
51
+
52
+ async def _ensure_cs_auth(self) -> str:
53
+ """Return a valid CS_SESS_ID cookie, logging in if needed."""
54
+ if self._cs_session_cookie:
55
+ return self._cs_session_cookie
56
+
57
+ session = await self._client._ensure_session() # noqa: SLF001
58
+ try:
59
+ async with session.post(
60
+ f"{self._base_v1}/login",
61
+ json={
62
+ "username": self._client._username, # noqa: SLF001
63
+ "password": self._client._password_b64, # noqa: SLF001
64
+ },
65
+ ) as resp:
66
+ if resp.status != 200:
67
+ raise QnapAuthError(
68
+ f"Container Station login failed: HTTP {resp.status}"
69
+ )
70
+ cookie = resp.cookies.get("CS_SESS_ID")
71
+ if not cookie:
72
+ body = await resp.text()
73
+ raise QnapAuthError(
74
+ f"Container Station login: no session cookie returned. Body: {body[:200]}"
75
+ )
76
+ self._cs_session_cookie = cookie.value
77
+ return self._cs_session_cookie
78
+ except aiohttp.ClientConnectorError as err:
79
+ raise QnapConnectionError(
80
+ f"Cannot connect to Container Station: {err}"
81
+ ) from err
82
+
83
+ # ------------------------------------------------------------------
84
+ # Public API
85
+ # ------------------------------------------------------------------
86
+
87
+ async def get_containers(self) -> list[Container]:
88
+ """Return all containers with id, name, status, image, type.
89
+
90
+ Uses the v3 API with the QTS SID (Bearer token) from the parent
91
+ QnapClient — no separate Container Station login needed.
92
+
93
+ Returns:
94
+ List of Container dataclasses.
95
+
96
+ Raises:
97
+ QnapAuthError: If not authenticated.
98
+ QnapAPIError: On bad response.
99
+ """
100
+ if self._client._sid is None: # noqa: SLF001
101
+ raise QnapAuthError("QnapClient is not authenticated")
102
+
103
+ session = await self._client._ensure_session() # noqa: SLF001
104
+ headers = {"Authorization": f"Bearer {self._client._sid}"} # noqa: SLF001
105
+
106
+ try:
107
+ async with session.get(
108
+ f"{self._base_v3}/containers",
109
+ headers=headers,
110
+ ) as resp:
111
+ if resp.status == 401:
112
+ raise QnapAuthError("Container Station: Bearer token rejected")
113
+ if resp.status != 200:
114
+ raise QnapAPIError(
115
+ f"Container Station list failed: HTTP {resp.status}"
116
+ )
117
+ data: dict[str, Any] = await resp.json()
118
+ except aiohttp.ClientConnectorError as err:
119
+ raise QnapConnectionError(
120
+ f"Cannot connect to Container Station: {err}"
121
+ ) from err
122
+
123
+ items_raw: list[dict[str, Any]] = data.get("data", {}).get("items", [])
124
+ return [
125
+ Container(
126
+ id=c.get("id", ""),
127
+ name=c.get("name", ""),
128
+ status=c.get("status", ""),
129
+ image=c.get("image", ""),
130
+ type=c.get("type", "docker"),
131
+ )
132
+ for c in items_raw
133
+ ]
134
+
135
+ async def container_action(
136
+ self, container_id: str, container_type: str, action: str
137
+ ) -> None:
138
+ """Perform an action on a container.
139
+
140
+ Args:
141
+ container_id: Container ID from get_containers().
142
+ container_type: "docker" or "lxc".
143
+ action: "start", "stop", or "restart".
144
+
145
+ Raises:
146
+ ValueError: If action is not valid.
147
+ QnapAuthError: If authentication fails.
148
+ QnapAPIError: If the action fails.
149
+ """
150
+ if action not in ("start", "stop", "restart"):
151
+ raise ValueError(f"Invalid container action: {action!r}. Must be start, stop, or restart.")
152
+
153
+ cookie = await self._ensure_cs_auth()
154
+ session = await self._client._ensure_session() # noqa: SLF001
155
+ url = f"{self._base_v1}/container/{container_type}/{container_id}/{action}"
156
+ headers = {"Cookie": f"CS_SESS_ID={cookie}"}
157
+
158
+ async with session.put(url, headers=headers) as resp:
159
+ if resp.status == 401:
160
+ # Session expired — clear and retry once
161
+ self._cs_session_cookie = None
162
+ cookie = await self._ensure_cs_auth()
163
+ headers = {"Cookie": f"CS_SESS_ID={cookie}"}
164
+ async with session.put(url, headers=headers) as retry_resp:
165
+ if retry_resp.status not in (200, 204):
166
+ raise QnapAPIError(
167
+ f"Container {action} failed after retry: HTTP {retry_resp.status}"
168
+ )
169
+ return
170
+
171
+ if resp.status not in (200, 204):
172
+ raise QnapAPIError(
173
+ f"Container {action} failed: HTTP {resp.status}"
174
+ )
175
+
176
+ async def start_container(self, container_id: str, container_type: str = "docker") -> None:
177
+ """Start a container."""
178
+ await self.container_action(container_id, container_type, "start")
179
+
180
+ async def stop_container(self, container_id: str, container_type: str = "docker") -> None:
181
+ """Stop a container."""
182
+ await self.container_action(container_id, container_type, "stop")
183
+
184
+ async def restart_container(self, container_id: str, container_type: str = "docker") -> None:
185
+ """Restart a container."""
186
+ await self.container_action(container_id, container_type, "restart")
@@ -0,0 +1,23 @@
1
+ """Exceptions for the qnap-client library."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class QnapError(Exception):
7
+ """Base exception for all qnap-client errors."""
8
+
9
+
10
+ class QnapAuthError(QnapError):
11
+ """Authentication failed — bad credentials or session expired."""
12
+
13
+
14
+ class QnapConnectionError(QnapError):
15
+ """Could not connect to the NAS."""
16
+
17
+
18
+ class QnapTimeoutError(QnapError):
19
+ """Request to the NAS timed out."""
20
+
21
+
22
+ class QnapAPIError(QnapError):
23
+ """NAS returned an unexpected or malformed response."""
qnap_client/models.py ADDED
@@ -0,0 +1,123 @@
1
+ """Typed dataclasses for all qnap-client return types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class SystemInfo:
10
+ """Basic NAS system information."""
11
+
12
+ model: str
13
+ name: str
14
+ serial_number: str
15
+ firmware_version: str
16
+ uptime_seconds: int
17
+
18
+
19
+ @dataclass
20
+ class SystemHealth:
21
+ """Overall system health status."""
22
+
23
+ status: str # "Ready" | "Warning" | "Error"
24
+
25
+
26
+ @dataclass
27
+ class CpuStats:
28
+ """CPU utilisation."""
29
+
30
+ usage_percent: float
31
+
32
+
33
+ @dataclass
34
+ class MemoryStats:
35
+ """RAM stats in megabytes."""
36
+
37
+ total_mb: int
38
+ free_mb: int
39
+ used_mb: int
40
+
41
+
42
+ @dataclass
43
+ class NetworkInterface:
44
+ """Stats for a single network interface."""
45
+
46
+ name: str
47
+ mac: str
48
+ ip: str
49
+ rx_bytes_per_sec: float
50
+ tx_bytes_per_sec: float
51
+
52
+
53
+ @dataclass
54
+ class DriveHealth:
55
+ """SMART / health info for a single drive."""
56
+
57
+ drive_number: int
58
+ model: str
59
+ health: str
60
+ temperature: int | None
61
+
62
+
63
+ @dataclass
64
+ class VolumeStats:
65
+ """Storage volume / pool statistics."""
66
+
67
+ name: str
68
+ total_bytes: int
69
+ used_bytes: int
70
+ free_bytes: int
71
+ status: str
72
+
73
+
74
+ @dataclass
75
+ class FirmwareUpdate:
76
+ """Firmware version info."""
77
+
78
+ current_version: str
79
+ latest_version: str | None
80
+
81
+
82
+ @dataclass
83
+ class FanStatus:
84
+ """Fan sensor reading."""
85
+
86
+ fan_number: int
87
+ speed_rpm: int
88
+
89
+
90
+ @dataclass
91
+ class ExternalDrive:
92
+ """Externally-connected USB / eSATA drive."""
93
+
94
+ name: str
95
+ total_bytes: int
96
+ used_bytes: int
97
+
98
+
99
+ @dataclass
100
+ class Container:
101
+ """Container Station container."""
102
+
103
+ id: str
104
+ name: str
105
+ state: str
106
+ image: str
107
+ type: str = "docker"
108
+
109
+
110
+ @dataclass
111
+ class NasData:
112
+ """Top-level aggregate of all NAS sensor data."""
113
+
114
+ system_info: SystemInfo
115
+ system_health: SystemHealth
116
+ cpu: CpuStats
117
+ memory: MemoryStats
118
+ network_interfaces: list[NetworkInterface] = field(default_factory=list)
119
+ drives: list[DriveHealth] = field(default_factory=list)
120
+ volumes: list[VolumeStats] = field(default_factory=list)
121
+ firmware: FirmwareUpdate | None = None
122
+ fans: list[FanStatus] = field(default_factory=list)
123
+ external_drives: list[ExternalDrive] = field(default_factory=list)
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: qnap-client
3
+ Version: 1.0.0
4
+ Summary: Async Python client for QNAP NAS — replaces python-qnapstats
5
+ Project-URL: Homepage, https://github.com/disforw/python-qnap
6
+ Project-URL: Repository, https://github.com/disforw/python-qnap
7
+ Project-URL: Issues, https://github.com/disforw/python-qnap/issues
8
+ Project-URL: Changelog, https://github.com/disforw/python-qnap/blob/main/CHANGELOG.md
9
+ Author-email: disforw <disforw@users.noreply.github.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: aiohttp,async,container-station,homeassistant,nas,qnap
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Home Automation
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: aiohttp>=3.9.0
22
+ Requires-Dist: xmltodict>=0.13.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: aioresponses>=0.7; extra == 'dev'
25
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
26
+ Requires-Dist: pytest>=8.0; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # QNAP NAS Integration for Home Assistant
30
+
31
+ [![PyPI version](https://img.shields.io/pypi/v/qnap-client.svg)](https://pypi.org/project/qnap-client/)
32
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
34
+
35
+ Async Python client for QNAP NAS. Replaces the unmaintained `python-qnapstats` with a fully async, `aiohttp`-based library with typed models, proper exception handling, Container Station support, and graceful handling of unexpected API responses.
36
+
37
+ ## Why This Exists
38
+
39
+ `python-qnapstats` hasn't had a meaningful update in years. Fan sensor support and external drive support were added to the source repo but never published to PyPI. The library is synchronous, has no typed return values, and crashes on certain NAS models due to missing key handling.
40
+
41
+ This library fixes all of that.
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install qnap-client
47
+ ```
48
+
49
+ ## Quick Start
50
+
51
+ ```python
52
+ import asyncio
53
+ from qnap_client import QnapClient
54
+
55
+ async def main():
56
+ async with QnapClient("192.168.1.100", 8080, "admin", "password") as client:
57
+ data = await client.get_all()
58
+ print(f"NAS: {data.system_info.name} ({data.system_info.model})")
59
+ print(f"CPU: {data.system_info.cpu_usage_percent:.1f}%")
60
+ print(f"Health: {data.system_health.status}")
61
+ for vol in data.volumes:
62
+ used_pct = vol.used_bytes / vol.total_bytes * 100
63
+ print(f"Volume {vol.name}: {used_pct:.1f}% used")
64
+ if data.firmware_update.latest_version:
65
+ print(f"Firmware update available: {data.firmware_update.latest_version}")
66
+
67
+ asyncio.run(main())
68
+ ```
69
+
70
+ ## API Reference
71
+
72
+ ### `QnapClient`
73
+
74
+ ```python
75
+ QnapClient(
76
+ host: str,
77
+ port: int,
78
+ username: str,
79
+ password: str,
80
+ *,
81
+ ssl: bool = False,
82
+ verify_ssl: bool = True,
83
+ timeout: int = 10,
84
+ session: aiohttp.ClientSession | None = None,
85
+ )
86
+ ```
87
+
88
+ | Method | Returns | Description |
89
+ |---|---|---|
90
+ | `login()` | `None` | Authenticate and store session ID |
91
+ | `logout()` | `None` | Log out and clear session |
92
+ | `get_system_info()` | `SystemInfo` | CPU, memory, firmware version, uptime |
93
+ | `get_system_health()` | `SystemHealth` | Overall health status string |
94
+ | `get_network_interfaces()` | `list[NetworkInterface]` | Per-interface RX/TX rates |
95
+ | `get_drive_health()` | `list[DriveHealth]` | S.M.A.R.T. status + temperature per drive |
96
+ | `get_volumes()` | `list[VolumeStats]` | Storage volume usage |
97
+ | `get_firmware_update()` | `FirmwareUpdate` | Current + latest firmware version |
98
+ | `get_fans()` | `list[FanStatus]` | Fan speed RPM (empty list if unsupported) |
99
+ | `get_external_drives()` | `list[ExternalDrive]` | External USB/eSATA drives |
100
+ | `get_all()` | `NasData` | All of the above in parallel |
101
+
102
+ ### `ContainerStationClient`
103
+
104
+ ```python
105
+ from qnap_client import ContainerStationClient
106
+
107
+ async with QnapClient(...) as client:
108
+ cs = ContainerStationClient(client)
109
+ containers = await cs.get_containers()
110
+ await cs.stop_container(containers[0].id)
111
+ ```
112
+
113
+ | Method | Returns | Description |
114
+ |---|---|---|
115
+ | `get_containers()` | `list[Container]` | All containers with id, name, status, image, type |
116
+ | `start_container(id, type)` | `None` | Start a container |
117
+ | `stop_container(id, type)` | `None` | Stop a container |
118
+ | `restart_container(id, type)` | `None` | Restart a container |
119
+ | `container_action(id, type, action)` | `None` | Generic action (start/stop/restart) |
120
+
121
+ ### Models
122
+
123
+ | Model | Fields |
124
+ |---|---|
125
+ | `SystemInfo` | `name`, `model`, `serial_number`, `firmware_version`, `uptime_seconds`, `cpu_usage_percent`, `memory_total_mb`, `memory_free_mb`, `memory_used_mb` |
126
+ | `SystemHealth` | `status` |
127
+ | `NetworkInterface` | `name`, `mac`, `ip`, `rx_bytes_per_sec`, `tx_bytes_per_sec` |
128
+ | `DriveHealth` | `drive_number`, `model`, `health`, `temperature` |
129
+ | `VolumeStats` | `name`, `total_bytes`, `used_bytes`, `free_bytes`, `status` |
130
+ | `FirmwareUpdate` | `current_version`, `latest_version` (None = up to date) |
131
+ | `FanStatus` | `fan_number`, `speed_rpm` |
132
+ | `ExternalDrive` | `name`, `total_bytes`, `used_bytes`, `free_bytes` |
133
+ | `Container` | `id`, `name`, `status`, `image`, `type` |
134
+ | `NasData` | All of the above combined |
135
+
136
+ ### Exceptions
137
+
138
+ | Exception | When |
139
+ |---|---|
140
+ | `QnapError` | Base exception |
141
+ | `QnapAuthError` | Bad credentials or session expired |
142
+ | `QnapConnectionError` | NAS unreachable |
143
+ | `QnapTimeoutError` | Request timed out |
144
+ | `QnapAPIError` | Unexpected or malformed API response |
145
+
146
+ ## HTTPS / Self-Signed Certificates
147
+
148
+ ```python
149
+ client = QnapClient("nas.local", 443, "admin", "password", ssl=True, verify_ssl=False)
150
+ ```
151
+
152
+ ## Home Assistant Integration
153
+
154
+ This library is the backing library for the [QNAP NAS Integration for Home Assistant](https://github.com/disforw/qnap).
155
+
156
+ ## Contributing
157
+
158
+ PRs welcome. This library is actively maintained. If your QNAP model returns unexpected data, open an issue with the raw API response and we'll fix it.
159
+
160
+ ## License
161
+
162
+ MIT
@@ -0,0 +1,9 @@
1
+ qnap_client/__init__.py,sha256=F-B4Oo_iJnTziV-lMjRvlY7rHqqls_Zrqo9dCi0bgd4,1017
2
+ qnap_client/client.py,sha256=A4rxj9igQy6_z1630trKWoo5vmXqoxlLDwXN0JRjzB4,16053
3
+ qnap_client/container_station.py,sha256=WpFdJ1QOAvua0C5Ip1lVbjdX_FB7Fzw-d6IsDUx7oOI,7214
4
+ qnap_client/exceptions.py,sha256=XZ9TATSCWAFc2ZG8DyrpmX2sX_GJqrIvFRCGhBfi8SQ,521
5
+ qnap_client/models.py,sha256=wPXB1qAEzgAcSfd8Nws-4H5K63v_5AIMrQS5ajAi_JY,2216
6
+ qnap_client-1.0.0.dist-info/METADATA,sha256=xzNI4OjQUqbnIFppi5ME0ejH8vpxEoW0mycOQxxX1xk,6202
7
+ qnap_client-1.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ qnap_client-1.0.0.dist-info/licenses/LICENSE,sha256=d7WprfcYP9hstoffASEUdD-pC_8_3vYEDCwCN27GuAY,1064
9
+ qnap_client-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 disforw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.