|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import re |
| 5 | +from functools import partial |
| 6 | +from typing import TYPE_CHECKING, Callable |
| 7 | + |
| 8 | +import bs4 |
| 9 | + |
| 10 | +from plugin.libraries.preset import PresetLibrary |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from aiohttp import ClientSession |
| 14 | + |
| 15 | + |
| 16 | +class MpvIoParser: |
| 17 | + def __init__(self, data: bytes, url_builder: Callable[[str], str]) -> None: |
| 18 | + self.data = data |
| 19 | + self.soup = bs4.BeautifulSoup(data, "html.parser") |
| 20 | + self.cache: dict[str, str] = {} |
| 21 | + self.url_builder = url_builder |
| 22 | + |
| 23 | + def header_to_fragment(self, header: str) -> str: |
| 24 | + return "#" + header.lower().replace(" ", "-") |
| 25 | + |
| 26 | + def parse( |
| 27 | + self, |
| 28 | + ) -> None: |
| 29 | + headers: list[bs4.Tag] = self.soup.find_all(re.compile("^h[1-6]$")) |
| 30 | + |
| 31 | + for header in headers: |
| 32 | + self.cache[header.text] = self.url_builder( |
| 33 | + self.header_to_fragment(header.text) |
| 34 | + ) |
| 35 | + |
| 36 | + |
| 37 | +class MpvIoBase(PresetLibrary): |
| 38 | + def __init_subclass__(cls, version: str) -> None: |
| 39 | + return super().__init_subclass__(base_url=f"https://mpv.io/manual/{version}") |
| 40 | + |
| 41 | + async def build_cache(self, session: ClientSession, webserver_port: int) -> None: |
| 42 | + async with session.get(self.url) as res: |
| 43 | + raw_content: bytes = await res.content.read() |
| 44 | + |
| 45 | + parser = MpvIoParser(raw_content, partial(self._build_url, port=webserver_port)) |
| 46 | + |
| 47 | + await asyncio.to_thread(parser.parse) |
| 48 | + self.cache = parser.cache |
| 49 | + |
| 50 | + |
| 51 | +class MpvIoLatest(MpvIoBase, version="master"): ... |
| 52 | + |
| 53 | + |
| 54 | +class MpvIoStable(MpvIoBase, version="stable"): ... |
| 55 | + |
| 56 | + |
| 57 | +presets = (MpvIoLatest, MpvIoStable) |
0 commit comments