Created
September 1, 2026 14:59
-
-
Save qianlifeng/c6b0e26b0db6efa9e9e9cd6a9252e08b to your computer and use it in GitHub Desktop.
Wox.Plugin.Script.VideoDownloader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # { | |
| # "Id": "b8e3d1a4-6c2f-4a9e-8d71-3f5c0a2e9b16", | |
| # "Name": "i18n:plugin_name", | |
| # "Author": "qianlifeng", | |
| # "Version": "1.0.0", | |
| # "MinWoxVersion": "2.0.0", | |
| # "Description": "i18n:plugin_description", | |
| # "Website": "https://github.com/yt-dlp/yt-dlp", | |
| # "Icon": "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><defs><linearGradient id=\"vdIconBg\" x1=\"6\" y1=\"2\" x2=\"44\" y2=\"46\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7c3aed\"/><stop offset=\".55\" stop-color=\"#e11d48\"/><stop offset=\"1\" stop-color=\"#fb923c\"/></linearGradient></defs><rect width=\"48\" height=\"48\" rx=\"13\" fill=\"url(#vdIconBg)\"/><rect x=\"8\" y=\"9\" width=\"32\" height=\"22\" rx=\"5\" fill=\"#fff7ed\"/><rect x=\"8\" y=\"9\" width=\"5\" height=\"22\" rx=\"2.5\" fill=\"#fbbf24\"/><circle cx=\"10.5\" cy=\"15\" r=\"1.2\" fill=\"#f97316\"/><circle cx=\"10.5\" cy=\"25\" r=\"1.2\" fill=\"#f97316\"/><polygon points=\"21,14 21,26 33,20\" fill=\"#e11d48\"/><circle cx=\"34\" cy=\"36.5\" r=\"8.4\" fill=\"#22d3ee\"/><path d=\"M34 31.6v8.4M30.2 36.6L34 40.8l3.8-4.2\" fill=\"none\" stroke=\"#0f172a\" stroke-width=\"2.3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>", | |
| # "TriggerKeywords": ["vd"], | |
| # "SupportedOS": ["windows", "linux", "darwin"], | |
| # "Commands": [ | |
| # { "Command": "update", "Description": "i18n:cmd_update" } | |
| # ], | |
| # "Features": [ | |
| # { "Name": "debounce", "Params": { "IntervalMs": 400 } }, | |
| # { "Name": "ignoreAutoScore" } | |
| # ], | |
| # "SettingDefinitions": [ | |
| # { | |
| # "Type": "head", | |
| # "Value": { "Content": "i18n:section_download" } | |
| # }, | |
| # { | |
| # "Type": "textbox", | |
| # "Value": { | |
| # "Key": "download_path", | |
| # "Label": "i18n:setting_download_path", | |
| # "Tooltip": "i18n:setting_download_path_tip", | |
| # "DefaultValue": "", | |
| # "Style": { "Width": 420 } | |
| # }, | |
| # "IsPlatformSpecific": true | |
| # }, | |
| # { | |
| # "Type": "select", | |
| # "Value": { | |
| # "Key": "sorting_order", | |
| # "Label": "i18n:setting_sorting", | |
| # "DefaultValue": "resolution", | |
| # "Options": [ | |
| # { "Label": "i18n:sort_resolution", "Value": "resolution" }, | |
| # { "Label": "i18n:sort_size", "Value": "size" }, | |
| # { "Label": "i18n:sort_bitrate", "Value": "bitrate" }, | |
| # { "Label": "i18n:sort_fps", "Value": "fps" } | |
| # ] | |
| # } | |
| # }, | |
| # { | |
| # "Type": "select", | |
| # "Value": { | |
| # "Key": "preferred_video_format", | |
| # "Label": "i18n:setting_video_format", | |
| # "DefaultValue": "mp4", | |
| # "Options": [ | |
| # { "Label": "mp4", "Value": "mp4" }, | |
| # { "Label": "mkv", "Value": "mkv" }, | |
| # { "Label": "webm", "Value": "webm" }, | |
| # { "Label": "mov", "Value": "mov" } | |
| # ] | |
| # } | |
| # }, | |
| # { | |
| # "Type": "select", | |
| # "Value": { | |
| # "Key": "preferred_audio_format", | |
| # "Label": "i18n:setting_audio_format", | |
| # "DefaultValue": "mp3", | |
| # "Options": [ | |
| # { "Label": "mp3", "Value": "mp3" }, | |
| # { "Label": "m4a", "Value": "m4a" }, | |
| # { "Label": "opus", "Value": "opus" }, | |
| # { "Label": "flac", "Value": "flac" }, | |
| # { "Label": "wav", "Value": "wav" }, | |
| # { "Label": "aac", "Value": "aac" } | |
| # ] | |
| # } | |
| # }, | |
| # { | |
| # "Type": "checkbox", | |
| # "Value": { | |
| # "Key": "auto_open_folder", | |
| # "Label": "i18n:setting_auto_open", | |
| # "DefaultValue": "true" | |
| # } | |
| # }, | |
| # { | |
| # "Type": "checkbox", | |
| # "Value": { | |
| # "Key": "overwrite_existing_files", | |
| # "Label": "i18n:setting_overwrite", | |
| # "DefaultValue": "true" | |
| # } | |
| # }, | |
| # { | |
| # "Type": "head", | |
| # "Value": { "Content": "i18n:section_tools" } | |
| # }, | |
| # { | |
| # "Type": "textbox", | |
| # "Value": { | |
| # "Key": "ytdlp_path", | |
| # "Label": "i18n:setting_ytdlp_path", | |
| # "Tooltip": "i18n:setting_ytdlp_path_tip", | |
| # "DefaultValue": "", | |
| # "Style": { "Width": 420 } | |
| # }, | |
| # "IsPlatformSpecific": true | |
| # }, | |
| # { | |
| # "Type": "textbox", | |
| # "Value": { | |
| # "Key": "ffmpeg_path", | |
| # "Label": "i18n:setting_ffmpeg_path", | |
| # "Tooltip": "i18n:setting_ffmpeg_path_tip", | |
| # "DefaultValue": "", | |
| # "Style": { "Width": 420 } | |
| # }, | |
| # "IsPlatformSpecific": true | |
| # }, | |
| # { | |
| # "Type": "head", | |
| # "Value": { "Content": "i18n:section_cookies" } | |
| # }, | |
| # { | |
| # "Type": "checkbox", | |
| # "Value": { | |
| # "Key": "use_cookie_file", | |
| # "Label": "i18n:setting_use_cookies", | |
| # "DefaultValue": "false" | |
| # } | |
| # }, | |
| # { | |
| # "Type": "textbox", | |
| # "Value": { | |
| # "Key": "cookie_file_path", | |
| # "Label": "i18n:setting_cookie_path", | |
| # "Tooltip": "i18n:setting_cookie_path_tip", | |
| # "DefaultValue": "", | |
| # "Style": { "Width": 420 } | |
| # }, | |
| # "IsPlatformSpecific": true | |
| # }, | |
| # { | |
| # "Type": "head", | |
| # "Value": { "Content": "i18n:section_trim" } | |
| # }, | |
| # { | |
| # "Type": "select", | |
| # "Value": { | |
| # "Key": "trim_mode", | |
| # "Label": "i18n:setting_trim_mode", | |
| # "Tooltip": "i18n:setting_trim_mode_tip", | |
| # "DefaultValue": "off", | |
| # "Options": [ | |
| # { "Label": "i18n:trim_off", "Value": "off" }, | |
| # { "Label": "i18n:trim_post", "Value": "post" }, | |
| # { "Label": "i18n:trim_native", "Value": "native" } | |
| # ] | |
| # } | |
| # }, | |
| # { | |
| # "Type": "checkbox", | |
| # "Value": { | |
| # "Key": "delete_original_after_trim", | |
| # "Label": "i18n:setting_delete_original", | |
| # "DefaultValue": "false" | |
| # } | |
| # } | |
| # ], | |
| # "I18n": { | |
| # "en_US": { | |
| # "plugin_name": "Video Downloader", | |
| # "plugin_description": "Download videos and audio from 1000+ sites with yt-dlp", | |
| # "cmd_update": "Update the bundled or detected yt-dlp binary", | |
| # "section_download": "Download", | |
| # "section_tools": "Tools", | |
| # "section_cookies": "Cookies", | |
| # "section_trim": "Video trimming", | |
| # "setting_download_path": "Download folder", | |
| # "setting_download_path_tip": "Leave empty to use the user Downloads folder.", | |
| # "setting_sorting": "Sort formats by", | |
| # "setting_video_format": "Preferred video container", | |
| # "setting_audio_format": "Preferred audio format", | |
| # "setting_auto_open": "Open the download folder after success", | |
| # "setting_overwrite": "Overwrite existing files", | |
| # "setting_ytdlp_path": "yt-dlp path", | |
| # "setting_ytdlp_path_tip": "Optional. Leave empty to auto-detect or download yt-dlp.", | |
| # "setting_ffmpeg_path": "FFmpeg path", | |
| # "setting_ffmpeg_path_tip": "Optional. File or folder that contains ffmpeg.", | |
| # "setting_use_cookies": "Use a cookies.txt file", | |
| # "setting_cookie_path": "cookies.txt path", | |
| # "setting_cookie_path_tip": "Netscape-format cookies file for sites that require login.", | |
| # "setting_trim_mode": "Trim mode", | |
| # "setting_trim_mode_tip": "Use: vd <url> 1:00 2:30. Off ignores start/end times.", | |
| # "setting_delete_original": "Delete the original file after a successful trim", | |
| # "sort_resolution": "Resolution", | |
| # "sort_size": "File size", | |
| # "sort_bitrate": "Total bitrate", | |
| # "sort_fps": "FPS", | |
| # "trim_off": "Off", | |
| # "trim_post": "Download then trim", | |
| # "trim_native": "Native section download", | |
| # "hint_title": "Paste a video URL", | |
| # "hint_subtitle": "Download path: %s", | |
| # "hint_usage": "Example: vd https://youtu.be/xxxx", | |
| # "hint_trim": "Optional trim: vd <url> 1:00 2:30", | |
| # "invalid_url": "This does not look like a video URL", | |
| # "invalid_url_sub": "Use a full http(s) link, not just a domain.", | |
| # "missing_ytdlp": "yt-dlp is not installed", | |
| # "missing_ytdlp_sub": "Download it once, or set the path in plugin settings", | |
| # "download_ytdlp": "Download yt-dlp", | |
| # "open_ytdlp": "Open yt-dlp releases", | |
| # "missing_ffmpeg": "FFmpeg was not found", | |
| # "missing_ffmpeg_sub": "Audio conversion and some video remuxes need FFmpeg", | |
| # "open_ffmpeg": "Open FFmpeg install guide", | |
| # "cookie_error": "Cookie file setting needs attention", | |
| # "trim_disabled": "Video trimming is disabled", | |
| # "trim_disabled_sub": "Enable a trim mode in plugin settings first", | |
| # "fetching": "Fetching video information...", | |
| # "fetching_sub": "Wait a few seconds, then edit the query to refresh", | |
| # "fetch_error": "Could not extract video information", | |
| # "empty_formats": "No downloadable formats were found", | |
| # "best_video": "Best video quality", | |
| # "best_audio": "Best audio only", | |
| # "download": "Download", | |
| # "copy_url": "Copy URL", | |
| # "open_page": "Open page", | |
| # "open_folder": "Open download folder", | |
| # "update_ytdlp": "Update yt-dlp", | |
| # "update_ytdlp_sub": "Check for a newer yt-dlp release", | |
| # "updating": "Updating yt-dlp in a new terminal", | |
| # "downloading": "Starting download in a new terminal" | |
| # }, | |
| # "zh_CN": { | |
| # "plugin_name": "视频下载", | |
| # "plugin_description": "用 yt-dlp 从 1000+ 网站下载视频和音频", | |
| # "cmd_update": "更新已检测到的 yt-dlp", | |
| # "section_download": "下载", | |
| # "section_tools": "工具", | |
| # "section_cookies": "Cookies", | |
| # "section_trim": "视频裁剪", | |
| # "setting_download_path": "下载目录", | |
| # "setting_download_path_tip": "留空则使用用户 Downloads 目录。", | |
| # "setting_sorting": "格式排序方式", | |
| # "setting_video_format": "首选视频容器", | |
| # "setting_audio_format": "首选音频格式", | |
| # "setting_auto_open": "下载成功后打开目录", | |
| # "setting_overwrite": "覆盖已存在的文件", | |
| # "setting_ytdlp_path": "yt-dlp 路径", | |
| # "setting_ytdlp_path_tip": "可选。留空则自动检测或下载 yt-dlp。", | |
| # "setting_ffmpeg_path": "FFmpeg 路径", | |
| # "setting_ffmpeg_path_tip": "可选。填写 ffmpeg 可执行文件或其所在目录。", | |
| # "setting_use_cookies": "使用 cookies.txt", | |
| # "setting_cookie_path": "cookies.txt 路径", | |
| # "setting_cookie_path_tip": "Netscape 格式的 cookies 文件,用于需要登录的网站。", | |
| # "setting_trim_mode": "裁剪模式", | |
| # "setting_trim_mode_tip": "用法:vd <url> 1:00 2:30。关闭时忽略起止时间。", | |
| # "setting_delete_original": "裁剪成功后删除原文件", | |
| # "sort_resolution": "分辨率", | |
| # "sort_size": "文件大小", | |
| # "sort_bitrate": "总码率", | |
| # "sort_fps": "帧率", | |
| # "trim_off": "关闭", | |
| # "trim_post": "先下载再裁剪", | |
| # "trim_native": "仅下载指定片段", | |
| # "hint_title": "粘贴视频链接", | |
| # "hint_subtitle": "下载目录:%s", | |
| # "hint_usage": "例如:vd https://youtu.be/xxxx", | |
| # "hint_trim": "可选裁剪:vd <url> 1:00 2:30", | |
| # "invalid_url": "这不像是有效的视频链接", | |
| # "invalid_url_sub": "请使用完整的 http(s) 链接,而不是只有域名。", | |
| # "missing_ytdlp": "未检测到 yt-dlp", | |
| # "missing_ytdlp_sub": "可以一键下载,或在插件设置中指定路径", | |
| # "download_ytdlp": "下载 yt-dlp", | |
| # "open_ytdlp": "打开 yt-dlp 发布页", | |
| # "missing_ffmpeg": "未检测到 FFmpeg", | |
| # "missing_ffmpeg_sub": "音频转换和部分视频封装需要 FFmpeg", | |
| # "open_ffmpeg": "打开 FFmpeg 安装说明", | |
| # "cookie_error": "Cookie 文件设置有问题", | |
| # "trim_disabled": "视频裁剪已关闭", | |
| # "trim_disabled_sub": "请先在插件设置中启用裁剪模式", | |
| # "fetching": "正在获取视频信息...", | |
| # "fetching_sub": "请稍等几秒,然后改一下查询内容以刷新", | |
| # "fetch_error": "无法解析视频信息", | |
| # "empty_formats": "没有找到可下载的格式", | |
| # "best_video": "最佳画质", | |
| # "best_audio": "最佳音频", | |
| # "download": "下载", | |
| # "copy_url": "复制链接", | |
| # "open_page": "打开页面", | |
| # "open_folder": "打开下载目录", | |
| # "update_ytdlp": "更新 yt-dlp", | |
| # "update_ytdlp_sub": "检查并更新 yt-dlp", | |
| # "updating": "正在新终端中更新 yt-dlp", | |
| # "downloading": "正在新终端中开始下载" | |
| # } | |
| # } | |
| # } | |
| """ | |
| Wox Python script plugin for downloading videos and audio. | |
| Inspired by Flow Launcher AnyVideo Downloader, powered by yt-dlp. | |
| Script plugins are short-lived (10s), so format probing is cached on disk | |
| and actual downloads run in a new console window. | |
| """ | |
| from __future__ import annotations | |
| import datetime | |
| import hashlib | |
| import json | |
| import os | |
| import shlex | |
| import shutil | |
| import subprocess | |
| import sys | |
| import time | |
| import uuid | |
| from typing import Any, List, TypedDict | |
| from urllib.parse import urlparse | |
| CREATE_NEW_CONSOLE = 0x00000010 | |
| CREATE_NO_WINDOW = 0x08000000 | |
| CACHE_SCHEMA = 1 | |
| CACHE_TTL_SECONDS = 30 * 60 | |
| ERROR_CACHE_TTL_SECONDS = 60 | |
| FETCH_WAIT_SECONDS = 8 | |
| MAX_FORMAT_RESULTS = 40 | |
| YTDLP_RELEASE_URL = "https://github.com/yt-dlp/yt-dlp/releases/latest" | |
| YTDLP_EXE_URL = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe" | |
| FFMPEG_GUIDE_URL = "https://github.com/yt-dlp/FFmpeg-Builds#ffmpeg-static-builds" | |
| PLUGIN_ICON = ( | |
| "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" " | |
| "viewBox=\"0 0 48 48\"><defs><linearGradient id=\"vdIconBg\" x1=\"6\" y1=\"2\" " | |
| "x2=\"44\" y2=\"46\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7c3aed\"/>" | |
| "<stop offset=\".55\" stop-color=\"#e11d48\"/><stop offset=\"1\" stop-color=\"#fb923c\"/>" | |
| "</linearGradient></defs><rect width=\"48\" height=\"48\" rx=\"13\" fill=\"url(#vdIconBg)\"/>" | |
| "<rect x=\"8\" y=\"9\" width=\"32\" height=\"22\" rx=\"5\" fill=\"#fff7ed\"/>" | |
| "<rect x=\"8\" y=\"9\" width=\"5\" height=\"22\" rx=\"2.5\" fill=\"#fbbf24\"/>" | |
| "<circle cx=\"10.5\" cy=\"15\" r=\"1.2\" fill=\"#f97316\"/>" | |
| "<circle cx=\"10.5\" cy=\"25\" r=\"1.2\" fill=\"#f97316\"/>" | |
| "<polygon points=\"21,14 21,26 33,20\" fill=\"#e11d48\"/>" | |
| "<circle cx=\"34\" cy=\"36.5\" r=\"8.4\" fill=\"#22d3ee\"/>" | |
| "<path d=\"M34 31.6v8.4M30.2 36.6L34 40.8l3.8-4.2\" fill=\"none\" stroke=\"#0f172a\" " | |
| "stroke-width=\"2.3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>" | |
| ) | |
| VIDEO_ICON = "emoji:🎬" | |
| AUDIO_ICON = "emoji:🎵" | |
| WARN_ICON = "emoji:⚠️" | |
| DOWNLOAD_ICON = "emoji:⬇️" | |
| UPDATE_ICON = "emoji:🔄" | |
| FOLDER_ICON = "emoji:📂" | |
| COPY_ICON = "emoji:📋" | |
| OPEN_ICON = "emoji:🔗" | |
| class WoxPluginBase: | |
| """Wox plugin base class for script plugins. Do not modify this class.""" | |
| class Preview(TypedDict, total=False): | |
| preview_type: str | |
| preview_data: str | |
| preview_properties: dict[str, str] | |
| class ActionItem(TypedDict, total=False): | |
| id: str | |
| name: str | |
| icon: str | |
| text: str | |
| url: str | |
| path: str | |
| message: str | |
| data: dict[str, str] | |
| class TailItem(TypedDict, total=False): | |
| id: str | |
| type: str | |
| text: str | |
| image: str | |
| contextData: dict[str, str] | |
| class QueryResult(TypedDict, total=False): | |
| title: str | |
| subtitle: str | |
| icon: str | |
| preview: WoxPluginBase.Preview | |
| tails: List[WoxPluginBase.TailItem] | |
| score: int | |
| actions: List[WoxPluginBase.ActionItem] | |
| def __init__(self): | |
| self.log_file_path = __file__ + ".log" | |
| def log(self, message: str) -> None: | |
| ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| message = f"[{ts}] {message}" | |
| if self.is_invoke_from_wox(): | |
| with open(self.log_file_path, "a", encoding="utf-8") as handle: | |
| handle.write(f"{message}\n") | |
| else: | |
| print(f"LOG: {message}") | |
| def is_invoke_from_wox(self) -> bool: | |
| return "WOX_PLUGIN_ID" in os.environ | |
| def _build_response(self, result: Any, request_id: Any) -> dict: | |
| return {"jsonrpc": "2.0", "result": result, "id": request_id} | |
| def _build_error_response( | |
| self, code: int, message: str, data: Any = None, request_id: Any = None | |
| ) -> dict: | |
| error = {"code": code, "message": message} | |
| if data is not None: | |
| error["data"] = data | |
| return {"jsonrpc": "2.0", "error": error, "id": request_id} | |
| def query( | |
| self, raw_query: str, trigger_keyword: str, command: str, search: str | |
| ) -> List[WoxPluginBase.QueryResult]: | |
| return [] | |
| def action(self, action_id: str, data: Any) -> None: | |
| return None | |
| def handle_query(self, params, request_id): | |
| results = self.query( | |
| params.get("raw_query", ""), | |
| params.get("trigger_keyword", ""), | |
| params.get("command", ""), | |
| params.get("search", ""), | |
| ) | |
| return self._build_response({"items": results}, request_id) | |
| def handle_action(self, params, request_id): | |
| self.action(params.get("id", ""), params.get("data", "")) | |
| return self._build_response({}, request_id) | |
| def run(self): | |
| if hasattr(sys.stdout, "reconfigure"): | |
| try: | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| except Exception: | |
| pass | |
| if self.is_invoke_from_wox(): | |
| try: | |
| stdin_text = sys.stdin.read() | |
| except Exception: | |
| return 1 | |
| else: | |
| print("Manual mode - please enter query:") | |
| query_input = input() | |
| stdin_text = ( | |
| '{"jsonrpc": "2.0", "method": "query", "params": {"search": "' | |
| + query_input.replace("\\", "\\\\").replace('"', '\\"') | |
| + '"}, "id": 1}' | |
| ) | |
| try: | |
| request = json.loads(stdin_text) | |
| except json.JSONDecodeError as exc: | |
| print( | |
| json.dumps( | |
| self._build_error_response(-32700, "Parse error", str(exc), None), | |
| ensure_ascii=False, | |
| ) | |
| ) | |
| return 1 | |
| if request.get("jsonrpc") != "2.0": | |
| print( | |
| json.dumps( | |
| self._build_error_response( | |
| -32600, "Invalid Request", None, request.get("id") | |
| ), | |
| ensure_ascii=False, | |
| ) | |
| ) | |
| return 1 | |
| method = request.get("method") | |
| params = request.get("params", {}) | |
| request_id = request.get("id") | |
| if method == "query": | |
| response = self.handle_query(params, request_id) | |
| elif method == "action": | |
| response = self.handle_action(params, request_id) | |
| else: | |
| response = self._build_error_response( | |
| -32601, | |
| "Method not found", | |
| f"Method '{method}' not supported", | |
| request_id, | |
| ) | |
| print(json.dumps(response, ensure_ascii=False)) | |
| return 0 | |
| def _setting(key: str, default: str = "") -> str: | |
| return os.environ.get(f"WOX_SETTING_{key.upper()}", default).strip() | |
| def _as_bool(value: str, default: bool = False) -> bool: | |
| if not value: | |
| return default | |
| return value.strip().lower() in {"1", "true", "yes", "on"} | |
| def _expand_path(path: str) -> str: | |
| if not path: | |
| return "" | |
| return os.path.abspath(os.path.expanduser(os.path.expandvars(path))) | |
| def _plugin_cache_dir() -> str: | |
| base = os.environ.get("WOX_DIRECTORY_USER_DATA") or os.path.join( | |
| os.path.expanduser("~"), ".wox", "wox-user" | |
| ) | |
| path = os.path.join(base, "cache", "video-downloader") | |
| os.makedirs(path, exist_ok=True) | |
| return path | |
| def _default_download_path() -> str: | |
| home = os.environ.get("USERPROFILE") or os.path.expanduser("~") | |
| downloads = os.path.join(home, "Downloads") | |
| return downloads if os.path.isdir(downloads) else home | |
| def _download_path() -> str: | |
| configured = _expand_path(_setting("download_path")) | |
| if configured and os.path.isdir(configured): | |
| return configured | |
| if configured: | |
| try: | |
| os.makedirs(configured, exist_ok=True) | |
| return configured | |
| except OSError: | |
| pass | |
| return _default_download_path() | |
| def _resolve_tool(configured: str, names: tuple[str, ...]) -> str: | |
| configured = _expand_path(configured) | |
| if configured: | |
| if os.path.isdir(configured): | |
| for name in names: | |
| for candidate in ( | |
| os.path.join(configured, name), | |
| os.path.join(configured, f"{name}.exe"), | |
| ): | |
| if os.path.isfile(candidate): | |
| return candidate | |
| if os.path.isfile(configured): | |
| return configured | |
| for name in names: | |
| found = shutil.which(name) | |
| if found: | |
| return found | |
| return "" | |
| def _cached_ytdlp_path() -> str: | |
| exe = "yt-dlp.exe" if os.name == "nt" else "yt-dlp" | |
| return os.path.join(_plugin_cache_dir(), exe) | |
| def _find_ytdlp() -> str: | |
| found = _resolve_tool(_setting("ytdlp_path"), ("yt-dlp", "yt-dlp.exe")) | |
| if found: | |
| return found | |
| cached = _cached_ytdlp_path() | |
| if os.path.isfile(cached): | |
| return cached | |
| home = os.path.expanduser("~") | |
| extras = ( | |
| os.path.join(home, "scoop", "shims", "yt-dlp.exe"), | |
| os.path.join(home, "scoop", "apps", "yt-dlp", "current", "yt-dlp.exe"), | |
| os.path.join(home, ".local", "bin", "yt-dlp"), | |
| ) | |
| for path in extras: | |
| if os.path.isfile(path): | |
| return path | |
| return "" | |
| def _find_ffmpeg() -> str: | |
| found = _resolve_tool(_setting("ffmpeg_path"), ("ffmpeg", "ffmpeg.exe")) | |
| if found: | |
| return found | |
| home = os.path.expanduser("~") | |
| extras = ( | |
| os.path.join(home, "scoop", "shims", "ffmpeg.exe"), | |
| os.path.join(home, "scoop", "apps", "ffmpeg", "current", "bin", "ffmpeg.exe"), | |
| ) | |
| for path in extras: | |
| if os.path.isfile(path): | |
| return path | |
| return "" | |
| def _ffmpeg_location(ffmpeg_path: str) -> str: | |
| if not ffmpeg_path: | |
| return "" | |
| if os.path.isdir(ffmpeg_path): | |
| return ffmpeg_path | |
| return os.path.dirname(ffmpeg_path) | |
| def _cookie_file() -> tuple[str, str]: | |
| if not _as_bool(_setting("use_cookie_file"), False): | |
| return "", "" | |
| path = _expand_path(_setting("cookie_file_path")) | |
| if not path: | |
| return "", "Cookie file support is enabled, but no cookies.txt path is configured." | |
| if not os.path.isfile(path): | |
| return "", f"Cookie file not found: {path}" | |
| return path, "" | |
| def _is_valid_url(url: str) -> bool: | |
| try: | |
| cleaned = url.strip() | |
| if not cleaned or any(char.isspace() for char in cleaned): | |
| return False | |
| parsed = urlparse(cleaned) | |
| except Exception: | |
| return False | |
| return parsed.scheme in {"http", "https"} and bool(parsed.netloc) | |
| def _has_extractable_target(url: str) -> bool: | |
| try: | |
| parsed = urlparse(url.strip()) | |
| except Exception: | |
| return False | |
| path = (parsed.path or "").strip("/") | |
| return bool(path or parsed.query or parsed.fragment) | |
| def _timestamp_seconds(token: str, allow_inf: bool = False) -> float | None: | |
| token = str(token or "").strip().lower() | |
| if token == "inf": | |
| return float("inf") if allow_inf else None | |
| if not token: | |
| return None | |
| parts = token.split(":") | |
| if len(parts) > 3: | |
| return None | |
| try: | |
| if len(parts) == 1: | |
| seconds = float(parts[0]) | |
| else: | |
| if any(part == "" for part in parts): | |
| return None | |
| if not all(part.isdigit() for part in parts[:-1]): | |
| return None | |
| seconds_part = float(parts[-1]) | |
| if seconds_part >= 60: | |
| return None | |
| if len(parts) == 2: | |
| seconds = int(parts[0]) * 60 + seconds_part | |
| else: | |
| minutes = int(parts[1]) | |
| if minutes >= 60: | |
| return None | |
| seconds = int(parts[0]) * 3600 + minutes * 60 + seconds_part | |
| except ValueError: | |
| return None | |
| return seconds if seconds >= 0 else None | |
| def _build_download_section(start_time: str, end_time: str) -> str: | |
| start_seconds = _timestamp_seconds(start_time) | |
| end_seconds = _timestamp_seconds(end_time, allow_inf=True) | |
| if start_seconds is None or end_seconds is None: | |
| return "" | |
| if end_seconds != float("inf") and end_seconds <= start_seconds: | |
| return "" | |
| return f"*{start_time}-{end_time}" | |
| def _parse_query_text(text: str) -> dict[str, str]: | |
| parts = str(text or "").strip().split() | |
| if len(parts) >= 3: | |
| section = _build_download_section(parts[-2], parts[-1]) | |
| if section: | |
| return { | |
| "url": " ".join(parts[:-2]), | |
| "section": section, | |
| "start": parts[-2].lower(), | |
| "end": parts[-1].lower(), | |
| } | |
| return {"url": str(text or "").strip(), "section": "", "start": "", "end": ""} | |
| def _numeric(value: Any, default: float | None = 0.0) -> float | None: | |
| if value is None: | |
| return default | |
| try: | |
| return float(value) | |
| except (TypeError, ValueError): | |
| return default | |
| def _format_resolution(item: dict[str, Any]) -> str: | |
| resolution = str(item.get("resolution") or "") | |
| if resolution and resolution not in {"unknown", "None"}: | |
| return resolution | |
| width = _numeric(item.get("width")) | |
| height = _numeric(item.get("height")) | |
| if width and height and width > 0 and height > 0: | |
| return f"{int(width)}x{int(height)}" | |
| if str(item.get("vcodec") or "") == "none": | |
| return "audio only" | |
| return "" | |
| def _is_media_format(item: dict[str, Any]) -> bool: | |
| ext = str(item.get("ext") or "").lower() | |
| protocol = str(item.get("protocol") or "").lower() | |
| note = str(item.get("format_note") or "").lower() | |
| if ext == "mhtml" or protocol == "mhtml" or "storyboard" in note: | |
| return False | |
| return not ( | |
| str(item.get("vcodec") or "") == "none" | |
| and str(item.get("acodec") or "") == "none" | |
| ) | |
| def _normalize_format(item: dict[str, Any], allow_unknown: bool = False) -> dict[str, Any] | None: | |
| format_id = str(item.get("format_id") or "").strip() | |
| if not format_id or not _is_media_format(item): | |
| return None | |
| resolution = _format_resolution(item) | |
| filesize = _numeric(item.get("filesize") or item.get("filesize_approx"), None) | |
| tbr = _numeric(item.get("tbr"), None) | |
| fps = _numeric(item.get("fps"), None) | |
| if not resolution and allow_unknown and item.get("url"): | |
| resolution = "unknown" | |
| if not resolution: | |
| return None | |
| if not allow_unknown and tbr is None and filesize is None: | |
| return None | |
| return { | |
| "format_id": format_id, | |
| "resolution": resolution, | |
| "filesize": filesize, | |
| "tbr": tbr, | |
| "fps": fps, | |
| "width": _numeric(item.get("width"), None), | |
| "height": _numeric(item.get("height"), None), | |
| "vcodec": item.get("vcodec"), | |
| "acodec": item.get("acodec"), | |
| "ext": item.get("ext"), | |
| } | |
| def _build_formats(info: dict[str, Any]) -> list[dict[str, Any]]: | |
| raw = info.get("formats") or [] | |
| if not isinstance(raw, list): | |
| raw = [] | |
| if not raw and info.get("format_id") and info.get("url"): | |
| raw = [info] | |
| formats: list[dict[str, Any]] = [] | |
| seen: set[tuple[Any, ...]] = set() | |
| for allow_unknown in (False, True): | |
| for item in raw: | |
| if not isinstance(item, dict): | |
| continue | |
| normalized = _normalize_format(item, allow_unknown=allow_unknown) | |
| if not normalized: | |
| continue | |
| key = ( | |
| normalized["format_id"], | |
| normalized["resolution"], | |
| normalized["tbr"], | |
| normalized["filesize"], | |
| normalized["fps"], | |
| ) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| formats.append(normalized) | |
| if formats: | |
| break | |
| return formats | |
| def _resolution_value(item: dict[str, Any]) -> tuple[int, int]: | |
| if item.get("resolution") == "audio only": | |
| return (0, 0) | |
| width = _numeric(item.get("width"), None) | |
| height = _numeric(item.get("height"), None) | |
| if width and height: | |
| return (int(width), int(height)) | |
| text = str(item.get("resolution") or "") | |
| if "x" in text.lower(): | |
| try: | |
| left, right = text.lower().split("x", 1) | |
| return (int(left), int(right)) | |
| except ValueError: | |
| return (0, 0) | |
| return (0, 0) | |
| def _sort_formats(formats: list[dict[str, Any]], order: str) -> list[dict[str, Any]]: | |
| if order == "size": | |
| return sorted( | |
| formats, | |
| key=lambda item: (item.get("filesize") is None, -(_numeric(item.get("filesize")) or 0)), | |
| ) | |
| if order == "bitrate": | |
| return sorted(formats, key=lambda item: _numeric(item.get("tbr")) or 0, reverse=True) | |
| if order == "fps": | |
| return sorted( | |
| formats, | |
| key=lambda item: (item.get("fps") is None, -(_numeric(item.get("fps"), float("-inf")) or 0)), | |
| ) | |
| return sorted(formats, key=_resolution_value, reverse=True) | |
| def _format_selector(item: dict[str, Any], is_audio: bool) -> str: | |
| format_id = str(item.get("format_id") or "") | |
| if is_audio or "+" in format_id: | |
| return format_id | |
| acodec = str(item.get("acodec") or "").lower() | |
| if acodec in {"", "none"}: | |
| return f"{format_id}+bestaudio" | |
| return format_id | |
| def _human_size(value: Any) -> str: | |
| size = _numeric(value, None) | |
| if not size or size <= 0: | |
| return "" | |
| mb = size / 1024 / 1024 | |
| if mb >= 1024: | |
| return f"{mb / 1024:.2f} GB" | |
| return f"{mb:.2f} MB" | |
| def _human_duration(value: Any) -> str: | |
| seconds = _numeric(value, None) | |
| if seconds is None or seconds < 0: | |
| return "" | |
| total = int(seconds) | |
| hours, remainder = divmod(total, 3600) | |
| minutes, secs = divmod(remainder, 60) | |
| if hours: | |
| return f"{hours}:{minutes:02d}:{secs:02d}" | |
| return f"{minutes}:{secs:02d}" | |
| def _cache_key(url: str) -> str: | |
| return hashlib.sha1(url.encode("utf-8")).hexdigest() | |
| def _info_cache_path(url: str) -> str: | |
| return os.path.join(_plugin_cache_dir(), f"info-{_cache_key(url)}.json") | |
| def _read_json(path: str) -> dict[str, Any] | None: | |
| try: | |
| with open(path, encoding="utf-8") as handle: | |
| data = json.load(handle) | |
| return data if isinstance(data, dict) else None | |
| except Exception: | |
| return None | |
| def _write_json(path: str, data: dict[str, Any]) -> None: | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| tmp = path + ".tmp" | |
| with open(tmp, "w", encoding="utf-8") as handle: | |
| json.dump(data, handle, ensure_ascii=False) | |
| os.replace(tmp, path) | |
| def _read_info_cache(url: str) -> dict[str, Any] | None: | |
| data = _read_json(_info_cache_path(url)) | |
| if not data or data.get("schema") != CACHE_SCHEMA or data.get("url") != url: | |
| return None | |
| fetched_at = _numeric(data.get("fetched_at"), 0) or 0 | |
| ttl = ERROR_CACHE_TTL_SECONDS if data.get("error") else CACHE_TTL_SECONDS | |
| if time.time() - fetched_at > ttl: | |
| return None | |
| return data | |
| def _compact_info(info: dict[str, Any]) -> dict[str, Any]: | |
| return { | |
| "title": info.get("title") or "Unknown Title", | |
| "thumbnail": info.get("thumbnail") or "", | |
| "duration": info.get("duration"), | |
| "uploader": info.get("uploader") or info.get("channel") or "", | |
| "webpage_url": info.get("webpage_url") or info.get("original_url") or "", | |
| "description": str(info.get("description") or "")[:400], | |
| "formats": info.get("formats") or [], | |
| "format_id": info.get("format_id"), | |
| "url": info.get("url"), | |
| "ext": info.get("ext"), | |
| "vcodec": info.get("vcodec"), | |
| "acodec": info.get("acodec"), | |
| "resolution": info.get("resolution"), | |
| "width": info.get("width"), | |
| "height": info.get("height"), | |
| "tbr": info.get("tbr"), | |
| "fps": info.get("fps"), | |
| "filesize": info.get("filesize"), | |
| "filesize_approx": info.get("filesize_approx"), | |
| } | |
| def _ytdlp_base_args(ytdlp: str, cookie_file: str = "") -> list[str]: | |
| args = [ | |
| ytdlp, | |
| "--no-playlist", | |
| "--no-warnings", | |
| "--skip-download", | |
| "--no-check-formats", | |
| "--socket-timeout", | |
| "20", | |
| "--retries", | |
| "2", | |
| ] | |
| if cookie_file: | |
| args += ["--cookies", cookie_file] | |
| if shutil.which("node"): | |
| args += ["--js-runtimes", "node"] | |
| ffmpeg = _find_ffmpeg() | |
| if ffmpeg: | |
| args += ["--ffmpeg-location", _ffmpeg_location(ffmpeg)] | |
| return args | |
| def _fetch_info_main(url: str, cookie_file: str = "") -> int: | |
| ytdlp = _find_ytdlp() | |
| cache_path = _info_cache_path(url) | |
| payload: dict[str, Any] = { | |
| "schema": CACHE_SCHEMA, | |
| "url": url, | |
| "fetched_at": time.time(), | |
| } | |
| if not ytdlp: | |
| payload["error"] = "yt-dlp is not installed" | |
| _write_json(cache_path, payload) | |
| return 1 | |
| command = _ytdlp_base_args(ytdlp, cookie_file) + ["-J", url] | |
| try: | |
| result = _run_hidden( | |
| command, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| timeout=90, | |
| ) | |
| if result.returncode != 0: | |
| message = (result.stderr or result.stdout or "yt-dlp failed").strip() | |
| payload["error"] = message.splitlines()[-1][:300] if message else "yt-dlp failed" | |
| _write_json(cache_path, payload) | |
| return 1 | |
| info = json.loads(result.stdout) | |
| if not isinstance(info, dict): | |
| payload["error"] = "Invalid yt-dlp JSON" | |
| _write_json(cache_path, payload) | |
| return 1 | |
| payload["info"] = _compact_info(info) | |
| _write_json(cache_path, payload) | |
| return 0 | |
| except Exception as exc: | |
| payload["error"] = str(exc) | |
| _write_json(cache_path, payload) | |
| return 1 | |
| def _no_window_kwargs() -> dict[str, Any]: | |
| """Hide console windows when launching helper processes on Windows.""" | |
| if os.name != "nt": | |
| return {} | |
| startupinfo = subprocess.STARTUPINFO() | |
| startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW | |
| startupinfo.wShowWindow = 0 | |
| return { | |
| "creationflags": getattr(subprocess, "CREATE_NO_WINDOW", CREATE_NO_WINDOW), | |
| "startupinfo": startupinfo, | |
| } | |
| def _hidden_python() -> str: | |
| """Prefer pythonw.exe on Windows so background work never opens a console.""" | |
| if os.name != "nt": | |
| return sys.executable | |
| folder, name = os.path.split(sys.executable) | |
| if name.lower() in {"python.exe", "python3.exe"}: | |
| pythonw = os.path.join(folder, "pythonw.exe") | |
| if os.path.isfile(pythonw): | |
| return pythonw | |
| return sys.executable | |
| def _run_hidden(args: list[str], **kwargs: Any) -> subprocess.CompletedProcess: | |
| merged = {**_no_window_kwargs(), **kwargs} | |
| return subprocess.run(args, **merged) | |
| def _spawn_hidden(args: list[str]) -> None: | |
| kwargs: dict[str, Any] = { | |
| "stdin": subprocess.DEVNULL, | |
| "stdout": subprocess.DEVNULL, | |
| "stderr": subprocess.DEVNULL, | |
| "close_fds": True, | |
| **_no_window_kwargs(), | |
| } | |
| if os.name != "nt": | |
| kwargs["start_new_session"] = True | |
| subprocess.Popen(args, **kwargs) | |
| def _spawn_visible(args: list[str]) -> None: | |
| """Open a real terminal for user-facing work on Windows, macOS, and Linux.""" | |
| if os.name == "nt": | |
| subprocess.Popen(args, creationflags=CREATE_NEW_CONSOLE, close_fds=True) | |
| return | |
| if sys.platform == "darwin": | |
| quoted = " ".join(shlex.quote(part) for part in args) | |
| script = f"tell application \"Terminal\" to do script {json.dumps(quoted)}" | |
| subprocess.Popen(["osascript", "-e", script], start_new_session=True) | |
| return | |
| terminals = ( | |
| ("x-terminal-emulator", ["-e"]), | |
| ("gnome-terminal", ["--"]), | |
| ("konsole", ["-e"]), | |
| ("xfce4-terminal", ["-e"]), | |
| ("mate-terminal", ["-e"]), | |
| ("xterm", ["-e"]), | |
| ) | |
| for name, flags in terminals: | |
| exe = shutil.which(name) | |
| if exe: | |
| subprocess.Popen([exe, *flags, *args], start_new_session=True) | |
| return | |
| subprocess.Popen(args, start_new_session=True) | |
| def _open_directory(path: str) -> None: | |
| if not path or not os.path.isdir(path): | |
| return | |
| if os.name == "nt": | |
| os.startfile(path) # type: ignore[attr-defined] | |
| return | |
| if sys.platform == "darwin": | |
| subprocess.Popen(["open", path], start_new_session=True) | |
| return | |
| opener = shutil.which("xdg-open") | |
| if opener: | |
| subprocess.Popen([opener, path], start_new_session=True) | |
| def _wait_for_enter() -> None: | |
| try: | |
| input("Press Enter to close...") | |
| except EOFError: | |
| pass | |
| def _schedule_fetch(url: str, cookie_file: str) -> None: | |
| cache_path = _info_cache_path(url) | |
| lock_path = cache_path + ".lock" | |
| try: | |
| fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | |
| os.close(fd) | |
| except FileExistsError: | |
| try: | |
| age = time.time() - os.path.getmtime(lock_path) | |
| except OSError: | |
| age = 0 | |
| if age < 120: | |
| return | |
| try: | |
| os.remove(lock_path) | |
| except OSError: | |
| return | |
| try: | |
| fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | |
| os.close(fd) | |
| except FileExistsError: | |
| return | |
| args = [_hidden_python(), os.path.abspath(__file__), "--fetch-info", url] | |
| if cookie_file: | |
| args += ["--cookies", cookie_file] | |
| _spawn_hidden(args) | |
| def _wait_for_cache(url: str, timeout: float) -> dict[str, Any] | None: | |
| deadline = time.time() + timeout | |
| while time.time() < deadline: | |
| cached = _read_info_cache(url) | |
| if cached is not None: | |
| return cached | |
| time.sleep(0.25) | |
| return _read_info_cache(url) | |
| def _bootstrap_ytdlp_main() -> int: | |
| target = _cached_ytdlp_path() | |
| os.makedirs(os.path.dirname(target), exist_ok=True) | |
| source = ( | |
| YTDLP_EXE_URL | |
| if os.name == "nt" | |
| else "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp" | |
| ) | |
| print(f"Downloading yt-dlp to {target}") | |
| try: | |
| import urllib.request | |
| urllib.request.urlretrieve(source, target) | |
| if os.name != "nt": | |
| os.chmod(target, 0o755) | |
| print("yt-dlp downloaded.") | |
| return 0 | |
| except Exception as exc: | |
| print(f"Failed to download yt-dlp: {exc}") | |
| return 1 | |
| def _update_ytdlp_main() -> int: | |
| ytdlp = _find_ytdlp() | |
| if not ytdlp: | |
| print("yt-dlp is not installed.") | |
| return 1 | |
| print(f"Updating {ytdlp}") | |
| return subprocess.run([ytdlp, "-U"]).returncode | |
| def _trimmed_output_path(source_path: str, overwrite: bool) -> str: | |
| root, ext = os.path.splitext(source_path) | |
| output = f"{root} - trimmed{ext}" | |
| if overwrite or not os.path.exists(output): | |
| return output | |
| index = 1 | |
| while True: | |
| candidate = f"{root} - trimmed ({index}){ext}" | |
| if not os.path.exists(candidate): | |
| return candidate | |
| index += 1 | |
| def _run_post_trim(payload: dict[str, str], source_path: str) -> str: | |
| start = payload.get("start", "") | |
| end = payload.get("end", "") | |
| start_seconds = _timestamp_seconds(start) | |
| end_seconds = _timestamp_seconds(end, allow_inf=True) | |
| if start_seconds is None or end_seconds is None: | |
| print(f"Post-trim skipped. Invalid range: {start}-{end}") | |
| return source_path | |
| ffmpeg = payload.get("ffmpeg", "") or "ffmpeg" | |
| overwrite = _as_bool(payload.get("overwrite", "true"), True) | |
| output = _trimmed_output_path(source_path, overwrite) | |
| command = [ffmpeg, "-y" if overwrite else "-n", "-ss", start, "-i", source_path] | |
| if end_seconds != float("inf"): | |
| duration = end_seconds - start_seconds | |
| command += ["-t", str(int(duration) if duration == int(duration) else round(duration, 3))] | |
| command += ["-c", "copy", output] | |
| result = subprocess.run(command) | |
| if result.returncode != 0 or not os.path.isfile(output): | |
| print("Post-trim failed.") | |
| return source_path | |
| if _as_bool(payload.get("delete_original", "false"), False): | |
| try: | |
| os.remove(source_path) | |
| except OSError: | |
| pass | |
| print(f"Trimmed file: {output}") | |
| return output | |
| def _download_main(payload: dict[str, str]) -> int: | |
| ytdlp = payload.get("ytdlp", "") or _find_ytdlp() | |
| url = payload.get("url", "") | |
| if not ytdlp or not url: | |
| print("Missing yt-dlp or URL.") | |
| return 1 | |
| is_audio = _as_bool(payload.get("is_audio", "false"), False) | |
| format_id = payload.get("format_id", "") | |
| choices = [format_id] if format_id else [] | |
| if is_audio: | |
| choices = ["bestaudio/best"] | |
| elif format_id: | |
| choices = [format_id, "bestvideo+bestaudio/best"] | |
| else: | |
| choices = ["bestvideo+bestaudio/best"] | |
| seen: set[str] = set() | |
| unique_choices = [] | |
| for item in choices: | |
| if item and item not in seen: | |
| seen.add(item) | |
| unique_choices.append(item) | |
| download_path = payload.get("download_path") or _download_path() | |
| os.makedirs(download_path, exist_ok=True) | |
| marker = os.path.join(_plugin_cache_dir(), f"final-{_cache_key(url)}-{int(time.time())}.txt") | |
| command = [ | |
| ytdlp, | |
| url, | |
| "-P", | |
| download_path, | |
| "--output", | |
| "%(title).100s.%(ext)s", | |
| "--restrict-filenames", | |
| "--trim-filenames", | |
| "100", | |
| *(["--windows-filenames"] if os.name == "nt" else []), | |
| "--no-mtime", | |
| "--no-playlist", | |
| "--retries", | |
| "10", | |
| "--fragment-retries", | |
| "10", | |
| "--progress", | |
| "--newline", | |
| "--print-to-file", | |
| "after_move:filepath", | |
| marker, | |
| ] | |
| if is_audio: | |
| command += [ | |
| "-x", | |
| "--audio-format", | |
| payload.get("audio_format") or "mp3", | |
| "--audio-quality", | |
| "0", | |
| ] | |
| else: | |
| command += ["--remux-video", payload.get("video_format") or "mp4"] | |
| if _as_bool(payload.get("overwrite", "true"), True): | |
| command.append("--force-overwrites") | |
| cookies = payload.get("cookies", "") | |
| if cookies and os.path.isfile(cookies): | |
| command += ["--cookies", cookies] | |
| ffmpeg = payload.get("ffmpeg", "") | |
| if ffmpeg: | |
| command += ["--ffmpeg-location", _ffmpeg_location(ffmpeg)] | |
| if shutil.which("node"): | |
| command += ["--js-runtimes", "node"] | |
| trim_mode = payload.get("trim_mode") or "off" | |
| section = payload.get("section", "") | |
| if section and trim_mode == "native": | |
| command += ["--download-sections", section] | |
| result = None | |
| for index, choice in enumerate(unique_choices): | |
| attempt = command[:2] + ["-f", choice] + command[2:] | |
| print(f"Downloading format: {choice}") | |
| result = subprocess.run(attempt) | |
| if result.returncode == 0: | |
| break | |
| if index + 1 < len(unique_choices): | |
| print("Selected format failed, retrying with a fallback...") | |
| final_path = "" | |
| if os.path.isfile(marker): | |
| try: | |
| lines = open(marker, encoding="utf-8", errors="replace").read().splitlines() | |
| for line in reversed(lines): | |
| if line.strip(): | |
| final_path = line.strip().strip('"') | |
| break | |
| except OSError: | |
| final_path = "" | |
| try: | |
| os.remove(marker) | |
| except OSError: | |
| pass | |
| if result and result.returncode == 0 and section and trim_mode == "post" and final_path: | |
| final_path = _run_post_trim(payload, final_path) | |
| if result and result.returncode == 0: | |
| print("Download finished.") | |
| if _as_bool(payload.get("auto_open", "true"), True): | |
| _open_directory(download_path) | |
| return 0 | |
| print("Download failed.") | |
| return 1 if result is None else result.returncode | |
| def _as_data_map(data: Any) -> dict[str, str]: | |
| if isinstance(data, dict): | |
| return {str(key): str(value) for key, value in data.items()} | |
| return {} | |
| def _message( | |
| title: str, | |
| subtitle: str, | |
| icon: str = PLUGIN_ICON, | |
| actions: list[WoxPluginBase.ActionItem] | None = None, | |
| score: int = 20, | |
| ) -> WoxPluginBase.QueryResult: | |
| return { | |
| "title": title, | |
| "subtitle": subtitle, | |
| "icon": icon, | |
| "score": score, | |
| "actions": actions or [], | |
| } | |
| class VideoDownloaderPlugin(WoxPluginBase): | |
| def query( | |
| self, raw_query: str, trigger_keyword: str, command: str, search: str | |
| ) -> List[WoxPluginBase.QueryResult]: | |
| command, search = self._normalize_query(command, search) | |
| if command == "update": | |
| return self._query_update() | |
| ytdlp = _find_ytdlp() | |
| ffmpeg = _find_ffmpeg() | |
| download_path = _download_path() | |
| cookies, cookie_error = _cookie_file() | |
| text = " ".join(part for part in (command, search) if part).strip() | |
| if not ytdlp: | |
| return [self._missing_ytdlp_result()] | |
| if not text: | |
| results = [ | |
| _message( | |
| "i18n:hint_title", | |
| download_path, | |
| PLUGIN_ICON, | |
| [ | |
| { | |
| "name": "i18n:open_folder", | |
| "id": "open-directory", | |
| "icon": FOLDER_ICON, | |
| "path": download_path, | |
| } | |
| ], | |
| 100, | |
| ), | |
| _message("i18n:hint_usage", "i18n:hint_trim", PLUGIN_ICON, score=80), | |
| ] | |
| if not ffmpeg: | |
| results.append(self._missing_ffmpeg_result()) | |
| return results | |
| request = _parse_query_text(text) | |
| url = request["url"] | |
| if not _is_valid_url(url) or not _has_extractable_target(url): | |
| return [_message("i18n:invalid_url", "i18n:invalid_url_sub", WARN_ICON, score=100)] | |
| trim_mode = (_setting("trim_mode", "off") or "off").lower() | |
| if request["section"] and trim_mode == "off": | |
| return [_message("i18n:trim_disabled", "i18n:trim_disabled_sub", WARN_ICON, score=100)] | |
| if cookie_error: | |
| return [_message("i18n:cookie_error", cookie_error, WARN_ICON, score=100)] | |
| cached = _read_info_cache(url) | |
| if cached is None: | |
| _schedule_fetch(url, cookies) | |
| cached = _wait_for_cache(url, FETCH_WAIT_SECONDS) | |
| if cached is None: | |
| return [_message("i18n:fetching", "i18n:fetching_sub", PLUGIN_ICON, score=100)] | |
| if cached.get("error"): | |
| return [_message("i18n:fetch_error", str(cached.get("error")), WARN_ICON, score=100)] | |
| info = cached.get("info") or {} | |
| formats = _sort_formats(_build_formats(info), _setting("sorting_order", "resolution") or "resolution") | |
| formats = formats[:MAX_FORMAT_RESULTS] | |
| if not formats: | |
| return [_message("i18n:empty_formats", url, WARN_ICON, score=100)] | |
| results: List[WoxPluginBase.QueryResult] = [] | |
| if not ffmpeg: | |
| results.append(self._missing_ffmpeg_result()) | |
| title = str(info.get("title") or "Unknown Title") | |
| thumbnail = str(info.get("thumbnail") or "") | |
| icon = f"url:{thumbnail}" if thumbnail.startswith("http") else VIDEO_ICON | |
| video_formats = [item for item in formats if item.get("resolution") not in {"audio only", "unknown"}] | |
| audio_formats = [item for item in formats if item.get("resolution") == "audio only"] | |
| if video_formats: | |
| best_video = max( | |
| video_formats, | |
| key=lambda item: (_resolution_value(item), _numeric(item.get("tbr")) or 0), | |
| ) | |
| results.append( | |
| self._format_result( | |
| "i18n:best_video", | |
| best_video, | |
| url, | |
| info, | |
| False, | |
| request, | |
| cookies, | |
| ytdlp, | |
| ffmpeg, | |
| download_path, | |
| icon, | |
| 100, | |
| ) | |
| ) | |
| if audio_formats: | |
| best_audio = max(audio_formats, key=lambda item: _numeric(item.get("tbr")) or 0) | |
| results.append( | |
| self._format_result( | |
| "i18n:best_audio", | |
| best_audio, | |
| url, | |
| info, | |
| True, | |
| request, | |
| cookies, | |
| ytdlp, | |
| ffmpeg, | |
| download_path, | |
| AUDIO_ICON, | |
| 95, | |
| ) | |
| ) | |
| short_title = title[:50] + "..." if len(title) > 50 else title | |
| for index, item in enumerate(formats): | |
| is_audio = item.get("resolution") == "audio only" | |
| results.append( | |
| self._format_result( | |
| short_title, | |
| item, | |
| url, | |
| info, | |
| is_audio, | |
| request, | |
| cookies, | |
| ytdlp, | |
| ffmpeg, | |
| download_path, | |
| AUDIO_ICON if is_audio else icon, | |
| 80 - index, | |
| ) | |
| ) | |
| return results | |
| def action(self, action_id: str, data: Any) -> None: | |
| payload = _as_data_map(data) | |
| script = os.path.abspath(__file__) | |
| if action_id == "vd-bootstrap-ytdlp": | |
| _spawn_visible([sys.executable, script, "--bootstrap-ytdlp"]) | |
| return | |
| if action_id == "vd-update": | |
| ytdlp = payload.get("ytdlp") or _find_ytdlp() | |
| if not ytdlp: | |
| _spawn_visible([sys.executable, script, "--bootstrap-ytdlp"]) | |
| return | |
| _spawn_visible([sys.executable, script, "--update-ytdlp"]) | |
| return | |
| if action_id != "vd-download": | |
| return | |
| raw = payload.get("payload", "") | |
| if not raw: | |
| return | |
| try: | |
| job = json.loads(raw) | |
| except json.JSONDecodeError: | |
| return | |
| job_path = os.path.join(_plugin_cache_dir(), f"job-{uuid.uuid4().hex}.json") | |
| _write_json(job_path, job if isinstance(job, dict) else {}) | |
| _spawn_visible([sys.executable, script, "--download-file", job_path]) | |
| def _normalize_query(self, command: str, search: str) -> tuple[str, str]: | |
| command = (command or "").strip() | |
| search = (search or "").strip() | |
| lowered = command.lower() | |
| if lowered == "update": | |
| return "update", search | |
| if not command and search: | |
| parts = search.split(None, 1) | |
| if parts[0].lower() == "update": | |
| return "update", parts[1] if len(parts) > 1 else "" | |
| return command, search | |
| def _query_update(self) -> List[WoxPluginBase.QueryResult]: | |
| ytdlp = _find_ytdlp() | |
| if not ytdlp: | |
| return [self._missing_ytdlp_result()] | |
| return [ | |
| { | |
| "title": "i18n:update_ytdlp", | |
| "subtitle": ytdlp, | |
| "icon": UPDATE_ICON, | |
| "score": 100, | |
| "actions": [ | |
| { | |
| "name": "i18n:update_ytdlp", | |
| "id": "vd-update", | |
| "icon": UPDATE_ICON, | |
| "data": {"ytdlp": ytdlp}, | |
| } | |
| ], | |
| } | |
| ] | |
| def _missing_ytdlp_result(self) -> WoxPluginBase.QueryResult: | |
| return _message( | |
| "i18n:missing_ytdlp", | |
| "i18n:missing_ytdlp_sub", | |
| WARN_ICON, | |
| [ | |
| { | |
| "name": "i18n:download_ytdlp", | |
| "id": "vd-bootstrap-ytdlp", | |
| "icon": DOWNLOAD_ICON, | |
| }, | |
| { | |
| "name": "i18n:open_ytdlp", | |
| "id": "open-url", | |
| "icon": OPEN_ICON, | |
| "url": YTDLP_RELEASE_URL, | |
| }, | |
| ], | |
| 100, | |
| ) | |
| def _missing_ffmpeg_result(self) -> WoxPluginBase.QueryResult: | |
| return _message( | |
| "i18n:missing_ffmpeg", | |
| "i18n:missing_ffmpeg_sub", | |
| WARN_ICON, | |
| [ | |
| { | |
| "name": "i18n:open_ffmpeg", | |
| "id": "open-url", | |
| "icon": OPEN_ICON, | |
| "url": FFMPEG_GUIDE_URL, | |
| } | |
| ], | |
| 30, | |
| ) | |
| def _format_result( | |
| self, | |
| title: str, | |
| item: dict[str, Any], | |
| url: str, | |
| info: dict[str, Any], | |
| is_audio: bool, | |
| request: dict[str, str], | |
| cookies: str, | |
| ytdlp: str, | |
| ffmpeg: str, | |
| download_path: str, | |
| icon: str, | |
| score: int, | |
| ) -> WoxPluginBase.QueryResult: | |
| resolution = str(item.get("resolution") or "") | |
| parts = [f"Res: {resolution}"] if resolution else [] | |
| if item.get("tbr") is not None: | |
| parts.append(f"{round(float(item['tbr']), 2)} kbps") | |
| size = _human_size(item.get("filesize")) | |
| if size: | |
| parts.append(f"Size: {size}") | |
| if item.get("fps"): | |
| parts.append(f"FPS: {int(float(item['fps']))}") | |
| if request.get("section"): | |
| parts.append(f"Trim: {request['start']} to {request['end']}") | |
| payload = { | |
| "url": url, | |
| "format_id": _format_selector(item, is_audio), | |
| "is_audio": "true" if is_audio else "false", | |
| "download_path": download_path, | |
| "video_format": _setting("preferred_video_format", "mp4") or "mp4", | |
| "audio_format": _setting("preferred_audio_format", "mp3") or "mp3", | |
| "auto_open": _setting("auto_open_folder", "true") or "true", | |
| "overwrite": _setting("overwrite_existing_files", "true") or "true", | |
| "cookies": cookies, | |
| "ytdlp": ytdlp, | |
| "ffmpeg": ffmpeg, | |
| "section": request.get("section", ""), | |
| "start": request.get("start", ""), | |
| "end": request.get("end", ""), | |
| "trim_mode": (_setting("trim_mode", "off") or "off").lower(), | |
| "delete_original": _setting("delete_original_after_trim", "false") or "false", | |
| } | |
| duration = _human_duration(info.get("duration")) | |
| tails: list[WoxPluginBase.TailItem] = [] | |
| if duration: | |
| tails.append({"id": "duration", "type": "text", "text": duration}) | |
| if item.get("ext"): | |
| tails.append({"id": "ext", "type": "text", "text": str(item["ext"])}) | |
| result: WoxPluginBase.QueryResult = { | |
| "title": title, | |
| "subtitle": " | ".join(parts), | |
| "icon": icon, | |
| "score": score, | |
| "actions": [ | |
| { | |
| "name": "i18n:download", | |
| "id": "vd-download", | |
| "icon": DOWNLOAD_ICON, | |
| "data": {"payload": json.dumps(payload, ensure_ascii=False)}, | |
| }, | |
| { | |
| "name": "i18n:copy_url", | |
| "id": "copy-to-clipboard", | |
| "icon": COPY_ICON, | |
| "text": url, | |
| }, | |
| { | |
| "name": "i18n:open_page", | |
| "id": "open-url", | |
| "icon": OPEN_ICON, | |
| "url": str(info.get("webpage_url") or url), | |
| }, | |
| { | |
| "name": "i18n:open_folder", | |
| "id": "open-directory", | |
| "icon": FOLDER_ICON, | |
| "path": download_path, | |
| }, | |
| ], | |
| } | |
| if tails: | |
| result["tails"] = tails | |
| return result | |
| def _cli_main(argv: list[str]) -> int: | |
| if len(argv) >= 2 and argv[1] == "--fetch-info": | |
| url = argv[2] if len(argv) >= 3 else "" | |
| cookies = "" | |
| if "--cookies" in argv: | |
| index = argv.index("--cookies") | |
| if index + 1 < len(argv): | |
| cookies = argv[index + 1] | |
| try: | |
| return _fetch_info_main(url, cookies) | |
| finally: | |
| lock_path = _info_cache_path(url) + ".lock" | |
| try: | |
| if os.path.isfile(lock_path): | |
| os.remove(lock_path) | |
| except OSError: | |
| pass | |
| if len(argv) >= 2 and argv[1] == "--bootstrap-ytdlp": | |
| code = _bootstrap_ytdlp_main() | |
| _wait_for_enter() | |
| return code | |
| if len(argv) >= 2 and argv[1] == "--update-ytdlp": | |
| code = _update_ytdlp_main() | |
| _wait_for_enter() | |
| return code | |
| if len(argv) >= 3 and argv[1] == "--download-file": | |
| job_path = argv[2] | |
| payload = _read_json(job_path) or {} | |
| try: | |
| code = _download_main({str(k): str(v) for k, v in payload.items()}) | |
| finally: | |
| try: | |
| if os.path.isfile(job_path): | |
| os.remove(job_path) | |
| except OSError: | |
| pass | |
| _wait_for_enter() | |
| return code | |
| return VideoDownloaderPlugin().run() | |
| if __name__ == "__main__": | |
| sys.exit(_cli_main(sys.argv)) |
qianlifeng
commented
Sep 1, 2026
Author
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment