Skip to content

Bulk asynchronous downloader for multiple file hosts

12.0 KB
Raw Blame
"""https://pixeldrain.com/api"""

from __future__ import annotations

import dataclasses
from collections import deque
from typing import TYPE_CHECKING, Any, ClassVar, Literal, final, override

from cyberdrop_dl import aio
from cyberdrop_dl.clients.http import HTTPConfig
from cyberdrop_dl.crawlers.crawler import (
    API,
    Crawler,
    DownloadConfig,
    SupportedDomains,
    SupportedPaths,
    URLConfig,
    auto_task_id,
)
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.models import type_adapter
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import basic_auth
from cyberdrop_dl.utils.errors import error_handling_wrapper

if TYPE_CHECKING:
    from collections.abc import Sequence

    from cyberdrop_dl.clients.response import AbstractResponse
    from cyberdrop_dl.url_objects import ScrapeItem


@final
@dataclasses.dataclass(slots=True, frozen=True)
class File:
    id: str
    name: str
    date_upload: str
    mime_type: str
    hash_sha256: str
    availability: str
    availability_message: str = ""


@dataclasses.dataclass(slots=True, frozen=True)
class Folder:
    id: str
    title: str
    files: tuple[File, ...]


@final
@dataclasses.dataclass(slots=True, frozen=True)
class Node:
    type: Literal["file", "dir"]
    path: str
    name: str
    modified: str
    sha256_sum: str
    id: str | None = None
    file_type: str | None = None

    # Properties so we can process a Node as a normal File
    @property
    def mime_type(self) -> str:
        return self.file_type or ""

    @property
    def date_upload(self) -> str:
        return self.modified

    @property
    def hash_sha256(self) -> str:
        return self.sha256_sum


@dataclasses.dataclass(slots=True)
class FileSystem:
    children: list[Node]
    base_index: int
    path: list[Node]


class PixelDrainProxyCrawler(Crawler):
    SUPPORTED_PATHS: ClassVar[SupportedPaths] = {"File": "/<file_id>"}
    SUPPORTED_DOMAINS: ClassVar[SupportedDomains] = "pd.cybar.xyz", "pd.1drv.eu.org"
    PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://pd.1drv.eu.org")
    DOMAIN: ClassVar[str] = "pixeldrain-proxy"

    @override
    async def fetch(self, scrape_item: ScrapeItem) -> None:
        match scrape_item.url.parts[1:]:
            case ["u", _]:
                self.handle_external_links(scrape_item)
            case _:
                raise ValueError

    @classmethod
    @override
    def transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
        url = super().transform_url(url).with_host("pixeldrain.com")
        match url.parts[1:]:
            case [file_id]:
                return url.origin() / "u" / file_id
            case _:
                return url


@HTTPConfig(rate_limit=(10, 1))
@DownloadConfig(slots=2)
@URLConfig(strict_host_match=True)
class PixelDrainCrawler(Crawler):
    SUPPORTED_DOMAINS: ClassVar[SupportedDomains] = (
        "pixeldrain.com",
        "pixeldrain.net",
        "pixeldra.in",
        "pixeldrain.nl",
        "pixeldrain.biz",
        "pixeldrain.tech",
        "pixeldrain.dev",
    )
    SUPPORTED_PATHS: ClassVar[SupportedPaths] = {
        "File": (
            "/u/<file_id>",
            "/l/<list_id>#item=<file_index>",
            "/api/file/<file_id>",
        ),
        "Folder": (
            "/l/<list_id>",
            "/api/list/<list_id>",
        ),
        "Filesystem": (
            "/d/<id>",
            "/api/filesystem/<path>...",
        ),
        "**NOTE**": "text files will not be downloaded but their content will be parsed for URLs",
    }
    PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://pixeldrain.com")
    DOMAIN: ClassVar[str] = "pixeldrain"
    FOLDER_DOMAIN: ClassVar[str] = "PixelDrain"

    def __post_init__(self) -> None:
        self.api: PixelDrainAPI = PixelDrainAPI.from_crawler(self)
        if self.api.logged_in:
            self.downloader.slots = None

    @override
    def __json_resp_check__(self, json_resp: dict[str, Any], resp: AbstractResponse[Any]) -> None:
        if not json_resp["success"]:
            msg = f"{json_resp['message']} ({json_resp['value']})"
            raise ScrapeError(resp.status, msg)

    @override
    def _prepare_headers(self, scrape_item: ScrapeItem) -> dict[str, str]:
        return super()._prepare_headers(scrape_item) | self.api.headers

    @override
    async def fetch(self, scrape_item: ScrapeItem) -> None:
        if self.origin.host not in self.SUPPORTED_DOMAINS:
            raise ValueError

        match scrape_item.url.parts[1:]:
            case ["u", file_id]:
                await self.file(scrape_item, file_id)
            case ["l", folder_id]:
                await self.folder(scrape_item, folder_id)
            case ["d", *path] if path:
                await self.filesystem(scrape_item, "/".join(path))
            case _:
                raise ValueError

    @classmethod
    @override
    def transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
        url = super().transform_url(url)
        match url.parts[1:]:
            case ["api", "file", file_id]:
                return url.origin() / "u" / file_id
            case ["api", "list", list_id]:
                return url.origin() / "l" / list_id
            case ["api", "filesystem", *rest] if rest:
                return (url.origin() / "d").joinpath(*rest)
            case _:
                return url

    @error_handling_wrapper
    async def folder(self, scrape_item: ScrapeItem, list_id: str) -> None:
        folder = await self.api.folder(list_id)
        title = self.create_title(folder.title, list_id)
        scrape_item.setup_as_album(title, album_id=list_id)

        try:
            files = _filter_files(folder.files, scrape_item.url.fragment)
        except (ValueError, IndexError):
            msg = f"Unable to parse item index in {scrape_item.url}. Falling back to downloading the entire folder"
            self.log.warning(msg)
            files = folder.files

        await self._files(scrape_item, files)

    async def _files(self, scrape_item: ScrapeItem, files: Sequence[File]) -> None:
        assert scrape_item.album_id
        downloaded = await self.get_completed_by_album(scrape_item.album_id)
        sleep = aio.periodic_sleep(10)
        async with aio.non_cancelling_taskgroup() as tg:
            for file in files:
                if self.api.download(file) in downloaded:
                    continue

                new_item = scrape_item.create_child(self.origin / "u" / file.id)
                tg.create_task(self._file_task(new_item, file))
                scrape_item.add_children()
                await sleep()

    @error_handling_wrapper
    async def filesystem(self, scrape_item: ScrapeItem, path: str) -> None:
        # https://github.com/Fornaxian/pixeldrain_web/blob/8e5ecfc5ce44c0b2b4fafdf9e8201dfc98395e88/svelte/src/filesystem/FilesystemAPI.ts
        fs = await self.api.filesystem(path)
        base_node = fs.path[fs.base_index]
        root = fs.path[0]
        assert root.id
        title = self.create_title(root.name, root.id)
        scrape_item.setup_as_album(title, album_id=root.id)

        if base_node.type == "file":
            fs.children = [base_node]

        await self._walk_filesystem(scrape_item, fs)

    async def _walk_filesystem(self, scrape_item: ScrapeItem, fs: FileSystem) -> None:
        assert scrape_item.album_id
        downloaded = await self.get_completed_by_album(scrape_item.album_id)
        sleep = aio.periodic_sleep(10)
        subfolders: deque[str] = deque()

        async with aio.non_cancelling_taskgroup() as tg:
            while True:
                for node in fs.children:
                    if node.name == ".search_index.gz":
                        continue

                    if node.type == "dir":
                        subfolders.append(node.path)
                        continue

                    if node.type != "file":
                        self.log.warning("Unknown node type: %s", node)
                        continue

                    if self.api.download(node) in downloaded:
                        continue

                    url = self.origin / "d" / node.path.removeprefix("/")
                    new_item = scrape_item.create_child(url)
                    leafs = node.path.split("/")[2:-1]
                    new_item.append_folders(*leafs)
                    tg.create_task(self._file_task(new_item, node))
                    await sleep()

                if not subfolders:
                    break

                fs = await self.api.filesystem(subfolders.popleft())

    @error_handling_wrapper
    async def file(self, scrape_item: ScrapeItem, file_id: str) -> None:
        if await self.check_complete_from_referer(scrape_item.url):
            return

        file = await self.api.file(file_id)
        await self._file(scrape_item, file)

    async def _file(self, scrape_item: ScrapeItem, file: File | Node) -> None:
        src = self.api.download(file).with_host(self.origin.host)

        if "text/plain" in file.mime_type:
            scrape_item.setup_as_album(self.create_title(file.name, file.id))
            text = await self.api.text(src)
            self._text(scrape_item, text)
            return

        if await self.check_complete_by_hash(src, "sha256", file.hash_sha256):
            return

        if type(file) is File:
            _check_file_is_available(file)

        filename, ext = self.get_filename_and_ext(file.name, mime_type=file.mime_type)
        scrape_item.uploaded_at = self.parse_iso_date(file.date_upload)
        await self.handle_file(
            src,
            scrape_item,
            file.name,
            ext,
            custom_filename=filename,
            thumbnail=src.with_query("thumbnail") if type(file) is Node else src / "thumbnail",
        )

    def _text(self, scrape_item: ScrapeItem, text: str) -> None:
        for line in text.splitlines():
            try:
                link = self.parse_url(line)
            except Exception:  # noqa: BLE001, S112
                continue
            new_item = scrape_item.create_child(link)
            self.handle_external_links(new_item)
            scrape_item.add_children()

    _file_task = auto_task_id(error_handling_wrapper(_file))


def _check_file_is_available(file: File) -> None:
    if file.availability == "unavailable_for_legal_reasons":
        raise ScrapeError(451, file.availability_message or file.availability)
    if file.availability.endswith(("_captcha_required", "_limit_exceeded")):
        raise ScrapeError(403, file.availability_message or file.availability)


class PixelDrainAPI(API):
    def __post_init__(self) -> None:
        self.headers: dict[str, str] = {}
        if api_key := self.config.auth.pixeldrain.api_key:
            self.headers["Authorization"] = basic_auth("Cyberdrop-DL", api_key)

    @property
    def logged_in(self) -> bool:
        return bool(self.headers)

    async def file(self, file_id: str) -> File:
        api_url = self.origin / "api/file" / file_id / "info"
        resp = await self.text(api_url)
        return type_adapter(File).validate_json(resp)

    async def folder(self, list_id: str) -> Folder:
        api_url = self.origin / "api/list" / list_id
        resp = await self.text(api_url)
        return type_adapter(Folder).validate_json(resp)

    async def filesystem(self, path: str) -> FileSystem:
        api_url = (self.origin / "api/filesystem" / path.removeprefix("/")).with_query("stat")
        resp = await self.text(api_url)
        return type_adapter(FileSystem).validate_json(resp)

    async def text(self, api_url: AbsoluteHttpURL) -> str:
        return await self.request_text(api_url, headers=self.headers)

    def download(self, file: File | Node) -> AbsoluteHttpURL:
        if type(file) is File:
            return (self.origin / "api/file" / file.id).with_query("download")
        return (self.origin / "api/filesystem" / file.path.removeprefix("/")).with_query("attach")


def _filter_files(files: Sequence[File], fragment: str) -> Sequence[File]:
    if fragment.startswith(prefix := "item="):
        item_idx = int(fragment.removeprefix(prefix))
        return [files[item_idx]]
    return files