feat: 优化配置和凭据构建

This commit is contained in:
amtoaer
2023-11-22 01:10:56 +08:00
parent 2df2bebed3
commit 8c451a5e8c
2 changed files with 68 additions and 16 deletions
+32
View File
@@ -0,0 +1,32 @@
from bilibili_api import Credential
from settings import settings
class PersistedCredential(Credential):
def __init__(self) -> None:
super().__init__(
settings.sessdata,
settings.bili_jct,
settings.buvid3,
settings.dedeuserid,
settings.ac_time_value,
)
async def refresh(self) -> None:
await super().refresh()
(
settings.sessdata,
settings.bili_jct,
settings.dedeuserid,
settings.ac_time_value,
) = (
self.sessdata,
self.bili_jct,
self.dedeuserid,
self.ac_time_value,
)
# 暂时使用同步调用
settings.save()
credential = PersistedCredential()
+36 -16
View File
@@ -2,45 +2,65 @@ from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin from dataclasses_json import DataClassJsonMixin
from pathlib import Path from pathlib import Path
from typing import Self from typing import Self
import os
from constants import DEFAULT_CONFIG_PATH
@dataclass @dataclass
class Config(DataClassJsonMixin): class Config(DataClassJsonMixin):
sessiondata: str sessdata: str
bili_jct: str bili_jct: str
buvid3: str buvid3: str
dedeuserid: str dedeuserid: str
ac_time_value: str ac_time_value: str
favorite_ids: list favorite_ids: list[int]
path_mapper: dict path_mapper: dict[int, str]
@staticmethod @staticmethod
def load(path: Path | str) -> Self: def load(path: Path | None = None) -> Self:
if isinstance(path, str): if not path:
path = Path(path) path = DEFAULT_CONFIG_PATH
try: try:
with path.open("r") as f: with path.open("r") as f:
return Config.schema().loads(f.read()) return Config.schema().loads(f.read())
except Exception as e: except Exception as e:
raise ValueError(f"Failed to load config file: {path}") from e raise RuntimeError(f"Failed to load config file: {path}") from e
def save(self, path: Path | str) -> Self: def save(self, path: Path | None = None) -> Self:
if isinstance(path, str): if not path:
path = Path(path) path = DEFAULT_CONFIG_PATH
try: try:
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w") as f: with path.open("w") as f:
f.write(Config.schema().dumps(self)) f.write(Config.schema().dumps(self))
return self
except Exception as e: except Exception as e:
raise PermissionError(f"Failed to save config file: {path}") from e raise RuntimeError(f"Failed to save config file: {path}") from e
return self
def init_settings() -> Config: def init_settings() -> Config:
if (Path(__file__).parent / "config.json").exists(): if DEFAULT_CONFIG_PATH.exists():
return Config.load(Path(__file__).parent / "config.json") return Config.load(DEFAULT_CONFIG_PATH)
# TODO: 读取环境变量 if os.getenv("TESTING"):
return Config().save(Path(__file__).parent / "config.json") from debug import debug_config
return debug_config
return (
Config.schema()
.load(
{
"sessdata": "",
"bili_jct": "",
"buvid3": "",
"dedeuserid": "",
"ac_time_value": "",
"favorite_ids": [],
"path_mapper": {},
}
)
.save(DEFAULT_CONFIG_PATH)
)
settings = init_settings() settings = init_settings()