From f98f4c1f7702e9e1f1389f8dfd7d63187c84cd86 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Sun, 13 Jul 2025 13:16:36 +0800 Subject: [PATCH] =?UTF-8?q?refactor(helper):=20=E4=BC=98=E5=8C=96=20Torren?= =?UTF-8?q?tHelper=20=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加检查临时目录中是否存在种子文件 - 修改 match_torrent 方法参数类型 - 优化种子文件下载和处理逻辑 --- app/helper/torrent.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/app/helper/torrent.py b/app/helper/torrent.py index e650e23d..3aed486d 100644 --- a/app/helper/torrent.py +++ b/app/helper/torrent.py @@ -39,6 +39,22 @@ class TorrentHelper(metaclass=WeakSingleton): """ if url.startswith("magnet:"): return None, url, "", [], f"磁力链接" + # 构建 torrent 种子文件的存储路径 + file_path = (Path(settings.TEMP_PATH) / StringUtils.md5_hash(url)).with_suffix(".torrent") + if file_path.exists(): + try: + # 获取种子目录和文件清单 + folder_name, file_list = self.get_torrent_info(file_path) + # 无法获取信息,则认为缓存文件无效 + if not folder_name and not file_list: + raise ValueError("无效的缓存种子文件") + # 获取种子数据 + content = file_path.read_bytes() + # 成功拿到种子数据 + return file_path, content, folder_name, file_list, "" + except Exception as err: + logger.error(f"处理缓存的种子文件 {file_path} 时出错: {err},将重新下载") + file_path.unlink(missing_ok=True) # 请求种子文件 req = RequestUtils( ua=ua, @@ -105,10 +121,6 @@ class TorrentHelper(metaclass=WeakSingleton): if req.content: # 检查是不是种子文件,如果不是仍然抛出异常 try: - # 读取种子文件名 - file_name = self.get_url_filename(req, url) - # 种子文件路径 - file_path = Path(settings.TEMP_PATH) / file_name # 保存到文件 file_path.write_bytes(req.content) # 获取种子目录和文件清单 @@ -307,7 +319,7 @@ class TorrentHelper(metaclass=WeakSingleton): self._invalid_torrents.append(url) @staticmethod - def match_torrent(mediainfo: MediaInfo, torrent_meta: MetaInfo, torrent: TorrentInfo) -> bool: + def match_torrent(mediainfo: MediaInfo, torrent_meta: MetaBase, torrent: TorrentInfo) -> bool: """ 检查种子是否匹配媒体信息 :param mediainfo: 需要匹配的媒体信息