The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
perf(github): 选站和建任务共用一次请求,解析快一倍
XiaoYouChR694c1d2f0cc4
diff --git a/features/github_pack/pack.py b/features/github_pack/pack.pyindex d96c9139..c278544a 100644--- a/features/github_pack/pack.py+++ b/features/github_pack/pack.py@@ -6,7 +6,7 @@ from loguru import loggerfrom app.models.pack import FeaturePack, TaskParserfrom app.models.task import Task, TaskOptions-from http_pack.pack import HttpParser+from http_pack.pack import buildTaskfrom http_pack.task import HttpTask, HttpTaskStepfrom .config import githubConfig, selectedProxySite, GITHUB_PROXY_SITESfrom .probe import probeUrls, toProxyHeaders@@ -92,24 +92,21 @@ class GitHubParser(TaskParser):selected = selectedProxySite()urls = [f"{site}/{originalUrl}" for site in GITHUB_PROXY_SITES if site != selected] + [originalUrl]- winner = ""+ file = Noneif selected:try:- await probeUrls([f"{selected}/{originalUrl}"], originalUrl, options.headers)- winner, fallbackUrls = f"{selected}/{originalUrl}", urls+ winner, file, _ = await probeUrls(options, [f"{selected}/{originalUrl}"])+ fallbackUrls = urlsexcept Exception as e:logger.warning("所选代理站不可用 {}: {}", selected, e)- if not winner:- winner, fallbackUrls = await probeUrls(urls, originalUrl, options.headers)-- if winner == originalUrl:- task = await HttpParser().parse(options)- else:- task = await self.delegate(replace(options, url=winner, headers=toProxyHeaders(options.headers)))-- step = task.steps[0]- if fallbackUrls and isinstance(step, HttpTaskStep):- githubStep = GitHubHttpTaskStep.build(step, fallbackUrls)+ if file is None:+ winner, file, fallbackUrls = await probeUrls(options, urls)++ logger.info("GitHub 选用 {}", winner)+ headers = options.headers if winner == originalUrl else toProxyHeaders(options.headers)+ task = buildTask(replace(options, url=winner, headers=headers), file)+ if fallbackUrls:+ githubStep = GitHubHttpTaskStep.build(task.steps[0], fallbackUrls)task.steps[0] = githubStepgithubStep._bindTask(task)diff --git a/features/github_pack/probe.py b/features/github_pack/probe.pyindex f01d5423..95e71fca 100644--- a/features/github_pack/probe.py+++ b/features/github_pack/probe.py@@ -1,13 +1,14 @@from __future__ import annotationsimport asyncio+from dataclasses import replacefrom time import perf_counterfrom urllib.parse import urlparsefrom loguru import logger-from app.client import buildClient-from app.models.task import TaskError+from app.models.task import TaskError, TaskOptions+from http_pack.pack import RemoteFile, probefrom .config import GITHUB_PROXY_SITES, githubConfigPROBE_TARGET = "https://github.com/cli/cli/releases/download/v2.62.0/gh_2.62.0_linux_amd64.tar.gz"@@ -19,34 +20,24 @@ def toProxyHeaders(headers: dict[str, str]) -> dict[str, str]:return {k: v for k, v in headers.items() if k.lower() not in {"authorization", "cookie"}}-def matchResponse(originalUrl: str, status: int, headers: dict[str, str]) -> bool:+def matchFile(originalUrl: str, file: RemoteFile) -> bool:parsedUrl = urlparse(originalUrl)if parsedUrl.hostname == "codeload.github.com" or "/archive/" in parsedUrl.path:- return status in {200, 206} and not headers.get("content-type", "").lower().startswith("text/")+ return not file.contentType.startswith("text/")+ return file.canUseRangeRequests and file.fileSize > 0- total = headers.get("content-range", "").rpartition("/")[2]- return status == 206 and total.isdigit() and int(total) > 0+async def probeUrls(options: TaskOptions, urls: list[str]) -> tuple[str, RemoteFile, list[str]]:+ originalUrl = options.url-async def fetchHead(url: str, headers: dict[str, str]) -> tuple[int, dict[str, str]]:- client = buildClient(timeout=5)- try:- response = await client.get(url, headers={**headers, "range": "bytes=0-0", "accept-encoding": "identity"})- try:- return response.status.as_int(), {k.decode().lower(): v.decode() for k, v in response.headers}- finally:- response.close()- finally:- client.close()-+ async def probeOne(url: str) -> RemoteFile:+ headers = options.headers if url == originalUrl else toProxyHeaders(options.headers)+ file = await asyncio.wait_for(probe(replace(options, url=url, headers=headers)), 5)+ if not matchFile(originalUrl, file):+ raise TaskError("代理站响应不合格")+ return file-async def probeUrls(urls: list[str], originalUrl: str, headers: dict[str, str]) -> tuple[str, list[str]]:- async def probe(url: str) -> None:- status, responseHeaders = await fetchHead(url, headers if url == originalUrl else toProxyHeaders(headers))- if not matchResponse(originalUrl, status, responseHeaders):- raise TaskError("代理站响应不合格({status})", status=status)-- urlByTask = {asyncio.create_task(probe(url)): url for url in urls}+ urlByTask = {asyncio.create_task(probeOne(url)): url for url in urls}pending = set(urlByTask)unmatchedUrls = set()lastError = None@@ -56,7 +47,7 @@ async def probeUrls(urls: list[str], originalUrl: str, headers: dict[str, str])for task in done:url = urlByTask[task]if task.exception() is None:- return url, [u for u in urls if u != url and u not in unmatchedUrls]+ return url, task.result(), [u for u in urls if u != url and u not in unmatchedUrls]unmatchedUrls.add(url)lastError = task.exception()logger.debug("GitHub 候选不可用 {}: {}", url, lastError)@@ -71,10 +62,12 @@ async def probeProxyLatencies() -> dict[str, int]:async def probeOne(site: str) -> tuple[str, int]:start = perf_counter()try:- status, headers = await fetchHead(f"{site}/{PROBE_TARGET}", {})- except Exception:+ file = await asyncio.wait_for(probe(TaskOptions(url=f"{site}/{PROBE_TARGET}", headers={})), 5)+ except TimeoutError:return site, PROBE_TIMEOUT- if not matchResponse(PROBE_TARGET, status, headers):+ except Exception:+ return site, PROBE_UNAVAILABLE+ if not matchFile(PROBE_TARGET, file):return site, PROBE_UNAVAILABLEreturn site, int((perf_counter() - start) * 1000)diff --git a/features/github_pack/setting_cards.py b/features/github_pack/setting_cards.pyindex dbd0fa0a..6ac44f86 100644--- a/features/github_pack/setting_cards.py+++ b/features/github_pack/setting_cards.py@@ -1,4 +1,3 @@-"""GitHub 加速的设置卡片(View)。config.py 只留配置数据。"""from __future__ import annotationsfrom urllib.parse import urlparsediff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex 40af227c..ac207fd1 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -1,6 +1,7 @@from __future__ import annotationsimport re+from dataclasses import dataclassfrom email.message import Messagefrom email.utils import collapse_rfc2231_valuefrom mimetypes import guess_extension@@ -30,6 +31,177 @@ DOWNLOADABLE_EXTENSIONS = frozenset({})+@dataclass(frozen=True)+class RemoteFile:+ name: str+ fileSize: int+ canUseRangeRequests: bool+ lastModified: str = ""+ contentType: str = ""+++async def probe(options: TaskOptions) -> RemoteFile:+ url = options.url+ headers = dict(options.headers)+ userAgent = options.userAgent+ name = ""+ emulation = toEmulation(+ options.clientProfile or cfg.clientProfile.value,+ options.sourceUserAgent,+ )+ client = buildClient(emulation=emulation, userAgent=userAgent or None, timeout=30)++ def rangeTotal(h: dict) -> int:+ cr = h.get("content-range", "")+ if not cr or "/" not in cr:+ return SpecialFileSize.UNKNOWN+ _, _, total = cr.rpartition("/")+ if not total or total == "*":+ return SpecialFileSize.UNKNOWN+ try:+ size = int(total)+ except ValueError:+ return SpecialFileSize.UNKNOWN+ return size if size > 0 else SpecialFileSize.UNKNOWN++ def bodyLength(h: dict) -> int:+ val = h.get("content-length", "").strip()+ if not val:+ return SpecialFileSize.UNKNOWN+ try:+ length = int(val)+ except ValueError:+ return SpecialFileSize.UNKNOWN+ return length if length > 0 else SpecialFileSize.UNKNOWN++ async def request(rangeValue: str = "") -> tuple[int, dict[str, str], str]:+ probeHeaders = dict(headers)+ probeHeaders["accept-encoding"] = "identity"+ if rangeValue:+ probeHeaders["range"] = rangeValue+ response = await client.get(url, headers=probeHeaders)+ try:+ status = response.status.as_int()+ if status not in {200, 206, 416}:+ response.raise_for_status()+ return (+ status,+ {k.decode().lower(): v.decode() for k, v in response.headers},+ str(response.url),+ )+ finally:+ response.close()++ try:+ statusCode, responseHeaders, finalUrl = await request("bytes=1-1")++ fileSize = rangeTotal(responseHeaders)+ canUseRangeRequests = statusCode == 206 and "content-range" in responseHeaders++ if canUseRangeRequests:+ logger.debug(+ "偏移 Range 探测成功, content-range: {}, fileSize: {}",+ responseHeaders.get("content-range", ""), fileSize,+ )+ else:+ fileSize = bodyLength(responseHeaders)+ logger.debug(+ "偏移 Range 探测返回 {}, content-length: {}",+ statusCode, responseHeaders.get("content-length", ""),+ )++ if statusCode == 200 and fileSize in {SpecialFileSize.UNKNOWN, 1}:+ fbStatus, fbHeaders, _ = await request("bytes=0-0")+ fbSize = rangeTotal(fbHeaders)+ if fbStatus == 206 and "content-range" in fbHeaders:+ logger.debug(+ "回退 Range 探测成功, content-range: {}, fileSize: {}",+ fbHeaders.get("content-range", ""), fbSize,+ )+ fileSize = fbSize+ canUseRangeRequests = True+ else:+ if fileSize == SpecialFileSize.UNKNOWN:+ fileSize = bodyLength(fbHeaders)+ if fileSize == SpecialFileSize.UNKNOWN and fbStatus == 416:+ fileSize = rangeTotal(fbHeaders)++ cd = responseHeaders.get("content-disposition", "")+ if cd:+ msg = Message()+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ paramDict = {k.lower(): v for k, v in params}+ name = unquote(collapse_rfc2231_value(+ paramDict.get("filename") or paramDict.get("filename*") or ""+ )).strip("\"' ")++ if not name and "content-location" in responseHeaders:+ cl = responseHeaders["content-location"]+ name = unquote(urlparse(cl).path.split("/")[-1])++ if not name:+ queryParams = parse_qs(urlparse(finalUrl).query)+ rcd = queryParams.get("response-content-disposition", [""])[0]+ if "filename=" in rcd.lower():+ m = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)+ if m:+ name = unquote(m.group(1)).strip("\"' ")++ if not name:+ path = urlparse(finalUrl).path+ if path and "/" in path:+ cleanPath = path.split(";")[0]+ name = unquote(cleanPath.split("/")[-1])++ contentType = responseHeaders.get("content-type", "").split(";", 1)[0].lower().strip()+ standardExt = guess_extension(contentType) if contentType else ""+ standardExt = standardExt or ""++ if not name:+ name = f"file_{time_ns()}{standardExt}"+ elif "." not in name and standardExt:+ name = f"{name}{standardExt}"++ name = toSafeFilename(name, fallback=f"file_{time_ns()}")++ lastModified = responseHeaders.get("last-modified", "")+ finally:+ client.close()++ return RemoteFile(+ name=name,+ fileSize=fileSize,+ canUseRangeRequests=canUseRangeRequests,+ lastModified=lastModified,+ contentType=contentType,+ )+++def buildTask(options: TaskOptions, file: RemoteFile) -> HttpTask:+ name = file.name+ if isinstance(options, ResourceTaskOptions) and options.name:+ name = toSafeFilename(options.name, fallback=f"file_{time_ns()}")+ task = HttpTask(+ name=name,+ url=options.url,+ fileSize=file.fileSize,+ outputFolder=options.outputFolder,+ )+ task.addStep(HttpTaskStep(+ stepIndex=1,+ url=options.url,+ fileSize=file.fileSize,+ headers=dict(options.headers),+ clientProfile=options.clientProfile,+ userAgent=options.userAgent,+ subworkerCount=options.subworkerCount,+ canUseRangeRequests=file.canUseRangeRequests,+ lastModified=file.lastModified,+ ))+ return task++class HttpParser(TaskParser):priority = 100@@ -44,167 +216,15 @@ class HttpParser(TaskParser):return any(path.endswith(ext) for ext in DOWNLOADABLE_EXTENSIONS)async def parse(self, options: TaskOptions) -> Task:- url = options.url- headers = dict(options.headers)- clientProfile = options.clientProfile- userAgent = options.userAgent- subworkerCount = options.subworkerCount- outputFolder = options.outputFolder-- name = ""- fileSize = SpecialFileSize.UNKNOWN- canUseRangeRequests = False- lastModified = ""-- if isinstance(options, ResourceTaskOptions) and options.name:- name = toSafeFilename(options.name, fallback=f"file_{time_ns()}")- fileSize = options.size if options.size > 0 else SpecialFileSize.UNKNOWN- canUseRangeRequests = options.canUseRangeRequests-- if fileSize == SpecialFileSize.UNKNOWN:- emulation = toEmulation(- options.clientProfile or cfg.clientProfile.value,- options.sourceUserAgent,+ if isinstance(options, ResourceTaskOptions) and options.name and options.size > 0:+ file = RemoteFile(+ name=options.name,+ fileSize=options.size,+ canUseRangeRequests=options.canUseRangeRequests,)- client = buildClient(emulation=emulation, userAgent=userAgent or None, timeout=30)-- def rangeTotal(h: dict) -> int:- cr = h.get("content-range", "")- if not cr or "/" not in cr:- return SpecialFileSize.UNKNOWN- _, _, total = cr.rpartition("/")- if not total or total == "*":- return SpecialFileSize.UNKNOWN- try:- size = int(total)- except ValueError:- return SpecialFileSize.UNKNOWN- return size if size > 0 else SpecialFileSize.UNKNOWN-- def bodyLength(h: dict) -> int:- val = h.get("content-length", "").strip()- if not val:- return SpecialFileSize.UNKNOWN- try:- length = int(val)- except ValueError:- return SpecialFileSize.UNKNOWN- return length if length > 0 else SpecialFileSize.UNKNOWN-- async def request(rangeValue: str = "") -> tuple[int, dict[str, str], str]:- probeHeaders = dict(headers)- probeHeaders["accept-encoding"] = "identity"- if rangeValue:- probeHeaders["range"] = rangeValue- response = await client.get(url, headers=probeHeaders)- try:- status = response.status.as_int()- if status not in {200, 206, 416}:- response.raise_for_status()- return (- status,- {k.decode().lower(): v.decode() for k, v in response.headers},- str(response.url),- )- finally:- response.close()-- try:- statusCode, responseHeaders, finalUrl = await request("bytes=1-1")-- fileSize = rangeTotal(responseHeaders)- canUseRangeRequests = statusCode == 206 and "content-range" in responseHeaders-- if canUseRangeRequests:- logger.info(- "偏移 Range 探测成功, content-range: {}, fileSize: {}",- responseHeaders.get("content-range", ""), fileSize,- )- else:- fileSize = bodyLength(responseHeaders)- logger.info(- "偏移 Range 探测返回 {}, content-length: {}",- statusCode, responseHeaders.get("content-length", ""),- )-- if statusCode == 200 and fileSize in {SpecialFileSize.UNKNOWN, 1}:- fbStatus, fbHeaders, _ = await request("bytes=0-0")- fbSize = rangeTotal(fbHeaders)- if fbStatus == 206 and "content-range" in fbHeaders:- logger.info(- "回退 Range 探测成功, content-range: {}, fileSize: {}",- fbHeaders.get("content-range", ""), fbSize,- )- fileSize = fbSize- canUseRangeRequests = True- else:- if fileSize == SpecialFileSize.UNKNOWN:- fileSize = bodyLength(fbHeaders)- if fileSize == SpecialFileSize.UNKNOWN and fbStatus == 416:- fileSize = rangeTotal(fbHeaders)-- if not name:- cd = responseHeaders.get("content-disposition", "")- if cd:- msg = Message()- msg["Content-Disposition"] = cd- params = msg.get_params(header="Content-Disposition")- paramDict = {k.lower(): v for k, v in params}- name = unquote(collapse_rfc2231_value(- paramDict.get("filename") or paramDict.get("filename*") or ""- )).strip("\"' ")-- if not name and "content-location" in responseHeaders:- cl = responseHeaders["content-location"]- name = unquote(urlparse(cl).path.split("/")[-1])-- if not name:- queryParams = parse_qs(urlparse(finalUrl).query)- rcd = queryParams.get("response-content-disposition", [""])[0]- if "filename=" in rcd.lower():- m = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)- if m:- name = unquote(m.group(1)).strip("\"' ")-- if not name:- path = urlparse(finalUrl).path- if path and "/" in path:- cleanPath = path.split(";")[0]- name = unquote(cleanPath.split("/")[-1])-- contentType = responseHeaders.get("content-type", "").split(";", 1)[0].lower().strip()- standardExt = guess_extension(contentType) if contentType else ""- standardExt = standardExt or ""-- if not name:- name = f"file_{time_ns()}{standardExt}"- elif "." not in name and standardExt:- name = f"{name}{standardExt}"-- name = toSafeFilename(name, fallback=f"file_{time_ns()}")-- lastModified = responseHeaders.get("last-modified", "")- finally:- client.close()-- task = HttpTask(- name=name,- url=url,- fileSize=fileSize,- outputFolder=outputFolder,- )- task.addStep(HttpTaskStep(- stepIndex=1,- url=url,- fileSize=fileSize,- headers=headers,- clientProfile=clientProfile,- userAgent=userAgent,- subworkerCount=subworkerCount,- canUseRangeRequests=canUseRangeRequests,- lastModified=lastModified,- ))- return task+ else:+ file = await probe(options)+ return buildTask(options, file)class HttpPack(FeaturePack):diff --git a/tests/test_github_probe.py b/tests/test_github_probe.pyindex 1ccc52d0..53d20eac 100644--- a/tests/test_github_probe.py+++ b/tests/test_github_probe.py@@ -5,7 +5,9 @@ import asyncioimport pytestfrom aiohttp import web-from github_pack.probe import matchResponse, probeUrls+from app.models.task import ResourceTaskOptions, TaskOptions+from github_pack.probe import matchFile, probeUrls+from http_pack.pack import RemoteFileASSET_URL = "https://github.com/o/r/releases/download/v1/a.tar.gz"RAW_URL = "https://raw.githubusercontent.com/o/r/main/README.md"@@ -13,24 +15,23 @@ ARCHIVE_URL = "https://github.com/o/r/archive/refs/heads/main.zip"CODELOAD_URL = "https://codeload.github.com/o/r/zip/refs/heads/main"[email protected]("originalUrl, status, headers, expected", [- (ASSET_URL, 206, {"content-range": "bytes 0-0/100", "content-type": "application/octet-stream"}, True),- (RAW_URL, 206, {"content-range": "bytes 0-0/100", "content-type": "text/plain"}, True),- (ASSET_URL, 200, {"content-type": "application/octet-stream", "content-length": "100"}, False),- (ASSET_URL, 200, {"content-type": "text/plain"}, False),- (ASSET_URL, 206, {"content-type": "application/octet-stream"}, False),- (ASSET_URL, 206, {"content-range": "bytes 0-0/*"}, False),- (ASSET_URL, 206, {"content-range": "bytes 0-0/0"}, False),- (ASSET_URL, 403, {"content-type": "text/html"}, False),- (ARCHIVE_URL, 200, {"content-type": "application/zip"}, True),- (CODELOAD_URL, 200, {"content-type": "application/zip"}, True),- (ARCHIVE_URL, 206, {"content-range": "bytes 0-0/100", "content-type": "application/zip"}, True),- (ARCHIVE_URL, 200, {"content-type": "text/html; charset=utf-8"}, False),- (ARCHIVE_URL, 200, {"content-type": "text/plain"}, False),- (ARCHIVE_URL, 404, {"content-type": "application/zip"}, False),+def buildFile(*, fileSize: int = 100, canUseRangeRequests: bool = True, contentType: str = "") -> RemoteFile:+ return RemoteFile(name="a", fileSize=fileSize, canUseRangeRequests=canUseRangeRequests, contentType=contentType)++[email protected]("originalUrl, file, expected", [+ (ASSET_URL, buildFile(), True),+ (RAW_URL, buildFile(contentType="text/plain"), True),+ (ASSET_URL, buildFile(canUseRangeRequests=False), False),+ (ASSET_URL, buildFile(fileSize=0), False),+ (ARCHIVE_URL, buildFile(canUseRangeRequests=False, fileSize=0, contentType="application/zip"), True),+ (CODELOAD_URL, buildFile(canUseRangeRequests=False, fileSize=0, contentType="application/zip"), True),+ (ARCHIVE_URL, buildFile(contentType="application/zip"), True),+ (ARCHIVE_URL, buildFile(canUseRangeRequests=False, contentType="text/html"), False),+ (ARCHIVE_URL, buildFile(canUseRangeRequests=False, contentType="text/plain"), False),])-def testMatchResponse(originalUrl, status, headers, expected):- assert matchResponse(originalUrl, status, headers) is expected+def testMatchFile(originalUrl, file, expected):+ assert matchFile(originalUrl, file) is expecteddef buildSiteHandler(*, delay: float = 0, status: int = 206, contentType: str = "application/octet-stream",@@ -41,7 +42,7 @@ def buildSiteHandler(*, delay: float = 0, status: int = 206, contentType: str =await asyncio.sleep(delay)headers = {"Content-Type": contentType}if status == 206:- headers["Content-Range"] = "bytes 0-0/100"+ headers["Content-Range"] = "bytes 1-1/100"return web.Response(status=status, body=b"x", headers=headers)return handler@@ -51,9 +52,10 @@ async def testFirstMatchedWins(server):fake = await server(buildSiteHandler(status=200, contentType="text/plain"))good = await server(buildSiteHandler(delay=0.2))- winner, fallbackUrls = await probeUrls([slow, fake, good], ASSET_URL, {})+ winner, file, fallbackUrls = await probeUrls(TaskOptions(url=ASSET_URL), [slow, fake, good])assert winner == good+ assert file.fileSize == 100assert fallbackUrls == [slow]@@ -62,7 +64,17 @@ async def testAllUnmatchedRaises(server):denied = await server(buildSiteHandler(status=403))with pytest.raises(Exception):- await probeUrls([fake, denied], ASSET_URL, {})+ await probeUrls(TaskOptions(url=ASSET_URL), [fake, denied])+++async def testKnownResourceStillProbes(server):+ fake = await server(buildSiteHandler(status=200, contentType="text/html"))+ good = await server(buildSiteHandler(delay=0.2))+ options = ResourceTaskOptions(url=ASSET_URL, name="a.tar.gz", size=100, canUseRangeRequests=True)++ winner, _, _ = await probeUrls(options, [fake, good])++ assert winner == goodasync def testProxySiteGetsNoCredentials(server):@@ -71,7 +83,7 @@ async def testProxySiteGetsNoCredentials(server):proxy = await server(buildSiteHandler(delay=0.2, requests=proxyRequests))headers = {"Authorization": "token t", "Cookie": "c=1", "X-Other": "1"}- await probeUrls([proxy, direct], direct, headers)+ await probeUrls(TaskOptions(url=direct, headers=headers), [proxy, direct])assert directRequests[0]["Authorization"] == "token t"assert "Authorization" not in proxyRequests[0]