feat(rp5): add rp5 api

This commit is contained in:
2026-09-03 19:47:42 +03:00
parent d6487facf4
commit 7c2436fb57
14 changed files with 1278 additions and 13 deletions
+27 -8
View File
@@ -1,5 +1,6 @@
import datetime
import logging
from typing import Literal
from typing import Any, Literal
import aiohttp
from playwright.async_api import async_playwright
@@ -9,6 +10,7 @@ logger = logging.getLogger("source")
RequestMode = Literal["base", "browser"]
DEFAULT_REQUEST_MODE: RequestMode = "base"
DEFAULT_METHOD = "GET"
class ApiSource:
@@ -31,30 +33,47 @@ class ApiSource:
self._cookies = cookies
self._headers = headers
async def _base_request(self, url: str) -> str:
async def _base_request(
self,
url: str,
method: str = DEFAULT_METHOD,
data: Any | None = None,
) -> str:
headers = {"User-Agent": self._user_agent, **(self._headers or {})}
async with aiohttp.ClientSession(
headers=headers,
cookies=self._cookies,
raise_for_status=True,
) as session:
async with session.request("GET", url, timeout=self._timeout) as response:
async with session.request(method, url, timeout=self._timeout, data=data) as response:
return await response.text()
async def _browser_request(self, url: str) -> str:
async def _browser_request(
self,
url: str,
method: str = DEFAULT_METHOD,
data: Any | None = None,
) -> str:
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(url, wait_until="networkidle")
await page.goto(url, timeout=datetime.timedelta(seconds=self._timeout), wait_until="networkidle")
content = await page.content()
await browser.close()
return content
async def request(self, endpoint: str, /, mode: RequestMode = DEFAULT_REQUEST_MODE) -> str:
async def request(
self,
endpoint: str,
/,
mode: RequestMode = DEFAULT_REQUEST_MODE,
method: str = DEFAULT_METHOD,
data: Any | None = None,
) -> str:
if endpoint.startswith("https:"):
url = endpoint
else:
url = f"{self._base_url}/{endpoint}"
logger.info(url)
method = getattr(self, f"_{mode}_request")
return await method(url)
fun = getattr(self, f"_{mode}_request")
return await fun(url, method, data)