CDMClient 0.1.0__tar.gz

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,16 @@
1
+ Metadata-Version: 2.1
2
+ Name: CDMClient
3
+ Version: 0.1.0
4
+ Summary: CDMClient
5
+ Author-email: Aron Radics <radics.aron.jozsef@gmail.com>
6
+ Requires-Python: >=3.9
7
+ License-File: LICENSE
8
+ Requires-Dist: requests
9
+ Requires-Dist: transmission_rpc
10
+ Requires-Dist: cryptography
11
+ Provides-Extra: dev
12
+ Requires-Dist: types-requests; extra == "dev"
13
+ Requires-Dist: twine; extra == "dev"
14
+ Requires-Dist: pylint; extra == "dev"
15
+ Requires-Dist: black; extra == "dev"
16
+ Requires-Dist: mypy; extra == "dev"
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ CDMClient.egg-info/PKG-INFO
5
+ CDMClient.egg-info/SOURCES.txt
6
+ CDMClient.egg-info/dependency_links.txt
7
+ CDMClient.egg-info/entry_points.txt
8
+ CDMClient.egg-info/requires.txt
9
+ CDMClient.egg-info/top_level.txt
10
+ cdm_client/__init__.py
11
+ cdm_client/cdm_client.py
12
+ cdm_client/config.py
13
+ cdm_client/transmission_adapter.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cdm-client = cdm_client.cdm_client:main
@@ -0,0 +1,10 @@
1
+ requests
2
+ transmission_rpc
3
+ cryptography
4
+
5
+ [dev]
6
+ types-requests
7
+ twine
8
+ pylint
9
+ black
10
+ mypy
@@ -0,0 +1 @@
1
+ cdm_client
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Aron Radics
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.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.1
2
+ Name: CDMClient
3
+ Version: 0.1.0
4
+ Summary: CDMClient
5
+ Author-email: Aron Radics <radics.aron.jozsef@gmail.com>
6
+ Requires-Python: >=3.9
7
+ License-File: LICENSE
8
+ Requires-Dist: requests
9
+ Requires-Dist: transmission_rpc
10
+ Requires-Dist: cryptography
11
+ Provides-Extra: dev
12
+ Requires-Dist: types-requests; extra == "dev"
13
+ Requires-Dist: twine; extra == "dev"
14
+ Requires-Dist: pylint; extra == "dev"
15
+ Requires-Dist: black; extra == "dev"
16
+ Requires-Dist: mypy; extra == "dev"
@@ -0,0 +1,49 @@
1
+ # CDMClient
2
+ CDM - Centralized Download Manager Client
3
+
4
+ ## Installation
5
+
6
+ ### Install/Upgrade package
7
+ ``` shell
8
+ python3 -m pip install --upgrade CDMClient --user
9
+ ```
10
+
11
+ ### Create service
12
+ ``` shell
13
+ echo "[Unit]
14
+ Description=cdm-client service
15
+ After=multi-user.target
16
+ Conflicts=getty@tty1.service
17
+ [Service]
18
+ User=${USER}
19
+ Type=simple
20
+ Environment="LC_ALL=C.UTF-8"
21
+ Environment="LANG=C.UTF-8"
22
+ ExecStart=${HOME}/.local/bin/cdm-client
23
+ Restart=on-failure
24
+ RestartSec=3
25
+ [Install]
26
+ WantedBy=multi-user.target" | sudo tee /etc/systemd/system/cdm-client.service
27
+ ```
28
+ ``` shell
29
+ sudo systemctl daemon-reload
30
+ sudo systemctl enable cdm-client.service
31
+ sudo systemctl start cdm-client.service
32
+ ```
33
+
34
+ ## Configuartion
35
+ Config file path: ```~/.config/cdm_client/config.ini```
36
+
37
+ This file automatically generated when the service starts. See the example below.
38
+ ``` ini
39
+ [connection]
40
+ server_host =
41
+ api_key =
42
+ rpc_user =
43
+ rpc_password =
44
+ ```
45
+
46
+ ## Check logs
47
+ ``` shell
48
+ journalctl -fu cdm-client
49
+ ```
File without changes
@@ -0,0 +1,66 @@
1
+ import logging
2
+ from logging.handlers import SysLogHandler
3
+ from time import sleep
4
+ import requests
5
+ from cdm_client.config import Config
6
+ from cdm_client.transmission_adapter import TransmissionAdapter
7
+
8
+
9
+ class CDMClient:
10
+ def __init__(self) -> None:
11
+ self._logger = self._init_logger()
12
+ self._config = Config()
13
+ self._transmission_adapter = TransmissionAdapter(
14
+ self._config["rpc_user"] or None, self._config["rpc_password"] or None
15
+ )
16
+
17
+ def _init_logger(self) -> logging.Logger:
18
+ syslog = SysLogHandler(address="/dev/log")
19
+ syslog.setFormatter(logging.Formatter("cdm-client %(name)s: %(levelname)s %(message)s"))
20
+ logger = logging.getLogger("cdm-client")
21
+ logger.addHandler(syslog)
22
+ logger.setLevel(logging.INFO)
23
+ return logger
24
+
25
+ def _update_status(self) -> None:
26
+ data = {"data": self._transmission_adapter.get_status()}
27
+ resp = requests.post(
28
+ f"{self._config['host']}/api/client/status/",
29
+ json=data,
30
+ headers={"x-api-key": self._config["api_key"]},
31
+ timeout=5,
32
+ )
33
+ resp.raise_for_status()
34
+
35
+ def _download_files(self) -> None:
36
+ resp = requests.get(
37
+ f"{self._config['host']}/api/client/", headers={"x-api-key": self._config["api_key"]}, timeout=5
38
+ )
39
+ resp.raise_for_status()
40
+
41
+ files = resp.json()["data"]["files"]
42
+ for torrent_id, path in files.items():
43
+ resp = requests.get(
44
+ f"{self._config['host']}/api/client/download/{torrent_id}/",
45
+ headers={"x-api-key": self._config["api_key"]},
46
+ stream=True,
47
+ timeout=5,
48
+ )
49
+ resp.raise_for_status()
50
+ self._transmission_adapter.add_torrent(resp.content, download_dir=path)
51
+ self._logger.info("Downloading torrent: %s to %s", torrent_id, path)
52
+
53
+ def run(self) -> None:
54
+ self._logger.info("Starting cdm-client...")
55
+ while True:
56
+ try:
57
+ self._update_status()
58
+ self._download_files()
59
+ sleep(30)
60
+ except Exception: # pylint: disable=broad-except
61
+ self._logger.exception("An error occurred.")
62
+
63
+
64
+ def main() -> None:
65
+ cdm_client = CDMClient()
66
+ cdm_client.run()
@@ -0,0 +1,85 @@
1
+ import os
2
+ import configparser
3
+ from typing import Union
4
+ from cryptography.fernet import Fernet
5
+
6
+
7
+ class Config:
8
+
9
+ CONFIG_FOLDER_PATH = os.path.join(os.path.expanduser("~"), ".config", "cdm_client")
10
+ KEY_PATH = os.path.join(CONFIG_FOLDER_PATH, "key.key")
11
+ CONFIG_PATH = os.path.join(CONFIG_FOLDER_PATH, "config.ini")
12
+ DEFAULT_CONFIG = {
13
+ "connection": {
14
+ "server_host": "",
15
+ "api_key": "",
16
+ "rpc_user": "",
17
+ "rpc_password": "",
18
+ }
19
+ }
20
+ ENCRYPTED_CONFIG = ["rpc_password"]
21
+
22
+ def __init__(self) -> None:
23
+ self._key: Union[bytes, str] = ""
24
+ self._config = self._load_config()
25
+ self._check_key()
26
+
27
+ def _check_key(self) -> None:
28
+ if not self._key_exists:
29
+ self._create_key()
30
+ else:
31
+ self._read_key()
32
+
33
+ def _create_key(self) -> None:
34
+ self._key = Fernet.generate_key()
35
+ with open(self.KEY_PATH, "w", encoding="utf-8") as f:
36
+ f.write(self._key.decode())
37
+
38
+ def _read_key(self) -> None:
39
+ with open(self.KEY_PATH, "r", encoding="utf-8") as f:
40
+ self._key = f.read().encode()
41
+
42
+ def _load_config(self) -> configparser.ConfigParser:
43
+ config = configparser.ConfigParser()
44
+ if config.read(self.CONFIG_PATH):
45
+ return config
46
+ return self._create_config()
47
+
48
+ def _create_config(self) -> configparser.ConfigParser:
49
+ if not os.path.exists(self.CONFIG_FOLDER_PATH):
50
+ os.makedirs(self.CONFIG_FOLDER_PATH)
51
+ config = configparser.ConfigParser()
52
+ for section, configs in self.DEFAULT_CONFIG.items():
53
+ config[section] = {}
54
+ for config_key, config_value in configs.items():
55
+ config[section][config_key] = config_value
56
+ with open(self.CONFIG_PATH, "w", encoding="utf-8") as f:
57
+ config.write(f)
58
+ return config
59
+
60
+ def _decrypt(self, value: str) -> str:
61
+ f = Fernet(self._key)
62
+ return f.decrypt(value.encode()).decode()
63
+
64
+ def _encrypt(self, value: str) -> str:
65
+ f = Fernet(self._key)
66
+ return f.encrypt(value.encode()).decode()
67
+
68
+ def _write_creds(self) -> None:
69
+ with open(self.CONFIG_PATH, "w", encoding="utf-8") as f:
70
+ self._config.write(f)
71
+
72
+ @property
73
+ def _key_exists(self) -> bool:
74
+ return os.path.exists(self.KEY_PATH)
75
+
76
+ def __getitem__(self, name: str) -> str:
77
+ if name in self.ENCRYPTED_CONFIG:
78
+ try:
79
+ return self._decrypt(self._config["connection"][name])
80
+ except Exception: # pylint: disable=broad-except
81
+ raw_value = self._config["connection"][name]
82
+ self._config["connection"][name] = self._encrypt(self._config["connection"][name])
83
+ self._write_creds()
84
+ return raw_value
85
+ return self._config["connection"][name]
@@ -0,0 +1,31 @@
1
+ import logging
2
+ from typing import Optional
3
+ from transmission_rpc import Client
4
+
5
+
6
+ class TransmissionAdapter:
7
+ def __init__(self, username: Optional[str] = None, password: Optional[str] = None) -> None:
8
+ self._client = Client(username=username, password=password)
9
+ self._logger = logging.getLogger("cdm-client")
10
+
11
+ def get_status(self) -> list[dict]:
12
+ torrents = self._client.get_torrents()
13
+ status = []
14
+ for torrent in torrents:
15
+ status.append(
16
+ {
17
+ "id": torrent.id,
18
+ "name": torrent.name,
19
+ "status": torrent.status.value,
20
+ "progress": int(torrent.progress),
21
+ "downloadDir": torrent.download_dir,
22
+ "addedDate": torrent.added_date.timestamp(),
23
+ "totalSize": torrent.total_size,
24
+ "eta": torrent.eta.total_seconds() if torrent.eta else None,
25
+ }
26
+ )
27
+ self._logger.info("Retrieved status of %s torrents", len(status))
28
+ return status
29
+
30
+ def add_torrent(self, torrent: bytes, download_dir: str) -> None:
31
+ self._client.add_torrent(torrent, download_dir=download_dir)
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "CDMClient"
3
+ version = "0.1.0"
4
+ description = "CDMClient"
5
+ authors = [{name = "Aron Radics", email = "radics.aron.jozsef@gmail.com"}]
6
+ requires-python = ">=3.9"
7
+ dependencies = [
8
+ "requests",
9
+ "transmission_rpc",
10
+ "cryptography",
11
+ ]
12
+
13
+ [project.optional-dependencies]
14
+ dev = [
15
+ "types-requests",
16
+ "twine",
17
+ "pylint",
18
+ "black",
19
+ "mypy",
20
+ ]
21
+
22
+ [build-system]
23
+ requires = ["setuptools>=42", "wheel"]
24
+ build-backend = "setuptools.build_meta"
25
+
26
+ [tool.setuptools]
27
+ packages = ["cdm_client"]
28
+
29
+ [project.scripts]
30
+ cdm-client = "cdm_client.cdm_client:main"
31
+
32
+ [tool.pylint]
33
+ disable = ["missing-docstring", "too-few-public-methods"]
34
+ max-line-length = 120
35
+
36
+ [tool.mypy]
37
+ disallow_untyped_calls = true
38
+ disallow_incomplete_defs = true
39
+ disallow_untyped_defs = true
40
+
41
+ [tool.black]
42
+ line-length = 120
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+