The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
优化函数名,添加Retry Decorator
XiaoYouChR3a63aae04806
diff --git a/app/common/download_task.py b/app/common/download_task.pyindex 3e786ac5..5d1aae48 100644--- a/app/common/download_task.py+++ b/app/common/download_task.py@@ -7,11 +7,10 @@ from urllib.parse import urlparse, parse_qs, unquoteimport httpxfrom PySide6.QtCore import QThread, Signal-from httpx import Clientfrom loguru import loggerfrom app.common.config import cfg-from app.common.methods import getWindowsProxy, getReadableSize+from app.common.methods import getProxy, getReadableSize, retryHeaders = {"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"}@@ -36,7 +35,7 @@ urlRe = re.compile(r"^" +def getRealUrl(url: str):try:response = httpx.head(url=url, headers=Headers, follow_redirects=False, verify=False,- proxy=getWindowsProxy())+ proxy=getProxy())if response.status_code == 400: # Bad Requests# TODO 报错处理@@ -57,7 +56,7 @@ def getRealUrl(url: str):logger.info(f"HTTP status code:302, Redirect to {url}")response = httpx.head(url=url, headers=Headers, follow_redirects=False, verify=False,- proxy=getWindowsProxy()) # 再访问一次+ proxy=getProxy()) # 再访问一次return url@@ -79,6 +78,7 @@ class DownloadTask(QThread):# processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替workerInfoChange = Signal(list) # 目前进度 v3.2版本引进了分段式进度条taskFinished = Signal() # 内置信号的不好用+ gotWrong = Signal(str) # 😭 我出问题了def __init__(self, url, maxBlockNum: int = 8, filePath=None, fileName=None, parent=None):super().__init__(parent)@@ -91,7 +91,7 @@ class DownloadTask(QThread):self.workers: list[DownloadWorker] = []self.client = httpx.Client(headers=Headers, verify=False,- proxy=getWindowsProxy())+ proxy=getProxy())def __reassignWorker(self):@@ -148,13 +148,14 @@ class DownloadTask(QThread):return step_list+ @retry(3, 0.1)def run(self):# 初始化信息# 获取真实URLself.url = getRealUrl(self.url)- head = httpx.head(self.url, headers=Headers, proxy=getWindowsProxy()).headers+ head = httpx.head(self.url, headers=Headers, proxy=getProxy()).headers# 获取文件大小, 判断是否可以分块下载if "content-length" not in head:@@ -305,7 +306,7 @@ class DownloadWorker(QThread):workerFinished = Signal() # 内置的信号不好用- def __init__(self, start, process, end, url, filePath, fileName, client: Client, parent=None):+ def __init__(self, start, process, end, url, filePath, fileName, client: httpx.Client, parent=None):super().__init__(parent)self.startPos = startself.process = processdiff --git a/app/common/methods.py b/app/common/methods.pyindex 7bd07caa..1fbee543 100644--- a/app/common/methods.py+++ b/app/common/methods.py@@ -41,7 +41,7 @@ def loadPlugins(mainWindow, directory="{}/plugins".format(QApplication.applicatilogger.error(f"Error loading plugins: {e}")-def getWindowsProxy():+def getProxy():if sys.platform == "win32":try:import winreg@@ -79,3 +79,48 @@ def getReadableSize(size):size = size / Kunit_index += 1return "%.2f %s" % (size, units[unit_index])+++from functools import wraps+from time import sleep+++def retry(retries: int = 3, delay: float = 0.1, handleFunction: callable = None):+ """+ 是装饰器。函数执行失败时,重试++ :param retries: 最大重试的次数+ :param delay: 每次重试的间隔时间,单位 秒+ :param handleFunction: 处理函数,用来处理异常+ :return:+ """++ # 校验重试的参数,参数值不正确时使用默认参数+ if retries < 1 or delay <= 0:+ retries = 3+ delay = 1++ def decorator(func):+ @wraps(func)+ def wrapper(*args, **kwargs):+ for i in range(retries + 1): # 第一次正常执行不算重试次数,所以 retries+1+ try:+ return func(*args, **kwargs)+ except Exception as e:+ # 检查重试次数+ if i == retries:+ logger.error(f'Error: {repr(e)}! "{func.__name__}()" 执行失败,已重试{retries}次.')+ try:+ handleFunction()+ finally:+ break+ else:+ logger.warning(+ f'Error: {repr(e)}! "{func.__name__}()"执行失败,将在{delay}秒后第[{i+1}/{retries}]次重试...'+ )+ sleep(delay)++ return wrapper++ return decorator+diff --git a/app/components/task_card.py b/app/components/task_card.pyindex cac5b157..3398eabf 100644--- a/app/components/task_card.py+++ b/app/components/task_card.py@@ -16,7 +16,7 @@ from .Ui_TaskCard import Ui_TaskCardfrom .task_progress_bar import TaskProgressBarfrom ..common.config import cfgfrom ..common.download_task import DownloadTask-from ..common.methods import getWindowsProxy, getReadableSize+from ..common.methods import getProxy, getReadableSize, retryHeaders = {"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"}@@ -38,7 +38,7 @@ urlRe = re.compile(r"^" +"$", re.IGNORECASE)# 获取系统代理-proxy = getWindowsProxy()+proxy = getProxy()class TaskCard(CardWidget, Ui_TaskCard):@@ -140,30 +140,33 @@ class TaskCard(CardWidget, Ui_TaskCard):if self.status == "working": # 暂停self.pauseButton.setDisabled(True)self.pauseButton.setIcon(FIF.PLAY)- for i in self.task.workers:- try:- i.file.close()- except Exception as e:- logger.warning(- f"Task:{self.fileName}, it seems that cannot cancel thread {i} occupancy of the file, error: {e}")- i.terminate()- self.task.terminate()- # 改变记录状态- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:- _ = f.read()+ try:+ for i in self.task.workers:+ try:+ i.file.close()+ except Exception as e:+ logger.warning(+ f"Task:{self.fileName}, it seems that cannot cancel thread {i} occupancy of the file, error: {e}")+ i.terminate()+ self.task.terminate()- _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),- "blockNum": self.maxBlockNum, "status": self.status}) + "\n",- str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),- "blockNum": self.maxBlockNum, "status": "paused"}) + "\n")+ # 改变记录状态+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:+ _ = f.read()- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:- f.write(_)+ _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum, "status": self.status}) + "\n",+ str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum, "status": "paused"}) + "\n")++ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:+ f.write(_)- self.speedLable.setText("任务已经暂停")- self.status = "paused"- self.pauseButton.setEnabled(True)+ finally:+ self.speedLable.setText("任务已经暂停")+ self.status = "paused"+ self.pauseButton.setEnabled(True)elif self.status == "paused": # 继续self.pauseButton.setDisabled(True)@@ -173,22 +176,26 @@ class TaskCard(CardWidget, Ui_TaskCard):self.task.workerInfoChange.connect(self.__changeInfo)self.task.taskFinished.connect(self.taskFinished)- # 改变记录状态- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:- _ = f.read()+ try:+ # 改变记录状态+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:+ _ = f.read()- _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),- "blockNum": self.maxBlockNum, "status": self.status}) + "\n",- str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),- "blockNum": self.maxBlockNum, "status": "working"}) + "\n")+ _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum, "status": self.status}) + "\n",+ str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum, "status": "working"}) + "\n")- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:- f.write(_)+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:+ f.write(_)- self.speedLable.setText("任务正在开始")- self.status = "working"- self.pauseButton.setEnabled(True)+ finally:+ self.speedLable.setText("任务正在开始")+ self.status = "working"+ self.pauseButton.setEnabled(True)++ @retry(3, 0.1)def cancelTask(self, completely: bool = False):self.pauseButton.setDisabled(True)self.cancelButton.setDisabled(True)@@ -199,23 +206,16 @@ class TaskCard(CardWidget, Ui_TaskCard):if completely:# 删除文件- tryCount = 0- isDeleted = False- while not isDeleted and tryCount < 3:- try:- Path(f"{self.filePath}/{self.fileName}").unlink()- Path(f"{self.filePath}/{self.fileName}.ghd").unlink()- logger.info(f"self:{self.fileName}, delete file successfully!")+ try:+ Path(f"{self.filePath}/{self.fileName}").unlink()+ Path(f"{self.filePath}/{self.fileName}.ghd").unlink()+ logger.info(f"self:{self.fileName}, delete file successfully!")- isDeleted = True- tryCount = 5+ except FileNotFoundError:+ pass- except FileNotFoundError:- isDeleted = True- tryCount = 5- except Exception as e:- logger.error(f"Task:{self.fileName}, it seems that cannot delete file, error: {e}")- tryCount += 1+ except Exception as e:+ raise e# 删除记录文件with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:@@ -230,11 +230,11 @@ class TaskCard(CardWidget, Ui_TaskCard):except Exception as e:logger.warning(f"Task:{self.fileName}, 删除时遇到错误: {e}")- self.status = "canceled"-- self.parent().parent().parent().expandLayout.removeWidget(self)-- self.hide()+ finally:+ self.status = "canceled"+ # Remove Widget+ self.parent().parent().parent().expandLayout.removeWidget(self)+ self.hide()def __changeInfo(self, content: list):# 理论来说 worker 直增不减 所以ProgressBar不用考虑线程减少的问题diff --git a/app/components/update_dialog.py b/app/components/update_dialog.pyindex 29193cd7..2196d4f3 100644--- a/app/components/update_dialog.py+++ b/app/components/update_dialog.py@@ -8,7 +8,7 @@ from qfluentwidgets import isDarkTheme, SettingCardGroup, TextEdit, ListWidget,from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBasefrom app.common.config import VERSION, cfg-from app.common.methods import getWindowsProxy+from app.common.methods import getProxyfrom app.common.signal_bus import signalBus@@ -21,7 +21,7 @@ class GetUpdateThread(QThread):try: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"},- proxy=getWindowsProxy(), follow_redirects=True).json()+ proxy=getProxy(), follow_redirects=True).json()tagName = content["tag_name"][1:]@@ -119,7 +119,7 @@ class UpdateDialog(MaskDialogBase):def __showResponse(parent, content: dict):if "INFO" in content:- InfoBar.info(title="当前已是最新版本", position=InfoBarPosition.TOP_RIGHT, parent=parent, duration=5000)+ InfoBar.info(title="当前已是最新版本", content="", position=InfoBarPosition.TOP_RIGHT, parent=parent, duration=5000)elif "ERROR" in content:InfoBar.error(title="检查更新失败", content=content["ERROR"], position=InfoBarPosition.TOP_RIGHT, parent=parent, duration=5000)else:diff --git a/app/view/main_window.py b/app/view/main_window.pyindex eeb06546..4beab6b7 100644--- a/app/view/main_window.py+++ b/app/view/main_window.py@@ -76,7 +76,6 @@ class MainWindow(MSFluentWindow):# 检查更新if cfg.checkUpdateAtStartUp.value == True:checkUpdate(self)- print("启动!")self.splashScreen.finish()diff --git a/plugins/jy_os_page.py b/plugins/jy_os_page.pyindex b2287e9e..55fc5c74 100644--- a/plugins/jy_os_page.py+++ b/plugins/jy_os_page.py@@ -14,7 +14,7 @@ from qfluentwidgets import ScrollArea, TitleLabel, isDarkTheme, SettingCardGroupPrimarySplitPushButtonfrom qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase-from app.common.methods import getWindowsProxy+from app.common.methods import getProxyfrom app.common.plugin_base import PluginBasefrom app.common.signal_bus import signalBus@@ -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=getWindowsProxy(), follow_redirects=True).text)["OS"])+ proxy=getProxy(), follow_redirects=True).text)["OS"])class HomeInterface(ScrollArea):