The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor: 统一异步会话管理
XiaoYouChR3b115352e457
diff --git a/features/bili_pack/login.py b/features/bili_pack/login.pyindex 396e7985..0be308a0 100644--- a/features/bili_pack/login.py+++ b/features/bili_pack/login.py@@ -74,25 +74,20 @@ def _extractCookie(response, successUrl: str) -> str:async def requestQrCode() -> dict[str, str]:- client = niquests.AsyncSession(+ async with niquests.AsyncSession(headers=_headers(),timeout=30,happy_eyeballs=True,- )- client.trust_env = False-- try:+ ) as client:+ client.trust_env = Falseresponse = await client.get(_QR_GENERATE_API,proxies=getProxies(),verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- payload = response.json()- finally:- response.close()+ response.raise_for_status()+ payload = response.json()if payload.get("code") not in {None, 0}:raise ValueError(payload.get("message") or "获取二维码失败")@@ -107,8 +102,6 @@ async def requestQrCode() -> dict[str, str]:"url": loginUrl,"qrcode_key": qrCodeKey,}- finally:- await client.close()async def pollQrLogin(@@ -118,14 +111,13 @@ async def pollQrLogin() -> dict[str, str | int]:from app.services.core_service import coreService- client = niquests.AsyncSession(+ async with niquests.AsyncSession(headers=_headers(),timeout=30,happy_eyeballs=True,- )- client.trust_env = False+ ) as client:+ client.trust_env = False- try:while True:if shouldStop is not None and shouldStop():return {"code": -1, "message": "cancelled", "url": "", "cookie": ""}@@ -137,13 +129,10 @@ async def pollQrLogin(verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- payload = response.json()- data = payload.get("data") or {}- cookieString = _extractCookie(response, str(data.get("url") or "")) if data.get("code") == 0 else ""- finally:- response.close()+ response.raise_for_status()+ payload = response.json()+ data = payload.get("data") or {}+ cookieString = _extractCookie(response, str(data.get("url") or "")) if data.get("code") == 0 else ""if payload.get("code") not in {None, 0}:raise ValueError(payload.get("message") or "轮询扫码状态失败")@@ -163,8 +152,6 @@ async def pollQrLogin(continuereturn result- finally:- await client.close()async def fetchLoginInfo(cookie: str) -> dict[str, str | bool]:@@ -177,25 +164,20 @@ async def fetchLoginInfo(cookie: str) -> dict[str, str | bool]:"vip": "未开通",}- client = niquests.AsyncSession(+ async with niquests.AsyncSession(headers=_headers(cookie),timeout=30,happy_eyeballs=True,- )- client.trust_env = False-- try:+ ) as client:+ client.trust_env = Falseresponse = await client.get(_LOGIN_INFO_API,proxies=getProxies(),verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- payload = response.json()- finally:- response.close()+ response.raise_for_status()+ payload = response.json()data = payload.get("data") or {}if payload.get("code") == -101 or not data.get("isLogin"):@@ -229,8 +211,6 @@ async def fetchLoginInfo(cookie: str) -> dict[str, str | bool]:"mid": str(data.get("mid") or "-"),"vip": vipText,}- finally:- await client.close()async def logout(cookie: str) -> dict[str, str | bool]:@@ -250,14 +230,12 @@ async def logout(cookie: str) -> dict[str, str | bool]:"message": f"Cookie 缺少 {', '.join(missingCookies)},已清除本地登录状态",}- client = niquests.AsyncSession(+ async with niquests.AsyncSession(headers=_headers(cookie, origin=True),timeout=30,happy_eyeballs=True,- )- client.trust_env = False-- try:+ ) as client:+ client.trust_env = Falseresponse = await client.post(_LOGOUT_API,data={@@ -268,19 +246,16 @@ async def logout(cookie: str) -> dict[str, str | bool]:verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- contentType = str(response.headers.get("content-type") or "").lower()- if "application/json" not in contentType:- return {- "remote_logout": False,- "clear_local": True,- "message": "当前 Cookie 可能已失效,已清除本地登录状态",- }+ response.raise_for_status()+ contentType = str(response.headers.get("content-type") or "").lower()+ if "application/json" not in contentType:+ return {+ "remote_logout": False,+ "clear_local": True,+ "message": "当前 Cookie 可能已失效,已清除本地登录状态",+ }- payload = response.json()- finally:- response.close()+ payload = response.json()if payload.get("code") == 0 and payload.get("status") is True:return {@@ -290,5 +265,3 @@ async def logout(cookie: str) -> dict[str, str | bool]:}raise ValueError(payload.get("message") or "退出登录失败")- finally:- await client.close()diff --git a/features/bili_pack/pack.py b/features/bili_pack/pack.pyindex 62f48121..3aefbaf3 100644--- a/features/bili_pack/pack.py+++ b/features/bili_pack/pack.py@@ -202,18 +202,14 @@ class BilibiliPack(FeaturePack):path: Path = payload.get("path", Path(cfg.downloadFolder.value))headers = _buildBilibiliHeaders(url)- client = niquests.AsyncSession(headers=headers, timeout=60, happy_eyeballs=True)- client.trust_env = False+ async with niquests.AsyncSession(headers=headers, timeout=60, happy_eyeballs=True) as client:+ client.trust_env = False- try:videoId, selectedPages = _parseVideoIdAndPages(url)response = await client.get(_buildViewApiUrl(videoId), proxies=proxies, allow_redirects=True)- try:- response.raise_for_status()- videoPayload = response.json()- finally:- response.close()+ response.raise_for_status()+ videoPayload = response.json()if videoPayload.get("code") not in {None, 0}:raise ValueError(videoPayload.get("message") or "获取 Bilibili 视频信息失败")@@ -253,11 +249,8 @@ class BilibiliPack(FeaturePack):proxies=proxies,allow_redirects=True,)- try:- playResponse.raise_for_status()- playPayload = playResponse.json()- finally:- playResponse.close()+ playResponse.raise_for_status()+ playPayload = playResponse.json()if playPayload.get("code") not in {None, 0}:raise ValueError(playPayload.get("message") or "获取 Bilibili 音视频流失败")@@ -339,5 +332,3 @@ class BilibiliPack(FeaturePack):))return task- finally:- await client.close()diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pyindex 672f2fd7..269ab948 100644--- a/features/bittorrent_pack/task.py+++ b/features/bittorrent_pack/task.py@@ -603,9 +603,8 @@ async def _loadFromUrl(payload: dict, webTrackers: list[str]) -> tuple[bytes, ltheaders if isinstance(headers, dict) else DEFAULT_HEADERS)- client = niquests.AsyncSession(timeout=30, happy_eyeballs=True)- client.trust_env = False- try:+ async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:+ client.trust_env = Falseresponse = await client.get(url,headers=requestHeaders,@@ -614,13 +613,8 @@ async def _loadFromUrl(payload: dict, webTrackers: list[str]) -> tuple[bytes, ltverify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- torrentBytes = bytes(response.content)- finally:- await response.close()- finally:- await client.close()+ response.raise_for_status()+ torrentBytes = bytes(response.content)ti = lt.torrent_info(torrentBytes)return torrentBytes, ti, mergeTrackers(_extractTrackers(ti), webTrackers)diff --git a/features/bittorrent_pack/trackers.py b/features/bittorrent_pack/trackers.pyindex a00d0e85..6ac06c0c 100644--- a/features/bittorrent_pack/trackers.py+++ b/features/bittorrent_pack/trackers.py@@ -51,23 +51,16 @@ async def fetchWebTrackers(sourceUrl: str) -> list[str]:if not normalizedSource:raise ValueError("Web Tracker 源地址无效")- client = niquests.AsyncSession(headers=DEFAULT_HEADERS.copy(), timeout=30, happy_eyeballs=True)- client.trust_env = False-- try:+ async with niquests.AsyncSession(headers=DEFAULT_HEADERS.copy(), timeout=30, happy_eyeballs=True) as client:+ client.trust_env = Falseresponse = await client.get(normalizedSource,proxies=getProxies(),verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- trackers = parseTrackerText(response.text)- finally:- response.close()- finally:- await client.close()+ response.raise_for_status()+ trackers = parseTrackerText(response.text)if not trackers:raise ValueError("Web Tracker 源没有返回有效的 Tracker")diff --git a/features/ffmpeg_pack/pack.py b/features/ffmpeg_pack/pack.pyindex 6560c802..c5aec7f1 100644--- a/features/ffmpeg_pack/pack.py+++ b/features/ffmpeg_pack/pack.py@@ -82,23 +82,16 @@ def _selectReleaseAsset(assets: list[dict[str, Any]]) -> dict[str, Any]:async def _requestLatestReleaseAsset() -> dict[str, Any]:- client = niquests.AsyncSession(headers=_FFMPEG_HEADERS, timeout=30, happy_eyeballs=True)- client.trust_env = False-- try:+ async with niquests.AsyncSession(headers=_FFMPEG_HEADERS, timeout=30, happy_eyeballs=True) as client:+ client.trust_env = Falseresponse = await client.get(_FFMPEG_RELEASE_API,proxies=getProxies(),verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- payload = response.json()- finally:- response.close()- finally:- await client.close()+ response.raise_for_status()+ payload = response.json()assets = payload.get("assets")if not isinstance(assets, list):diff --git a/features/github_pack/config.py b/features/github_pack/config.pyindex 555a5db5..157cc2c7 100644--- a/features/github_pack/config.py+++ b/features/github_pack/config.py@@ -146,34 +146,31 @@ async def measureProxyLatencies() -> dict[str, int]:if customSite and customSite not in sites:sites.append(customSite)- session = niquests.AsyncSession(happy_eyeballs=True)- session.trust_env = False-- async def measureSiteLatency(site: str) -> tuple[str, int]:- startedAt = perf_counter()- try:- response = await session.get(- f"{site.rstrip('/')}/{GITHUB_PROBE_TARGET}",- timeout=15,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,- )- try:- response.raise_for_status()- finally:- await response.close()+ async with niquests.AsyncSession(happy_eyeballs=True) as session:+ session.trust_env = False- return site, max(1, int((perf_counter() - startedAt) * 1000))- except Exception as e:- logger.opt(exception=e).error("{} 测速失败", site)- return site, -1+ async def measureSiteLatency(site: str) -> tuple[str, int]:+ startedAt = perf_counter()+ try:+ response = await session.get(+ f"{site.rstrip('/')}/{GITHUB_PROBE_TARGET}",+ timeout=15,+ proxies=getProxies(),+ verify=cfg.SSLVerify.value,+ allow_redirects=True,+ stream=True,+ )+ try:+ response.raise_for_status()+ finally:+ await response.close()++ return site, max(1, int((perf_counter() - startedAt) * 1000))+ except Exception as e:+ logger.opt(exception=e).error("{} 测速失败", site)+ return site, -1- try:results = await asyncio.gather(*(measureSiteLatency(site) for site in sites))- finally:- await session.close()return dict(results)diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex a79e7a69..31cb075f 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -67,10 +67,9 @@ async def _sendProbe(client: niquests.AsyncSession, url: str, headers: dict, proasync def _probe(url: str, headers: dict, proxies: dict) -> tuple[int, bool, str, dict[str, str]]:- client = niquests.AsyncSession(happy_eyeballs=True)- client.trust_env = False+ async with niquests.AsyncSession(happy_eyeballs=True) as client:+ client.trust_env = False- try:statusCode, responseHeaders, finalUrl = await _sendProbe(client,url,@@ -116,8 +115,6 @@ async def _probe(url: str, headers: dict, proxies: dict) -> tuple[int, bool, strlogger.info("文件大小已知但未探测到 Range 支持, fileSize: {}", fileSize)return fileSize, False, finalUrl, responseHeaders- finally:- await client.close()def _fileName(url: str, headers: dict) -> str:diff --git a/features/jack_yao/pack.py b/features/jack_yao/pack.pyindex 678b0f8b..a541b55a 100644--- a/features/jack_yao/pack.py+++ b/features/jack_yao/pack.py@@ -38,19 +38,14 @@ class JackYaoPack(FeaturePack):async def run():- # with open("./Content.json", "r", encoding="utf-8") as f:- # self.json = json.loads(f.read())["OS"]- # f.close()- _ = getProxies()- client = niquests.AsyncSession(happy_eyeballs=True)- client.trust_env = False- result = await client.get(- url="https://xineko-my.sharepoint.com/personal/os_store_xineko_onmicrosoft_com/_layouts/52/download.aspx?share=IQCK7kKU1-8oSqWDNNPss2xeAbmG3v4cItTXNqW2NG9Hzwc",- headers={- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"},- proxies=_, allow_redirects=True)- await client.close()- return loads(result.text)["OS"]+ async with niquests.AsyncSession(happy_eyeballs=True) as client:+ client.trust_env = False+ result = await client.get(+ url="https://xineko-my.sharepoint.com/personal/os_store_xineko_onmicrosoft_com/_layouts/52/download.aspx?share=IQCK7kKU1-8oSqWDNNPss2xeAbmG3v4cItTXNqW2NG9Hzwc",+ headers={+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"},+ proxies=getProxies(), allow_redirects=True)+ return loads(result.text)["OS"]class LoadingStatusWidget(QWidget):diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex 2027a452..36914b07 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -32,10 +32,8 @@ class M3U8Pack(FeaturePack):headers if isinstance(headers, dict) else DEFAULT_HEADERS)- client = niquests.AsyncSession(timeout=30, happy_eyeballs=True)- client.trust_env = False-- try:+ async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:+ client.trust_env = Falseresponse = await client.get(url,headers=requestHeaders,@@ -44,18 +42,13 @@ class M3U8Pack(FeaturePack):verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- body = response.text- loweredHeaders = {key.lower(): value for key, value in response.headers.items()}- manifestType = _manifestType(str(response.url), loweredHeaders, body)- isLive = _isLive(manifestType, body)- extension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value- title = _title(str(response.url), loweredHeaders, extension)- finally:- response.close()- finally:- await client.close()+ response.raise_for_status()+ body = response.text+ loweredHeaders = {key.lower(): value for key, value in response.headers.items()}+ manifestType = _manifestType(str(response.url), loweredHeaders, body)+ isLive = _isLive(manifestType, body)+ extension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value+ title = _title(str(response.url), loweredHeaders, extension)if isinstance(headers, dict):headers = headers.copy()diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.pyindex d4b34d15..e8941720 100644--- a/features/m3u8_pack/task.py+++ b/features/m3u8_pack/task.py@@ -352,22 +352,16 @@ async def createInstallTask() -> Task:else:raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")- client = niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True)- client.trust_env = False- try:+ async with niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True) as client:+ client.trust_env = Falseresponse = await client.get(_M3U8DL_RELEASE_API,proxies=getProxies(),verify=cfg.SSLVerify.value,allow_redirects=True,)- try:- response.raise_for_status()- payload = response.json()- finally:- response.close()- finally:- await client.close()+ response.raise_for_status()+ payload = response.json()assets = payload.get("assets")if not isinstance(assets, list):