feat: 代码格式化, 改进仪表盘, 新增多CSS支持
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
"""音频服务"""
|
||||
|
||||
from typing import Callable
|
||||
|
||||
from heurams.context import config_var
|
||||
@@ -7,7 +8,10 @@ from heurams.services.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
play_by_path: Callable = prov[config_var.get()["services"]["audio"]['provider']].play_by_path
|
||||
play_by_path: Callable = prov[
|
||||
config_var.get()["services"]["audio"]["provider"]
|
||||
].play_by_path
|
||||
logger.debug(
|
||||
"音频服务初始化完成, 使用 Provider: %s", config_var.get()["services"]["audio"]['provider']
|
||||
"音频服务初始化完成, 使用 Provider: %s",
|
||||
config_var.get()["services"]["audio"]["provider"],
|
||||
)
|
||||
|
||||
@@ -11,26 +11,27 @@ from heurams.services.exceptions import WTFException
|
||||
# 我们的流程是: 找到文件名: 返回文件名里头的数据; 找不到: 继续查索引; 所以 self.data 除了存本级各种索引球用没得
|
||||
logger = get_logger(__name__)
|
||||
|
||||
class ConfigDict(UserDict): # 舒服了
|
||||
_instances = {} # 必须使用单例模式, 不然有严重的多实例导致的配置无法持久化问题
|
||||
|
||||
class ConfigDict(UserDict): # 舒服了
|
||||
_instances = {} # 必须使用单例模式, 不然有严重的多实例导致的配置无法持久化问题
|
||||
|
||||
def __new__(cls, config_path: pathlib.Path, dict=None):
|
||||
if dict:
|
||||
raise WTFException("不要放默认值...")
|
||||
|
||||
|
||||
# 规范化路径, 免得单例存在"别名"
|
||||
path_key = config_path.resolve()
|
||||
|
||||
|
||||
if path_key in cls._instances:
|
||||
return cls._instances[path_key]
|
||||
|
||||
|
||||
instance = super().__new__(cls)
|
||||
cls._instances[path_key] = instance
|
||||
return instance
|
||||
|
||||
def __init__(self, config_path: pathlib.Path, dict = None): # 需要自己把自己提起来
|
||||
def __init__(self, config_path: pathlib.Path, dict=None): # 需要自己把自己提起来
|
||||
# 避免重复初始化
|
||||
if hasattr(self, '_initialized'):
|
||||
if hasattr(self, "_initialized"):
|
||||
return
|
||||
self._initialized = True
|
||||
if dict:
|
||||
@@ -42,13 +43,13 @@ class ConfigDict(UserDict): # 舒服了
|
||||
if self.is_dir:
|
||||
self.update_index()
|
||||
else:
|
||||
with open(self.path, 'r+') as f: #TODO: 给这个做缓存
|
||||
with open(self.path, "r+") as f: # TODO: 给这个做缓存
|
||||
try:
|
||||
self.data = toml.load(f)
|
||||
except:
|
||||
self.data = {}
|
||||
self.persist = lambda: False # 不修改错误的配置文件
|
||||
|
||||
self.persist = lambda: False # 不修改错误的配置文件
|
||||
|
||||
def __getitem__(self, key):
|
||||
# 我们实现了先进的懒狗加载
|
||||
value = super().__getitem__(key)
|
||||
@@ -60,7 +61,7 @@ class ConfigDict(UserDict): # 舒服了
|
||||
return super().__contains__(key)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
origvalue = super().__getitem__(key) # 所以你不该访问不存在的对象
|
||||
origvalue = super().__getitem__(key) # 所以你不该访问不存在的对象
|
||||
if isinstance(origvalue, ConfigDict):
|
||||
if origvalue.path.is_dir():
|
||||
raise WTFException("你怎么能变更目录配置的内容呢?!")
|
||||
@@ -70,20 +71,22 @@ class ConfigDict(UserDict): # 舒服了
|
||||
origvalue.data = value
|
||||
super().__setitem__(key, value)
|
||||
|
||||
def update_index(self): # 如果有人没事干在config里面创建指向config的符号链接 这玩意会崩溃 但是不要修复: 需要这个符号链接特性
|
||||
def update_index(
|
||||
self,
|
||||
): # 如果有人没事干在config里面创建指向config的符号链接 这玩意会崩溃 但是不要修复: 需要这个符号链接特性
|
||||
for i in self.path.iterdir():
|
||||
if i.name.startswith('_'):
|
||||
if i.name == '_.toml' and not i.is_dir():
|
||||
with open(self.path/'_.toml', 'r+') as f:
|
||||
if i.name.startswith("_"):
|
||||
if i.name == "_.toml" and not i.is_dir():
|
||||
with open(self.path / "_.toml", "r+") as f:
|
||||
self.data.update(dict(toml.load(f)))
|
||||
continue
|
||||
if i.is_dir():
|
||||
self.data[i.name] = i
|
||||
else:
|
||||
if i.suffix == '.toml':
|
||||
if i.suffix == ".toml":
|
||||
self.data[i.stem] = i
|
||||
else:
|
||||
logger.debug(f"配置目录中有无效的文件 {i.stem}") # what's up bro
|
||||
logger.debug(f"配置目录中有无效的文件 {i.stem}") # what's up bro
|
||||
|
||||
def persist(self):
|
||||
if self.is_dir:
|
||||
@@ -94,5 +97,5 @@ class ConfigDict(UserDict): # 舒服了
|
||||
logger.debug("完成配置持久化")
|
||||
return
|
||||
|
||||
with open(self.path, 'w+') as f:
|
||||
toml.dump(self.data, f)
|
||||
with open(self.path, "w+") as f:
|
||||
toml.dump(self.data, f)
|
||||
|
||||
@@ -3,27 +3,41 @@ from heurams.services.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
def epath(dct, path: str = '', default=None, parents=False, enable_modify=False, new_value=None):
|
||||
|
||||
def epath(
|
||||
dct,
|
||||
path: str = "",
|
||||
default=None,
|
||||
parents=False,
|
||||
enable_modify=False,
|
||||
new_value=None,
|
||||
):
|
||||
if not path:
|
||||
return dct
|
||||
|
||||
path = path.rstrip('.')
|
||||
path = path.lstrip('.')
|
||||
|
||||
path = path.rstrip(".")
|
||||
path = path.lstrip(".")
|
||||
target = dct
|
||||
keys = path.split('.')
|
||||
keys = path.split(".")
|
||||
logger.debug(f"处理 EPATH {path}, {new_value}")
|
||||
for idx, i in enumerate(keys):
|
||||
is_last = (idx == len(keys) - 1)
|
||||
|
||||
is_last = idx == len(keys) - 1
|
||||
|
||||
# 处理字典键
|
||||
logger.debug(f'处理 {i}, {(isinstance(target, dict) or isinstance(target, ConfigDict))} {i in target}')
|
||||
|
||||
logger.debug(
|
||||
f"处理 {i}, {(isinstance(target, dict) or isinstance(target, ConfigDict))} {i in target}"
|
||||
)
|
||||
|
||||
if is_last and enable_modify:
|
||||
# 最后一次循环执行修改
|
||||
if (isinstance(target, dict) or isinstance(target, ConfigDict)):
|
||||
if isinstance(target, dict) or isinstance(target, ConfigDict):
|
||||
target[i] = new_value
|
||||
return new_value
|
||||
elif i.startswith('[') and i.endswith(']') and isinstance(target, (list, tuple)):
|
||||
elif (
|
||||
i.startswith("[")
|
||||
and i.endswith("]")
|
||||
and isinstance(target, (list, tuple))
|
||||
):
|
||||
idx_num = int(i[1:-1])
|
||||
if 0 <= idx_num < len(target):
|
||||
target[idx_num] = new_value
|
||||
@@ -38,9 +52,15 @@ def epath(dct, path: str = '', default=None, parents=False, enable_modify=False,
|
||||
else:
|
||||
return default
|
||||
else:
|
||||
if (isinstance(target, dict) or isinstance(target, ConfigDict)) and i in target:
|
||||
if (
|
||||
isinstance(target, dict) or isinstance(target, ConfigDict)
|
||||
) and i in target:
|
||||
target = target[i]
|
||||
elif i.startswith('[') and i.endswith(']') and isinstance(target, (list, tuple)):
|
||||
elif (
|
||||
i.startswith("[")
|
||||
and i.endswith("]")
|
||||
and isinstance(target, (list, tuple))
|
||||
):
|
||||
idx_num = int(i[1:-1])
|
||||
if 0 <= idx_num < len(target):
|
||||
target = target[idx_num]
|
||||
@@ -56,5 +76,5 @@ def epath(dct, path: str = '', default=None, parents=False, enable_modify=False,
|
||||
target = target[i]
|
||||
else:
|
||||
return default
|
||||
|
||||
return target
|
||||
|
||||
return target
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from heurams.services.logger import get_logger
|
||||
|
||||
|
||||
class WTFException(Exception):
|
||||
pass
|
||||
pass
|
||||
|
||||
@@ -63,7 +63,7 @@ class FavoriteManager:
|
||||
|
||||
def _get_file_path(self) -> Path:
|
||||
"""获取收藏文件路径"""
|
||||
config_path = Path(config_var.get()['global']["paths"]["data"])
|
||||
config_path = Path(config_var.get()["global"]["paths"]["data"])
|
||||
fav_path = config_path / "global" / "favorites.json"
|
||||
fav_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
return fav_path
|
||||
|
||||
@@ -3,8 +3,10 @@ def truncate(text):
|
||||
return text
|
||||
return text[:3] + ">"
|
||||
|
||||
|
||||
def domize(text):
|
||||
return text.replace('.', '--DOT--')
|
||||
return text.replace(".", "--DOT--")
|
||||
|
||||
|
||||
def undomize(text):
|
||||
return text.replace('--DOT--', '.')
|
||||
return text.replace("--DOT--", ".")
|
||||
|
||||
@@ -9,12 +9,15 @@ logger = get_logger(__name__)
|
||||
|
||||
def get_daystamp() -> int:
|
||||
"""获取当前日戳(以天为单位的整数时间戳)"""
|
||||
time_override = config_var.get()['services']["timer"]["daystamp_override"]
|
||||
time_override = config_var.get()["services"]["timer"]["daystamp_override"]
|
||||
if time_override != -1:
|
||||
logger.debug("使用覆盖的日戳: %d", time_override)
|
||||
return int(time_override)
|
||||
|
||||
result = int((time.time() + config_var.get()['services']["timer"]["timezone_offset"]) // (24 * 3600))
|
||||
result = int(
|
||||
(time.time() + config_var.get()["services"]["timer"]["timezone_offset"])
|
||||
// (24 * 3600)
|
||||
)
|
||||
logger.debug("计算日戳: %d", result)
|
||||
return result
|
||||
|
||||
@@ -22,7 +25,7 @@ def get_daystamp() -> int:
|
||||
def get_timestamp() -> float:
|
||||
"""获取 UNIX 时间戳"""
|
||||
# 搞这个类的原因是要支持可复现操作
|
||||
time_override = config_var.get()['services']["timer"]["timestamp_override"]
|
||||
time_override = config_var.get()["services"]["timer"]["timestamp_override"]
|
||||
if time_override != -1:
|
||||
logger.debug("使用覆盖的时间戳: %f", time_override)
|
||||
return float(time_override)
|
||||
|
||||
@@ -7,7 +7,8 @@ from heurams.services.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
convertor: Callable = prov[config_var.get()['services']["tts"]["provider"]].convert
|
||||
convertor: Callable = prov[config_var.get()["services"]["tts"]["provider"]].convert
|
||||
logger.debug(
|
||||
"TTS 服务初始化完成, 使用 provider: %s", config_var.get()['services']["tts"]["provider"]
|
||||
"TTS 服务初始化完成, 使用 provider: %s",
|
||||
config_var.get()["services"]["tts"]["provider"],
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user