Skip to content

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

跨平台原生 Notification

XiaoYouChRaec1b5e881f7
diff --git a/app/common/application.py b/app/common/application.py
index f799e355..ac8c721b 100644
--- a/app/common/application.py
+++ b/app/common/application.py
@@ -6,7 +6,6 @@ from PySide6.QtCore import QSharedMemory, Qt, QEvent
from PySide6.QtWidgets import QApplication
from loguru import logger
-from .methods import bringWindowToTop
from .signal_bus import signalBus
diff --git a/app/common/download_task.py b/app/common/download_task.py
index 8e4f4a08..bb3efaf3 100644
--- a/app/common/download_task.py
+++ b/app/common/download_task.py
@@ -664,7 +664,10 @@ class DownloadTask(QThread):
"""Cancel all worker tasks"""
for task in self.tasks:
if task and not task.done():
- task.cancel()
+ try:
+ task.cancel()
+ finally:
+ pass
def __closeFiles(self):
"""Close all open files"""
diff --git a/app/common/methods.py b/app/common/methods.py
index 1ca1809a..9321c624 100644
--- a/app/common/methods.py
+++ b/app/common/methods.py
@@ -14,7 +14,7 @@ from typing import Optional
from urllib.parse import unquote, parse_qs, urlparse
import niquests
-from PySide6.QtCore import QUrl, QOperatingSystemVersion, QResource
+from PySide6.QtCore import QUrl, QOperatingSystemVersion
from PySide6.QtGui import QDesktopServices
from loguru import logger
from qfluentwidgets import MessageBox
@@ -44,7 +44,7 @@ def isGreaterEqualWin11():
def isAbleToShowToast():
- return sys.platform == 'win32' and sys.getwindowsversion().build >= 16299 # 高于 Win10 1709
+ return (sys.platform == 'win32' and sys.getwindowsversion().build >= 10240) or True
def loadPlugins(mainWindow, directory="{}/plugins".format(cfg.appPath)):
@@ -213,26 +213,26 @@ def getLocalTimeFromGithubApiTime(gmtTimeStr: str):
return localTimeNaive
-def attemptRegisterAppID(appId: str = "GD3", appName: str = "Ghost Downloader",
- iconPath: Path = Path("{}/logo.ico".format(cfg.appPath))):
- import winreg
- keyPath = f"SOFTWARE\\Classes\\AppUserModelId\\{appId}"
-
- try:
- reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, keyPath)
- winreg.CloseKey(reg_key)
- return
- except FileNotFoundError:
- with open(iconPath, "wb") as f:
- f.write(QResource(":/image/logo.ico").data())
-
- winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
- with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, keyPath) as masterKey:
- winreg.SetValueEx(masterKey, "DisplayName", 0, winreg.REG_SZ, appName)
- if iconPath is not None:
- winreg.SetValueEx(masterKey, "IconUri", 0, winreg.REG_SZ, str(iconPath.resolve()))
- except Exception as e:
- logger.error(f"Could not register the application: {e}")
+# def attemptRegisterAppID(appId: str = "Ghost Downloader", appName: str = "Ghost Downloader",
+# iconPath: Path = Path("{}/logo.ico".format(cfg.appPath))):
+# import winreg
+# keyPath = f"SOFTWARE\\Classes\\AppUserModelId\\{appId}"
+#
+# try:
+# reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, keyPath)
+# winreg.CloseKey(reg_key)
+# return
+# except FileNotFoundError:
+# with open(iconPath, "wb") as f:
+# f.write(QResource(":/image/logo.ico").data())
+#
+# winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
+# with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, keyPath) as masterKey:
+# winreg.SetValueEx(masterKey, "DisplayName", 0, winreg.REG_SZ, appName)
+# if iconPath is not None:
+# winreg.SetValueEx(masterKey, "IconUri", 0, winreg.REG_SZ, str(iconPath.resolve()))
+# 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,
diff --git a/app/view/pop_up_window.py b/app/view/pop_up_window.py
index 655ecec5..097b866e 100644
--- a/app/view/pop_up_window.py
+++ b/app/view/pop_up_window.py
@@ -1,17 +1,31 @@
import sys
from os.path import dirname, basename
+from pathlib import Path
-from PySide6.QtCore import Qt, QUrl, QTimer, QEasingCurve, QPropertyAnimation, QRect, QFileInfo, QObject
+from PySide6.QtCore import Qt, QUrl, QTimer, QEasingCurve, QPropertyAnimation, QRect, QFileInfo, QObject, \
+ QStandardPaths, QResource
from PySide6.QtGui import QPixmap, QPainter, QColor, QPainterPath
from PySide6.QtWidgets import QWidget, QFileIconProvider, QPushButton, QToolButton
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets.common.screen import getCurrentScreenGeometry
from qframelesswindow import WindowEffect
-from app.common.methods import isGreaterEqualWin10, attemptRegisterAppID
+from app.common.methods import isGreaterEqualWin10
from app.common.methods import openFile, bringWindowToTop, isAbleToShowToast
+from app.common.signal_bus import signalBus
from app.view.Ui_PopUpWindow import Ui_PopUpWindow
+if isAbleToShowToast():
+ from desktop_notifier import DesktopNotifierSync, Icon, Button
+
+ _ = Path(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.TempLocation) + "/gd3_logo.png")
+ if not _.exists():
+ with open(_, "wb") as f:
+ f.write(QResource(":/image/logo.png").data())
+
+ desktopNotifierIcon = Icon(path=_)
+ desktopNotifier = DesktopNotifierSync(app_name="Ghost Downloader", app_icon=desktopNotifierIcon)
+
class PopUpWindowBase(QWidget, Ui_PopUpWindow):
def __init__(self, mainWindow=None):
@@ -226,7 +240,7 @@ class FinishedPopUpWindow(PopUpWindowBase):
_ = basename(fileResolvePath)
self.contentLabel.setText(_)
- self.contentLabel.fontMetrics().elidedText(_, Qt.ElideRight, 261)
+ self.contentLabel.fontMetrics().elidedText(_, Qt.TextElideMode.ElideRight, 261)
self.openFileBtn.clicked.connect(lambda: openFile(fileResolvePath))
self.openPathBtn.clicked.connect(lambda: openFile(dirname(fileResolvePath)))
@@ -234,34 +248,19 @@ class FinishedPopUpWindow(PopUpWindowBase):
@classmethod
def showPopUpWindow(cls, fileResolvePath:str, mainWindow=None):
if isAbleToShowToast():
- from app.common.concurrent.TaskExecutor import TaskExecutor
- from PySide6.QtCore import QStandardPaths, QFileInfo
- from win11toast import toast
- from PySide6.QtWidgets import QFileIconProvider
- from os.path import dirname
-
- iconTempFile = QStandardPaths.writableLocation(QStandardPaths.TempLocation) + "/finished_file_icon.png"
- QFileIconProvider().icon(QFileInfo(fileResolvePath)).pixmap(128, 128).save(iconTempFile, "PNG")
-
- icon = {
- 'src': f"file://{iconTempFile}",
- 'placement': 'appLogoOverride'
- }
+ iconTempFile = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.TempLocation) + "/finished_file_icon.png"
+ QFileIconProvider().icon(QFileInfo(fileResolvePath)).pixmap(48, 48).scaled(128, 128, aspectMode=Qt.AspectRatioMode.KeepAspectRatio,
+ mode=Qt.TransformationMode.SmoothTransformation).save(iconTempFile, "PNG")
+
+ buttons = [Button(cls.tr('打开文件'), lambda: openFile(fileResolvePath)),
+ Button(cls.tr('打开目录'), lambda: openFile(dirname(fileResolvePath)))]
+ return desktopNotifier.send(cls.tr("下载完成"), fileResolvePath, buttons=buttons, on_clicked=signalBus.showMainWindow.emit, icon=Icon(Path(iconTempFile)))
- buttons = [
- {'activationType': 'protocol', 'arguments': fileResolvePath, 'content': cls.tr('打开文件')},
- {'activationType': 'protocol', 'arguments': dirname(fileResolvePath), 'content': cls.tr('打开目录')}
- ]
-
- attemptRegisterAppID()
-
- return TaskExecutor.run(toast, cls.tr("下载完成"), fileResolvePath, icon=icon, buttons=buttons, app_id="GD3")
else:
w = FinishedPopUpWindow(fileResolvePath, mainWindow)
w.show()
return w
-
class ReceivedPopUpWindow(PopUpWindowBase):
def __init__(self, receiveContent:str, mainWindow=None):
super().__init__(mainWindow)
@@ -283,23 +282,8 @@ class ReceivedPopUpWindow(PopUpWindowBase):
@classmethod
def showPopUpWindow(cls, receiveContent:str, mainWindow=None):
if isAbleToShowToast():
- from app.common.concurrent.TaskExecutor import TaskExecutor
- from pathlib import Path
- from PySide6.QtCore import QStandardPaths, QResource
- from win11toast import toast
-
- logoTempFile = Path(QStandardPaths.writableLocation(QStandardPaths.TempLocation) + "/gd3_logo.png")
- if not logoTempFile.exists():
- with open(logoTempFile, "wb") as f:
- f.write(QResource(":/image/logo.png").data())
- icon = {
- 'src': f"file://{logoTempFile}",
- 'placement': 'appLogoOverride'
- }
-
- attemptRegisterAppID()
-
- return TaskExecutor.run(toast, cls.tr("接收到来自浏览器的下载任务:"), receiveContent, icon=icon, app_id="GD3") # TODO 点击后 bringWindowToTop(mainWindow), 需要信号
+ return desktopNotifier.send(cls.tr("接收到来自浏览器的下载任务:"), receiveContent, on_clicked=signalBus.showMainWindow.emit)
+
else:
w = ReceivedPopUpWindow(receiveContent, mainWindow)
w.show()
diff --git a/tests/test_pop_up_window.py b/tests/test_pop_up_window.py
index 57658a94..605336e8 100644
--- a/tests/test_pop_up_window.py
+++ b/tests/test_pop_up_window.py
@@ -34,51 +34,22 @@ class TestPopUpWindow(QWidget):
self.setLayout(layout)
def show_received_toast(self):
- from app.common.concurrent.TaskExecutor import TaskExecutor
- from pathlib import Path
- from PySide6.QtCore import QStandardPaths, QResource
- from win11toast import toast
-
- logoTempFile = Path(QStandardPaths.writableLocation(QStandardPaths.TempLocation) + "/gd3_logo.png")
- if not logoTempFile.exists():
- with open(logoTempFile, "wb") as f:
- f.write(QResource(":/image/logo.png").data())
- icon = {
- 'src': f"file://{logoTempFile}",
- 'placement': 'appLogoOverride'
- }
- TaskExecutor.run(toast, "接收到来自浏览器的下载任务:", "https://cn.pornhub.com", on_click=lambda args: print('clicked!', args), icon=icon)
+ pass
+ # TaskExecutor.run(desktopNotifier.send, "Received:", "https://github.com", buttons=[
+ # Button("OpenFile", lambda :openFile(r"C:\Users\XiaoYouChR\Downloads\10.0 Cheetah & 10.1 Puma.png"))
+ # ],)
def show_finished_toast(self):
- from app.common.concurrent.TaskExecutor import TaskExecutor
- from PySide6.QtCore import QStandardPaths, QFileInfo
- from win11toast import toast
- from PySide6.QtWidgets import QFileIconProvider
- from os.path import dirname
-
- fileResolovePath = r"C:\Users\BGTV\Downloads\Ghost-Downloader-v3.5.4-Windows-x86_64.zip"
-
- iconTempFile = QStandardPaths.writableLocation(QStandardPaths.TempLocation) + "/finished_file_icon.png"
- QFileIconProvider().icon(QFileInfo(fileResolovePath)).pixmap(128, 128).save(iconTempFile, "PNG")
-
- icon = {
- 'src': f"file://{iconTempFile}",
- 'placement': 'appLogoOverride'
- }
-
- buttons = [
- {'activationType': 'protocol', 'arguments': fileResolovePath, 'content': '打开文件'},
- {'activationType': 'protocol', 'arguments': dirname(fileResolovePath), 'content': '打开目录'}
- ]
-
- TaskExecutor.run(toast, "下载完成", fileResolovePath, icon=icon, buttons=buttons)
-
+ pass
+ # TaskExecutor.run(desktopNotifier.send, "Received:", "https://github.com", buttons=[
+ # Button("OpenFile", lambda :openFile(r"C:\Users\XiaoYouChR\Downloads\10.0 Cheetah & 10.1 Puma.png"))
+ # ])
def show_received_pop_up(self):
ReceivedPopUpWindow.showPopUpWindow(f"")
def show_finished_pop_up(self):
- FinishedPopUpWindow.showPopUpWindow(r"F:\Class-Widget\audio\attend_class.wav")
+ FinishedPopUpWindow.showPopUpWindow(r"C:\Users\XiaoYouChR\Downloads\OfficeSetup.exe")
if __name__ == "__main__":
app = QApplication(sys.argv)