Skip to content

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

feat(android): 任务页交互重做,补齐哈希与裁剪

XiaoYouChR16dab948e82e
diff --git a/app/i18n.py b/app/i18n.py
index b7fb9486..86b26310 100644
--- a/app/i18n.py
+++ b/app/i18n.py
@@ -15,6 +15,7 @@ N("TaskErrors", "压缩包未找到:{path}")
N("TaskErrors", "不支持的压缩格式:{name}")
N("TaskErrors", "解压后未找到可执行文件:{name}")
N("TaskErrors", "无法读取校验文件:{path}")
+N("TaskErrors", "无法读取文件:{detail}")
N("TaskErrors", "SHA256 校验失败:期望 {expected},实际 {actual}")
N("TaskErrors", "下载的文件未找到:{path}")
N("TaskErrors", "无法获取 {name} 的最新 release")
diff --git a/app/services/task_draft.py b/app/services/task_draft.py
index 4e7ae27c..60cdcc06 100644
--- a/app/services/task_draft.py
+++ b/app/services/task_draft.py
@@ -8,7 +8,7 @@ from typing import Any, TYPE_CHECKING
from app.signal import Signal
from loguru import logger
-from app.models.task import toTaskError
+from app.models.task import TaskOptions, toTaskError
if TYPE_CHECKING:
from app.models.task import Task, TaskError
@@ -85,8 +85,6 @@ class TaskDraft:
self.itemsChanged.emit()
def setUrls(self, urls: list[str]) -> None:
- from app.models.task import TaskOptions
-
seen: set[str] = set()
urls = [u for u in urls if u not in seen and not seen.add(u)]
@@ -106,21 +104,9 @@ class TaskDraft:
item.parseId = ""
for url in urls[newStart:newEnd]:
item = DraftItem(url=url)
- try:
- options = TaskOptions.fromOptions({**self._baseOptions, "url": url})
- parseId = self._coroutineRunner.submit(
- self._featureService.parse(options),
- done=self._onParsed,
- failed=self._onParseFailed,
- item=item,
- )
- except Exception as e:
- logger.opt(exception=e).error("提交解析请求失败 {}", url)
- item.error = toTaskError(e)
+ self._submit(item)
+ if item.error is not None:
submitErrors.append((url, item.error))
- nextItems.append(item)
- continue
- item.parseId = parseId
nextItems.append(item)
self._items = nextItems
@@ -129,6 +115,31 @@ class TaskDraft:
self.parseFailed.emit(url, error)
self.itemsChanged.emit()
+ def refresh(self, url: str) -> None:
+ item = self.itemByUrl(url)
+ if item is None or item.error is None:
+ return
+ self._submit(item)
+ self.parsingBusyChanged.emit(self._isParsing())
+ if item.error is not None:
+ self.parseFailed.emit(url, item.error)
+ self.itemsChanged.emit()
+
+ def _submit(self, item: DraftItem) -> None:
+ item.error = None
+ try:
+ item.parseId = self._coroutineRunner.submit(
+ self._featureService.parse(
+ TaskOptions.fromOptions({**self._baseOptions, "url": item.url})
+ ),
+ done=self._onParsed,
+ failed=self._onParseFailed,
+ item=item,
+ )
+ except Exception as e:
+ logger.opt(exception=e).error("提交解析请求失败 {}", item.url)
+ item.error = toTaskError(e)
+
def addParsedTasks(self, tasks: list[Task]) -> list[str]:
if not tasks:
return []
@@ -152,6 +163,7 @@ class TaskDraft:
byUrl[url] = item
task.setOptions(self._buildOptions(item))
+ item.error = None
item.task = task
self.parseSucceeded.emit(url, task)
diff --git a/features/bili_pack/android.py b/features/bili_pack/android.py
index 1e9814b0..275eeab1 100644
--- a/features/bili_pack/android.py
+++ b/features/bili_pack/android.py
@@ -45,6 +45,33 @@ def init(pack) -> dict:
# ---- task/draft serialization (called by engine.py internally) ----
+def taskFields(task) -> dict:
+ return {
+ "fileSelectKind": "season" if task.isSeason else "pages",
+ "canSelectFiles": task.isVideoEnabled or task.isAudioEnabled,
+ }
+
+
+def fileFields(task) -> dict:
+ return {
+ page.index: {
+ "startTime": page.startTime,
+ "endTime": page.endTime,
+ }
+ for page in task.files or []
+ }
+
+
+def applyFileEdits(task, edits: dict):
+ from .task import setTimeRanges
+
+ trim = {int(i): (v[0], v[1]) for i, v in (edits.get("trim") or {}).items()}
+ if trim:
+ setTimeRanges(task.files or [], trim)
+ for index, name in (edits.get("titles") or {}).items():
+ setFileName(task, int(index), name)
+
+
def fileGroups(task) -> dict[int, list[str]]:
if not task.isSeason:
return {}
@@ -54,6 +81,10 @@ def fileGroups(task) -> dict[int, list[str]]:
}
+def toDraftOptions(pairs) -> list[dict]:
+ return [{"key": key, "label": label} for key, label in pairs]
+
+
def draftFields(task) -> dict:
from .task import (
audioTiers, currentAudioTier, currentVideoTier, subtitleChoices, videoTiers,
@@ -61,16 +92,26 @@ def draftFields(task) -> dict:
page = task.files[0] if task.files and len(task.files) == 1 else None
return {
- "videoTiers": [{"key": k, "label": l} for k, l in videoTiers(task)],
- "audioTiers": [{"key": k, "label": l} for k, l in audioTiers(task)],
- "subtitles": [{"key": k, "label": l} for k, l in subtitleChoices(task)],
- "videoTier": currentVideoTier(task),
- "audioTier": currentAudioTier(task),
- "subtitleLanguages": list(task.subtitleLanguages),
- "isVideoEnabled": task.isVideoEnabled,
- "isAudioEnabled": task.isAudioEnabled,
+ "controls": [
+ {
+ "id": "video",
+ "title": "视频",
+ "value": currentVideoTier(task) if task.isVideoEnabled else "",
+ "options": toDraftOptions(videoTiers(task)),
+ "isOptional": task.isAudioEnabled,
+ },
+ {
+ "id": "audio",
+ "title": "音频",
+ "value": currentAudioTier(task) if task.isAudioEnabled else "",
+ "options": toDraftOptions(audioTiers(task)),
+ "isOptional": task.isVideoEnabled,
+ },
+ ],
"isCoverEnabled": task.isCoverEnabled,
"hasCover": bool(task.coverUrl),
+ "subtitles": toDraftOptions(subtitleChoices(task)),
+ "subtitleLanguages": list(task.subtitleLanguages),
"duration": page._duration if page else 0,
"startTime": page.startTime if page else 0,
"endTime": page.endTime if page else 0,
@@ -80,24 +121,22 @@ def draftFields(task) -> dict:
# ---- draft mutations (called by engine.py setDraft dispatcher) ----
-def setTrack(task, track: str, isEnabled: bool):
- if track == "video":
- task.isVideoEnabled = isEnabled
- elif track == "audio":
- task.isAudioEnabled = isEnabled
+def setControl(task, controlId: str, value: str):
+ if controlId == "video":
+ task.isVideoEnabled = bool(value)
+ if value:
+ task.setVideoQuality(*map(int, value.split("-")))
+ elif controlId == "audio":
+ task.isAudioEnabled = bool(value)
+ if value:
+ task.setAudioQuality(int(value))
+ elif controlId == "cover":
+ task.isCoverEnabled = bool(value)
else:
- task.isCoverEnabled = isEnabled
+ raise ValueError(f"Unknown control: {controlId}")
task.update()
-def setQuality(task, track: str, key: str):
- if track == "video":
- qn, codecid = key.split("-")
- task.setVideoQuality(int(qn), int(codecid))
- else:
- task.setAudioQuality(int(key))
-
-
def setSubtitles(task, languages: str):
task.setSubtitleLanguages([lan for lan in languages.split(",") if lan])
diff --git a/features/bittorrent_pack/android.py b/features/bittorrent_pack/android.py
index 81bb4687..58205f56 100644
--- a/features/bittorrent_pack/android.py
+++ b/features/bittorrent_pack/android.py
@@ -28,3 +28,17 @@ def taskFields(task) -> dict:
"uploadSpeed": task.uploadRate,
},
}
+
+
+def setWebTrackerSources(sources: str):
+ from app.config.cfg import cfg
+ from .config import bittorrentConfig
+
+ urls = list(dict.fromkeys(u.strip() for u in sources.split("\n") if u.strip()))
+ cfg.set(bittorrentConfig.webTrackerSources, urls)
+
+
+async def refreshWebTrackers():
+ from .web_tracker.service import trackerService
+
+ await trackerService.refresh()
diff --git a/features/github_pack/android.py b/features/github_pack/android.py
index e3628651..682b3943 100644
--- a/features/github_pack/android.py
+++ b/features/github_pack/android.py
@@ -1,3 +1,8 @@
from http_pack.android import editFields
UI_CLASS = "com.xychr.ghostdownloader.features.github_pack.GitHubUi"
+
+async def probeSites() -> dict:
+ from .config import probeProxyLatencies
+
+ return await probeProxyLatencies()
diff --git a/features/huggingface_pack/android.py b/features/huggingface_pack/android.py
index 26d66005..954319f4 100644
--- a/features/huggingface_pack/android.py
+++ b/features/huggingface_pack/android.py
@@ -1 +1,6 @@
UI_CLASS = "com.xychr.ghostdownloader.features.huggingface_pack.HuggingFaceUi"
+
+async def probeSites() -> dict:
+ from .config import probeProxyLatencies
+
+ return await probeProxyLatencies()
diff --git a/features/m3u8_pack/android.py b/features/m3u8_pack/android.py
index 556e3578..7f4bb72d 100644
--- a/features/m3u8_pack/android.py
+++ b/features/m3u8_pack/android.py
@@ -1,5 +1,6 @@
"""Android View adapter for M3U8Pack."""
+from app.i18n import N
from app.models.task import TaskStatus
UI_CLASS = "com.xychr.ghostdownloader.features.m3u8_pack.M3u8Ui"
@@ -16,14 +17,36 @@ def editFields(task) -> dict:
}
+def optionFields(task) -> dict:
+ if len(task.streams) <= 1:
+ return {}
+ step = task.steps[0]
+ return {"streams": toStreamOptions(task.streams), "selectVideo": step.selectVideo}
+
+
+def toStreamOptions(streams: list) -> list[dict]:
+ options = [{"key": "", "label": "默认(最佳)"}]
+ for stream in streams:
+ width, height = stream.get("width", 0), stream.get("height", 0)
+ details = [v for v in (stream.get("codecs") or "",
+ f"{stream['frameRate']}fps" if stream.get("frameRate") else "") if v]
+ label = f"{width}×{height}" + (f" ({', '.join(details)})" if details else "")
+ selectExpr = f'res="{width}x{height}"'
+ if stream.get("frameRate"):
+ selectExpr += f':frame="{int(stream["frameRate"])}*"'
+ options.append({"key": selectExpr, "label": label})
+ return options
+
+
def taskFields(task) -> dict:
if not task.isLive:
return {}
step = task.steps[0] if task.steps else None
isRunning = task.status == TaskStatus.RUNNING
+ waiting = step is not None and step.liveStatus == "Waiting"
return {
"progressMode": "indeterminate" if isRunning else "determinate",
- "statusText": ("recording" if not step or step.liveStatus != "Waiting" else "waiting")
+ "statusText": (N("TaskState", "等待中") if waiting else N("TaskState", "录制中"))
if isRunning else "",
"canStop": isRunning and step is not None,
"canPause": False,
diff --git a/features/yt_dlp_pack/android.py b/features/yt_dlp_pack/android.py
index 6495e92b..8b4cc1a0 100644
--- a/features/yt_dlp_pack/android.py
+++ b/features/yt_dlp_pack/android.py
@@ -9,29 +9,49 @@ from .task import YouTubeFile, buildFormatPair, probeFormats, probePlaylist
UI_CLASS = "com.xychr.ghostdownloader.features.yt_dlp_pack.YtDlpUi"
+def toDraftOptions(pairs) -> list[dict]:
+ return [{"key": key, "label": label} for key, label in pairs]
+
+
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
+ videoTiers = buildVideoTiers(info, "最佳画质") if hasInfo else [("0", "最佳画质")]
+ audioTiers = buildAudioTiers(info, "最佳音质") if hasInfo else [("0", "最佳音质")]
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,
+ "controls": [
+ {
+ "id": "video",
+ "title": "视频",
+ "value": str(task.maxVideoHeight) if task.isVideoEnabled else "",
+ "options": toDraftOptions(videoTiers),
+ "isOptional": task.isAudioEnabled,
+ },
+ {
+ "id": "audio",
+ "title": "音频",
+ "value": str(task.maxAudioBitrate) if task.isAudioEnabled else "",
+ "options": toDraftOptions(audioTiers),
+ "isOptional": task.isVideoEnabled,
+ },
+ {
+ "id": "language",
+ "title": "语言",
+ "value": task.audioLanguages if task.isAudioEnabled else "",
+ "options": toDraftOptions(buildAudioLanguageChoices(info)),
+ "isMultiple": True,
+ "isOptional": True,
+ },
+ ],
"isCoverEnabled": task.isCoverEnabled,
"hasCover": bool(task.coverUrl),
- "subtitles": [{"key": key, "label": label} for key, label in subtitles],
+ "subtitles": toDraftOptions(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,
@@ -45,7 +65,12 @@ def probe(task, url, kind):
if not info or not info.get("formats"):
raise ValueError("No media formats found")
task._mediaInfo = info
- task.setCoverUrl(info.get("thumbnail") or "")
+ choices = buildAudioLanguageChoices(info)
+ if choices and not task.audioLanguages:
+ task.audioLanguages = choices[0][0]
+ thumbnailUrl = info.get("thumbnail") or ""
+ if thumbnailUrl:
+ task.setCoverUrl(thumbnailUrl)
updateSize(task)
elif kind == "playlist":
result = probePlaylist(url)
@@ -65,32 +90,25 @@ def updateSize(task):
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)
+def setControl(task, controlId, value):
+ tracks = (task.isVideoEnabled, task.isAudioEnabled, task.isCoverEnabled)
+ if controlId == "video":
+ task.isVideoEnabled = bool(value)
+ if value:
+ task.maxVideoHeight = int(value)
+ elif controlId == "audio":
+ task.isAudioEnabled = bool(value)
+ if value:
+ task.maxAudioBitrate = int(value)
+ elif controlId == "language":
+ task.audioLanguages = value
+ elif controlId == "cover":
+ task.isCoverEnabled = bool(value)
else:
- raise ValueError("Unknown track")
- updateSize(task)
-
-
-def setAudioLanguages(task, languages):
- task.audioLanguages = languages
+ raise ValueError(f"Unknown control: {controlId}")
+ if (task.isVideoEnabled, task.isAudioEnabled, task.isCoverEnabled) != tracks:
+ extension = "mp4" if task.isVideoEnabled else "m4a" if task.isAudioEnabled else "jpg"
+ task.setName(f"{Path(task.name).stem}.{extension}")
updateSize(task)
@@ -110,6 +128,23 @@ def setTrim(task, start, end):
task.files[0].endTime = end
+def fileFields(task) -> dict:
+ return {
+ file.index: {
+ "startTime": file.startTime,
+ "endTime": file.endTime,
+ }
+ for file in task.files or []
+ }
+
+
+def applyFileEdits(task, edits: dict):
+ trim = {int(i): (v[0], v[1]) for i, v in (edits.get("trim") or {}).items()}
+ for file in task.files or []:
+ if file.index in trim:
+ file.startTime, file.endTime = trim[file.index]
+
+
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")]
@@ -137,3 +172,21 @@ def buildPreview(info):
async def probePreview(task):
return buildPreview(getattr(task, "_mediaInfo", {}))
+
+
+def cookieState() -> dict:
+ from .config import hasCookieFile
+
+ return {"hasCookies": hasCookieFile()}
+
+
+def saveCookies(cookieText: str):
+ from .config import saveCookies as _saveCookies
+
+ _saveCookies(cookieText)
+
+
+def clearCookies():
+ from .config import clearCookies as _clearCookies
+
+ _clearCookies()