Skip to content

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

fix(platform): 关机时延缓系统退出以保存任务记录 (#1200)

XiaoYouChR94daaff93128
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index f034eca0..ad427376 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import os
import sys
import traceback
+from contextlib import suppress
from dataclasses import replace
from typing import TYPE_CHECKING
@@ -373,12 +374,23 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
updateService.changed.connect(onUpdateChanged)
checkUpdateAtStartup(updateService)
- def onAboutToQuit():
- engine.stop()
- updateService.apply()
- coroutineRunner.stop()
+ def onTerminated() -> None:
+ with suppress(RuntimeError):
+ application.aboutToQuit.disconnect(updateService.apply)
- application.aboutToQuit.connect(onAboutToQuit)
+ application.aboutToQuit.connect(engine.stop)
+ application.aboutToQuit.connect(updateService.apply)
+ application.aboutToQuit.connect(coroutineRunner.stop)
+ application.terminated.connect(onTerminated)
+ if sys.platform == "win32":
+ from app.platform.windows import ShutdownListener
+ shutdownListener = ShutdownListener(
+ application.translate("Shutdown", "正在保存任务进度"),
+ icon=QIcon(":/image/logo.png"),
+ )
+ application.shutdownListener = shutdownListener
+ shutdownListener.triggered.connect(onTerminated)
+ application.aboutToQuit.connect(shutdownListener.close)
from app.cli import Cli
cli = Cli(taskService, featureService.parse, coroutineRunner.submit,
diff --git a/app/platform/application.py b/app/platform/application.py
index 155072ef..37880695 100644
--- a/app/platform/application.py
+++ b/app/platform/application.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import sys
from pathlib import Path
-from signal import signal, SIGINT
+from signal import SIGINT, signal
from typing import TYPE_CHECKING
from PySide6.QtCore import QEvent, Signal
@@ -20,6 +20,7 @@ class Application(QApplication):
openRequested = Signal(str)
activated = Signal()
systemPaletteChanged = Signal()
+ terminated = Signal()
def __init__(self, argv: list[str]) -> None:
super().__init__(argv)
@@ -28,7 +29,44 @@ class Application(QApplication):
self.setDesktopFileName(DESKTOP_ID)
self.isFileDragActive: bool = False
self.clipboardListener: ClipboardListener | None = None
- signal(SIGINT, self._onInterrupt)
+ if sys.platform == "win32":
+ signal(SIGINT, self._onInterrupt)
+ else:
+ import socket
+ from signal import SIG_DFL, SIGTERM, set_wakeup_fd
+ from PySide6.QtCore import QSocketNotifier
+
+ readSock, writeSock = socket.socketpair()
+ readSock.setblocking(False)
+ writeSock.setblocking(False)
+ prevFd = set_wakeup_fd(writeSock.fileno(), warn_on_full_buffer=False)
+ signal(SIGINT, lambda *_: None)
+ signal(SIGTERM, lambda *_: None)
+ notifier = QSocketNotifier(readSock.fileno(), QSocketNotifier.Type.Read, self)
+
+ def onSignal() -> None:
+ try:
+ data = readSock.recv(64)
+ except BlockingIOError:
+ return
+ if SIGTERM in data:
+ notifier.setEnabled(False)
+ self.terminated.emit()
+ self.quit()
+ elif SIGINT in data:
+ notifier.setEnabled(False)
+ self._onInterrupt(SIGINT, None)
+
+ def closeSignals() -> None:
+ notifier.setEnabled(False)
+ signal(SIGINT, SIG_DFL)
+ signal(SIGTERM, SIG_DFL)
+ set_wakeup_fd(prevFd)
+ readSock.close()
+ writeSock.close()
+
+ notifier.activated.connect(onSignal)
+ self.aboutToQuit.connect(closeSignals)
def event(self, e: QEvent) -> bool:
if isinstance(e, QFileOpenEvent):
diff --git a/app/platform/windows.py b/app/platform/windows.py
index fb87a55c..9193ea75 100644
--- a/app/platform/windows.py
+++ b/app/platform/windows.py
@@ -54,3 +54,64 @@ def setAnimationFrameRate(frameRate: float) -> None:
instance.restype = c_void_p
setTimingInterval.argtypes = [c_void_p, c_int]
setTimingInterval(instance(), round(1000 / frameRate))
+
+
+if sys.platform == "win32":
+ import ctypes
+ from contextlib import suppress
+ from ctypes import WinDLL, wintypes
+ from typing import TYPE_CHECKING
+
+ from PySide6.QtCore import QAbstractNativeEventFilter, QCoreApplication
+ from loguru import logger
+
+ from app.signal import Signal
+
+ if TYPE_CHECKING:
+ from PySide6.QtGui import QIcon
+
+ _user32 = WinDLL("user32", use_last_error=True)
+ _user32.ShutdownBlockReasonCreate.argtypes = [wintypes.HWND, wintypes.LPCWSTR]
+ _user32.ShutdownBlockReasonCreate.restype = wintypes.BOOL
+ _user32.ShutdownBlockReasonDestroy.argtypes = [wintypes.HWND]
+ _user32.ShutdownBlockReasonDestroy.restype = wintypes.BOOL
+
+ class ShutdownListener(QAbstractNativeEventFilter):
+ triggered = Signal()
+
+ def __init__(self, reason: str, icon: QIcon) -> None:
+ super().__init__()
+ from PySide6.QtGui import QWindow
+
+ self._reason = reason[:255]
+ self._window = QWindow()
+ self._window.setTitle("Ghost Downloader")
+ self._window.setIcon(icon)
+ self._window.create()
+ self._hwnd = int(self._window.winId())
+ QCoreApplication.instance().installNativeEventFilter(self)
+
+ def nativeEventFilter(self, eventType, message):
+ if bytes(eventType) != b"windows_generic_MSG":
+ return False, 0
+ msg = wintypes.MSG.from_address(int(message))
+ if msg.message == 0x0011: # WM_QUERYENDSESSION
+ try:
+ if not _user32.ShutdownBlockReasonCreate(self._hwnd, self._reason):
+ logger.warning("阻止系统关机失败: {}", ctypes.get_last_error())
+ except OSError as e:
+ logger.warning("阻止系统关机失败: {}", e)
+ elif msg.message == 0x0016: # WM_ENDSESSION
+ if msg.wParam:
+ self.triggered.emit()
+ else:
+ with suppress(OSError):
+ _user32.ShutdownBlockReasonDestroy(self._hwnd)
+ # 必须放行给 Qt,否则取消关机后 QWindowsSessionManager 不会解锁输入
+ return False, 0
+
+ def close(self) -> None:
+ with suppress(OSError):
+ _user32.ShutdownBlockReasonDestroy(self._hwnd)
+ QCoreApplication.instance().removeNativeEventFilter(self)
+ self._window.deleteLater()
diff --git a/tests/bittorrent_pack/test_session.py b/tests/bittorrent_pack/test_session.py
index 14c0e540..6a46fc14 100644
--- a/tests/bittorrent_pack/test_session.py
+++ b/tests/bittorrent_pack/test_session.py
@@ -293,3 +293,75 @@ async def test_set_selection_downloads_newly_selected_file(config, startServer,
finally:
await session.close()
seeder.remove_torrent(seederHandle)
+
+
+async def test_close_preserves_seeding_share_ratio(config, tmp_path):
+ torrentData, _ = buildMultiFileTorrent(tmp_path, {"a.bin": b"A" * 32768})
+ sourceRoot = tmp_path / "source"
+
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+ probe.bind(("127.0.0.1", 0))
+ listenPort = probe.getsockname()[1]
+
+ cfg.set(bittorrentConfig.listenPort, listenPort)
+ cfg.set(bittorrentConfig.enableDht, False)
+ cfg.set(bittorrentConfig.enableLsd, False)
+
+ ready, uploaded, restored = asyncio.Event(), asyncio.Event(), asyncio.Event()
+ restoredRatio = 0.0
+
+ def onSeeding(p):
+ if p.isSeeding:
+ ready.set()
+ if p.shareRatioPercent > 0:
+ uploaded.set()
+
+ def onRestored(p):
+ nonlocal restoredRatio
+ if p.isSeeding:
+ restoredRatio = p.shareRatioPercent
+ restored.set()
+
+ session, restarted = BTSession(), BTSession()
+ leecher = lt.session({
+ "listen_interfaces": "127.0.0.1:0", "enable_dht": False, "enable_lsd": False,
+ "enable_upnp": False, "enable_natpmp": False, "ignore_limits_on_local_network": True,
+ })
+ leecherHandle = seedingTask = restartedTask = None
+ try:
+ seedingTask = asyncio.create_task(session.runSeeding(
+ "t1", TorrentParams(torrentData=torrentData, savePath=str(sourceRoot)),
+ isManual=True, onProgress=onSeeding,
+ ))
+ async with asyncio.timeout(5):
+ await ready.wait()
+
+ params = lt.load_torrent_buffer(torrentData)
+ params.save_path = str(tmp_path / "leecher")
+ leecherHandle = leecher.add_torrent(params)
+ leecherHandle.resume()
+ leecherHandle.connect_peer(("127.0.0.1", listenPort))
+
+ async with asyncio.timeout(10):
+ await uploaded.wait()
+
+ await session.close()
+ assert seedingTask.done()
+ resumeData = session.lastResumeData("t1")
+ assert resumeData
+
+ restartedTask = asyncio.create_task(restarted.runSeeding(
+ "t1", TorrentParams(torrentData=torrentData, savePath=str(sourceRoot), resumeData=resumeData),
+ isManual=True, onProgress=onRestored,
+ ))
+ async with asyncio.timeout(10):
+ await restored.wait()
+ assert restoredRatio > 0
+ finally:
+ for task in (restartedTask, seedingTask):
+ if task is not None and not task.done():
+ await cancelRun(task)
+ await restarted.close()
+ await session.close()
+ if leecherHandle is not None:
+ leecher.remove_torrent(leecherHandle)