Skip to content

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

feat(zip): 压缩包预览,只下载选中的文件 #1015

XiaoYouChR53bdb335c576
diff --git a/GLOSSARY.md b/GLOSSARY.md
index 8958009f..201744b9 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -83,6 +83,7 @@ _Avoid_: totalBytes、content-length
多文件 Task 内的一个可勾选下载单元——仓库文件、播放列表视频、多分 P 页面或种子文件。
任何 Task 状态下都允许改变选择;取消选择的文件保留部分进度。
Task 有多于一个 Selectable File 时,成品是以 Name 命名的文件夹;只有一个时,成品就是这个文件本身。
+压缩包例外:全部选中时,成品是压缩包本身。
_Avoid_: 与 Task Files 混淆
**Revive**:
diff --git a/features/zip_pack/android.py b/features/zip_pack/android.py
new file mode 100644
index 00000000..7f646e59
--- /dev/null
+++ b/features/zip_pack/android.py
@@ -0,0 +1 @@
+from http_pack.android import editFields
diff --git a/features/zip_pack/cards.py b/features/zip_pack/cards.py
new file mode 100644
index 00000000..b1485d6a
--- /dev/null
+++ b/features/zip_pack/cards.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from app.view.cards.draft_cards import MultiFileDraftCard
+from app.view.cards.task_cards import MultiFileTaskCard
+from app.view.dialogs.file_select import FileSelectDialog
+
+
+class ZipDraftCard(MultiFileDraftCard):
+ fileSelectDialog = FileSelectDialog
+
+
+class ZipTaskCard(MultiFileTaskCard):
+ fileSelectDialog = FileSelectDialog
diff --git a/features/zip_pack/manifest.toml b/features/zip_pack/manifest.toml
new file mode 100644
index 00000000..593ab8f8
--- /dev/null
+++ b/features/zip_pack/manifest.toml
@@ -0,0 +1,6 @@
+[pack]
+entry = "pack.py"
+class = "ZipPack"
+dependencies = ["http_pack"]
+version = "1.0.0"
+gdMinVersion = "4.4.7"
diff --git a/features/zip_pack/pack.py b/features/zip_pack/pack.py
new file mode 100644
index 00000000..b9b65fd4
--- /dev/null
+++ b/features/zip_pack/pack.py
@@ -0,0 +1,150 @@
+from __future__ import annotations
+
+import zipfile
+from copy import deepcopy
+
+from loguru import logger
+
+from app.config.cfg import cfg
+from app.models.pack import FeaturePack, TaskParser
+from app.models.task import ResourceTaskOptions, Task, TaskOptions
+from app.platform.filesystem import toSafeFilename
+from http_pack.pack import buildTask, fetchRange
+from .sparse import SparseView
+from .task import ZipEntry, ZipExtractStep, ZipTask
+
+TAIL_SIZE = (64 << 10) + 98
+MAX_CENTRAL_SIZE = 4 << 20
+ZIP_CONTENT_TYPES = {"application/zip", "application/x-zip-compressed"}
+SUPPORTED_COMPRESSIONS = {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED, zipfile.ZIP_BZIP2, zipfile.ZIP_LZMA}
+if hasattr(zipfile, "ZIP_ZSTANDARD"):
+ SUPPORTED_COMPRESSIONS.add(zipfile.ZIP_ZSTANDARD)
+
+
+def findCentralOffset(tail: bytes, tailOffset: int) -> int:
+ end = tail.rfind(b"PK\x05\x06")
+ if end < 0:
+ raise zipfile.BadZipFile("找不到中央目录结束记录")
+ centralSize = int.from_bytes(tail[end + 12:end + 16], "little")
+ locator = end - 20
+ if locator >= 0 and tail[locator:locator + 4] == b"PK\x06\x07":
+ end = locator - 56
+ if end < 0 or tail[end:end + 4] != b"PK\x06\x06":
+ raise zipfile.BadZipFile("找不到 ZIP64 中央目录结束记录")
+ centralSize = int.from_bytes(tail[end + 40:end + 48], "little")
+ return tailOffset + end - centralSize
+
+
+def loadInfos(view: SparseView) -> tuple[str, list[zipfile.ZipInfo]]:
+ try:
+ with zipfile.ZipFile(view, metadata_encoding="gbk") as archive:
+ return "gbk", archive.infolist()
+ except UnicodeDecodeError:
+ with zipfile.ZipFile(view) as archive:
+ return "", archive.infolist()
+
+
+def buildEntries(infos: list[zipfile.ZipInfo], centralOffset: int) -> list[ZipEntry]:
+ starts = sorted({info.header_offset for info in infos} | {centralOffset})
+ entries: list[ZipEntry] = []
+ relativePaths: set[str] = set()
+ for info in sorted(infos, key=lambda info: info.header_offset):
+ if info.is_dir():
+ continue
+ if info.flag_bits & 0x1 or info.compress_type not in SUPPORTED_COMPRESSIONS:
+ raise zipfile.BadZipFile(f"不支持的条目 {info.filename}")
+ parts = [part for part in info.filename.split("/") if part not in {"", "."}]
+ if not parts or ".." in parts:
+ raise zipfile.BadZipFile(f"不安全的路径 {info.filename}")
+ relativePath = "/".join(toSafeFilename(part, fallback="_") for part in parts)
+ if relativePath.lower() in relativePaths:
+ raise zipfile.BadZipFile(f"重复的路径 {relativePath}")
+ relativePaths.add(relativePath.lower())
+ entries.append(ZipEntry(
+ index=len(entries),
+ relativePath=relativePath,
+ size=info.file_size,
+ name=info.filename,
+ localHeaderOffset=info.header_offset,
+ windowEnd=next(start for start in starts if start > info.header_offset),
+ ))
+ if not entries:
+ raise zipfile.BadZipFile("压缩包里没有文件")
+ return entries
+
+
+def buildZipTask(options: TaskOptions, entries: list[ZipEntry], tailOffset: int, metadataEncoding: str) -> ZipTask:
+ name = options.name if isinstance(options, ResourceTaskOptions) and options.name else options.file.name
+ if name.lower().endswith(".zip"):
+ name = name[:-4]
+ whole = deepcopy(options.template)
+ steps = [whole]
+ for entry in entries:
+ window = deepcopy(options.template)
+ window.stepIndex = 2 * entry.index + 2
+ window.fileIndex = entry.index
+ window.httpByteOffset = entry.localHeaderOffset
+ window.fileSize = entry.windowEnd - entry.localHeaderOffset
+ window.lastModified = ""
+ if window.fileSize < cfg.maxReassignSize.value * 1024:
+ window.subworkerCount = 1
+ steps.append(window)
+ steps.append(ZipExtractStep(stepIndex=2 * entry.index + 3, fileIndex=entry.index))
+ return ZipTask(
+ name=toSafeFilename(name, fallback="archive"),
+ url=options.url,
+ fileSize=options.file.fileSize,
+ outputFolder=options.outputFolder,
+ files=entries,
+ steps=steps,
+ archiveSize=options.file.fileSize,
+ tailOffset=tailOffset,
+ metadataEncoding=metadataEncoding,
+ )
+
+
+class ZipParser(TaskParser):
+ priority = 96
+
+ def match(self, options: TaskOptions) -> bool:
+ if not options.isProbed or not options.file.canUseRangeRequests or options.file.fileSize <= 0:
+ return False
+ return options.file.name.lower().endswith(".zip") or options.file.contentType in ZIP_CONTENT_TYPES
+
+ async def parse(self, options: TaskOptions) -> Task:
+ size = options.file.fileSize
+ try:
+ tailOffset = max(0, size - TAIL_SIZE)
+ tail = await fetchRange(options.template, tailOffset, size - tailOffset)
+ centralOffset = findCentralOffset(tail, tailOffset)
+ if size - centralOffset > MAX_CENTRAL_SIZE:
+ raise zipfile.BadZipFile("中央目录过大")
+ if centralOffset < tailOffset:
+ tail = await fetchRange(options.template, centralOffset, tailOffset - centralOffset) + tail
+ tailOffset = centralOffset
+ metadataEncoding, infos = loadInfos(SparseView(size, [(tailOffset, tail)]))
+ return buildZipTask(options, buildEntries(infos, centralOffset), tailOffset, metadataEncoding)
+ except Exception as e:
+ logger.opt(exception=e).warning("无法预览压缩包,按普通文件下载 {}", options.url)
+ return buildTask(options)
+
+
+class ZipPack(FeaturePack):
+ packId = "zip"
+ parsers = [ZipParser]
+
+ def taskCardClass(self, task: Task) -> type | None:
+ from .cards import ZipTaskCard
+ return ZipTaskCard
+
+ def draftCardClass(self, task: Task) -> type | None:
+ from .cards import ZipDraftCard
+ return ZipDraftCard
+
+ def optionCards(self, task, parent=None):
+ from http_pack.pack import HttpPack
+ return HttpPack.optionCards(self, task, parent)
+
+ def editCards(self, task, parent=None):
+ from http_pack.pack import HttpPack
+ return HttpPack.editCards(self, task, parent)
diff --git a/features/zip_pack/sparse.py b/features/zip_pack/sparse.py
new file mode 100644
index 00000000..006aaacd
--- /dev/null
+++ b/features/zip_pack/sparse.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+import io
+import os
+from pathlib import Path
+
+
+class SparseView(io.RawIOBase):
+ def __init__(self, size: int, segments: list[tuple[int, bytes | Path]]):
+ super().__init__()
+ self._size = size
+ self._segments = []
+ for start, source in sorted(segments, key=lambda segment: segment[0]):
+ length = len(source) if isinstance(source, bytes) else os.path.getsize(source)
+ self._segments.append((start, start + length, source))
+ self._files: dict[Path, io.BufferedReader] = {}
+ self._position = 0
+
+ def readable(self) -> bool:
+ return True
+
+ def seekable(self) -> bool:
+ return True
+
+ def tell(self) -> int:
+ return self._position
+
+ def seek(self, offset: int, whence: int = os.SEEK_SET) -> int:
+ base = {os.SEEK_SET: 0, os.SEEK_CUR: self._position, os.SEEK_END: self._size}[whence]
+ self._position = base + offset
+ return self._position
+
+ def readinto(self, buffer) -> int:
+ if self._position >= self._size:
+ return 0
+ for start, end, source in self._segments:
+ if start <= self._position < end:
+ length = min(len(buffer), end - self._position)
+ offset = self._position - start
+ if isinstance(source, bytes):
+ data = source[offset:offset + length]
+ else:
+ if source not in self._files:
+ self._files[source] = open(source, "rb")
+ file = self._files[source]
+ file.seek(offset)
+ data = file.read(length)
+ buffer[:len(data)] = data
+ self._position += len(data)
+ return len(data)
+ raise OSError(f"压缩包的这段数据还没有下载:{self._position}")
+
+ def close(self) -> None:
+ for file in self._files.values():
+ file.close()
+ self._files.clear()
+ super().close()
diff --git a/features/zip_pack/task.py b/features/zip_pack/task.py
new file mode 100644
index 00000000..54bbb106
--- /dev/null
+++ b/features/zip_pack/task.py
@@ -0,0 +1,164 @@
+from __future__ import annotations
+
+import asyncio
+import os
+import shutil
+import zipfile
+from contextlib import suppress
+from copy import deepcopy
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+
+from loguru import logger
+
+from app.models.task import Task, TaskFile, TaskOptions, TaskStatus, TaskStep
+from app.platform.filesystem import deletePath
+from http_pack.pack import fetchRange
+from http_pack.task import HttpTaskStep
+from .sparse import SparseView
+
+
+@dataclass(kw_only=True)
+class ZipEntry(TaskFile):
+ name: str = ""
+ localHeaderOffset: int = 0
+ windowEnd: int = 0
+
+
+@dataclass(kw_only=True, eq=False)
+class ZipTask(Task):
+ packId: str = "zip"
+ canEdit = True
+ fileType = ZipEntry
+ archiveSize: int = 0
+ tailOffset: int = 0
+ metadataEncoding: str = ""
+
+ @property
+ def isWhole(self) -> bool:
+ return all(file.selected for file in self.files)
+
+ @property
+ def isOutputFolder(self) -> bool:
+ return not self.isWhole
+
+ @property
+ def outputPath(self) -> str:
+ return str(self.outputFolder / (f"{self.name}.zip" if self.isWhole else self.name))
+
+ @property
+ def wholeStep(self) -> HttpTaskStep:
+ return next(step for step in self.steps if step.fileIndex is None)
+
+ @property
+ def tailPath(self) -> Path:
+ return Path(self.partPath, "tail")
+
+ def toWindowPath(self, fileIndex: int) -> Path:
+ return Path(f"{self.toFilePath(fileIndex)}.ghd", "window")
+
+ def _isStepSelected(self, step: TaskStep) -> bool:
+ if step.fileIndex is None:
+ return self.isWhole
+ return not self.isWhole and super()._isStepSelected(step)
+
+ def setSelection(self, selectedIndexes):
+ super().setSelection(selectedIndexes)
+ if self.isWhole:
+ self.fileSize = self.archiveSize
+
+ def currentSnapshot(self) -> tuple[float, int, int]:
+ steps = [step for step in self.steps if isinstance(step, HttpTaskStep) and self._isStepSelected(step)]
+ total = sum(step.fileSize for step in steps)
+ receivedBytes = sum(step.receivedBytes for step in steps)
+ progress = receivedBytes / total * 100 if total else 0.0
+ return progress, sum(step.speed for step in steps), receivedBytes
+
+ def canReuseProgress(self, probed: TaskOptions) -> bool:
+ return probed.file.fileSize == self.archiveSize
+
+ def replaceWith(self, probed: TaskOptions) -> None:
+ isSameArchive = self.canReuseProgress(probed)
+ self.url = probed.url
+ for position, old in enumerate(self.steps):
+ if not isinstance(old, HttpTaskStep):
+ continue
+ new = deepcopy(probed.template)
+ for name in ("stepId", "stepIndex", "fileIndex", "httpByteOffset", "fileSize", "subworkerCount"):
+ setattr(new, name, getattr(old, name))
+ if isSameArchive:
+ new.status, new.progress, new.receivedBytes = old.status, old.progress, old.receivedBytes
+ new._bindTask(self)
+ self.steps[position] = new
+ if not isSameArchive:
+ self.archiveSize = self.wholeStep.fileSize = probed.file.fileSize
+ self.setSelection([file.index for file in self.files])
+ self.updateStatus()
+
+ def deletePlaceholders(self) -> None:
+ for file in self.files:
+ if not file.completed:
+ deletePath(Path(f"{self.toFilePath(file.index)}.ghd"))
+ super().deletePlaceholders()
+
+ async def run(self, reportSpeed, waitForSpeedLimit):
+ if self.isWhole:
+ return await super().run(reportSpeed, waitForSpeedLimit)
+ try:
+ if not self.tailPath.exists():
+ tail = await fetchRange(self.wholeStep, self.tailOffset, self.archiveSize - self.tailOffset)
+ self.tailPath.parent.mkdir(parents=True, exist_ok=True)
+ self.tailPath.write_bytes(tail)
+
+ stepsByFile: dict[int, list[TaskStep]] = {}
+ for step in self.pendingSteps():
+ stepsByFile.setdefault(step.fileIndex, []).append(step)
+ slots = asyncio.Semaphore(max(1, self.wholeStep.subworkerCount))
+
+ async def runFile(steps: list[TaskStep]) -> None:
+ async with slots:
+ for step in steps:
+ if isinstance(step, HttpTaskStep):
+ step.filePath = str(self.toWindowPath(step.fileIndex))
+ await self.runStep(step, reportSpeed, waitForSpeedLimit)
+
+ try:
+ async with asyncio.TaskGroup() as group:
+ for steps in stepsByFile.values():
+ group.create_task(runFile(steps))
+ except ExceptionGroup as eg:
+ raise eg.exceptions[0] from eg
+ if self.status == TaskStatus.COMPLETED:
+ deletePath(self.partPath)
+ except asyncio.CancelledError:
+ logger.info("{} stopped", self.name)
+ raise
+ except Exception as e:
+ logger.opt(exception=e).error("{} failed", self.name)
+ raise
+
+
+@dataclass(kw_only=True)
+class ZipExtractStep(TaskStep):
+ canPause = False
+
+ @property
+ def outputPath(self) -> str:
+ return str(self.task.toFilePath(self.fileIndex))
+
+ async def run(self, reportSpeed, waitForSpeedLimit) -> None:
+ task: ZipTask = self.task
+ entry = next(file for file in task.files if file.index == self.fileIndex)
+ window = task.toWindowPath(self.fileIndex)
+ view = SparseView(task.archiveSize, [(task.tailOffset, task.tailPath),
+ (entry.localHeaderOffset, window)])
+ with view, zipfile.ZipFile(view, metadata_encoding=task.metadataEncoding or None) as archive:
+ info = archive.getinfo(entry.name)
+ with archive.open(info) as source, open(self.outputPath, "wb") as target:
+ await asyncio.to_thread(shutil.copyfileobj, source, target, 1 << 20)
+ with suppress(ValueError):
+ modifiedAt = datetime(*info.date_time).timestamp()
+ os.utime(self.outputPath, (modifiedAt, modifiedAt))
+ deletePath(window.parent)
+ self.progress = 100
diff --git a/tests/zip_pack/__init__.py b/tests/zip_pack/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/zip_pack/test_task.py b/tests/zip_pack/test_task.py
new file mode 100644
index 00000000..7f655aaa
--- /dev/null
+++ b/tests/zip_pack/test_task.py
@@ -0,0 +1,175 @@
+from __future__ import annotations
+
+import io
+import zipfile
+from datetime import datetime
+
+import pytest
+from aiohttp import web
+
+import zip_pack.pack
+from app.models.pack import PackServices
+from app.models.task import TaskOptions, TaskStatus
+from http_pack.pack import HttpPack
+from http_pack.task import HttpTask
+from tests.helpers import buildFileContent, buildRangeHandler, waitUntil
+from zip_pack.pack import ZipPack
+from zip_pack.task import ZipTask
+
+FILES = {
+ "bin/tool.dll": buildFileContent(300_000),
+ "readme.txt": b"hello " * 1000,
+ "empty.txt": b"",
+}
+MODIFIED_AT = (2024, 5, 6, 7, 8, 10)
+
+
[email protected](params=["desktop", "android"])
+def engine(startEngine, request):
+ return startEngine(request.param)
+
+
+def features(engine):
+ services = PackServices(coroutineRunner=engine.coroutineRunner, speedMeter=engine.speedMeter)
+ for pack in (HttpPack(services), ZipPack(services)):
+ engine.featureService.register(pack)
+ return engine.featureService
+
+
+def buildArchive(files: dict[str, bytes] = FILES, compression: int = zipfile.ZIP_DEFLATED) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr(zipfile.ZipInfo("bin/", date_time=MODIFIED_AT), b"")
+ for name, data in files.items():
+ info = zipfile.ZipInfo(name, date_time=MODIFIED_AT)
+ info.compress_type = compression
+ archive.writestr(info, data)
+ return buffer.getvalue()
+
+
+def buildNamedHandler(content: bytes, name: str):
+ rangeHandler = buildRangeHandler(content)
+
+ async def handler(request: web.Request) -> web.Response:
+ response = await rangeHandler(request)
+ response.headers["Content-Disposition"] = f'attachment; filename="{name}"'
+ return response
+ return handler
+
+
+async def startArchive(startServer, archive: bytes) -> str:
+ return await startServer(buildNamedHandler(archive, "a.zip"))
+
+
+async def runToCompletion(engine, task) -> None:
+ engine.taskService.add(task)
+ await waitUntil(lambda: task.status in {TaskStatus.COMPLETED, TaskStatus.FAILED}, timeout=20)
+ assert task.status == TaskStatus.COMPLETED
+
+
+async def test_parse_archive_lists_its_files(features, startServer):
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, buildArchive())))
+
+ assert isinstance(task, ZipTask)
+ assert task.name == "a"
+ assert [file.relativePath for file in task.files] == ["bin/tool.dll", "readme.txt", "empty.txt"]
+ assert [file.size for file in task.files] == [len(data) for data in FILES.values()]
+
+
+async def test_parse_link_without_suffix_reads_name_from_server(features, startServer):
+ url = await startArchive(startServer, buildArchive())
+
+ task = await features.parse(TaskOptions(url=f"{url}?id=1"))
+
+ assert isinstance(task, ZipTask)
+
+
[email protected]("compression", [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED, zipfile.ZIP_BZIP2,
+ zipfile.ZIP_LZMA])
+async def test_run_selected_files_extracts_only_them(engine, features, startServer, downloadFolder, compression):
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, buildArchive(compression=compression))))
+ task.setSelection([0, 2])
+
+ await runToCompletion(engine, task)
+
+ tool = downloadFolder / "a" / "bin" / "tool.dll"
+ assert tool.read_bytes() == FILES["bin/tool.dll"]
+ assert (downloadFolder / "a" / "empty.txt").read_bytes() == b""
+ assert datetime.fromtimestamp(tool.stat().st_mtime).timetuple()[:6] == MODIFIED_AT
+ assert sorted(path.relative_to(downloadFolder).as_posix() for path in downloadFolder.rglob("*")) == [
+ "a", "a/bin", "a/bin/tool.dll", "a/empty.txt"]
+
+
+async def test_run_all_selected_downloads_archive_itself(engine, features, startServer, downloadFolder):
+ archive = buildArchive()
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, archive)))
+
+ await runToCompletion(engine, task)
+
+ assert [path.name for path in downloadFolder.iterdir()] == ["a.zip"]
+ assert (downloadFolder / "a.zip").read_bytes() == archive
+
+
+async def test_parse_archive_from_chinese_windows_reads_names(features, startServer):
+ archive = buildArchive({"abcd.txt": b"x"}).replace(b"abcd.txt", "中文.txt".encode("gbk"))
+
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, archive)))
+
+ assert [file.relativePath for file in task.files] == ["中文.txt"]
+
+
+async def test_parse_zip64_archive_lists_its_files(features, startServer, monkeypatch):
+ monkeypatch.setattr(zipfile, "ZIP_FILECOUNT_LIMIT", 1)
+ archive = buildArchive()
+ assert b"PK\x06\x06" in archive
+
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, archive)))
+
+ assert [file.relativePath for file in task.files] == ["bin/tool.dll", "readme.txt", "empty.txt"]
+
+
+def encrypt(archive: bytes) -> bytes:
+ data = bytearray(archive)
+ central = data.find(b"PK\x01\x02")
+ while central >= 0:
+ data[central + 8] |= 0x1
+ central = data.find(b"PK\x01\x02", central + 1)
+ return bytes(data)
+
+
[email protected]("archive", [
+ pytest.param(encrypt(buildArchive()), id="encrypted"),
+ pytest.param(buildArchive({"../evil.txt": b"x", "ok.txt": b"y"}), id="unsafe-path"),
+ pytest.param(b"not a zip" * 100, id="not-zip"),
+])
+async def test_parse_unpreviewable_archive_adds_plain_file(features, startServer, archive):
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, archive)))
+
+ assert isinstance(task, HttpTask)
+ assert task.name == "a.zip"
+
+
+async def test_parse_huge_central_directory_adds_plain_file(features, startServer, monkeypatch):
+ monkeypatch.setattr(zip_pack.pack, "MAX_CENTRAL_SIZE", 10)
+
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, buildArchive())))
+
+ assert isinstance(task, HttpTask)
+
+
+async def test_relink_same_archive_keeps_selection(engine, features, startServer, downloadFolder):
+ archive = buildArchive()
+ task = await features.parse(TaskOptions(url=await startArchive(startServer, archive)))
+ task.setSelection([1])
+ engine.taskService.add(task, autoStart=False)
+ newUrl = await startArchive(startServer, archive)
+
+ probed = await features.probe(TaskOptions(url=newUrl))
+ assert task.canReuseProgress(probed)
+ engine.taskService.edit(task, {}, probed)
+ engine.taskService.start(task)
+ await waitUntil(lambda: task.status == TaskStatus.COMPLETED, timeout=20)
+
+ assert task.url == newUrl
+ assert (downloadFolder / "a" / "readme.txt").read_bytes() == FILES["readme.txt"]