The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor: 简化 M3U8 功能包
XiaoYouChR4bf1fcd67eb7
diff --git a/app/supports/utils.py b/app/supports/utils.pyindex 9a5be41a..83d71d14 100644--- a/app/supports/utils.py+++ b/app/supports/utils.py@@ -31,7 +31,7 @@ _WINDOWS_RESERVED_FILENAMES = {}-def _normalizeFilenameCandidate(value: str) -> str:+def _cleanFilenameRaw(value: str) -> str:candidate = str(value or "")lastSeparator = max(candidate.rfind("/"), candidate.rfind("\\"))if lastSeparator >= 0:@@ -50,12 +50,12 @@ def _normalizeFilenameCandidate(value: str) -> str:return candidate-def sanitizeFilename(name: str, fallback: str = "file", maxLength: int = 200) -> str:+def toSafeFilename(name: str, fallback: str = "file", maxLength: int = 200) -> str:normalizedFallback = ""- candidate = _normalizeFilenameCandidate(name)+ candidate = _cleanFilenameRaw(name)if not candidate:- normalizedFallback = _normalizeFilenameCandidate(fallback) or "file"+ normalizedFallback = _cleanFilenameRaw(fallback) or "file"candidate = normalizedFallbackif maxLength > 0 and len(candidate) > maxLength:@@ -72,12 +72,15 @@ def sanitizeFilename(name: str, fallback: str = "file", maxLength: int = 200) ->candidate = candidate.rstrip(". ")if candidate in {"", ".", ".."}:if not normalizedFallback:- normalizedFallback = _normalizeFilenameCandidate(fallback) or "file"+ normalizedFallback = _cleanFilenameRaw(fallback) or "file"candidate = normalizedFallbackreturn candidate+sanitizeFilename = toSafeFilename++def openFolder(path):path = Path(path)if path.exists():@@ -171,14 +174,18 @@ def splitRequestHeadersAndCookies(headers: dict[str, str] | None) -> tuple[dict[return requestHeaders, cookiejar_from_dict(cookieItems)-def getReadableSize(size: int):+def toReadableSize(size: int):for unit in ['B', 'KB', 'MB', 'GB']:if size < 1024.0:return f"{size:.2f} {unit}"size /= 1024.0return f"{size:.2f} TB"-def getReadableTime(seconds: int) -> str:++getReadableSize = toReadableSize+++def toReadableTime(seconds: int) -> str:if seconds < 60:return f"{seconds}s"elif seconds < 3600:@@ -188,6 +195,23 @@ def getReadableTime(seconds: int) -> str:return f"{int(seconds // 3600)}h{int(remainingSeconds // 60)}m{remainingSeconds % 60}s"+getReadableTime = toReadableTime+++def toPosixPath(path) -> str:+ return str(Path(path)).replace("\\", "/")+++def toExecutable(name: str) -> str:+ return f"{name}.exe" if sys.platform == "win32" else name+++def toBytes(value: str, unit: str) -> int:+ _SCALE = {"B": 1, "KB": 1024, "MB": 1024 ** 2, "GB": 1024 ** 3,+ "Bps": 1, "KBps": 1024, "MBps": 1024 ** 2, "GBps": 1024 ** 3}+ return int(float(value) * _SCALE[unit])++def ensureUniqueTaskTarget(task: "Task",) -> bool:diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pyindex 3b5ea20d..f269071c 100644--- a/features/bittorrent_pack/task.py+++ b/features/bittorrent_pack/task.py@@ -321,7 +321,7 @@ class BTWorker(Worker):self._seedingTimeBaseSeconds = self.task.seedingTimeSecondsself._sessionSeedingStartSeconds: int | None = None- def _buildParams(self) -> lt.add_torrent_params:+ def _buildArgs(self) -> lt.add_torrent_params:if self.task.resumeData:try:params = lt.read_resume_data(b64decode(self.task.resumeData.encode("ascii")))@@ -539,7 +539,7 @@ class BTWorker(Worker):)try:- params = self._buildParams()+ params = self._buildArgs()self.handle = self.session.add_torrent(params)self._mapFiles()self._updateSettings()diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex ef4e000f..1c04f7cc 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -18,31 +18,28 @@ from qfluentwidgets import (from app.bases.models import PackConfigfrom app.services.core_service import coreServicefrom app.supports.config import cfg+from app.supports.utils import toExecutable, toPosixPathif TYPE_CHECKING:from app.view.pages.setting_page import SettingPagefrom app.view.windows.main_window import MainWindow-def _executableName(name: str) -> str:- return f"{name}.exe" if sys.platform == "win32" else name--def _guessInstallRoot(ffmpegPath: str) -> str:path = Path(ffmpegPath)if path.parent.name.lower() == "bin":- return str(path.parent.parent).replace("\\", "/")- return str(path.parent).replace("\\", "/")+ return toPosixPath(path.parent.parent)+ return toPosixPath(path.parent)def _resolveExecutable(name: str) -> str:installFolder = Path(ffmpegConfig.installFolder.value)- for candidate in (installFolder / "bin" / _executableName(name), installFolder / _executableName(name)):+ for candidate in (installFolder / "bin" / toExecutable(name), installFolder / toExecutable(name)):if candidate.is_file():- return str(candidate).replace("\\", "/")+ return toPosixPath(candidate)found = shutil.which(name)- return str(found).replace("\\", "/") if found else ""+ return toPosixPath(found) if found else ""def resolveFFmpegExecutables() -> tuple[str, str]:diff --git a/features/ffmpeg_pack/pack.py b/features/ffmpeg_pack/pack.pyindex 9fec8a73..1aa1b2c6 100644--- a/features/ffmpeg_pack/pack.py+++ b/features/ffmpeg_pack/pack.py@@ -10,8 +10,8 @@ from loguru import loggerfrom app.bases.interfaces import FeaturePackfrom app.bases.models import Task, SpecialFileSizefrom app.supports.config import DEFAULT_HEADERS, cfg-from app.supports.utils import getProxies, sanitizeFilename-from .config import _executableName, ffmpegConfig, resolveFFmpegExecutables+from app.supports.utils import getProxies, toExecutable, toPosixPath, toSafeFilename+from .config import ffmpegConfig, resolveFFmpegExecutablesfrom .task import FFmpegStageif TYPE_CHECKING:@@ -38,7 +38,7 @@ def _resourceExtension(name: str, url: str) -> str:def _mergeOutputTitle(title: str) -> str:- baseTitle = sanitizeFilename(title, fallback="merged-media")+ baseTitle = toSafeFilename(title, fallback="merged-media")if baseTitle.lower().endswith(".mp4"):return baseTitlereturn f"{baseTitle}.mp4"@@ -226,7 +226,7 @@ async def createInstallTask() -> Task:downloadStage: HttpTaskStage = downloadTask.stages[0]archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else assetInfo["size"]assetName = downloadTask.title or str(assetInfo["name"])- archivePath = str(Path(installFolder) / assetName).replace("\\", "/")+ archivePath = toPosixPath(Path(installFolder) / assetName)downloadStage.stageIndex = 1downloadStage.outputFile = archivePath@@ -248,8 +248,8 @@ async def createInstallTask() -> Task:task.addStage(ExtractStage(stageIndex=2,archivePath=archivePath,- installFolder=str(Path(installFolder)).replace("\\", "/"),- executableNames=[_executableName("ffmpeg"), _executableName("ffprobe")],+ installFolder=toPosixPath(Path(installFolder)),+ executableNames=[toExecutable("ffmpeg"), toExecutable("ffprobe")],))return taskdiff --git a/features/ftp_pack/task.py b/features/ftp_pack/task.pyindex af62f251..7640e45e 100644--- a/features/ftp_pack/task.py+++ b/features/ftp_pack/task.py@@ -32,7 +32,7 @@ def _parseSize(value) -> int:return size if size > 0 else SpecialFileSize.UNKNOWN-def _buildClientArgs(proxies: dict | None) -> dict[str, Any]:+def _buildArgs(proxies: dict | None) -> dict[str, Any]:kwargs: dict[str, Any] = {"connection_timeout": FTP_CONNECTION_TIMEOUT,"socket_timeout": FTP_SOCKET_TIMEOUT,@@ -744,7 +744,7 @@ async def _openClient(connectionInfo: FtpConnectionInfo, proxies: dict | None) -for index, (port, mode) in enumerate(attempts):client = aioftp.Client(- **_buildClientArgs(proxies),+ **_buildArgs(proxies),ssl=ssl.create_default_context() if mode == "implicit" else None,)try:diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 694f6f98..c82c9456 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -29,6 +29,7 @@ from qfluentwidgets import (from app.bases.models import PackConfigfrom app.services.core_service import coreServicefrom app.supports.config import cfg+from app.supports.utils import toExecutable, toPosixPathfrom app.view.components.setting_cards import SpinBoxSettingCardif TYPE_CHECKING:@@ -41,36 +42,20 @@ except ImportError:from features.ffmpeg_pack.config import resolveFFmpegExecutables-def _normalizePath(path: Path | str) -> str:- return str(Path(path)).replace("\\", "/")---def _executableName(name: str) -> str:- return f"{name}.exe" if sys.platform == "win32" else name---def _guessInstallRoot(downloaderPath: str) -> str:- return _normalizePath(Path(downloaderPath).parent)---def _resolveExecutable() -> str:+def resolveDownloaderPath() -> str:installFolder = Path(m3u8Config.installFolder.value)- candidate = installFolder / _executableName("N_m3u8DL-RE")+ candidate = installFolder / toExecutable("N_m3u8DL-RE")if candidate.is_file():- return _normalizePath(candidate)+ return toPosixPath(candidate)found = shutil.which("N_m3u8DL-RE")if not found and sys.platform == "win32":found = shutil.which("N_m3u8DL-RE.exe")- return _normalizePath(found) if found else ""---def resolveM3U8DownloaderExecutable() -> str:- return _resolveExecutable()+ return toPosixPath(found) if found else ""async def queryM3U8Runtime() -> dict[str, str]:- downloaderPath = resolveM3U8DownloaderExecutable()+ downloaderPath = resolveDownloaderPath()ffmpegPath, _ = resolveFFmpegExecutables()runtimeInfo = {"downloaderPath": downloaderPath,@@ -95,7 +80,7 @@ async def queryM3U8Runtime() -> dict[str, str]:output = stdout.decode("utf-8", errors="ignore") or stderr.decode("utf-8", errors="ignore")lines = [line.strip() for line in output.splitlines() if line.strip()]runtimeInfo["version"] = lines[0] if lines else ""- runtimeInfo["installPath"] = _guessInstallRoot(downloaderPath)+ runtimeInfo["installPath"] = toPosixPath(Path(downloaderPath).parent)return runtimeInfodiff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex c5f341c8..3c1cb97d 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -6,24 +6,9 @@ import niquestsfrom app.bases.interfaces import FeaturePackfrom app.bases.models import Taskfrom app.supports.config import DEFAULT_HEADERS, cfg-from app.supports.utils import getProxies, splitRequestHeadersAndCookies+from app.supports.utils import getProxies, splitRequestHeadersAndCookies, toPosixPathfrom .config import m3u8Config-from .task import (- M3U8TaskStage,- _deriveDefaultTitle,- _deriveManifestType,- _detectLive,- _normalizePath,- _stripKnownSuffix,-)---def _isSupportedUrl(url: str) -> bool:- parsedUrl = urlparse(url)- if parsedUrl.scheme.lower() not in {"http", "https"}:- return False- loweredUrl = url.lower()- return any(marker in loweredUrl for marker in (".m3u8", ".m3u", ".mpd"))+from .task import M3U8TaskStage, _isLive, _manifestType, _stem, _titleclass M3U8Pack(FeaturePack):@@ -32,7 +17,11 @@ class M3U8Pack(FeaturePack):config = m3u8Configdef matches(self, url: str) -> bool:- return _isSupportedUrl(url)+ parsedUrl = urlparse(url)+ if parsedUrl.scheme.lower() not in {"http", "https"}:+ return False+ loweredUrl = url.lower()+ return ".m3u8" in loweredUrl or ".m3u" in loweredUrl or ".mpd" in loweredUrlasync def resolve(self, payload: dict) -> dict:url = str(payload["url"]).strip()@@ -58,10 +47,10 @@ class M3U8Pack(FeaturePack):response.raise_for_status()body = response.textloweredHeaders = {key.lower(): value for key, value in response.headers.items()}- manifestType = _deriveManifestType(str(response.url), loweredHeaders, body)- isLive = _detectLive(manifestType, body)+ manifestType = _manifestType(str(response.url), loweredHeaders, body)+ isLive = _isLive(manifestType, body)extension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value- title = _deriveDefaultTitle(str(response.url), loweredHeaders, extension)+ title = _title(str(response.url), loweredHeaders, extension)finally:response.close()finally:@@ -85,6 +74,9 @@ class M3U8Pack(FeaturePack):manifestType: str = payload.get("manifestType", "m3u8")isLive: bool = payload.get("isLive", False)+ outputExtension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value+ saveName = _stem(title)+metadata = {"headers": headers,"proxies": proxies,@@ -103,6 +95,8 @@ class M3U8Pack(FeaturePack):"manifestType": manifestType,"isLive": isLive,"actualExtension": "",+ "saveName": saveName,+ "outputExtension": outputExtension,}task = Task(@@ -115,8 +109,8 @@ class M3U8Pack(FeaturePack):)taskId = task.taskId- outputFile = _normalizePath(path / title)- tempDir = _normalizePath(path / ".gd3_m3u8" / taskId)+ outputFile = toPosixPath(path / title)+ tempDir = toPosixPath(path / ".gd3_m3u8" / taskId)task.addStage(M3U8TaskStage(stageIndex=1,diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.pyindex 0412e082..7c14eb4c 100644--- a/features/m3u8_pack/task.py+++ b/features/m3u8_pack/task.py@@ -15,8 +15,8 @@ from loguru import loggerfrom app.bases.interfaces import Workerfrom app.bases.models import Task, TaskStage, TaskStatusfrom app.supports.config import DEFAULT_HEADERS, cfg-from app.supports.utils import getProxies, sanitizeFilename, splitRequestHeadersAndCookies-from .config import m3u8Config, resolveM3U8DownloaderExecutable+from app.supports.utils import getProxies, toBytes, toExecutable, toPosixPath, toSafeFilename+from .config import m3u8Config, resolveDownloaderPathif TYPE_CHECKING:from features.ffmpeg_pack.config import resolveFFmpegExecutables@@ -46,36 +46,18 @@ _M3U8DL_RELEASE_HEADERS = {}-def _normalizePath(path: Path | str) -> str:- return str(Path(path)).replace("\\", "/")---def _stripKnownSuffix(name: str) -> str:+def _stem(name: str) -> str:suffix = Path(name).suffix.lower()if suffix in _KNOWN_SUFFIXES:return name[:-len(suffix)]return name-def _parseContentDispositionName(headers: dict[str, str]) -> str:- cd = headers.get("content-disposition", "")- if not cd:- return ""-- msg = Message()- msg["Content-Disposition"] = cd- params = msg.get_params(header="Content-Disposition")- paramDict = {key.lower(): value for key, value in params if isinstance(value, str)}-- if "filename*" in paramDict and "'" in paramDict["filename*"]:- encoding, _, encodedText = paramDict["filename*"].split("'", 2)- return unquote(encodedText, encoding=encoding or "utf-8")- if "filename" in paramDict:- return paramDict["filename"].strip("\"' ")- return ""+def _toBool(value: bool) -> str:+ return "true" if value else "false"-def _deriveManifestType(url: str, headers: dict[str, str], body: str) -> str:+def _manifestType(url: str, headers: dict[str, str], body: str) -> str:loweredUrl = url.lower()contentType = headers.get("content-type", "").lower()sample = body.lstrip()[:256].lower()@@ -85,17 +67,28 @@ def _deriveManifestType(url: str, headers: dict[str, str], body: str) -> str:return "m3u8"-def _detectLive(manifestType: str, body: str) -> bool:+def _isLive(manifestType: str, body: str) -> bool:loweredBody = body.lower()if manifestType == "mpd":return 'type="dynamic"' in loweredBody or "type='dynamic'" in loweredBodyreturn "#ext-x-endlist" not in loweredBody-def _deriveDefaultTitle(url: str, headers: dict[str, str], extension: str) -> str:+def _title(url: str, headers: dict[str, str], extension: str) -> str:candidates: list[str] = []- if name := _parseContentDispositionName(headers):- candidates.append(name)++ # Content-Disposition filename 解析+ cd = headers.get("content-disposition", "")+ if cd:+ msg = Message()+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ paramDict = {key.lower(): value for key, value in params if isinstance(value, str)}+ if "filename*" in paramDict and "'" in paramDict["filename*"]:+ encoding, _, encodedText = paramDict["filename*"].split("'", 2)+ candidates.append(unquote(encodedText, encoding=encoding or "utf-8"))+ elif "filename" in paramDict:+ candidates.append(paramDict["filename"].strip("\"' "))parsedUrl = urlparse(url)query = parse_qs(parsedUrl.query)@@ -108,109 +101,13 @@ def _deriveDefaultTitle(url: str, headers: dict[str, str], extension: str) -> stcandidates.append(unquote(Path(parsedUrl.path).name))for candidate in candidates:- name = _stripKnownSuffix(sanitizeFilename(candidate, fallback="stream"))+ name = _stem(toSafeFilename(candidate, fallback="stream"))if name:return f"{name}.{extension}"return f"stream.{extension}"-def _bytesFromUnit(value: str, unit: str) -> int:- scale = {- "B": 1, "KB": 1024, "MB": 1024 ** 2, "GB": 1024 ** 3,- "Bps": 1, "KBps": 1024, "MBps": 1024 ** 2, "GBps": 1024 ** 3,- }- return int(float(value) * scale[unit])---def _boolText(value: bool) -> str:- return "true" if value else "false"---def _pickProxy(proxies: dict | None) -> str:- if not isinstance(proxies, dict):- return ""- for key in ("https", "http"):- value = str(proxies.get(key) or "").strip()- if value:- return value- return ""---def _executableName(name: str) -> str:- return f"{name}.exe" if sys.platform == "win32" else name---def _detectRuntimeTarget() -> tuple[str, str]:- machine = platform.machine().lower()-- if sys.platform == "win32":- if machine in {"amd64", "x86_64"}:- return "win-x64", "Windows x64"- if machine in {"arm64", "aarch64"}:- return "win-arm64", "Windows ARM64"- return "win-NT6.0-x86", "Windows x86"-- if sys.platform == "darwin":- if machine in {"arm64", "aarch64"}:- return "osx-arm64", "macOS Apple Silicon"- return "osx-x64", "macOS Intel"-- if sys.platform == "linux":- libcName = platform.libc_ver()[0].lower()- if machine in {"arm64", "aarch64"}:- return ("linux-musl-arm64", "Linux musl ARM64") if libcName == "musl" else ("linux-arm64", "Linux ARM64")- return ("linux-musl-x64", "Linux musl x64") if libcName == "musl" else ("linux-x64", "Linux x64")-- raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")---def _selectReleaseAsset(assets: list[dict[str, Any]]) -> dict[str, Any]:- target, _ = _detectRuntimeTarget()- for asset in assets:- name = str(asset.get("name") or "")- if target in name:- return asset- raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")---async def _requestReleaseAsset() -> dict[str, Any]:- client = niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True)- client.trust_env = False-- try:- response = await client.get(- _M3U8DL_RELEASE_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- try:- response.raise_for_status()- payload = response.json()- finally:- response.close()- finally:- await client.close()-- assets = payload.get("assets")- if not isinstance(assets, list):- raise RuntimeError("GitHub Release 返回了无效的 assets 数据")-- asset = _selectReleaseAsset(assets)- downloadUrl = str(asset.get("browser_download_url") or "").strip()- assetName = str(asset.get("name") or "").strip()- size = int(asset.get("size") or 0)- if not downloadUrl or not assetName or size <= 0:- raise RuntimeError("GitHub Release 返回了不完整的安装包信息")-- return {- "name": assetName,- "url": downloadUrl,- "size": size,- }--@dataclass(kw_only=True)class M3U8TaskStage(TaskStage):workerType: type = field(init=False, repr=False)@@ -221,18 +118,8 @@ class M3U8TaskStage(TaskStage):lastMessage: str = ""def updateOutputFile(self, taskPath: Path, taskTitle: str):- meta = self.task.metadata- outputExtension = meta.get("actualExtension") or (- "ts" if meta.get("liveRealTimeMerge") else meta.get("outputFormat", "mp4")- )- suffix = f".{outputExtension.lower()}"- if taskTitle.lower().endswith(suffix):- saveName = taskTitle[:-len(suffix)]- else:- saveName = _stripKnownSuffix(taskTitle)-- self.outputFile = _normalizePath(taskPath / taskTitle)- self.tempDir = _normalizePath(taskPath / ".gd3_m3u8" / self.task.taskId)+ self.outputFile = toPosixPath(taskPath / taskTitle)+ self.tempDir = toPosixPath(taskPath / ".gd3_m3u8" / self.task.taskId)class M3U8Worker(Worker):@@ -241,17 +128,9 @@ class M3U8Worker(Worker):self.stage = stageself.task = stage.task- def _buildArguments(self, downloaderPath: str) -> list[str]:+ def _buildArgs(self, downloaderPath: str) -> list[str]:meta = self.task.metadata- outputExtension = meta.get("actualExtension") or (- "ts" if meta.get("liveRealTimeMerge") else meta.get("outputFormat", "mp4")- )- suffix = f".{outputExtension.lower()}"- title = self.task.title- if title.lower().endswith(suffix):- saveName = title[:-len(suffix)]- else:- saveName = _stripKnownSuffix(title)+ saveName = meta.get("saveName", _stem(self.task.title))args = [self.task.url,@@ -261,11 +140,11 @@ class M3U8Worker(Worker):f"--thread-count={meta.get('threadCount', 16)}",f"--download-retry-count={meta.get('retryCount', 3)}",f"--http-request-timeout={meta.get('requestTimeout', 10)}",- f"--auto-select={_boolText(meta.get('autoSelect', True))}",- f"--concurrent-download={_boolText(meta.get('concurrentDownload', True))}",- f"--append-url-params={_boolText(meta.get('appendUrlParams', False))}",- f"--binary-merge={_boolText(meta.get('binaryMerge', False))}",- f"--check-segments-count={_boolText(meta.get('checkSegmentsCount', True))}",+ f"--auto-select={_toBool(meta.get('autoSelect', True))}",+ f"--concurrent-download={_toBool(meta.get('concurrentDownload', True))}",+ f"--append-url-params={_toBool(meta.get('appendUrlParams', False))}",+ f"--binary-merge={_toBool(meta.get('binaryMerge', False))}",+ f"--check-segments-count={_toBool(meta.get('checkSegmentsCount', True))}","--del-after-done=true","--write-meta-json=false","--no-log=true",@@ -274,7 +153,9 @@ class M3U8Worker(Worker):]proxies = meta.get("proxies")- proxyUrl = _pickProxy(proxies)+ proxyUrl = ""+ if isinstance(proxies, dict):+ proxyUrl = next((v for v in proxies.values() if v), "")args.append("--use-system-proxy=false")if proxyUrl:args.append(f"--custom-proxy={proxyUrl}")@@ -285,8 +166,8 @@ class M3U8Worker(Worker):if meta.get("liveRealTimeMerge"):args.append("--live-real-time-merge=true")- args.append(f"--live-keep-segments={_boolText(meta.get('liveKeepSegments', False))}")- args.append(f"--live-pipe-mux={_boolText(meta.get('livePipeMux', False))}")+ args.append(f"--live-keep-segments={_toBool(meta.get('liveKeepSegments', False))}")+ args.append(f"--live-pipe-mux={_toBool(meta.get('livePipeMux', False))}")else:outputFormat = meta.get("outputFormat", "mp4")muxOption = f"format={outputFormat}:muxer=ffmpeg"@@ -305,7 +186,7 @@ class M3U8Worker(Worker):return args- def _handleOutputLine(self, line: str):+ def _parseOutputLine(self, line: str):text = line.strip()if not text:return@@ -314,13 +195,10 @@ class M3U8Worker(Worker):vodMatch = _VOD_PROGRESS_PATTERN.search(text)if vodMatch:- progress = float(vodMatch.group(3))- currentSize = _bytesFromUnit(vodMatch.group(4), vodMatch.group(5))- totalSize = _bytesFromUnit(vodMatch.group(6), vodMatch.group(7))- speed = _bytesFromUnit(vodMatch.group(8), vodMatch.group(9))- self.stage.progress = progress- self.stage.receivedBytes = currentSize- self.stage.speed = speed+ self.stage.progress = float(vodMatch.group(3))+ self.stage.receivedBytes = toBytes(vodMatch.group(4), vodMatch.group(5))+ self.stage.speed = toBytes(vodMatch.group(8), vodMatch.group(9))+ totalSize = toBytes(vodMatch.group(6), vodMatch.group(7))if totalSize > 0:self.task.fileSize = totalSizereturn@@ -328,9 +206,9 @@ class M3U8Worker(Worker):liveMatch = _LIVE_PROGRESS_PATTERN.search(text)if liveMatch:self.stage.progress = float(liveMatch.group(4))- self.stage.speed = 0 if liveMatch.group(5) == "-" else _bytesFromUnit(liveMatch.group(6), liveMatch.group(7))+ self.stage.speed = 0 if liveMatch.group(5) == "-" else toBytes(liveMatch.group(6), liveMatch.group(7))- async def _readOutput(self, stream: asyncio.StreamReader | None):+ async def supervisor(self, stream: asyncio.StreamReader | None):if stream is None:return@@ -345,34 +223,31 @@ class M3U8Worker(Worker):lines = buffer.split("\n")buffer = lines.pop()for line in lines:- self._handleOutputLine(line)+ self._parseOutputLine(line)if buffer.strip():- self._handleOutputLine(buffer)+ self._parseOutputLine(buffer)- def _resolveFinalOutput(self) -> Path | None:+ def _updateOutput(self):target = Path(self.stage.outputFile)if target.is_file():- return target+ self.task.metadata["actualExtension"] = target.suffix.lstrip(".")+ self.task.fileSize = max(self.task.fileSize, target.stat().st_size)+ returnoutputDir = self.task.pathif not outputDir.is_dir():- return None+ returnmeta = self.task.metadata+ saveName = meta.get("saveName", _stem(self.task.title))outputExtension = meta.get("actualExtension") or ("ts" if meta.get("liveRealTimeMerge") else meta.get("outputFormat", "mp4"))- suffix = f".{outputExtension.lower()}"- title = self.task.title- if title.lower().endswith(suffix):- saveName = title[:-len(suffix)]- else:- saveName = _stripKnownSuffix(title)- candidates: list[Path] = []prefix = saveName.lower()ignoredSuffixes = {".json", ".txt", ".log", ".tmp", ".ghd"}+ candidates: list[Path] = []for candidate in outputDir.iterdir():if not candidate.is_file():@@ -384,7 +259,7 @@ class M3U8Worker(Worker):candidates.append(candidate)if not candidates:- return None+ returnexpectedSuffix = f".{outputExtension}"candidates.sort(@@ -393,31 +268,14 @@ class M3U8Worker(Worker):-path.stat().st_mtime,))- return candidates[0]-- def _syncFinalOutput(self):- candidate = self._resolveFinalOutput()- if candidate is None:- return-- self.task.metadata["actualExtension"] = candidate.suffix.lstrip(".")- self.task.fileSize = max(self.task.fileSize, candidate.stat().st_size)- if candidate.name != self.task.title:- self.task.setTitle(candidate.name)-- async def _stopProcess(self, process: asyncio.subprocess.Process):- if process.returncode is not None:- return-- process.terminate()- try:- await asyncio.wait_for(process.wait(), timeout=3)- except asyncio.TimeoutError:- process.kill()- await process.wait()+ found = candidates[0]+ self.task.metadata["actualExtension"] = found.suffix.lstrip(".")+ self.task.fileSize = max(self.task.fileSize, found.stat().st_size)+ if found.name != self.task.title:+ self.task.setTitle(found.name)async def run(self):- downloaderPath = resolveM3U8DownloaderExecutable()+ downloaderPath = resolveDownloaderPath()if not downloaderPath:raise RuntimeError("未找到可用的 N_m3u8DL-RE,请先在设置中安装或配置运行时")@@ -425,9 +283,9 @@ class M3U8Worker(Worker):Path(self.stage.tempDir).mkdir(parents=True, exist_ok=True)process = None- outputTask = None+ supervisorTask = Nonetry:- args = self._buildArguments(downloaderPath)+ args = self._buildArgs(downloaderPath)process = await asyncio.create_subprocess_exec(downloaderPath,*args,@@ -436,26 +294,31 @@ class M3U8Worker(Worker):stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,)- outputTask = asyncio.create_task(self._readOutput(process.stdout))+ supervisorTask = asyncio.create_task(self.supervisor(process.stdout))await process.wait()- if outputTask is not None:- await outputTask+ if supervisorTask is not None:+ await supervisorTaskif process.returncode != 0:message = self.stage.lastMessage or f"N_m3u8DL-RE 退出码异常: {process.returncode}"raise RuntimeError(message)- self._syncFinalOutput()+ self._updateOutput()self.stage.setStatus(TaskStatus.COMPLETED)except asyncio.CancelledError:self.stage.setStatus(TaskStatus.PAUSED)- if process is not None:- await self._stopProcess(process)- if outputTask is not None and not outputTask.done():- outputTask.cancel()+ if process is not None and process.returncode is None:+ process.terminate()+ try:+ await asyncio.wait_for(process.wait(), timeout=3)+ except asyncio.TimeoutError:+ process.kill()+ await process.wait()+ if supervisorTask is not None and not supervisorTask.done():+ supervisorTask.cancel()with suppress(asyncio.CancelledError):- await outputTask+ await supervisorTaskraiseexcept Exception as e:self.stage.setError(e)@@ -468,12 +331,70 @@ M3U8TaskStage.workerType = M3U8Workerasync def createInstallTask() -> Task:from app.services.feature_service import featureService- assetInfo = await _requestReleaseAsset()- _, archLabel = _detectRuntimeTarget()- installFolder = m3u8Config.installFolder.value+ # 检测当前平台+ machine = platform.machine().lower()+ if sys.platform == "win32":+ if machine in {"amd64", "x86_64"}:+ target, archLabel = "win-x64", "Windows x64"+ elif machine in {"arm64", "aarch64"}:+ target, archLabel = "win-arm64", "Windows ARM64"+ else:+ target, archLabel = "win-NT6.0-x86", "Windows x86"+ elif sys.platform == "darwin":+ if machine in {"arm64", "aarch64"}:+ target, archLabel = "osx-arm64", "macOS Apple Silicon"+ else:+ target, archLabel = "osx-x64", "macOS Intel"+ elif sys.platform == "linux":+ libcName = platform.libc_ver()[0].lower()+ if machine in {"arm64", "aarch64"}:+ target, archLabel = ("linux-musl-arm64", "Linux musl ARM64") if libcName == "musl" else ("linux-arm64", "Linux ARM64")+ else:+ target, archLabel = ("linux-musl-x64", "Linux musl x64") if libcName == "musl" else ("linux-x64", "Linux x64")+ else:+ raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")++ # 请求 GitHub Release+ client = niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True)+ client.trust_env = False+ try:+ response = await client.get(+ _M3U8DL_RELEASE_API,+ proxies=getProxies(),+ verify=cfg.SSLVerify.value,+ allow_redirects=True,+ )+ try:+ response.raise_for_status()+ payload = response.json()+ finally:+ response.close()+ finally:+ await client.close()++ assets = payload.get("assets")+ if not isinstance(assets, list):+ raise RuntimeError("GitHub Release 返回了无效的 assets 数据")++ # 匹配当前平台的 asset+ asset = None+ for item in assets:+ if target in str(item.get("name") or ""):+ asset = item+ break+ if asset is None:+ raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")+ downloadUrl = str(asset.get("browser_download_url") or "").strip()+ assetName = str(asset.get("name") or "").strip()+ size = int(asset.get("size") or 0)+ if not downloadUrl or not assetName or size <= 0:+ raise RuntimeError("GitHub Release 返回了不完整的安装包信息")++ # 构建安装任务+ installFolder = m3u8Config.installFolder.valuedownloadPayload = {- "url": assetInfo["url"],+ "url": downloadUrl,"headers": DEFAULT_HEADERS.copy(),"proxies": getProxies(),"path": Path(installFolder),@@ -484,16 +405,15 @@ async def createInstallTask() -> Task:raise RuntimeError("解析 N_m3u8DL-RE 安装包链接后未获取到下载阶段")downloadStage: HttpTaskStage = downloadTask.stages[0]- archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else assetInfo["size"]- assetName = downloadTask.title or str(assetInfo["name"])- archivePath = _normalizePath(Path(installFolder) / assetName)+ archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else size+ archivePath = toPosixPath(Path(installFolder) / (downloadTask.title or assetName))downloadStage.stageIndex = 1downloadStage.outputFile = archivePathtask = Task(title=f"N_m3u8DL-RE 安装 ({archLabel})",- url=assetInfo["url"],+ url=downloadUrl,packId="m3u8",fileSize=archiveSize,path=Path(installFolder),@@ -508,7 +428,7 @@ async def createInstallTask() -> Task:task.addStage(ExtractStage(stageIndex=2,archivePath=archivePath,- installFolder=_normalizePath(Path(installFolder)),- executableNames=[_executableName("N_m3u8DL-RE")],+ installFolder=toPosixPath(Path(installFolder)),+ executableNames=[toExecutable("N_m3u8DL-RE")],))return task