fix: 修复音乐路径设置后找不到音乐的问题

This commit is contained in:
涵曦 2024-07-14 09:52:14 +00:00
parent dd77176035
commit d8a66ca152
2 changed files with 24 additions and 6 deletions

View File

@ -1,5 +1,6 @@
import asyncio import asyncio
import json import json
from pathlib import Path
import os import os
import secrets import secrets
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
@ -73,7 +74,6 @@ def reset_http_server():
app.dependency_overrides[verification] = no_verification app.dependency_overrides[verification] = no_verification
else: else:
app.dependency_overrides = {} app.dependency_overrides = {}
app.mount("/music", StaticFiles(directory=config.music_path), name="music")
def HttpInit(_xiaomusic): def HttpInit(_xiaomusic):
@ -86,6 +86,24 @@ def HttpInit(_xiaomusic):
reset_http_server() reset_http_server()
@app.get("/music/{file_path:path}")
async def read_music_file(file_path: str):
base_dir = Path(config.music_path).resolve()
real_path = os.path.join(base_dir, file_path)
file_location = Path(real_path).resolve()
log.info(f"read_music_file. file_path:{file_path} real_path:{real_path}")
if not file_location.exists() or not file_location.is_file():
raise HTTPException(status_code=404, detail="File not found")
# 确保请求的文件在我们的基础目录下
if base_dir not in file_location.parents:
raise HTTPException(
status_code=403, detail="Access to this file is not permitted"
)
return FileResponse(file_location)
@app.get("/") @app.get("/")
async def read_index(): async def read_index():
return FileResponse("xiaomusic/static/index.html") return FileResponse("xiaomusic/static/index.html")