wiki.py
4.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import os
import io
import zipfile
import logging
logger = logging.getLogger(__name__)
from fastapi import APIRouter, HTTPException, Body
from fastapi.responses import FileResponse, StreamingResponse
from config import WIKI_DIR
router = APIRouter()
@router.get("/wiki/content/{name}")
async def get_wiki_content(name: str):
"""从 wiki 子目录中查找并返回特定页面的 Markdown 内容。"""
logger.info(f"请求查看 Wiki 页面内容: name={name}")
for root, dirs, files in os.walk(WIKI_DIR):
if name in files or f"{name}.md" in files:
target = os.path.join(root, name if name.endswith(".md") else f"{name}.md")
with open(target, "r", encoding="utf-8", errors="replace") as f:
return {"content": f.read()}
raise HTTPException(status_code=404, detail="Wiki page not found")
@router.get("/wiki/tree")
async def get_wiki_tree():
"""返回 ware/wiki 目录下的文件树结构。"""
logger.info("请求获取 Wiki 目录树")
def build_tree(dir_path, rel_path=""):
tree = []
try:
items = os.listdir(dir_path)
except Exception:
return tree
for item in sorted(items):
full_path = os.path.join(dir_path, item)
item_rel = os.path.join(rel_path, item).replace("\\", "/")
if os.path.isdir(full_path):
tree.append({
"name": item,
"type": "dir",
"path": item_rel,
"children": build_tree(full_path, item_rel)
})
else:
tree.append({
"name": item,
"type": "file",
"path": item_rel
})
return tree
return {"tree": build_tree(WIKI_DIR)}
@router.get("/wiki/file")
async def get_wiki_file_by_path(path: str):
"""根据相对路径读取 ware/wiki 下的文件内容。"""
if not path:
raise HTTPException(status_code=400, detail="Path is required")
target_path = os.path.abspath(os.path.join(WIKI_DIR, path))
if not target_path.startswith(os.path.abspath(WIKI_DIR)):
raise HTTPException(status_code=403, detail="Access denied")
if not os.path.exists(target_path) or not os.path.isfile(target_path):
raise HTTPException(status_code=404, detail="File not found")
try:
with open(target_path, "r", encoding="utf-8", errors="replace") as f:
return {"content": f.read()}
except Exception as e:
logger.error(f"读取 Wiki 文件失败 [{path}]: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/wiki/download")
async def download_wiki_file(path: str):
"""下载 ware/wiki 下的单个文件。"""
logger.info(f"请求下载单个 Wiki 文件: path={path}")
if not path:
raise HTTPException(status_code=400, detail="Path is required")
target_path = os.path.abspath(os.path.join(WIKI_DIR, path))
if not target_path.startswith(os.path.abspath(WIKI_DIR)):
raise HTTPException(status_code=403, detail="Access denied")
if not os.path.exists(target_path) or not os.path.isfile(target_path):
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(target_path, filename=os.path.basename(target_path))
@router.post("/wiki/download_batch")
async def download_wiki_batch(data: dict = Body(...)):
"""批量下载 ware/wiki 下的文件,返回 ZIP。"""
paths = data.get("paths", [])
logger.info(f"请求批量下载 Wiki 文件,涉及路径数量: {len(paths)}")
if not paths:
raise HTTPException(status_code=400, detail="No paths provided")
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for p in paths:
target_path = os.path.abspath(os.path.join(WIKI_DIR, p))
if target_path.startswith(os.path.abspath(WIKI_DIR)) and os.path.isfile(target_path):
zip_file.write(target_path, arcname=p)
zip_buffer.seek(0)
return StreamingResponse(
zip_buffer,
media_type="application/zip",
headers={"Content-Disposition": "attachment; filename=wiki_export.zip"}
)