tenet 0.6.1__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.

Potentially problematic release.


This version of tenet might be problematic. Click here for more details.

tenet/__init__.py ADDED
@@ -0,0 +1,229 @@
1
+
2
+ """
3
+ Defines the :class:`TenetAccount` class,to be used to retrieve Tenet account info # NOQA
4
+ """
5
+
6
+ import time
7
+ from decimal import Decimal
8
+ from xml.etree import ElementTree
9
+
10
+ import requests
11
+
12
+ from . import exceptions, utils
13
+
14
+ __all__ = ["TenetAccount", "exceptions", "utils"]
15
+
16
+
17
+ class TenetAccount:
18
+ """Tenet client account for stats.tenet.ua"""
19
+
20
+ ACC_STATE_URL = "https://stats.tenet.ua/utl/!gadgapi.ls_state_evpkt"
21
+ BONUS_CHECK_URL = "https://stats.tenet.ua/utl/!gadgapi.ev_bonus_check"
22
+ BONUS_SWITCH_URL = "https://stats.tenet.ua/utl/!gadgapi.ev_bonus_switch"
23
+
24
+ ACC_STATE_NORMAL = "Normal"
25
+ ACC_STATE_LOCKED = "Locked"
26
+ ACC_STATE_WARNING = "Warning"
27
+
28
+ BONUS_ENABLED = "Enabled"
29
+ BONUS_DISABLED = "Disabled"
30
+ BONUS_ENDED = "Ended"
31
+ BONUS_ABSENT = "Absent"
32
+
33
+ USER_AGENT = "TenetAccount/1.0"
34
+
35
+ def __init__(self, **kwargs):
36
+ """
37
+ The __init__ expects user credentials
38
+
39
+ @param username: User's login to stats.tenet.ua
40
+ @type username: string
41
+
42
+ @param password: User's password to stats.tenet.ua
43
+ @type password: string
44
+
45
+ @param md5password: The MD5 hash of user's password to stats.tenet.ua
46
+ @type md5password: string
47
+ """
48
+ all_opts = [("username", "password"), ("username", "md5password")]
49
+ is_ok = any(set(opts).issubset(kwargs.keys()) for opts in all_opts)
50
+ if not is_ok:
51
+ raise exceptions.TenetBaseException(
52
+ "Usage: TenetAccount(username='user', password='pass')"
53
+ " or TenetAccount(username='user', md5password='hash')"
54
+ )
55
+
56
+ # account id number
57
+ self._id = None
58
+ # debtor, creditor or someone else?
59
+ self._state = None
60
+ # is account on or off?
61
+ self._enabled = None
62
+ # saldo
63
+ self._saldo = None
64
+ # tariff
65
+ self._tariff_plan = None
66
+ # is "Good day" enabled?
67
+ self._good_day = None
68
+ # on, off, end
69
+ self._bonus_state = None
70
+ # traffic left in megabytes
71
+ self._bonus_rest = None
72
+
73
+ self._username = kwargs.get("username")
74
+ self._password = kwargs.get("md5password")
75
+ if not self._password:
76
+ self._password = utils.password_to_hash(kwargs.get("password"))
77
+
78
+ self._session = requests.Session()
79
+ self._session.headers.update({"User-Agent": self.USER_AGENT})
80
+
81
+ @property
82
+ def id(self):
83
+ """Get or set the account id."""
84
+ return self._id
85
+
86
+ @id.setter
87
+ def id(self, value):
88
+ self._id = value
89
+
90
+ @property
91
+ def state(self):
92
+ """Get or set the account state."""
93
+ return self._state
94
+
95
+ @state.setter
96
+ def state(self, value):
97
+ value = value.lower()
98
+ if value == "n":
99
+ self._state = self.ACC_STATE_NORMAL
100
+ elif value == "l":
101
+ self._state = self.ACC_STATE_LOCKED
102
+ else:
103
+ self._state = self.ACC_STATE_WARNING
104
+
105
+ @property
106
+ def enabled(self):
107
+ """Get or set the account enabled status."""
108
+ return self._enabled
109
+
110
+ @enabled.setter
111
+ def enabled(self, value):
112
+ self._enabled = False
113
+ if value.upper() == "ON":
114
+ self._enabled = True
115
+
116
+ @property
117
+ def saldo(self):
118
+ """Get or set the saldo."""
119
+ return self._saldo
120
+
121
+ @saldo.setter
122
+ def saldo(self, value):
123
+ self._saldo = "{:.2f}".format(Decimal(value.replace(",", ".")))
124
+
125
+ @property
126
+ def tariff_plan(self):
127
+ """Get or set the service name."""
128
+ return self._tariff_plan
129
+
130
+ @tariff_plan.setter
131
+ def tariff_plan(self, value):
132
+ self._tariff_plan = value
133
+
134
+ @property
135
+ def good_day(self):
136
+ """Get or set the Good Day service status."""
137
+ return self._good_day
138
+
139
+ @good_day.setter
140
+ def good_day(self, value):
141
+ self._good_day = False
142
+ if value.upper() == "YES":
143
+ self._good_day = True
144
+
145
+ @property
146
+ def bonus_state(self):
147
+ """Get or set the bonus state."""
148
+ return self._bonus_state
149
+
150
+ @bonus_state.setter
151
+ def bonus_state(self, value):
152
+ if value.upper() == "ON":
153
+ self._bonus_state = self.BONUS_ENABLED
154
+ elif value.upper() == "OFF":
155
+ self._bonus_state = self.BONUS_DISABLED
156
+ elif value.upper() == "END":
157
+ self._bonus_state = self.BONUS_ENDED
158
+ elif value.upper() == "ABSENT":
159
+ self._bonus_state = self.BONUS_ABSENT
160
+
161
+ @property
162
+ def bonus_rest(self):
163
+ """Get or set the ammount of bonus left."""
164
+ return self._bonus_rest
165
+
166
+ @bonus_rest.setter
167
+ def bonus_rest(self, value):
168
+ # Convert MBytes to Bytes
169
+ value = float(str(value).replace(",", ".")) * 1024 * 1024
170
+ self._bonus_rest = value
171
+
172
+ def _request(self, url):
173
+ try:
174
+ payload = {
175
+ "login": self._username,
176
+ "md5pass": self._password,
177
+ "t": int(time.time()),
178
+ }
179
+ r = self._session.post(url, data=payload, timeout=5)
180
+ r.raise_for_status()
181
+ return r.content
182
+ except OSError as e:
183
+ raise exceptions.TenetBadRequest(str(e))
184
+
185
+ def _check_account(self):
186
+ # Get account info
187
+ xml_body = self._request(self.ACC_STATE_URL)
188
+ etree = ElementTree.fromstring(xml_body)
189
+
190
+ result = etree.findtext("./result")
191
+ if result != "OK":
192
+ error_msg = etree.findtext("./error_desc") or "Unknown Error"
193
+ raise exceptions.TenetServerError(error_msg.strip())
194
+
195
+ self.id = etree.findtext("./LS")
196
+ self.state = etree.findtext("./lsstate")
197
+ self.enabled = etree.findtext("./usrstate")
198
+ self.saldo = etree.findtext("./saldo")
199
+ self.tariff_plan = etree.findtext("./evpkt")
200
+ self.good_day = etree.findtext("./good_day")
201
+
202
+ def _check_bonus(self):
203
+ # Check bonus state
204
+ xml_body = self._request(self.BONUS_CHECK_URL)
205
+ etree = ElementTree.fromstring(xml_body)
206
+
207
+ result = etree.findtext("./result")
208
+ if result != "OK":
209
+ error_msg = etree.findtext("./error_desc") or "Unknown Error"
210
+ raise exceptions.TenetServerError(error_msg.strip())
211
+
212
+ self.bonus_state = etree.findtext("./bonus")
213
+ self.bonus_rest = etree.findtext("./rest")
214
+
215
+ def update(self):
216
+ """Update account info"""
217
+ self._check_account()
218
+ self._check_bonus()
219
+
220
+ def toggle_bonus(self):
221
+ """Toggle bonus switch"""
222
+ xml_body = self._request(self.BONUS_SWITCH_URL)
223
+ etree = ElementTree.fromstring(xml_body)
224
+
225
+ # The API will return "Unknown error" when bonus traffic is over
226
+ # and we are trying to disable bonus.
227
+ # Let's ignore all errors for now.
228
+ if etree.findtext("./result") == "OK":
229
+ self._check_bonus()
tenet/exceptions.py ADDED
@@ -0,0 +1,18 @@
1
+ """
2
+ Global TenetAccount exceptions and warnings classes.
3
+ """
4
+
5
+
6
+ class TenetBaseException(Exception):
7
+ """The base exception class for all exceptions this library raises."""
8
+
9
+
10
+
11
+ class TenetBadRequest(TenetBaseException):
12
+ """Bad connection or bad credentials."""
13
+
14
+
15
+
16
+ class TenetServerError(TenetBaseException):
17
+ """Received error message from API."""
18
+
tenet/utils.py ADDED
@@ -0,0 +1,35 @@
1
+ """
2
+ TenetAccount utility functions.
3
+ """
4
+
5
+ import hashlib
6
+
7
+
8
+ def sizeof_fmt(num_in_bytes):
9
+ """
10
+ Converts bytes into human readable format (e.g., 1K 234M 2G)
11
+
12
+ @param num_in_bytes: Number in bytes
13
+ @type num_in_bytes: **any** numeric type
14
+
15
+ @rtype: string
16
+ @return: Bytes into human readable format (e.g., 1K 234M 2G)
17
+ """
18
+ for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"]:
19
+ if abs(num_in_bytes) < 1024.0:
20
+ return f"{num_in_bytes:3.1f} {unit}"
21
+ num_in_bytes /= 1024.0
22
+ return "{:.1f} {}".format(num_in_bytes, "YiB")
23
+
24
+
25
+ def password_to_hash(password):
26
+ """
27
+ Generates the MD5 hash of password.
28
+
29
+ @param password: Password
30
+ @type password: string
31
+
32
+ @rtype: string
33
+ @return: MD5 hash of password
34
+ """
35
+ return hashlib.md5(password).hexdigest()
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: tenet
3
+ Version: 0.6.1
4
+ Summary: stats.tenet.ua account manager
5
+ Author-email: Dmytro Poltavchenko <dmytro.poltavchenko@gmail.com>
6
+ License-Expression: GPL-3.0-or-later
7
+ Classifier: Topic :: Internet
8
+ Classifier: Topic :: Software Development :: Libraries
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: certifi
14
+ Requires-Dist: chardet
15
+ Requires-Dist: idna
16
+ Requires-Dist: lxml
17
+ Requires-Dist: requests
18
+ Requires-Dist: urllib3
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest; extra == "dev"
21
+ Requires-Dist: ruff; extra == "dev"
22
+
23
+ # TenetAccount
24
+
25
+ ## Description
26
+ This is a Python module for the ISP TeNeT API.
27
+
28
+ ## Usage:
29
+ ```
30
+ >>> from tenet import TenetAccount
31
+ >>> from tenet.utils import sizeof_fmt
32
+ >>> TenetAccount()
33
+ Traceback (most recent call last):
34
+ File "<stdin>", line 1, in <module>
35
+ File "tenet/__init__.py", line 34, in __init__
36
+ "Usage: TenetAccount(username='user', password='pass')"
37
+ tenet.exceptions.TenetBaseException: Usage: TenetAccount(username='user', password='pass') or TenetAccount(username='user', md5password='hash')
38
+ >>> account = TenetAccount(
39
+ ... username='user-00000',
40
+ ... md5password='8b46a9e3095d350b2faeb1c503239b5e'
41
+ ... )
42
+ >>> account.update()
43
+ >>> print(account.id)
44
+ 00000
45
+ >>> print(account.state)
46
+ Normal
47
+ >>> print(account.enabled)
48
+ True
49
+ >>> print(account.tariff_plan)
50
+ Швидкісний Інтернет та Wi-Fi
51
+ >>> print(account.saldo)
52
+ 374.60
53
+ >>> print(account.good_day)
54
+ False
55
+ >>> print(account.bonus_state)
56
+ Enabled
57
+ >>> account.toggle_bonus()
58
+ >>> print(account.bonus_state)
59
+ Disabled
60
+ >>> print(sizeof_fmt(account.bonus_rest))
61
+ 10.0 GiB
62
+ ```
@@ -0,0 +1,7 @@
1
+ tenet/__init__.py,sha256=cc5Fkdo8vuMBy9yNsyP41CFwvTZphaUPHPGTjTuxdfQ,6844
2
+ tenet/exceptions.py,sha256=fiAP_G-OtYjfESwqJql86oe3CHR-GrMvTkpNscxAAS4,357
3
+ tenet/utils.py,sha256=8XKThInCWwNfG0wULs5XUm1HZZUKb0AcVj5-eyLvaJA,830
4
+ tenet-0.6.1.dist-info/METADATA,sha256=OGynMdvEH9BsG2YfezJGnIMXYf8z1PIHJSLdY7vWaEI,1716
5
+ tenet-0.6.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ tenet-0.6.1.dist-info/top_level.txt,sha256=2_8JJaJga6gacFpR0XC5IC8h5kH_HH1Uk0meCGm2t1s,6
7
+ tenet-0.6.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ tenet