### MediaService usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-media.md Shows how to import MediaService, get the singleton instance, and print the download directory. ```python from src.web.services.media_service import MediaService service = MediaService.get_instance() print(service.get_download_dir()) ``` -------------------------------- ### Usage example for ConfigManager get_instance, get_settings, update_settings Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-core-config.md Shows how to get the singleton, modify settings, update them, and observe auto-synced cookies. ```python manager = ConfigManager.get_instance() s = manager.get_settings() s.path = "./Downloaded/" s.raw_cookie = "msToken=abc; ttwid=123" updated = manager.update_settings(s) print(updated.cookies) # {"msToken": "abc", "ttwid": "123"} (auto-synced) ``` -------------------------------- ### Environment Setup with pip Source: https://github.com/datnndd/douyin-download/blob/main/README.md Use traditional pip to create a virtual environment and install dependencies from requirements.txt. ```bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Get TaskManager instance and list tasks Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-task-manager.md Example of obtaining the singleton and listing all tasks. ```python manager = TaskManager.get_instance() print(manager.list_tasks()) ``` -------------------------------- ### Launch the Web UI Source: https://github.com/datnndd/douyin-download/blob/main/README.md Start the web interface using uv. ```bash uv run python webui.py ``` -------------------------------- ### Usage example for download_with_resume Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-download.md Example of using `download_with_resume` to download a video file. It creates a `Download` instance with one thread, calls the method with a URL, destination path, and description, and prints the result. ```python from pathlib import Path from src.douyin.download import Download dl = Download(thread=1) ok = dl.download_with_resume( "https://v3-web.douyinvod.com/.../index.m3u8.mp4", Path("./Downloads/clip.mp4"), "clip", worker_id=1, ) print("ok:", ok) ``` -------------------------------- ### Environment Setup with uv Source: https://github.com/datnndd/douyin-download/blob/main/README.md Use uv to automatically create a virtual environment and synchronize dependencies. ```bash uv sync ``` -------------------------------- ### Example usage of DouyinClient Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Shows how to load configuration from a YAML file, set the link and mode, and run the client to process the link. ```python from douyinCommand import Config, DouyinClient cfg = Config.from_yaml("config.yaml") cfg.link = ["https://www.douyin.com/user/MS4wLjABAAAAm..."] cfg.mode = ["post"] cfg.number = {"post": 3} client = DouyinClient(cfg) client.process_all() ``` -------------------------------- ### main() Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/webui-launcher.md Parses command-line arguments and starts the uvicorn server for the Web UI. Optionally opens the browser and handles startup errors. ```APIDOC ## main() ### Description Parses command-line arguments and starts the uvicorn server for the Web UI. Optionally opens the browser and handles startup errors. ### Method Function call ### Endpoint N/A (Python function) ### Parameters #### Command-line Arguments - **--host** (str) - Optional - Host interface to bind. Default: 127.0.0.1 - **--port** (int) - Optional - Port to listen on. Default: 8000 - **--reload** (flag) - Optional - Enable uvicorn hot reloading for development. Default: off - **--no-browser** (flag) - Optional - Do not automatically open browser on startup. Default: off ### Request Example ```bash uv run python webui.py --port 8080 --host 0.0.0.0 --no-browser ``` ### Response #### Success Response - **Exit code**: 0 on clean Ctrl+C; 1 on startup failure. #### Response Example No response body. ``` -------------------------------- ### GET /{full_path:path} (SPA fallback) Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Serves static files from the frontend dist directory. If the requested path is a file, it is served; otherwise, the index.html is returned. Paths starting with 'api' or 'ws' are rejected with 404. ```APIDOC ## GET /{full_path:path} ### Description Serves static files from the frontend dist directory. If the requested path is a file, it is served; otherwise, the index.html is returned. Paths starting with 'api' or 'ws' are rejected with 404. ### Method GET ### Endpoint /{full_path:path} ### Parameters #### Path Parameters - **full_path** (string) - Required - The path to the requested resource. ### Response #### Success Response (200) - Serves the file if it exists, otherwise returns index.html. #### Error Response (404) - Returns {"detail":"Not Found"} for paths starting with 'api' or 'ws'. ``` -------------------------------- ### getKey usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-api.md Example usage of getKey with a user URL. It checks that the key_type is 'user' and prints the extracted sec_uid. ```python key_type, key = api.getKey("https://www.douyin.com/user/MS4wLjABAAAAm...") if key_type != "user": raise SystemExit("unexpected") print(key) # MS4wLjABAAAAm... ``` -------------------------------- ### awemeDownload with cancellation and error handling Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-download.md Example demonstrating how to use a cancel_event and progress_callback with awemeDownload, and how to collect failed aweme IDs. ```python import threading failures = [] dl = Download(progress_callback=lambda e: print(e["event"], e["filename"])) cancel = threading.Event() try: ok = dl.awemeDownload(aweme, Path("./Downloads"), cancel_event=cancel) if not ok: failures.append(aweme["aweme_id"]) except Exception: failures.append(aweme["aweme_id"]) print("failed items:", failures) ``` -------------------------------- ### Usage example for resolve_download_path and get_cookie_header Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-core-config.md Shows how to resolve the download directory and retrieve the active cookie header. ```python from src.web.core.config import ConfigManager cm = ConfigManager.get_instance() download_dir = cm.resolve_download_path() print(download_dir) # /workspace/.../Downloaded print(cm.get_cookie_header()) # 'msToken=...; ttwid=...' or '' ``` -------------------------------- ### Deploy n8n Automation on VPS Source: https://github.com/datnndd/douyin-download/blob/main/README.md Commands to initialize the environment variables and start the containerized services using Docker Compose. ```bash cd n8n/setup cp .env.example .env # Edit your domain name, credentials, and volume paths in .env docker compose up -d --build ``` -------------------------------- ### Basic usage of userDownload Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-download.md Example showing how to download a list of awemes using userDownload, with a thread count of 8 and folderstyle enabled. ```python posts = api.getUserInfoApi("MS4wLjABAAAAm...", mode="post", number=5) dl = Download(thread=8, folderstyle=True) ok = dl.userDownload(posts, Path("./Downloads/user_x")) print("all succeeded:", ok) ``` -------------------------------- ### Opening a folder Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-media.md Example of calling open_folder with a subpath and printing the returned success flag, path, and error message. ```python ok, path, err = service.open_folder("user_x") print(ok, path, err) ``` -------------------------------- ### str2bool usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/common-utils.md Shows how to use utils.str2bool with various inputs. Note that unrecognized values return True (fail-open). ```python utils.str2bool("t") # True utils.str2bool("False") # False utils.str2bool("maybe") # True (fail-open) ``` -------------------------------- ### main() -> None Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Entry point that sets up logging, parses arguments, loads configuration from args or YAML, validates it, and runs the DouyinClient process_all. ```APIDOC ## main() -> None ### Description Entry point that sets up logging, parses arguments, loads configuration from args or YAML, validates it, and runs the DouyinClient process_all. ### Returns - None ### Example ```python def main() -> None: setup_logging() parser = build_parser() args = parser.parse_args() cfg = Config.from_args(args) if args.cmd else Config.from_yaml(args.config) if not cfg.validate_and_prepare(): return client = DouyinClient(cfg) client.process_all() ``` ``` -------------------------------- ### DouyinClient.__init__ Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Initializes a DouyinClient instance with the provided configuration, setting up the API client and downloader. ```APIDOC ## DouyinClient.__init__ ### Description Initializes a DouyinClient instance with the provided configuration, setting up the API client and downloader. ### Method Constructor ### Signature `__init__(self, cfg: Config)` ### Parameters - **cfg** (Config) - Required - Configuration object containing database, cookie, thread, music, cover, avatar, json, and folderstyle settings. ### Behavior - Creates a `DouyinApi` instance with database path and cookie. - Creates a `Download` instance with thread, music, cover, avatar, json, and folderstyle settings. - If a cookie is provided, sets the `Cookie` header in `douyin_headers`. ### Example ```python from douyinCommand import Config, DouyinClient cfg = Config.from_yaml("config.yaml") client = DouyinClient(cfg) ``` ``` -------------------------------- ### GET /api/tasks/{task_id} Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Gets details of a specific download task. ```APIDOC ## GET /api/tasks/{task_id} ### Description Gets details of a specific download task. ### Method GET ### Endpoint /api/tasks/{task_id} ### Parameters #### Path Parameters - **task_id** (string) - Required - The ID of the task. ### Response #### Success Response (200) - **task** (object) - Task details. #### Response Example { "task": {} } ``` -------------------------------- ### getUserAllMixInfoApi usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-api.md Example usage of getUserAllMixInfoApi: iterates over the returned mapping and prints each mix_id and name. ```python mixes = api.getUserAllMixInfoApi(sec_uid) for mix_id, name in mixes.items(): print(mix_id, name) ``` -------------------------------- ### getShareLink usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-api.md Example usage of getShareLink with a typical share text. It prints the extracted clean URL. ```python from src.douyin.douyinapi import DouyinApi api = DouyinApi(database_path=None) url = api.getShareLink("【抖音】 https://v.douyin.com/iWhQezyaUco/ 复制此方法") print(url) # https://v.douyin.com/iWhQezyaUco/ ``` -------------------------------- ### replaceStr usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/common-utils.md Shows how to use utils.replaceStr to sanitize a filename. The example asserts the output for a sample input. ```python from src.common import utils assert utils.replaceStr("My<>Video: 抖音 下载.mp4") == "MyVideo抖音下载mp4" ``` -------------------------------- ### main function implementation Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Entry point that sets up logging, parses arguments, loads config from args or YAML, validates, and processes all items via DouyinClient. ```python def main() -> None: setup_logging() parser = build_parser() args = parser.parse_args() cfg = Config.from_args(args) if args.cmd else Config.from_yaml(args.config) if not cfg.validate_and_prepare(): return client = DouyinClient(cfg) client.process_all() ``` -------------------------------- ### safe_name usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Shows how to use safe_name to sanitize a string with a fallback. The example asserts that '抖音 测试' becomes '抖音测试'. ```python from douyinCommand import safe_name assert safe_name("抖音 测试", "unknown") == "抖音测试" ``` -------------------------------- ### clearDict usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-result.md Example of clearing a Result's awemeDict and asserting that nested statistics and images are reset to empty values. ```python r.clearDict(r.awemeDict) assert r.awemeDict["statistics"]["digg_count"] == "" assert r.awemeDict["images"] == [] ``` -------------------------------- ### Database.__init__(path) Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-database.md Initializes a Database instance with the given SQLite file path. Runs connection preparation and migration. ```APIDOC ## Database.__init__(path) ### Description Initializes a Database instance with the given SQLite file path. Runs connection preparation and migration. ### Method Constructor ### Signature ```python def __init__(self, path: str = "data.db") -> None: ``` ### Parameters - **path** (str) - Optional - Default: "data.db" - SQLite file path ### Behavior Runs `_prepare()` (pragmas) then `migrate()`. Also usable as a context manager. ### Example ```python with Database("scrape.db") as db: db.upsert_user({"sec_uid": "abc", "nickname": "x"}) # connection closed on exit ``` ``` -------------------------------- ### getShareLink error handling example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-api.md Example of catching the IndexError thrown by getShareLink when the input is empty. The error message is 'Input text is empty'. ```python try: api.getShareLink(" ") except IndexError as e: print(f"caught: {e}") # caught: Input text is empty ``` -------------------------------- ### Basic usage of awemeDownload Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-download.md Example showing how to create a Download instance and download a single aweme using awemeDownload. It uses a filename template and enables folderstyle, resjson, and media options. ```python from pathlib import Path from src.douyin.download import Download from src.douyin.douyinapi import DouyinApi api = DouyinApi(database_path=None) aweme = api.getAwemeInfoApi("7345492945006595379") dl = Download(thread=4, music=True, cover=True, avatar=True, resjson=True, folderstyle=True, filename_template="{date}_{title}_{id}") ok = dl.awemeDownload(aweme, Path("./Downloads")) print("downloaded:", ok) ``` -------------------------------- ### Config.validate_and_prepare() -> bool Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Validates the configuration and prepares the output path. Returns True if usable, False otherwise. ```APIDOC ## Config.validate_and_prepare ### Description Validates the configuration: errors (log only) when `link` is empty, clamps `thread` to 5 when not a positive integer, and resolves and creates the output `path`. Returns `True` when the configuration is usable. ### Method Instance method ### Signature `validate_and_prepare() -> bool` ### Parameters None ### Returns - **bool** - `True` if the configuration is valid and prepared, `False` otherwise. ### Example ```python from douyinCommand import Config cfg = Config.from_yaml("config.yaml") cfg.link = ["https://v.douyin.com/iWhQezyaUco/"] assert cfg.validate_and_prepare() is True ``` ``` -------------------------------- ### parse_url error handling example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-douyin.md Example of handling exceptions from parse_url, including DouyinInvalidUrlError, DouyinNotFoundError, and DouyinUpstreamError. Demonstrates safe parsing with error messages. ```python from src.web.services.douyin_service import ( DouyinService, DouyinInvalidUrlError, DouyinNotFoundError, DouyinUpstreamError, ) async def safe_parse(text: str): try: return await DouyinService().parse_url(text) except DouyinInvalidUrlError as e: print("400 - bad link:", e) except DouyinNotFoundError as e: print("404 - deleted/private:", e) except DouyinUpstreamError as e: print("502 - upstream block/ratelimit:", e) asyncio.run(safe_parse("https://v.douyin.com/nonexistent/")) ``` -------------------------------- ### parse_url usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-douyin.md Example of using the async parse_url method to parse a Douyin share URL and print the result. Requires asyncio and DouyinService. ```python import asyncio from src.web.services.douyin_service import DouyinService async def main(): service = DouyinService() resp = await service.parse_url("https://v.douyin.com/iWhQezyaUco/ 复制") print(resp.key_type, resp.key, resp.content_type) print(resp.preview.title if resp.preview else None) asyncio.run(main()) ``` -------------------------------- ### Customize Web UI Launch Source: https://github.com/datnndd/douyin-download/blob/main/README.md Launch the web interface with custom host, port, and browser settings. ```bash uv run python webui.py --port 8080 --host 0.0.0.0 --no-browser ``` -------------------------------- ### upsert_aweme usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-database.md Example usage of upsert_aweme with a sample aweme dict, then retrieving the row with get_aweme and printing the desc field by name (sqlite3.Row). ```python db.upsert_aweme( {"aweme_id": "123", "awemeType": 0, "author": {"sec_uid": "abc", "nickname": "n"}, "desc": "hello", "images": [], "video": {"play_addr": {"uri": "u", "url_list": ["https://..."]}}, "music": {}, "mix_info": {}, "statistics": {"digg_count": 5}}, is_user_post=True, as_like_for_sec_uid="viewer_1", ) row = db.get_aweme("123") print(row["desc"]) # sqlite3.Row by name ``` -------------------------------- ### ABogus.__init__(platform=None) Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/common-abogus.md Initializes the ABogus instance. If platform is provided, a randomized browser fingerprint is generated; otherwise, a fixed fingerprint is used. ```APIDOC ## Constructor: ABogus.__init__(platform=None) ### Description Initializes the ABogus instance. If platform is provided, a randomized browser fingerprint is generated via generate_browser_info(platform); otherwise, a fixed fingerprint is used. ### Method Constructor ### Parameters - **platform** (str | None) - Optional - Browser platform token. When provided, a randomized fingerprint is generated; when None, the fixed fingerprint "1536|742|1536|864|0|0|0|0|1536|864|1536|864|1536|742|24|24|MacIntel" is used. ### State Built - chunk, size, reg (SM3 init vector), ua_code (fixed 32-byte Chrome UA hash), browser, browser_len, browser_code ### Example ```python from src.common.abogus import ABogus abogus = ABogus() abogus_win = ABogus(platform="Win32") ``` ``` -------------------------------- ### getMusicInfo usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-api.md Example usage of getMusicInfo: retrieves up to 3 tracks for a given music ID and prints the first 40 characters of each track's description and its play count. ```python tracks = api.getMusicInfo("7101234567890123456", count=35, number=3) for t in tracks: print(t["desc"][:40], t["statistics"]["play_count"]) ``` -------------------------------- ### main() argument parser setup Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/webui-launcher.md Defines CLI arguments for the launcher: `--host`, `--port`, `--reload`, and `--no-browser`. Defaults are 127.0.0.1, 8000, off, and off respectively. ```python def main(): parser = argparse.ArgumentParser( description="Douyin Web Downloader - Modern Editorial Edition Launcher" ) parser.add_argument( "--host", type=str, default="127.0.0.1", help="Host interface to bind (default: 127.0.0.1)", ) parser.add_argument( "--port", type=int, default=8000, help="Port to listen on (default: 8000)", ) parser.add_argument( "--reload", action="store_true", help="Enable uvicorn hot reloading for development", ) parser.add_argument( "--no-browser", action="store_true", help="Do not automatically open browser on startup", ) ``` -------------------------------- ### POST /api/parse example request Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Example JSON body for the parse endpoint. The url field is required and can be raw share text or URL; cookie is optional and overrides the default cookie header. ```json { "url": "https://v.douyin.com/abc123/", "cookie": "msToken=...; ttwid=..." } ``` -------------------------------- ### get_download_items usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-douyin.md Shows how to create a DownloadRequest and call get_download_items to resolve download items for a user's posts. Prints the number of resolved items. ```python from src.web.core.schemas import DownloadRequest req = DownloadRequest(url="https://www.douyin.com/user/abc", key_type="user", key="abc", modes=["post"], number={"post": 20}) items = service.get_download_items(req) print("resolved:", len(items)) ``` -------------------------------- ### GET /api/health Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Health check endpoint. ```APIDOC ## GET /api/health ### Description Health check endpoint. ### Method GET ### Endpoint /api/health ### Response #### Success Response (200) - **status** (string) - Health status. #### Response Example { "status": "ok" } ``` -------------------------------- ### Using Config.from_yaml and validate_and_prepare Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/cli-douyin-command.md Shows how to load a Config from a YAML file, set the link, and validate it. The validate_and_prepare method returns True when the config is usable, and logs errors (returning False) when link is empty or thread is invalid. ```python from douyinCommand import Config cfg = Config.from_yaml("config.yaml") cfg.link = ["https://v.douyin.com/iWhQezyaUco/"] assert cfg.validate_and_prepare() is True ``` -------------------------------- ### GET /api/media Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Lists media files. ```APIDOC ## GET /api/media ### Description Lists media files. ### Method GET ### Endpoint /api/media ### Response #### Success Response (200) - **media** (array) - List of media files. #### Response Example { "media": [] } ``` -------------------------------- ### MediaService.__init__ Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/web-services-media.md Constructor for MediaService. Accepts an optional ConfigManager instance, falling back to the singleton instance if not provided. ```APIDOC ## MediaService.__init__ ### Description Initializes a new MediaService instance. If no ConfigManager is provided, the singleton instance is used. ### Method Constructor ### Signature ```python def __init__(self, config_manager: Optional[ConfigManager] = None): ``` ### Parameters - **config_manager** (ConfigManager | None) - Optional - Falls back to `ConfigManager.get_instance()` ### Example ```python from src.web.services.media_service import MediaService service = MediaService() ``` ``` -------------------------------- ### GET /api/settings Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Retrieves current settings. ```APIDOC ## GET /api/settings ### Description Retrieves current settings. ### Method GET ### Endpoint /api/settings ### Response #### Success Response (200) - **settings** (object) - Current settings. #### Response Example { "settings": {} } ``` -------------------------------- ### GET /api/tasks Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Lists all download tasks. ```APIDOC ## GET /api/tasks ### Description Lists all download tasks. ### Method GET ### Endpoint /api/tasks ### Response #### Success Response (200) - **tasks** (array) - List of task objects. #### Response Example { "tasks": [] } ``` -------------------------------- ### GET /api/media/download/{path:path} Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Downloads a media file. ```APIDOC ## GET /api/media/download/{path:path} ### Description Downloads a media file. ### Method GET ### Endpoint /api/media/download/{path:path} ### Parameters #### Path Parameters - **path** (string) - Required - Path to the media file. ### Response #### Success Response (200) - **file** (binary) - The media file. #### Response Example (binary data) ``` -------------------------------- ### Terminal usage examples Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/webui-launcher.md Typical commands to launch the Web UI. The first uses defaults (http://127.0.0.1:8000) and opens the browser; the second binds to all interfaces on port 8080 without opening a browser. ```bash cd douyin-download uv run python webui.py # http://127.0.0.1:8000 + browser uv run python webui.py --port 8080 --host 0.0.0.0 --no-browser ``` -------------------------------- ### GET /api/media/stream/{path:path} Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Streams a media file. ```APIDOC ## GET /api/media/stream/{path:path} ### Description Streams a media file. ### Method GET ### Endpoint /api/media/stream/{path:path} ### Parameters #### Path Parameters - **path** (string) - Required - Path to the media file. ### Response #### Success Response (200) - **file** (binary) - The media file stream. #### Response Example (binary data) ``` -------------------------------- ### Download.__init__ Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-download.md Constructor for the Download class. Initializes download options, concurrency, progress callback, cancellation token, and filename template. ```APIDOC ## Download.__init__ ### Description Initializes the Download engine with configurable options for concurrency, media types, progress reporting, cancellation, and filename templating. ### Method Constructor ### Signature ```python def __init__( self, thread=5, music=True, cover=True, avatar=True, resjson=True, folderstyle=True, progress_callback: Optional[Callable[[Dict[str, Any]], None]] = None, cancel_event: Optional[threading.Event] = None, filename_template: Optional[str] = None, ): ``` ### Parameters - **thread** (int) - Optional, default `5` - Max concurrent worker threads (also the per-aweme task pool size) - **music** (bool) - Optional, default `True` - Download background music as `*_music_{title}.mp3` - **cover** (bool) - Optional, default `True` - Download video cover as `*_cover.jpeg` (video posts only) - **avatar** (bool) - Optional, default `True` - Download creator avatar as `*_avatar.jpeg` - **resjson** (bool) - Optional, default `True` - Save `*_result.json` metadata file - **folderstyle** (bool) - Optional, default `True` - `True` = folder per item; `False` = all files in one folder - **progress_callback** (Callable[[dict], None] | None) - Optional, default `None` - Telemetry hook; receives dicts described below - **cancel_event** (threading.Event | None) - Optional, default `None` - Cooperative cancellation token - **filename_template** (str | None) - Optional, default `None` - Token template; `None` ⇒ default `{digg_count:09d}likes_{create_time}_{desc}` ### Instance Attributes - `retry_times` = 5 - `chunk_size` = 8192 - `timeout` = 60 - `_tls` = threading.local() (per-thread sessions with `Retry(total=2, backoff_factor=0.2)` and 100-connection pools) ### Progress-callback Contract Events emitted by `download_with_resume`: | event | payload keys | |---|---| | `"file_start"` | `worker_id`, `filepath`, `filename`, `chunk_bytes=0`, `downloaded_bytes`, `total_bytes`, `desc` | | `"chunk"` | same + throttled to ~250 ms intervals (`time.monotonic` diff ≥ 0.25) | | `"file_complete"` | same, final byte counts | | `"item_complete"` | `item_index`, `item_total` (emitted by `userDownload`) | ``` -------------------------------- ### GET /api/stream Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md Global SSE stream for task updates. ```APIDOC ## GET /api/stream ### Description Global SSE stream for task updates. ### Method GET ### Endpoint /api/stream ### Response #### Success Response (200) - **event** (string) - Event type. - **data** (object) - Event data. #### Response Example { "event": "task_update", "data": {} } ``` -------------------------------- ### Incremental dedup usage example Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/api-reference/douyin-database.md Usage example for incremental dedup: creates a Database instance, checks if a post is known, and upserts a batch from mix/music endpoints. sqlite3 errors propagate from tx() after rollback; callers catch broad Exception. close() never raises. ```python from src.douyin.database import Database db = Database("scrape.db") print("known:", db.has_user_post("sec_uid_1", "7345492945006595379")) # Upsert a batch fetched from mix/music endpoints (not author posts): db.bulk_upsert_awemes(items, is_user_posts=False) ``` -------------------------------- ### GET /api/tasks/{task_id}/stream Source: https://github.com/datnndd/douyin-download/blob/main/_autodocs/endpoints.md SSE stream for a specific task. ```APIDOC ## GET /api/tasks/{task_id}/stream ### Description SSE stream for a specific task. ### Method GET ### Endpoint /api/tasks/{task_id}/stream ### Parameters #### Path Parameters - **task_id** (string) - Required - The ID of the task. ### Response #### Success Response (200) - **event** (string) - Event type. - **data** (object) - Event data. #### Response Example { "event": "task_update", "data": {} } ```