Skip to content

Bulk asynchronous downloader for multiple file hosts

4.6 KB
Raw Blame
from __future__ import annotations

from http import HTTPStatus
from typing import TYPE_CHECKING, Any, ClassVar

from cyberdrop_dl.cache import disk_cached_method
from cyberdrop_dl.clients import etag
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, extr_text
from cyberdrop_dl.utils.errors import error_handling_wrapper

if TYPE_CHECKING:
    from cyberdrop_dl.url_objects import ScrapeItem

_API_ENTRYPOINT = AbsoluteHttpURL("https://api.imgur.com/3/")
_IMAGE_CDN = AbsoluteHttpURL("https://i.imgur.com")


etag.register(etag.ETag("d835884373f4d6c8f24742ceabe74946", "Image has been removed", HTTPStatus.GONE))


class ImgurCrawler(Crawler):
    SUPPORTED_PATHS: ClassVar[SupportedPaths] = {
        "Album": "/a/<album_id>",
        "Gallery": "/gallery/<slug>-<album_id>",
        "Image": (
            "/<image_id>",
            "/download/<image_id>",
        ),
        "Direct links": f"{_IMAGE_CDN}/<image_id>.<ext>",
    }
    PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://imgur.com/")
    DOMAIN: ClassVar[str] = "imgur"

    def __post_init__(self) -> None:
        self.client_id: str = ""

    def __json_resp_check__(self, json_resp: dict[str, Any], _) -> None:
        if data := json_resp.get("data"):
            raise ScrapeError(json_resp["status"], data["error"])

    async def __async_post_init__(self) -> None:
        async with self.catch_errors(self.PRIMARY_URL), self.disable_on_error("Unable to get client id"):
            self.client_id = await self._get_client_id()

    @disk_cached_method("client_id", ttl=86400 * 90)
    async def _get_client_id(self) -> str:
        soup = await self.request_soup(self.PRIMARY_URL)
        js_src = css.select(soup, "script[src*='/desktop-assets/js/main']", "src")
        js_text = await self.request_text(self.parse_url(js_src))
        return extr_text(js_text, 'apiClientId:"', '"')

    async def fetch(self, scrape_item: ScrapeItem) -> None:
        if scrape_item.url.host == _IMAGE_CDN.host:
            await self.direct_file(scrape_item)
            return

        match scrape_item.url.parts[1:]:
            case ["a", album_id]:
                await self.album(scrape_item, album_id)
            case ["removed.png"]:
                await self.raise_exc(scrape_item, HTTPStatus.GONE)
            case [slug]:
                image_id = slug.partition(".")[0]
                await self.image(scrape_item, image_id)
            case _:
                raise ValueError

    @classmethod
    def transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
        match url.parts[1:]:
            case ["gallery", slug]:
                album_id = slug.rpartition("-")[-1]
                return cls.PRIMARY_URL / "a" / album_id
            case ["download", image_id]:
                return cls.PRIMARY_URL / image_id
            case _:
                return url

    async def _api_request(self, *parts: str) -> dict[str, str]:
        api_url = _API_ENTRYPOINT.joinpath(*parts)
        return (
            await self.request_json(
                api_url,
                headers={"Authorization": f"Client-ID {self.client_id}"},
            )
        )["data"]

    @error_handling_wrapper
    async def album(self, scrape_item: ScrapeItem, album_id: str) -> None:
        album: dict[str, Any] = await self._api_request("album", album_id)
        title = self.create_title(album.get("title") or album_id, album_id=album_id)
        scrape_item.setup_as_album(title, album_id=album_id)
        results = await self.get_album_results(album_id)
        for image in album["images"]:
            link = self.parse_url(image["link"])
            if self.check_album_results(link, results):
                continue
            web_url = self.PRIMARY_URL / image["id"]
            new_scrape_item = scrape_item.create_child(web_url)
            self.create_eager_task(self._image(new_scrape_item, image))
            scrape_item.add_children()

    @error_handling_wrapper
    async def image(self, scrape_item: ScrapeItem, image_id: str) -> None:
        if await self.check_complete_from_referer(scrape_item.url):
            return
        image = await self._api_request("image", image_id)
        await self._image(scrape_item, image)

    @error_handling_wrapper
    async def _image(self, scrape_item: ScrapeItem, image: dict[str, Any]) -> None:
        scrape_item.uploaded_at = image["datetime"]
        url = self.parse_url(image["link"])
        filename, ext = self.get_filename_and_ext(url.name)
        await self.handle_file(url, scrape_item, filename, ext, metadata=image)