2023-07-09 22:11:45 +05:30
|
|
|
import json
|
|
|
|
from io import BytesIO
|
|
|
|
|
|
|
|
import aiohttp
|
|
|
|
|
2024-01-08 16:01:41 +05:30
|
|
|
from app.utils.media_helper import get_filename
|
2023-09-09 14:35:58 +05:30
|
|
|
|
2023-10-23 12:48:11 +05:30
|
|
|
SESSION: aiohttp.ClientSession | None = None
|
2023-07-09 22:11:45 +05:30
|
|
|
|
|
|
|
|
2024-01-08 16:01:41 +05:30
|
|
|
async def init_task() -> None:
|
2023-07-09 22:11:45 +05:30
|
|
|
if not SESSION:
|
|
|
|
globals().update({"SESSION": aiohttp.ClientSession()})
|
|
|
|
else:
|
|
|
|
await SESSION.close()
|
|
|
|
|
|
|
|
|
2023-07-30 13:00:24 +05:30
|
|
|
async def get_json(
|
|
|
|
url: str,
|
|
|
|
headers: dict = None,
|
2024-01-08 16:01:41 +05:30
|
|
|
params: dict | str = None,
|
2023-07-30 13:00:24 +05:30
|
|
|
json_: bool = False,
|
|
|
|
timeout: int = 10,
|
2023-10-23 12:48:11 +05:30
|
|
|
) -> dict | None:
|
2023-07-09 22:11:45 +05:30
|
|
|
try:
|
2023-07-30 13:00:24 +05:30
|
|
|
async with SESSION.get(
|
|
|
|
url=url, headers=headers, params=params, timeout=timeout
|
|
|
|
) as ses:
|
2023-07-09 22:11:45 +05:30
|
|
|
if json_:
|
|
|
|
ret_json = await ses.json()
|
|
|
|
else:
|
|
|
|
ret_json = json.loads(await ses.text())
|
|
|
|
return ret_json
|
|
|
|
except BaseException:
|
|
|
|
return
|
|
|
|
|
|
|
|
|
2023-10-23 12:48:11 +05:30
|
|
|
async def in_memory_dl(url: str) -> BytesIO:
|
2023-07-09 22:11:45 +05:30
|
|
|
async with SESSION.get(url) as remote_file:
|
|
|
|
bytes_data = await remote_file.read()
|
|
|
|
file = BytesIO(bytes_data)
|
2023-09-09 14:35:58 +05:30
|
|
|
file.name = get_filename(url)
|
|
|
|
return file
|
|
|
|
|
|
|
|
|
2023-10-23 12:48:11 +05:30
|
|
|
async def thumb_dl(thumb) -> BytesIO | str | None:
|
2023-07-09 22:11:45 +05:30
|
|
|
if not thumb or not thumb.startswith("http"):
|
|
|
|
return thumb
|
2024-01-08 16:01:41 +05:30
|
|
|
return await in_memory_dl(thumb) # NOQA
|