Skip to content

Commit bf23c55

Browse files
committed
fix: fix config init error
1. fix config init 2. remove passlib
1 parent e2a9beb commit bf23c55

29 files changed

Lines changed: 166 additions & 201 deletions

backend/pyproject.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,14 @@ requires-python = ">=3.11"
77
dependencies = [
88
"aiolimiter>=1.2.1",
99
"alembic>=1.17.2",
10-
"bcrypt==4.2.0",
10+
"bcrypt>=5.0.0",
1111
"beautifulsoup4>=4.13.4",
1212
"bencode-py>=4.0.0",
1313
"dotenv>=0.9.9",
1414
"fastapi>=0.116.1",
1515
"httpx[http2,socks]>=0.28.1",
1616
"jinja2>=3.1.6",
1717
"packaging>=25.0",
18-
"passlib>=1.7.4",
1918
"pydantic-settings>=2.0.0",
2019
"python-jose>=3.5.0",
2120
"python-multipart>=0.0.20",

backend/src/alembic/versions/002_migrate_to_new_schema.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ def upgrade() -> None:
3636
# 删除字段
3737
batch_op.drop_column("save_path")
3838

39+
# 清空 poster_link,迁移后重新获取
40+
conn.execute(sa.text("UPDATE bangumi SET poster_link = ''"))
41+
3942
# ========== 2. Torrent 表重建 ==========
4043
# 由于主键变更(id -> url),需要完全重建表
4144

backend/src/api/routes/bangumi.py

Lines changed: 9 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import logging
2+
import asyncio
23
from pathlib import Path
34

45
from fastapi import APIRouter, Depends, HTTPException
56
from fastapi.responses import FileResponse, JSONResponse
6-
from sqlalchemy.util.concurrency import asyncio
77

88
from module.database import Database, engine
99
from module.manager import BangumiManager
@@ -97,7 +97,7 @@ async def delete_rule(bangumi_id: str, file: bool = False):
9797
response_model=APIResponse,
9898
dependencies=[Depends(get_current_user)],
9999
)
100-
async def delete_many_rule(bangumi_id: list, file: bool = False):
100+
async def delete_many_rule(bangumi_id: list[int], file: bool = False):
101101
tasks = []
102102
for i in bangumi_id:
103103
tasks.append(BangumiManager().delete_rule(i, file))
@@ -185,29 +185,6 @@ async def refresh_poster():
185185
return u_response(resp)
186186

187187

188-
@router.get(
189-
path="/refresh/poster/{bangumi_id}",
190-
response_model=APIResponse,
191-
dependencies=[Depends(get_current_user)],
192-
)
193-
async def refresh_single_poster(bangumi_id: int):
194-
resp = await BangumiManager().refind_poster(bangumi_id)
195-
if resp:
196-
resp = ResponseModel(
197-
status_code=200,
198-
status=True,
199-
msg_en="Refresh poster link successfully.",
200-
msg_zh="刷新海报链接成功。",
201-
)
202-
else:
203-
resp = ResponseModel(
204-
status_code=406,
205-
status=False,
206-
msg_en=f"Can't find id {bangumi_id}",
207-
msg_zh=f"无法找到 id {bangumi_id}",
208-
)
209-
return u_response(resp)
210-
211188

212189
@router.get("/reset/all", response_model=APIResponse, dependencies=[Depends(get_current_user)])
213190
async def reset_all():
@@ -224,42 +201,22 @@ async def reset_all():
224201

225202
@router.get("/posters/{path:path}", dependencies=[Depends(get_current_user)])
226203
async def get_poster(path: str):
227-
"""
228-
安全的poster图片访问端点
229-
- 添加了用户鉴权
230-
- 防止路径遍历攻击
231-
- 限制只能访问posters目录下的文件
232-
"""
233-
# 验证路径安全性 - 阻止路径遍历
234-
if ".." in path or path.startswith("/") or "\\" in path:
235-
logger.warning(f"[Poster] Blocked path traversal attempt: {path}")
236-
raise HTTPException(status_code=400, detail="Invalid path")
237-
238-
# 构建安全的文件路径
239-
poster_dir = Path("data") / Path("posters")
240-
post_path = poster_dir / Path(path)
204+
poster_dir = (Path("data") / "posters").resolve()
205+
post_path = (poster_dir / path).resolve()
241206

242-
# 确保解析后的路径仍在预期目录内
243-
try:
244-
post_path.resolve().relative_to(poster_dir.resolve())
245-
except ValueError:
246-
logger.warning(f"[Poster] Path outside allowed directory: {path}")
247-
raise HTTPException(status_code=400, detail="Path outside allowed directory")
207+
if not post_path.is_relative_to(poster_dir):
208+
raise HTTPException(status_code=400, detail="Invalid path")
248209

249-
# 如果文件不存在,尝试下载
250210
if not post_path.exists():
251211
try:
252212
await load_image(path)
253213
except Exception as e:
254214
logger.warning(f"[Poster] Failed to load image {path}: {e}")
255215

256-
# 返回文件
257-
if post_path.exists() and post_path.is_file():
216+
if post_path.is_file():
258217
return FileResponse(
259218
post_path,
260219
media_type="image/jpeg",
261-
headers={"Cache-Control": "public, max-age=86400"}, # 缓存1天
220+
headers={"Cache-Control": "public, max-age=86400"},
262221
)
263-
else:
264-
logger.warning(f"[Poster] File not found: {post_path}")
265-
raise HTTPException(status_code=404, detail="Poster not found")
222+
raise HTTPException(status_code=404, detail="Poster not found")

backend/src/api/routes/program.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,10 @@ async def program_status():
9595
if not program.program_status.is_running:
9696
return {
9797
"status": False,
98-
"first_run": program.program_status.first_run,
9998
}
10099
else:
101100
return {
102101
"status": True,
103-
"first_run": program.program_status.first_run,
104102
}
105103

106104

backend/src/core/monitors/download_check.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import logging
33

44
from module.database import Database
5-
from module.downloader import Client as download_client
5+
from module.downloader import get_client
66
from models import Bangumi, Torrent
77
from module.utils import event_bus
88
from module.utils.events import Event, EventBus, EventType
@@ -96,11 +96,11 @@ async def _find_real_hash(self, hash_list: list[str]) -> str | None:
9696
logger.debug(f"[DownloadCheckMonitor] 检查 hash: {hash_value}")
9797
for _ in range(3):
9898
# 尝试从下载客户端获取种子信息
99-
if download_client.downloader_error:
99+
if get_client().downloader_error:
100100
logger.warning(f"[DownloadCheckMonitor] 下载客户端不可用,跳过检查 hash: {hash_value}")
101101
break
102102
try:
103-
info = await download_client.get_torrent_info(hash_value)
103+
info = await get_client().get_torrent_info(hash_value)
104104
last_exception = None
105105
if info:
106106
logger.info(f"[DownloadCheckMonitor] 找到真实hash: {hash_value}")

backend/src/core/monitors/download_monitor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from datetime import datetime, timedelta
44

55
from module.database import Database
6-
from module.downloader import Client as download_client
6+
from module.downloader import get_client
77
from models import Bangumi, Torrent
88
from module.utils import event_bus
99
from module.utils.events import Event, EventBus, EventType
@@ -131,7 +131,7 @@ async def monitor_torrent(self, bangumi: Bangumi, torrent: Torrent) -> None:
131131
break
132132

133133
# 获取种子信息
134-
info = await download_client.get_torrent_info(torrent_hash)
134+
info = await get_client().get_torrent_info(torrent_hash)
135135
logger.debug(f"[DownloadMonitor] 获取种子信息: {torrent.name} - {torrent_hash}")
136136

137137
if not info:

backend/src/core/monitors/notification_monitor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import logging
22
from typing import Any
33

4-
from module.notification import PostNotification,notification_config
4+
from module.notification import PostNotification, get_notification_config
55
from module.utils.events import Event, EventBus, EventType, event_bus
66

77
logger = logging.getLogger(__name__)
@@ -17,12 +17,12 @@ def __init__(self):
1717
self._event_bus: EventBus = event_bus
1818
self._notification_sender = PostNotification()
1919
self._running: bool = False
20-
self.enable: bool = notification_config.enable
20+
self.enable: bool = get_notification_config().enable
2121

2222
async def initialize(self):
2323
"""初始化通知监控器"""
2424
logger.info("[NotificationMonitor] 初始化通知监控器")
25-
self.enable = notification_config.enable
25+
self.enable = get_notification_config().enable
2626
if not self.enable:
2727
logger.warning("[NotificationMonitor] 通知功能未启用")
2828
return

backend/src/core/monitors/rename_monitor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import asyncio
22
import logging
33

4-
from module.rename import Renamer, rename_config
4+
from module.rename import Renamer, get_rename_config
55
from models import Bangumi, Torrent
66
from module.utils import event_bus
77
from module.utils.events import Event, EventBus, EventType
@@ -20,11 +20,11 @@ def __init__(self):
2020
self._initialized: bool = False
2121
# 存储活跃的重命名任务 {torrent_hash: asyncio.Task}
2222
self.active_rename_tasks: dict[str, asyncio.Task] = {}
23-
self.enable: bool = rename_config.enable
23+
self.enable: bool = get_rename_config().enable
2424

2525
async def initialize(self) -> None:
2626
"""初始化重命名器"""
27-
self.enable = rename_config.enable
27+
self.enable = get_rename_config().enable
2828
if not self.enable:
2929
logger.warning("[RenameMonitor] 重命名功能未启用")
3030
return

backend/src/core/program.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ async def startup(self):
4242
check_and_upgrade_database()
4343
except Exception as e:
4444
logger.error(f"数据库升级过程中出现异常: {e}")
45-
raise
46-
# 确保默认用户存在
45+
raise
46+
# 确保所有表存在(create_all 会跳过已存在的表,只创建缺失的)
4747
with Database() as db:
48+
db.create_table()
4849
db.user.add_default_user()
4950
await self.start()
5051

backend/src/core/services/download_service.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from typing_extensions import override
55

66
from module.database import Database, engine
7-
from module.downloader import Client as client
7+
from module.downloader import get_client
88
from module.downloader.download_queue import download_queue
99
from module.utils import event_bus
1010
from module.utils.events import Event, EventBus, EventType, ServiceException
@@ -48,7 +48,7 @@ async def execute(self) -> None:
4848
async def _download(self) -> None:
4949
"""从队列获取并执行下载任务"""
5050
# 确保下载客户端已登录,没有的话就直接返回
51-
if not await client.wait_for_login():
51+
if not await get_client().wait_for_login():
5252
return
5353

5454
queue_size = download_queue.qsize()
@@ -61,7 +61,7 @@ async def _download(self) -> None:
6161

6262
# 执行下载任务
6363
try:
64-
hash_list = await client.add_torrent(torrent, bangumi)
64+
hash_list = await get_client().add_torrent(torrent, bangumi)
6565
# 处理下载结果并发布检查事件
6666
if hash_list: # 下载请求已发送,hash列表不为空
6767
# 发布下载检查事件,让 DownloadCheckMonitor 验证真实hash
@@ -98,9 +98,7 @@ async def _publish_download_check(self, torrent: Torrent, bangumi: Bangumi, hash
9898
async def cleanup(self) -> None:
9999
"""清理下载客户端"""
100100
try:
101-
from module.downloader import Client
102-
103-
await Client.stop()
101+
await get_client().stop()
104102
self._initialized: bool = False
105103
logger.debug("[DownloadService] 下载客户端已重启")
106104
except Exception as e:

0 commit comments

Comments
 (0)