Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: switch to API class (GoFile)
NTFSvolume0f04e3066a38
diff --git a/cyberdrop_dl/crawlers/gofile.py b/cyberdrop_dl/crawlers/gofile.pyindex dcc7a071c..2c9da6dec 100644--- a/cyberdrop_dl/crawlers/gofile.py+++ b/cyberdrop_dl/crawlers/gofile.py@@ -7,10 +7,10 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal, NotRequired, TypedDictfrom typing_extensions import ReadOnly-from cyberdrop_dl import env+from cyberdrop_dl import aio, envfrom cyberdrop_dl.cache import disk_cached_methodfrom cyberdrop_dl.clients.http import HTTPConfig-from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPathsfrom cyberdrop_dl.exceptions import PasswordProtectedError, ScrapeErrorfrom cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem, ScrapeItemTypefrom cyberdrop_dl.utils.errors import error_handling_wrapper@@ -19,44 +19,6 @@ if TYPE_CHECKING:from collections.abc import AsyncGenerator, Iterable-_API_ENTRYPOINT = AbsoluteHttpURL("https://api.gofile.io")-_PRIMARY_URL = AbsoluteHttpURL("https://gofile.io")---class Response(TypedDict):- status: str---class Node(TypedDict):- canAccess: ReadOnly[bool]- id: str- type: ReadOnly[Literal["folder", "file"]]- name: str- createTime: int---class UnlockedNode(Node):- canAccess: Literal[True]---class File(UnlockedNode):- type: Literal["file"]- link: str- directLink: NotRequired[str] # Only present in overloaded files (imported)- isFrozen: NotRequired[bool] # Only present in files uploaded by free accounts and older than 30 days- viruses: NotRequired[bool]- md5: str---class Folder(UnlockedNode):- type: Literal["folder"]- code: str- childrenCount: int- children: dict[str, Node]- password: NotRequired[str]- passwordStatus: NotRequired[str]--@HTTPConfig(rate_limit=(4, 10))class GoFileCrawler(Crawler):SUPPORTED_PATHS: ClassVar[SupportedPaths] = {@@ -70,63 +32,32 @@ class GoFileCrawler(Crawler):"ex: https://gofile.io/d/ABC654?password=1234",),}- PRIMARY_URL: ClassVar[AbsoluteHttpURL] = _PRIMARY_URL+ PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://gofile.io")DOMAIN: ClassVar[str] = "gofile"FOLDER_DOMAIN: ClassVar[str] = "GoFile"- _SALT: ClassVar[str] = env.GOFILE_SALT or "9844d94d963d30"- _BROWSER_LANG: ClassVar[str] = "en-US"-def __post_init__(self) -> None:- self._api_key: str = ""+ self.api: GoFileAPI = GoFileAPI.from_crawler(self)- @property- def headers(self) -> dict[str, str]:- headers = {- "User-Agent": (ua := self.config.network.user_agent),- "Origin": "https://gofile.io",- "Referer": "https://gofile.io/",- "Priority": "u=0",- "Sec-Fetch-Dest": "empty",- "Sec-Fetch-Mode": "cors",- "Sec-Fetch-Site": "same-site",- }- if self._api_key:- headers |= {- "Authorization": f"Bearer {self._api_key}",- "X-BL": self._BROWSER_LANG,- "X-Website-Token": _create_web_token(- ua,- self._BROWSER_LANG,- self._api_key,- self._SALT,- ),- }-- return headers-- def __json_resp_check__(self, json_resp: dict[str, Any], _=None) -> None:- status = json_resp.get("status", "")- if "notFound" in status:- raise ScrapeError(404)- if "wrongToken" in status:- self._create_temp_account.clear()- msg = "Invalid API key" if self.config.auth.gofile.api_key else "token expired, please retry"- raise ScrapeError(401, msg)+ def __json_resp_check__(self, resp: dict[str, Any], _=None) -> None:+ self.api.check_resp(resp)async def __async_post_init__(self) -> None:- await self._get_credentials(_API_ENTRYPOINT)+ with self.catch_errors(self.api.ENTRYPOINT), self.disable_on_error("Unable create temp account"):+ if key := self.config.auth.gofile.api_key:+ self.api.key = key+ else:+ self.api.key = await self.api.create_temp_account()+ self.update_cookies({"accountToken": self.api.key})def _prepare_headers(self, scrape_item: ScrapeItem) -> dict[str, str]:- return super()._prepare_headers(scrape_item) | {"Authorization": f"Bearer {self._api_key}"}+ return super()._prepare_headers(scrape_item) | {"Authorization": f"Bearer {self.api.key}"}async def fetch(self, scrape_item: ScrapeItem) -> None:match scrape_item.url.parts[1:]:case ["d", content_id]:return await self.folder(scrape_item, content_id)- case ["download", "web", file_id, _]:- return await self.single_file(scrape_item, file_id)- case ["download", file_id, _]:+ case ["download", "web", file_id, _] | ["download", file_id, _]:return await self.single_file(scrape_item, file_id)case _:raise ValueError@@ -140,24 +71,19 @@ class GoFileCrawler(Crawler):@error_handling_wrapperasync def folder(self, scrape_item: ScrapeItem, content_id: str, single_file_id: str | None = None) -> None:- is_first_page: bool = True-- async for node in self.api_pager(content_id, scrape_item.password):- if is_first_page:- if _has_single_not_nested_file(scrape_item, node):- # Consider this file a loose file (autogenerated folder name)- title = ""- part_of_album = False- else:- name = node["name"]- title = self.create_title(name, content_id, force_album_id=name == "root")- part_of_album = True-- scrape_item.setup_as_album(title, album_id=content_id)- scrape_item.part_of_album = part_of_album- scrape_item.url = scrape_item.url.with_query(None)- is_first_page = False-+ node, pages = await aio.peek_first(self.api.content(content_id, scrape_item.password))+ if _has_single_not_nested_file(scrape_item, node):+ # Consider this file a loose file (autogenerated folder name)+ title = ""+ scrape_item.part_of_album = False+ else:+ title = self.create_title(name := node["name"], content_id, force_album_id=name == "root")+ scrape_item.part_of_album = True++ scrape_item.setup_as_album(title, album_id=content_id)+ scrape_item.url = scrape_item.url.with_query(None)++ async for node in pages:children = {node["id"]: node} if node["type"] == "file" else node["children"]if single_file_id:@@ -165,16 +91,16 @@ class GoFileCrawler(Crawler):if not file:continue- self._handle_children(scrape_item, [file])+ self._iter_children(scrape_item, [file])return- self._handle_children(scrape_item, children.values())+ self._iter_children(scrape_item, children.values())- def _handle_children(self, scrape_item: ScrapeItem, children: Iterable[Node]) -> None:+ def _iter_children(self, scrape_item: ScrapeItem, children: Iterable[Node]) -> None:def web_url(node: Node) -> AbsoluteHttpURL:node_id = node["id"]if node["type"] == "folder":- return _PRIMARY_URL / "d" / (node.get("code") or node_id)+ return self.PRIMARY_URL / "d" / (node.get("code") or node_id)return scrape_item.url.with_fragment(node_id)for node in children:@@ -193,26 +119,6 @@ class GoFileCrawler(Crawler):self.create_eager_task(self._file(scrape_item, node))- async def api_pager(self, content_id: str, password: str | None = None) -> AsyncGenerator[Folder | File]:- api_url = (_API_ENTRYPOINT / "contents" / content_id).with_query(- sortField="createTime",- sortDirection=1,- pageSize=100,- )-- if password:- sha256_password = hashlib.sha256(password.encode(), usedforsecurity=False).hexdigest()- api_url = api_url.update_query(password=sha256_password)-- for page in itertools.count(1):- resp = await self.request_json(api_url.update_query(page=page), headers=self.headers)- self.__json_resp_check__(resp)- node = resp["data"]- _check_node_is_accessible(node)- yield node- if not resp["metadata"].get("hasNextPage"):- break-@error_handling_wrapperasync def _file(self, scrape_item: ScrapeItem, file: File) -> None:link_str: str = file["link"]@@ -240,24 +146,104 @@ class GoFileCrawler(Crawler):thumbnail=self.parse_url(thumb) if (thumb := file.get("thumbnail")) else None,)- @error_handling_wrapper- async def _get_credentials(self, _) -> None:- with self.disable_on_error("Unable to get api_key"):- if key := self.config.auth.gofile.api_key:- self._api_key = key- else:- self._api_key = await self._create_temp_account()- self.update_cookies({"accountToken": self._api_key})++class Node(TypedDict):+ canAccess: ReadOnly[bool]+ id: str+ type: ReadOnly[Literal["folder", "file"]]+ name: str+ createTime: int+++class File(Node):+ type: Literal["file"]+ link: str+ directLink: NotRequired[str] # Only present in overloaded files (imported)+ isFrozen: NotRequired[bool] # Only present in files uploaded by free accounts and older than 30 days+ viruses: NotRequired[bool]+ md5: str+++class Folder(Node):+ type: Literal["folder"]+ code: str+ childrenCount: int+ children: dict[str, Node]+ password: NotRequired[str]+ passwordStatus: NotRequired[str]+++class GoFileAPI(API):+ ENTRYPOINT: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://api.gofile.io")+ BROWSER_LANG: ClassVar[str] = "en-US"+ SALT: ClassVar[str] = env.GOFILE_SALT or "9844d94d963d30"+ key: str = ""++ @property+ def headers(self) -> dict[str, str]:+ headers = {+ "User-Agent": (ua := self.config.network.user_agent),+ "Origin": "https://gofile.io",+ "Referer": "https://gofile.io/",+ "Priority": "u=0",+ "Sec-Fetch-Dest": "empty",+ "Sec-Fetch-Mode": "cors",+ "Sec-Fetch-Site": "same-site",+ }+ if self.key:+ headers |= {+ "Authorization": f"Bearer {self.key}",+ "X-BL": self.BROWSER_LANG,+ "X-Website-Token": _create_web_token(+ ua,+ self.BROWSER_LANG,+ self.key,+ self.SALT,+ ),+ }++ return headers@disk_cached_method(key="account_token", ttl=86400)- async def _create_temp_account(self) -> str:+ async def create_temp_account(self) -> str:self.log.info("Creating temp account")- api_url = _API_ENTRYPOINT / "accounts"- json_resp = await self.request_json(api_url, method="POST", data={}, headers=self.headers)- if json_resp["status"] != "ok":+ api_url = self.ENTRYPOINT / "accounts"+ resp = await self.request_json(api_url, method="POST", data={}, headers=self.headers)+ if resp["status"] != "ok":raise ScrapeError(401, "Couldn't generate GoFile temp account", origin=api_url)- return json_resp["data"]["token"]+ return resp["data"]["token"]++ def check_resp(self, resp: dict[str, Any]) -> None:+ status = resp.get("status", "")+ if "notFound" in status:+ raise ScrapeError(404)+ if "wrongToken" in status:+ self.create_temp_account.clear()+ msg = "Invalid API key" if self.config.auth.gofile.api_key else "token expired, please retry"+ raise ScrapeError(401, msg)++ def content(self, content_id: str, password: str | None = None) -> AsyncGenerator[Folder | File]:+ url = (self.ENTRYPOINT / "contents" / content_id).with_query(+ sortField="createTime",+ sortDirection=1,+ pageSize=100,+ )++ if password:+ url = url.update_query(password=hashlib.sha256(password.encode(), usedforsecurity=False).hexdigest())++ return self.pager(url)++ async def pager(self, url: AbsoluteHttpURL) -> AsyncGenerator[Folder | File]:+ for page in itertools.count(1):+ resp = await self.request_json(url.update_query(page=page), headers=self.headers)+ self.check_resp(resp)+ node = resp["data"]+ _check_node_is_accessible(node)+ yield node+ if not resp["metadata"].get("hasNextPage"):+ breakdef _check_node_is_accessible(node: Node) -> TypeGuard[File | Folder]:diff --git a/tests/crawlers/test_cases/gofile.py b/tests/crawlers/test_cases/gofile.pynew file mode 100644index 000000000..bb1422848--- /dev/null+++ b/tests/crawlers/test_cases/gofile.py@@ -0,0 +1,20 @@+DOMAIN = "gofile"+TEST_CASES = [+ {+ "url": "https://gofile.io/d/pZLspCZv",+ "results": [+ {+ "url": "re:/download/web/3abadc13-64c1-4e38-a59c-516efdd2ecba/AUGUST%20BJ%20RENEW%20TREATthank%20you%20soooo%20much%20for%20staying%20with%20me!%20i%20have%20a%20special%20treat%20for%20you!%20%F0%9F%8D%86%20%F0%9F%92%A6%20here%20is%20a.mp4",+ "filename": "AUGUST BJ RENEW TREATthank you soooo much for staying with me! i have a special treat for y.mp4",+ "debrid_url": None,+ "original_filename": "AUGUST BJ RENEW TREATthank you soooo much for staying with me! i have a special treat for you! 🍆 💦 here is a.mp4",+ "referer": "https://gofile.io/d/pZLspCZv#3abadc13-64c1-4e38-a59c-516efdd2ecba",+ "album_id": "pZLspCZv",+ "uploaded_at": 1786618103,+ "download_folder": "re:Loose Files (GoFile)",+ "thumbnail": "re:.gofile.io/download/web/3abadc13-64c1-4e38-a59c-516efdd2ecba/thumb_51758aee0053e97995d592676d155deb",+ }+ ],+ "count": 1,+ }+]