### Start API Server Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Starts the Kuaishou Downloader API server. You can specify the host and port for the server to listen on. ```bash python main.py api [--host 0.0.0.0] [--port 5557] ``` -------------------------------- ### Start API Server with Host and Port Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Command to start the API server, specifying the host address and port number. This is useful for network accessibility and port management. ```bash python main.py api --host 0.0.0.0 --port 5557 ``` -------------------------------- ### Version Management Example Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Demonstrates checking for software updates by comparing current and target versions. Fetches the latest version from GitHub releases. ```python class Version: async def get_target_version(self) -> str | None: # Fetches latest version from GitHub releases @staticmethod def compare_versions( current: str, target: str, beta: bool, ) -> int: # Returns: 0 (up to date), 1 (update available), -1 (error) version = Version(manager) target = await version.get_target_version() if target: state = version.compare_versions("1.6", target, False) # state: 0=ok, 1=update available, -1=error ``` -------------------------------- ### HTTP Client Initialization Example Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Shows how to initialize a base HTTP client with a user agent, timeout, and proxy settings. This client is used for making web requests. ```python # HTTP client client = base_client("Mozilla/5.0...", 10, proxy_dict) ``` -------------------------------- ### Basic CLI and API Server Startup Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Shows how to start the application in either Terminal UI mode or API server mode. The API server can be configured with host and port. ```python # Terminal UI mode python main.py # API server mode python main.py api --port 8080 ``` -------------------------------- ### Console Output Example Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Demonstrates basic console output using a ColorConsole object with predefined styles. Use this for user-facing messages in TUI applications. ```python # Console output console = ColorConsole(beta=False) console.print("Starting...", style=INFO) ``` -------------------------------- ### GET / Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md Redirects to the project's GitHub repository. This endpoint is used for informational purposes and does not require authentication. ```APIDOC ## GET / ### Description Redirects to the project GitHub repository. ### Method GET ### Endpoint / ### Parameters #### Query Parameters None ### Response #### Success Response (307) - **Location**: (string) - URL to the GitHub repository. ### Response Example ``` HTTP/1.1 307 Temporary Redirect Location: https://github.com/JoeanAmier/KS-Downloader ``` ``` -------------------------------- ### HTTP Client Pattern Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Demonstrates the asynchronous HTTP client pattern using httpx.AsyncClient for making GET requests and processing JSON responses. ```python async with httpx.AsyncClient() as client: response = await client.get(url) data = response.json() ``` -------------------------------- ### Redirect to GitHub Repository Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md The root endpoint redirects users to the project's GitHub repository. This is a simple GET request. ```bash curl -L http://localhost:5557/ # Follows redirect to GitHub repository ``` -------------------------------- ### Author Cache Management Example Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Manages an author ID to nickname mapping cache. Use this to store and retrieve author nicknames associated with their IDs. ```python class Mapping: async def update_cache(self, author_id: str, nickname: str) -> None: # Updates cache for author ID → nickname mapping mapping = Mapping(manager, database) await mapping.update_cache("user_123", "MyCreator") # Later: Database remembers this mapping ``` -------------------------------- ### Get User Input with ColorConsole Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Prompts the user for input using a specified prompt string, with console styling applied. Returns the user's input as a string. ```python url = console.input("Enter work URL: ") ``` -------------------------------- ### Text Cleaning Example Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Illustrates using a Cleaner object to filter user input for safe filenames. This helps sanitize potentially problematic characters. ```python # Text cleaning cleaner = Cleaner() filename = cleaner.filter_name(user_input) ``` -------------------------------- ### Override Server Configuration via Command Line Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md The Uvicorn server's default configuration (host, port, etc.) can be overridden using command-line arguments when starting the application. ```bash python main.py api --host 127.0.0.1 --port 8080 ``` -------------------------------- ### Remove Empty Directories Utility Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Recursively removes empty directories starting from a given root path. Useful for cleaning up directories after file operations. ```python def remove_empty_directories(root: Path) -> None: # Removes all empty subdirectories under root remove_empty_directories(Path("/app/temp")) # Cleans up after downloads complete ``` -------------------------------- ### remove_empty_directories Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Recursively removes all empty subdirectories starting from a specified root directory. ```APIDOC ## Directory Utilities: remove_empty_directories() ### Description Recursively removes empty directories. ### Method Signature `def remove_empty_directories(root: Path) -> None:` ### Example ```python from pathlib import Path remove_empty_directories(Path("/app/temp")) # Cleans up after downloads complete ``` ``` -------------------------------- ### Nested Data Access Example Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Demonstrates accessing nested data within a structure using Namespace.safe_extract. This method provides a safe way to retrieve values from potentially missing keys. ```python # Nested data access data = Namespace.generate_data_object(api_response) name = Namespace.safe_extract(data, "user.name", "Unknown") ``` -------------------------------- ### Configuration Pattern Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Shows the pattern for initializing configuration and parameters, reading settings, and running the manager. ```python config = Config(console) params = Parameter(console, cleaner, **config.read()) manager = Manager(**params.run()) ``` -------------------------------- ### Programmatic Work Download with KS Client Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Demonstrates how to use the `KS` client programmatically to download a work by its URL. It shows how to handle the result, printing the caption on success or an error message. ```python from source import KS async def download_work(url: str): async with KS() as app: result = await app.detail_one(url, download=True) if isinstance(result, dict): print(f"Downloaded: {result['caption']}") else: print(f"Error: {result}") # Run with asyncio import asyncio asyncio.run(download_work("https://www.kuaishou.com/short-video/abc123")) ``` -------------------------------- ### Context Manager Pattern Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Demonstrates the context manager pattern for initializing and running the KS application asynchronously. ```python async with KS() as app: await app.run() ``` -------------------------------- ### Create Configured HTTP Client Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Factory function to create an httpx.AsyncClient with specified user agent, timeout, and proxy settings. Useful for making HTTP requests. ```python client = base_client( user_agent="Mozilla/5.0...", timeout=10, proxy={"http://": None, "https://": None}, ) response = await client.get("https://example.com") await client.aclose() ``` -------------------------------- ### Import Main Classes Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Import necessary classes from the KS-Downloader library for various functionalities. ```python from source import KS from source.app import KS from source.manager import Manager from source.downloader import Downloader from source.extract import HTMLExtractor, APIExtractor from source.link import Examiner, DetailPage from source.module import Database, CacheError from source.config import Config, Parameter from source.request import Detail, User from source.tools import ColorConsole, Cleaner, Mapping, Version from source.model import DetailModel, ResponseModel, ShortUrl, UrlResponse ``` -------------------------------- ### Initialize ColorConsole Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Initializes the ColorConsole class for formatted console output. The 'beta' parameter can be used to mark output as a beta version. ```python class ColorConsole: def __init__(self, beta: bool = False) -> None: self.beta = beta self.console = Console() ``` -------------------------------- ### base_client Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Factory function to create an httpx.AsyncClient with pre-configured timeout, proxy, and headers. ```APIDOC ## Function: base_client ### Description Creates an httpx.AsyncClient with configured timeout, proxy, and headers. ### Parameters - **user_agent** (str) - Required - HTTP User-Agent header. - **timeout** (int) - Required - Request timeout in seconds. - **proxy** (dict) - Required - Proxy configuration in the format: `{"http://": url, "https://": url}`. ### Returns - httpx.AsyncClient — A configured async HTTP client. ``` -------------------------------- ### Initialize DetailPage Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Instantiate the DetailPage class with a Manager instance. This object is used for fetching HTML content from Kuaishou work URLs. ```python detail_page = DetailPage(manager) ``` -------------------------------- ### Version.compare_versions Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Compares the current version string against a target version string, considering beta releases. ```APIDOC ## Version Management: Version.compare_versions() ### Description Compare version strings. ### Method Signature `def compare_versions(self, current: str, target: str, beta: bool) -> int:` ### Returns - `0`: Versions are up to date. - `1`: An update is available. - `-1`: An error occurred during comparison. ### Example ```python version = Version(manager) state = version.compare_versions("1.6", target, False) # state: 0=ok, 1=update available, -1=error ``` ``` -------------------------------- ### DetailPage Constructor Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Initializes the DetailPage class, which is responsible for fetching HTML content from Kuaishou work URLs with retry logic and automatic cookie updates. ```APIDOC ## DetailPage Constructor ### Description Initializes the DetailPage class, which is responsible for fetching HTML content from Kuaishou work URLs with retry logic and automatic cookie updates. ### Method `def __init__(self, manager: Manager) -> None:` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **manager** (Manager) - Required - Manager instance ### Example ```python detail_page = DetailPage(manager) ``` ``` -------------------------------- ### Handle Extractor Run Failures Gracefully Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Demonstrates how to handle potential failures during the extraction process. The `run` method returns an empty dictionary on error and logs warnings without raising exceptions. ```python def run(self, html: str, id_: str, web: bool) -> dict: # Returns empty dict {} on any error # Logs warnings to console # Never raises exceptions result = extractor.run(html, "id123", web=True) if not result: print("Extraction failed") ``` -------------------------------- ### Initialize Examiner Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Instantiate the Examiner class with a Manager instance. The manager provides necessary HTTP client and header configurations. ```python examiner = Examiner(manager) ``` -------------------------------- ### Version.get_target_version Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Asynchronously fetches the latest version of the software from GitHub releases. ```APIDOC ## Version Management: Version.get_target_version() ### Description Fetches latest version from GitHub releases. ### Method Signature `async def get_target_version(self) -> str | None:` ### Example ```python version = Version(manager) target = await version.get_target_version() ``` ``` -------------------------------- ### HTTP Headers Constants Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Provides default user agent and HTTP header templates for making requests. Includes headers for general HTML acceptance and JSON content. ```python PC_USERAGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)..." PC_PAGE_HEADERS = { "Accept": "text/html,application/xhtml+xml...", "Accept-Language": "zh-CN,zh;q=0.9", ... } PC_DATA_HEADERS = { "Content-Type": "application/json", ... } ``` -------------------------------- ### Resolve Short URL Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Use this cURL command to resolve a shortened Kuaishou URL to its full video details. ```bash curl -X POST http://localhost:5557/share \ -H "Content-Type: application/json" \ -d '{"text": "https://www.kuaishou.com/f/abc123"}' ``` -------------------------------- ### Namespace Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Provides safe navigation of nested objects using dot notation, with fallback to a default value if any part of the chain is missing. ```APIDOC ## Class: Namespace ### Description Provides safe navigation of nested objects using dot notation, with fallback to a default value if any part of the chain is missing. ### Methods #### safe_extract(data, attribute_chain, default="") Safely navigates nested attributes in an object or dictionary. - **data** - Required - The object or dictionary to navigate. - **attribute_chain** (str) - Required - A dot-separated string representing the path to the desired attribute. - **default** - Optional - Default: `""` - The value to return if the attribute chain is not found. **Returns:** The extracted value or the default value. #### object_extract(data, path) Extracts a value from an object hierarchy. - **data** - Required - The object to extract from. - **path** (str) - Required - The path to the desired value. **Returns:** The extracted value. #### generate_data_object(data) Converts a dictionary into a SimpleNamespace object for attribute-style access. - **data** (dict) - Required - The dictionary to convert. **Returns:** A SimpleNamespace object. ``` -------------------------------- ### POST /share Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md Resolves Kuaishou short URLs to their full work links. It can handle multiple URLs within a single request and supports optional proxy configuration. ```APIDOC ## POST /share ### Description Resolve short URLs to full work links. ### Method POST ### Endpoint /share ### Parameters #### Request Body - **text** (string) - Required - Text containing one or more short URLs. - **proxy** (string) - Optional - HTTP/HTTPS proxy server URL for resolution. ### Request Example ```json { "text": "https://www.kuaishou.com/f/abcdef123", "proxy": "" } ``` ### Response #### Success Response (200) - **message** (string) - Status message: "请求重定向链接成功!" (success) or "请求重定向链接失败!" (failure). - **urls** (array[string] | null) - Array of resolved full URLs, or null if resolution failed. - **params** (object) - Echo of request parameters. - **params.text** (string) - Original input text. - **params.proxy** (string) - Proxy used (if any). - **time** (string) - Server response time "YYYY-MM-DD HH:MM:SS". #### Response Example ```json { "message": "请求重定向链接成功!", "urls": [ "https://www.kuaishou.com/short-video/abc123", "https://www.kuaishou.com/short-video/xyz789" ], "params": { "text": "https://www.kuaishou.com/f/abc123 https://v.kuaishou.com/xyz789", "proxy": "" }, "time": "2024-01-15 14:35:42" } ``` ``` -------------------------------- ### Run Examiner to Extract User URLs and IDs Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Use the Examiner's run method to extract Kuaishou user profile URLs and their corresponding user IDs. Specify type_='user'. ```python users = await examiner.run( "Profile: https://www.kuaishou.com/profile/xyz789", type_="user" ) # Returns: [("https://www.kuaishou.com/profile/xyz789", "xyz789")] ``` -------------------------------- ### ColorConsole Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Provides rich-based console output with support for colored and formatted text. It includes methods for printing general text, prompts, warnings, errors, and info messages. ```APIDOC ## Class: ColorConsole ### Description Provides rich-based console output with support for colored and formatted text. It includes methods for printing general text, prompts, warnings, errors, and info messages. ### Constructor - **beta** (bool) - Optional - Default: `False` - Whether to mark output as beta version ### Methods #### print(text: str, style: str = "") Prints formatted text to console. - **text** (str) - Required - Text to print - **style** (str) - Optional - Default: `""` - Rich style (color, bold, etc.) **Available Styles:** - `MASTER`: "bold magenta" - `PROMPT`: "cyan" - `GENERAL`: "white" - `PROGRESS`: "blue" - `ERROR`: "bold red" - `WARNING`: "bold yellow" - `INFO`: "bold cyan" #### input(prompt: str = "") Prompts user for input with styling. - **prompt** (str) - Optional - Default: `""` - Prompt text **Returns:** str — User input #### warning(text: str) Prints warning message in yellow. #### error(text: str) Prints error message in red. #### info(text: str) Prints info message in cyan. ``` -------------------------------- ### Extract Work Metadata Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Use this cURL command to extract detailed metadata for a specific Kuaishou short video using its URL. ```bash curl -X POST http://localhost:5557/detail/ \ -H "Content-Type: application/json" \ -d '{"text": "https://www.kuaishou.com/short-video/abc123"}' ``` -------------------------------- ### Progress (Rich) Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Provides visual progress bars for TUI (Text User Interface) mode using the Rich library. ```APIDOC ## Progress Tracking: Progress (Rich) ### Description Visual progress bars for TUI mode. ### Usage ```python from rich.progress import Progress with Progress() as progress: task = progress.add_task("Downloading", total=100) progress.update(task, advance=10) ``` ``` -------------------------------- ### POST /detail/ Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md Extracts work metadata from a Kuaishou work URL. It can automatically extract URLs from text and fetches details like title, duration, download URLs, and author information. ```APIDOC ## POST /detail/ ### Description Extract work metadata from URL. ### Method POST ### Endpoint /detail/ ### Parameters #### Request Body (The request body schema is not explicitly defined in the source, but it is expected to contain URL information.) ### Response #### Success Response (The success response model 'ResponseModel' is mentioned but not detailed in the source.) ``` -------------------------------- ### Examiner.run() Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Processes text containing URLs, resolves short links to full URLs, and validates them by type. It can extract work URLs, user URLs with IDs, or raw URLs. ```APIDOC ## Examiner.run() ### Description Processes text containing URLs, resolves short links to full URLs, and validates them by type. It can extract work URLs, user URLs with IDs, or raw URLs. ### Method `async def run(self, text: str, type_: str = "detail", proxy: str = "") -> list[str] | list[tuple[str, str]]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **text** (str) - Required - Text possibly containing URLs - **type_** (str) - Optional - Default: "detail" - URL type: "detail", "user", or "" (raw) - **proxy** (str) - Optional - Default: "" - Optional proxy for short URL resolution ### Returns - For type_="detail": `list[str]` — List of validated work URLs - For type_="user": `list[tuple[str, str]]` — List of (profile_url, user_id) tuples - For type_="": `list[str]` — Raw URLs split by whitespace ### Throws - ValueError if type_ is invalid - Exceptions from HTTP requests (wrapped by decorators) ### Example ```python # Extract work URLs urls = await examiner.run( "Check this: https://www.kuaishou.com/short-video/abc123", type_="detail" ) # Returns: ["https://www.kuaishou.com/short-video/abc123"] # Extract user URLs with IDs users = await examiner.run( "Profile: https://www.kuaishou.com/profile/xyz789", type_="user" ) # Returns: [("https://www.kuaishou.com/profile/xyz789", "xyz789")] # Raw URL extraction urls = await examiner.run("https://a.com https://b.com", type_="") # Returns: ["https://a.com", "https://b.com"] ``` ``` -------------------------------- ### Print Formatted Text with ColorConsole Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Prints text to the console with specified Rich styles for colors and formatting. Use predefined styles like MASTER, PROMPT, ERROR, etc. ```python console.print("Welcome!", style=MASTER) console.print("Input: ", style=PROMPT) console.print("Error occurred!", style=ERROR) ``` -------------------------------- ### Console Output with Color Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Utilizes the `ColorConsole` class to output messages with different severity levels (ERROR, WARNING, INFO) and associated colors to the console. ```python from source.tools import ColorConsole, ERROR, WARNING, INFO console = ColorConsole() console.error("Fatal error") console.warning("Warning message") console.info("Info message") ``` -------------------------------- ### Error Handling Pattern Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Illustrates a common error handling pattern using try-except blocks for CacheError and general exceptions. ```python try: result = await method() except CacheError as e: print(f"Cache error: {e.message}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### beautify_string Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Formats a string for display, including truncation and adding an ellipsis if necessary. ```APIDOC ## String Utilities: beautify_string() ### Description Formats string for display (ellipsis, truncation). ### Usage ```python beautiful = beautify_string("Very long description", max_length=10) # Returns: "Very long..." ``` ``` -------------------------------- ### API Endpoints Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md The Kuaishou Downloader API exposes several endpoints for interacting with the service. These include redirecting to GitHub, resolving short URLs, and extracting detailed metadata for works. ```APIDOC ## GET / ### Description Redirects the user to the project's GitHub page. ### Method GET ### Endpoint / ## POST /share ### Description Resolves short URLs into their full, accessible versions. ### Method POST ### Endpoint /share ### Request Body - **text** (string) - Required - The short URL or text containing a short URL. - **proxy** (string) - Optional - The proxy to use for the request. ### Response #### Success Response (200) - **message** (string) - Status message. - **urls** (array) - An array of resolved URLs. - **params** (object) - The parameters used in the request. - **time** (string) - The timestamp of the response. ## POST /detail/ ### Description Extracts detailed metadata for a given work using its URL or text containing a URL. ### Method POST ### Endpoint /detail/ ### Request Body - **text** (string) - Required - The URL or text containing the URL of the work. - **cookie** (string) - Optional - Browser cookies to use for the request. - **proxy** (string) - Optional - The proxy to use for the request. ### Response #### Success Response (200) - **message** (string) - Status message. - **params** (object) - The parameters used in the request. - **data** (object) - The metadata of the work. - **time** (string) - The timestamp of the response. ``` -------------------------------- ### Extract Parameters from App/Redirect Work URL Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Use extract_params to parse a Kuaishou app or redirect work URL and retrieve its parameters. Returns (is_web, user_id, detail_id). ```python web, uid, did = examiner.extract_params( "https://chenzhongtech.com/fw/photo?userId=user1&photoId=photo1" ) # Returns: (False, "user1", "photo1") ``` -------------------------------- ### Resolve Kuaishou Short URLs to Full Links Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md Use this POST endpoint to resolve Kuaishou short URLs to their full work links. It supports resolving multiple URLs from a single text input and can optionally use a proxy server. ```json { "text": "string", "proxy": "string" } ``` ```json { "text": "https://www.kuaishou.com/f/abcdef123", "proxy": "" } ``` ```json { "text": "Check these: https://www.kuaishou.com/f/abc123 and https://v.kuaishou.com/xyz789", "proxy": "" } ``` ```json { "text": "https://v.kuaishou.com/abc123", "proxy": "http://proxy.example.com:8080" } ``` ```json { "message": "请求重定向链接成功!", "urls": [ "https://www.kuaishou.com/short-video/abc123", "https://www.kuaishou.com/short-video/xyz789" ], "params": { "text": "https://www.kuaishou.com/f/abc123 https://v.kuaishou.com/xyz789", "proxy": "" }, "time": "2024-01-15 14:35:42" } ``` ```json { "message": "请求重定向链接失败!", "urls": null, "params": { "text": "invalid text", "proxy": "" }, "time": "2024-01-15 14:35:42" } ``` ```json { "detail": [ { "type": "missing", "loc": ["body", "text"], "msg": "Field required", "input": {} } ] } ``` -------------------------------- ### ShortUrl Request Model Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Defines the structure for resolving short URLs. It accepts text containing URLs and an optional proxy. ```json { "text": "url_or_text_with_urls", "proxy": "optional_proxy" } ``` -------------------------------- ### time_conversion() Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Converts a duration in milliseconds into a standard "HH:MM:SS" time format. ```APIDOC ## time_conversion() ### Description Converts milliseconds to "HH:MM:SS" format. ### Method `staticmethod` ### Parameters #### Path Parameters - **time_ms** (int) - Required - Duration in milliseconds ### Returns `str` — Duration in "HH:MM:SS" format (zero-padded) ### Example ```python duration = APIExtractor.time_conversion(125000) # Returns: "00:02:05" duration = APIExtractor.time_conversion(3661000) # Returns: "01:01:01" ``` ``` -------------------------------- ### Run Examiner to Extract Work URLs Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Use the Examiner's run method to extract and validate Kuaishou work URLs from a given text. Specify type_='detail' for work URLs. ```python urls = await examiner.run( "Check this: https://www.kuaishou.com/short-video/abc123", type_="detail" ) # Returns: ["https://www.kuaishou.com/short-video/abc123"] ``` -------------------------------- ### DetailModel Request Model Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Defines the structure for requesting metadata of a single work. It accepts a URL or text containing a URL, and optionally cookies and proxy information. ```json { "text": "url_or_text_with_url", "cookie": "optional_cookies", "proxy": "optional_proxy" } ``` -------------------------------- ### Custom CacheError Exception Handling Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Demonstrates how to catch and handle a custom `CacheError` exception, printing its message. This is useful for specific error scenarios in cache operations. ```python from source.module.error import CacheError try: await cache_operation() except CacheError as e: print(f"Cache error: {e.message}") ``` -------------------------------- ### Beautify String Utility Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Formats a string for display by adding an ellipsis and truncating if it exceeds a maximum length. Ideal for user-facing text. ```python beautiful = beautify_string("Very long description", max_length=10) # Returns: "Very long..." ``` -------------------------------- ### FakeProgress Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md A dummy progress object that does nothing, suitable for server environments where visual progress bars are not needed. ```APIDOC ## Progress Tracking: FakeProgress ### Description Dummy progress object for server mode (no visual output). ### Usage ```python progress = FakeProgress() with progress: # Does nothing, used in API server mode pass ``` ``` -------------------------------- ### wait Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Pauses execution for a random duration between 0 and 1 second to avoid detection and rate limiting. ```APIDOC ## Sleep with Randomization: wait() ### Description Sleeps 0-1 seconds randomly to avoid detection and rate limiting. ### Method Signature `async def wait() -> None:` ### Example ```python async def fetch_multiple(urls): for url in urls: await fetch(url) await wait() # Random delay between requests ``` ``` -------------------------------- ### Fake Progress Indicator Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md A dummy progress object used in server mode where visual output is not needed. It acts as a placeholder for progress tracking. ```python progress = FakeProgress() with progress: # Does nothing, used in API server mode pass ``` -------------------------------- ### Run Examiner for Raw URL Extraction Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Use the Examiner's run method to extract raw URLs from text without validation. Specify type_="" for raw URL extraction. ```python urls = await examiner.run("https://a.com https://b.com", type_="") # Returns: ["https://a.com", "https://b.com"] ``` -------------------------------- ### format_date() Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Converts a Unix millisecond timestamp into a human-readable date string based on a specified format. ```APIDOC ## format_date() ### Description Converts Unix millisecond timestamp to formatted date string. ### Method `staticmethod` ### Parameters #### Path Parameters - **timestamp** (int) - Required - Unix timestamp in milliseconds - **format_** (str) - Required - Python strftime format string ### Returns `str` — Formatted date string, or "unknown" if timestamp <= 0 ### Example ```python date_str = APIExtractor.format_date(1704067200000, "%Y-%m-%d_%H:%M:%S") # Returns: "2024-01-01_08:00:00" date_str = APIExtractor.format_date(0, "%Y-%m-%d") # Returns: "unknown" ``` ``` -------------------------------- ### trim_string Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Removes leading and trailing whitespace from a string. ```APIDOC ## String Utilities: trim_string() ### Description Removes leading/trailing whitespace. ### Usage ```python trimmed = trim_string(" text ") # Returns: "text" ``` ``` -------------------------------- ### Configure CORS Support with FastAPI Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md CORS is not enabled by default. Use the FastAPI CORSMiddleware to allow cross-origin requests by specifying allowed origins, methods, and headers. ```python from fastapi.middleware.cors import CORSMiddleware api.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) ``` -------------------------------- ### Work Metadata Dictionary Structure Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Defines the structure of a dictionary containing detailed metadata for a Kuaishou work, including ID, type, title, author information, download URLs, and engagement metrics. ```json { "detailID": "work_id", "photoType": "视频|图片", "caption": "work_title", "authorID": "author_id", "name": "author_nickname", "download": ["file_urls"], "timestamp": "YYYY-MM-DD_HH:MM:SS", "duration": "HH:MM:SS", "coverUrl": "cover_image_url", "viewCount": 12345, "commentCount": 50, "shareCount": 25, "realLikeCount": 500, "userSex": "男|女|未知" } ``` -------------------------------- ### Randomized Sleep Utility Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Implements a randomized sleep function to avoid detection and rate limiting. Use this between requests to introduce natural delays. ```python async def wait() -> None: # Sleeps 0-1 seconds randomly async def fetch_multiple(urls): for url in urls: await fetch(url) await wait() # Random delay between requests ``` -------------------------------- ### Trim String Utility Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Removes leading and trailing whitespace from a string. Ensures clean string data. ```python trimmed = trim_string(" text ") # Returns: "text" ``` -------------------------------- ### Rich Progress Bar Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Visual progress bars for TUI mode using the Rich library. Use this to provide visual feedback during long-running operations. ```python with Progress(...) as progress: task = progress.add_task("Downloading", total=100) progress.update(task, advance=10) ``` -------------------------------- ### Cleaner Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Sanitizes text to be used as filenames or identifiers by removing invalid characters. ```APIDOC ## Class: Cleaner ### Description Sanitizes text to be used as filenames or identifiers by removing invalid characters. ### Methods #### filter_name(name: str, default: str = "") Removes invalid characters from a string. - **name** (str) - Required - The string to sanitize. - **default** (str) - Optional - Default: `""` - The default value to return if the sanitized string is empty. **Returns:** str — The sanitized string or the default value. ``` -------------------------------- ### Truncate String Utility Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Truncates a given string to a specified maximum length. Useful for displaying long strings in limited space. ```python truncated = truncate_string("Long text", max_length=5) # Returns: "Long " ``` -------------------------------- ### generate_data_object() Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Transforms a dictionary into a SimpleNamespace object, enabling attribute-style access to dictionary keys. ```APIDOC ## generate_data_object() ### Description Converts dict to SimpleNamespace for attribute-style access. ### Method `staticmethod` ### Parameters #### Path Parameters - **data** (dict) - Required - Dictionary to convert ### Returns `SimpleNamespace | list[SimpleNamespace]` — Object(s) with attribute access ### Example ```python data = {"name": "John", "age": 30} obj = APIExtractor.generate_data_object(data) print(obj.name) # "John" print(obj.age) # 30 ``` ``` -------------------------------- ### Extract Parameters from Web Work URL Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Use extract_params to parse a Kuaishou web work URL and retrieve its parameters. Returns (is_web, user_id, detail_id). ```python web, uid, did = examiner.extract_params("https://www.kuaishou.com/short-video/abc123") # Returns: (True, "", "abc123") ``` -------------------------------- ### ResponseModel Structure Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Represents a standard API response, including a status message, request parameters, work metadata, and the timestamp of the response. ```json { "message": "status_message", "params": {request_params}, "data": {work_metadata}, "time": "YYYY-MM-DD HH:MM:SS" } ``` -------------------------------- ### Convert Milliseconds to HH:MM:SS Format Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Converts a duration in milliseconds into a zero-padded string representing hours, minutes, and seconds. Useful for displaying video or audio lengths. ```python @staticmethod def time_conversion(time_ms: int) -> str: # ... implementation details ... duration = APIExtractor.time_conversion(125000) # Returns: "00:02:05" (125 seconds = 2 min 5 sec) duration = APIExtractor.time_conversion(3661000) # Returns: "01:01:01" (1 hour 1 min 1 sec) ``` -------------------------------- ### Console Styles Constants Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Defines constants for console text styles using Rich. These are used for consistent formatting of output messages. ```python MASTER = "bold magenta" # Main titles PROMPT = "cyan" # User prompts GENERAL = "white" # General text PROGRESS = "blue" # Progress indicators ERROR = "bold red" # Error messages WARNING = "bold yellow" # Warnings INFO = "bold cyan" # Information ``` -------------------------------- ### safe_extract() Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Safely extracts data from a nested SimpleNamespace object using a dot-separated attribute chain, with support for array indexing and a default fallback value. ```APIDOC ## safe_extract() ### Description Safely navigates nested object attributes with support for array indexing. Returns default value if any level is missing. ### Method `staticmethod` ### Parameters #### Path Parameters - **data** (SimpleNamespace) - Required - Object to extract from - **attribute_chain** (str) - Required - Dot-separated path: "level1.level2.level3[0].level4" - **default** (Any) - Optional - Value to return if path doesn't exist. Defaults to "" ### Returns Value at path, or default if missing ### Supports - Nested attributes: "photo.userName" - Array indexing: "urls[0]" - Combined: "data.items[2].name" ### Example ```python # Deep extraction with default name = APIExtractor.safe_extract(data, "photo.user.name", default="Unknown") # Array indexing first_url = APIExtractor.safe_extract(data, "urls[0]", default="") # Complex path value = APIExtractor.safe_extract( data, "results[0].metadata.tags[1].name", default="N/A" ) ``` ``` -------------------------------- ### Extract Parameters from Invalid URL Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Demonstrates the behavior of extract_params when given an invalid URL. It returns (None, "", ""). ```python web, uid, did = examiner.extract_params("https://invalid.com/path") # Returns: (None, "", "") ``` -------------------------------- ### Decorator-Based Request Error Handling Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Applies decorators for automatic retries on transient errors (`retry_request`) and error logging without raising exceptions (`capture_error_request`). Use this for robust network requests. ```python from source.tools import retry_request, capture_error_request @retry_request # Auto-retries on transient errors @capture_error_request # Logs errors, doesn't raise async def fetch(url): pass result = await fetch(url) # Never raises, returns None on error ``` -------------------------------- ### Format Unix Timestamp to Date String Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Converts a Unix millisecond timestamp into a human-readable date string based on a specified format. Returns 'unknown' for invalid (non-positive) timestamps. ```python @staticmethod def format_date( timestamp: int, format_: str, ) -> str: # ... implementation details ... date_str = APIExtractor.format_date(1704067200000, "%Y-%m-%d_%H:%M:%S") # Returns: "2024-01-01_08:00:00" date_str = APIExtractor.format_date(0, "%Y-%m-%d") # Returns: "unknown" ``` -------------------------------- ### Convert Dictionary to SimpleNamespace Object Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Transforms a dictionary into a SimpleNamespace object, allowing access to dictionary keys as object attributes. This simplifies accessing nested data. ```python @staticmethod def generate_data_object(data: dict) -> SimpleNamespace | list[SimpleNamespace]: # ... implementation details ... data = {"name": "John", "age": 30} obj = APIExtractor.generate_data_object(data) print(obj.name) # "John" print(obj.age) # 30 ``` -------------------------------- ### Mapping.update_cache Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Updates the cache with an author ID to nickname mapping. ```APIDOC ## Author Cache Management: Mapping.update_cache() ### Description Updates cache for author ID → nickname mapping. ### Method Signature `async def update_cache(self, author_id: str, nickname: str) -> None:` ### Example ```python mapping = Mapping(manager, database) await mapping.update_cache("user_123", "MyCreator") ``` ``` -------------------------------- ### Retry Failed HTTP Requests Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Decorator that automatically retries asynchronous HTTP requests upon network errors with exponential backoff. It does not retry on HTTP status errors. ```python @retry_request async def fetch_data(url: str) -> dict: response = await client.get(url) response.raise_for_status() return response.json() ``` -------------------------------- ### retry_request Decorator Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md A decorator that automatically retries failed HTTP requests with exponential backoff. It handles network issues but not HTTP status errors. ```APIDOC ## Decorator: @retry_request ### Description Automatically retries failed HTTP requests with exponential backoff. It handles network issues but not HTTP status errors. ### Behavior - Retries on `RequestError` (network issues). - Does NOT retry on `HTTPStatusError` (e.g., 404, 403). - Uses exponential backoff (1s, 2s, 4s, 8s...). - Maximum retries are determined by `manager.max_retry` (default: 5). ``` -------------------------------- ### Examiner.extract_params() Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/link-processing.md Extracts work/user parameters from a complete URL. It routes to the appropriate parser based on the provided type. ```APIDOC ## Examiner.extract_params() ### Description Extracts work/user parameters from a complete URL. Routes to appropriate parser by type. ### Method `def extract_params(self, url: str, type_: str = "detail") -> tuple[bool | None, str, str]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **url** (str) - Required - Complete URL - **type_** (str) - Optional - Default: "detail" - Parameter type to extract ### Returns For work URLs: `(is_web, user_id, detail_id)` tuple where: - **is_web** (`bool | None`) — True for web URLs, False for app URLs, None if parsing failed - **user_id** (`str`) — Kuaishou user ID (empty for web-only URLs) - **detail_id** (`str`) — Work/photo ID ### Throws - ValueError if type_ is invalid ### Example ```python # Web URL web, uid, did = examiner.extract_params("https://www.kuaishou.com/short-video/abc123") # Returns: (True, "", "abc123") # App/Redirect URL web, uid, did = examiner.extract_params( "https://chenzhongtech.com/fw/photo?userId=user1&photoId=photo1" ) # Returns: (False, "user1", "photo1") # Invalid URL web, uid, did = examiner.extract_params("https://invalid.com/path") # Returns: (None, "", "") ``` ``` -------------------------------- ### UrlResponse Structure Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/REFERENCE-GUIDE.md Represents an API response specifically for URL resolution, including a status message, resolved URLs, request parameters, and the timestamp. ```json { "message": "status_message", "urls": ["resolved_urls"], "params": {request_params}, "time": "YYYY-MM-DD HH:MM:SS" } ``` -------------------------------- ### Sanitize Text for Filenames with Cleaner Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Filters a given string to remove invalid characters, making it suitable for use as a filename or identifier. Returns a default value if the sanitized string is empty. ```python cleaner = Cleaner() cleaned = cleaner.filter_name("My@Video#Title") # Returns: "MyVideoTitle" ``` -------------------------------- ### truncate_string Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Truncates a given string to a specified maximum length. ```APIDOC ## String Utilities: truncate_string() ### Description Truncates string to max length. ### Usage ```python truncated = truncate_string("Long text", max_length=5) # Returns: "Long " ``` ``` -------------------------------- ### Standard Error Response Format Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/endpoints.md All error responses adhere to the Pydantic validation error format. This structure provides details about the type of error, its location, and a descriptive message. ```json { "detail": [ { "type": "error_type", "loc": ["field", "location"], "msg": "Error message", "input": {} } ] } ``` -------------------------------- ### capture_error_request Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md A decorator that logs errors encountered during request execution without raising exceptions, allowing the program to continue. ```APIDOC ## Decorator: @capture_error_request ### Description Logs errors and continues without raising exceptions. Catches all exceptions, logs to the console with WARNING style, returns None on error, and never raises exceptions. ### Usage ```python @capture_error_request async def safe_fetch(url: str) -> str | None: # Returns None on any error pass result = await safe_fetch(url) if result is None: print("Failed, but didn't raise") ``` ``` -------------------------------- ### Capture Error Request Decorator Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Logs errors and continues without raising exceptions. Returns None on error. Use this decorator to wrap asynchronous functions that might fail but should not halt execution. ```python @retry_request @capture_error_request async def safe_fetch(url: str) -> str | None: # Returns None on any error after retries pass result = await safe_fetch(url) if result is None: print("Failed, but didn't raise") ``` ```python @capture_error_request async def fetch(url): # Errors logged, returns None pass ``` -------------------------------- ### retry_request Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md A decorator that retries a function call if it encounters transient errors, up to a maximum number of retries. ```APIDOC ## Error Handling Utilities: retry_request ### Description Decorator that retries on transient errors. ### Usage ```python @retry_request async def fetch(url): # Retries up to max_retry times pass ``` ``` -------------------------------- ### Retry Request Decorator Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/tools-utilities.md Decorator that retries a function call on transient errors. Use this to make network requests or other operations more resilient. ```python @retry_request async def fetch(url): # Retries up to max_retry times pass ``` -------------------------------- ### Safely Extract Nested Data with Default Value Source: https://github.com/joeanamier/ks-downloader/blob/master/_autodocs/api-reference/extractors.md Safely retrieves data from nested objects or lists using a dot-separated attribute chain, returning a specified default value if the path does not exist. Supports attribute access and array indexing. ```python @staticmethod def safe_extract( data: SimpleNamespace, attribute_chain: str, default: str | int | list | dict | SimpleNamespace = "", ) -> Any: # ... implementation details ... # Deep extraction with default name = APIExtractor.safe_extract(data, "photo.user.name", default="Unknown") # Array indexing first_url = APIExtractor.safe_extract(data, "urls[0]", default="") # Complex path value = APIExtractor.safe_extract( data, "results[0].metadata.tags[1].name", default="N/A" ) ```