Skip to content

The only downloader you need. 下载器的集大成者。

feat(android): Pack adapter 补全与构建清理

XiaoYouChR7d7489fe760d
diff --git a/app/assets/logo_withoutBackground.png b/app/assets/logo_withoutBackground.png
index f96a7c2d..ad404335 100755
Binary files a/app/assets/logo_withoutBackground.png and b/app/assets/logo_withoutBackground.png differ
diff --git a/app/models/task.py b/app/models/task.py
index d60dda47..cb473b45 100644
--- a/app/models/task.py
+++ b/app/models/task.py
@@ -39,6 +39,9 @@ class TaskError(Exception):
def __str__(self):
return self.message.format_map(self.params) if self.params else self.message
+ def toDict(self) -> dict:
+ return {"message": self.message, "params": {k: str(v) for k, v in self.params.items()}}
+
def toTaskError(error) -> TaskError:
if isinstance(error, TaskError):
diff --git a/features/bili_pack/android.py b/features/bili_pack/android.py
index ef9c6433..e555745f 100644
--- a/features/bili_pack/android.py
+++ b/features/bili_pack/android.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import json
+UI_CLASS = "com.xychr.ghostdownloader.packs.BilibiliUi"
+
_account = None
_qr: dict = {}
@@ -36,6 +38,7 @@ def draftFields(task) -> dict:
"duration": page._duration if page else 0,
"startTime": page.startTime if page else 0,
"endTime": page.endTime if page else 0,
+ "hasPreview": bool(page and page.cid),
}
@@ -66,6 +69,9 @@ def setSubtitles(task, languages: str):
def setTrim(task, startTime: int, endTime: int):
if not task.files:
return
+ duration = task.files[0]._duration
+ if len(task.files) != 1 or not (0 <= startTime < (endTime or duration) <= duration):
+ raise ValueError("Invalid trim range")
task.files[0].startTime = startTime
task.files[0].endTime = endTime
task.update()
@@ -76,6 +82,42 @@ def setFileName(task, index: int, name: str):
_setFileName(task, index, name)
+async def probePreview(task):
+ import re
+ from urllib.parse import urlparse
+ from app.client import buildClient
+
+ page = task.files[0] if task.files and len(task.files) == 1 else None
+ match = re.match(r"/video/(BV[a-zA-Z0-9]+|av\d+)", urlparse(task.url).path)
+ if not page or not page.cid or not match:
+ return {"sheets": []}
+ videoId = match.group(1)
+ key, value = ("aid", videoId[2:]) if videoId.startswith("av") else ("bvid", videoId)
+ headers = {"Referer": "https://www.bilibili.com/"}
+ cookie = page.headers.get("cookie") or page.headers.get("Cookie")
+ client = buildClient(headers={**headers, **({"Cookie": cookie} if cookie else {})})
+ try:
+ response = await client.get(f"https://api.bilibili.com/x/player/videoshot?{key}={value}&cid={page.cid}&index=1")
+ try:
+ response.raise_for_status()
+ payload = await response.json()
+ finally:
+ response.close()
+ if payload.get("code") != 0:
+ raise ValueError("Preview request failed")
+ data = payload.get("data") or {}
+ columns, rows = int(data.get("img_x_len") or 10), int(data.get("img_y_len") or 10)
+ count = columns * rows
+ timestamps = data.get("index") or []
+ return {"sheets": [
+ {"url": "https:" + url if url.startswith("//") else url,
+ "columns": columns, "rows": rows, "times": timestamps[index * count:(index + 1) * count]}
+ for index, url in enumerate(data.get("image") or [])
+ ], "headers": headers}
+ finally:
+ client.close()
+
+
# ---- account state (called by Kotlin via packState/requestPack) ----
def accountState() -> dict:
diff --git a/features/ftp_pack/android.py b/features/ftp_pack/android.py
new file mode 100644
index 00000000..b00c496b
--- /dev/null
+++ b/features/ftp_pack/android.py
@@ -0,0 +1,2 @@
+def editFields(task) -> dict:
+ return {"subworkerCount": task.steps[0].subworkerCount}
diff --git a/features/github_pack/android.py b/features/github_pack/android.py
new file mode 100644
index 00000000..d3dbac8a
--- /dev/null
+++ b/features/github_pack/android.py
@@ -0,0 +1,3 @@
+from http_pack.android import editFields
+
+UI_CLASS = "com.xychr.ghostdownloader.packs.GitHubUi"
diff --git a/features/http_pack/android.py b/features/http_pack/android.py
new file mode 100644
index 00000000..d624ce03
--- /dev/null
+++ b/features/http_pack/android.py
@@ -0,0 +1,12 @@
+"""Android projection of existing HTTP edit options."""
+
+
+def editFields(task) -> dict:
+ step = task.steps[0]
+ return {
+ "url": task.url,
+ "headers": dict(step.headers),
+ "clientProfile": step.clientProfile,
+ "userAgent": step.userAgent,
+ "subworkerCount": step.subworkerCount,
+ }
diff --git a/features/huggingface_pack/android.py b/features/huggingface_pack/android.py
new file mode 100644
index 00000000..3c5eeab6
--- /dev/null
+++ b/features/huggingface_pack/android.py
@@ -0,0 +1 @@
+UI_CLASS = "com.xychr.ghostdownloader.packs.HuggingFaceUi"
diff --git a/features/m3u8_pack/android.py b/features/m3u8_pack/android.py
index 6937eb82..5a8f7e11 100644
--- a/features/m3u8_pack/android.py
+++ b/features/m3u8_pack/android.py
@@ -1,5 +1,39 @@
"""Android View adapter for M3U8Pack."""
+from app.models.task import TaskStatus
+
+UI_CLASS = "com.xychr.ghostdownloader.packs.M3u8Ui"
+
+
+def editFields(task) -> dict:
+ step = task.steps[0]
+ return {
+ "headers": dict(step.headers),
+ **({"recordLimit": step.recordLimit} if task.isLive else {}),
+ "decryptionKeys": list(step.decryptionKeys),
+ "decryptionKeyFile": step.decryptionKeyFile,
+ "muxImports": list(step.muxImports),
+ }
+
def taskFields(task) -> dict:
- return {"isLive": task.isLive}
+ if not task.isLive:
+ return {}
+ step = task.steps[0] if task.steps else None
+ isRunning = task.status == TaskStatus.RUNNING
+ return {
+ "progressMode": "indeterminate" if isRunning else "determinate",
+ "statusText": ("recording" if not step or step.liveStatus != "Waiting" else "waiting")
+ if isRunning else "",
+ "canStop": isRunning and step is not None,
+ "canPause": False,
+ "packFields": {
+ "liveElapsed": step.liveElapsed if step else "",
+ "recordLimit": step.recordLimit if step else "",
+ },
+ }
+
+
+def stop(task) -> None:
+ if task.isLive and task.status == TaskStatus.RUNNING and task.steps:
+ task.steps[0].terminate()
diff --git a/features/yt_dlp_pack/android.py b/features/yt_dlp_pack/android.py
new file mode 100644
index 00000000..3333df71
--- /dev/null
+++ b/features/yt_dlp_pack/android.py
@@ -0,0 +1,139 @@
+"""Android draft adapter. No Qt imports; extraction uses the same functions as Desktop."""
+from __future__ import annotations
+
+from pathlib import Path
+
+from .choices import buildAudioLanguageChoices, buildAudioTiers, buildSubtitleChoices, buildVideoTiers
+from .task import YouTubeFile, buildFormatPair, probeFormats, probePlaylist
+
+UI_CLASS = "com.xychr.ghostdownloader.packs.YtDlpUi"
+
+
+def draftFields(task) -> dict:
+ info = getattr(task, "_mediaInfo", {})
+ hasInfo = bool(info.get("formats"))
+ subtitles, _ = buildSubtitleChoices(info, "自动")
+ page = task.files[0] if task.files and len(task.files) == 1 else None
+ return {
+ "canProbeMedia": True,
+ "hasMediaInfo": hasInfo,
+ "canProbePlaylist": task.isPlaylist,
+ "videoTiers": [{"key": key, "label": label} for key, label in
+ (buildVideoTiers(info, "最佳画质") if hasInfo else [("0", "最佳画质")])],
+ "audioTiers": [{"key": key, "label": label} for key, label in
+ (buildAudioTiers(info, "最佳音质") if hasInfo else [("0", "最佳音质")])],
+ "videoTier": str(task.maxVideoHeight),
+ "audioTier": str(task.maxAudioBitrate),
+ "isVideoEnabled": task.isVideoEnabled,
+ "isAudioEnabled": task.isAudioEnabled,
+ "isCoverEnabled": task.isCoverEnabled,
+ "hasCover": bool(task.coverUrl),
+ "subtitles": [{"key": key, "label": label} for key, label in subtitles],
+ "subtitleLanguages": [s for s in task.subtitleLanguages.split(",") if s],
+ "audioLanguages": [{"key": key, "label": label} for key, label in buildAudioLanguageChoices(info)],
+ "selectedAudioLanguages": [s for s in task.audioLanguages.split(",") if s],
+ "duration": int(info.get("duration") or 0) if not task.isPlaylist else 0,
+ "startTime": page.startTime if page else 0,
+ "endTime": page.endTime if page else 0,
+ "hasPreview": any(f.get("format_note") == "storyboard" for f in info.get("formats") or []),
+ }
+
+
+def probe(task, url, kind):
+ if kind == "media":
+ info = probeFormats(url)
+ if not info or not info.get("formats"):
+ raise ValueError("No media formats found")
+ task._mediaInfo = info
+ task.setCoverUrl(info.get("thumbnail") or "")
+ updateSize(task)
+ elif kind == "playlist":
+ result = probePlaylist(url)
+ if not result:
+ raise ValueError("No playlist entries found")
+ task.setVideos(result)
+ else:
+ raise ValueError(f"Unsupported probe kind: {kind}")
+
+
+def updateSize(task):
+ info = getattr(task, "_mediaInfo", None)
+ if not info:
+ return
+ video, audio = buildFormatPair(info, task)
+ task.fileSize = sum(int(f.get("filesize") or f.get("filesize_approx") or 0)
+ for f in (video, audio) if f)
+
+
+def setTrack(task, track, isEnabled):
+ if track == "video":
+ task.isVideoEnabled = isEnabled
+ elif track == "audio":
+ task.isAudioEnabled = isEnabled
+ elif track == "cover":
+ task.isCoverEnabled = isEnabled
+ else:
+ raise ValueError("Unknown track")
+ extension = "mp4" if task.isVideoEnabled else "m4a" if task.isAudioEnabled else "jpg"
+ task.setName(f"{Path(task.name).stem}.{extension}")
+ updateSize(task)
+
+
+def setQuality(task, track, key):
+ if track == "video":
+ task.maxVideoHeight = int(key)
+ elif track == "audio":
+ task.maxAudioBitrate = int(key)
+ else:
+ raise ValueError("Unknown track")
+ updateSize(task)
+
+
+def setAudioLanguages(task, languages):
+ task.audioLanguages = languages
+ updateSize(task)
+
+
+def setSubtitles(task, languages):
+ _, auto = buildSubtitleChoices(getattr(task, "_mediaInfo", {}), "")
+ task.subtitleLanguages = languages
+ task.shouldIncludeAutoSubs = bool(auto.intersection(languages.split(",")))
+
+
+def setTrim(task, start, end):
+ duration = int(getattr(task, "_mediaInfo", {}).get("duration") or 0)
+ if task.isPlaylist or not (0 <= start < (end or duration) <= duration):
+ raise ValueError("Invalid trim range")
+ if not task.files:
+ task.files = [YouTubeFile(index=0, relativePath="")]
+ task.files[0].startTime = start
+ task.files[0].endTime = end
+
+
+def buildPreview(info):
+ candidates = [f for f in info.get("formats") or []
+ if f.get("format_note") == "storyboard" and f.get("columns") and f.get("rows")]
+ fmt = max(candidates, key=lambda f: f.get("width") or 0, default=None)
+ if not fmt:
+ return {"sheets": []}
+ columns, rows = int(fmt["columns"]), int(fmt["rows"])
+ count = columns * rows
+ fps = float(fmt.get("fps") or 0)
+ if fps <= 0:
+ return {"sheets": []}
+ sheets = []
+ start = 0.0
+ for fragment in fmt.get("fragments") or []:
+ duration = float(fragment.get("duration") or 0)
+ url = fragment.get("url") or fragment.get("path") or ""
+ if url and duration > 0:
+ sheets.append({
+ "url": url, "columns": columns, "rows": rows,
+ "times": [start + index / fps for index in range(count) if index / fps < duration],
+ })
+ start += duration
+ return {"sheets": sheets, "headers": fmt.get("http_headers") or info.get("http_headers") or {}}
+
+
+async def probePreview(task):
+ return buildPreview(getattr(task, "_mediaInfo", {}))
diff --git a/features/yt_dlp_pack/cards.py b/features/yt_dlp_pack/cards.py
index e45b2492..0ef3e6ef 100644
--- a/features/yt_dlp_pack/cards.py
+++ b/features/yt_dlp_pack/cards.py
@@ -21,154 +21,10 @@ from app.view.components.range_slider import RangeSlider
from app.view.components.track_bar import TrackBar, TrackButton
from app.view.components.tree_view import AutoSizingTreeView
from app.view.dialogs.subtitle_select import SubtitleSelectDialog
-from .config import ytDlpConfig
-from .task import DIRECT_PROTOCOLS, STEPS_PER_VIDEO, YouTubeCoverStep, YouTubeTask, buildFormatPair, probeFormats, probePlaylist
+from .task import STEPS_PER_VIDEO, YouTubeCoverStep, YouTubeTask, buildFormatPair, probeFormats, probePlaylist
-def toCodecName(codec: str) -> str:
- if not codec or codec == "none":
- return ""
- c = codec.lower()
- if c.startswith("av01"):
- return "AV1"
- if c.startswith("vp9") or c.startswith("vp09"):
- return "VP9"
- if c.startswith("avc") or c.startswith("h264"):
- return "H.264"
- if c.startswith("hev") or c.startswith("hvc") or c.startswith("h265"):
- return "H.265"
- if c == "opus":
- return "Opus"
- if c.startswith("mp4a"):
- return "AAC"
- return ""
-
-
-def toCodecLabel(fmt: dict) -> str:
- codec = toCodecName(fmt.get("vcodec", "")) or toCodecName(fmt.get("acodec", ""))
- br = fmt.get("vbr") or fmt.get("abr") or fmt.get("tbr") or 0
- parts = []
- if codec:
- parts.append(codec)
- if br >= 1000:
- parts.append(f"{br / 1000:.1f}Mbps")
- elif br > 0:
- parts.append(f"{int(br)}Kbps")
- return ", ".join(parts)
-
-
-def buildVideoTiers(mediaInfo: dict, bestLabel: str) -> list[tuple[str, str]]:
- formats = mediaInfo.get("formats") or []
- best: dict[int, dict] = {}
-
- for f in formats:
- if f.get("vcodec") in (None, "none"):
- continue
- height = f.get("height") or 0
- if height <= 0:
- continue
- vbr = f.get("vbr") or f.get("tbr") or 0
- if height not in best or vbr > (best[height].get("vbr") or best[height].get("tbr") or 0):
- best[height] = f
-
- tiers = sorted(best.keys(), reverse=True)
-
- result: list[tuple[str, str]] = []
- if tiers:
- fmt = best[tiers[0]]
- fps = fmt.get("fps") or 0
- fpsLabel = "60" if fps > 30 else ""
- info = toCodecLabel(fmt)
- label = bestLabel + (f" ({tiers[0]}p{fpsLabel}, {info})" if info else f" ({tiers[0]}p{fpsLabel})")
- result.append(("0", label))
-
- for height in tiers:
- fmt = best[height]
- fps = fmt.get("fps") or 0
- fpsLabel = "60" if fps > 30 else ""
- info = toCodecLabel(fmt)
- label = f"{height}p{fpsLabel} ({info})" if info else f"{height}p{fpsLabel}"
- result.append((str(height), label))
-
- return result
-
-
-def buildAudioTiers(mediaInfo: dict, bestLabel: str) -> list[tuple[str, str]]:
- formats = mediaInfo.get("formats") or []
- best: dict[int, dict] = {}
-
- for f in formats:
- if f.get("acodec") in (None, "none"):
- continue
- if f.get("vcodec", "none") != "none":
- continue
- abr = int(f.get("abr") or f.get("tbr") or 0)
- if abr <= 0:
- continue
- bucket = round(abr / 16) * 16
- if bucket not in best or abr > int(best[bucket].get("abr") or best[bucket].get("tbr") or 0):
- best[bucket] = f
-
- tiers = sorted(best.keys(), reverse=True)
-
- result: list[tuple[str, str]] = []
- if tiers:
- info = toCodecLabel(best[tiers[0]])
- result.append(("0", bestLabel + f" ({info})" if info else bestLabel))
- for bucket in tiers:
- fmt = best[bucket]
- abr = int(fmt.get("abr") or fmt.get("tbr") or 0)
- codec = toCodecName(fmt.get("acodec", ""))
- label = f"{abr}Kbps ({codec})" if codec else f"{abr}Kbps"
- result.append((str(abr), label))
-
- return result
-
-
-def buildSubtitleChoices(mediaInfo: dict, automaticLabel: str) -> tuple[list[tuple[str, str]], set[str]]:
- choices: list[tuple[str, str]] = []
- autoLangs: set[str] = set()
- seen: set[str] = set()
-
- for lang in (mediaInfo.get("subtitles") or {}):
- if lang not in seen:
- seen.add(lang)
- choices.append((lang, lang))
-
- for lang in (mediaInfo.get("automatic_captions") or {}):
- if lang not in seen:
- seen.add(lang)
- autoLangs.add(lang)
- choices.append((lang, f"{lang} ({automaticLabel})"))
-
- return choices, autoLangs
-
-
-def buildAudioLanguageChoices(mediaInfo: dict) -> list[tuple[str, str]]:
- formats = mediaInfo.get("formats") or []
- seen: dict[str, tuple[str, int]] = {}
-
- for f in formats:
- if f.get("acodec", "none") == "none" or f.get("vcodec", "none") != "none":
- continue
- if f.get("protocol") not in DIRECT_PROTOCOLS:
- continue
- lang = f.get("language")
- if not lang or lang in seen:
- continue
- note = f.get("format_note") or ""
- comma = note.find(",")
- displayName = note[:comma].strip() if comma >= 0 else note.strip()
- pref = f.get("language_preference") or 0
- if not displayName:
- displayName = f"{lang} (Original)" if pref >= 10 else lang
- seen[lang] = (displayName, pref)
-
- if len(seen) <= 1:
- return []
-
- items = sorted(seen.items(), key=lambda kv: (-kv[1][1], kv[1][0]))
- return [(lang, displayName) for lang, (displayName, _) in items]
+from .choices import buildVideoTiers, buildAudioTiers, buildSubtitleChoices, buildAudioLanguageChoices
STEP_LABELS = {
diff --git a/features/yt_dlp_pack/choices.py b/features/yt_dlp_pack/choices.py
new file mode 100644
index 00000000..4948f7ca
--- /dev/null
+++ b/features/yt_dlp_pack/choices.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+from .task import DIRECT_PROTOCOLS
+
+
+def toCodecName(codec: str) -> str:
+ if not codec or codec == "none":
+ return ""
+ c = codec.lower()
+ if c.startswith("av01"):
+ return "AV1"
+ if c.startswith("vp9") or c.startswith("vp09"):
+ return "VP9"
+ if c.startswith("avc") or c.startswith("h264"):
+ return "H.264"
+ if c.startswith("hev") or c.startswith("hvc") or c.startswith("h265"):
+ return "H.265"
+ if c == "opus":
+ return "Opus"
+ if c.startswith("mp4a"):
+ return "AAC"
+ return ""
+
+
+def toCodecLabel(fmt: dict) -> str:
+ codec = toCodecName(fmt.get("vcodec", "")) or toCodecName(fmt.get("acodec", ""))
+ br = fmt.get("vbr") or fmt.get("abr") or fmt.get("tbr") or 0
+ parts = []
+ if codec:
+ parts.append(codec)
+ if br >= 1000:
+ parts.append(f"{br / 1000:.1f}Mbps")
+ elif br > 0:
+ parts.append(f"{int(br)}Kbps")
+ return ", ".join(parts)
+
+
+def buildVideoTiers(mediaInfo: dict, bestLabel: str) -> list[tuple[str, str]]:
+ formats = mediaInfo.get("formats") or []
+ best: dict[int, dict] = {}
+
+ for f in formats:
+ if f.get("vcodec") in (None, "none"):
+ continue
+ height = f.get("height") or 0
+ if height <= 0:
+ continue
+ vbr = f.get("vbr") or f.get("tbr") or 0
+ if height not in best or vbr > (best[height].get("vbr") or best[height].get("tbr") or 0):
+ best[height] = f
+
+ tiers = sorted(best.keys(), reverse=True)
+
+ result: list[tuple[str, str]] = []
+ if tiers:
+ fmt = best[tiers[0]]
+ fps = fmt.get("fps") or 0
+ fpsLabel = "60" if fps > 30 else ""
+ info = toCodecLabel(fmt)
+ label = bestLabel + (f" ({tiers[0]}p{fpsLabel}, {info})" if info else f" ({tiers[0]}p{fpsLabel})")
+ result.append(("0", label))
+
+ for height in tiers:
+ fmt = best[height]
+ fps = fmt.get("fps") or 0
+ fpsLabel = "60" if fps > 30 else ""
+ info = toCodecLabel(fmt)
+ label = f"{height}p{fpsLabel} ({info})" if info else f"{height}p{fpsLabel}"
+ result.append((str(height), label))
+
+ return result
+
+
+def buildAudioTiers(mediaInfo: dict, bestLabel: str) -> list[tuple[str, str]]:
+ formats = mediaInfo.get("formats") or []
+ best: dict[int, dict] = {}
+
+ for f in formats:
+ if f.get("acodec") in (None, "none"):
+ continue
+ if f.get("vcodec", "none") != "none":
+ continue
+ abr = int(f.get("abr") or f.get("tbr") or 0)
+ if abr <= 0:
+ continue
+ bucket = round(abr / 16) * 16
+ if bucket not in best or abr > int(best[bucket].get("abr") or best[bucket].get("tbr") or 0):
+ best[bucket] = f
+
+ tiers = sorted(best.keys(), reverse=True)
+
+ result: list[tuple[str, str]] = []
+ if tiers:
+ info = toCodecLabel(best[tiers[0]])
+ result.append(("0", bestLabel + f" ({info})" if info else bestLabel))
+ for bucket in tiers:
+ fmt = best[bucket]
+ abr = int(fmt.get("abr") or fmt.get("tbr") or 0)
+ codec = toCodecName(fmt.get("acodec", ""))
+ label = f"{abr}Kbps ({codec})" if codec else f"{abr}Kbps"
+ result.append((str(abr), label))
+
+ return result
+
+
+def buildSubtitleChoices(mediaInfo: dict, automaticLabel: str) -> tuple[list[tuple[str, str]], set[str]]:
+ choices: list[tuple[str, str]] = []
+ autoLangs: set[str] = set()
+ seen: set[str] = set()
+
+ for lang in (mediaInfo.get("subtitles") or {}):
+ if lang not in seen:
+ seen.add(lang)
+ choices.append((lang, lang))
+
+ for lang in (mediaInfo.get("automatic_captions") or {}):
+ if lang not in seen:
+ seen.add(lang)
+ autoLangs.add(lang)
+ choices.append((lang, f"{lang} ({automaticLabel})"))
+
+ return choices, autoLangs
+
+
+def buildAudioLanguageChoices(mediaInfo: dict) -> list[tuple[str, str]]:
+ formats = mediaInfo.get("formats") or []
+ seen: dict[str, tuple[str, int]] = {}
+
+ for f in formats:
+ if f.get("acodec", "none") == "none" or f.get("vcodec", "none") != "none":
+ continue
+ if f.get("protocol") not in DIRECT_PROTOCOLS:
+ continue
+ lang = f.get("language")
+ if not lang or lang in seen:
+ continue
+ note = f.get("format_note") or ""
+ comma = note.find(",")
+ displayName = note[:comma].strip() if comma >= 0 else note.strip()
+ pref = f.get("language_preference") or 0
+ if not displayName:
+ displayName = f"{lang} (Original)" if pref >= 10 else lang
+ seen[lang] = (displayName, pref)
+
+ if len(seen) <= 1:
+ return []
+
+ items = sorted(seen.items(), key=lambda kv: (-kv[1][1], kv[1][0]))
+ return [(lang, displayName) for lang, (displayName, _) in items]