Skip to content

Commit

Permalink
fix: 缺少GroupLocalTime的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
HeartfeltJoy committed Jul 13, 2024
1 parent ba2ccf1 commit 1d5973e
Show file tree
Hide file tree
Showing 13 changed files with 386 additions and 52 deletions.
58 changes: 56 additions & 2 deletions src/Core/Config/ConfigModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class HttpConfig(BaseModel):
secret: str
enableHeart: bool
enablePost: bool
postUrls: List[HttpUrl]
postUrls: List[Optional[HttpUrl]]

@field_validator("port")
@staticmethod
Expand All @@ -83,7 +83,7 @@ class WsConfig(BaseModel):

class ReverseWsConfig(BaseModel):
enable: bool
urls: List[WebsocketUrl]
urls: List[Optional[WebsocketUrl]]


class ConnectConfig(BaseModel):
Expand All @@ -92,10 +92,16 @@ class ConnectConfig(BaseModel):
reverseWs: ReverseWsConfig


class NCGroupLocalTime(BaseModel):
Record: bool
RecordList: List[Optional[str]]


class AdvancedConfig(BaseModel):
QQPath: str
startScriptPath: str
ffmpegPath: str
GroupLocalTime: NCGroupLocalTime
debug: bool
localFile2url: bool
fileLog: bool
Expand All @@ -108,3 +114,51 @@ class Config(BaseModel):
bot: BotConfig
connect: ConnectConfig
advanced: AdvancedConfig


DEFAULT_CONFIG = {
"bot": {
"name": "",
"QQID": "",
"messagePostFormat": "array",
"reportSelfMsg": False,
"musicSignUrl": "",
"heartInterval": "30000",
"accessToken": "",
},
"connect": {
"http": {
"enable": False,
"host": "",
"port": "",
"secret": "",
"enableHeart": False,
"enablePost": False,
"postUrls": [],
},
"ws": {
"enable": False,
"host": "",
"port": 3001
},
"reverseWs": {
"enable": False,
"urls": []
},
},
"advanced": {
"QQPath": "",
"startScriptPath": "",
"ffmpegPath": "",
"GroupLocalTime": {
"Record": False,
"RecordList": []
},
"debug": False,
"localFile2url": False,
"fileLog": False,
"consoleLog": False,
"fileLogLevel": "debug",
"consoleLogLevel": "info"
}
}
4 changes: 4 additions & 0 deletions src/Core/CreateScript.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,10 @@ def _createConfig(self, bot_config_path: Path, napcat_config_path: Path) -> None
"enable": self.config.connect.reverseWs.enable,
"urls": [str(url) for url in self.config.connect.reverseWs.urls],
},
"GroupLocalTime": {
"Record": self.config.advanced.GroupLocalTime.Record,
"RecordList": self.config.advanced.GroupLocalTime.RecordList
},
"debug": self.config.advanced.debug,
"heartInterval": self.config.bot.heartInterval,
"messagePostFormat": self.config.bot.messagePostFormat,
Expand Down
7 changes: 3 additions & 4 deletions src/Ui/AddPage/AddWidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@

from src.Ui.AddPage.Advanced import AdvancedWidget
from src.Ui.AddPage.BotWidget import BotWidget
from src.Ui.AddPage.Connect import ConnectWidget

from src.Ui.AddPage.ConfigTopCard import ConfigTopCard
from src.Ui.AddPage.Connect import ConnectWidget
from src.Ui.StyleSheet import StyleSheet

if TYPE_CHECKING:
Expand Down Expand Up @@ -60,8 +59,8 @@ def _createView(self) -> None:
"""
self.view = QStackedWidget()
self.botWidget = BotWidget(self)
self.connectWidget = ConnectWidget(self)
self.advancedWidget = AdvancedWidget(self)
self.connectWidget = ConnectWidget("Add", self)
self.advancedWidget = AdvancedWidget("Add", self)

self.view.addWidget(self.botWidget)
self.view.addWidget(self.connectWidget)
Expand Down
43 changes: 36 additions & 7 deletions src/Ui/AddPage/Advanced.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget
from creart import it
from qfluentwidgets import ExpandLayout, FluentIcon, ScrollArea

from src.Core.PathFunc import PathFunc
from src.Core.Config.ConfigModel import AdvancedConfig
from src.Core.PathFunc import PathFunc
from src.Ui.common.InputCard import (
SwitchConfigCard,
FolderConfigCard,
ComboBoxConfigCard,
TextCard
)

if TYPE_CHECKING:
pass


class AdvancedWidget(ScrollArea):
"""
## Advance Item 项对应的 QWidget
"""

def __init__(self, parent=None, config: AdvancedConfig = None) -> None:
def __init__(self, identifier, parent=None, config: AdvancedConfig = None) -> None:
super().__init__(parent=parent)
self.setObjectName("AdvanceWidget")
self.identifier = identifier
self.view = QWidget()
self.cardLayout = ExpandLayout(self.view)

Expand Down Expand Up @@ -66,6 +63,19 @@ def _initWidget(self) -> None:
title=self.tr("Specifies ffmpeg path"),
parent=self.view,
)
self.groupLocalTimeSwitchCard = SwitchConfigCard(
icon=FluentIcon.DATE_TIME,
title=self.tr("Local group chat time logging"),
content=self.tr("Specifies whether to enable local group chat time recording"),
parent=self.view
)
self.groupLocalTimeListCard = TextCard(
identifier=self.identifier,
icon=FluentIcon.MENU,
title=self.tr("Swarms that need to be recorded"),
content=self.tr("Hover over for detailed tips"),
parent=self.view
)
self.debugModeCard = SwitchConfigCard(
icon=FluentIcon.COMMAND_PROMPT,
title=self.tr("Debug"),
Expand Down Expand Up @@ -108,10 +118,23 @@ def _initWidget(self) -> None:
parent=self.view,
)

# 当 GroupLocalTimeList 被删除至空时, 设置为 False
self.groupLocalTimeListCard.emptiedSignal.connect(
lambda: self.groupLocalTimeSwitchCard.switchButton.setChecked(False)
)

# 隐藏卡片,并设置条件显示
self.groupLocalTimeListCard.hide()
self.groupLocalTimeSwitchCard.switchButton.checkedChanged.connect(
lambda checked: self.groupLocalTimeListCard.show() if checked else self.groupLocalTimeListCard.hide()
)

self.cards = [
self.QQPathCard,
self.startScriptPathCard,
self.ffmpegPathCard,
self.groupLocalTimeSwitchCard,
self.groupLocalTimeListCard,
self.debugModeCard,
self.localFile2UrlCard,
self.fileLogCard,
Expand All @@ -127,6 +150,8 @@ def fillValue(self) -> None:
self.QQPathCard.fillValue(self.config.QQPath)
self.startScriptPathCard.fillValue(self.config.startScriptPath)
self.ffmpegPathCard.fillValue(self.config.ffmpegPath)
self.groupLocalTimeSwitchCard.fillValue(self.config.GroupLocalTime.Record)
self.groupLocalTimeListCard.fillValue(self.config.GroupLocalTime.RecordList)
self.debugModeCard.fillValue(self.config.debug)
self.localFile2UrlCard.fillValue(self.config.localFile2url)
self.fileLogCard.fillValue(self.config.fileLog)
Expand Down Expand Up @@ -154,6 +179,10 @@ def getValue(self) -> dict:
"QQPath": self.QQPathCard.getValue(),
"startScriptPath": self.startScriptPathCard.getValue(),
"ffmpegPath": self.ffmpegPathCard.getValue(),
"GroupLocalTime": {
"Record": self.groupLocalTimeSwitchCard.getValue(),
"RecordList": self.groupLocalTimeListCard.getValue()
},
"debug": self.debugModeCard.getValue(),
"localFile2url": self.localFile2UrlCard.getValue(),
"fileLog": self.fileLogCard.getValue(),
Expand Down
3 changes: 3 additions & 0 deletions src/Ui/AddPage/ConfigTopCard.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ def _addBotListBtnSlot(self) -> None:
with open(str(bot_config_path), "w", encoding="utf-8") as f:
json.dump(bot_configs, f, indent=4)

# 同时创建bat脚本
self._createBatScriptSlot()

# 执行刷新
it(BotListWidget).botList.updateList()

Expand Down
5 changes: 4 additions & 1 deletion src/Ui/AddPage/Connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ class ConnectWidget(ScrollArea):
## Connect Item 项对应的 QWidget
"""

def __init__(self, parent=None, config: ConnectConfig = None) -> None:
def __init__(self, identifier, parent=None, config: ConnectConfig = None) -> None:
super().__init__(parent=parent)
self.setObjectName("ConnectWidget")
self.identifier = identifier
self.view = QWidget()
self.cardLayout = ExpandLayout(self)

Expand All @@ -50,6 +51,7 @@ def _initWidget(self) -> None:
"""
self.httpConfigCard = HttpConfigCard(self.view)
self.httpPostUrlCard = UrlCard(
identifier=self.identifier,
icon=FluentIcon.SCROLL,
title=self.tr("Http Report address"),
content=self.tr("Set the address for reporting HTTP"),
Expand All @@ -63,6 +65,7 @@ def _initWidget(self) -> None:
parent=self.view,
)
self.wsReverseUrlCard = UrlCard(
identifier=self.identifier,
icon=FluentIcon.SCROLL,
title=self.tr("WebSocket Reverse address"),
content=self.tr("Reverse WebSocket reporting address"),
Expand Down
36 changes: 27 additions & 9 deletions src/Ui/BotListPage/BotList.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from creart import it
from qfluentwidgets import ScrollArea, FlowLayout

from src.Core.Config.ConfigModel import Config
from src.Core.Config.ConfigModel import Config, DEFAULT_CONFIG
from src.Core.PathFunc import PathFunc
from src.Ui.BotListPage.BotCard import BotCard

Expand Down Expand Up @@ -99,20 +99,25 @@ def _parseList(self) -> None:
# 读取配置列表
with open(str(it(PathFunc).bot_config_path), "r", encoding="utf-8") as f:
bot_configs = json.load(f)
if bot_configs:
# 如果从文件加载的 bot_config 不为空则执行使用Config和列表表达式解析
self.botList: List[Config] = [Config(**config) for config in bot_configs]
self.parent().parent().showSuccess(
title=self.tr("Load the list of bots"),
content=self.tr("The list of bots was successfully loaded"),
)
else:

if not bot_configs:
# 创建信息条
self.parent().parent().showInfo(
title=self.tr("There are no bot configuration items"),
content=self.tr("You'll need to add it in the Add bot page"),
)
self.botList = []
return

# 检查是否有新配置项并配置默认值
bot_configs = [self.updateConfig(config, DEFAULT_CONFIG) for config in bot_configs]

# 如果从文件加载的 bot_config 不为空则执行使用Config和列表表达式解析
self.botList: List[Config] = [Config(**config) for config in bot_configs]
self.parent().parent().showSuccess(
title=self.tr("Load the list of bots"),
content=self.tr("The list of bots was successfully loaded"),
)

except FileNotFoundError:
# 如果文件不存在则创建一个
Expand All @@ -126,3 +131,16 @@ def _parseList(self) -> None:
with open(str(it(PathFunc).bot_config_path), "w", encoding="utf-8") as f:
json.dump([], f, indent=4)
self.botList = []

def updateConfig(self, user_config, default_config):
"""
## 这是一个检查是否有新版参数并填入默认值的函数
"""
for key, value in default_config.items():
if isinstance(value, dict):
# 如果值是字典,则递归调用
user_config[key] = self.updateConfig(user_config.get(key, {}), value)
else:
if key not in user_config:
user_config[key] = value
return user_config
4 changes: 2 additions & 2 deletions src/Ui/BotListPage/BotWidget/BotSetupPage.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ def _createSubPages(self) -> None:
子页面直接使用 AddWidget 中的页面
"""
self.botWidget = BotWidget(self, self.config.bot)
self.connectWidget = ConnectWidget(self, self.config.connect)
self.advancedWidget = AdvancedWidget(self, self.config.advanced)
self.connectWidget = ConnectWidget("Setup", self, self.config.connect)
self.advancedWidget = AdvancedWidget("Setup", self, self.config.advanced)

self.botWidget.view.setObjectName("BotListBotSetupView")
self.connectWidget.view.setObjectName("BotListConnectSetupView")
Expand Down
43 changes: 24 additions & 19 deletions src/Ui/BotListPage/BotWidget/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from PySide6.QtGui import QTextCursor, QPixmap
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QStackedWidget
from creart import it
from loguru import logger
from qfluentwidgets import (
SegmentedWidget, TransparentToolButton, FluentIcon, ToolTipFilter, PrimaryPushButton, PushButton, MessageBoxBase,
SubtitleLabel, ImageLabel, ToolButton, BodyLabel
Expand Down Expand Up @@ -285,34 +286,38 @@ def _updateButtonSlot(self) -> None:
## 更新按钮的槽函数
"""
from src.Ui.BotListPage import BotListWidget
from src.Core.Config.ConfigModel import DEFAULT_CONFIG
self.newConfig = Config(**self.botSetupPage.getValue())

# 读取配置列表
with open(str(it(PathFunc).bot_config_path), "r", encoding="utf-8") as f:
bot_configs = [Config(**config) for config in json.load(f)]

if bot_configs:
# 如果从文件加载的 bot_config 不为空则进行更新(为空怎么办呢,我能怎么办,崩了呗bushi
for index, config in enumerate(bot_configs):
# 遍历配置列表,找到一样则替换
if config.bot.QQID == self.newConfig.bot.QQID:
bot_configs[index] = self.newConfig
break
# 不可以直接使用 dict方法 转为 dict对象, 内部 WebsocketUrl 和 HttpUrl 不会自动转为 str
bot_configs = [json.loads(config.json()) for config in bot_configs]
with open(str(it(PathFunc).bot_config_path), "w", encoding="utf-8") as f:
json.dump(bot_configs, f, indent=4)
# 更新成功提示
it(BotListWidget).showSuccess(
title=self.tr("Update success"),
content=self.tr("The updated configuration is successful")
)
else:
bot_configs = [it(BotListWidget).botList.updateConfig(config, DEFAULT_CONFIG) for config in json.load(f)]
bot_configs = [Config(**config) for config in bot_configs]

if not bot_configs:
# 为空报错
logger.error(f"机器人列表加载失败 数据为空: {bot_configs}")
it(BotListWidget).showError(
title=self.tr("Update error"),
content=self.tr("Data loss within the profile")
)
return

# 如果从文件加载的 bot_config 不为空则进行更新(为空怎么办呢,我能怎么办,崩了呗bushi
for index, config in enumerate(bot_configs):
# 遍历配置列表,找到一样则替换
if config.bot.QQID == self.newConfig.bot.QQID:
bot_configs[index] = self.newConfig
break
# 不可以直接使用 dict方法 转为 dict对象, 内部 WebsocketUrl 和 HttpUrl 不会自动转为 str
bot_configs = [json.loads(config.json()) for config in bot_configs]
with open(str(it(PathFunc).bot_config_path), "w", encoding="utf-8") as f:
json.dump(bot_configs, f, indent=4)
# 更新成功提示
it(BotListWidget).showSuccess(
title=self.tr("Update success"),
content=self.tr("The updated configuration is successful")
)

@Slot()
def _deleteButtonSlot(self) -> None:
Expand Down
Loading

0 comments on commit 1d5973e

Please sign in to comment.