diff options
author | Maxim Devaev <[email protected]> | 2021-07-27 05:25:54 +0300 |
---|---|---|
committer | Maxim Devaev <[email protected]> | 2021-07-27 05:25:54 +0300 |
commit | 6b07a80834879970639b651b1a225f8d1f5f7c2e (patch) | |
tree | 51f5c91b3b384852ff5c8558b097c02f7a5fd120 /kvmd/htclient.py | |
parent | 3c421fa94cbd1e479a51d66eaa4fb33d74277009 (diff) |
/msd/write_remote handle
Diffstat (limited to 'kvmd/htclient.py')
-rw-r--r-- | kvmd/htclient.py | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/kvmd/htclient.py b/kvmd/htclient.py index 368bf668..1927ede2 100644 --- a/kvmd/htclient.py +++ b/kvmd/htclient.py @@ -20,7 +20,15 @@ # ========================================================================== # +import os +import contextlib + +from typing import Dict +from typing import AsyncGenerator +from typing import Optional + import aiohttp +import aiohttp.multipart from . import __version__ @@ -41,3 +49,48 @@ def raise_not_200(response: aiohttp.ClientResponse) -> None: message=response.reason, headers=response.headers, ) + + +def get_content_length(response: aiohttp.ClientResponse) -> int: + try: + value = int(response.headers["Content-Length"]) + except Exception: + raise aiohttp.ClientError("Empty or invalid Content-Length") + if value < 0: + raise aiohttp.ClientError("Negative Content-Length") + return value + + +def get_filename(response: aiohttp.ClientResponse) -> str: + try: + disp = response.headers["Content-Disposition"] + parsed = aiohttp.multipart.parse_content_disposition(disp) + return str(parsed[1]["filename"]) + except Exception: + try: + return os.path.basename(response.url.path) + except Exception: + raise aiohttp.ClientError("Can't determine filename") + + +async def download( + url: str, + verify: bool=True, + timeout: float=10.0, + read_timeout: Optional[float]=None, + app: str="KVMD", +) -> AsyncGenerator[aiohttp.ClientResponse, None]: + + kwargs: Dict = { + "headers": {"User-Agent": make_user_agent(app)}, + "timeout": aiohttp.ClientTimeout( + connect=timeout, + sock_connect=timeout, + sock_read=(read_timeout if read_timeout is not None else timeout), + ), + } + async with aiohttp.ClientSession(**kwargs) as session: + async with session.get(url, verify_ssl=verify) as response: + raise_not_200(response) + yield response |