This commit is contained in:
mio 2025-04-17 16:49:38 +08:00
parent 2ec600f217
commit 3ad1080339
8 changed files with 70 additions and 44 deletions

View File

@ -18,7 +18,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ secrets.GH_TOKEN }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Read current version
id: read_version
@ -62,7 +62,7 @@ jobs:
if: steps.check_diff.outputs.version_changed == 'false'
uses: peter-evans/create-pull-request@v7
with:
token: ${{ secrets.GH_TOKEN }}
token: ${{ secrets.GITHUB_TOKEN }}
branch: create-pr/update_version
title: ":tada: chore(version): 自动更新版本到 ${{ steps.update_version.outputs.new_version }}"
body: "This PR updates the version file."

View File

@ -97,7 +97,8 @@ async def _handle_setting(
async def fix_db_schema():
"""修复数据库架构问题"""
from tortoise import connections
from tortoise.connection import connections
conn = connections.get("default")
# 检查是否存在superuser列并处理
try:
@ -150,14 +151,19 @@ async def _():
"is_show",
"ignore_prompt",
# 移除了 menu_type
# 确保 level, default_status, limit_superuser, cost_gold, impression, status, block_type 等用户配置不在此列表
# 确保 level, default_status, limit_superuser,
# cost_gold, impression, status, block_type 等用户配置不在此列表
]
)
# # 验证更新是否成功
# updated_plugin = await PluginInfo.get(id=plugin.id)
# if updated_plugin.menu_type != plugin.menu_type:
# logger.warning(f"插件 {plugin.name} 的menu_type更新失败: 期望值 '{plugin.menu_type}', 实际值 '{updated_plugin.menu_type}'")
# logger.warning(
# f"插件 {plugin.name} 的menu_type更新失败: "
# f"期望值 '{plugin.menu_type}', "
# f"实际值 '{updated_plugin.menu_type}'"
# )
# # 尝试单独更新menu_type
# updated_plugin.menu_type = plugin.menu_type
# await updated_plugin.save(update_fields=["menu_type"])

View File

@ -93,6 +93,8 @@ WsApiRouter.include_router(chat_routes)
async def _():
try:
_tasks = []
async def log_sink(message: str):
loop = None
if not loop:
@ -102,7 +104,10 @@ async def _():
logger.warning("Web Ui log_sink", e=e)
if not loop:
loop = asyncio.new_event_loop()
loop.create_task(LOG_STORAGE.add(message.rstrip("\n")))
task = loop.create_task(LOG_STORAGE.add(message.rstrip("\n")))
_tasks.append(task)
while _tasks and _tasks[0].done():
_tasks.pop(0)
logger_.add(
log_sink, colorize=True, filter=default_filter, format=default_format

View File

@ -9,13 +9,13 @@ from ....base_model import Result
from ....utils import authentication
from .data_source import ApiDataSource
from .model import (
BatchUpdatePlugins,
PluginCount,
PluginDetail,
PluginInfo,
PluginSwitch,
UpdatePlugin,
BatchUpdatePlugins,
RenameMenuTypePayload,
UpdatePlugin,
)
router = APIRouter(prefix="/plugin")
@ -165,7 +165,10 @@ async def batch_update_plugin_config_api(params: BatchUpdatePlugins):
# 这里我们返回包含错误详情的 200 OK让前端处理
# 或者可以抛出 HTTPException
# from fastapi import HTTPException
# raise HTTPException(status_code=400, detail={"message": "部分插件更新失败", "errors": result["errors"]})
# raise HTTPException(
# status_code=400,
# detail={"message": "部分插件更新失败", "errors": result["errors"]}
# )
pass # 暂时只返回结果字典
return result
@ -179,9 +182,14 @@ async def batch_update_plugin_config_api(params: BatchUpdatePlugins):
)
async def rename_menu_type_api(payload: RenameMenuTypePayload) -> Result:
try:
result = await ApiDataSource.rename_menu_type(old_name=payload.old_name, new_name=payload.new_name)
result = await ApiDataSource.rename_menu_type(
old_name=payload.old_name, new_name=payload.new_name)
if result.get("success"):
return Result.ok(info=result.get("info", f"成功将 {result.get('updated_count', 0)} 个插件的菜单类型从 '{payload.old_name}' 修改为 '{payload.new_name}'"))
return Result.ok(info=result.get(
"info",
f"成功将 {result.get('updated_count', 0)} 个插件的菜单类型"
f"'{payload.old_name}' 修改为 '{payload.new_name}'"
))
else:
# 这种情况理论上不会发生,因为 rename_menu_type 失败会抛异常
return Result.fail(info=result.get("info", "重命名失败"))

View File

@ -2,12 +2,12 @@ import re
import cattrs
from fastapi import Query
from tortoise.exceptions import DoesNotExist
from zhenxun.configs.config import Config
from zhenxun.configs.utils import ConfigGroup
from zhenxun.models.plugin_info import PluginInfo as DbPluginInfo
from zhenxun.utils.enum import BlockType, PluginType
from tortoise.exceptions import DoesNotExist
from .model import (
BatchUpdatePlugins,
@ -134,7 +134,7 @@ class ApiDataSource:
errors.append(
{
"module": item.module,
"error": f"Save block_type failed: {str(e_save)}",
"error": f"Save block_type failed: {e_save!s}",
}
)
plugin_changed_other = False
@ -158,7 +158,7 @@ class ApiDataSource:
errors.append(
{
"module": "batch_update_other",
"error": f"Bulk update failed: {str(e_bulk)}",
"error": f"Bulk update failed: {e_bulk!s}",
}
)
@ -217,7 +217,11 @@ class ApiDataSource:
if not old_name or not new_name:
raise ValueError("旧名称和新名称都不能为空")
if old_name == new_name:
return {"success": True, "updated_count": 0, "info": "新旧名称相同,无需更新"}
return {
"success": True,
"updated_count": 0,
"info": "新旧名称相同,无需更新"
}
# 检查新名称是否已存在(理论上前端会校验,后端再保险一次)
exists = await DbPluginInfo.filter(menu_type=new_name).exists()
@ -226,11 +230,12 @@ class ApiDataSource:
try:
# 使用 filter().update() 进行批量更新
updated_count = await DbPluginInfo.filter(menu_type=old_name).update(menu_type=new_name)
updated_count = await DbPluginInfo.filter(menu_type=old_name).update(
menu_type=new_name)
return {"success": True, "updated_count": updated_count}
except Exception as e:
# 可以添加更详细的日志记录
raise RuntimeError(f"数据库更新菜单类型失败: {str(e)}")
raise RuntimeError(f"数据库更新菜单类型失败: {e!s}")
@classmethod
async def get_plugin_detail(cls, module: str) -> PluginDetail:

View File

@ -113,11 +113,13 @@ class BatchUpdatePluginItem(BaseModel):
module: str = Field(..., description="插件模块名")
default_status: bool | None = Field(None, description="默认状态(开关)")
menu_type: str | None = Field(None, description="菜单类型")
block_type: BlockType | None = Field(None, description="插件禁用状态 (None: 启用, ALL: 禁用)")
block_type: BlockType | None = Field(
None, description="插件禁用状态 (None: 启用, ALL: 禁用)")
class BatchUpdatePlugins(BaseModel):
updates: list[BatchUpdatePluginItem] = Field(..., description="要批量更新的插件列表")
updates: list[BatchUpdatePluginItem] = Field(
..., description="要批量更新的插件列表")
class PluginDetail(PluginInfo):

View File

@ -530,7 +530,7 @@ class ConfigsManager:
# 原子替换
temp_file.replace(path)
except Exception as e:
logger.error(f"保存配置文件失败: {str(e)}")
logger.error(f"保存配置文件失败: {e!s}")
def reload(self):
"""重新加载配置文件"""
@ -554,10 +554,10 @@ class ConfigsManager:
self.save()
except ScannerError as e:
logger.error(f"配置文件解析失败: {str(e)},保留现有配置")
logger.error(f"配置文件解析失败: {e!s},保留现有配置")
self._data = backup_data
except Exception as e:
logger.error(f"重新加载配置失败: {str(e)}")
logger.error(f"重新加载配置失败: {e!s}")
# 发生错误时恢复到备份配置
self._data = backup_data