2021-07-26 06:52:13 +02:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2023-01-11 07:23:42 +01:00
|
|
|
import sys
|
2021-07-26 06:52:13 +02:00
|
|
|
import anyio
|
2023-01-11 07:23:42 +01:00
|
|
|
import aiohttp
|
2021-09-17 08:34:44 +02:00
|
|
|
import contextlib
|
2021-07-26 08:29:20 +02:00
|
|
|
from functools import wraps
|
2021-09-17 08:34:44 +02:00
|
|
|
|
|
|
|
def as_corofunc(f):
|
|
|
|
@wraps(f)
|
|
|
|
async def wrapped(*args, **kwargs):
|
|
|
|
# can't decide if i want an `anyio.sleep(0)` here.
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
def as_async_cm(cls):
|
|
|
|
@wraps(cls, updated=()) # cls.__dict__ doesn't support .update()
|
|
|
|
class wrapped(cls, contextlib.AbstractAsyncContextManager):
|
|
|
|
__aenter__ = as_corofunc(cls.__enter__)
|
|
|
|
__aexit__ = as_corofunc(cls.__exit__)
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
suppress = as_async_cm(contextlib.suppress)
|
2021-07-26 06:52:13 +02:00
|
|
|
|
|
|
|
def shield(f):
|
2021-07-26 08:29:20 +02:00
|
|
|
@wraps(f)
|
2021-07-26 06:52:13 +02:00
|
|
|
async def shielded(*args, **kwargs):
|
2021-07-26 08:29:20 +02:00
|
|
|
with anyio.CancelScope(shield=True):
|
2021-07-26 06:52:13 +02:00
|
|
|
return await f(*args, **kwargs)
|
|
|
|
return shielded
|
2021-08-19 12:40:57 +02:00
|
|
|
|
|
|
|
def removeprefix(s, prefix):
|
|
|
|
try:
|
|
|
|
return s.removeprefix(prefix)
|
|
|
|
except AttributeError:
|
|
|
|
# compatibility for pre-3.9
|
|
|
|
return s[len(prefix):] if s.startswith(prefix) else s
|
2021-09-17 08:35:54 +02:00
|
|
|
|
2023-01-11 07:23:42 +01:00
|
|
|
def http_session_factory(headers={}, **kwargs):
|
|
|
|
py_version = '.'.join(map(str, sys.version_info))
|
|
|
|
user_agent = (
|
|
|
|
'pleroma-ebooks (https://github.com/ioistired/pleroma-ebooks); '
|
|
|
|
f'aiohttp/{aiohttp.__version__}; '
|
|
|
|
f'python/{py_version}'
|
|
|
|
)
|
|
|
|
return aiohttp.ClientSession(
|
|
|
|
headers={'User-Agent': user_agent, **headers},
|
|
|
|
**kwargs,
|
|
|
|
)
|