格式化代码
This commit is contained in:
@@ -4,6 +4,7 @@ from functools import wraps
|
|||||||
# 创建认证蓝图
|
# 创建认证蓝图
|
||||||
auth_bp = Blueprint('auth', __name__)
|
auth_bp = Blueprint('auth', __name__)
|
||||||
|
|
||||||
|
|
||||||
# 登录检查装饰器
|
# 登录检查装饰器
|
||||||
def login_required(f):
|
def login_required(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
@@ -11,8 +12,10 @@ def login_required(f):
|
|||||||
if not session.get('logged_in'):
|
if not session.get('logged_in'):
|
||||||
return redirect(url_for('auth.login'))
|
return redirect(url_for('auth.login'))
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
|
|
||||||
# 登录页面
|
# 登录页面
|
||||||
@auth_bp.route('/login', methods=['GET', 'POST'])
|
@auth_bp.route('/login', methods=['GET', 'POST'])
|
||||||
def login():
|
def login():
|
||||||
@@ -20,20 +23,21 @@ def login():
|
|||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
username = request.form['username']
|
username = request.form['username']
|
||||||
password = request.form['password']
|
password = request.form['password']
|
||||||
|
|
||||||
# 从应用上下文获取服务器实例,而不是从蓝图对象
|
# 从应用上下文获取服务器实例,而不是从蓝图对象
|
||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
|
|
||||||
if username == server.username and password == server.password:
|
if username == server.username and password == server.password:
|
||||||
session['logged_in'] = True
|
session['logged_in'] = True
|
||||||
return redirect(url_for('main.index'))
|
return redirect(url_for('main.index'))
|
||||||
else:
|
else:
|
||||||
error = '用户名或密码错误'
|
error = '用户名或密码错误'
|
||||||
|
|
||||||
return render_template('login.html', error=error)
|
return render_template('login.html', error=error)
|
||||||
|
|
||||||
|
|
||||||
# 登出
|
# 登出
|
||||||
@auth_bp.route('/logout')
|
@auth_bp.route('/logout')
|
||||||
def logout():
|
def logout():
|
||||||
session.pop('logged_in', None)
|
session.pop('logged_in', None)
|
||||||
return redirect(url_for('auth.login'))
|
return redirect(url_for('auth.login'))
|
||||||
|
|||||||
@@ -7,15 +7,17 @@ from loguru import logger
|
|||||||
# 创建联系人管理蓝图
|
# 创建联系人管理蓝图
|
||||||
contacts_bp = Blueprint('contacts', __name__, url_prefix='/contacts')
|
contacts_bp = Blueprint('contacts', __name__, url_prefix='/contacts')
|
||||||
|
|
||||||
|
|
||||||
def send_message_in_thread(func, *args, **kwargs):
|
def send_message_in_thread(func, *args, **kwargs):
|
||||||
"""在独立线程中发送消息"""
|
"""在独立线程中发送消息"""
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
loop = None
|
loop = None
|
||||||
try:
|
try:
|
||||||
# 创建新的事件循环
|
# 创建新的事件循环
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
|
|
||||||
# 创建异步任务
|
# 创建异步任务
|
||||||
async def send():
|
async def send():
|
||||||
try:
|
try:
|
||||||
@@ -25,13 +27,13 @@ def send_message_in_thread(func, *args, **kwargs):
|
|||||||
finally:
|
finally:
|
||||||
# 发送完成后停止事件循环
|
# 发送完成后停止事件循环
|
||||||
loop.stop()
|
loop.stop()
|
||||||
|
|
||||||
# 创建并运行任务
|
# 创建并运行任务
|
||||||
asyncio.run_coroutine_threadsafe(send(), loop)
|
asyncio.run_coroutine_threadsafe(send(), loop)
|
||||||
|
|
||||||
# 运行事件循环直到停止
|
# 运行事件循环直到停止
|
||||||
loop.run_forever()
|
loop.run_forever()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"线程执行失败: {e}")
|
logger.error(f"线程执行失败: {e}")
|
||||||
finally:
|
finally:
|
||||||
@@ -42,23 +44,24 @@ def send_message_in_thread(func, *args, **kwargs):
|
|||||||
pending = asyncio.all_tasks(loop)
|
pending = asyncio.all_tasks(loop)
|
||||||
for task in pending:
|
for task in pending:
|
||||||
task.cancel()
|
task.cancel()
|
||||||
|
|
||||||
# 运行事件循环直到所有任务都被取消
|
# 运行事件循环直到所有任务都被取消
|
||||||
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
|
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
|
||||||
|
|
||||||
# 停止事件循环
|
# 停止事件循环
|
||||||
loop.stop()
|
loop.stop()
|
||||||
|
|
||||||
# 关闭事件循环
|
# 关闭事件循环
|
||||||
loop.close()
|
loop.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"清理资源失败: {e}")
|
logger.error(f"清理资源失败: {e}")
|
||||||
|
|
||||||
# 创建并启动线程
|
# 创建并启动线程
|
||||||
thread = threading.Thread(target=run)
|
thread = threading.Thread(target=run)
|
||||||
thread.daemon = True # 设置为守护线程,这样主程序退出时线程会自动结束
|
thread.daemon = True # 设置为守护线程,这样主程序退出时线程会自动结束
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
|
|
||||||
# 联系人管理页面
|
# 联系人管理页面
|
||||||
@contacts_bp.route('/')
|
@contacts_bp.route('/')
|
||||||
@login_required
|
@login_required
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ from loguru import logger
|
|||||||
|
|
||||||
file_browser_bp = Blueprint('file_browser', __name__)
|
file_browser_bp = Blueprint('file_browser', __name__)
|
||||||
|
|
||||||
|
|
||||||
@file_browser_bp.route('/file_browser')
|
@file_browser_bp.route('/file_browser')
|
||||||
def file_browser():
|
def file_browser():
|
||||||
"""文件浏览器页面"""
|
"""文件浏览器页面"""
|
||||||
return render_template('file_browser.html')
|
return render_template('file_browser.html')
|
||||||
|
|
||||||
|
|
||||||
@file_browser_bp.route('/api/list_files')
|
@file_browser_bp.route('/api/list_files')
|
||||||
def list_files():
|
def list_files():
|
||||||
"""获取指定目录下的文件列表"""
|
"""获取指定目录下的文件列表"""
|
||||||
@@ -18,14 +20,14 @@ def list_files():
|
|||||||
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||||
# 构建完整路径
|
# 构建完整路径
|
||||||
full_path = os.path.join(project_root, path)
|
full_path = os.path.join(project_root, path)
|
||||||
|
|
||||||
# 安全检查:确保路径在项目根目录内
|
# 安全检查:确保路径在项目根目录内
|
||||||
if not os.path.abspath(full_path).startswith(project_root):
|
if not os.path.abspath(full_path).startswith(project_root):
|
||||||
return jsonify({"success": False, "message": "访问被拒绝:路径超出项目范围"})
|
return jsonify({"success": False, "message": "访问被拒绝:路径超出项目范围"})
|
||||||
|
|
||||||
if not os.path.exists(full_path):
|
if not os.path.exists(full_path):
|
||||||
return jsonify({"success": False, "message": "目录不存在"})
|
return jsonify({"success": False, "message": "目录不存在"})
|
||||||
|
|
||||||
# 需要隐藏的目录列表
|
# 需要隐藏的目录列表
|
||||||
hidden_dirs = {
|
hidden_dirs = {
|
||||||
'__pycache__',
|
'__pycache__',
|
||||||
@@ -44,30 +46,30 @@ def list_files():
|
|||||||
'.eggs',
|
'.eggs',
|
||||||
'*.egg-info'
|
'*.egg-info'
|
||||||
}
|
}
|
||||||
|
|
||||||
items = []
|
items = []
|
||||||
for item in os.listdir(full_path):
|
for item in os.listdir(full_path):
|
||||||
# 跳过隐藏文件和目录
|
# 跳过隐藏文件和目录
|
||||||
if item.startswith('.'):
|
if item.startswith('.'):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
item_path = os.path.join(full_path, item)
|
item_path = os.path.join(full_path, item)
|
||||||
is_dir = os.path.isdir(item_path)
|
is_dir = os.path.isdir(item_path)
|
||||||
|
|
||||||
# 跳过隐藏目录
|
# 跳过隐藏目录
|
||||||
if is_dir and item in hidden_dirs:
|
if is_dir and item in hidden_dirs:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
items.append({
|
items.append({
|
||||||
"name": item,
|
"name": item,
|
||||||
"is_dir": is_dir,
|
"is_dir": is_dir,
|
||||||
"size": os.path.getsize(item_path) if not is_dir else 0,
|
"size": os.path.getsize(item_path) if not is_dir else 0,
|
||||||
"modified": os.path.getmtime(item_path)
|
"modified": os.path.getmtime(item_path)
|
||||||
})
|
})
|
||||||
|
|
||||||
# 对文件列表进行排序:目录在前,同类型按名称排序
|
# 对文件列表进行排序:目录在前,同类型按名称排序
|
||||||
items.sort(key=lambda x: (not x["is_dir"], x["name"].lower()))
|
items.sort(key=lambda x: (not x["is_dir"], x["name"].lower()))
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"data": {
|
"data": {
|
||||||
@@ -79,6 +81,7 @@ def list_files():
|
|||||||
logger.error(f"列出文件失败: {e}")
|
logger.error(f"列出文件失败: {e}")
|
||||||
return jsonify({"success": False, "message": str(e)})
|
return jsonify({"success": False, "message": str(e)})
|
||||||
|
|
||||||
|
|
||||||
@file_browser_bp.route('/api/download_file')
|
@file_browser_bp.route('/api/download_file')
|
||||||
def download_file():
|
def download_file():
|
||||||
"""下载指定文件"""
|
"""下载指定文件"""
|
||||||
@@ -88,17 +91,17 @@ def download_file():
|
|||||||
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||||
# 构建完整路径
|
# 构建完整路径
|
||||||
full_path = os.path.join(project_root, path)
|
full_path = os.path.join(project_root, path)
|
||||||
|
|
||||||
# 安全检查:确保路径在项目根目录内
|
# 安全检查:确保路径在项目根目录内
|
||||||
if not os.path.abspath(full_path).startswith(project_root):
|
if not os.path.abspath(full_path).startswith(project_root):
|
||||||
return jsonify({"success": False, "message": "访问被拒绝:路径超出项目范围"})
|
return jsonify({"success": False, "message": "访问被拒绝:路径超出项目范围"})
|
||||||
|
|
||||||
if not os.path.exists(full_path):
|
if not os.path.exists(full_path):
|
||||||
return jsonify({"success": False, "message": "文件不存在"})
|
return jsonify({"success": False, "message": "文件不存在"})
|
||||||
|
|
||||||
if os.path.isdir(full_path):
|
if os.path.isdir(full_path):
|
||||||
return jsonify({"success": False, "message": "不能下载目录"})
|
return jsonify({"success": False, "message": "不能下载目录"})
|
||||||
|
|
||||||
return send_file(
|
return send_file(
|
||||||
full_path,
|
full_path,
|
||||||
as_attachment=True,
|
as_attachment=True,
|
||||||
@@ -106,4 +109,4 @@ def download_file():
|
|||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"下载文件失败: {e}")
|
logger.error(f"下载文件失败: {e}")
|
||||||
return jsonify({"success": False, "message": str(e)})
|
return jsonify({"success": False, "message": str(e)})
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ from .auth import login_required
|
|||||||
# 创建主页蓝图
|
# 创建主页蓝图
|
||||||
main_bp = Blueprint('main', __name__)
|
main_bp = Blueprint('main', __name__)
|
||||||
|
|
||||||
|
|
||||||
@main_bp.route('/')
|
@main_bp.route('/')
|
||||||
@login_required
|
@login_required
|
||||||
def index():
|
def index():
|
||||||
return render_template('index.html')
|
return render_template('index.html')
|
||||||
|
|||||||
@@ -127,4 +127,4 @@ def get_hourly_message_trend():
|
|||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"获取按小时聊天趋势数据失败: {e}")
|
logger.error(f"获取按小时聊天趋势数据失败: {e}")
|
||||||
return jsonify({'success': False, 'error': str(e)}), 500
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ LOG = logger
|
|||||||
def robot_management():
|
def robot_management():
|
||||||
return render_template('plugins_manage.html')
|
return render_template('plugins_manage.html')
|
||||||
|
|
||||||
|
|
||||||
@plugin_routes.route('/api/plugins', methods=['GET'])
|
@plugin_routes.route('/api/plugins', methods=['GET'])
|
||||||
@login_required
|
@login_required
|
||||||
def get_plugins():
|
def get_plugins():
|
||||||
@@ -26,7 +27,7 @@ def get_plugins():
|
|||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
# 获取插件注册表
|
# 获取插件注册表
|
||||||
plugins = server.plugin_registry.get_all_plugins()
|
plugins = server.plugin_registry.get_all_plugins()
|
||||||
|
|
||||||
# 转换为前端需要的格式
|
# 转换为前端需要的格式
|
||||||
plugin_list = []
|
plugin_list = []
|
||||||
for name, plugin in plugins.items():
|
for name, plugin in plugins.items():
|
||||||
@@ -35,7 +36,7 @@ def get_plugins():
|
|||||||
module_name = plugin.__class__.__module__.split('.')[-2]
|
module_name = plugin.__class__.__module__.split('.')[-2]
|
||||||
except (IndexError, AttributeError):
|
except (IndexError, AttributeError):
|
||||||
module_name = "unknown"
|
module_name = "unknown"
|
||||||
|
|
||||||
plugin_info = {
|
plugin_info = {
|
||||||
"name": plugin.name,
|
"name": plugin.name,
|
||||||
"module_name": module_name,
|
"module_name": module_name,
|
||||||
@@ -45,12 +46,13 @@ def get_plugins():
|
|||||||
"status": plugin.status.name if hasattr(plugin, 'status') else 'UNKNOWN'
|
"status": plugin.status.name if hasattr(plugin, 'status') else 'UNKNOWN'
|
||||||
}
|
}
|
||||||
plugin_list.append(plugin_info)
|
plugin_list.append(plugin_info)
|
||||||
|
|
||||||
return jsonify({"success": True, "data": plugin_list})
|
return jsonify({"success": True, "data": plugin_list})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
LOG.error(f"获取插件列表失败: {str(e)}", exc_info=True)
|
LOG.error(f"获取插件列表失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"获取插件列表失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"获取插件列表失败: {str(e)}"})
|
||||||
|
|
||||||
|
|
||||||
@plugin_routes.route('/api/plugins/info', methods=['GET'])
|
@plugin_routes.route('/api/plugins/info', methods=['GET'])
|
||||||
@login_required
|
@login_required
|
||||||
def get_plugin_info():
|
def get_plugin_info():
|
||||||
@@ -60,19 +62,19 @@ def get_plugin_info():
|
|||||||
plugin_name = request.args.get('plugin_name')
|
plugin_name = request.args.get('plugin_name')
|
||||||
if not plugin_name:
|
if not plugin_name:
|
||||||
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
||||||
|
|
||||||
# 获取插件管理器
|
# 获取插件管理器
|
||||||
display_name, plugin = server.plugin_manager.find_plugin_by_name(plugin_name)
|
display_name, plugin = server.plugin_manager.find_plugin_by_name(plugin_name)
|
||||||
|
|
||||||
if not plugin:
|
if not plugin:
|
||||||
return jsonify({"success": False, "message": f"未找到插件: {plugin_name}"})
|
return jsonify({"success": False, "message": f"未找到插件: {plugin_name}"})
|
||||||
|
|
||||||
# 获取插件模块名
|
# 获取插件模块名
|
||||||
try:
|
try:
|
||||||
module_name = plugin.__class__.__module__.split('.')[-2]
|
module_name = plugin.__class__.__module__.split('.')[-2]
|
||||||
except (IndexError, AttributeError):
|
except (IndexError, AttributeError):
|
||||||
module_name = "unknown"
|
module_name = "unknown"
|
||||||
|
|
||||||
# 构建详细信息
|
# 构建详细信息
|
||||||
plugin_info = {
|
plugin_info = {
|
||||||
"name": plugin.name,
|
"name": plugin.name,
|
||||||
@@ -85,12 +87,13 @@ def get_plugin_info():
|
|||||||
"commands": getattr(plugin, 'commands', []),
|
"commands": getattr(plugin, 'commands', []),
|
||||||
"config": getattr(plugin, '_config', {})
|
"config": getattr(plugin, '_config', {})
|
||||||
}
|
}
|
||||||
|
|
||||||
return jsonify({"success": True, "data": plugin_info})
|
return jsonify({"success": True, "data": plugin_info})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
LOG.error(f"获取插件详情失败: {str(e)}", exc_info=True)
|
LOG.error(f"获取插件详情失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"获取插件详情失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"获取插件详情失败: {str(e)}"})
|
||||||
|
|
||||||
|
|
||||||
@plugin_routes.route('/api/plugins/enable', methods=['POST'])
|
@plugin_routes.route('/api/plugins/enable', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def enable_plugin():
|
def enable_plugin():
|
||||||
@@ -101,7 +104,7 @@ def enable_plugin():
|
|||||||
plugin_name = data.get('plugin_name')
|
plugin_name = data.get('plugin_name')
|
||||||
if not plugin_name:
|
if not plugin_name:
|
||||||
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
||||||
|
|
||||||
# 获取插件管理器
|
# 获取插件管理器
|
||||||
# 启用插件
|
# 启用插件
|
||||||
if server.plugin_manager.start_plugin(plugin_name):
|
if server.plugin_manager.start_plugin(plugin_name):
|
||||||
@@ -112,6 +115,7 @@ def enable_plugin():
|
|||||||
LOG.error(f"启用插件失败: {str(e)}", exc_info=True)
|
LOG.error(f"启用插件失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"启用插件失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"启用插件失败: {str(e)}"})
|
||||||
|
|
||||||
|
|
||||||
@plugin_routes.route('/api/plugins/disable', methods=['POST'])
|
@plugin_routes.route('/api/plugins/disable', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def disable_plugin():
|
def disable_plugin():
|
||||||
@@ -122,7 +126,7 @@ def disable_plugin():
|
|||||||
plugin_name = data.get('plugin_name')
|
plugin_name = data.get('plugin_name')
|
||||||
if not plugin_name:
|
if not plugin_name:
|
||||||
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
||||||
|
|
||||||
# 禁用插件
|
# 禁用插件
|
||||||
if server.plugin_manager.stop_plugin(plugin_name):
|
if server.plugin_manager.stop_plugin(plugin_name):
|
||||||
return jsonify({"success": True, "message": f"插件 {plugin_name} 禁用成功"})
|
return jsonify({"success": True, "message": f"插件 {plugin_name} 禁用成功"})
|
||||||
@@ -132,6 +136,7 @@ def disable_plugin():
|
|||||||
LOG.error(f"禁用插件失败: {str(e)}", exc_info=True)
|
LOG.error(f"禁用插件失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"禁用插件失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"禁用插件失败: {str(e)}"})
|
||||||
|
|
||||||
|
|
||||||
@plugin_routes.route('/api/plugins/reload', methods=['POST'])
|
@plugin_routes.route('/api/plugins/reload', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def reload_plugin():
|
def reload_plugin():
|
||||||
@@ -142,10 +147,10 @@ def reload_plugin():
|
|||||||
plugin_name = data.get('plugin_name')
|
plugin_name = data.get('plugin_name')
|
||||||
if not plugin_name:
|
if not plugin_name:
|
||||||
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
||||||
|
|
||||||
# 重载插件
|
# 重载插件
|
||||||
reloaded_plugin = server.plugin_manager.reload_plugin(plugin_name)
|
reloaded_plugin = server.plugin_manager.reload_plugin(plugin_name)
|
||||||
|
|
||||||
if reloaded_plugin:
|
if reloaded_plugin:
|
||||||
return jsonify({"success": True, "message": f"插件 {plugin_name} 重载成功"})
|
return jsonify({"success": True, "message": f"插件 {plugin_name} 重载成功"})
|
||||||
else:
|
else:
|
||||||
@@ -164,34 +169,34 @@ def get_raw_plugin_config():
|
|||||||
plugin_name = request.args.get('plugin_name')
|
plugin_name = request.args.get('plugin_name')
|
||||||
if not plugin_name:
|
if not plugin_name:
|
||||||
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
return jsonify({"success": False, "message": "缺少插件名称参数"})
|
||||||
|
|
||||||
# 获取插件管理器
|
# 获取插件管理器
|
||||||
|
|
||||||
# 查找插件
|
# 查找插件
|
||||||
display_name, plugin = server.plugin_manager.find_plugin_by_name(plugin_name)
|
display_name, plugin = server.plugin_manager.find_plugin_by_name(plugin_name)
|
||||||
|
|
||||||
if not plugin:
|
if not plugin:
|
||||||
return jsonify({"success": False, "message": f"未找到插件: {plugin_name}"})
|
return jsonify({"success": False, "message": f"未找到插件: {plugin_name}"})
|
||||||
|
|
||||||
# 获取配置文件路径
|
# 获取配置文件路径
|
||||||
config_path = plugin.get_config_path()
|
config_path = plugin.get_config_path()
|
||||||
|
|
||||||
if not os.path.exists(config_path):
|
if not os.path.exists(config_path):
|
||||||
return jsonify({"success": False, "message": f"配置文件不存在: {config_path}"})
|
return jsonify({"success": False, "message": f"配置文件不存在: {config_path}"})
|
||||||
|
|
||||||
# 读取配置文件内容
|
# 读取配置文件内容
|
||||||
with open(config_path, 'r', encoding='utf-8') as f:
|
with open(config_path, 'r', encoding='utf-8') as f:
|
||||||
config_text = f.read()
|
config_text = f.read()
|
||||||
|
|
||||||
# 确定配置文件格式
|
# 确定配置文件格式
|
||||||
format_type = 'toml'
|
format_type = 'toml'
|
||||||
if config_path.endswith('.json'):
|
if config_path.endswith('.json'):
|
||||||
format_type = 'json'
|
format_type = 'json'
|
||||||
elif config_path.endswith('.yaml') or config_path.endswith('.yml'):
|
elif config_path.endswith('.yaml') or config_path.endswith('.yml'):
|
||||||
format_type = 'yaml'
|
format_type = 'yaml'
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"data": config_text,
|
"data": config_text,
|
||||||
"format": format_type
|
"format": format_type
|
||||||
})
|
})
|
||||||
@@ -199,6 +204,7 @@ def get_raw_plugin_config():
|
|||||||
LOG.error(f"获取插件配置文件失败: {str(e)}", exc_info=True)
|
LOG.error(f"获取插件配置文件失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"获取配置文件失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"获取配置文件失败: {str(e)}"})
|
||||||
|
|
||||||
|
|
||||||
@plugin_routes.route('/api/plugins/config/update', methods=['POST'])
|
@plugin_routes.route('/api/plugins/config/update', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def update_plugin_config():
|
def update_plugin_config():
|
||||||
@@ -209,27 +215,27 @@ def update_plugin_config():
|
|||||||
plugin_name = data.get('plugin_name')
|
plugin_name = data.get('plugin_name')
|
||||||
config_text = data.get('config_text')
|
config_text = data.get('config_text')
|
||||||
format_type = data.get('format', 'toml')
|
format_type = data.get('format', 'toml')
|
||||||
|
|
||||||
if not plugin_name or config_text is None:
|
if not plugin_name or config_text is None:
|
||||||
return jsonify({"success": False, "message": "缺少必要参数"})
|
return jsonify({"success": False, "message": "缺少必要参数"})
|
||||||
|
|
||||||
# 查找插件
|
# 查找插件
|
||||||
# 获取插件管理器
|
# 获取插件管理器
|
||||||
display_name, plugin = server.plugin_manager.find_plugin_by_name(plugin_name)
|
display_name, plugin = server.plugin_manager.find_plugin_by_name(plugin_name)
|
||||||
|
|
||||||
if not plugin:
|
if not plugin:
|
||||||
return jsonify({"success": False, "message": f"未找到插件: {plugin_name}"})
|
return jsonify({"success": False, "message": f"未找到插件: {plugin_name}"})
|
||||||
|
|
||||||
# 获取配置文件路径
|
# 获取配置文件路径
|
||||||
config_path = plugin.get_config_path()
|
config_path = plugin.get_config_path()
|
||||||
|
|
||||||
# 确保配置目录存在
|
# 确保配置目录存在
|
||||||
os.makedirs(os.path.dirname(config_path), exist_ok=True)
|
os.makedirs(os.path.dirname(config_path), exist_ok=True)
|
||||||
|
|
||||||
# 写入配置文件
|
# 写入配置文件
|
||||||
with open(config_path, 'w', encoding='utf-8') as f:
|
with open(config_path, 'w', encoding='utf-8') as f:
|
||||||
f.write(config_text)
|
f.write(config_text)
|
||||||
|
|
||||||
# 解析配置并更新插件内部配置
|
# 解析配置并更新插件内部配置
|
||||||
try:
|
try:
|
||||||
if format_type == 'toml':
|
if format_type == 'toml':
|
||||||
@@ -238,15 +244,15 @@ def update_plugin_config():
|
|||||||
config_obj = json.loads(config_text)
|
config_obj = json.loads(config_text)
|
||||||
else:
|
else:
|
||||||
return jsonify({"success": False, "message": f"不支持的配置格式: {format_type}"})
|
return jsonify({"success": False, "message": f"不支持的配置格式: {format_type}"})
|
||||||
|
|
||||||
# 更新插件内部配置
|
# 更新插件内部配置
|
||||||
plugin._config = config_obj
|
plugin._config = config_obj
|
||||||
|
|
||||||
return jsonify({"success": True, "message": "配置已保存"})
|
return jsonify({"success": True, "message": "配置已保存"})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
LOG.error(f"解析配置失败: {str(e)}", exc_info=True)
|
LOG.error(f"解析配置失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"配置已保存,但解析失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"配置已保存,但解析失败: {str(e)}"})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
LOG.error(f"更新插件配置失败: {str(e)}", exc_info=True)
|
LOG.error(f"更新插件配置失败: {str(e)}", exc_info=True)
|
||||||
return jsonify({"success": False, "message": f"更新配置失败: {str(e)}"})
|
return jsonify({"success": False, "message": f"更新配置失败: {str(e)}"})
|
||||||
|
|||||||
@@ -7,27 +7,32 @@ from flask import current_app
|
|||||||
# 创建统计数据蓝图
|
# 创建统计数据蓝图
|
||||||
stats_bp = Blueprint('stats', __name__)
|
stats_bp = Blueprint('stats', __name__)
|
||||||
|
|
||||||
|
|
||||||
# 页面路由
|
# 页面路由
|
||||||
@stats_bp.route('/plugins')
|
@stats_bp.route('/plugins')
|
||||||
@login_required
|
@login_required
|
||||||
def plugins():
|
def plugins():
|
||||||
return render_template('plugins.html')
|
return render_template('plugins.html')
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/users')
|
@stats_bp.route('/users')
|
||||||
@login_required
|
@login_required
|
||||||
def users_page():
|
def users_page():
|
||||||
return render_template('users.html')
|
return render_template('users.html')
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/groups')
|
@stats_bp.route('/groups')
|
||||||
@login_required
|
@login_required
|
||||||
def groups():
|
def groups():
|
||||||
return render_template('groups.html')
|
return render_template('groups.html')
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/errors')
|
@stats_bp.route('/errors')
|
||||||
@login_required
|
@login_required
|
||||||
def errors():
|
def errors():
|
||||||
return render_template('errors.html')
|
return render_template('errors.html')
|
||||||
|
|
||||||
|
|
||||||
# API路由
|
# API路由
|
||||||
@stats_bp.route('/api/user_stats')
|
@stats_bp.route('/api/user_stats')
|
||||||
@login_required
|
@login_required
|
||||||
@@ -49,6 +54,7 @@ def api_user_stats():
|
|||||||
logger.error(f"获取用户统计失败: {e}")
|
logger.error(f"获取用户统计失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/api/group_stats')
|
@stats_bp.route('/api/group_stats')
|
||||||
@login_required
|
@login_required
|
||||||
def api_group_stats():
|
def api_group_stats():
|
||||||
@@ -69,6 +75,7 @@ def api_group_stats():
|
|||||||
logger.error(f"获取群组统计失败: {e}")
|
logger.error(f"获取群组统计失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/api/plugin_stats')
|
@stats_bp.route('/api/plugin_stats')
|
||||||
@login_required
|
@login_required
|
||||||
def api_plugin_stats():
|
def api_plugin_stats():
|
||||||
@@ -81,6 +88,7 @@ def api_plugin_stats():
|
|||||||
logger.error(f"获取插件统计失败: {e}")
|
logger.error(f"获取插件统计失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/api/error_logs')
|
@stats_bp.route('/api/error_logs')
|
||||||
@login_required
|
@login_required
|
||||||
def api_error_logs():
|
def api_error_logs():
|
||||||
@@ -94,6 +102,7 @@ def api_error_logs():
|
|||||||
logger.error(f"获取错误日志失败: {e}")
|
logger.error(f"获取错误日志失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/api/dashboard_summary')
|
@stats_bp.route('/api/dashboard_summary')
|
||||||
@login_required
|
@login_required
|
||||||
def api_dashboard_summary():
|
def api_dashboard_summary():
|
||||||
@@ -118,6 +127,7 @@ def api_dashboard_summary():
|
|||||||
logger.error(f"获取仪表盘摘要数据出错: {e}")
|
logger.error(f"获取仪表盘摘要数据出错: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/api/plugin_trend')
|
@stats_bp.route('/api/plugin_trend')
|
||||||
@login_required
|
@login_required
|
||||||
def api_plugin_trend():
|
def api_plugin_trend():
|
||||||
@@ -131,6 +141,7 @@ def api_plugin_trend():
|
|||||||
logger.error(f"获取插件趋势失败: {e}")
|
logger.error(f"获取插件趋势失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@stats_bp.route('/api/error_detail/<int:error_id>')
|
@stats_bp.route('/api/error_detail/<int:error_id>')
|
||||||
@login_required
|
@login_required
|
||||||
def api_error_detail(error_id):
|
def api_error_detail(error_id):
|
||||||
@@ -140,4 +151,4 @@ def api_error_detail(error_id):
|
|||||||
return jsonify({"success": True, "data": detail})
|
return jsonify({"success": True, "data": detail})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"获取错误详情失败: {e}")
|
logger.error(f"获取错误详情失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|||||||
@@ -13,20 +13,27 @@ system_bp = Blueprint('system', __name__)
|
|||||||
|
|
||||||
# 记录应用启动时间
|
# 记录应用启动时间
|
||||||
APP_START_TIME = time.time()
|
APP_START_TIME = time.time()
|
||||||
|
|
||||||
|
|
||||||
@system_bp.route('/api_docs')
|
@system_bp.route('/api_docs')
|
||||||
@login_required
|
@login_required
|
||||||
def api_docs():
|
def api_docs():
|
||||||
return render_template('api_docs.html')
|
return render_template('api_docs.html')
|
||||||
|
|
||||||
|
|
||||||
@system_bp.route('/system_status')
|
@system_bp.route('/system_status')
|
||||||
@login_required
|
@login_required
|
||||||
def system_status():
|
def system_status():
|
||||||
return render_template('system_status.html')
|
return render_template('system_status.html')
|
||||||
|
|
||||||
|
|
||||||
# 页面路由
|
# 页面路由
|
||||||
@system_bp.route('/wx_logs')
|
@system_bp.route('/wx_logs')
|
||||||
@login_required
|
@login_required
|
||||||
def wx_logs():
|
def wx_logs():
|
||||||
return render_template('wx_logs.html')
|
return render_template('wx_logs.html')
|
||||||
|
|
||||||
|
|
||||||
# API路由
|
# API路由
|
||||||
@system_bp.route('/api/system_info')
|
@system_bp.route('/api/system_info')
|
||||||
@login_required
|
@login_required
|
||||||
@@ -50,6 +57,7 @@ def api_system_info():
|
|||||||
logger.error(f"获取系统信息失败: {e}")
|
logger.error(f"获取系统信息失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
@system_bp.route('/api/wx_logs')
|
@system_bp.route('/api/wx_logs')
|
||||||
@login_required
|
@login_required
|
||||||
def api_wx_logs():
|
def api_wx_logs():
|
||||||
@@ -59,14 +67,14 @@ def api_wx_logs():
|
|||||||
|
|
||||||
# 修正日志文件路径计算,获取项目根目录
|
# 修正日志文件路径计算,获取项目根目录
|
||||||
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
|
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
|
||||||
|
|
||||||
if log_type == 'error':
|
if log_type == 'error':
|
||||||
log_file = os.path.join(project_root, 'wx_error.log')
|
log_file = os.path.join(project_root, 'wx_error.log')
|
||||||
elif log_type == 'debug':
|
elif log_type == 'debug':
|
||||||
log_file = os.path.join(project_root, 'wx_debug.log')
|
log_file = os.path.join(project_root, 'wx_debug.log')
|
||||||
else:
|
else:
|
||||||
log_file = os.path.join(project_root, 'wx_info.log')
|
log_file = os.path.join(project_root, 'wx_info.log')
|
||||||
|
|
||||||
# 读取日志文件
|
# 读取日志文件
|
||||||
log_content = []
|
log_content = []
|
||||||
if os.path.exists(log_file):
|
if os.path.exists(log_file):
|
||||||
@@ -95,6 +103,7 @@ def api_wx_logs():
|
|||||||
logger.error(f"获取微信日志失败: {e}")
|
logger.error(f"获取微信日志失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
# 在现有路由下添加
|
# 在现有路由下添加
|
||||||
@system_bp.route('/api/current_user_info', methods=['GET'])
|
@system_bp.route('/api/current_user_info', methods=['GET'])
|
||||||
@login_required
|
@login_required
|
||||||
|
|||||||
@@ -3,15 +3,16 @@ import uuid
|
|||||||
from flask import Blueprint, jsonify, request, current_app, render_template
|
from flask import Blueprint, jsonify, request, current_app, render_template
|
||||||
from .auth import login_required
|
from .auth import login_required
|
||||||
|
|
||||||
|
|
||||||
virtual_group_bp = Blueprint('virtual_group', __name__)
|
virtual_group_bp = Blueprint('virtual_group', __name__)
|
||||||
|
|
||||||
|
|
||||||
# 添加虚拟群组管理视图
|
# 添加虚拟群组管理视图
|
||||||
@virtual_group_bp.route('/')
|
@virtual_group_bp.route('/')
|
||||||
@login_required
|
@login_required
|
||||||
def virtual_group():
|
def virtual_group():
|
||||||
return render_template('virtual_group_management.html')
|
return render_template('virtual_group_management.html')
|
||||||
|
|
||||||
|
|
||||||
@virtual_group_bp.route('/api/virtual_groups', methods=['GET'])
|
@virtual_group_bp.route('/api/virtual_groups', methods=['GET'])
|
||||||
@login_required
|
@login_required
|
||||||
def get_virtual_groups():
|
def get_virtual_groups():
|
||||||
@@ -19,15 +20,15 @@ def get_virtual_groups():
|
|||||||
try:
|
try:
|
||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
redis_client = server.db_manager.get_redis_connection()
|
redis_client = server.db_manager.get_redis_connection()
|
||||||
|
|
||||||
# 从Redis获取虚拟群组数据
|
# 从Redis获取虚拟群组数据
|
||||||
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
||||||
if not chat_groups_json:
|
if not chat_groups_json:
|
||||||
return jsonify({"success": True, "data": {"chatGroups": []}})
|
return jsonify({"success": True, "data": {"chatGroups": []}})
|
||||||
|
|
||||||
import json
|
import json
|
||||||
chat_groups = json.loads(chat_groups_json)
|
chat_groups = json.loads(chat_groups_json)
|
||||||
|
|
||||||
# 确保群组名称是最新的
|
# 确保群组名称是最新的
|
||||||
for chat_group in chat_groups.get("chatGroups", []):
|
for chat_group in chat_groups.get("chatGroups", []):
|
||||||
for group in chat_group.get("groups", []):
|
for group in chat_group.get("groups", []):
|
||||||
@@ -36,7 +37,7 @@ def get_virtual_groups():
|
|||||||
group_name = server.contact_manager.get_nickname(group_id)
|
group_name = server.contact_manager.get_nickname(group_id)
|
||||||
if group_name:
|
if group_name:
|
||||||
group["name"] = group_name
|
group["name"] = group_name
|
||||||
|
|
||||||
return jsonify({"success": True, "data": chat_groups})
|
return jsonify({"success": True, "data": chat_groups})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"获取虚拟群组失败: {e}")
|
logger.error(f"获取虚拟群组失败: {e}")
|
||||||
@@ -51,11 +52,11 @@ def create_virtual_group():
|
|||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
redis_client = server.db_manager.get_redis_connection()
|
redis_client = server.db_manager.get_redis_connection()
|
||||||
data = request.json
|
data = request.json
|
||||||
|
|
||||||
group_name = data.get('name')
|
group_name = data.get('name')
|
||||||
if not group_name:
|
if not group_name:
|
||||||
return jsonify({"success": False, "error": "群组名称不能为空"}), 400
|
return jsonify({"success": False, "error": "群组名称不能为空"}), 400
|
||||||
|
|
||||||
# 从Redis获取现有虚拟群组
|
# 从Redis获取现有虚拟群组
|
||||||
import json
|
import json
|
||||||
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
||||||
@@ -63,21 +64,21 @@ def create_virtual_group():
|
|||||||
chat_groups = json.loads(chat_groups_json)
|
chat_groups = json.loads(chat_groups_json)
|
||||||
else:
|
else:
|
||||||
chat_groups = {"chatGroups": []}
|
chat_groups = {"chatGroups": []}
|
||||||
|
|
||||||
# 创建新的虚拟群组
|
# 创建新的虚拟群组
|
||||||
new_group = {
|
new_group = {
|
||||||
"id": str(uuid.uuid4()),
|
"id": str(uuid.uuid4()),
|
||||||
"name": group_name,
|
"name": group_name,
|
||||||
"groups": []
|
"groups": []
|
||||||
}
|
}
|
||||||
|
|
||||||
chat_groups["chatGroups"].append(new_group)
|
chat_groups["chatGroups"].append(new_group)
|
||||||
|
|
||||||
# 保存回Redis
|
# 保存回Redis
|
||||||
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": f"虚拟群组 {group_name} 创建成功",
|
"message": f"虚拟群组 {group_name} 创建成功",
|
||||||
"data": new_group
|
"data": new_group
|
||||||
})
|
})
|
||||||
@@ -93,15 +94,15 @@ def delete_virtual_group(group_id):
|
|||||||
try:
|
try:
|
||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
redis_client = server.db_manager.get_redis_connection()
|
redis_client = server.db_manager.get_redis_connection()
|
||||||
|
|
||||||
# 从Redis获取现有虚拟群组
|
# 从Redis获取现有虚拟群组
|
||||||
import json
|
import json
|
||||||
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
||||||
if not chat_groups_json:
|
if not chat_groups_json:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
chat_groups = json.loads(chat_groups_json)
|
chat_groups = json.loads(chat_groups_json)
|
||||||
|
|
||||||
# 查找并删除指定的虚拟群组
|
# 查找并删除指定的虚拟群组
|
||||||
found = False
|
found = False
|
||||||
for i, group in enumerate(chat_groups.get("chatGroups", [])):
|
for i, group in enumerate(chat_groups.get("chatGroups", [])):
|
||||||
@@ -109,15 +110,15 @@ def delete_virtual_group(group_id):
|
|||||||
del chat_groups["chatGroups"][i]
|
del chat_groups["chatGroups"][i]
|
||||||
found = True
|
found = True
|
||||||
break
|
break
|
||||||
|
|
||||||
if not found:
|
if not found:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
# 保存回Redis
|
# 保存回Redis
|
||||||
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": "虚拟群组删除成功"
|
"message": "虚拟群组删除成功"
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -133,24 +134,24 @@ def add_group_to_virtual(group_id):
|
|||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
redis_client = server.db_manager.get_redis_connection()
|
redis_client = server.db_manager.get_redis_connection()
|
||||||
data = request.json
|
data = request.json
|
||||||
|
|
||||||
wx_group_id = data.get('wx_group_id')
|
wx_group_id = data.get('wx_group_id')
|
||||||
if not wx_group_id:
|
if not wx_group_id:
|
||||||
return jsonify({"success": False, "error": "微信群ID不能为空"}), 400
|
return jsonify({"success": False, "error": "微信群ID不能为空"}), 400
|
||||||
|
|
||||||
# 检查微信群是否存在
|
# 检查微信群是否存在
|
||||||
group_name = server.contact_manager.get_nickname(wx_group_id)
|
group_name = server.contact_manager.get_nickname(wx_group_id)
|
||||||
if not group_name:
|
if not group_name:
|
||||||
return jsonify({"success": False, "error": "微信群不存在或未被机器人识别"}), 404
|
return jsonify({"success": False, "error": "微信群不存在或未被机器人识别"}), 404
|
||||||
|
|
||||||
# 从Redis获取现有虚拟群组
|
# 从Redis获取现有虚拟群组
|
||||||
import json
|
import json
|
||||||
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
||||||
if not chat_groups_json:
|
if not chat_groups_json:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
chat_groups = json.loads(chat_groups_json)
|
chat_groups = json.loads(chat_groups_json)
|
||||||
|
|
||||||
# 查找指定的虚拟群组
|
# 查找指定的虚拟群组
|
||||||
found = False
|
found = False
|
||||||
for chat_group in chat_groups.get("chatGroups", []):
|
for chat_group in chat_groups.get("chatGroups", []):
|
||||||
@@ -159,7 +160,7 @@ def add_group_to_virtual(group_id):
|
|||||||
for group in chat_group.get("groups", []):
|
for group in chat_group.get("groups", []):
|
||||||
if group.get("id") == wx_group_id:
|
if group.get("id") == wx_group_id:
|
||||||
return jsonify({"success": False, "error": "该微信群已在虚拟群组中"}), 400
|
return jsonify({"success": False, "error": "该微信群已在虚拟群组中"}), 400
|
||||||
|
|
||||||
# 添加微信群到虚拟群组
|
# 添加微信群到虚拟群组
|
||||||
chat_group["groups"].append({
|
chat_group["groups"].append({
|
||||||
"id": wx_group_id,
|
"id": wx_group_id,
|
||||||
@@ -167,15 +168,15 @@ def add_group_to_virtual(group_id):
|
|||||||
})
|
})
|
||||||
found = True
|
found = True
|
||||||
break
|
break
|
||||||
|
|
||||||
if not found:
|
if not found:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
# 保存回Redis
|
# 保存回Redis
|
||||||
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": f"微信群 {group_name} 已添加到虚拟群组",
|
"message": f"微信群 {group_name} 已添加到虚拟群组",
|
||||||
"data": {
|
"data": {
|
||||||
"id": wx_group_id,
|
"id": wx_group_id,
|
||||||
@@ -194,15 +195,15 @@ def remove_group_from_virtual(group_id, wx_group_id):
|
|||||||
try:
|
try:
|
||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
redis_client = server.db_manager.get_redis_connection()
|
redis_client = server.db_manager.get_redis_connection()
|
||||||
|
|
||||||
# 从Redis获取现有虚拟群组
|
# 从Redis获取现有虚拟群组
|
||||||
import json
|
import json
|
||||||
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
||||||
if not chat_groups_json:
|
if not chat_groups_json:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
chat_groups = json.loads(chat_groups_json)
|
chat_groups = json.loads(chat_groups_json)
|
||||||
|
|
||||||
# 查找指定的虚拟群组和微信群
|
# 查找指定的虚拟群组和微信群
|
||||||
found_group = False
|
found_group = False
|
||||||
found_wx_group = False
|
found_wx_group = False
|
||||||
@@ -215,18 +216,18 @@ def remove_group_from_virtual(group_id, wx_group_id):
|
|||||||
found_wx_group = True
|
found_wx_group = True
|
||||||
break
|
break
|
||||||
break
|
break
|
||||||
|
|
||||||
if not found_group:
|
if not found_group:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
if not found_wx_group:
|
if not found_wx_group:
|
||||||
return jsonify({"success": False, "error": "该微信群不在虚拟群组中"}), 404
|
return jsonify({"success": False, "error": "该微信群不在虚拟群组中"}), 404
|
||||||
|
|
||||||
# 保存回Redis
|
# 保存回Redis
|
||||||
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": "微信群已从虚拟群组移除"
|
"message": "微信群已从虚拟群组移除"
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -242,19 +243,19 @@ def update_virtual_group(group_id):
|
|||||||
server = current_app.dashboard_server
|
server = current_app.dashboard_server
|
||||||
redis_client = server.db_manager.get_redis_connection()
|
redis_client = server.db_manager.get_redis_connection()
|
||||||
data = request.json
|
data = request.json
|
||||||
|
|
||||||
group_name = data.get('name')
|
group_name = data.get('name')
|
||||||
if not group_name:
|
if not group_name:
|
||||||
return jsonify({"success": False, "error": "群组名称不能为空"}), 400
|
return jsonify({"success": False, "error": "群组名称不能为空"}), 400
|
||||||
|
|
||||||
# 从Redis获取现有虚拟群组
|
# 从Redis获取现有虚拟群组
|
||||||
import json
|
import json
|
||||||
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
chat_groups_json = redis_client.get("group_virtual:chat_groups")
|
||||||
if not chat_groups_json:
|
if not chat_groups_json:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
chat_groups = json.loads(chat_groups_json)
|
chat_groups = json.loads(chat_groups_json)
|
||||||
|
|
||||||
# 查找并更新指定的虚拟群组
|
# 查找并更新指定的虚拟群组
|
||||||
found = False
|
found = False
|
||||||
for chat_group in chat_groups.get("chatGroups", []):
|
for chat_group in chat_groups.get("chatGroups", []):
|
||||||
@@ -262,15 +263,15 @@ def update_virtual_group(group_id):
|
|||||||
chat_group["name"] = group_name
|
chat_group["name"] = group_name
|
||||||
found = True
|
found = True
|
||||||
break
|
break
|
||||||
|
|
||||||
if not found:
|
if not found:
|
||||||
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
return jsonify({"success": False, "error": "虚拟群组不存在"}), 404
|
||||||
|
|
||||||
# 保存回Redis
|
# 保存回Redis
|
||||||
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
redis_client.set("group_virtual:chat_groups", json.dumps(chat_groups, ensure_ascii=False))
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": "虚拟群组更新成功",
|
"message": "虚拟群组更新成功",
|
||||||
"data": {
|
"data": {
|
||||||
"id": group_id,
|
"id": group_id,
|
||||||
@@ -279,4 +280,4 @@ def update_virtual_group(group_id):
|
|||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"更新虚拟群组失败: {e}")
|
logger.error(f"更新虚拟群组失败: {e}")
|
||||||
return jsonify({"success": False, "error": str(e)}), 500
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|||||||
Reference in New Issue
Block a user