2024-01-27 04:00:44 +03:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-03-15 13:46:06 +03:00
|
|
|
from aiohttp import ClientSession, ClientResponse, ClientTimeout, BaseConnector, FormData
|
2024-03-12 04:06:06 +03:00
|
|
|
from typing import AsyncIterator, Any, Optional
|
2024-01-27 04:00:44 +03:00
|
|
|
|
2024-01-29 20:14:46 +03:00
|
|
|
from .defaults import DEFAULT_HEADERS
|
2024-03-12 04:06:06 +03:00
|
|
|
from ..errors import MissingRequirementsError
|
2024-01-27 04:00:44 +03:00
|
|
|
|
|
|
|
class StreamResponse(ClientResponse):
|
2024-03-12 04:06:06 +03:00
|
|
|
async def iter_lines(self) -> AsyncIterator[bytes]:
|
2024-01-27 04:00:44 +03:00
|
|
|
async for line in self.content:
|
|
|
|
yield line.rstrip(b"\r\n")
|
|
|
|
|
2024-03-12 04:06:06 +03:00
|
|
|
async def iter_content(self) -> AsyncIterator[bytes]:
|
|
|
|
async for chunk in self.content.iter_any():
|
|
|
|
yield chunk
|
|
|
|
|
2024-04-06 02:05:00 +03:00
|
|
|
async def json(self, content_type: str = None) -> Any:
|
|
|
|
return await super().json(content_type=content_type)
|
2024-01-27 04:00:44 +03:00
|
|
|
|
|
|
|
class StreamSession(ClientSession):
|
2024-04-06 02:05:00 +03:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
headers: dict = {},
|
|
|
|
timeout: int = None,
|
|
|
|
connector: BaseConnector = None,
|
|
|
|
proxies: dict = {},
|
|
|
|
impersonate = None,
|
|
|
|
**kwargs
|
|
|
|
):
|
2024-01-27 04:00:44 +03:00
|
|
|
if impersonate:
|
|
|
|
headers = {
|
2024-01-29 20:14:46 +03:00
|
|
|
**DEFAULT_HEADERS,
|
2024-01-27 04:00:44 +03:00
|
|
|
**headers
|
|
|
|
}
|
2024-04-10 15:23:30 +03:00
|
|
|
connect = None
|
|
|
|
if isinstance(timeout, tuple):
|
|
|
|
connect, timeout = timeout;
|
|
|
|
if timeout is not None:
|
|
|
|
timeout = ClientTimeout(timeout, connect)
|
2024-01-27 04:00:44 +03:00
|
|
|
super().__init__(
|
|
|
|
**kwargs,
|
2024-04-10 15:23:30 +03:00
|
|
|
timeout=timeout,
|
2024-01-27 04:00:44 +03:00
|
|
|
response_class=StreamResponse,
|
2024-04-06 02:05:00 +03:00
|
|
|
connector=get_connector(connector, proxies.get("all", proxies.get("https"))),
|
2024-01-27 04:00:44 +03:00
|
|
|
headers=headers
|
2024-03-12 04:06:06 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
def get_connector(connector: BaseConnector = None, proxy: str = None, rdns: bool = False) -> Optional[BaseConnector]:
|
|
|
|
if proxy and not connector:
|
|
|
|
try:
|
|
|
|
from aiohttp_socks import ProxyConnector
|
|
|
|
if proxy.startswith("socks5h://"):
|
|
|
|
proxy = proxy.replace("socks5h://", "socks5://")
|
|
|
|
rdns = True
|
|
|
|
connector = ProxyConnector.from_url(proxy, rdns=rdns)
|
|
|
|
except ImportError:
|
|
|
|
raise MissingRequirementsError('Install "aiohttp_socks" package for proxy support')
|
2024-03-15 16:55:53 +03:00
|
|
|
return connector
|