Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helper functions for qBittorrent."""
2 
3 from datetime import UTC, datetime
4 from typing import Any, cast
5 
6 from qbittorrentapi import Client, TorrentDictionary, TorrentInfoList
7 
8 
9 def setup_client(url: str, username: str, password: str, verify_ssl: bool) -> Client:
10  """Create a qBittorrent client."""
11  client = Client(
12  url, username=username, password=password, VERIFY_WEBUI_CERTIFICATE=verify_ssl
13  )
14  client.auth_log_in(username, password)
15  return client
16 
17 
18 def seconds_to_hhmmss(seconds) -> str:
19  """Convert seconds to HH:MM:SS format."""
20  if seconds == 8640000:
21  return "None"
22 
23  minutes, seconds = divmod(seconds, 60)
24  hours, minutes = divmod(minutes, 60)
25  return f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"
26 
27 
28 def format_unix_timestamp(timestamp) -> str:
29  """Format a UNIX timestamp to a human-readable date."""
30  dt_object = datetime.fromtimestamp(timestamp, tz=UTC)
31  return dt_object.isoformat()
32 
33 
34 def format_progress(torrent: TorrentDictionary) -> str:
35  """Format the progress of a torrent."""
36  progress = cast(float, torrent["progress"]) * 100
37  return f"{progress:.2f}"
38 
39 
41  torrents: TorrentInfoList,
42 ) -> dict[str, dict[str, Any]]:
43  """Format a list of torrents."""
44  value = {}
45  for torrent in torrents:
46  value[str(torrent["name"])] = format_torrent(torrent)
47 
48  return value
49 
50 
51 def format_torrent(torrent: TorrentDictionary) -> dict[str, Any]:
52  """Format a single torrent."""
53  value = {}
54  value["id"] = torrent["hash"]
55  value["added_date"] = format_unix_timestamp(torrent["added_on"])
56  value["percent_done"] = format_progress(torrent)
57  value["status"] = torrent["state"]
58  value["eta"] = seconds_to_hhmmss(torrent["eta"])
59  ratio = cast(float, torrent["ratio"])
60  value["ratio"] = f"{ratio:.2f}"
61 
62  return value
str format_progress(TorrentDictionary torrent)
Definition: helpers.py:34
dict[str, Any] format_torrent(TorrentDictionary torrent)
Definition: helpers.py:51
Client setup_client(str url, str username, str password, bool verify_ssl)
Definition: helpers.py:9
dict[str, dict[str, Any]] format_torrents(TorrentInfoList torrents)
Definition: helpers.py:42