Skip to content

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

禁用 niquests, 重新拥抱 httpx

XiaoYouChR0dba221a5c79
diff --git a/app/common/download_task.py b/app/common/download_task.py
index bb3efaf3..7902a664 100644
--- a/app/common/download_task.py
+++ b/app/common/download_task.py
@@ -4,12 +4,12 @@ import sys
import time
from abc import ABC, abstractmethod
from asyncio import Task
-from collections import deque
from pathlib import Path
from threading import Thread
from typing import List
+from collections import deque
-import niquests
+import httpx
from PySide6.QtCore import QThread, Signal
from loguru import logger
@@ -21,7 +21,7 @@ from app.common.methods import getProxy, getReadableSize, getLinkInfo, createSpa
class DownloadWorker:
"""Worker responsible for downloading a specific range of a file"""
- def __init__(self, start, progress, end, client: niquests.AsyncSession):
+ def __init__(self, start, progress, end, client: httpx.AsyncClient):
self.startPos = start
self.progress = progress
self.endPos = end
@@ -67,7 +67,7 @@ class DownloadWorker:
class WorkerStrategy(ABC):
"""Base strategy for handling download workers"""
- def __init__(self, file, client: niquests.AsyncSession, url: str):
+ def __init__(self, file, client: httpx.AsyncClient, url: str):
self.file = file
self.client = client
self.url = url
@@ -93,23 +93,24 @@ class ParallelDownloadStrategy(WorkerStrategy):
workingRangeHeaders = self.client.headers.copy()
workingRangeHeaders["range"] = f"bytes={worker.progress}-{worker.endPos - 1}"
- res = await self.client.get(url=self.url, headers=workingRangeHeaders, timeout=30, stream=True)
- res.raise_for_status()
- if res.status_code != 206:
- raise Exception(f"Server rejected range request, status code: {res.status_code}")
+ async with self.client.stream(url=self.url, headers=workingRangeHeaders,
+ timeout=30, method="GET") as res:
+ res.raise_for_status()
+ if res.status_code != 206:
+ raise Exception(f"Server rejected range request, status code: {res.status_code}")
- async for chunk in await res.iter_raw(chunk_size=65536):
- if worker.isCompleted:
- break
+ async for chunk in res.aiter_bytes(chunk_size=65536):
+ if worker.isCompleted:
+ break
- if chunk:
- self.file.seek(worker.progress)
- self.file.write(chunk)
- worker.progress += 65536
- cfg.globalSpeed += 65536
+ if chunk:
+ self.file.seek(worker.progress)
+ self.file.write(chunk)
+ worker.progress += 65536
+ cfg.globalSpeed += 65536
- if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:
- await asyncio.sleep(1.5)
+ if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:
+ await asyncio.sleep(2)
worker.progress = worker.endPos
@@ -123,7 +124,7 @@ class ParallelDownloadStrategy(WorkerStrategy):
class SingleDownloadStrategy(WorkerStrategy):
"""Strategy for non-parallel downloading"""
- def __init__(self, file, client: niquests.AsyncSession, url: str, onComplete: callable = None):
+ def __init__(self, file, client: httpx.AsyncClient, url: str, onComplete: callable = None):
super().__init__(file, client, url)
self.onComplete = onComplete
@@ -137,19 +138,20 @@ class SingleDownloadStrategy(WorkerStrategy):
while worker.progress <= worker.endPos:
try:
workingHeaders = self.client.headers.copy()
- res = await self.client.get(url=self.url, headers=workingHeaders, timeout=30, stream=True)
- res.raise_for_status()
+ async with self.client.stream(url=self.url, headers=workingHeaders,
+ timeout=30, method="GET") as res:
+ res.raise_for_status()
- async for chunk in await res.iter_raw():
- if chunk:
- self.file.seek(worker.progress)
- self.file.write(chunk)
- chunkSize = len(chunk)
- worker.progress += chunkSize
- cfg.globalSpeed += chunkSize
+ async for chunk in res.aiter_bytes():
+ if chunk:
+ self.file.seek(worker.progress)
+ self.file.write(chunk)
+ chunkSize = len(chunk)
+ worker.progress += chunkSize
+ cfg.globalSpeed += chunkSize
- if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:
- await asyncio.sleep(1.5)
+ if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:
+ await asyncio.sleep(2)
if self.onComplete:
self.onComplete()
@@ -222,13 +224,15 @@ class DownloadTask(QThread):
self.historyProgress = deque([self.progress] * 10) # Rolling window of 10 seconds for speed calculation
# HTTP client setup
- proxies = getProxy()
- self.client = niquests.AsyncSession()
- self.client.headers = headers
- self.client.verify = cfg.SSLVerify.value
- self.client.proxies = proxies
- self.client.trust_env = False
- self.client.allow_redirects = True
+ proxy = getProxy()
+ self.client = httpx.AsyncClient(
+ headers=headers,
+ verify=cfg.SSLVerify.value,
+ proxy=proxy,
+ limits=httpx.Limits(max_connections=256),
+ trust_env=False,
+ follow_redirects=True
+ )
# Initialize task in a separate thread
self.initThread = Thread(target=self.__initTask, daemon=True)
@@ -521,7 +525,7 @@ class DownloadTask(QThread):
async def handleWorker(self, worker: DownloadWorker):
await self.downloadStrategy.handleWorker(worker)
if not self.autoSpeedUp or self.taskNum <= self.preBlockNum:# 如果开启了自动提速且添加了额外线程,则重新分配工作线程由自动提速控制
- # print("autoSpeedUp is off, reassigning worker")
+ print("autoSpeedUp is off, reassigning worker")
self.__reassignWorker()
self.doneTask += 1
@@ -599,7 +603,7 @@ class DownloadTask(QThread):
try:
await self.supervisorTask
except asyncio.CancelledError:
- await self.client.close()
+ await self.client.aclose()
# Clean up resources
await self.__cleanupResources()
@@ -613,7 +617,7 @@ class DownloadTask(QThread):
async def __cleanupResources(self):
"""Clean up resources after download completes or is cancelled"""
# Close HTTP client
- await self.client.close()
+ await self.client.aclose()
# Close the download file
if self.file:
diff --git a/app/common/methods.py b/app/common/methods.py
index 9321c624..2da91451 100644
--- a/app/common/methods.py
+++ b/app/common/methods.py
@@ -10,12 +10,12 @@ from email.utils import decode_rfc2231
from functools import wraps
from pathlib import Path
from time import sleep, localtime, time_ns
-from typing import Optional
from urllib.parse import unquote, parse_qs, urlparse
-import niquests
+import httpx
from PySide6.QtCore import QUrl, QOperatingSystemVersion
from PySide6.QtGui import QDesktopServices
+from PySide6.QtWidgets import QApplication
from loguru import logger
from qfluentwidgets import MessageBox
@@ -25,28 +25,23 @@ from app.common.signal_bus import signalBus
plugins = []
-
def isGreaterEqualWin10():
""" determine if the Windows version ≥ Win10 """
cv = QOperatingSystemVersion.current()
return sys.platform == "win32" and cv.majorVersion() >= 10
-
def isLessThanWin10():
""" determine if the Windows version < Win10"""
cv = QOperatingSystemVersion.current()
return sys.platform == "win32" and cv.majorVersion() < 10
-
def isGreaterEqualWin11():
""" determine if the windows version ≥ Win11 """
return isGreaterEqualWin10() and sys.getwindowsversion().build >= 22000
-
def isAbleToShowToast():
return (sys.platform == 'win32' and sys.getwindowsversion().build >= 10240) or True
-
def loadPlugins(mainWindow, directory="{}/plugins".format(cfg.appPath)):
try:
for filename in os.listdir(directory):
@@ -76,7 +71,7 @@ def loadPlugins(mainWindow, directory="{}/plugins".format(cfg.appPath)):
logger.error(f"Error loading plugins: {e}")
-def getSystemProxy() -> Optional[str]:
+def getSystemProxy():
if sys.platform == "win32":
try:
import winreg
@@ -120,19 +115,13 @@ def getSystemProxy() -> Optional[str]:
return None
-def getProxy() -> Optional[dict]:
+def getProxy():
if cfg.proxyServer.value == "Off":
return None
elif cfg.proxyServer.value == "Auto":
- return {
- "http": getSystemProxy(),
- "https": getSystemProxy(),
- }
+ return getSystemProxy()
else:
- return {
- "http": cfg.proxyServer.value,
- "https": cfg.proxyServer.value,
- }
+ return cfg.proxyServer.value
def getReadableSize(size):
@@ -176,7 +165,7 @@ def retry(retries: int = 3, delay: float = 0.1, handleFunction: callable = None)
break
else:
logger.warning(
- f'Error: {repr(e)}! "{func.__name__}()"执行失败,将在{delay}秒后第[{i + 1}/{retries}]次重试...'
+ f'Error: {repr(e)}! "{func.__name__}()"执行失败,将在{delay}秒后第[{i+1}/{retries}]次重试...'
)
sleep(delay)
@@ -194,7 +183,7 @@ def openFile(fileResolve):
QDesktopServices.openUrl(QUrl.fromLocalFile(fileResolve))
-def getLocalTimeFromGithubApiTime(gmtTimeStr: str):
+def getLocalTimeFromGithubApiTime(gmtTimeStr:str):
# 解析 GMT 时间
gmtTime = datetime.fromisoformat(gmtTimeStr.replace("Z", "+00:00"))
@@ -234,20 +223,13 @@ def getLocalTimeFromGithubApiTime(gmtTimeStr: str):
# except Exception as e:
# logger.error(f"Could not register the application: {e}")
-
-def getLinkInfo(url: str, headers: dict, fileName: str = "", verify: bool = cfg.SSLVerify.value, proxies=None,
- followRedirects: bool = True) -> tuple:
- if proxies is not None:
- proxies = getProxy()
- else:
- proxies = {}
-
+def getLinkInfo(url: str, headers: dict, fileName: str = "", verify: bool = cfg.SSLVerify.value, proxy: str = "", followRedirects: bool = True) -> tuple:
+ if not proxy:
+ proxy = getProxy()
headers = headers.copy()
- headers["Range"] = "bytes=0-" #尝试发送范围请求
-
+ headers["Range"] = "bytes=0-"#尝试发送范围请求
# 使用 stream 请求获取响应, 反爬
- with niquests.get(url, headers=headers, verify=verify, proxies=proxies, allow_redirects=followRedirects,
- stream=True) as response:
+ with httpx.stream("GET", url, headers=headers, verify=verify, proxy=proxy, follow_redirects=followRedirects, trust_env=False) as response:
response.raise_for_status() # 如果状态码不是 2xx,抛出异常
head = response.headers
@@ -262,8 +244,7 @@ def getLinkInfo(url: str, headers: dict, fileName: str = "", verify: bool = cfg.
if right != "*":
fileSize = int(right)
- logger.info(
- f"content-range: {head['content-range']}, fileSize: {fileSize}, content-length: {head['content-length']}")
+ logger.info(f"content-range: {head['content-range']}, fileSize: {fileSize}, content-length: {head['content-length']}")
elif "content-length" in head:
fileSize = int(head["content-length"])
@@ -353,8 +334,7 @@ def bringWindowToTop(window):
def addDownloadTask(url: str, fileName: str = None, filePath: str = None,
- headers: dict = None, status: str = "working", preBlockNum: int = None,
- notCreateHistoryFile: bool = False, fileSize: int = -1):
+ headers: dict = None, status:str = "working", preBlockNum: int= None, notCreateHistoryFile: bool = False, fileSize: int = -1):
""" Global function to add download task """
if not filePath:
filePath = cfg.downloadFolder.value
@@ -365,9 +345,7 @@ def addDownloadTask(url: str, fileName: str = None, filePath: str = None,
if not headers:
headers = Headers
- signalBus.addTaskSignal.emit(url, fileName, filePath, headers, status, preBlockNum, notCreateHistoryFile,
- str(fileSize))
-
+ signalBus.addTaskSignal.emit(url, fileName, filePath, headers, status, preBlockNum, notCreateHistoryFile, str(fileSize))
def showMessageBox(self, title: str, content: str, showYesButton=False, yesSlot=None):
""" show message box """
@@ -414,14 +392,14 @@ def isSparseSupported(filePath: Path) -> bool:
# 调用 Windows API 获取卷信息
success = ctypes.windll.kernel32.GetVolumeInformationW(
- ctypes.c_wchar_p(rootPath), # 根路径
- volumeNameBuffer, # 卷名缓冲区
- ctypes.sizeof(volumeNameBuffer), # 缓冲区大小
- None, # 序列号
- None, # 最大组件长度
- None, # 文件系统标志
- fileSystemBuffer, # 文件系统名称缓冲区
- ctypes.sizeof(fileSystemBuffer) # 缓冲区大小
+ ctypes.c_wchar_p(rootPath), # 根路径
+ volumeNameBuffer, # 卷名缓冲区
+ ctypes.sizeof(volumeNameBuffer), # 缓冲区大小
+ None, # 序列号
+ None, # 最大组件长度
+ None, # 文件系统标志
+ fileSystemBuffer, # 文件系统名称缓冲区
+ ctypes.sizeof(fileSystemBuffer) # 缓冲区大小
)
if not success:
@@ -462,7 +440,6 @@ def isSparseSupported(filePath: Path) -> bool:
logger.warning(f"文件系统检测失败: {repr(e)}")
return False
-
def createSparseFile(filePath: Path) -> bool:
"""
创建一个支持稀疏写入的空文件。
@@ -489,8 +466,8 @@ def createSparseFile(filePath: Path) -> bool:
["fsutil", "sparse", "setflag", str(filePath)],
capture_output=True,
text=True,
- check=True, # 如果命令返回非零退出码,则引发 CalledProcessError
- creationflags=subprocess.CREATE_NO_WINDOW # 不显示控制台窗口
+ check=True, # 如果命令返回非零退出码,则引发 CalledProcessError
+ creationflags=subprocess.CREATE_NO_WINDOW # 不显示控制台窗口
)
# check=True 会处理错误,但为清晰起见保留检查
if result.returncode != 0:
diff --git a/app/components/update_dialog.py b/app/components/update_dialog.py
index 51083a9d..2f27c2d4 100644
--- a/app/components/update_dialog.py
+++ b/app/components/update_dialog.py
@@ -1,4 +1,4 @@
-import niquests
+import httpx
from PySide6.QtCore import QThread, Signal, QVersionNumber
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QTableWidgetItem
@@ -19,9 +19,9 @@ class GetUpdateThread(QThread):
def run(self):
try:
_ = getProxy()
- content = niquests.get(url="https://api.github.com/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest", headers={
+ content = httpx.get(url="https://api.github.com/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest", 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).json()
+ proxy=_, follow_redirects=True, trust_env=False).json()
tagName = content["tag_name"][1:]
diff --git a/deploy.py b/deploy.py
index b004d00f..4b7c1db7 100644
--- a/deploy.py
+++ b/deploy.py
@@ -31,6 +31,7 @@ elif sys.platform == "darwin":
'--plugin-enable=pyside6',
# '--show-memory',
# '--show-progress',
+ '--static-libpython=no',
"--macos-create-app-bundle",
"--assume-yes-for-download",
"--macos-app-mode=gui",
diff --git a/plugins/jy_os_page.py.DISABLE b/plugins/jy_os_page.py.DISABLE
index 72bbce4c..c17c1311 100644
--- a/plugins/jy_os_page.py.DISABLE
+++ b/plugins/jy_os_page.py.DISABLE
@@ -48,7 +48,7 @@ class getInfoThread(QThread):
url="https://seelevollerei-my.sharepoint.com/personal/jackyao_xn--7et36u_cn/_layouts/52/download.aspx?share=Ecm5kLYVJedKlw60gcDkxPEB1PlS5Y-P-ttDSit_V8KuLw",
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"},
- proxy=_, allow_redirects=True, trust_env=False).text)["OS"])
+ proxy=_, follow_redirects=True, trust_env=False).text)["OS"])
class HomeInterface(SmoothScrollArea):
diff --git a/requirements.txt b/requirements.txt
index a5c97c34..63de9b12 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,7 +2,7 @@ PySide6-Fluent-Widgets>=1.8.0
PysideSix-Frameless-Window>=0.7.1
PySide6==6.8.3
loguru
-niquests[socks]
+httpx[socks]
nuitka==2.7.11
desktop-notifier
darkdetect[macos-listener]; sys_platform=="darwin"