Skip to content

Commit

Permalink
修复一个看得懂的人都觉得很好笑的 Bug,安全的关闭未完成的任务以防止程序闪退
Browse files Browse the repository at this point in the history
  • Loading branch information
XiaoYouChR committed Sep 17, 2024
1 parent 1d8110b commit 1e8b075
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 30 deletions.
52 changes: 26 additions & 26 deletions app/common/download_task.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import asyncio
import re
import struct
from asyncio import Task
from pathlib import Path
from threading import Thread
from types import coroutine

import httpx
from PySide6.QtCore import QThread, Signal
Expand Down Expand Up @@ -95,15 +95,15 @@ def __init__(self, url, maxBlockNum: int = 8, filePath=None, fileName=None, pare
self.filePath = filePath
self.maxBlockNum = maxBlockNum
self.workers: list[DownloadWorker] = []
self.tasks: list[coroutine] = []
self.tasks: list[Task] = []

self.client = httpx.AsyncClient(headers=Headers, verify=False,
proxy=getProxy(), limits=httpx.Limits(max_connections=256))

self.__tempThread = Thread(target=self.__getLinkInfo, daemon=True) # TODO 获取文件名和文件大小的线程等信息, 暂时使用线程方式
self.__tempThread.start()

def __reassignWorker(self, task: coroutine):
def __reassignWorker(self, task: Task):

# 找到剩余进度最多的线程
maxRemainder = 0
Expand All @@ -130,7 +130,7 @@ def __reassignWorker(self, task: coroutine):

newWorker = DownloadWorker(s_pos, s_pos, maxRemainderWorkerEnd, self.client)

newTask = asyncio.create_task(self.__handleWorker(newWorker))
newTask = self.loop.create_task(self.__handleWorker(newWorker))
newTask.add_done_callback(self.__reassignWorker)

self.workers.insert(self.workers.index(maxRemainderWorker) + 1, newWorker)
Expand Down Expand Up @@ -220,7 +220,7 @@ async def __handleWorker(self, worker: DownloadWorker):
finished = False
while not finished:
try:
download_headers = Headers
download_headers = Headers.copy()
download_headers["range"] = f"bytes={worker.process}-{worker.endPos}" # 添加范围

async with worker.client.stream(url=self.url, headers=download_headers, timeout=30,
Expand Down Expand Up @@ -296,6 +296,20 @@ async def __main(self):
# 关闭
await self.client.aclose()

self.file.close()
self.ghdFile.close()

# 删除历史记录文件
try:
Path(f"{self.filePath}/{self.fileName}.ghd").unlink()

except Exception as e:
logger.error(f"Failed to delete the history file, please delete it manually. Err: {e}")

logger.info(f"Task {self.fileName} finished!")

self.taskFinished.emit()

except Exception as e:
self.gotWrong.emit(repr(e))

Expand All @@ -314,27 +328,13 @@ def run(self):
self.__loadWorkers()

# 主逻辑, 使用事件循环启动异步任务
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)

try:
loop.run_until_complete(self.__main())
except asyncio.CancelledError:
pass
self.loop.run_until_complete(self.__main())
except asyncio.CancelledError as e:
print(e)
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()

self.file.close()
self.ghdFile.close()

# 删除历史记录文件
try:
Path(f"{self.filePath}/{self.fileName}.ghd").unlink()

except Exception as e:
logger.error(f"Failed to delete the history file, please delete it manually. Err: {e}")

logger.info(f"Task {self.fileName} finished!")

self.taskFinished.emit()
self.loop.run_until_complete(self.loop.shutdown_asyncgens())
self.loop.close()
8 changes: 6 additions & 2 deletions app/components/custom_tray.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import time

from PySide6.QtCore import QRect
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QSystemTrayIcon, QApplication
Expand Down Expand Up @@ -66,13 +68,15 @@ def __onQuitActionTriggered(self):
for j in i.task.tasks:
j.cancel()

while not all(j.done() for j in i.task.tasks):
time.sleep(0.05)

i.task.file.close()
i.task.ghdFile.close()
i.task.terminate()
i.task.wait()
i.task.deleteLater()

delete(i.task)

QApplication.quit()

def onTrayIconClick(self, reason):
Expand Down
7 changes: 5 additions & 2 deletions app/components/task_card.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import hashlib
import re
import time
from pathlib import Path

from PySide6.QtCore import QThread, Signal, QFileInfo
Expand Down Expand Up @@ -148,13 +149,15 @@ def pauseTask(self):
for i in self.task.tasks:
i.cancel()

while not all(i.done() for i in self.task.tasks):
time.sleep(0.05)

self.task.file.close()
self.task.ghdFile.close()
self.task.terminate()
self.task.wait()
self.task.deleteLater()

delete(self.task)

# 改变记录状态
with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:
_ = f.read()
Expand Down

0 comments on commit 1e8b075

Please sign in to comment.