74 lines
2.0 KiB
Python
74 lines
2.0 KiB
Python
"""
|
|
backend/app/services/kb/storage.py
|
|
|
|
用途:知识库本地文件存储路径解析与上传写入。
|
|
依赖:Flask current_app、hashlib。
|
|
逻辑:api/kb/common 与 services/kb/path_upload_service 共用;禁止 import api 层。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import re
|
|
from pathlib import Path
|
|
|
|
from flask import current_app
|
|
|
|
|
|
def safe_upload_filename(raw_filename: str | None) -> str:
|
|
"""
|
|
清洗上传文件名,去除路径分隔与非法字符。
|
|
Args:
|
|
raw_filename: 原始文件名。
|
|
Returns:
|
|
安全文件名。
|
|
"""
|
|
original_name = Path(raw_filename or '').name.strip()
|
|
if not original_name:
|
|
return 'uploaded_file'
|
|
safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name)
|
|
return safe_name or 'uploaded_file'
|
|
|
|
|
|
def kb_storage_root() -> Path:
|
|
"""返回 KB_STORAGE_ROOT 并确保目录存在。"""
|
|
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
return root
|
|
|
|
|
|
def resolve_storage_path(path_value: str | None) -> Path | None:
|
|
"""
|
|
解析存储路径并校验在 KB_STORAGE_ROOT 内。
|
|
Returns:
|
|
绝对 Path 或 None(越界/空)。
|
|
"""
|
|
if not path_value:
|
|
return None
|
|
candidate = Path(path_value).resolve()
|
|
root = kb_storage_root()
|
|
try:
|
|
candidate.relative_to(root)
|
|
except ValueError:
|
|
return None
|
|
return candidate
|
|
|
|
|
|
def save_upload(file_storage, target_path: Path) -> tuple[str, int]:
|
|
"""
|
|
流式写入上传文件并计算 sha256。
|
|
Returns:
|
|
(sha256_hex, size_bytes)。
|
|
"""
|
|
target_path.parent.mkdir(parents=True, exist_ok=True)
|
|
sha = hashlib.sha256()
|
|
size = 0
|
|
with target_path.open('wb') as handle:
|
|
while True:
|
|
chunk = file_storage.stream.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
handle.write(chunk)
|
|
sha.update(chunk)
|
|
size += len(chunk)
|
|
return sha.hexdigest(), size
|