Skip to content

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

feat(github): 新增「自动」选站,代理站扩到 21 个

XiaoYouChRd8c4c6ae3a3f
diff --git a/CONTEXT.md b/CONTEXT.md
index c4529fb3..88b2a23d 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -205,3 +205,13 @@ _Avoid_: Mirror、CDN、channel
> **Dev:** "用户按重新下载时,我们创建新 Task 吗?"
> **Domain expert:** "不。Redownload 停止 Task Run、删除 Task Files、重置同一个 Task、启动新的 Task Run。"
+### GitHub 加速
+
+**Proxy Site**:
+把 GitHub 文件 URL 作为路径前缀转发下载的第三方反向代理。
+_Avoid_: Mirror、Source、CDN
+
+**Auto Site**:
+选站方式之一:每个任务解析时让直连与全部 Proxy Site 竞速,取第一个合格响应。不跨任务记忆胜出者。
+_Avoid_: 测速、最快站(不比较全部结果)
+
diff --git a/features/github_pack/android.py b/features/github_pack/android.py
index 24de1d00..811e4d14 100644
--- a/features/github_pack/android.py
+++ b/features/github_pack/android.py
@@ -7,5 +7,5 @@ def proxySiteList() -> list:
return list(GITHUB_PROXY_SITES)
async def probeSites() -> dict:
- from .config import probeProxyLatencies
+ from .probe import probeProxyLatencies
return await probeProxyLatencies()
diff --git a/features/github_pack/config.py b/features/github_pack/config.py
index fde1dad1..0f10c8e6 100644
--- a/features/github_pack/config.py
+++ b/features/github_pack/config.py
@@ -2,18 +2,34 @@ from __future__ import annotations
from urllib.parse import urlparse
-from app.client import buildClient
-from app.config.cfg import BoolValidator, ConfigItem, ConfigValidator
+from app.config.cfg import BoolValidator, ConfigItem, ConfigValidator, OptionsValidator
from app.models.pack import PackConfig
GITHUB_PROXY_SITES = (
"https://gh-proxy.com",
"https://gh-proxy.org",
- "https://gh.ddlc.top",
+ "https://cdn.gh-proxy.org",
+ "https://edgeone.gh-proxy.org",
+ "https://hk.gh-proxy.org",
"https://ghfast.top",
+ "https://ghfile.geekertao.top",
+ "https://gh.chjina.com",
+ "https://gh.monlor.com",
+ "https://gh.jasonzeng.dev",
+ "https://ghproxy.monkeyray.net",
+ "https://github.ednovas.xyz",
+ "https://gh.nxnow.top",
+ "https://ghproxy.cxkpro.top",
+ "https://fastgit.cc",
+ "https://gh.zwy.one",
+ "https://gitproxy.mrhjx.cn",
+ "https://github.boki.moe",
+ "https://gh.xxooo.cf",
+ "https://gh.llkk.cc",
+ "https://wget.la",
)
+AUTO_SITE_KEY = "__auto__"
CUSTOM_SITE_KEY = "__custom__"
-PROBE_TARGET = "https://github.com/cli/cli/releases/download/v2.62.0/gh_2.62.0_linux_amd64.tar.gz"
def toProxySite(site: str) -> str:
@@ -26,43 +42,13 @@ def toProxySite(site: str) -> str:
def selectedProxySite() -> str:
+ if githubConfig.selectedSite.value == AUTO_SITE_KEY:
+ return ""
if githubConfig.selectedSite.value == CUSTOM_SITE_KEY:
return githubConfig.customSite.value
return githubConfig.selectedSite.value
-PROBE_UNAVAILABLE = -1
-PROBE_TIMEOUT = -2
-
-
-async def probeProxyLatencies() -> dict[str, int]:
- import asyncio
- from time import perf_counter
-
- sites = list(GITHUB_PROXY_SITES)
- custom = githubConfig.customSite.value
- if custom:
- sites.append(custom)
-
- async def probeOne(site: str) -> tuple[str, int]:
- url = f"{site.rstrip('/')}/{PROBE_TARGET}"
- client = buildClient()
- try:
- start = perf_counter()
- response = await asyncio.wait_for(client.head(url), timeout=10)
- elapsed = int((perf_counter() - start) * 1000)
- return site, elapsed if response.status.as_int() < 400 else PROBE_UNAVAILABLE
- except (asyncio.TimeoutError, TimeoutError):
- return site, PROBE_TIMEOUT
- except Exception:
- return site, PROBE_TIMEOUT
- finally:
- client.close()
-
- results = await asyncio.gather(*(probeOne(s) for s in sites))
- return dict(results)
-
-
class GitHubProxySiteValidator(ConfigValidator):
def validate(self, value) -> bool:
site = toProxySite(value)
@@ -84,7 +70,10 @@ class GitHubProxySiteValidator(ConfigValidator):
class GitHubConfig(PackConfig):
enabled = ConfigItem("GitHub", "Enabled", False, BoolValidator())
- selectedSite = ConfigItem("GitHub", "SelectedSite", GITHUB_PROXY_SITES[0], GitHubProxySiteValidator())
+ selectedSite = ConfigItem(
+ "GitHub", "SelectedSite", AUTO_SITE_KEY,
+ OptionsValidator([AUTO_SITE_KEY, *GITHUB_PROXY_SITES, CUSTOM_SITE_KEY]),
+ )
customSite = ConfigItem("GitHub", "CustomSite", "", GitHubProxySiteValidator())
def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
@@ -95,7 +84,7 @@ class GitHubConfig(PackConfig):
githubGroup = CollapsibleSettingCardGroup(self.tr("GitHub 加速"), "github", parent)
enableCard = SwitchSettingCard(
FluentIcon.LINK, self.tr("启用 GitHub 加速"),
- self.tr("优先使用所选代理站,不可用时自动切换其他站点或直连"),
+ self.tr("经代理站下载 GitHub 文件,不可用时自动切换其他站点或直连"),
self.enabled, githubGroup,
)
proxySiteCard = GitHubProxySiteCard(self.submit, githubGroup)
diff --git a/features/github_pack/pack.py b/features/github_pack/pack.py
index bc7b0da0..d96c9139 100644
--- a/features/github_pack/pack.py
+++ b/features/github_pack/pack.py
@@ -4,12 +4,12 @@ from urllib.parse import urlparse
from loguru import logger
-from app.client import buildClient
from app.models.pack import FeaturePack, TaskParser
-from app.models.task import Task, TaskError, TaskOptions, ResourceTaskOptions
+from app.models.task import Task, TaskOptions
from http_pack.pack import HttpParser
from http_pack.task import HttpTask, HttpTaskStep
from .config import githubConfig, selectedProxySite, GITHUB_PROXY_SITES
+from .probe import probeUrls, toProxyHeaders
GITHUB_HOSTS = {
"api.github.com",
@@ -70,6 +70,7 @@ class GitHubHttpTaskStep(HttpTaskStep):
nextUrl = self.fallbackUrls.pop(0)
logger.warning("GitHub 下载 fallback: {} → {}", self.url, nextUrl)
self.url = nextUrl
+ self.headers = toProxyHeaders(self.headers)
self.subworkers = []
self.receivedBytes = 0
self.progress = 0
@@ -84,63 +85,37 @@ class GitHubParser(TaskParser):
priority = 90
def match(self, options: TaskOptions) -> bool:
- return (
- githubConfig.enabled.value
- and bool(selectedProxySite())
- and isGitHubFileUrl(options.url)
- )
+ return githubConfig.enabled.value and isGitHubFileUrl(options.url)
async def parse(self, options: TaskOptions) -> Task:
- fallbackUrls = self._buildFallbackUrls(options.url)
- isResourceWithName = isinstance(options, ResourceTaskOptions) and options.name
+ originalUrl = options.url
+ selected = selectedProxySite()
+ urls = [f"{site}/{originalUrl}" for site in GITHUB_PROXY_SITES if site != selected] + [originalUrl]
- lastError = None
- for i, url in enumerate(fallbackUrls):
- isDirectUrl = (url == options.url)
+ winner = ""
+ if selected:
try:
- if isResourceWithName and not isDirectUrl:
- await self._probeProxy(url, options.headers)
-
- if isDirectUrl:
- task = await HttpParser().parse(options)
- else:
- task = await self.delegate(replace(options, url=url))
-
- remaining = fallbackUrls[i + 1:]
- if remaining:
- step = task.steps[0]
- if isinstance(step, HttpTaskStep):
- githubStep = GitHubHttpTaskStep.build(step, remaining)
- task.steps[0] = githubStep
- githubStep._bindTask(task)
-
- task.url = options.url
- task.packId = "github"
- return task
+ await probeUrls([f"{selected}/{originalUrl}"], originalUrl, options.headers)
+ winner, fallbackUrls = f"{selected}/{originalUrl}", urls
except Exception as e:
- lastError = e
- logger.warning("GitHub proxy 不可用 {}: {}", url, e)
-
- raise lastError
-
- def _buildFallbackUrls(self, originalUrl: str) -> list[str]:
- selected = selectedProxySite()
- urls = [f"{selected.rstrip('/')}/{originalUrl}"]
- for site in GITHUB_PROXY_SITES:
- if site != selected:
- urls.append(f"{site.rstrip('/')}/{originalUrl}")
- urls.append(originalUrl)
- return urls
-
- async def _probeProxy(self, url: str, headers: dict) -> None:
- client = buildClient(timeout=10)
- try:
- response = await client.get(
- url, headers={**headers, "range": "bytes=0-0", "accept-encoding": "identity"},
- )
- response.close()
- finally:
- client.close()
+ 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)
+ task.steps[0] = githubStep
+ githubStep._bindTask(task)
+
+ task.url = originalUrl
+ task.packId = "github"
+ return task
class GitHubPack(FeaturePack):
diff --git a/features/github_pack/probe.py b/features/github_pack/probe.py
new file mode 100644
index 00000000..f01d5423
--- /dev/null
+++ b/features/github_pack/probe.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+import asyncio
+from time import perf_counter
+from urllib.parse import urlparse
+
+from loguru import logger
+
+from app.client import buildClient
+from app.models.task import TaskError
+from .config import GITHUB_PROXY_SITES, githubConfig
+
+PROBE_TARGET = "https://github.com/cli/cli/releases/download/v2.62.0/gh_2.62.0_linux_amd64.tar.gz"
+PROBE_UNAVAILABLE = -1
+PROBE_TIMEOUT = -2
+
+
+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:
+ 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/")
+
+ total = headers.get("content-range", "").rpartition("/")[2]
+ return status == 206 and total.isdigit() and int(total) > 0
+
+
+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 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}
+ pending = set(urlByTask)
+ unmatchedUrls = set()
+ lastError = None
+ try:
+ while pending:
+ done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
+ 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]
+ unmatchedUrls.add(url)
+ lastError = task.exception()
+ logger.debug("GitHub 候选不可用 {}: {}", url, lastError)
+ raise lastError
+ finally:
+ for task in pending:
+ task.cancel()
+ await asyncio.gather(*pending, return_exceptions=True)
+
+
+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:
+ return site, PROBE_TIMEOUT
+ if not matchResponse(PROBE_TARGET, status, headers):
+ return site, PROBE_UNAVAILABLE
+ return site, int((perf_counter() - start) * 1000)
+
+ sites = list(GITHUB_PROXY_SITES)
+ if githubConfig.customSite.value:
+ sites.append(githubConfig.customSite.value)
+ return dict(await asyncio.gather(*(probeOne(s) for s in sites)))
diff --git a/features/github_pack/setting_cards.py b/features/github_pack/setting_cards.py
index beab5704..dbd0fa0a 100644
--- a/features/github_pack/setting_cards.py
+++ b/features/github_pack/setting_cards.py
@@ -5,14 +5,10 @@ from urllib.parse import urlparse
from qfluentwidgets import ComboBox, FluentIcon, LineEdit, SettingCard, ToolButton, ToolTipFilter
-from .config import (
- CUSTOM_SITE_KEY,
- GITHUB_PROXY_SITES,
- PROBE_TIMEOUT,
- PROBE_UNAVAILABLE,
- githubConfig,
- probeProxyLatencies,
-)
+from .config import AUTO_SITE_KEY, CUSTOM_SITE_KEY, GITHUB_PROXY_SITES, githubConfig
+from .probe import PROBE_TIMEOUT, PROBE_UNAVAILABLE, probeProxyLatencies
+
+SITE_OPTIONS = [AUTO_SITE_KEY, *GITHUB_PROXY_SITES, CUSTOM_SITE_KEY]
class GitHubProxySiteCard(SettingCard):
@@ -40,17 +36,13 @@ class GitHubProxySiteCard(SettingCard):
self.refreshButton.setToolTip(self.tr("刷新延迟"))
self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))
+ self.comboBox.addItem(self.tr("自动"))
for site in GITHUB_PROXY_SITES:
self.comboBox.addItem(urlparse(site).netloc or site.rstrip("/"))
self.comboBox.addItem(self.tr("自定义"))
currentSite = githubConfig.selectedSite.value
- if currentSite == CUSTOM_SITE_KEY:
- self.comboBox.setCurrentIndex(len(GITHUB_PROXY_SITES))
- elif currentSite in GITHUB_PROXY_SITES:
- self.comboBox.setCurrentIndex(GITHUB_PROXY_SITES.index(currentSite))
- else:
- self.comboBox.setCurrentIndex(0)
+ self.comboBox.setCurrentIndex(SITE_OPTIONS.index(currentSite))
self.customSiteEdit.setText(githubConfig.customSite.value)
self.customSiteEdit.setVisible(currentSite == CUSTOM_SITE_KEY)
@@ -77,7 +69,7 @@ class GitHubProxySiteCard(SettingCard):
return f"{latency} ms"
def _refreshLatencyLabels(self):
- for i, site in enumerate(GITHUB_PROXY_SITES):
+ for i, site in enumerate(GITHUB_PROXY_SITES, start=1):
displayName = urlparse(site).netloc or site.rstrip("/")
tag = self._latencyTag(self._latencies.get(site))
label = f"{displayName} ({tag})" if tag else displayName
@@ -87,17 +79,14 @@ class GitHubProxySiteCard(SettingCard):
customLatency = self._latencies.get(customSite) if customSite else None
tag = self._latencyTag(customLatency)
customLabel = f"{self.tr('自定义')} ({tag})" if tag else self.tr("自定义")
- self.comboBox.setItemText(len(GITHUB_PROXY_SITES), customLabel)
+ self.comboBox.setItemText(SITE_OPTIONS.index(CUSTOM_SITE_KEY), customLabel)
def _onCurrentIndexChanged(self, index: int):
from app.config.cfg import cfg
if index < 0:
return
- if index < len(GITHUB_PROXY_SITES):
- cfg.set(githubConfig.selectedSite, GITHUB_PROXY_SITES[index])
- else:
- cfg.set(githubConfig.selectedSite, CUSTOM_SITE_KEY)
- self.customSiteEdit.setVisible(index >= len(GITHUB_PROXY_SITES))
+ cfg.set(githubConfig.selectedSite, SITE_OPTIONS[index])
+ self.customSiteEdit.setVisible(SITE_OPTIONS[index] == CUSTOM_SITE_KEY)
def _onCustomSiteEditingFinished(self):
from app.config.cfg import cfg
diff --git a/tests/test_github_probe.py b/tests/test_github_probe.py
new file mode 100644
index 00000000..44f54ae5
--- /dev/null
+++ b/tests/test_github_probe.py
@@ -0,0 +1,83 @@
+"""GitHub 加速的选站:响应判定规则与竞速。
+
+使用本地 aiohttp 服务器模拟 Proxy Site,不连外网。
+"""
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from aiohttp import web
+
+from github_pack.probe import matchResponse, probeUrls
+
+ASSET_URL = "https://github.com/o/r/releases/download/v1/a.tar.gz"
+RAW_URL = "https://raw.githubusercontent.com/o/r/main/README.md"
+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 testMatchResponse(originalUrl, status, headers, expected):
+ assert matchResponse(originalUrl, status, headers) is expected
+
+
+def buildSiteHandler(*, delay: float = 0, status: int = 206, contentType: str = "application/octet-stream",
+ requests: list | None = None):
+ async def handler(request: web.Request) -> web.Response:
+ if requests is not None:
+ requests.append(dict(request.headers))
+ await asyncio.sleep(delay)
+ headers = {"Content-Type": contentType}
+ if status == 206:
+ headers["Content-Range"] = "bytes 0-0/100"
+ return web.Response(status=status, body=b"x", headers=headers)
+ return handler
+
+
+async def testFirstMatchedWins(server):
+ slow = await server(buildSiteHandler(delay=2))
+ 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, {})
+
+ assert winner == good
+ assert fallbackUrls == [slow]
+
+
+async def testAllUnmatchedRaises(server):
+ fake = await server(buildSiteHandler(status=200, contentType="text/html"))
+ denied = await server(buildSiteHandler(status=403))
+
+ with pytest.raises(Exception):
+ await probeUrls([fake, denied], ASSET_URL, {})
+
+
+async def testProxySiteGetsNoCredentials(server):
+ directRequests, proxyRequests = [], []
+ direct = await server(buildSiteHandler(delay=0.2, requests=directRequests))
+ 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)
+
+ assert directRequests[0]["Authorization"] == "token t"
+ assert "Authorization" not in proxyRequests[0]
+ assert "Cookie" not in proxyRequests[0]
+ assert proxyRequests[0]["X-Other"] == "1"