mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-22 15:13:55 +08:00
增加设备私有配置,每台设备可以配置不同的模型和提示词
增加后台管理功能,可以通过后台调整设备私有配置信息
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
import os
|
||||
import yaml
|
||||
import logging
|
||||
from aiohttp import web
|
||||
from typing import Dict, Any
|
||||
from core.utils.util import get_project_dir
|
||||
from config.private_config import PrivateConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class ConfigHandler:
|
||||
def __init__(self):
|
||||
self.private_config_path = get_project_dir() + '.private_config.yaml'
|
||||
self.config_path = get_project_dir() + 'config.yaml'
|
||||
# 如果存在.config.yaml文件,则使用该文件
|
||||
if os.path.exists(get_project_dir() + ".config.yaml"):
|
||||
self.config_path = get_project_dir() + ".config.yaml"
|
||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||
self.config = yaml.safe_load(f)
|
||||
|
||||
async def get_module_options(self, request):
|
||||
"""Get all available module options from config.yaml"""
|
||||
try:
|
||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||
config = yaml.safe_load(f)
|
||||
|
||||
# Extract available modules
|
||||
modules = {
|
||||
'LLM': list(config.get('LLM', {}).keys()),
|
||||
'TTS': list(config.get('TTS', {}).keys()),
|
||||
'VAD': list(config.get('VAD', {}).keys()),
|
||||
'ASR': list(config.get('ASR', {}).keys())
|
||||
}
|
||||
|
||||
return web.json_response({
|
||||
'success': True,
|
||||
'data': modules,
|
||||
'message': '获取成功'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting module options: {str(e)}", exc_info=True)
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '获取配置选项失败'
|
||||
})
|
||||
|
||||
async def get_private_configs(self, request):
|
||||
"""获取所有私有配置设备列表及其配置"""
|
||||
try:
|
||||
if os.path.exists(self.private_config_path):
|
||||
with open(self.private_config_path, 'r', encoding='utf-8') as f:
|
||||
all_configs = yaml.safe_load(f) or {}
|
||||
else:
|
||||
all_configs = {}
|
||||
|
||||
# 转换配置为前端友好的格式
|
||||
devices = []
|
||||
for device_id, config in all_configs.items():
|
||||
device_info = {
|
||||
'id': device_id,
|
||||
'config': {
|
||||
'selected_module': config.get('selected_module', {}),
|
||||
'prompt': config.get('prompt', ''),
|
||||
'last_chat_time': config.get('last_chat_time', ''),
|
||||
'nickname': config.get('nickname', '小智'),
|
||||
'modules': {
|
||||
'LLM': config.get('LLM', {}),
|
||||
'TTS': config.get('TTS', {}),
|
||||
'ASR': config.get('ASR', {}),
|
||||
'VAD': config.get('VAD', {})
|
||||
}
|
||||
}
|
||||
}
|
||||
devices.append(device_info)
|
||||
|
||||
return web.json_response({
|
||||
'success': True,
|
||||
'data': devices,
|
||||
'message': '获取成功'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting private configs: {str(e)}", exc_info=True)
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '获取配置失败'
|
||||
})
|
||||
|
||||
async def save_device_config(self, request):
|
||||
"""保存单个设备的配置"""
|
||||
try:
|
||||
data = await request.json()
|
||||
device_id = data.get('id')
|
||||
config = data.get('config')
|
||||
logger.info(f"Device config updated: {device_id} :\n{config}")
|
||||
if not device_id or not config:
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '设备ID和配置不能为空'
|
||||
})
|
||||
|
||||
# 使用PrivateConfig处理配置保存
|
||||
private_config = PrivateConfig(device_id, self.config)
|
||||
await private_config.load_or_create()
|
||||
|
||||
success = await private_config.update_config(
|
||||
config.get('selected_module'),
|
||||
config.get('prompt'),
|
||||
config.get('nickname', '小智')
|
||||
)
|
||||
|
||||
|
||||
if not success:
|
||||
raise Exception("Failed to update device config")
|
||||
|
||||
return web.json_response({
|
||||
'success': True,
|
||||
'message': '保存成功'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving device config: {str(e)}", exc_info=True)
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': f'保存配置失败: {str(e)}'
|
||||
})
|
||||
|
||||
async def delete_device_config(self, request):
|
||||
"""删除设备配置"""
|
||||
try:
|
||||
data = await request.json()
|
||||
device_id = data.get('device_id')
|
||||
|
||||
# 使用PrivateConfig处理配置删除
|
||||
private_config = PrivateConfig(device_id, self.config)
|
||||
success = await private_config.delete_config()
|
||||
|
||||
if not success:
|
||||
raise Exception("Failed to delete device config")
|
||||
|
||||
return web.json_response({
|
||||
'success': True,
|
||||
'message': '删除成功'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting device config: {str(e)}", exc_info=True)
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': f'删除配置失败: {str(e)}'
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import logging
|
||||
from aiohttp import web
|
||||
import datetime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class LoginHandler:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
async def handle_login(self, request):
|
||||
"""处理登录请求"""
|
||||
try:
|
||||
data = await request.json()
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
if not username or not password:
|
||||
logger.warning(f"Login attempt with empty credentials from {request.remote}")
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '用户名和密码不能为空'
|
||||
})
|
||||
|
||||
stored_user = self.config['get_user'](username)
|
||||
if not stored_user or stored_user['password'] != self.config['hash_password'](password):
|
||||
logger.warning(f"Failed login attempt for user {username} from {request.remote}")
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '用户名或密码错误'
|
||||
})
|
||||
|
||||
# 更新最后登录时间
|
||||
self.config['update_user'](username, {
|
||||
'last_login': datetime.datetime.now().isoformat()
|
||||
})
|
||||
|
||||
logger.info(f"Successful login for user {username} from {request.remote}")
|
||||
return web.json_response({
|
||||
'success': True,
|
||||
'message': '登录成功'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Login error: {str(e)}", exc_info=True)
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '登录失败,请稍后重试'
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import logging
|
||||
from aiohttp import web
|
||||
import datetime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class RegisterHandler:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
async def handle_register(self, request):
|
||||
"""处理注册请求"""
|
||||
try:
|
||||
data = await request.json()
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
if not username or not password:
|
||||
logger.warning(f"Registration attempt with empty credentials from {request.remote}")
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '用户名和密码不能为空'
|
||||
})
|
||||
|
||||
users = self.config.get('users', {})
|
||||
if username in users:
|
||||
logger.warning(f"Registration attempt with existing username {username} from {request.remote}")
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '用户名已存在'
|
||||
})
|
||||
|
||||
# 存储新用户
|
||||
self.config['users'][username] = {
|
||||
'password': self.config['hash_password'](password),
|
||||
'created_at': datetime.datetime.now().isoformat()
|
||||
}
|
||||
self.config['save_user_data']()
|
||||
|
||||
logger.info(f"Successfully registered new user {username} from {request.remote}")
|
||||
return web.json_response({
|
||||
'success': True,
|
||||
'message': '注册成功'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Registration error: {str(e)}", exc_info=True)
|
||||
return web.json_response({
|
||||
'success': False,
|
||||
'message': '注册失败,请稍后重试'
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,27 @@
|
||||
<!doctype html>
|
||||
<html lang="en" style="height: 100%;">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>智控台</title>
|
||||
<style>
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
#app {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
<script type="module" crossorigin src="/assets/index-xClKUcGO.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-B6rJ-92F.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
import yaml
|
||||
import hashlib
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class UserManager:
|
||||
def __init__(self):
|
||||
self.secrets_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.secrets.yaml')
|
||||
self.users = {}
|
||||
self.ensure_secrets_file()
|
||||
self.load_user_data()
|
||||
|
||||
def ensure_secrets_file(self):
|
||||
"""确保 .secrets.yaml 文件存在"""
|
||||
if not os.path.exists(self.secrets_path):
|
||||
default_config = {
|
||||
'users': {}
|
||||
}
|
||||
try:
|
||||
with open(self.secrets_path, 'w', encoding='utf-8') as f:
|
||||
yaml.dump(default_config, f)
|
||||
os.chmod(self.secrets_path, 0o600)
|
||||
logger.info("Created new .secrets.yaml file")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create .secrets.yaml: {e}")
|
||||
raise
|
||||
|
||||
def load_user_data(self):
|
||||
"""加载用户数据"""
|
||||
try:
|
||||
with open(self.secrets_path, 'r', encoding='utf-8') as f:
|
||||
data = yaml.safe_load(f) or {'users': {}}
|
||||
self.users = data['users']
|
||||
logger.info("Successfully loaded user data")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load user data: {e}")
|
||||
self.users = {}
|
||||
|
||||
def save_user_data(self):
|
||||
"""保存用户数据"""
|
||||
try:
|
||||
with open(self.secrets_path, 'w', encoding='utf-8') as f:
|
||||
yaml.dump({'users': self.users}, f)
|
||||
logger.info("Successfully saved user data")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save user data: {e}")
|
||||
raise
|
||||
|
||||
def hash_password(self, password):
|
||||
"""密码哈希"""
|
||||
return hashlib.sha256(password.encode()).hexdigest()
|
||||
|
||||
def get_users(self):
|
||||
"""获取所有用户"""
|
||||
return self.users
|
||||
|
||||
def get_user(self, username):
|
||||
"""获取指定用户"""
|
||||
return self.users.get(username)
|
||||
|
||||
def update_user(self, username, data):
|
||||
"""更新用户数据"""
|
||||
if username in self.users:
|
||||
self.users[username].update(data)
|
||||
self.save_user_data()
|
||||
Reference in New Issue
Block a user