1
0
mirror of https://github.com/hanxi/xiaomusic.git synced 2026-03-19 08:49:45 +08:00

feat: 新增清空临时目录接口,优化tts接口

This commit is contained in:
涵曦
2026-01-14 22:59:32 +08:00
parent 31f5b1cfa2
commit 33d034e148
6 changed files with 51 additions and 41 deletions

View File

@@ -49,10 +49,18 @@ from xiaomusic.utils import (
safe_join_path,
try_add_access_control_param,
)
from xiaomusic.utils.file_utils import clean_temp_dir
router = APIRouter()
@router.post("/file/cleantempdir")
async def cleantempdir(Verifcation=Depends(verification)):
await clean_temp_dir(xiaomusic.config)
log.info("clean_temp_dir ok")
return {"ret": "OK"}
@router.post("/downloadjson")
async def downloadjson(data: UrlInfo, Verifcation=Depends(verification)):
"""下载 JSON"""

View File

@@ -1,5 +1,4 @@
import json
import os
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.base import BaseTrigger
@@ -9,6 +8,7 @@ from xiaomusic.holiday import (
is_off_day,
is_working_day,
)
from xiaomusic.utils.file_utils import clean_temp_dir
class CustomCronTrigger(BaseTrigger):
@@ -224,29 +224,7 @@ class Crontab:
if xiaomusic.config.enable_auto_clean_temp:
async def clean_temp_job():
try:
temp_dir = xiaomusic.config.temp_dir
if not os.path.exists(temp_dir):
self.log.info(f"临时目录不存在: {temp_dir}")
return
files = os.listdir(temp_dir)
deleted_count = 0
for filename in files:
try:
file_path = os.path.join(temp_dir, filename)
if os.path.isfile(file_path):
os.remove(file_path)
deleted_count += 1
self.log.debug(f"已删除临时文件: {file_path}")
except Exception as e:
self.log.warning(f"删除文件失败 {file_path}: {e}")
self.log.info(
f"定时清理临时文件完成,共删除 {deleted_count} 个文件"
)
except Exception as e:
self.log.exception(f"清理临时文件异常: {e}")
clean_temp_dir(xiaomusic.config)
self.add_job("0 3 * * *", clean_temp_job)
self.log.info("已添加每日凌晨3点定时清理临时文件任务")

View File

@@ -647,9 +647,6 @@ class XiaoMusicDevice:
)
self.log.info(f"edge-tts 生成的文件路径: {mp3_path}")
# 保存当前 TTS 文件路径,用于定时器清空文件
self._current_tts_file = mp3_path
# 生成播放 URL
url = self.xiaomusic._music_url_handler._get_file_url(mp3_path)
self.log.info(f"TTS 播放 URL: {url}")
@@ -678,20 +675,6 @@ class XiaoMusicDevice:
pass
# 再置空引用
self._tts_timer = None
# 保底逻辑:删除临时 mp3 文件
if (
hasattr(self, "_current_tts_file")
and self._current_tts_file
):
try:
if os.path.exists(self._current_tts_file):
await asyncio.sleep(1) # 延迟1秒后再删除文件
os.remove(self._current_tts_file)
self.log.info(
f"已删除 TTS 临时文件: {self._current_tts_file}"
)
except Exception as delete_err:
self.log.warning(f"删除 TTS 文件失败: {delete_err}")
await self.stop(arg1="notts")
except Exception as e:
self.log.error(f"TTS 定时器异常: {e}")

View File

@@ -336,6 +336,7 @@ var vConsole = new window.VConsole();
<div class="button-group">
<button id="refresh_music_tag">刷新tag</button>
<button id="clear_cache">清空缓存</button>
<button id="cleantempdir">清空临时目录</button>
<a href="/downloadlog" download="xiaomusic.txt"><button>下载日志文件</button></a>
</div>

View File

@@ -191,6 +191,22 @@ $(function () {
$("#clear_cache").on("click", () => {
localStorage.clear();
});
$("#cleantempdir").on("click", () => {
$.ajax({
type: "POST",
url: "/file/cleantempdir",
contentType: "application/json",
data: JSON.stringify({}),
success: (msg) => {
alert(msg.ret);
},
error: (msg) => {
alert(msg);
}
});
});
$("#hostname").on("change", function () {
const hostname = $(this).val();
// 检查是否包含端口号1到5位数字

View File

@@ -4,6 +4,7 @@
import logging
import os
import re
import shutil
log = logging.getLogger(__package__)
@@ -187,3 +188,26 @@ def chmoddir(dir_path: str) -> None:
log.info(f"Changed permissions of file: {item_path}")
except Exception as e:
log.info(f"chmoddir failed: {e}")
async def clean_temp_dir(config):
try:
temp_dir = config.temp_dir
if not os.path.exists(temp_dir):
log.info(f"临时目录不存在: {temp_dir}")
# 目录不存在时也创建,保持目录结构统一
os.makedirs(temp_dir, exist_ok=True)
log.info(f"已创建临时目录: {temp_dir}")
return
# 递归删除整个临时目录(包括目录内所有文件/子目录)
shutil.rmtree(temp_dir)
log.debug(f"已删除临时目录: {temp_dir}")
# 重新创建空的临时目录
os.makedirs(temp_dir, exist_ok=True)
log.info(f"已重新创建临时目录: {temp_dir}")
log.info("定时清理临时文件完成,已删除并重建临时目录")
except Exception as e:
log.exception(f"清理临时文件异常: {e}")