-
Notifications
You must be signed in to change notification settings - Fork 299
Expand file tree
/
Copy pathconfig_files.py
More file actions
205 lines (168 loc) · 9.16 KB
/
Copy pathconfig_files.py
File metadata and controls
205 lines (168 loc) · 9.16 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# -*- coding: utf-8 -*-
# Copyright 2025-2026 Project N.E.K.O. Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Workshop config get/save and sandboxed file listing/reading
endpoints.
Split out of the former monolithic ``main_routers/workshop_router.py``.
"""
from ._shared import logger, router
import os
import asyncio
from urllib.parse import unquote
from fastapi.responses import JSONResponse
from utils.workshop_utils import (
get_workshop_path,
)
@router.get('/config')
async def get_workshop_config():
try:
from utils.workshop_utils import load_workshop_config
workshop_config_data = await asyncio.to_thread(load_workshop_config)
return {"success": True, "config": workshop_config_data}
except Exception as e:
logger.error(f"获取创意工坊配置失败: {str(e)}")
return {"success": False, "error": str(e)}
# 保存创意工坊配置
@router.post('/config')
async def save_workshop_config_api(config_data: dict):
try:
# 导入与get_workshop_config相同路径的函数,保持一致性
from utils.workshop_utils import load_workshop_config, save_workshop_config, ensure_workshop_folder_exists
# 先加载现有配置,避免使用全局变量导致的不一致问题
workshop_config_data = await asyncio.to_thread(load_workshop_config) or {}
# 更新配置
if 'default_workshop_folder' in config_data:
workshop_config_data['default_workshop_folder'] = config_data['default_workshop_folder']
if 'auto_create_folder' in config_data:
workshop_config_data['auto_create_folder'] = config_data['auto_create_folder']
# 支持用户mod路径配置
if 'user_mod_folder' in config_data:
workshop_config_data['user_mod_folder'] = config_data['user_mod_folder']
# 落盘 + 建目录一起交给同一个 worker。ensure_workshop_folder_exists 自己
# 还要再读一次配置文件、exists 一把、可能 os.makedirs —— 目标是网络盘或可
# 移动盘时这几下同样能把事件循环卡住,而且它必须排在保存之后(读的是刚写
# 进去的配置)。收成一个单元既保住次序,也不留半截在环上。
folder_path = ''
if workshop_config_data.get('auto_create_folder', True):
# 优先使用user_mod_folder,如果没有则使用default_workshop_folder
folder_path = workshop_config_data.get('user_mod_folder') or workshop_config_data.get('default_workshop_folder') or ''
def _save_and_ensure() -> None:
save_workshop_config(workshop_config_data)
if folder_path:
ensure_workshop_folder_exists(folder_path)
await asyncio.to_thread(_save_and_ensure)
return {"success": True, "config": workshop_config_data}
except Exception as e:
logger.error(f"保存创意工坊配置失败: {str(e)}")
return {"success": False, "error": str(e)}
def _assert_under_base(path: str, base: str) -> str:
full = os.path.realpath(os.path.normpath(path))
base_full = os.path.realpath(os.path.normpath(base))
if os.path.commonpath([full, base_full]) != base_full:
raise PermissionError("path not allowed")
return full
@router.get('/read-file')
async def read_workshop_file(path: str):
"""Read workshop file content."""
try:
logger.info(f"读取创意工坊文件请求,路径: {path}")
# 解码URL编码的路径
decoded_path = unquote(path)
decoded_path = _assert_under_base(decoded_path, get_workshop_path())
logger.info(f"解码后的路径: {decoded_path}")
# 检查文件是否存在
if not os.path.exists(decoded_path) or not os.path.isfile(decoded_path):
logger.warning(f"文件不存在: {decoded_path}")
return JSONResponse(content={"success": False, "error": "文件不存在"}, status_code=404)
# 检查文件大小限制(例如5MB)
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
file_size = os.path.getsize(decoded_path)
if file_size > MAX_FILE_SIZE:
logger.warning(f"文件过大: {decoded_path} ({file_size / 1024 / 1024:.2f}MB > {MAX_FILE_SIZE / 1024 / 1024}MB)")
return JSONResponse(content={"success": False, "error": "文件过大"}, status_code=413)
# 尝试判断文件类型并选择合适的读取方式
file_extension = os.path.splitext(decoded_path)[1].lower()
is_binary = file_extension in ['.mp3', '.wav', '.png', '.jpg', '.jpeg', '.gif']
if is_binary:
# 以二进制模式读取文件并进行base64编码
import base64
with open(decoded_path, 'rb') as f:
binary_content = f.read()
content = base64.b64encode(binary_content).decode('utf-8')
else:
# 以文本模式读取文件
with open(decoded_path, 'r', encoding='utf-8') as f:
content = f.read()
logger.info(f"成功读取文件: {decoded_path}, 是二进制文件: {is_binary}")
return JSONResponse(content={"success": True, "content": content, "is_binary": is_binary})
except Exception as e:
logger.error(f"读取文件失败: {str(e)}")
return JSONResponse(content={"success": False, "error": f"读取文件失败: {str(e)}"}, status_code=500)
@router.get('/list-chara-files')
async def list_chara_files(directory: str):
"""List all .chara.json files under the given directory."""
try:
logger.info(f"列出创意工坊目录下的角色卡文件请求,目录: {directory}")
# 解码URL编码的路径
decoded_dir = _assert_under_base(unquote(directory), get_workshop_path())
logger.info(f"解码后的目录路径: {decoded_dir}")
# 检查目录是否存在
if not os.path.exists(decoded_dir) or not os.path.isdir(decoded_dir):
logger.warning(f"目录不存在: {decoded_dir}")
return JSONResponse(content={"success": False, "error": "目录不存在"}, status_code=404)
# 查找所有.chara.json文件
chara_files = []
for filename in os.listdir(decoded_dir):
if filename.endswith('.chara.json'):
file_path = os.path.join(decoded_dir, filename)
if os.path.isfile(file_path):
chara_files.append({
'name': filename,
'path': file_path
})
logger.info(f"成功列出目录下的角色卡文件: {decoded_dir}, 找到 {len(chara_files)} 个文件")
return JSONResponse(content={"success": True, "files": chara_files})
except Exception as e:
logger.error(f"列出角色卡文件失败: {str(e)}")
return JSONResponse(content={"success": False, "error": f"列出角色卡文件失败: {str(e)}"}, status_code=500)
@router.get('/list-audio-files')
async def list_audio_files(directory: str):
"""List all audio files (.mp3, .wav) under the given directory."""
try:
logger.info(f"列出创意工坊目录下的音频文件请求,目录: {directory}")
# 解码URL编码的路径并验证是否在workshop目录下
decoded_dir = _assert_under_base(unquote(directory), get_workshop_path())
logger.info(f"解码后的目录路径: {decoded_dir}")
# 检查目录是否存在
if not os.path.exists(decoded_dir) or not os.path.isdir(decoded_dir):
logger.warning(f"目录不存在: {decoded_dir}")
return JSONResponse(content={"success": False, "error": "目录不存在"}, status_code=404)
# 查找所有音频文件
audio_files = []
for filename in os.listdir(decoded_dir):
if filename.endswith(('.mp3', '.wav')):
file_path = os.path.join(decoded_dir, filename)
if os.path.isfile(file_path):
# 提取文件名前缀(不含扩展名)作为prefix
prefix = os.path.splitext(filename)[0]
audio_files.append({
'name': filename,
'path': file_path,
'prefix': prefix
})
logger.info(f"成功列出目录下的音频文件: {decoded_dir}, 找到 {len(audio_files)} 个文件")
return JSONResponse(content={"success": True, "files": audio_files})
except Exception as e:
logger.error(f"列出音频文件失败: {str(e)}")
return JSONResponse(content={"success": False, "error": f"列出音频文件失败: {str(e)}"}, status_code=500)