pdfconversionapi 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.
- pdfconversionapi/__init__.py +80 -0
- pdfconversionapi/_async_client.py +290 -0
- pdfconversionapi/_base.py +134 -0
- pdfconversionapi/_client.py +315 -0
- pdfconversionapi/_core.py +593 -0
- pdfconversionapi/_exceptions.py +170 -0
- pdfconversionapi/_files.py +36 -0
- pdfconversionapi/_inputs.py +266 -0
- pdfconversionapi/_models.py +281 -0
- pdfconversionapi/_multipart.py +80 -0
- pdfconversionapi/_version.py +1 -0
- pdfconversionapi/py.typed +0 -0
- pdfconversionapi-0.1.0.dist-info/METADATA +410 -0
- pdfconversionapi-0.1.0.dist-info/RECORD +16 -0
- pdfconversionapi-0.1.0.dist-info/WHEEL +4 -0
- pdfconversionapi-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
"""What the sync and async clients share: settings, request building, retry decisions,
|
|
2
|
+
response parsing and error mapping. Nothing here does I/O on the network."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
import binascii
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import random
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
from decimal import Decimal
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, NamedTuple, Union
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from ._exceptions import (
|
|
26
|
+
ERRORS_BY_STATUS,
|
|
27
|
+
APIConnectionError,
|
|
28
|
+
ApiError,
|
|
29
|
+
APITimeoutError,
|
|
30
|
+
InvalidResponseError,
|
|
31
|
+
MissingApiKeyError,
|
|
32
|
+
)
|
|
33
|
+
from ._inputs import FileInput, UploadFile, own_name, to_upload, to_uploads
|
|
34
|
+
from ._models import Conversion, Usage
|
|
35
|
+
from ._multipart import FieldValue, MultipartBody
|
|
36
|
+
from ._version import __version__
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger("pdfconversionapi")
|
|
39
|
+
|
|
40
|
+
DEFAULT_BASE_URL = "https://api.pdfconversionapi.com"
|
|
41
|
+
DEFAULT_TIMEOUT = 240.0
|
|
42
|
+
DEFAULT_CONNECT_TIMEOUT = 10.0
|
|
43
|
+
DEFAULT_MAX_RETRIES = 4
|
|
44
|
+
DEFAULT_MAX_RETRY_WAIT = 60.0
|
|
45
|
+
|
|
46
|
+
KEY_ENV = "PDFCONVERSIONAPI_KEY"
|
|
47
|
+
BASE_URL_ENV = "PDFCONVERSIONAPI_BASE_URL"
|
|
48
|
+
|
|
49
|
+
USER_AGENT = f"pdfconversionapi-python/{__version__} python/{platform.python_version()}"
|
|
50
|
+
|
|
51
|
+
_FORMAT = re.compile(r"[A-Za-z0-9-]{1,20}")
|
|
52
|
+
_FILE_ID = re.compile(r"[0-9a-fA-F]{32}")
|
|
53
|
+
_KEY_CHARS = re.compile(r"[\x21-\x7e]+")
|
|
54
|
+
_DIGITS = re.compile(r"[0-9]+")
|
|
55
|
+
|
|
56
|
+
Number = Union[int, float, Decimal]
|
|
57
|
+
ParamValue = Union[str, int, float, Decimal, bool, None, FileInput]
|
|
58
|
+
"""A parameter value: text, a number, a boolean, ``None`` (left out), or a file sent as a named
|
|
59
|
+
file field (a ``pathlib.Path``, bytes, a binary stream or an :class:`UploadFile`). A ``str``
|
|
60
|
+
value is always text, never a path."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# Settings
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class Settings:
|
|
68
|
+
api_key: str | None = field(repr=False)
|
|
69
|
+
base_url: str
|
|
70
|
+
timeout: float
|
|
71
|
+
connect_timeout: float
|
|
72
|
+
max_retries: int
|
|
73
|
+
max_retry_wait: float
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _seconds(value: object, name: str, *, allow_zero: bool = False) -> float:
|
|
77
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
78
|
+
raise TypeError(f"{name} must be a number of seconds, not {type(value).__name__}")
|
|
79
|
+
if math.isnan(value) or value < 0 or (value == 0 and not allow_zero) or math.isinf(value):
|
|
80
|
+
raise ValueError(f"{name} must be a positive number of seconds, got {value!r}")
|
|
81
|
+
return float(value)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def resolve_settings(
|
|
85
|
+
*,
|
|
86
|
+
api_key: str | None,
|
|
87
|
+
base_url: str | None,
|
|
88
|
+
timeout: float,
|
|
89
|
+
connect_timeout: float,
|
|
90
|
+
max_retries: int,
|
|
91
|
+
max_retry_wait: float,
|
|
92
|
+
) -> Settings:
|
|
93
|
+
if api_key is None:
|
|
94
|
+
api_key = os.environ.get(KEY_ENV)
|
|
95
|
+
elif not isinstance(api_key, str):
|
|
96
|
+
raise TypeError(f"api_key must be a str, not {type(api_key).__name__}")
|
|
97
|
+
key = (api_key or "").strip() or None
|
|
98
|
+
if key is not None and not _KEY_CHARS.fullmatch(key):
|
|
99
|
+
# Never echo the key: say only what is wrong with it.
|
|
100
|
+
raise ValueError("api_key has characters that can't be sent in an HTTP header")
|
|
101
|
+
|
|
102
|
+
if base_url is None:
|
|
103
|
+
base_url = os.environ.get(BASE_URL_ENV) or DEFAULT_BASE_URL
|
|
104
|
+
elif not isinstance(base_url, str):
|
|
105
|
+
raise TypeError(f"base_url must be a str, not {type(base_url).__name__}")
|
|
106
|
+
base = base_url.strip().rstrip("/")
|
|
107
|
+
try:
|
|
108
|
+
parsed = httpx.URL(base)
|
|
109
|
+
except (httpx.InvalidURL, TypeError, ValueError):
|
|
110
|
+
parsed = None
|
|
111
|
+
if (
|
|
112
|
+
parsed is None
|
|
113
|
+
or parsed.scheme not in ("http", "https")
|
|
114
|
+
or not parsed.host
|
|
115
|
+
or parsed.query
|
|
116
|
+
or parsed.fragment
|
|
117
|
+
):
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"base_url must be an http or https URL without a query, such as "
|
|
120
|
+
f"{DEFAULT_BASE_URL!r}; got {base_url!r}"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
if isinstance(max_retries, bool) or not isinstance(max_retries, int):
|
|
124
|
+
raise TypeError(f"max_retries must be an int, not {type(max_retries).__name__}")
|
|
125
|
+
if max_retries < 0:
|
|
126
|
+
raise ValueError(f"max_retries must be 0 or more, got {max_retries}")
|
|
127
|
+
|
|
128
|
+
return Settings(
|
|
129
|
+
api_key=key,
|
|
130
|
+
base_url=base,
|
|
131
|
+
timeout=_seconds(timeout, "timeout"),
|
|
132
|
+
connect_timeout=_seconds(connect_timeout, "connect_timeout"),
|
|
133
|
+
max_retries=max_retries,
|
|
134
|
+
max_retry_wait=_seconds(max_retry_wait, "max_retry_wait", allow_zero=True),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def scrub(text: str, settings: Settings) -> str:
|
|
139
|
+
"""Removes the key from a message, in case a lower layer ever quoted it."""
|
|
140
|
+
return text.replace(settings.api_key, "***") if settings.api_key else text
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# Requests
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True)
|
|
147
|
+
class Call:
|
|
148
|
+
"""One API call, before any attempt."""
|
|
149
|
+
|
|
150
|
+
method: str
|
|
151
|
+
url: str
|
|
152
|
+
timeout: float
|
|
153
|
+
authorized: bool = False
|
|
154
|
+
accept_json: bool = True
|
|
155
|
+
fields: Sequence[tuple[str, FieldValue]] | None = None
|
|
156
|
+
conversion: bool = False
|
|
157
|
+
label: str = ""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def check_format(value: object, what: str) -> str:
|
|
161
|
+
if not isinstance(value, str):
|
|
162
|
+
raise TypeError(f"{what} must be a str, not {type(value).__name__}")
|
|
163
|
+
if not _FORMAT.fullmatch(value):
|
|
164
|
+
raise ValueError(f"{what} must be 1 to 20 letters, digits or hyphens; got {value!r}")
|
|
165
|
+
return value.lower()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def check_file_id(value: object) -> str:
|
|
169
|
+
if not isinstance(value, str):
|
|
170
|
+
raise TypeError(f"file_id must be a str, not {type(value).__name__}")
|
|
171
|
+
if not _FILE_ID.fullmatch(value):
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f"file_id must be 32 hex characters, as in a stored file's FileId; got {value!r}"
|
|
174
|
+
)
|
|
175
|
+
return value.lower()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def check_url(value: object) -> str:
|
|
179
|
+
if not isinstance(value, str):
|
|
180
|
+
raise TypeError(f"url must be a str, not {type(value).__name__}")
|
|
181
|
+
try:
|
|
182
|
+
parsed = httpx.URL(value)
|
|
183
|
+
except (httpx.InvalidURL, TypeError, ValueError):
|
|
184
|
+
parsed = None
|
|
185
|
+
if parsed is None or parsed.scheme not in ("http", "https") or not parsed.host:
|
|
186
|
+
raise ValueError("url must be an absolute http or https URL, such as a stored file's url")
|
|
187
|
+
return value
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def call_timeout(settings: Settings, timeout: float | None) -> float:
|
|
191
|
+
return settings.timeout if timeout is None else _seconds(timeout, "timeout")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def require_key(settings: Settings) -> None:
|
|
195
|
+
if settings.api_key is None:
|
|
196
|
+
raise MissingApiKeyError(
|
|
197
|
+
"this call needs an API key: pass api_key= to the client or set the "
|
|
198
|
+
f"{KEY_ENV} environment variable (get a key at https://app.pdfconversionapi.com)"
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def format_number(value: Number) -> str:
|
|
203
|
+
"""Plain decimal: 72, 1.5, 0.0001 (never 1e-04)."""
|
|
204
|
+
if isinstance(value, int):
|
|
205
|
+
return str(value)
|
|
206
|
+
if isinstance(value, float):
|
|
207
|
+
if not math.isfinite(value):
|
|
208
|
+
raise ValueError(f"parameter values must be finite numbers, got {value!r}")
|
|
209
|
+
if value.is_integer():
|
|
210
|
+
return str(int(value))
|
|
211
|
+
value = Decimal(repr(value))
|
|
212
|
+
if not value.is_finite():
|
|
213
|
+
raise ValueError(f"parameter values must be finite numbers, got {value!r}")
|
|
214
|
+
text = format(value, "f")
|
|
215
|
+
return text.rstrip("0").rstrip(".") if "." in text else text
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def encode_param(name: str, value: object) -> FieldValue | None:
|
|
219
|
+
if value is None:
|
|
220
|
+
return None
|
|
221
|
+
if isinstance(value, bool):
|
|
222
|
+
return "true" if value else "false"
|
|
223
|
+
if isinstance(value, str):
|
|
224
|
+
return value
|
|
225
|
+
if isinstance(value, (int, float, Decimal)):
|
|
226
|
+
return format_number(value)
|
|
227
|
+
return to_upload(value, f"parameter {name!r}")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def convert_fields(
|
|
231
|
+
files: object,
|
|
232
|
+
params: Mapping[str, object] | None,
|
|
233
|
+
file_name: str | None,
|
|
234
|
+
store_file: bool,
|
|
235
|
+
) -> list[tuple[str, FieldValue]]:
|
|
236
|
+
"""The form fields in order: the input files, the parameters, FileName, StoreFile."""
|
|
237
|
+
uploads = to_uploads(files)
|
|
238
|
+
if params is not None and not isinstance(params, Mapping):
|
|
239
|
+
raise TypeError(f"params must be a mapping of names to values, not {type(params).__name__}")
|
|
240
|
+
if file_name is not None and not isinstance(file_name, str):
|
|
241
|
+
raise TypeError(f"file_name must be a str, not {type(file_name).__name__}")
|
|
242
|
+
if not isinstance(store_file, bool):
|
|
243
|
+
raise TypeError(f"store_file must be a bool, not {type(store_file).__name__}")
|
|
244
|
+
|
|
245
|
+
file_field = "File" if len(uploads) == 1 else "Files"
|
|
246
|
+
fields: list[tuple[str, FieldValue]] = [(file_field, upload) for upload in uploads]
|
|
247
|
+
overridden = set()
|
|
248
|
+
if file_name is not None:
|
|
249
|
+
overridden.add("filename")
|
|
250
|
+
if store_file:
|
|
251
|
+
overridden.add("storefile")
|
|
252
|
+
for name, value in (params or {}).items():
|
|
253
|
+
if not isinstance(name, str):
|
|
254
|
+
raise TypeError(f"parameter names must be str, not {type(name).__name__}")
|
|
255
|
+
if name.lower() in overridden:
|
|
256
|
+
continue # the typed option wins
|
|
257
|
+
encoded = encode_param(name, value)
|
|
258
|
+
if encoded is not None:
|
|
259
|
+
fields.append((name, encoded))
|
|
260
|
+
if file_name is not None:
|
|
261
|
+
fields.append(("FileName", file_name))
|
|
262
|
+
if store_file:
|
|
263
|
+
fields.append(("StoreFile", "true"))
|
|
264
|
+
return fields
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def request_headers(call: Call, settings: Settings, body: MultipartBody | None) -> dict[str, str]:
|
|
268
|
+
headers = {"User-Agent": USER_AGENT}
|
|
269
|
+
if call.accept_json:
|
|
270
|
+
headers["Accept"] = "application/json"
|
|
271
|
+
if call.authorized and settings.api_key is not None:
|
|
272
|
+
headers["Authorization"] = f"Bearer {settings.api_key}"
|
|
273
|
+
if body is not None:
|
|
274
|
+
headers["Content-Type"] = body.content_type
|
|
275
|
+
headers["Content-Length"] = str(body.content_length)
|
|
276
|
+
return headers
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def httpx_timeout(call: Call, settings: Settings) -> httpx.Timeout:
|
|
280
|
+
return httpx.Timeout(call.timeout, connect=min(settings.connect_timeout, call.timeout))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class Deadline:
|
|
284
|
+
"""The end of one attempt's time. ``check()`` raises APITimeoutError once it has passed."""
|
|
285
|
+
|
|
286
|
+
def __init__(self, call: Call) -> None:
|
|
287
|
+
self._call = call
|
|
288
|
+
self._at = time.monotonic() + call.timeout
|
|
289
|
+
|
|
290
|
+
def check(self) -> None:
|
|
291
|
+
if time.monotonic() > self._at:
|
|
292
|
+
raise timeout_error(self._call)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def timeout_error(call: Call) -> APITimeoutError:
|
|
296
|
+
text = (
|
|
297
|
+
f"{call.label}: no complete response within {call.timeout:g} seconds (the client's timeout)"
|
|
298
|
+
)
|
|
299
|
+
if call.conversion:
|
|
300
|
+
text += (
|
|
301
|
+
". The conversion may still be running on the server, and it counts toward this "
|
|
302
|
+
"month's conversions if it succeeds; give it more time with timeout= rather than "
|
|
303
|
+
"retrying at once"
|
|
304
|
+
)
|
|
305
|
+
return APITimeoutError(text)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _reason(exc: BaseException, settings: Settings) -> str:
|
|
309
|
+
return scrub(str(exc) or type(exc).__name__, settings)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def connection_error(
|
|
313
|
+
exc: BaseException, call: Call, attempts: int, settings: Settings
|
|
314
|
+
) -> APIConnectionError:
|
|
315
|
+
host = httpx.URL(call.url).host
|
|
316
|
+
tries = "1 attempt" if attempts == 1 else f"{attempts} attempts"
|
|
317
|
+
return APIConnectionError(
|
|
318
|
+
f"{call.label}: no response from {host} after {tries}: {_reason(exc, settings)}"
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def body_error(exc: httpx.HTTPError, call: Call, settings: Settings) -> Exception:
|
|
323
|
+
"""An error while the body of a response was read: never retried."""
|
|
324
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
325
|
+
return timeout_error(call)
|
|
326
|
+
if isinstance(exc, httpx.DecodingError):
|
|
327
|
+
return InvalidResponseError(f"{call.label}: the response body could not be decoded: {exc}")
|
|
328
|
+
return APIConnectionError(
|
|
329
|
+
f"{call.label}: the connection was closed while the response was being read "
|
|
330
|
+
f"({_reason(exc, settings)}). Not retried: a conversion may already have run and counted"
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# Retries
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def jitter(attempt: int, rand: Callable[[], float] = random.random) -> float:
|
|
338
|
+
"""A random number of seconds in [0, 2**attempt)."""
|
|
339
|
+
return float(rand() * (2**attempt))
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def parse_retry_after(value: str | None) -> int | None:
|
|
343
|
+
"""Whole seconds, or None when the header is missing or unreadable."""
|
|
344
|
+
if value is None:
|
|
345
|
+
return None
|
|
346
|
+
text = value.strip()
|
|
347
|
+
return int(text) if _DIGITS.fullmatch(text) else None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class RetryState:
|
|
351
|
+
"""The retry decisions for one call (SPEC section 8). One per call, never shared."""
|
|
352
|
+
|
|
353
|
+
def __init__(
|
|
354
|
+
self, max_retries: int, max_retry_wait: float, rand: Callable[[], float] = random.random
|
|
355
|
+
) -> None:
|
|
356
|
+
self.attempt = 0
|
|
357
|
+
self._max_attempts = max_retries + 1
|
|
358
|
+
self._max_retry_wait = max_retry_wait
|
|
359
|
+
self._rand = rand
|
|
360
|
+
self._retried_500 = False
|
|
361
|
+
|
|
362
|
+
def next_attempt(self) -> None:
|
|
363
|
+
self.attempt += 1
|
|
364
|
+
|
|
365
|
+
def _attempts_left(self) -> bool:
|
|
366
|
+
return self.attempt < self._max_attempts
|
|
367
|
+
|
|
368
|
+
def after_no_response(self) -> float | None:
|
|
369
|
+
"""Seconds to wait before retrying, or None to raise."""
|
|
370
|
+
if not self._attempts_left():
|
|
371
|
+
return None
|
|
372
|
+
return jitter(self.attempt, self._rand)
|
|
373
|
+
|
|
374
|
+
def after_status(self, status: int, retry_after: str | None) -> float | None:
|
|
375
|
+
"""Seconds to wait before retrying, or None to return or raise this response."""
|
|
376
|
+
if status in (429, 503):
|
|
377
|
+
wait = parse_retry_after(retry_after)
|
|
378
|
+
wait = 1 if wait is None else wait
|
|
379
|
+
if self._attempts_left() and wait <= self._max_retry_wait:
|
|
380
|
+
return wait + jitter(self.attempt, self._rand)
|
|
381
|
+
return None
|
|
382
|
+
if status == 500 and not self._retried_500 and self._attempts_left():
|
|
383
|
+
self._retried_500 = True
|
|
384
|
+
return 1 + jitter(self.attempt, self._rand)
|
|
385
|
+
return None
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def wait_after_send_error(
|
|
389
|
+
exc: httpx.TransportError, state: RetryState, call: Call, settings: Settings
|
|
390
|
+
) -> float:
|
|
391
|
+
"""What to do when no status line arrived: the seconds to wait, or raise."""
|
|
392
|
+
if isinstance(exc, httpx.TimeoutException) and not isinstance(exc, httpx.ConnectTimeout):
|
|
393
|
+
raise timeout_error(call) from exc
|
|
394
|
+
if isinstance(exc, (httpx.UnsupportedProtocol, httpx.LocalProtocolError)):
|
|
395
|
+
raise connection_error(exc, call, state.attempt, settings) from exc
|
|
396
|
+
wait = state.after_no_response()
|
|
397
|
+
if wait is None:
|
|
398
|
+
raise connection_error(exc, call, state.attempt, settings) from exc
|
|
399
|
+
return wait
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def log_retry(call: Call, state: RetryState, wait: float, why: str) -> None:
|
|
403
|
+
logger.info("%s: %s; retrying in %.2f s (attempt %d)", call.label, why, wait, state.attempt + 1)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
# Responses
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def request_id(headers: Mapping[str, str]) -> str | None:
|
|
410
|
+
return headers.get("x-request-id") or None
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def api_error(status: int, headers: Mapping[str, str], body: bytes | bytearray) -> ApiError:
|
|
414
|
+
"""The error for a non-success response (SPEC section 9)."""
|
|
415
|
+
text = body.decode("utf-8", "replace")
|
|
416
|
+
content_type = headers.get("content-type")
|
|
417
|
+
mime = content_type.split(";", 1)[0].strip() if content_type else ""
|
|
418
|
+
message: str | None = None
|
|
419
|
+
if not text.strip():
|
|
420
|
+
message = "empty response"
|
|
421
|
+
else:
|
|
422
|
+
try:
|
|
423
|
+
parsed = json.loads(body)
|
|
424
|
+
except (ValueError, RecursionError):
|
|
425
|
+
parsed = None
|
|
426
|
+
if isinstance(parsed, dict) and isinstance(parsed.get("Message"), str):
|
|
427
|
+
message = parsed["Message"]
|
|
428
|
+
elif mime.lower() == "text/plain" and len(text) <= 1000:
|
|
429
|
+
message = text.strip()
|
|
430
|
+
else:
|
|
431
|
+
message = f"non-JSON response ({mime or 'no content type'})"
|
|
432
|
+
error_class = ERRORS_BY_STATUS.get(status, ApiError)
|
|
433
|
+
return error_class(
|
|
434
|
+
status,
|
|
435
|
+
message,
|
|
436
|
+
request_id=request_id(headers),
|
|
437
|
+
retry_after=parse_retry_after(headers.get("retry-after")),
|
|
438
|
+
body=text,
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _invalid(what: str, rid: str | None) -> InvalidResponseError:
|
|
443
|
+
return InvalidResponseError(f"unusable response from the API: {what}", request_id=rid)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def parse_json(body: bytes | bytearray, rid: str | None) -> Any:
|
|
447
|
+
try:
|
|
448
|
+
return json.loads(body)
|
|
449
|
+
except (ValueError, RecursionError):
|
|
450
|
+
snippet = bytes(body[:80]).decode("utf-8", "replace")
|
|
451
|
+
raise _invalid(f"the body is not JSON (it starts {snippet!r})", rid) from None
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _field(obj: Mapping[str, Any], key: str, kind: type | tuple[type, ...], rid: str | None) -> Any:
|
|
455
|
+
value = obj.get(key)
|
|
456
|
+
if isinstance(value, bool) and kind is not bool:
|
|
457
|
+
raise _invalid(f"{key} is {value!r}", rid)
|
|
458
|
+
if not isinstance(value, kind):
|
|
459
|
+
raise _invalid(f"{key} is missing or not a {getattr(kind, '__name__', kind)}", rid)
|
|
460
|
+
return value
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
@dataclass(frozen=True)
|
|
464
|
+
class FileEntry:
|
|
465
|
+
"""One entry of ``Files``, checked and decoded."""
|
|
466
|
+
|
|
467
|
+
name: str
|
|
468
|
+
ext: str
|
|
469
|
+
size: int
|
|
470
|
+
data: bytes | None
|
|
471
|
+
url: str | None
|
|
472
|
+
file_id: str | None
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
class ParsedConversion(NamedTuple):
|
|
476
|
+
conversion_cost: int
|
|
477
|
+
conversion_time: float
|
|
478
|
+
files: list[FileEntry]
|
|
479
|
+
request_id: str | None
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def parse_conversion(body: bytes | bytearray, rid: str | None) -> ParsedConversion:
|
|
483
|
+
doc = parse_json(body, rid)
|
|
484
|
+
if not isinstance(doc, dict):
|
|
485
|
+
raise _invalid("the body is not a JSON object", rid)
|
|
486
|
+
entries = doc.get("Files")
|
|
487
|
+
if not isinstance(entries, list) or not entries:
|
|
488
|
+
raise _invalid("Files is missing or empty", rid)
|
|
489
|
+
cost = doc.get("ConversionCost", 0)
|
|
490
|
+
if isinstance(cost, bool) or not isinstance(cost, int):
|
|
491
|
+
raise _invalid(f"ConversionCost is {cost!r}", rid)
|
|
492
|
+
seconds = doc.get("ConversionTime", 0)
|
|
493
|
+
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
|
|
494
|
+
raise _invalid(f"ConversionTime is {seconds!r}", rid)
|
|
495
|
+
|
|
496
|
+
files = []
|
|
497
|
+
for entry in entries:
|
|
498
|
+
if not isinstance(entry, dict):
|
|
499
|
+
raise _invalid("an entry of Files is not an object", rid)
|
|
500
|
+
name = _field(entry, "FileName", str, rid)
|
|
501
|
+
size = _field(entry, "FileSize", int, rid)
|
|
502
|
+
ext = entry.get("FileExt")
|
|
503
|
+
if not isinstance(ext, str):
|
|
504
|
+
ext = Path(own_name(name)).suffix.lstrip(".").lower()
|
|
505
|
+
encoded = entry.get("FileData")
|
|
506
|
+
if isinstance(encoded, str):
|
|
507
|
+
try:
|
|
508
|
+
data = base64.b64decode(encoded, validate=True)
|
|
509
|
+
except (binascii.Error, ValueError):
|
|
510
|
+
raise _invalid(f"FileData of {name!r} is not valid base64", rid) from None
|
|
511
|
+
if len(data) != size:
|
|
512
|
+
raise _invalid(
|
|
513
|
+
f"{name!r} decodes to {len(data)} bytes, but FileSize says {size}", rid
|
|
514
|
+
)
|
|
515
|
+
files.append(FileEntry(name, ext, size, data, None, None))
|
|
516
|
+
else:
|
|
517
|
+
url = _field(entry, "Url", str, rid)
|
|
518
|
+
file_id = _field(entry, "FileId", str, rid)
|
|
519
|
+
files.append(FileEntry(name, ext, size, None, url, file_id))
|
|
520
|
+
return ParsedConversion(cost, float(seconds), files, rid)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _datetime(value: Any, key: str, rid: str | None) -> datetime:
|
|
524
|
+
if not isinstance(value, str):
|
|
525
|
+
raise _invalid(f"{key} is missing or not a string", rid)
|
|
526
|
+
text = value.strip()
|
|
527
|
+
if text.endswith(("Z", "z")):
|
|
528
|
+
text = text[:-1] + "+00:00"
|
|
529
|
+
try:
|
|
530
|
+
parsed = datetime.fromisoformat(text)
|
|
531
|
+
except ValueError:
|
|
532
|
+
raise _invalid(f"{key} is not a date-time: {value!r}", rid) from None
|
|
533
|
+
if parsed.tzinfo is None:
|
|
534
|
+
return parsed.replace(tzinfo=timezone.utc)
|
|
535
|
+
return parsed.astimezone(timezone.utc)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def parse_usage(body: bytes | bytearray, rid: str | None) -> Usage:
|
|
539
|
+
doc = parse_json(body, rid)
|
|
540
|
+
if not isinstance(doc, dict):
|
|
541
|
+
raise _invalid("the body is not a JSON object", rid)
|
|
542
|
+
remaining = doc.get("Remaining")
|
|
543
|
+
if remaining is not None:
|
|
544
|
+
remaining = _field(doc, "Remaining", int, rid)
|
|
545
|
+
max_upload = doc.get("MaxUploadMB")
|
|
546
|
+
if isinstance(max_upload, float) and max_upload.is_integer():
|
|
547
|
+
max_upload = int(max_upload)
|
|
548
|
+
else:
|
|
549
|
+
max_upload = _field(doc, "MaxUploadMB", int, rid)
|
|
550
|
+
return Usage(
|
|
551
|
+
plan=_field(doc, "Plan", str, rid),
|
|
552
|
+
included=_field(doc, "Included", int, rid),
|
|
553
|
+
used=_field(doc, "Used", int, rid),
|
|
554
|
+
remaining=remaining,
|
|
555
|
+
overage=_field(doc, "Overage", bool, rid),
|
|
556
|
+
running=_field(doc, "Running", int, rid),
|
|
557
|
+
concurrent_limit=_field(doc, "ConcurrentLimit", int, rid),
|
|
558
|
+
max_upload_mb=max_upload,
|
|
559
|
+
period_start=_datetime(doc.get("PeriodStart"), "PeriodStart", rid),
|
|
560
|
+
period_end=_datetime(doc.get("PeriodEnd"), "PeriodEnd", rid),
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def parse_conversions(body: bytes | bytearray, rid: str | None) -> list[Conversion]:
|
|
565
|
+
doc = parse_json(body, rid)
|
|
566
|
+
if not isinstance(doc, list):
|
|
567
|
+
raise _invalid("the body is not a JSON array", rid)
|
|
568
|
+
conversions = []
|
|
569
|
+
for entry in doc:
|
|
570
|
+
if not isinstance(entry, dict):
|
|
571
|
+
raise _invalid("an entry is not an object", rid)
|
|
572
|
+
conversions.append(
|
|
573
|
+
Conversion(
|
|
574
|
+
from_format=_field(entry, "From", str, rid),
|
|
575
|
+
to_format=_field(entry, "To", str, rid),
|
|
576
|
+
title=_field(entry, "Title", str, rid),
|
|
577
|
+
category=_field(entry, "Category", str, rid),
|
|
578
|
+
inputs=_field(entry, "Inputs", str, rid),
|
|
579
|
+
)
|
|
580
|
+
)
|
|
581
|
+
return conversions
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
__all__ = [
|
|
585
|
+
"DEFAULT_BASE_URL",
|
|
586
|
+
"Call",
|
|
587
|
+
"Deadline",
|
|
588
|
+
"FileEntry",
|
|
589
|
+
"ParamValue",
|
|
590
|
+
"RetryState",
|
|
591
|
+
"Settings",
|
|
592
|
+
"UploadFile",
|
|
593
|
+
]
|