mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-06 04:10:02 +08:00
update v0.1.5.0
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
from .group import *
|
||||
from .plugins import *
|
||||
from .request import *
|
||||
from .system import *
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
import ujson as json
|
||||
from configs.path_config import (
|
||||
DATA_PATH,
|
||||
FONT_PATH,
|
||||
IMAGE_PATH,
|
||||
LOG_PATH,
|
||||
RECORD_PATH,
|
||||
TEMP_PATH,
|
||||
TEXT_PATH,
|
||||
)
|
||||
from services.log import logger
|
||||
from utils.http_utils import AsyncHttpx
|
||||
|
||||
from ..auth import Depends, User, token_to_user
|
||||
from ..config import *
|
||||
|
||||
CPU_DATA_PATH = DATA_PATH / "system" / "cpu.json"
|
||||
MEMORY_DATA_PATH = DATA_PATH / "system" / "memory.json"
|
||||
DISK_DATA_PATH = DATA_PATH / "system" / "disk.json"
|
||||
CPU_DATA_PATH.parent.mkdir(exist_ok=True, parents=True)
|
||||
cpu_data = {"data": []}
|
||||
memory_data = {"data": []}
|
||||
disk_data = {"data": []}
|
||||
|
||||
|
||||
@app.get("/webui/system")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
return await get_system_data()
|
||||
|
||||
|
||||
@app.get("/webui/system/status")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
return Result(
|
||||
code=200,
|
||||
data=await asyncio.get_event_loop().run_in_executor(None, _get_system_status),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/webui/system/disk")
|
||||
async def _(type_: Optional[str] = None, user: User = Depends(token_to_user)) -> Result:
|
||||
return Result(
|
||||
code=200,
|
||||
data=await asyncio.get_event_loop().run_in_executor(
|
||||
None, _get_system_disk, type_
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/webui/system/statusList")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
global cpu_data, memory_data, disk_data
|
||||
await asyncio.get_event_loop().run_in_executor(None, _get_system_status)
|
||||
cpu_rst = cpu_data["data"][-10:] if len(cpu_data["data"]) > 10 else cpu_data["data"]
|
||||
memory_rst = (
|
||||
memory_data["data"][-10:]
|
||||
if len(memory_data["data"]) > 10
|
||||
else memory_data["data"]
|
||||
)
|
||||
disk_rst = (
|
||||
disk_data["data"][-10:] if len(disk_data["data"]) > 10 else disk_data["data"]
|
||||
)
|
||||
return Result(
|
||||
code=200,
|
||||
data=SystemStatusList(
|
||||
cpu_data=cpu_rst,
|
||||
memory_data=memory_rst,
|
||||
disk_data=disk_rst,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def get_system_data():
|
||||
"""
|
||||
说明:
|
||||
获取系统信息,资源文件大小,网络状态等
|
||||
"""
|
||||
baidu = 200
|
||||
google = 200
|
||||
try:
|
||||
await AsyncHttpx.get("https://www.baidu.com/", timeout=5)
|
||||
except Exception as e:
|
||||
logger.warning(f"访问BaiDu失败... {type(e)}: {e}")
|
||||
baidu = 404
|
||||
try:
|
||||
await AsyncHttpx.get("https://www.google.com/", timeout=5)
|
||||
except Exception as e:
|
||||
logger.warning(f"访问Google失败... {type(e)}: {e}")
|
||||
google = 404
|
||||
network = SystemNetwork(baidu=baidu, google=google)
|
||||
disk = await asyncio.get_event_loop().run_in_executor(None, _get_system_disk)
|
||||
status = await asyncio.get_event_loop().run_in_executor(None, _get_system_status)
|
||||
return Result(
|
||||
code=200,
|
||||
data=SystemResult(
|
||||
status=status,
|
||||
network=network,
|
||||
disk=disk,
|
||||
check_time=datetime.now().replace(microsecond=0),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _get_system_status() -> SystemStatus:
|
||||
"""
|
||||
说明:
|
||||
获取系统信息等
|
||||
"""
|
||||
cpu = psutil.cpu_percent()
|
||||
memory = psutil.virtual_memory().percent
|
||||
disk = psutil.disk_usage("/").percent
|
||||
save_system_data(cpu, memory, disk)
|
||||
return SystemStatus(
|
||||
cpu=cpu,
|
||||
memory=memory,
|
||||
disk=disk,
|
||||
check_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
|
||||
|
||||
def _get_system_disk(
|
||||
type_: Optional[str],
|
||||
) -> Union[SystemFolderSize, Dict[str, Union[float, datetime]]]:
|
||||
"""
|
||||
说明:
|
||||
获取资源文件大小等
|
||||
"""
|
||||
if not type_:
|
||||
disk = SystemFolderSize(
|
||||
font_dir_size=_get_dir_size(FONT_PATH) / 1024 / 1024,
|
||||
image_dir_size=_get_dir_size(IMAGE_PATH) / 1024 / 1024,
|
||||
text_dir_size=_get_dir_size(TEXT_PATH) / 1024 / 1024,
|
||||
record_dir_size=_get_dir_size(RECORD_PATH) / 1024 / 1024,
|
||||
temp_dir_size=_get_dir_size(TEMP_PATH) / 1024 / 102,
|
||||
data_dir_size=_get_dir_size(DATA_PATH) / 1024 / 1024,
|
||||
log_dir_size=_get_dir_size(LOG_PATH) / 1024 / 1024,
|
||||
check_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
return disk
|
||||
else:
|
||||
if type_ == "image":
|
||||
dir_path = IMAGE_PATH
|
||||
elif type_ == "font":
|
||||
dir_path = FONT_PATH
|
||||
elif type_ == "text":
|
||||
dir_path = TEXT_PATH
|
||||
elif type_ == "record":
|
||||
dir_path = RECORD_PATH
|
||||
elif type_ == "data":
|
||||
dir_path = DATA_PATH
|
||||
elif type_ == "temp":
|
||||
dir_path = TEMP_PATH
|
||||
else:
|
||||
dir_path = LOG_PATH
|
||||
dir_map = {}
|
||||
other_file_size = 0
|
||||
for file in os.listdir(dir_path):
|
||||
file = Path(dir_path / file)
|
||||
if file.is_dir():
|
||||
dir_map[file.name] = _get_dir_size(file) / 1024 / 1024
|
||||
else:
|
||||
other_file_size += os.path.getsize(file) / 1024 / 1024
|
||||
dir_map["其他文件"] = other_file_size
|
||||
dir_map["check_time"] = datetime.now().replace(microsecond=0)
|
||||
return dir_map
|
||||
|
||||
|
||||
def _get_dir_size(dir_path: Path) -> float:
|
||||
"""
|
||||
说明:
|
||||
获取文件夹大小
|
||||
参数:
|
||||
:param dir_path: 文件夹路径
|
||||
"""
|
||||
size = 0
|
||||
for root, dirs, files in os.walk(dir_path):
|
||||
size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
|
||||
return size
|
||||
|
||||
|
||||
def save_system_data(cpu: float, memory: float, disk: float):
|
||||
"""
|
||||
说明:
|
||||
保存一些系统信息
|
||||
参数:
|
||||
:param cpu: cpu
|
||||
:param memory: memory
|
||||
:param disk: disk
|
||||
"""
|
||||
global cpu_data, memory_data, disk_data
|
||||
if CPU_DATA_PATH.exists() and not cpu_data["data"]:
|
||||
with open(CPU_DATA_PATH, "r") as f:
|
||||
cpu_data = json.load(f)
|
||||
if MEMORY_DATA_PATH.exists() and not memory_data["data"]:
|
||||
with open(MEMORY_DATA_PATH, "r") as f:
|
||||
memory_data = json.load(f)
|
||||
if DISK_DATA_PATH.exists() and not disk_data["data"]:
|
||||
with open(DISK_DATA_PATH, "r") as f:
|
||||
disk_data = json.load(f)
|
||||
now = str(datetime.now().time().replace(microsecond=0))
|
||||
cpu_data["data"].append({"time": now, "data": cpu})
|
||||
memory_data["data"].append({"time": now, "data": memory})
|
||||
disk_data["data"].append({"time": now, "data": disk})
|
||||
if len(cpu_data["data"]) > 50:
|
||||
cpu_data["data"] = cpu_data["data"][-50:]
|
||||
if len(memory_data["data"]) > 50:
|
||||
memory_data["data"] = memory_data["data"][-50:]
|
||||
if len(disk_data["data"]) > 50:
|
||||
disk_data["data"] = disk_data["data"][-50:]
|
||||
with open(CPU_DATA_PATH, "w") as f:
|
||||
json.dump(cpu_data, f, indent=4, ensure_ascii=False)
|
||||
with open(MEMORY_DATA_PATH, "w") as f:
|
||||
json.dump(memory_data, f, indent=4, ensure_ascii=False)
|
||||
with open(DISK_DATA_PATH, "w") as f:
|
||||
json.dump(disk_data, f, indent=4, ensure_ascii=False)
|
||||
@@ -1,6 +1,7 @@
|
||||
from typing import Optional, List, Any, Union
|
||||
from typing import Optional, List, Any, Union, Dict
|
||||
from pydantic import BaseModel
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from datetime import datetime
|
||||
import nonebot
|
||||
|
||||
|
||||
@@ -18,6 +19,9 @@ app.add_middleware(
|
||||
|
||||
|
||||
class CdLimit(BaseModel):
|
||||
"""
|
||||
Cd 限制
|
||||
"""
|
||||
cd: int
|
||||
status: bool
|
||||
check_type: str
|
||||
@@ -26,6 +30,9 @@ class CdLimit(BaseModel):
|
||||
|
||||
|
||||
class BlockLimit(BaseModel):
|
||||
"""
|
||||
Block限制
|
||||
"""
|
||||
status: bool
|
||||
check_type: str
|
||||
limit_type: str
|
||||
@@ -33,6 +40,9 @@ class BlockLimit(BaseModel):
|
||||
|
||||
|
||||
class CountLimit(BaseModel):
|
||||
"""
|
||||
Count限制
|
||||
"""
|
||||
max_count: int
|
||||
status: bool
|
||||
limit_type: bool
|
||||
@@ -40,6 +50,9 @@ class CountLimit(BaseModel):
|
||||
|
||||
|
||||
class PluginManager(BaseModel):
|
||||
"""
|
||||
插件信息
|
||||
"""
|
||||
plugin_name: str # 插件名称
|
||||
status: Optional[bool] # 插件状态
|
||||
error: Optional[bool] # 加载状态
|
||||
@@ -49,6 +62,9 @@ class PluginManager(BaseModel):
|
||||
|
||||
|
||||
class PluginSettings(BaseModel):
|
||||
"""
|
||||
插件基本设置
|
||||
"""
|
||||
level: Optional[int] # 群权限等级
|
||||
default_status: Optional[bool] # 默认开关
|
||||
limit_superuser: Optional[bool] # 是否限制超级用户
|
||||
@@ -58,6 +74,9 @@ class PluginSettings(BaseModel):
|
||||
|
||||
|
||||
class PluginConfig(BaseModel):
|
||||
"""
|
||||
插件配置项
|
||||
"""
|
||||
id: int
|
||||
key: str
|
||||
value: Optional[Any]
|
||||
@@ -66,6 +85,9 @@ class PluginConfig(BaseModel):
|
||||
|
||||
|
||||
class Plugin(BaseModel):
|
||||
"""
|
||||
插件
|
||||
"""
|
||||
model: str # 模块
|
||||
plugin_settings: Optional[PluginSettings]
|
||||
plugin_manager: Optional[PluginManager]
|
||||
@@ -76,6 +98,9 @@ class Plugin(BaseModel):
|
||||
|
||||
|
||||
class Group(BaseModel):
|
||||
"""
|
||||
群组信息
|
||||
"""
|
||||
group_id: int
|
||||
group_name: str
|
||||
member_count: int
|
||||
@@ -83,12 +108,18 @@ class Group(BaseModel):
|
||||
|
||||
|
||||
class Task(BaseModel):
|
||||
"""
|
||||
被动技能
|
||||
"""
|
||||
name: str
|
||||
nameZh: str
|
||||
status: bool
|
||||
|
||||
|
||||
class GroupResult(BaseModel):
|
||||
"""
|
||||
群组返回数据
|
||||
"""
|
||||
group: Group
|
||||
level: int
|
||||
status: bool
|
||||
@@ -97,6 +128,9 @@ class GroupResult(BaseModel):
|
||||
|
||||
|
||||
class RequestResult(BaseModel):
|
||||
"""
|
||||
好友/群组请求管理
|
||||
"""
|
||||
oid: str
|
||||
id: int
|
||||
flag: str
|
||||
@@ -111,11 +145,68 @@ class RequestResult(BaseModel):
|
||||
|
||||
|
||||
class RequestParma(BaseModel):
|
||||
"""
|
||||
操作请求接收数据
|
||||
"""
|
||||
id: int
|
||||
handle: str
|
||||
type: str
|
||||
|
||||
|
||||
class SystemStatus(BaseModel):
|
||||
"""
|
||||
系统状态
|
||||
"""
|
||||
cpu: int
|
||||
memory: int
|
||||
disk: int
|
||||
check_time: datetime
|
||||
|
||||
|
||||
class SystemNetwork(BaseModel):
|
||||
"""
|
||||
系统网络状态
|
||||
"""
|
||||
baidu: int
|
||||
google: int
|
||||
|
||||
|
||||
class SystemFolderSize(BaseModel):
|
||||
"""
|
||||
资源文件占比
|
||||
"""
|
||||
font_dir_size: float
|
||||
image_dir_size: float
|
||||
text_dir_size: float
|
||||
record_dir_size: float
|
||||
temp_dir_size: float
|
||||
data_dir_size: float
|
||||
log_dir_size: float
|
||||
check_time: datetime
|
||||
|
||||
|
||||
class SystemStatusList(BaseModel):
|
||||
"""
|
||||
状态记录
|
||||
"""
|
||||
cpu_data: List[Dict[str, Union[float, str]]]
|
||||
memory_data: List[Dict[str, Union[float, str]]]
|
||||
disk_data: List[Dict[str, Union[float, str]]]
|
||||
|
||||
|
||||
class SystemResult(BaseModel):
|
||||
"""
|
||||
系统api返回
|
||||
"""
|
||||
status: SystemStatus
|
||||
network: SystemNetwork
|
||||
disk: SystemFolderSize
|
||||
check_time: datetime
|
||||
|
||||
|
||||
class Result(BaseModel):
|
||||
"""
|
||||
总体返回
|
||||
"""
|
||||
code: int
|
||||
data: Any
|
||||
|
||||
Reference in New Issue
Block a user