Skip to content

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

在添加任务窗口可以自定义请求标头(#19)

XiaoYouChRbdb3f45a581f
diff --git a/app/components/Ui_AddTaskOptionDialog.py b/app/components/Ui_AddTaskOptionDialog.py
index ae3baf14..6f4209ab 100644
--- a/app/components/Ui_AddTaskOptionDialog.py
+++ b/app/components/Ui_AddTaskOptionDialog.py
@@ -8,41 +8,15 @@
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
-from PySide6.QtCore import (QCoreApplication, QSize, Qt)
-from PySide6.QtWidgets import (QHBoxLayout, QSizePolicy, QTableWidgetItem, QVBoxLayout, QApplication, QHeaderView)
+from PySide6.QtCore import (QCoreApplication, QSize)
+from PySide6.QtWidgets import (QHBoxLayout, QSizePolicy, QTableWidgetItem, QVBoxLayout, QHeaderView)
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import (PushButton, SubtitleLabel,
TableWidget, TextEdit, RoundMenu, Action)
from qfluentwidgets.components.widgets.button import PrimarySplitPushButton
+from app.components.disabled_rich_text_edit import DisabledRichTextEdit
-class DisabledRichTextEdit(TextEdit):
- def __init__(self, parent=None):
- super().__init__(parent)
-
- def copy(self):
- # 仅复制纯文本到剪贴板
- clipboard = QApplication.clipboard()
- clipboard.setText(self.toPlainText()) # 使用纯文本格式
-
- def paste(self):
- # 仅粘贴纯文本
- clipboard = QApplication.clipboard()
- text = clipboard.text().replace(" ", "") # 获取纯文本内容并去除空格
- self.insertPlainText(text) # 使用 insertPlainText 插入纯文本
-
- def keyPressEvent(self, event):
- if event.modifiers() == Qt.ControlModifier:
- if event.key() == Qt.Key_C:
- self.copy()
- event.accept() # 阻止默认复制操作
- elif event.key() == Qt.Key_V:
- self.paste()
- event.accept() # 阻止默认粘贴操作
- else:
- super().keyPressEvent(event)
- else:
- super().keyPressEvent(event)
class Ui_AddTaskOptionDialog(object):
def setupUi(self, AddTaskOptionDialog):
diff --git a/app/components/Ui_UpdateDialog.py b/app/components/Ui_UpdateDialog.py
index af8986b4..fb67bf54 100644
--- a/app/components/Ui_UpdateDialog.py
+++ b/app/components/Ui_UpdateDialog.py
@@ -10,7 +10,7 @@
from PySide6.QtCore import (QCoreApplication)
from PySide6.QtWidgets import (QHBoxLayout,
- QSizePolicy, QVBoxLayout, QAbstractItemView, QHeaderView)
+ QSizePolicy, QVBoxLayout, QAbstractItemView, QHeaderView, QSpacerItem)
from qfluentwidgets import (PillPushButton, PrimaryPushButton, PushButton, StrongBodyLabel,
SubtitleLabel, TextEdit, TableWidget, FluentIcon)
@@ -42,7 +42,7 @@ class Ui_UpdateDialog(object):
self.horizontalLayout.addWidget(self.updatedDateLabel)
- self.horizontalLayout.addSpacing(16777215)
+ self.horizontalLayout.addSpacerItem(QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum))
self.sponsorButton = PillPushButton(UpdateDialog)
self.sponsorButton.setObjectName(u"sponsorButton")
diff --git a/app/components/add_task_dialog.py b/app/components/add_task_dialog.py
index 3d151a70..2921b8a9 100644
--- a/app/components/add_task_dialog.py
+++ b/app/components/add_task_dialog.py
@@ -10,6 +10,7 @@ from qfluentwidgets import PushSettingCard, RangeSettingCard, MessageBox, InfoBa
from qfluentwidgets.common.icon import FluentIcon as FIF
from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase
+from app.components.edit_headers_dialog import EditHeadersDialog # 添加导入
from .Ui_AddTaskOptionDialog import Ui_AddTaskOptionDialog
from ..common.config import cfg, Headers
from ..common.methods import getReadableSize, getLinkInfo
@@ -41,6 +42,8 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
def __init__(self, parent=None):
super().__init__(parent=parent)
+ self.customHeaders = Headers.copy()
+
FluentStyleSheet.DIALOG.apply(self.widget)
self.widget.setContentsMargins(11, 11, 11, 11)
@@ -62,7 +65,6 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
self.widget
)
- # Choose Threading Card
self.blockNumCard = RangeSettingCard(
cfg.maxBlockNum,
FIF.CLOUD,
@@ -71,8 +73,18 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
self.widget
)
+ # Edit customHeaders Card
+ self.editHeadersCard = PushSettingCard(
+ "编辑请求标头",
+ FIF.EDIT,
+ "自定义请求标头",
+ "",
+ self.widget
+ )
+
self.verticalLayout.insertWidget(4, self.downloadFolderCard)
self.verticalLayout.insertWidget(5, self.blockNumCard)
+ self.verticalLayout.insertWidget(6, self.editHeadersCard)
self.__connectSignalToSlot()
@@ -87,6 +99,7 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
self.linkTextEdit.textChanged.connect(self.__onLinkTextChanged)
self.__addTableRowSignal.connect(self.__addTableRow)
self.__gotWrong.connect(self.__handleWrong)
+ self.editHeadersCard.clicked.connect(self.__onEditHeadersCardClicked)
def __handleWrong(self, error: str, index: int):
InfoBar.error(
@@ -95,11 +108,18 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
orient=Qt.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
- # position='Custom', # NOTE: use custom info bar manager
duration=10000,
parent=self.parent()
)
+ def __onEditHeadersCardClicked(self):
+ dialog = EditHeadersDialog(self, initialHeaders=self.customHeaders)
+ dialog.headersUpdated.connect(self.__onHeadersUpdated)
+ dialog.exec()
+
+ def __onHeadersUpdated(self, newHeaders):
+ self.customHeaders = newHeaders
+
def __onYesButtonClicked(self):
path = Path(self.downloadFolderCard.contentLabel.text())
@@ -118,7 +138,7 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
signalBus.addTaskSignal.emit(item.data(1),
str(path), self.blockNumCard.configItem.value,
- item.text(), "working", Headers, False)
+ item.text(), "working", self.customHeaders, False) # 使用新的 customHeaders
self.close()
@@ -140,7 +160,7 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
signalBus.addTaskSignal.emit(item.data(1),
str(path), self.blockNumCard.configItem.value,
- item.text(), "paused", Headers, False)
+ item.text(), "paused", self.customHeaders, False) # 使用新的 customHeaders
self.close()
@@ -153,7 +173,6 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
self.downloadFolderCard.setContent(folder)
-
def __onLinkTextChanged(self):
if hasattr(self, '_timer'):
self._timer.stop()
@@ -165,13 +184,12 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
def __handleUrl(self, url: str, index: int):
try:
- _url, fileName, fileSize = getLinkInfo(url, Headers)
+ _url, fileName, fileSize = getLinkInfo(url, self.customHeaders)
self.__addTableRowSignal.emit(fileName, str(fileSize), url) # 不希望使用重定向后的url,故使用原始url
-
+
except Exception as e:
self.__gotWrong.emit(repr(e), index)
-
def __addTableRow(self, fileName: str, fileSize: str, url: str):
""" add table row slot """
self.taskTableWidget.insertRow(self.taskTableWidget.rowCount())
@@ -214,7 +232,6 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
orient=Qt.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
- # position='Custom', # NOTE: use custom info bar manager
duration=1000,
parent=self.parent()
)
@@ -224,7 +241,7 @@ class AddTaskOptionDialog(MaskDialogBase, Ui_AddTaskOptionDialog):
thread.start()
Thread(target=self.__waitForThreads, daemon=True).start()
-
+
def __waitForThreads(self):
for thread in self.threads:
thread.join()
diff --git a/app/components/disabled_rich_text_edit.py b/app/components/disabled_rich_text_edit.py
new file mode 100644
index 00000000..f5f3d1f2
--- /dev/null
+++ b/app/components/disabled_rich_text_edit.py
@@ -0,0 +1,32 @@
+from PySide6.QtCore import Qt
+from PySide6.QtWidgets import QApplication
+from qfluentwidgets import TextEdit
+
+
+class DisabledRichTextEdit(TextEdit):
+ def __init__(self, parent=None):
+ super().__init__(parent)
+
+ def copy(self):
+ # 仅复制纯文本到剪贴板
+ clipboard = QApplication.clipboard()
+ clipboard.setText(self.toPlainText()) # 使用纯文本格式
+
+ def paste(self):
+ # 仅粘贴纯文本
+ clipboard = QApplication.clipboard()
+ text = clipboard.text().replace(" ", "") # 获取纯文本内容并去除空格
+ self.insertPlainText(text) # 使用 insertPlainText 插入纯文本
+
+ def keyPressEvent(self, event):
+ if event.modifiers() == Qt.ControlModifier:
+ if event.key() == Qt.Key_C:
+ self.copy()
+ event.accept() # 阻止默认复制操作
+ elif event.key() == Qt.Key_V:
+ self.paste()
+ event.accept() # 阻止默认粘贴操作
+ else:
+ super().keyPressEvent(event)
+ else:
+ super().keyPressEvent(event)
diff --git a/app/components/edit_headers_dialog.py b/app/components/edit_headers_dialog.py
new file mode 100644
index 00000000..0b303954
--- /dev/null
+++ b/app/components/edit_headers_dialog.py
@@ -0,0 +1,66 @@
+from PySide6.QtCore import Signal
+from PySide6.QtGui import QColor
+from PySide6.QtWidgets import QVBoxLayout
+from qfluentwidgets import FluentStyleSheet, MaskDialogBase, InfoBar, InfoBarPosition, PrimaryPushButton, \
+ SubtitleLabel
+
+from app.components.disabled_rich_text_edit import DisabledRichTextEdit
+
+
+class EditHeadersDialog(MaskDialogBase):
+ headersUpdated = Signal(dict)
+
+ def __init__(self, parent=None, initialHeaders=None):
+ super().__init__(parent=parent)
+ FluentStyleSheet.DIALOG.apply(self.widget)
+ self.widget.setContentsMargins(11, 11, 11, 11)
+
+ self.setShadowEffect(60, (0, 10), QColor(0, 0, 0, 50))
+ self.setMaskColor(QColor(0, 0, 0, 76))
+ self.setClosableOnMaskClicked(True)
+
+ self.widget.setFixedSize(400, 500)
+
+ self.layout = QVBoxLayout(self)
+
+ self.titleLabel = SubtitleLabel("编辑请求标头", self.widget)
+ self.layout.addWidget(self.titleLabel)
+
+ self.headersTextEdit = DisabledRichTextEdit(self.widget)
+ self.headersTextEdit.setPlaceholderText('请输入请求标头,每行一个键值对,格式为 "key: value"')
+ if initialHeaders:
+ self.headersTextEdit.setPlainText("\n".join([f"{k}: {v}" for k, v in initialHeaders.items()]))
+ self.layout.addWidget(self.headersTextEdit)
+
+ self.saveButton = PrimaryPushButton("保存", self.widget)
+ self.saveButton.clicked.connect(self.__onSaveButtonClicked)
+ self.layout.addWidget(self.saveButton)
+
+ self.widget.setLayout(self.layout)
+
+ def __onSaveButtonClicked(self):
+ headers_text = self.headersTextEdit.toPlainText()
+ headersDict = self.__parseHeaders(headers_text)
+ if headersDict is not None:
+ self.headersUpdated.emit(headersDict)
+ self.accept()
+ else:
+ InfoBar.error(
+ title="错误",
+ content='请输入格式正确的请求标头, 格式为 "key: value"',
+ position=InfoBarPosition.TOP,
+ parent=self.parent(),
+ duration=3000,
+ )
+
+ def __parseHeaders(self, headers_text):
+ headersDict = {}
+ lines = headers_text.strip().split('\n')
+ for line in lines:
+ if line.strip():
+ parts = line.split(':', 1)
+ if len(parts) != 2:
+ return None
+ key, value = parts
+ headersDict[key.strip()] = value.strip()
+ return headersDict
\ No newline at end of file