Skip to content

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

feat: 增加下载限速功能 style(设置界面): 优化初始化方法和样式表设置顺序

XiaoYouChRf553ca1e7f2b
diff --git a/app/common/config.py b/app/common/config.py
index 4dfe35f0..a9e87c5e 100644
--- a/app/common/config.py
+++ b/app/common/config.py
@@ -2,7 +2,7 @@
import sys
from re import compile
-from PySide6.QtCore import QDir, QRect
+from PySide6.QtCore import QDir, QRect, QTimer
from qfluentwidgets import (QConfig, ConfigItem, OptionsConfigItem, BoolValidator,
OptionsValidator, RangeConfigItem, RangeValidator,
FolderValidator, ConfigValidator, ConfigSerializer)
@@ -54,6 +54,7 @@ class Config(QConfig):
maxBlockNum = RangeConfigItem("Download", "MaxBlockNum", 8, RangeValidator(1, 256))
maxTaskNum = RangeConfigItem("Download", "MaxTaskNum", 3, RangeValidator(1, 10))
+ speedLimitation = RangeConfigItem("Download", "SpeedLimitation", 0, RangeValidator(0, 104857600)) # 单位 KB
autoSpeedUp = ConfigItem("Download", "AutoSpeedUp", True, BoolValidator())
proxyServer = ConfigItem("Download", "ProxyServer", "Auto", ProxyValidator())
@@ -72,9 +73,13 @@ class Config(QConfig):
autoRun = ConfigItem("Software", "AutoRun", False, BoolValidator())
enableClipboardListener = ConfigItem("Software", "ClipboardListener", True, BoolValidator())
geometry = ConfigItem("Software", "Geometry", "Default", GeometryValidator(), GeometrySerializer()) # 保存程序的位置和大小, Validator 在 mainWindow 中设置
- # 程序运行路径
+
+ # 全局变量
appPath = "./"
+ globalSpeed = 0 # 用于记录每秒下载速度, 单位 KB/s
+ def resetGlobalSpeed(self):
+ self.globalSpeed = 0
YEAR = 2024
AUTHOR = "XiaoYouChR"
@@ -83,6 +88,7 @@ LATEST_EXTENSION_VERSION = "1.0.5"
AUTHOR_URL = "https://space.bilibili.com/437313511"
FEEDBACK_URL = "https://github.com/XiaoYouChR/Ghost-Downloader-3/issues"
# RELEASE_URL = "https://github.com/XiaoYouChR/Ghost-Downloader-3/releases/latest"
+
Headers = {
"accept-encoding": "deflate, br, gzip",
"accept-language": "zh-CN,zh;q=0.9",
@@ -94,7 +100,7 @@ Headers = {
"upgrade-insecure-requests": "1",
"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"}
-# WARN 附件类型必须全部小写
+# 附件类型必须全部小写
attachmentTypes = """3gp 7z aac ace aif arj asf avi bin bz2 exe gz gzip img iso lzh m4a m4v mkv mov mp3 mp4 mpa mpe
mpeg mpg msi msu ogg ogv pdf plj pps ppt qt ra rar rm rmvb sea sit sitx tar tif tiff
wav wma wmv z zip esd wim msp apk apks apkm cab msp"""
diff --git a/app/common/download_task.py b/app/common/download_task.py
index ac151a6f..41fb19a7 100644
--- a/app/common/download_task.py
+++ b/app/common/download_task.py
@@ -5,6 +5,7 @@ import time
from asyncio import Task
from pathlib import Path
from threading import Thread
+from time import sleep
import aiofiles
import httpx
@@ -208,6 +209,10 @@ class DownloadTask(QThread):
await self.file.seek(worker.progress)
await self.file.write(chunk)
worker.progress += 65536
+ cfg.globalSpeed += 64 # 我真的不想使用 len(chunk), 因为误差只有一点点
+ if cfg.speedLimitation.value:
+ if cfg.globalSpeed >= cfg.speedLimitation.value:
+ await asyncio.sleep(1) # 在锁里面睡,只阻塞 worker, 不阻塞 supervisor
if worker.progress >= worker.endPos:
worker.progress = worker.endPos
@@ -220,7 +225,7 @@ class DownloadTask(QThread):
self.gotWrong.emit(repr(e))
- await asyncio.sleep(5)
+ await asyncio.sleep(5) # 5s 后重试
worker.progress = worker.endPos
@@ -237,10 +242,13 @@ class DownloadTask(QThread):
async for chunk in res.aiter_bytes(chunk_size=65536): # aiter_content 的单位是字节, 即每64K写一次文件
if chunk:
- async with self.aioLock:
- await self.file.seek(worker.progress)
- await self.file.write(chunk)
- worker.progress += len(chunk)
+ await self.file.seek(worker.progress)
+ await self.file.write(chunk)
+ worker.progress += len(chunk)
+ cfg.globalSpeed += len(chunk) / 1024 # B 转 KB
+ if cfg.speedLimitation.value:
+ if cfg.globalSpeed >= cfg.speedLimitation.value:
+ await asyncio.sleep(1) # 在锁里面睡,只阻塞 worker, 不阻塞 supervisor
self.ableToParallelDownload = True # 事实上用来表示任务已经完成
diff --git a/app/components/task_card.py b/app/components/task_card.py
index 4246b3b5..f8467e51 100644
--- a/app/components/task_card.py
+++ b/app/components/task_card.py
@@ -279,7 +279,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
finally:
# Remove Widget
- self.parent().parent().parent().expandLayout.removeWidget(self)
+ self.parent().parent().parent().expandLayout.takeAt(self.parent().parent().parent().expandLayout.indexOf(self))
self.parent().parent().parent().cards.remove(self)
self.taskStatusChanged.emit()
self.deleteLater()
diff --git a/app/view/setting_interface.py b/app/view/setting_interface.py
index 1ad87636..4b0daa60 100644
--- a/app/view/setting_interface.py
+++ b/app/view/setting_interface.py
@@ -8,7 +8,8 @@ from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import QWidget, QFileDialog, QVBoxLayout, QApplication, QButtonGroup, QHBoxLayout, QSpacerItem, \
QSizePolicy
from qfluentwidgets import FluentIcon as FIF, InfoBarPosition, ExpandGroupSettingCard, ConfigItem, \
- BodyLabel, RadioButton, ComboBox, LineEdit, ComboBoxSettingCard, FlyoutView, Flyout
+ BodyLabel, RadioButton, ComboBox, LineEdit, ComboBoxSettingCard, FlyoutView, Flyout, SettingCard, CompactSpinBox, \
+ SpinBox
from qfluentwidgets import InfoBar
from qfluentwidgets import (SettingCardGroup, SwitchSettingCard, PushSettingCard,
HyperlinkCard, PrimaryPushSettingCard, SmoothScrollArea,
@@ -32,11 +33,7 @@ class CustomProxySettingCard(ExpandGroupSettingCard):
parent: QWidget
parent window
"""
- icon = FIF.GLOBE
- title = "代理"
- content = "设置下载时希望使用的代理"
-
- super().__init__(icon, title, content, parent=parent)
+ super().__init__(FIF.GLOBE, "代理", "设置下载时希望使用的代理", parent=parent)
self.configItem = configItem
@@ -171,6 +168,31 @@ class CustomProxySettingCard(ExpandGroupSettingCard):
self.defaultRadioButton.click()
self.defaultRadioButton.setChecked(True)
+class SpeedLimitationSettingCard(SettingCard):
+ """ Speed limitation setting card """
+
+ def __init__(self, configItem: ConfigItem=None, parent=None):
+ super().__init__(FIF.SPEED_OFF, "下载限速", "限制每秒全局下载速度, 0 为不限速", parent=parent)
+
+ self.configItem = configItem
+
+ self.spinBox = CompactSpinBox(self)
+ self.spinBox.setObjectName('spinBox')
+ self.spinBox.setRange(0, 104857600)
+ self.spinBox.setValue(self.configItem.value)
+ self.spinBox.setSingleStep(512)
+ self.spinBox.setMinimumWidth(180)
+ self.spinBox.setSuffix(" KB/s")
+
+ self.hBoxLayout.addWidget(self.spinBox)
+ self.hBoxLayout.addSpacing(24)
+
+ self.spinBox.setValue(self.configItem.value)
+ self.spinBox.valueChanged.connect(self.setValue)
+
+ def setValue(self, value):
+ if self.configItem:
+ cfg.set(self.configItem, value)
class SettingInterface(SmoothScrollArea):
@@ -189,7 +211,7 @@ class SettingInterface(SmoothScrollArea):
cfg.maxBlockNum,
FIF.CLOUD,
"下载线程数",
- '下载线程越多,下载越快。当线程数大于 64 时,有文件损坏的风险。',
+ '线程越多,下载越快。线程数大于 64 时,有触发反爬导致文件损坏的风险',
self.downloadGroup
)
@@ -197,7 +219,7 @@ class SettingInterface(SmoothScrollArea):
cfg.maxReassignSize,
FIF.LIBRARY,
"最大重新分配大小 (MB)",
- '每线程剩余量大于此值时, 有线程完成或自动提速条件满足会触发',
+ '每线程剩余量大于此值时, 有线程完成或自动提速条件满足会触发重新分配',
self.downloadGroup
)
@@ -209,6 +231,11 @@ class SettingInterface(SmoothScrollArea):
self.downloadGroup
)
+ self.speedLimitationCard = SpeedLimitationSettingCard(
+ cfg.speedLimitation,
+ self.downloadGroup
+ )
+
self.autoSpeedUpCard = SwitchSettingCard(
FIF.SPEED_HIGH,
"自动提速",
@@ -357,15 +384,6 @@ class SettingInterface(SmoothScrollArea):
self.aboutGroup
)
- self.__initWidget()
-
- # Apply QSS
- self.setStyleSheet("""QScrollArea, .QWidget {
- border: none;
- background-color: transparent;
- }""")
-
- def __initWidget(self):
self.resize(1000, 800)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setWidget(self.scrollWidget)
@@ -374,6 +392,10 @@ class SettingInterface(SmoothScrollArea):
# initialize style sheet
self.scrollWidget.setObjectName('scrollWidget')
+ self.setStyleSheet("""QScrollArea, .QWidget {
+ border: none;
+ background-color: transparent;
+ }""")
# initialize layout
self.__initLayout()
@@ -385,6 +407,7 @@ class SettingInterface(SmoothScrollArea):
self.downloadGroup.addSettingCard(self.blockNumCard)
self.downloadGroup.addSettingCard(self.maxReassignSizeCard)
self.downloadGroup.addSettingCard(self.maxTaskNumCard)
+ self.downloadGroup.addSettingCard(self.speedLimitationCard)
self.downloadGroup.addSettingCard(self.autoSpeedUpCard)
self.downloadGroup.addSettingCard(self.downloadFolderCard)
self.downloadGroup.addSettingCard(self.proxyServerCard)
diff --git a/main.py b/main.py
index 5802f981..b6c4e7ba 100644
--- a/main.py
+++ b/main.py
@@ -32,7 +32,7 @@ else:
app = QApplication(sys.argv)
# 检测程序重复运行
-from PySide6.QtCore import QSharedMemory
+from PySide6.QtCore import QSharedMemory, QTimer
# 尝试访问
sharedMemory = QSharedMemory()
@@ -110,7 +110,13 @@ if sys.platform == "linux":
# except Exception as e:
# logger.error(f"Cannot get theme color: {e}")
-
+
+# create SpeedLimiter
+speedLimiter = QTimer() # 限速器
+speedLimiter.setInterval(1000) # 一秒刷新一次
+speedLimiter.timeout.connect(cfg.resetGlobalSpeed) # 刷新 globalSpeed为 0
+speedLimiter.start()
+
# create main window
w = MainWindow()