Skip to content

Commit

Permalink
重构webui适配 (#1801)
Browse files Browse the repository at this point in the history
* ♻️ 使用Uninfo重构PlatformUtils基础方法

* 🩹 优化插件加载与模块格式转换逻辑

* 🚑 修复商店道具无法使用

* 🚑 修复道具无法正常使用

* 🔧 增加Bot状态管理及模块禁用功能

* 🎨  优化Web UI代码结构,修改target方法

* 🚨 auto fix by pre-commit hooks

* 🎨 添加菜单API及优化异常处理

* 🐛 优化菜单API及模型结构,修复WebUi插件列表Api

* 📝 更新仓库readme

* 🚨 add mdlint file

* 📝 Add help chapter.

* 🐛 修复优化AuthChecker逻辑

* 🐛 优化数据库API,移除冗余导入及修正SQL_DICT引用

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: BalconyJH <balconyjh@gmail.com>
  • Loading branch information
3 people authored Dec 25, 2024
1 parent ebf05fd commit 35014e4
Show file tree
Hide file tree
Showing 32 changed files with 1,950 additions and 1,765 deletions.
4 changes: 4 additions & 0 deletions .markdownlint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
MD013: false
MD024: # 重复标题
siblings_only: true
MD033: false # 允许 html
854 changes: 216 additions & 638 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion resources/template/check/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ body {
}

.main {
height: 448px;
height: 444px;
width: 335px;
padding: 0 30px;
position: relative;
Expand Down
8 changes: 0 additions & 8 deletions zhenxun/builtin_plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,12 @@
import uuid

import nonebot
from nonebot import require
from nonebot.adapters import Bot
from nonebot.drivers import Driver
from tortoise import Tortoise
from tortoise.exceptions import OperationalError
import ujson as json

require("nonebot_plugin_apscheduler")
require("nonebot_plugin_alconna")
require("nonebot_plugin_session")
require("nonebot_plugin_userinfo")
require("nonebot_plugin_htmlrender")
# require("nonebot_plugin_uninfo")

from zhenxun.models.bot_connect_log import BotConnectLog
from zhenxun.models.bot_console import BotConsole
from zhenxun.models.goods_info import GoodsInfo
Expand Down
4 changes: 2 additions & 2 deletions zhenxun/builtin_plugins/hooks/_auth_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ async def auth_plugin(
session=session,
)
raise IgnoredException("该群未开启此功能...")
if not plugin.status and plugin.block_type == BlockType.GROUP:
if plugin.block_type == BlockType.GROUP:
"""全局群组禁用"""
try:
if self.is_send_limit_message(plugin, sid) and not is_poke:
Expand All @@ -410,7 +410,7 @@ async def auth_plugin(
raise IgnoredException("该插件在群组中已被禁用...")
else:
sid = user_id
if not plugin.status and plugin.block_type == BlockType.PRIVATE:
if plugin.block_type == BlockType.PRIVATE:
"""全局私聊禁用"""
try:
if self.is_send_limit_message(plugin, sid) and not is_poke:
Expand Down
6 changes: 3 additions & 3 deletions zhenxun/builtin_plugins/init/init_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ async def _():
if module_list := await PluginInfo.all().values("id", "module_path"):
module2id = {m["module_path"]: m["id"] for m in module_list}
for plugin in get_loaded_plugins():
load_plugin.append(plugin.name)
load_plugin.append(plugin.module_name)
await _handle_setting(plugin, plugin_list, limit_list, task_list)
create_list = []
update_list = []
Expand Down Expand Up @@ -198,8 +198,8 @@ async def _():
10,
)
await data_migration()
await PluginInfo.filter(module__in=load_plugin).update(load_status=True)
await PluginInfo.filter(module__not_in=load_plugin).update(load_status=False)
await PluginInfo.filter(module_path__in=load_plugin).update(load_status=True)
await PluginInfo.filter(module_path__not_in=load_plugin).update(load_status=False)
manager.init()
if limit_list:
for limit in limit_list:
Expand Down
2 changes: 1 addition & 1 deletion zhenxun/builtin_plugins/restart/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ async def _(bot: Bot):
async with aiofiles.open(RESTART_MARK, encoding="utf8") as f:
bot_id, user_id = (await f.read()).split()
if bot := nonebot.get_bot(bot_id):
if target := PlatformUtils.get_target(bot, user_id):
if target := PlatformUtils.get_target(user_id=user_id):
await MessageUtils.build_message(
f"{BotConfig.self_nickname}已成功重启!"
).send(target, bot=bot)
Expand Down
3 changes: 1 addition & 2 deletions zhenxun/builtin_plugins/scheduler/chat_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ async def _():
update_list = []
if modules := await TaskInfo.annotate().values_list("module", flat=True):
for bot in nonebot.get_bots().values():
group_list, _ = await PlatformUtils.get_group_list(bot)
group_list = [g for g in group_list if g.channel_id is None]
group_list, _ = await PlatformUtils.get_group_list(bot, True)
for group in group_list:
try:
last_message = (
Expand Down
4 changes: 3 additions & 1 deletion zhenxun/builtin_plugins/shop/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ async def _(session: Uninfo, arparma: Arparma):
async def _(session: Uninfo, arparma: Arparma, nickname: str = UserName()):
logger.info("查看道具", arparma.header_result, session=session)
if image := await ShopManage.my_props(
session.user.id, nickname, PlatformUtils.get_platform(session)
session.user.id,
nickname,
PlatformUtils.get_platform(session),
):
await MessageUtils.build_message(image.pic2bytes()).finish(reply_to=True)
return await MessageUtils.build_message("你的道具为空捏...").send(reply_to=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ async def send(
group.group_id,
):
target = PlatformUtils.get_target(
bot, None, group.channel_id or group.group_id
group_id=group.group_id, channel_id=group.channel_id
)
if target:
await MessageUtils.build_message(message_list).send(
Expand Down
6 changes: 4 additions & 2 deletions zhenxun/builtin_plugins/web_ui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from .api.logs import router as ws_log_routes
from .api.logs.log_manager import LOG_STORAGE
from .api.menu import router as menu_router
from .api.tabs.dashboard import router as dashboard_router
from .api.tabs.database import router as database_router
from .api.tabs.main import router as main_router
Expand Down Expand Up @@ -80,6 +81,7 @@
BaseApiRouter.include_router(database_router)
BaseApiRouter.include_router(plugin_router)
BaseApiRouter.include_router(system_router)
BaseApiRouter.include_router(menu_router)


WsApiRouter = APIRouter(prefix="/zhenxun/socket")
Expand Down Expand Up @@ -112,6 +114,6 @@ async def log_sink(message: str):
app.include_router(BaseApiRouter)
app.include_router(WsApiRouter)
await init_public(app)
logger.info("<g>API启动成功</g>", "Web UI")
logger.info("<g>API启动成功</g>", "WebUi")
except Exception as e:
logger.error("<g>API启动失败</g>", "Web UI", e=e)
logger.error("<g>API启动失败</g>", "WebUi", e=e)
3 changes: 2 additions & 1 deletion zhenxun/builtin_plugins/web_ui/api/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .tabs import * # noqa: F403
from .menu import * # noqa: F403f
from .tabs import * # noqa: F403f
26 changes: 26 additions & 0 deletions zhenxun/builtin_plugins/web_ui/api/menu/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from fastapi import APIRouter
from fastapi.responses import JSONResponse

from zhenxun.services.log import logger

from ...base_model import Result
from ...utils import authentication
from .data_source import menu_manage
from .model import MenuData

router = APIRouter(prefix="/menu")


@router.get(
"/get_menus",
dependencies=[authentication()],
response_model=Result[list[MenuData]],
response_class=JSONResponse,
deprecated="获取菜单列表", # type: ignore
)
async def _() -> Result[list[MenuData]]:
try:
return Result.ok(menu_manage.get_menus(), "拿到菜单了哦!")
except Exception as e:
logger.error(f"{router.prefix}/get_menus 调用错误", "WebUi", e=e)
return Result.fail(f"发生了一点错误捏 {type(e)}: {e}")
64 changes: 64 additions & 0 deletions zhenxun/builtin_plugins/web_ui/api/menu/data_source.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import ujson as json

from zhenxun.configs.path_config import DATA_PATH
from zhenxun.services.log import logger

from .model import MenuData, MenuItem


class MenuManage:
def __init__(self) -> None:
self.file = DATA_PATH / "web_ui" / "menu.json"
self.menu = []
if self.file.exists():
try:
self.menu = json.load(self.file.open(encoding="utf8"))
except Exception as e:
logger.warning("菜单文件损坏,已重新生成...", "WebUi", e=e)
if not self.menu:
self.menu = [
MenuItem(
name="仪表盘",
module="dashboard",
router="/dashboard",
icon="dashboard",
default=True,
),
MenuItem(
name="真寻控制台",
module="command",
router="/command",
icon="command",
),
MenuItem(
name="插件列表", module="plugin", router="/plugin", icon="plugin"
),
MenuItem(
name="插件商店", module="store", router="/store", icon="store"
),
MenuItem(
name="好友/群组", module="manage", router="/manage", icon="user"
),
MenuItem(
name="数据库管理",
module="database",
router="/database",
icon="database",
),
MenuItem(
name="系统信息", module="system", router="/system", icon="system"
),
]
self.save()

def get_menus(self):
return MenuData(menus=self.menu)

def save(self):
self.file.parent.mkdir(parents=True, exist_ok=True)
temp = [menu.dict() for menu in self.menu]
with self.file.open("w", encoding="utf8") as f:
json.dump(temp, f, ensure_ascii=False, indent=4)


menu_manage = MenuManage()
21 changes: 21 additions & 0 deletions zhenxun/builtin_plugins/web_ui/api/menu/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from pydantic import BaseModel


class MenuItem(BaseModel):
module: str
"""模块名称"""
name: str
"""菜单名称"""
router: str
"""路由"""
icon: str
"""图标"""
default: bool = False
"""默认选中"""


class MenuData(BaseModel):
bot_type: str = "zhenxun"
"""bot类型"""
menus: list[MenuItem]
"""菜单列表"""
Loading

0 comments on commit 35014e4

Please sign in to comment.