perfectpanel-client 0.1.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.
- perfectpanel/__init__.py +66 -0
- perfectpanel/_money.py +128 -0
- perfectpanel/client.py +452 -0
- perfectpanel/exceptions.py +159 -0
- perfectpanel/models.py +208 -0
- perfectpanel/py.typed +0 -0
- perfectpanel_client-0.1.0.dist-info/METADATA +216 -0
- perfectpanel_client-0.1.0.dist-info/RECORD +11 -0
- perfectpanel_client-0.1.0.dist-info/WHEEL +5 -0
- perfectpanel_client-0.1.0.dist-info/licenses/LICENSE +21 -0
- perfectpanel_client-0.1.0.dist-info/top_level.txt +1 -0
perfectpanel/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""perfectpanel — a small, typed client for the Perfect Panel v2 API.
|
|
2
|
+
|
|
3
|
+
from perfectpanel import PerfectPanelClient
|
|
4
|
+
|
|
5
|
+
with PerfectPanelClient("sandbox") as client:
|
|
6
|
+
for service in client.services()[:3]:
|
|
7
|
+
print(service.service, service.name, service.rate)
|
|
8
|
+
|
|
9
|
+
Seven methods cover the whole public API: :meth:`services`, :meth:`add`,
|
|
10
|
+
:meth:`status`, :meth:`multi_status`, :meth:`balance`, :meth:`cancel`,
|
|
11
|
+
:meth:`refill`. Every failure raises a subclass of
|
|
12
|
+
:class:`perfectpanel.PerfectPanelError`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from ._money import MICRO, Money, from_micro, to_micro
|
|
18
|
+
from .client import DEFAULT_BASE_URL, PerfectPanelClient
|
|
19
|
+
from .exceptions import (
|
|
20
|
+
APIError,
|
|
21
|
+
CancelRejectedError,
|
|
22
|
+
InvalidAPIKeyError,
|
|
23
|
+
OrderNotFoundError,
|
|
24
|
+
OrderRejectedError,
|
|
25
|
+
PerfectPanelError,
|
|
26
|
+
RefillRejectedError,
|
|
27
|
+
ResponseParseError,
|
|
28
|
+
ServiceNotFoundError,
|
|
29
|
+
TransportError,
|
|
30
|
+
UnknownActionError,
|
|
31
|
+
)
|
|
32
|
+
from .models import (
|
|
33
|
+
ActionAck,
|
|
34
|
+
Balance,
|
|
35
|
+
OrderPlaced,
|
|
36
|
+
OrderStatus,
|
|
37
|
+
Service,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__version__ = "0.1.0"
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"__version__",
|
|
44
|
+
"PerfectPanelClient",
|
|
45
|
+
"DEFAULT_BASE_URL",
|
|
46
|
+
"MICRO",
|
|
47
|
+
"Money",
|
|
48
|
+
"to_micro",
|
|
49
|
+
"from_micro",
|
|
50
|
+
"Service",
|
|
51
|
+
"OrderPlaced",
|
|
52
|
+
"OrderStatus",
|
|
53
|
+
"Balance",
|
|
54
|
+
"ActionAck",
|
|
55
|
+
"PerfectPanelError",
|
|
56
|
+
"APIError",
|
|
57
|
+
"TransportError",
|
|
58
|
+
"ResponseParseError",
|
|
59
|
+
"InvalidAPIKeyError",
|
|
60
|
+
"ServiceNotFoundError",
|
|
61
|
+
"OrderRejectedError",
|
|
62
|
+
"OrderNotFoundError",
|
|
63
|
+
"CancelRejectedError",
|
|
64
|
+
"RefillRejectedError",
|
|
65
|
+
"UnknownActionError",
|
|
66
|
+
]
|
perfectpanel/_money.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Integer-safe money handling.
|
|
2
|
+
|
|
3
|
+
Panels return money as decimal strings (``"0.5050"``). Binary floats quietly
|
|
4
|
+
lose fractions of a cent once you sum a few thousand orders, so every amount
|
|
5
|
+
here is parsed with :class:`decimal.Decimal` and then carried as an integer
|
|
6
|
+
number of **micro-units** (one millionth of the currency unit), the same unit
|
|
7
|
+
used by Talon's public price API (``cheapest_micro``).
|
|
8
|
+
|
|
9
|
+
Integer micro-units add, subtract and compare exactly, so a wallet
|
|
10
|
+
reconciliation never drifts by ``0.0000000000001``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
|
17
|
+
from typing import Union
|
|
18
|
+
|
|
19
|
+
MICRO = 1_000_000
|
|
20
|
+
"""Micro-units per currency unit."""
|
|
21
|
+
|
|
22
|
+
Number = Union[int, float, str, Decimal]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def to_micro(value: Number, *, places: int = 6) -> int:
|
|
26
|
+
"""Convert a panel money value to integer micro-units.
|
|
27
|
+
|
|
28
|
+
Accepts the decimal strings panels actually send (``"0.5050"``), plus
|
|
29
|
+
ints, floats and :class:`~decimal.Decimal`. Rounds half-up to six decimal
|
|
30
|
+
places rather than truncating, so ``0.1234565`` becomes ``123457``.
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
ValueError: if the value is not a finite number.
|
|
34
|
+
"""
|
|
35
|
+
if isinstance(value, bool): # bool is an int subclass; never money
|
|
36
|
+
raise ValueError("money value must be numeric, got bool")
|
|
37
|
+
try:
|
|
38
|
+
amount = Decimal(str(value).strip())
|
|
39
|
+
except (InvalidOperation, AttributeError, ValueError) as exc:
|
|
40
|
+
raise ValueError(f"money value is not numeric: {value!r}") from exc
|
|
41
|
+
if not amount.is_finite():
|
|
42
|
+
raise ValueError(f"money value is not finite: {value!r}")
|
|
43
|
+
scaled = amount * MICRO
|
|
44
|
+
quantized = scaled.quantize(Decimal(1), rounding=ROUND_HALF_UP)
|
|
45
|
+
if places != 6: # pragma: no cover - kept for callers that pre-round
|
|
46
|
+
step = Decimal(10) ** (6 - places)
|
|
47
|
+
quantized = (quantized / step).quantize(Decimal(1), rounding=ROUND_HALF_UP) * step
|
|
48
|
+
return int(quantized)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def from_micro(micro: int, *, trim: bool = True) -> str:
|
|
52
|
+
"""Render integer micro-units back to a plain decimal string.
|
|
53
|
+
|
|
54
|
+
``125000`` becomes ``"0.125"``; with ``trim=False`` it keeps all six
|
|
55
|
+
places (``"0.125000"``), which is handy for CSV exports.
|
|
56
|
+
"""
|
|
57
|
+
if isinstance(micro, bool) or not isinstance(micro, int):
|
|
58
|
+
raise TypeError("micro must be an int")
|
|
59
|
+
sign = "-" if micro < 0 else ""
|
|
60
|
+
whole, frac = divmod(abs(micro), MICRO)
|
|
61
|
+
text = f"{sign}{whole}.{frac:06d}"
|
|
62
|
+
if trim:
|
|
63
|
+
text = text.rstrip("0").rstrip(".") if "." in text else text
|
|
64
|
+
return text
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, order=True)
|
|
68
|
+
class Money:
|
|
69
|
+
"""An exact amount of money, stored as integer micro-units.
|
|
70
|
+
|
|
71
|
+
``Money`` never holds a float. Two amounts are equal only when both the
|
|
72
|
+
number of micro-units and the currency match, and ``+``/``-`` refuse to
|
|
73
|
+
mix currencies instead of silently adding dollars to rubles.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
micro: int
|
|
77
|
+
currency: str = "USD"
|
|
78
|
+
|
|
79
|
+
def __post_init__(self) -> None:
|
|
80
|
+
if isinstance(self.micro, bool) or not isinstance(self.micro, int):
|
|
81
|
+
raise TypeError("micro must be an int; use Money.parse for strings")
|
|
82
|
+
object.__setattr__(self, "currency", (self.currency or "USD").upper())
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def parse(cls, value: Number, currency: str = "USD") -> "Money":
|
|
86
|
+
"""Build a :class:`Money` from any panel value (string, int, float)."""
|
|
87
|
+
return cls(micro=to_micro(value), currency=currency)
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def zero(cls, currency: str = "USD") -> "Money":
|
|
91
|
+
return cls(0, currency)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def amount(self) -> Decimal:
|
|
95
|
+
"""The exact amount as a :class:`~decimal.Decimal`."""
|
|
96
|
+
return Decimal(self.micro) / MICRO
|
|
97
|
+
|
|
98
|
+
def format(self, places: int = 2, *, trim: bool = False) -> str:
|
|
99
|
+
"""Format for display, e.g. ``"1.23"`` (banker-friendly 2 places)."""
|
|
100
|
+
if places < 0:
|
|
101
|
+
raise ValueError("places must be >= 0")
|
|
102
|
+
text = from_micro(self.micro, trim=trim)
|
|
103
|
+
if places == 6:
|
|
104
|
+
return text
|
|
105
|
+
quantized = self.amount.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
|
106
|
+
return f"{quantized:.{places}f}"
|
|
107
|
+
|
|
108
|
+
def _same_currency(self, other: "Money") -> None:
|
|
109
|
+
if not isinstance(other, Money):
|
|
110
|
+
raise TypeError(f"expected Money, got {type(other).__name__}")
|
|
111
|
+
if other.currency != self.currency:
|
|
112
|
+
raise ValueError(
|
|
113
|
+
f"currency mismatch: {self.currency} vs {other.currency}"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def __add__(self, other: "Money") -> "Money":
|
|
117
|
+
self._same_currency(other)
|
|
118
|
+
return Money(self.micro + other.micro, self.currency)
|
|
119
|
+
|
|
120
|
+
def __sub__(self, other: "Money") -> "Money":
|
|
121
|
+
self._same_currency(other)
|
|
122
|
+
return Money(self.micro - other.micro, self.currency)
|
|
123
|
+
|
|
124
|
+
def __neg__(self) -> "Money":
|
|
125
|
+
return Money(-self.micro, self.currency)
|
|
126
|
+
|
|
127
|
+
def __str__(self) -> str:
|
|
128
|
+
return f"{self.format(6, trim=True)} {self.currency}"
|
perfectpanel/client.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"""A small, typed client for the Perfect Panel **v2** HTTP API.
|
|
2
|
+
|
|
3
|
+
The panel API is one endpoint that takes ``key`` and ``action`` as form
|
|
4
|
+
fields. This module turns that into seven methods, typed results, and an
|
|
5
|
+
exception model you can reason about.
|
|
6
|
+
|
|
7
|
+
The API key is never logged, never included in exception messages, and is
|
|
8
|
+
redacted from ``repr()``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import random
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from .exceptions import (
|
|
22
|
+
APIError,
|
|
23
|
+
InvalidAPIKeyError,
|
|
24
|
+
OrderNotFoundError,
|
|
25
|
+
PerfectPanelError,
|
|
26
|
+
ResponseParseError,
|
|
27
|
+
TransportError,
|
|
28
|
+
UnknownActionError,
|
|
29
|
+
error_from_payload,
|
|
30
|
+
)
|
|
31
|
+
from .models import (
|
|
32
|
+
ActionAck,
|
|
33
|
+
Balance,
|
|
34
|
+
OrderPlaced,
|
|
35
|
+
OrderStatus,
|
|
36
|
+
Service,
|
|
37
|
+
parse_services,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__all__ = ["PerfectPanelClient"]
|
|
41
|
+
|
|
42
|
+
_LOG = logging.getLogger("perfectpanel")
|
|
43
|
+
|
|
44
|
+
DEFAULT_BASE_URL = "https://talonpanel.com/api/v2"
|
|
45
|
+
DEFAULT_USER_AGENT = "perfectpanel-client/0.1.0 (+https://github.com/w3radar/perfectpanel-client)"
|
|
46
|
+
ENV_KEY = "PERFECTPANEL_API_KEY"
|
|
47
|
+
|
|
48
|
+
#: Statuses worth retrying: rate limit plus the gateway/upstream family.
|
|
49
|
+
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class PerfectPanelClient:
|
|
53
|
+
"""Client for a Perfect Panel v2 endpoint.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
api_key: the panel key. Treat it like a password.
|
|
57
|
+
base_url: full URL of the v2 endpoint. Defaults to Talon's.
|
|
58
|
+
timeout: per-request timeout in seconds.
|
|
59
|
+
max_retries: extra attempts after the first one (0 disables retries).
|
|
60
|
+
backoff_factor: base delay in seconds; attempt *n* waits
|
|
61
|
+
``backoff_factor * 2 ** (n - 1)``, capped at ``max_backoff``.
|
|
62
|
+
max_backoff: upper bound for a single wait, in seconds.
|
|
63
|
+
jitter: fraction of the delay added as random jitter (0 disables it,
|
|
64
|
+
which is what the tests use).
|
|
65
|
+
user_agent: override for the ``User-Agent`` header.
|
|
66
|
+
transport: an ``httpx`` transport, e.g. ``httpx.MockTransport``.
|
|
67
|
+
headers: extra headers, merged over the defaults.
|
|
68
|
+
|
|
69
|
+
The client is safe to reuse across threads for independent calls; it owns
|
|
70
|
+
one ``httpx.Client``. Use it as a context manager to close that pool.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
api_key: str,
|
|
76
|
+
*,
|
|
77
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
78
|
+
timeout: float = 30.0,
|
|
79
|
+
max_retries: int = 3,
|
|
80
|
+
backoff_factor: float = 0.5,
|
|
81
|
+
max_backoff: float = 10.0,
|
|
82
|
+
jitter: float = 0.1,
|
|
83
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
84
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
85
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
86
|
+
) -> None:
|
|
87
|
+
if not isinstance(api_key, str) or not api_key.strip():
|
|
88
|
+
raise ValueError("api_key must be a non-empty string")
|
|
89
|
+
if max_retries < 0:
|
|
90
|
+
raise ValueError("max_retries must be >= 0")
|
|
91
|
+
if timeout <= 0:
|
|
92
|
+
raise ValueError("timeout must be > 0")
|
|
93
|
+
if not isinstance(base_url, str) or not base_url.strip():
|
|
94
|
+
raise ValueError("base_url must be a non-empty string")
|
|
95
|
+
|
|
96
|
+
self._api_key = api_key.strip()
|
|
97
|
+
self.base_url = base_url.strip().rstrip("/")
|
|
98
|
+
self.max_retries = int(max_retries)
|
|
99
|
+
self.backoff_factor = float(backoff_factor)
|
|
100
|
+
self.max_backoff = float(max_backoff)
|
|
101
|
+
self.jitter = min(max(float(jitter), 0.0), 1.0)
|
|
102
|
+
self._sleep = time.sleep
|
|
103
|
+
self._default_currency = "USD"
|
|
104
|
+
|
|
105
|
+
merged = {
|
|
106
|
+
"User-Agent": user_agent,
|
|
107
|
+
"Accept": "application/json",
|
|
108
|
+
}
|
|
109
|
+
if headers:
|
|
110
|
+
merged.update(headers)
|
|
111
|
+
self._http = httpx.Client(
|
|
112
|
+
timeout=timeout,
|
|
113
|
+
headers=merged,
|
|
114
|
+
transport=transport,
|
|
115
|
+
follow_redirects=True,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# ------------------------------------------------------------------ setup
|
|
119
|
+
@classmethod
|
|
120
|
+
def from_env(
|
|
121
|
+
cls, env_var: str = ENV_KEY, **kwargs: Any
|
|
122
|
+
) -> "PerfectPanelClient":
|
|
123
|
+
"""Build a client from ``PERFECTPANEL_API_KEY`` (or a custom variable)."""
|
|
124
|
+
key = os.environ.get(env_var, "").strip()
|
|
125
|
+
if not key:
|
|
126
|
+
raise ValueError(f"environment variable {env_var} is not set")
|
|
127
|
+
return cls(key, **kwargs)
|
|
128
|
+
|
|
129
|
+
def __repr__(self) -> str:
|
|
130
|
+
# The key is deliberately absent: this repr ends up in logs and tracebacks.
|
|
131
|
+
return f"<PerfectPanelClient base_url={self.base_url!r} key=***>"
|
|
132
|
+
|
|
133
|
+
def close(self) -> None:
|
|
134
|
+
"""Close the underlying HTTP connection pool."""
|
|
135
|
+
self._http.close()
|
|
136
|
+
|
|
137
|
+
def __enter__(self) -> "PerfectPanelClient":
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
def __exit__(self, *exc_info: Any) -> None:
|
|
141
|
+
self.close()
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------ money
|
|
144
|
+
@property
|
|
145
|
+
def currency(self) -> str:
|
|
146
|
+
"""Currency used when a response omits one. Defaults to ``"USD"``."""
|
|
147
|
+
return self._default_currency
|
|
148
|
+
|
|
149
|
+
@currency.setter
|
|
150
|
+
def currency(self, value: str) -> None:
|
|
151
|
+
self._default_currency = (value or "USD").upper()
|
|
152
|
+
|
|
153
|
+
# --------------------------------------------------------------- actions
|
|
154
|
+
def services(self) -> Tuple[Service, ...]:
|
|
155
|
+
"""``action=services`` — the whole catalogue, cheapest parse of prices."""
|
|
156
|
+
return parse_services(self._call("services"))
|
|
157
|
+
|
|
158
|
+
def add(
|
|
159
|
+
self,
|
|
160
|
+
service: Union[int, str],
|
|
161
|
+
link: str,
|
|
162
|
+
quantity: int,
|
|
163
|
+
*,
|
|
164
|
+
comments: Optional[Union[str, Sequence[str]]] = None,
|
|
165
|
+
runs: Optional[int] = None,
|
|
166
|
+
interval: Optional[int] = None,
|
|
167
|
+
) -> OrderPlaced:
|
|
168
|
+
"""``action=add`` — place an order.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
service: service id from :meth:`services`.
|
|
172
|
+
link: the target URL (or ``username`` for some services).
|
|
173
|
+
quantity: units to deliver; must be a positive integer.
|
|
174
|
+
comments: for comment services, one string or a sequence (joined
|
|
175
|
+
with newlines).
|
|
176
|
+
runs: drip-feed runs, if the service supports it.
|
|
177
|
+
interval: minutes between drip-feed runs.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
:class:`~perfectpanel.models.OrderPlaced` with the new order id,
|
|
181
|
+
the charged amount and the remaining balance — both exact.
|
|
182
|
+
"""
|
|
183
|
+
payload: Dict[str, Any] = {
|
|
184
|
+
"service": _positive_int(service, "service"),
|
|
185
|
+
"link": _non_empty_str(link, "link"),
|
|
186
|
+
"quantity": _positive_int(quantity, "quantity"),
|
|
187
|
+
}
|
|
188
|
+
if comments is not None:
|
|
189
|
+
if isinstance(comments, str):
|
|
190
|
+
payload["comments"] = comments
|
|
191
|
+
else:
|
|
192
|
+
payload["comments"] = "\n".join(str(c) for c in comments)
|
|
193
|
+
if runs is not None:
|
|
194
|
+
payload["runs"] = _positive_int(runs, "runs")
|
|
195
|
+
if interval is not None:
|
|
196
|
+
payload["interval"] = _positive_int(interval, "interval")
|
|
197
|
+
|
|
198
|
+
data = self._call("add", payload)
|
|
199
|
+
return OrderPlaced.from_payload(_require_mapping(data, "add"), self.currency)
|
|
200
|
+
|
|
201
|
+
def status(self, order: Union[int, str]) -> OrderStatus:
|
|
202
|
+
"""``action=status`` — state of one order."""
|
|
203
|
+
order_id = _positive_int(order, "order")
|
|
204
|
+
data = self._call("status", {"order": order_id})
|
|
205
|
+
return OrderStatus.from_payload(
|
|
206
|
+
_require_mapping(data, "status"),
|
|
207
|
+
order=order_id,
|
|
208
|
+
currency=self.currency,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def multi_status(
|
|
212
|
+
self, orders: Iterable[Union[int, str]], *, fallback: bool = True
|
|
213
|
+
) -> Tuple[OrderStatus, ...]:
|
|
214
|
+
"""``action=status`` with ``orders=1,2,3`` — several orders at once.
|
|
215
|
+
|
|
216
|
+
Perfect Panel's batch form sends the ids as a comma-separated string
|
|
217
|
+
and answers with an object keyed by order id. Panels that only
|
|
218
|
+
implement the single-order form are detected: with ``fallback=True``
|
|
219
|
+
the client quietly re-asks one order at a time, so the method works
|
|
220
|
+
against every v2 panel.
|
|
221
|
+
|
|
222
|
+
Raises:
|
|
223
|
+
ValueError: if the list is empty or contains a non-positive id.
|
|
224
|
+
APIError: for a per-order error the panel attached to a batch row.
|
|
225
|
+
"""
|
|
226
|
+
ids = [_positive_int(o, "order") for o in orders]
|
|
227
|
+
if not ids:
|
|
228
|
+
raise ValueError("orders must contain at least one id")
|
|
229
|
+
if len(set(ids)) != len(ids):
|
|
230
|
+
raise ValueError("orders contains duplicate ids")
|
|
231
|
+
|
|
232
|
+
try:
|
|
233
|
+
data = self._call("status", {"orders": ",".join(str(i) for i in ids)})
|
|
234
|
+
except (UnknownActionError, OrderNotFoundError):
|
|
235
|
+
# Panels that only implement the single-order form reject the
|
|
236
|
+
# comma-joined id (unknown action, or "no such order").
|
|
237
|
+
if not fallback:
|
|
238
|
+
raise
|
|
239
|
+
data = None
|
|
240
|
+
parsed = _parse_status_batch(data, ids, self.currency)
|
|
241
|
+
if parsed and len(parsed) == len(ids):
|
|
242
|
+
return parsed
|
|
243
|
+
if not fallback:
|
|
244
|
+
return parsed
|
|
245
|
+
_LOG.debug("batch status unsupported, falling back to %d single calls", len(ids))
|
|
246
|
+
return tuple(self.status(i) for i in ids)
|
|
247
|
+
|
|
248
|
+
def balance(self) -> Balance:
|
|
249
|
+
"""``action=balance`` — wallet snapshot."""
|
|
250
|
+
return Balance.from_payload(_require_mapping(self._call("balance"), "balance"))
|
|
251
|
+
|
|
252
|
+
def cancel(self, order: Union[int, str]) -> ActionAck:
|
|
253
|
+
"""``action=cancel`` — request a cancellation."""
|
|
254
|
+
order_id = _positive_int(order, "order")
|
|
255
|
+
data = _require_mapping(self._call("cancel", {"order": order_id}), "cancel")
|
|
256
|
+
return ActionAck.from_payload(data, action="cancel")
|
|
257
|
+
|
|
258
|
+
def refill(self, order: Union[int, str]) -> ActionAck:
|
|
259
|
+
"""``action=refill`` — request a refill for an eligible order."""
|
|
260
|
+
order_id = _positive_int(order, "order")
|
|
261
|
+
data = _require_mapping(self._call("refill", {"order": order_id}), "refill")
|
|
262
|
+
return ActionAck.from_payload(data, action="refill")
|
|
263
|
+
|
|
264
|
+
# ------------------------------------------------------------- utilities
|
|
265
|
+
def wait_for(
|
|
266
|
+
self,
|
|
267
|
+
order: Union[int, str],
|
|
268
|
+
*,
|
|
269
|
+
timeout: float = 300.0,
|
|
270
|
+
poll_interval: float = 5.0,
|
|
271
|
+
) -> OrderStatus:
|
|
272
|
+
"""Poll :meth:`status` until the order reaches a terminal state.
|
|
273
|
+
|
|
274
|
+
Useful right after :meth:`add`. Returns the last status seen, even on
|
|
275
|
+
timeout — inspect ``.terminal`` to know which happened. A timeout is
|
|
276
|
+
not an error: an order that is still ``In progress`` is not a failure.
|
|
277
|
+
"""
|
|
278
|
+
if timeout <= 0:
|
|
279
|
+
raise ValueError("timeout must be > 0")
|
|
280
|
+
if poll_interval < 0:
|
|
281
|
+
raise ValueError("poll_interval must be >= 0")
|
|
282
|
+
deadline = time.monotonic() + timeout
|
|
283
|
+
while True:
|
|
284
|
+
current = self.status(order)
|
|
285
|
+
if current.terminal:
|
|
286
|
+
return current
|
|
287
|
+
remaining = deadline - time.monotonic()
|
|
288
|
+
if remaining <= 0:
|
|
289
|
+
return current
|
|
290
|
+
self._sleep(min(poll_interval, remaining))
|
|
291
|
+
|
|
292
|
+
# ---------------------------------------------------------------- wiring
|
|
293
|
+
def _call(self, action: str, params: Optional[Mapping[str, Any]] = None) -> Any:
|
|
294
|
+
"""POST one ``action`` with retries and return parsed JSON."""
|
|
295
|
+
form: Dict[str, Any] = dict(params or {})
|
|
296
|
+
form["action"] = action
|
|
297
|
+
form["key"] = self._api_key
|
|
298
|
+
|
|
299
|
+
attempts = self.max_retries + 1
|
|
300
|
+
last_error: Optional[PerfectPanelError] = None
|
|
301
|
+
|
|
302
|
+
for attempt in range(1, attempts + 1):
|
|
303
|
+
_LOG.debug("action=%s attempt=%d/%d", action, attempt, attempts)
|
|
304
|
+
try:
|
|
305
|
+
response = self._http.post(self.base_url, data=form)
|
|
306
|
+
except httpx.TimeoutException as exc:
|
|
307
|
+
last_error = TransportError(
|
|
308
|
+
f"timeout calling action={action!r} after {attempt} attempt(s)",
|
|
309
|
+
action=action,
|
|
310
|
+
attempts=attempt,
|
|
311
|
+
cause=exc,
|
|
312
|
+
)
|
|
313
|
+
except httpx.HTTPError as exc:
|
|
314
|
+
last_error = TransportError(
|
|
315
|
+
f"network error calling action={action!r}: {type(exc).__name__}",
|
|
316
|
+
action=action,
|
|
317
|
+
attempts=attempt,
|
|
318
|
+
cause=exc,
|
|
319
|
+
)
|
|
320
|
+
else:
|
|
321
|
+
if response.status_code in RETRY_STATUSES and attempt < attempts:
|
|
322
|
+
self._sleep(self._delay_for(attempt, response))
|
|
323
|
+
continue
|
|
324
|
+
return self._decode(response, action)
|
|
325
|
+
|
|
326
|
+
if attempt < attempts:
|
|
327
|
+
self._sleep(self._backoff(attempt))
|
|
328
|
+
|
|
329
|
+
assert last_error is not None # the loop always sets one
|
|
330
|
+
raise last_error
|
|
331
|
+
|
|
332
|
+
def _delay_for(self, attempt: int, response: httpx.Response) -> float:
|
|
333
|
+
"""Honour ``Retry-After`` when the panel sends one, else back off."""
|
|
334
|
+
header = response.headers.get("Retry-After", "").strip()
|
|
335
|
+
if header:
|
|
336
|
+
try:
|
|
337
|
+
return min(max(float(header), 0.0), self.max_backoff)
|
|
338
|
+
except ValueError:
|
|
339
|
+
pass # an HTTP-date; fall through to exponential backoff
|
|
340
|
+
return self._backoff(attempt)
|
|
341
|
+
|
|
342
|
+
def _backoff(self, attempt: int) -> float:
|
|
343
|
+
delay = min(self.backoff_factor * (2 ** (attempt - 1)), self.max_backoff)
|
|
344
|
+
if self.jitter:
|
|
345
|
+
delay += delay * self.jitter * random.random()
|
|
346
|
+
return max(delay, 0.0)
|
|
347
|
+
|
|
348
|
+
def _decode(self, response: httpx.Response, action: str) -> Any:
|
|
349
|
+
"""Turn an HTTP response into data or the right exception."""
|
|
350
|
+
text = response.text or ""
|
|
351
|
+
try:
|
|
352
|
+
payload = response.json()
|
|
353
|
+
except ValueError:
|
|
354
|
+
payload = None
|
|
355
|
+
|
|
356
|
+
if response.status_code == 401:
|
|
357
|
+
if isinstance(payload, Mapping):
|
|
358
|
+
raise error_from_payload(payload, status_code=401, action=action)
|
|
359
|
+
raise InvalidAPIKeyError(
|
|
360
|
+
"the panel rejected the key (HTTP 401)",
|
|
361
|
+
error_code="API_KEY_INVALID",
|
|
362
|
+
status_code=401,
|
|
363
|
+
action=action,
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
if isinstance(payload, Mapping) and ("error" in payload or "error_code" in payload):
|
|
367
|
+
# Perfect Panel answers rejected actions with 200 + error_code.
|
|
368
|
+
raise error_from_payload(payload, status_code=response.status_code, action=action)
|
|
369
|
+
|
|
370
|
+
if payload is None:
|
|
371
|
+
if response.status_code >= 400:
|
|
372
|
+
raise APIError(
|
|
373
|
+
f"HTTP {response.status_code} from action={action!r}",
|
|
374
|
+
status_code=response.status_code,
|
|
375
|
+
action=action,
|
|
376
|
+
)
|
|
377
|
+
raise ResponseParseError(
|
|
378
|
+
f"action={action!r} returned a non-JSON body",
|
|
379
|
+
status_code=response.status_code,
|
|
380
|
+
body_preview=text[:200],
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
if response.status_code >= 400:
|
|
384
|
+
raise APIError(
|
|
385
|
+
f"HTTP {response.status_code} from action={action!r}",
|
|
386
|
+
status_code=response.status_code,
|
|
387
|
+
action=action,
|
|
388
|
+
)
|
|
389
|
+
return payload
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ----------------------------------------------------------------- helpers
|
|
393
|
+
def _positive_int(value: Any, name: str) -> int:
|
|
394
|
+
if isinstance(value, bool):
|
|
395
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
396
|
+
try:
|
|
397
|
+
number = int(value)
|
|
398
|
+
except (TypeError, ValueError) as exc:
|
|
399
|
+
raise ValueError(f"{name} must be a positive integer") from exc
|
|
400
|
+
if number <= 0:
|
|
401
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
402
|
+
return number
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _non_empty_str(value: Any, name: str) -> str:
|
|
406
|
+
if not isinstance(value, str) or not value.strip():
|
|
407
|
+
raise ValueError(f"{name} must be a non-empty string")
|
|
408
|
+
return value.strip()
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _require_mapping(payload: Any, action: str) -> Mapping[str, Any]:
|
|
412
|
+
if not isinstance(payload, Mapping):
|
|
413
|
+
raise ResponseParseError(f"action={action!r} did not return a JSON object")
|
|
414
|
+
return payload
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _parse_status_batch(
|
|
418
|
+
payload: Any, ids: Sequence[int], currency: str
|
|
419
|
+
) -> Tuple[OrderStatus, ...]:
|
|
420
|
+
"""Normalise both known batch shapes: object-keyed-by-id and list."""
|
|
421
|
+
rows: Tuple[Tuple[int, Mapping[str, Any]], ...] = ()
|
|
422
|
+
|
|
423
|
+
if isinstance(payload, Mapping):
|
|
424
|
+
pairs = []
|
|
425
|
+
for key, value in payload.items():
|
|
426
|
+
if not isinstance(value, Mapping):
|
|
427
|
+
continue
|
|
428
|
+
if "error" in value or "error_code" in value:
|
|
429
|
+
raise error_from_payload(value, action="status")
|
|
430
|
+
try:
|
|
431
|
+
order_id = int(key)
|
|
432
|
+
except (TypeError, ValueError):
|
|
433
|
+
order_id = 0
|
|
434
|
+
pairs.append((order_id, value))
|
|
435
|
+
rows = tuple(pairs)
|
|
436
|
+
elif isinstance(payload, (list, tuple)):
|
|
437
|
+
pairs = []
|
|
438
|
+
for index, value in enumerate(payload):
|
|
439
|
+
if not isinstance(value, Mapping):
|
|
440
|
+
continue
|
|
441
|
+
if "error" in value or "error_code" in value:
|
|
442
|
+
raise error_from_payload(value, action="status")
|
|
443
|
+
fallback_id = ids[index] if index < len(ids) else 0
|
|
444
|
+
pairs.append((fallback_id, value))
|
|
445
|
+
rows = tuple(pairs)
|
|
446
|
+
|
|
447
|
+
statuses = []
|
|
448
|
+
for order_id, row in rows:
|
|
449
|
+
statuses.append(
|
|
450
|
+
OrderStatus.from_payload(row, order=order_id, currency=currency)
|
|
451
|
+
)
|
|
452
|
+
return tuple(statuses)
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Exception model.
|
|
2
|
+
|
|
3
|
+
Everything raised by this client inherits from :class:`PerfectPanelError`, so
|
|
4
|
+
one ``except`` clause is enough to make an integration crash-safe.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Mapping, Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PerfectPanelError(Exception):
|
|
13
|
+
"""Base class for every error raised by this package."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TransportError(PerfectPanelError):
|
|
17
|
+
"""The request never produced a usable answer (DNS, timeout, socket).
|
|
18
|
+
|
|
19
|
+
Raised only after the configured retries are exhausted.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
message: str,
|
|
25
|
+
*,
|
|
26
|
+
action: Optional[str] = None,
|
|
27
|
+
attempts: int = 0,
|
|
28
|
+
cause: Optional[BaseException] = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.message = message
|
|
32
|
+
self.action = action
|
|
33
|
+
self.attempts = attempts
|
|
34
|
+
self.cause = cause
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ResponseParseError(PerfectPanelError):
|
|
38
|
+
"""The panel answered with something that is not JSON (an HTML error page,
|
|
39
|
+
a proxy banner, a truncated body)."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
message: str,
|
|
44
|
+
*,
|
|
45
|
+
status_code: Optional[int] = None,
|
|
46
|
+
body_preview: str = "",
|
|
47
|
+
) -> None:
|
|
48
|
+
super().__init__(message)
|
|
49
|
+
self.status_code = status_code
|
|
50
|
+
self.body_preview = body_preview
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class APIError(PerfectPanelError):
|
|
54
|
+
"""The panel understood the request and refused it.
|
|
55
|
+
|
|
56
|
+
Perfect Panel answers *rejected actions* with HTTP 200 and an
|
|
57
|
+
``error_code`` for compatibility with reseller panels, so **check the
|
|
58
|
+
exception type, not the status code**. ``error_code`` is the stable
|
|
59
|
+
contract; ``message`` is the panel's human text and may change wording.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
error_code: Optional[str] = None
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
message: str,
|
|
67
|
+
*,
|
|
68
|
+
error_code: Optional[str] = None,
|
|
69
|
+
status_code: Optional[int] = None,
|
|
70
|
+
action: Optional[str] = None,
|
|
71
|
+
payload: Optional[Mapping[str, Any]] = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
super().__init__(message)
|
|
74
|
+
self.message = message
|
|
75
|
+
self.error_code = error_code
|
|
76
|
+
self.status_code = status_code
|
|
77
|
+
self.action = action
|
|
78
|
+
self.payload = dict(payload or {})
|
|
79
|
+
|
|
80
|
+
def __str__(self) -> str:
|
|
81
|
+
prefix = f"[{self.error_code}] " if self.error_code else ""
|
|
82
|
+
return f"{prefix}{self.message}"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class InvalidAPIKeyError(APIError):
|
|
86
|
+
"""The key is wrong, expired or lacks credit (HTTP 401 / ``API_KEY_INVALID``)."""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class ServiceNotFoundError(APIError):
|
|
90
|
+
"""``service`` does not exist in the catalogue (``SERVICE_NOT_FOUND``)."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class OrderRejectedError(APIError):
|
|
94
|
+
"""The panel refused the order, e.g. bad link, quantity out of range,
|
|
95
|
+
or not enough balance (``ORDER_REJECTED``)."""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class OrderNotFoundError(APIError):
|
|
99
|
+
"""No order with that id on this account (``ORDER_NOT_FOUND``)."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class CancelRejectedError(APIError):
|
|
103
|
+
"""The order exists but can no longer be cancelled (``CANCEL_REJECTED``)."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class RefillRejectedError(APIError):
|
|
107
|
+
"""The order is not eligible for a refill (``REFILL_REJECTED``)."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class UnknownActionError(APIError):
|
|
111
|
+
"""The panel does not implement that ``action`` (``ACTION_UNKNOWN``)."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
_ERROR_CODES = {
|
|
115
|
+
"API_KEY_INVALID": InvalidAPIKeyError,
|
|
116
|
+
"SERVICE_NOT_FOUND": ServiceNotFoundError,
|
|
117
|
+
"ORDER_REJECTED": OrderRejectedError,
|
|
118
|
+
"ORDER_NOT_FOUND": OrderNotFoundError,
|
|
119
|
+
"CANCEL_REJECTED": CancelRejectedError,
|
|
120
|
+
"REFILL_REJECTED": RefillRejectedError,
|
|
121
|
+
"ACTION_UNKNOWN": UnknownActionError,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def exception_for_code(code: Optional[str]) -> type:
|
|
126
|
+
"""Return the exception class for a panel ``error_code``.
|
|
127
|
+
|
|
128
|
+
Unknown codes fall back to :class:`APIError`, so a new server-side code
|
|
129
|
+
never crashes a caller that already handles the base class.
|
|
130
|
+
"""
|
|
131
|
+
if not code:
|
|
132
|
+
return APIError
|
|
133
|
+
return _ERROR_CODES.get(code.strip().upper(), APIError)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def error_from_payload(
|
|
137
|
+
payload: Mapping[str, Any],
|
|
138
|
+
*,
|
|
139
|
+
status_code: Optional[int] = None,
|
|
140
|
+
action: Optional[str] = None,
|
|
141
|
+
) -> APIError:
|
|
142
|
+
"""Build the right :class:`APIError` subclass from a panel error body."""
|
|
143
|
+
code = payload.get("error_code") or payload.get("errorCode") or payload.get("code")
|
|
144
|
+
message = (
|
|
145
|
+
payload.get("error")
|
|
146
|
+
or payload.get("message")
|
|
147
|
+
or payload.get("error_message")
|
|
148
|
+
or "the panel rejected the request"
|
|
149
|
+
)
|
|
150
|
+
cls = exception_for_code(code if isinstance(code, str) else None)
|
|
151
|
+
if cls is APIError and status_code == 401:
|
|
152
|
+
cls = InvalidAPIKeyError
|
|
153
|
+
return cls(
|
|
154
|
+
str(message),
|
|
155
|
+
error_code=str(code) if code is not None else None,
|
|
156
|
+
status_code=status_code,
|
|
157
|
+
action=action,
|
|
158
|
+
payload=payload,
|
|
159
|
+
)
|
perfectpanel/models.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Typed responses.
|
|
2
|
+
|
|
3
|
+
Every panel payload is parsed into an immutable dataclass. Unknown extra
|
|
4
|
+
fields are kept in ``.raw`` instead of being dropped, so an integration is
|
|
5
|
+
never broken by a panel that adds a column.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any, Mapping, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
from ._money import Money
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _as_int(value: Any, default: int = 0) -> int:
|
|
17
|
+
"""Panel ints sometimes arrive as ``"1000"`` or ``"1000.0"``."""
|
|
18
|
+
if value is None or value == "":
|
|
19
|
+
return default
|
|
20
|
+
try:
|
|
21
|
+
return int(float(str(value).strip()))
|
|
22
|
+
except (TypeError, ValueError):
|
|
23
|
+
return default
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _as_bool(value: Any) -> bool:
|
|
27
|
+
if isinstance(value, bool):
|
|
28
|
+
return value
|
|
29
|
+
if isinstance(value, (int, float)):
|
|
30
|
+
# ``{ok: <order id>}`` is a truthful ack; 0 is not.
|
|
31
|
+
return value != 0
|
|
32
|
+
return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _as_str(value: Any, default: str = "") -> str:
|
|
36
|
+
return default if value is None else str(value)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _as_money(value: Any, currency: str = "USD") -> Optional[Money]:
|
|
40
|
+
if value is None or value == "":
|
|
41
|
+
return None
|
|
42
|
+
try:
|
|
43
|
+
return Money.parse(value, currency)
|
|
44
|
+
except ValueError:
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Service:
|
|
50
|
+
"""One row of the catalogue.
|
|
51
|
+
|
|
52
|
+
``rate`` is the price per 1000 units and is kept exact as
|
|
53
|
+
:class:`~perfectpanel._money.Money`.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
service: int
|
|
57
|
+
name: str
|
|
58
|
+
type: str
|
|
59
|
+
category: str
|
|
60
|
+
rate: Optional[Money]
|
|
61
|
+
min: int
|
|
62
|
+
max: int
|
|
63
|
+
refill: bool
|
|
64
|
+
cancel: bool
|
|
65
|
+
dripfeed: bool = False
|
|
66
|
+
raw: Mapping[str, Any] = field(default_factory=dict, repr=False)
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_payload(cls, payload: Mapping[str, Any]) -> "Service":
|
|
70
|
+
return cls(
|
|
71
|
+
service=_as_int(payload.get("service")),
|
|
72
|
+
name=_as_str(payload.get("name")),
|
|
73
|
+
type=_as_str(payload.get("type")),
|
|
74
|
+
category=_as_str(payload.get("category")),
|
|
75
|
+
rate=_as_money(payload.get("rate")),
|
|
76
|
+
min=_as_int(payload.get("min")),
|
|
77
|
+
max=_as_int(payload.get("max")),
|
|
78
|
+
refill=_as_bool(payload.get("refill")),
|
|
79
|
+
cancel=_as_bool(payload.get("cancel")),
|
|
80
|
+
dripfeed=_as_bool(payload.get("dripfeed")),
|
|
81
|
+
raw=dict(payload),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def price_for(self, quantity: int) -> Optional[Money]:
|
|
85
|
+
"""Exact cost of ``quantity`` units at this rate (``rate / 1000``)."""
|
|
86
|
+
if quantity < 0:
|
|
87
|
+
raise ValueError("quantity must be >= 0")
|
|
88
|
+
if self.rate is None:
|
|
89
|
+
return None
|
|
90
|
+
currency = self.rate.currency
|
|
91
|
+
return Money((self.rate.micro * quantity) // 1000, currency)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class OrderPlaced:
|
|
96
|
+
"""Result of :meth:`~perfectpanel.PerfectPanelClient.add`."""
|
|
97
|
+
|
|
98
|
+
order: int
|
|
99
|
+
charge: Optional[Money]
|
|
100
|
+
balance: Optional[Money]
|
|
101
|
+
raw: Mapping[str, Any] = field(default_factory=dict, repr=False)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def from_payload(cls, payload: Mapping[str, Any], currency: str = "USD") -> "OrderPlaced":
|
|
105
|
+
return cls(
|
|
106
|
+
order=_as_int(payload.get("order")),
|
|
107
|
+
charge=_as_money(payload.get("charge"), currency),
|
|
108
|
+
balance=_as_money(payload.get("balance"), currency),
|
|
109
|
+
raw=dict(payload),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True)
|
|
114
|
+
class OrderStatus:
|
|
115
|
+
"""State of one order. ``status`` is the panel's own string
|
|
116
|
+
(``Pending``, ``In progress``, ``Completed``, ``Partial``, ``Canceled``)."""
|
|
117
|
+
|
|
118
|
+
order: int
|
|
119
|
+
status: str
|
|
120
|
+
charge: Optional[Money]
|
|
121
|
+
start_count: int
|
|
122
|
+
remains: int
|
|
123
|
+
currency: str = "USD"
|
|
124
|
+
raw: Mapping[str, Any] = field(default_factory=dict, repr=False)
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def from_payload(
|
|
128
|
+
cls,
|
|
129
|
+
payload: Mapping[str, Any],
|
|
130
|
+
*,
|
|
131
|
+
order: Optional[int] = None,
|
|
132
|
+
currency: str = "USD",
|
|
133
|
+
) -> "OrderStatus":
|
|
134
|
+
return cls(
|
|
135
|
+
order=_as_int(payload.get("order"), order or 0),
|
|
136
|
+
status=_as_str(payload.get("status")),
|
|
137
|
+
charge=_as_money(payload.get("charge"), _as_str(payload.get("currency"), currency)),
|
|
138
|
+
start_count=_as_int(payload.get("start_count")),
|
|
139
|
+
remains=_as_int(payload.get("remains")),
|
|
140
|
+
currency=_as_str(payload.get("currency"), currency).upper(),
|
|
141
|
+
raw=dict(payload),
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def completed(self) -> bool:
|
|
146
|
+
return self.status.strip().lower() == "completed"
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def canceled(self) -> bool:
|
|
150
|
+
return self.status.strip().lower() in {"canceled", "cancelled"}
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def terminal(self) -> bool:
|
|
154
|
+
"""True when no further change is expected (completed, partial, canceled)."""
|
|
155
|
+
return self.status.strip().lower() in {
|
|
156
|
+
"completed",
|
|
157
|
+
"partial",
|
|
158
|
+
"canceled",
|
|
159
|
+
"cancelled",
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass(frozen=True)
|
|
164
|
+
class Balance:
|
|
165
|
+
"""Wallet snapshot: ``{(balance, currency)}``."""
|
|
166
|
+
|
|
167
|
+
balance: Optional[Money]
|
|
168
|
+
currency: str = "USD"
|
|
169
|
+
raw: Mapping[str, Any] = field(default_factory=dict, repr=False)
|
|
170
|
+
|
|
171
|
+
@classmethod
|
|
172
|
+
def from_payload(cls, payload: Mapping[str, Any]) -> "Balance":
|
|
173
|
+
currency = _as_str(payload.get("currency"), "USD").upper() or "USD"
|
|
174
|
+
return cls(
|
|
175
|
+
balance=_as_money(payload.get("balance"), currency),
|
|
176
|
+
currency=currency,
|
|
177
|
+
raw=dict(payload),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True)
|
|
182
|
+
class ActionAck:
|
|
183
|
+
"""Acknowledgement of ``cancel`` or ``refill``: ``{ok, order}``."""
|
|
184
|
+
|
|
185
|
+
ok: bool
|
|
186
|
+
order: int
|
|
187
|
+
action: str = ""
|
|
188
|
+
raw: Mapping[str, Any] = field(default_factory=dict, repr=False)
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def from_payload(cls, payload: Mapping[str, Any], *, action: str = "") -> "ActionAck":
|
|
192
|
+
ok = payload.get("ok")
|
|
193
|
+
return cls(
|
|
194
|
+
ok=True if ok is None else _as_bool(ok),
|
|
195
|
+
order=_as_int(payload.get("order")),
|
|
196
|
+
action=action,
|
|
197
|
+
raw=dict(payload),
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def parse_services(payload: Any) -> Tuple[Service, ...]:
|
|
202
|
+
"""Parse a ``services`` answer (array, or ``{"services": [...]}``)."""
|
|
203
|
+
rows = payload
|
|
204
|
+
if isinstance(payload, Mapping):
|
|
205
|
+
rows = payload.get("services") or payload.get("data") or []
|
|
206
|
+
if not isinstance(rows, (list, tuple)):
|
|
207
|
+
return ()
|
|
208
|
+
return tuple(Service.from_payload(row) for row in rows if isinstance(row, Mapping))
|
perfectpanel/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: perfectpanel-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed, dependency-light Python client for the Perfect Panel v2 SMM API
|
|
5
|
+
Author: w3radar
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/w3radar/perfectpanel-client
|
|
8
|
+
Project-URL: Documentation, https://github.com/w3radar/perfectpanel-client#readme
|
|
9
|
+
Project-URL: Panel API docs, https://talonpanel.com/api-docs
|
|
10
|
+
Project-URL: Issues, https://github.com/w3radar/perfectpanel-client/issues
|
|
11
|
+
Keywords: smm,api-client,perfect-panel,panel,httpx
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: httpx>=0.24
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
25
|
+
Requires-Dist: pytest-cov>=4; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# perfectpanel-client
|
|
29
|
+
|
|
30
|
+
Typed, dependency-light Python client for the **Perfect Panel v2** SMM API — the
|
|
31
|
+
same `POST /api/v2` + `action=` shape that most SMM panels speak.
|
|
32
|
+
|
|
33
|
+
[](https://github.com/w3radar/perfectpanel-client/actions/workflows/tests.yml)
|
|
34
|
+
[](https://github.com/w3radar/perfectpanel-client)
|
|
35
|
+
[](LICENSE)
|
|
36
|
+
|
|
37
|
+
- Seven methods, typed results, one exception base class.
|
|
38
|
+
- Money is **never a float**: exact integer micro-units, like the panel's own
|
|
39
|
+
`cheapest_micro`.
|
|
40
|
+
- Retries with exponential backoff and `Retry-After` support.
|
|
41
|
+
- The API key is never logged and is redacted from `repr()`.
|
|
42
|
+
- 150+ tests, 100% line and branch coverage, no network in CI.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install "git+https://github.com/w3radar/perfectpanel-client.git"
|
|
48
|
+
# or, during development:
|
|
49
|
+
pip install -e ".[dev]"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Requires Python 3.9+. The only runtime dependency is `httpx`.
|
|
53
|
+
|
|
54
|
+
## 60-second quickstart
|
|
55
|
+
|
|
56
|
+
Every panel publishes a sandbox key so you can integrate before spending
|
|
57
|
+
anything. It reads the real catalogue and writes nothing:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from perfectpanel import PerfectPanelClient
|
|
61
|
+
|
|
62
|
+
with PerfectPanelClient("sandbox") as panel:
|
|
63
|
+
for service in panel.services()[:3]:
|
|
64
|
+
print(service.service, service.name, service.rate, service.min, service.max)
|
|
65
|
+
|
|
66
|
+
order = panel.add(service_id, "https://instagram.com/p/example", 1000)
|
|
67
|
+
print(order.order, order.charge, order.balance) # exact Money, not floats
|
|
68
|
+
|
|
69
|
+
print(panel.status(order.order).status) # "Pending" / "In progress" / "Completed"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Swap `"sandbox"` for your live key when you are ready — or keep it out of the
|
|
73
|
+
code entirely:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
export PERFECTPANEL_API_KEY="…"
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
panel = PerfectPanelClient.from_env()
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Waiting for delivery
|
|
84
|
+
|
|
85
|
+
`add` returns immediately. `wait_for` polls until the order reaches a terminal
|
|
86
|
+
state (`Completed`, `Partial`, `Canceled`) and returns the last status even on
|
|
87
|
+
timeout — an order still in progress is not an error:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
final = panel.wait_for(order.order, timeout=600, poll_interval=10)
|
|
91
|
+
if not final.completed:
|
|
92
|
+
print("still running or partial:", final.status, final.remains)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Several orders at once
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
for s in panel.multi_status([101, 102, 103]):
|
|
99
|
+
print(s.order, s.status, s.remains)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The panel's batch form takes `orders=101,102,103`. Panels that only implement
|
|
103
|
+
single-order status are detected automatically and asked one by one, so the
|
|
104
|
+
same call works everywhere.
|
|
105
|
+
|
|
106
|
+
## Endpoints
|
|
107
|
+
|
|
108
|
+
One URL, one form body, `action` selects the operation.
|
|
109
|
+
|
|
110
|
+
| Method | `action` | Parameters | Returns |
|
|
111
|
+
| --- | --- | --- | --- |
|
|
112
|
+
| `services()` | `services` | — | `tuple[Service, ...]` |
|
|
113
|
+
| `add(service, link, quantity, …)` | `add` | `service`, `link`, `quantity`, optional `comments`, `runs`, `interval` | `OrderPlaced(order, charge, balance)` |
|
|
114
|
+
| `status(order)` | `status` | `order` | `OrderStatus` |
|
|
115
|
+
| `multi_status([ids])` | `status` | `orders` (comma-joined) | `tuple[OrderStatus, ...]` |
|
|
116
|
+
| `balance()` | `balance` | — | `Balance(balance, currency)` |
|
|
117
|
+
| `cancel(order)` | `cancel` | `order` | `ActionAck(ok, order)` |
|
|
118
|
+
| `refill(order)` | `refill` | `order` | `ActionAck(ok, order)` |
|
|
119
|
+
|
|
120
|
+
Responses are parsed into frozen dataclasses. Fields a panel adds later are
|
|
121
|
+
kept in `.raw` instead of breaking your integration.
|
|
122
|
+
|
|
123
|
+
## Error model
|
|
124
|
+
|
|
125
|
+
Every failure inherits from `PerfectPanelError`, so one `except` is enough:
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from perfectpanel import PerfectPanelError
|
|
129
|
+
try:
|
|
130
|
+
panel.add(12, "https://instagram.com/p/x", 1000)
|
|
131
|
+
except PerfectPanelError as exc:
|
|
132
|
+
print(type(exc).__name__, getattr(exc, "error_code", None))
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
| Exception | When |
|
|
136
|
+
| --- | --- |
|
|
137
|
+
| `InvalidAPIKeyError` | HTTP 401 / `API_KEY_INVALID` |
|
|
138
|
+
| `ServiceNotFoundError` | `SERVICE_NOT_FOUND` |
|
|
139
|
+
| `OrderRejectedError` | `ORDER_REJECTED` — bad link, quantity out of range, no balance |
|
|
140
|
+
| `OrderNotFoundError` | `ORDER_NOT_FOUND` |
|
|
141
|
+
| `CancelRejectedError` | `CANCEL_REJECTED` — too late to cancel |
|
|
142
|
+
| `RefillRejectedError` | `REFILL_REJECTED` |
|
|
143
|
+
| `UnknownActionError` | `ACTION_UNKNOWN` — panel does not implement that action |
|
|
144
|
+
| `TransportError` | DNS, connection or timeout, after all retries |
|
|
145
|
+
| `ResponseParseError` | the answer was not JSON (proxy or HTML error page) |
|
|
146
|
+
|
|
147
|
+
The important detail: **a rejected action comes back as HTTP 200** with an
|
|
148
|
+
`error_code`, for compatibility with older reseller panels. Catch the exception
|
|
149
|
+
type, not the status code. `error_code` is the stable contract; the human
|
|
150
|
+
`message` may be reworded by any panel.
|
|
151
|
+
|
|
152
|
+
## Money
|
|
153
|
+
|
|
154
|
+
Panel charges arrive as decimal strings (`"0.6327"`). Summing floats over
|
|
155
|
+
thousands of orders drifts by fractions of a cent, so every amount is stored as
|
|
156
|
+
an `int` number of micro-units (`1_000_000 = 1.00 USD`, the same unit the panel's
|
|
157
|
+
public price API uses for `cheapest_micro`):
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from perfectpanel import Money, to_micro, from_micro
|
|
161
|
+
|
|
162
|
+
Money.parse("0.6327").micro # 632700
|
|
163
|
+
Money.parse("0.1") + Money.parse("0.2") == Money.parse("0.3") # True, exactly
|
|
164
|
+
str(Money.parse("1.5")) # "1.5 USD"
|
|
165
|
+
to_micro("0.0000005") # 1 (half-up, never truncated)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`Money + Money` refuses to mix currencies instead of adding dollars to rubles.
|
|
169
|
+
|
|
170
|
+
## Retries
|
|
171
|
+
|
|
172
|
+
`max_retries=3` by default, on timeouts, connection errors, `429`, `500`,
|
|
173
|
+
`502`, `503` and `504`. Backoff is `backoff_factor * 2 ** (n - 1)` with jitter,
|
|
174
|
+
capped by `max_backoff`, and `Retry-After` wins when the panel sends it. Input
|
|
175
|
+
is validated before any request is made, so a bad `quantity` costs zero calls.
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
panel = PerfectPanelClient(key, timeout=20, max_retries=5, backoff_factor=0.4)
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## What a panel API is, honestly
|
|
182
|
+
|
|
183
|
+
An SMM panel resells social-media services — followers, views, likes — placed
|
|
184
|
+
against a link or username. The v2 API is a thin order desk: list the catalogue,
|
|
185
|
+
place an order with your prepaid balance, poll its status, occasionally cancel
|
|
186
|
+
or refill. It is not a social-network API and it cannot guarantee that a
|
|
187
|
+
platform will keep the numbers; it can only tell you what was ordered and what
|
|
188
|
+
the panel says it delivered. That is exactly why this client returns the
|
|
189
|
+
panel's raw status strings unchanged, keeps your balance exact to the micro-unit,
|
|
190
|
+
and never pretends a `Partial` is a `Completed`.
|
|
191
|
+
|
|
192
|
+
## Who publishes this and why
|
|
193
|
+
|
|
194
|
+
Built and maintained by the team behind [Talon](https://talonpanel.com) — a
|
|
195
|
+
panel that publishes its prices and its methodology instead of hiding them.
|
|
196
|
+
|
|
197
|
+
- The API contract this client implements: <https://talonpanel.com/api-docs>
|
|
198
|
+
- How Talon measures itself against other panels: <https://talonpanel.com/compare/>
|
|
199
|
+
|
|
200
|
+
The client is deliberately panel-agnostic: it speaks the shared v2 shape, so it
|
|
201
|
+
works against any panel that follows it. Talon is only the default URL.
|
|
202
|
+
|
|
203
|
+
## Development
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
python -m venv .venv && . .venv/bin/activate
|
|
207
|
+
pip install -e ".[dev]"
|
|
208
|
+
pytest # 100% coverage, no network
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
The tests inject an `httpx.MockTransport`, so nothing touches the network and
|
|
212
|
+
no key is required.
|
|
213
|
+
|
|
214
|
+
## License
|
|
215
|
+
|
|
216
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
perfectpanel/__init__.py,sha256=QWMPKpS5qmlihaDR5PQsjv6ewrFjFdj4MhTDNO7J5hQ,1578
|
|
2
|
+
perfectpanel/_money.py,sha256=Cwu4UOV3Ecu2O3uL_tlN0VnXkOljn933eNjOrNY--8E,4953
|
|
3
|
+
perfectpanel/client.py,sha256=54C_gHfeelJ67vK-Z0M0fUGPa861hvtpvqV1TVhhnfc,17336
|
|
4
|
+
perfectpanel/exceptions.py,sha256=Ohy3zpC6UlvXOeWX81WHmWjlZ4hW-mRtTR_WBkKiCF8,4734
|
|
5
|
+
perfectpanel/models.py,sha256=B345Rqo0PWc03zJ0sZ82xwx9AjqRmid8NIDcNcbZLWk,6402
|
|
6
|
+
perfectpanel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
perfectpanel_client-0.1.0.dist-info/licenses/LICENSE,sha256=CmepCSvTkqi3Vqcv0LdZPvz6x3ZwngrC0iWNA1TPZ6o,1064
|
|
8
|
+
perfectpanel_client-0.1.0.dist-info/METADATA,sha256=oBSrg2BwlDFoJXlyg423mc49ihyM1tNB07SEcrOGRQc,8304
|
|
9
|
+
perfectpanel_client-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
+
perfectpanel_client-0.1.0.dist-info/top_level.txt,sha256=jdXYOcZsSGtPlW2vkjnOa2FA_1-1eywjSg_S-oLkfI4,13
|
|
11
|
+
perfectpanel_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 w3radar
|
|
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 @@
|
|
|
1
|
+
perfectpanel
|