修复 AList Strm Gen 插件无法生成 STRM 文件的问题,规范日志输出

This commit is contained in:
x1ao4 2025-05-30 19:29:56 +08:00
parent 4aed66e59d
commit 60352fbe62
3 changed files with 119 additions and 62 deletions

View File

@ -2,7 +2,7 @@ import re
import requests import requests
""" """
配合 Alist-Strm 项目触发特定配置运行 配合 AList-Strm 项目触发特定配置运行
https://github.com/tefuirZ/alist-strm https://github.com/tefuirZ/alist-strm
""" """
@ -47,12 +47,12 @@ class Alist_strm:
for item in matchs for item in matchs
if item[0] in config_id_str.split(",") if item[0] in config_id_str.split(",")
] ]
print(f"Alist-Strm 配置运行: {config_name}") print(f"AList-Strm 配置运行: {config_name}")
return True return True
else: else:
print(f"Alist-Strm 配置运行: 匹配失败 ❌ 请检查网络连通和cookie有效性") print(f"AList-Strm 配置运行: 匹配失败 ❌ 请检查网络连通和 Cookie 有效性")
except Exception as e: except Exception as e:
print(f"获取 Alist-Strm 配置信息出错: {e}") print(f"获取 AList-Strm 配置信息出错 ❌ {e}")
return False return False
def run_selected_configs(self, selected_configs_str): def run_selected_configs(self, selected_configs_str):
@ -61,7 +61,7 @@ class Alist_strm:
try: try:
selected_configs = [int(x.strip()) for x in selected_configs_str.split(",")] selected_configs = [int(x.strip()) for x in selected_configs_str.split(",")]
except ValueError: except ValueError:
print("🔗 Alist-Strm 配置运行: 出错 ❌ ID 应以 , 分割") print("🔗 AList-Strm 配置运行: 出错 ❌ ID 应以 , 分割")
return False return False
data = [("selected_configs", config_id) for config_id in selected_configs] data = [("selected_configs", config_id) for config_id in selected_configs]
data.append(("action", "run_selected")) data.append(("action", "run_selected"))
@ -73,10 +73,10 @@ class Alist_strm:
match = re.search(r'role="alert">\s*([^<]+)\s*<button', html_content) match = re.search(r'role="alert">\s*([^<]+)\s*<button', html_content)
if match: if match:
alert = match.group(1).strip() alert = match.group(1).strip()
print(f"🔗 Alist-Strm 配置运行: {alert}") print(f"🔗 AList-Strm 配置运行: {alert}")
return True return True
else: else:
print(f"🔗 Alist-Strm 配置运行: 失败 ❌") print(f"🔗 AList-Strm 配置运行: 失败 ❌")
except Exception as e: except Exception as e:
print(f"Error: {e}") print(f"Error: {e}")
return False return False

View File

@ -2,16 +2,15 @@
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
""" """
@File : alist_strm_gen.py @File : alist_strm_gen.py
@Desc : Alist 生成 strm 文件简化版 @Desc : AList 生成 STRM 文件简化版
@Version : v1.1 @Time : 2025/05/30
@Time : 2024/11/16 @Author : xiaoQQya, x1ao4
@Author : xiaoQQya
@Contact : xiaoQQya@126.com
""" """
import os import os
import re import re
import json import json
import requests import requests
from quark_auto_save import sort_file_by_name
class Alist_strm_gen: class Alist_strm_gen:
@ -32,47 +31,97 @@ class Alist_strm_gen:
storage_mount_path = None storage_mount_path = None
quark_root_dir = None quark_root_dir = None
strm_server = None strm_server = None
# 缓存生成的文件列表
generated_files = []
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.plugin_name = self.__class__.__name__.lower() self.plugin_name = self.__class__.__name__.lower()
if kwargs:
for key, _ in self.default_config.items(): # 检查必要配置
if key in kwargs: missing_configs = []
setattr(self, key, kwargs[key]) for key, _ in self.default_config.items():
if key in kwargs:
setattr(self, key, kwargs[key])
else:
missing_configs.append(key)
if missing_configs:
print(f"{self.plugin_name} 模块缺少必要参数: {', '.join(missing_configs)}")
return
if not self.url or not self.token or not self.storage_id:
print(f"{self.plugin_name} 模块配置不完整,请检查配置")
return
# 检查 strm_save_dir 是否存在
if not os.path.exists(self.strm_save_dir):
try:
os.makedirs(self.strm_save_dir)
except Exception as e:
print(f"创建 STRM 保存目录失败 ❌ {e}")
return
success, result = self.storage_id_to_path(self.storage_id)
if success:
self.is_active = True
# 存储挂载路径, 夸克根文件夹
self.storage_mount_path, self.quark_root_dir = result
# 替换strm文件内链接的主机地址
self.strm_replace_host = self.strm_replace_host.strip()
if self.strm_replace_host:
if self.strm_replace_host.startswith("http"):
self.strm_server = f"{self.strm_replace_host}/d"
else: else:
print(f"{self.plugin_name} 模块缺少必要参数: {key}") self.strm_server = f"http://{self.strm_replace_host}/d"
if self.url and self.token and self.storage_id: else:
success, result = self.storage_id_to_path(self.storage_id) self.strm_server = f"{self.url.strip()}/d"
if success: else:
self.is_active = True pass
# 存储挂载路径, 夸克根文件夹
self.storage_mount_path, self.quark_root_dir = result
# 替换strm文件内链接的主机地址
self.strm_replace_host = self.strm_replace_host.strip()
if self.strm_replace_host:
if self.strm_replace_host.startswith("http"):
self.strm_server = f"{self.strm_replace_host}/d"
else:
self.strm_server = f"http://{self.strm_replace_host}/d"
else:
self.strm_server = f"{self.url.strip()}/d"
def run(self, task, **kwargs): def run(self, task, **kwargs):
if not self.is_active:
return
task_config = task.get("addition", {}).get( task_config = task.get("addition", {}).get(
self.plugin_name, self.default_task_config self.plugin_name, self.default_task_config
) )
if not task_config.get("auto_gen"): if not task_config.get("auto_gen"):
return return
if task.get("savepath") and task.get("savepath").startswith(
self.quark_root_dir if not task.get("savepath"):
): return
alist_path = os.path.normpath(
os.path.join( # 标准化路径
self.storage_mount_path, savepath = os.path.normpath(task["savepath"]).replace("\\", "/")
task["savepath"].replace(self.quark_root_dir, "", 1).lstrip("/"), quark_root = os.path.normpath(self.quark_root_dir).replace("\\", "/")
)
).replace("\\", "/") # 确保路径以 / 开头
self.check_dir(alist_path) if not savepath.startswith("/"):
savepath = "/" + savepath
if not quark_root.startswith("/"):
quark_root = "/" + quark_root
if not savepath.startswith(quark_root):
print(f"{self.plugin_name} 任务的保存路径不在配置的夸克根目录内,跳过处理")
return
alist_path = os.path.normpath(
os.path.join(
self.storage_mount_path,
savepath.replace(quark_root, "", 1).lstrip("/"),
)
).replace("\\", "/")
# 清空生成的文件列表
self.generated_files = []
self.check_dir(alist_path)
# 按顺序显示生成的文件
if self.generated_files:
sorted_files = sorted(self.generated_files, key=sort_file_by_name)
for file_path in sorted_files:
print(f"🌐 生成 STRM 文件: {file_path} 成功 ✅")
def storage_id_to_path(self, storage_id): def storage_id_to_path(self, storage_id):
storage_mount_path, quark_root_dir = None, None storage_mount_path, quark_root_dir = None, None
@ -82,7 +131,7 @@ class Alist_strm_gen:
storage_mount_path, quark_root_dir = match.group(1), match.group(2) storage_mount_path, quark_root_dir = match.group(1), match.group(2)
file_list = self.get_file_list(storage_mount_path) file_list = self.get_file_list(storage_mount_path)
if file_list.get("code") != 200: if file_list.get("code") != 200:
print(f"Alist-Strm 生成: 获取挂载路径失败 ❌ {file_list.get('message')}") print(f"AList-Strm 生成: 获取挂载路径失败 ❌ {file_list.get('message')}")
return False, (None, None) return False, (None, None)
# 2. 检查是否数字,调用 Alist API 获取存储信息 # 2. 检查是否数字,调用 Alist API 获取存储信息
elif re.match(r"^\d+$", storage_id): elif re.match(r"^\d+$", storage_id):
@ -97,15 +146,15 @@ class Alist_strm_gen:
) )
elif storage_info["driver"] == "QuarkTV": elif storage_info["driver"] == "QuarkTV":
print( print(
f"Alist-Strm 生成: [QuarkTV] 驱动 ⚠️ storage_id 请手动填入 /Alist挂载路径:/Quark目录路径" f"AList-Strm 生成: [QuarkTV] 驱动 ⚠️ storage_id 请手动填入 /Alist挂载路径:/Quark目录路径"
) )
else: else:
print(f"Alist-Strm 生成: 不支持 [{storage_info['driver']}] 驱动 ❌") print(f"AList-Strm 生成: 不支持 [{storage_info['driver']}] 驱动 ❌")
else: else:
print(f"Alist-Strm 生成: storage_id [{storage_id}] 格式错误") print(f"AList-Strm 生成: storage_id [{storage_id}] 格式错误 ")
# 返回结果 # 返回结果
if storage_mount_path and quark_root_dir: if storage_mount_path and quark_root_dir:
print(f"Alist-Strm 生成: [{storage_mount_path}:{quark_root_dir}]") print(f"AList-Strm 生成: [{storage_mount_path}:{quark_root_dir}]")
return True, (storage_mount_path, quark_root_dir) return True, (storage_mount_path, quark_root_dir)
else: else:
return False, (None, None) return False, (None, None)
@ -121,15 +170,15 @@ class Alist_strm_gen:
if data.get("code") == 200: if data.get("code") == 200:
return data.get("data", []) return data.get("data", [])
else: else:
print(f"Alist-Strm 生成: 获取存储失败 ❌ {data.get('message')}") print(f"AList-Strm 生成: 获取存储失败 ❌ {data.get('message')}")
except Exception as e: except Exception as e:
print(f"Alist-Strm 生成: 获取存储出错 {e}") print(f"AList-Strm 生成: 获取存储出错 ❌ {e}")
return [] return []
def check_dir(self, path): def check_dir(self, path):
data = self.get_file_list(path) data = self.get_file_list(path)
if data.get("code") != 200: if data.get("code") != 200:
print(f"📺 Alist-Strm 生成: 获取文件列表失败 ❌ {data.get('message')}") print(f"🌐 AList-Strm 生成: 获取文件列表失败 ❌ {data.get('message')}")
return return
elif files := data.get("data", {}).get("content"): elif files := data.get("data", {}).get("content"):
for item in files: for item in files:
@ -154,7 +203,7 @@ class Alist_strm_gen:
response.raise_for_status() response.raise_for_status()
return response.json() return response.json()
except Exception as e: except Exception as e:
print(f"📺 Alist-Strm 生成: 获取文件列表出错 ❌ {e}") print(f"🌐 AList-Strm 生成: 获取文件列表出错 ❌ {e}")
return {} return {}
def generate_strm(self, file_path): def generate_strm(self, file_path):
@ -168,10 +217,18 @@ class Alist_strm_gen:
if os.path.exists(strm_path): if os.path.exists(strm_path):
return return
if not os.path.exists(os.path.dirname(strm_path)): if not os.path.exists(os.path.dirname(strm_path)):
os.makedirs(os.path.dirname(strm_path)) try:
with open(strm_path, "w", encoding="utf-8") as strm_file: os.makedirs(os.path.dirname(strm_path))
strm_file.write(f"{self.strm_server}{file_path}") except Exception as e:
print(f"📺 生成 STRM 文件 {strm_path} 成功 ✅") print(f"🌐 创建目录失败: {os.path.dirname(strm_path)}{e}")
return
try:
with open(strm_path, "w", encoding="utf-8") as strm_file:
strm_file.write(f"{self.strm_server}{file_path}")
# 将生成的文件添加到列表中,稍后统一显示
self.generated_files.append(strm_path)
except Exception as e:
print(f"🌐 生成 STRM 文件: {strm_path} 失败 ❌ {e}")
def get_root_folder_full_path(self, cookie, pdir_fid): def get_root_folder_full_path(self, cookie, pdir_fid):
if pdir_fid == "0": if pdir_fid == "0":
@ -203,5 +260,5 @@ class Alist_strm_gen:
path = f"{path}/{item['file_name']}" path = f"{path}/{item['file_name']}"
return path return path
except Exception as e: except Exception as e:
print(f"Alist-Strm 生成: 获取 Quark 路径出错 {e}") print(f"AList-Strm 生成: 获取 Quark 路径出错 ❌ {e}")
return "" return ""

View File

@ -151,7 +151,7 @@ class Aria2:
download_return, cookie = account.download(file_fids) download_return, cookie = account.download(file_fids)
if not download_return.get("data"): if not download_return.get("data"):
print("📝 Aria2: 获取下载链接失败") print("📝 Aria2: 获取下载链接失败")
return return
# 准备要下载的文件信息 # 准备要下载的文件信息
@ -186,7 +186,7 @@ class Aria2:
# print(f"📥 Aria2下载: {file_path} (已存在,跳过)") # print(f"📥 Aria2下载: {file_path} (已存在,跳过)")
continue continue
print(f"📥 Aria2 下载: {file_path}") print(f"📥 添加 Aria2 下载任务: {file_path} 成功 ✅")
# 确保目录存在 # 确保目录存在
os.makedirs(os.path.dirname(local_path), exist_ok=True) os.makedirs(os.path.dirname(local_path), exist_ok=True)
@ -210,7 +210,7 @@ class Aria2:
if idx >= 0 and idx < len(file_info): if idx >= 0 and idx < len(file_info):
downloaded_files.append(file_info[idx]) downloaded_files.append(file_info[idx])
except Exception as e: except Exception as e:
print(f"📥 Aria2 添加下载任务失败: {e}") print(f"📥 添加 Aria2 下载任务失败 ❌ {e}")
# 如果配置了自动删除且有成功添加下载任务的文件,则删除夸克网盘中的文件 # 如果配置了自动删除且有成功添加下载任务的文件,则删除夸克网盘中的文件
if task_config.get("auto_delete_quark_files") and downloaded_files: if task_config.get("auto_delete_quark_files") and downloaded_files:
@ -225,7 +225,7 @@ class Aria2:
if files_to_delete: if files_to_delete:
account.delete(files_to_delete) account.delete(files_to_delete)
except Exception as e: except Exception as e:
print(f"📝 Aria2: 删除夸克网盘文件失败: {e}") print(f"📝 Aria2: 删除夸克网盘文件失败 {e}")
else: else:
if not task_config.get("auto_delete_quark_files"): if not task_config.get("auto_delete_quark_files"):
# 未启用自动删除,不需要输出信息 # 未启用自动删除,不需要输出信息
@ -249,7 +249,7 @@ class Aria2:
response.raise_for_status() response.raise_for_status()
return response.json() return response.json()
except Exception as e: except Exception as e:
print(f"Aria2 下载: 错误{e}") print(f"Aria2 下载: 错误{e}")
return {} return {}
def get_version(self): def get_version(self):
@ -259,7 +259,7 @@ class Aria2:
print(f"Aria2 下载: v{response['result']['version']}") print(f"Aria2 下载: v{response['result']['version']}")
return True return True
else: else:
print(f"Aria2 下载: 连接失败{response.get('error')}") print(f"Aria2 下载: 连接失败{response.get('error')}")
return False return False
def add_uri(self, params=None): def add_uri(self, params=None):