| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401 |
- # This Python file uses the following encoding: utf-8
- # @author runhey
- # github https://github.com/runhey
- from typing import Dict, Any
- import re
- import inflection
- from pathlib import Path
- from pydantic import BaseModel, ValidationError, Field
- from module.config.utils import *
- from module.logger import logger
- # 导入配置的Python文件
- from tasks.Component.config_base import ConfigBase, TimeDelta
- from tasks.Exploration.config import Exploration
- from tasks.RyouToppa.config import RyouToppa
- from tasks.Script.config import Script
- from tasks.Restart.config import Restart
- from tasks.GlobalGame.config import GlobalGame
- # 每日任务-----------------------------------------------------------------------------------------------------
- from tasks.AreaBoss.config import AreaBoss
- from tasks.ExperienceYoukai.config import ExperienceYoukai
- from tasks.GoldYoukai.config import GoldYoukai
- from tasks.Nian.config import Nian
- from tasks.KekkaiUtilize.config import KekkaiUtilize
- from tasks.KekkaiActivation.config import KekkaiActivation
- from tasks.DemonEncounter.config import DemonEncounter
- from tasks.DailyTrifles.config import DailyTrifles
- from tasks.TalismanPass.config import TalismanPass
- from tasks.Pets.config import Pets
- from tasks.SoulsTidy.config import SoulsTidy
- from tasks.Delegation.config import Delegation
- from tasks.WantedQuests.config import WantedQuests
- from tasks.Tako.config import Tako
- # ----------------------------------------------------------------------------------------------------------------------
- from tasks.Orochi.config import Orochi
- from tasks.OrochiMoans.config import OrochiMoans
- from tasks.Sougenbi.config import Sougenbi
- from tasks.FallenSun.config import FallenSun
- from tasks.EternitySea.config import EternitySea
- from tasks.RealmRaid.config import RealmRaid
- from tasks.CollectiveMissions.config import CollectiveMissions
- from tasks.Hunt.config import Hunt
- # 这一部分是活动的配置-----------------------------------------------------------------------------------------------------
- from tasks.ActivityShikigami.config import ActivityShikigami
- from tasks.MetaDemon.config import MetaDemon
- from tasks.FrogBoss.config import FrogBoss
- # ----------------------------------------------------------------------------------------------------------------------
- # 肝帝专属---------------------------------------------------------------------------------------------------------------
- from tasks.BondlingFairyland.config import BondlingFairyland
- from tasks.EvoZone.config import EvoZone
- from tasks.GoryouRealm.config import GoryouRealm
- # ----------------------------------------------------------------------------------------------------------------------
- # 每周任务---------------------------------------------------------------------------------------------------------------
- from tasks.TrueOrochi.config import TrueOrochi
- from tasks.RichMan.config import RichMan
- from tasks.Secret.config import Secret
- from tasks.WeeklyTrifles.config import WeeklyTrifles
- from tasks.MysteryShop.config import MysteryShop
- from tasks.Duel.config import Duel
- # ----------------------------------------------------------------------------------------------------------------------
- class ConfigModel(ConfigBase):
- config_name: str = "oas"
- script: Script = Field(default_factory=Script)
- restart: Restart = Field(default_factory=Restart)
- global_game: GlobalGame = Field(default_factory=GlobalGame)
- # 这些是每日任务的
- area_boss: AreaBoss = Field(default_factory=AreaBoss)
- experience_youkai: ExperienceYoukai = Field(default_factory=ExperienceYoukai)
- gold_youkai: GoldYoukai = Field(default_factory=GoldYoukai)
- nian: Nian = Field(default_factory=Nian)
- realm_raid: RealmRaid = Field(default_factory=RealmRaid)
- ryou_toppa: RyouToppa = Field(default_factory=RyouToppa)
- kekkai_utilize: KekkaiUtilize = Field(default_factory=KekkaiUtilize)
- kekkai_activation: KekkaiActivation = Field(default_factory=KekkaiActivation)
- demon_encounter: DemonEncounter = Field(default_factory=DemonEncounter)
- daily_trifles: DailyTrifles = Field(default_factory=DailyTrifles)
- talisman_pass: TalismanPass = Field(default_factory=TalismanPass)
- pets: Pets = Field(default_factory=Pets)
- souls_tidy: SoulsTidy = Field(default_factory=SoulsTidy)
- delegation: Delegation = Field(default_factory=Delegation)
- exploration: Exploration = Field(default_factory=Exploration)
- wanted_quests: WantedQuests = Field(default_factory=WantedQuests)
- tako: Tako = Field(default_factory=Tako)
- # 这些是刷御魂的
- orochi: Orochi = Field(default_factory=Orochi)
- orochi_moans: OrochiMoans = Field(default_factory=OrochiMoans)
- sougenbi: Sougenbi = Field(default_factory=Sougenbi)
- fallen_sun: FallenSun = Field(default_factory=FallenSun)
- eternity_sea: EternitySea = Field(default_factory=EternitySea)
- # 这些是活动的
- activity_shikigami: ActivityShikigami = Field(default_factory=ActivityShikigami)
- meta_demon: MetaDemon = Field(default_factory=MetaDemon)
- frog_boss: FrogBoss = Field(default_factory=FrogBoss)
- # 这些是肝帝专属
- bondling_fairyland: BondlingFairyland = Field(default_factory=BondlingFairyland)
- evo_zone: EvoZone = Field(default_factory=EvoZone)
- goryou_realm: GoryouRealm = Field(default_factory=GoryouRealm)
- # 这些是每周任务
- true_orochi: TrueOrochi = Field(default_factory=TrueOrochi)
- rich_man: RichMan = Field(default_factory=RichMan)
- secret: Secret = Field(default_factory=Secret)
- weekly_trifles: WeeklyTrifles = Field(default_factory=WeeklyTrifles)
- mystery_shop: MysteryShop = Field(default_factory=MysteryShop)
- duel: Duel = Field(default_factory=Duel)
- # 阴阳寮
- collective_missions: CollectiveMissions = Field(default_factory=CollectiveMissions)
- hunt: Hunt = Field(default_factory=Hunt)
- # @validator('script')
- # def script_validator(cls, v):
- # if v is None:
- # return Script()
- def __init__(self, config_name: str=None) -> None:
- """
- :param config_name:
- """
- if not config_name:
- super().__init__()
- return
- data = self.read_json(config_name)
- data["config_name"] = config_name
- super().__init__(**data)
- def __setattr__(self, key, value):
- """
- 只要修改属性就会触发这个函数 自动保存
- :param key:
- :param value:
- :return:
- """
- super().__setattr__(key, value)
- logger.info("auto save config")
- self.save()
- @staticmethod
- def read_json(config_name: str) -> dict:
- """
- 读文件 没有额外操作
- :param config_name: 不带后缀
- :return:
- """
- filepath = Path.cwd() / "config" / f"{config_name}.json"
- return read_file(filepath)
- @staticmethod
- def write_json(config_name: str, data) -> None:
- """
- :param config_name: 不带后缀
- :param data: 字典而不是字符串
- :return:
- """
- filepath = Path.cwd() / "config" / f"{config_name}.json"
- write_file(filepath, data)
- def gui_args(self, task: str) -> str:
- """
- 返回提供给gui显示的参数
- :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
- :return: 返回的是pydantic给我们结构化的输出的信息, 如果不能获取就返回空的str
- """
- task = convert_to_underscore(task)
- task_gui = getattr(self, task, None)
- if task_gui is None:
- logger.warning(f'{task} is no inexistence')
- return ''
- schema2 = task_gui.schema()
- # https://github.com/pydantic/pydantic/discussions/5687
- if 'definitions' in schema2:
- if 'Scheduler' in schema2['definitions']:
- if 'properties' in schema2['definitions']['Scheduler']:
- properties = schema2['definitions']['Scheduler']['properties']
- if 'success_interval' in properties:
- properties['success_interval']['type'] = 'string'
- if 'failure_interval' in properties:
- properties['failure_interval']['type'] = 'string'
- return json.dumps(schema2)
- def gui_task(self, task: str) -> str:
- """
- 返回提供给gui显示的参数
- :param task:
- :return:
- """
- task_name = convert_to_underscore(task)
- task = getattr(self, task_name, None)
- if task is None:
- logger.warning(f'{task_name} is no inexistence')
- return ''
- return task.json()
- def save(self) -> None:
- """
- :return:
- """
- self.write_json(self.config_name, self.dict())
- @staticmethod
- def type(key: str) -> str:
- """
- 输入模型的键值,获取这个字段对象的类型 比如输入是orochi输出是Orochi
- :param key:
- :return:
- """
- field_type: str = str(ConfigModel.__annotations__[key])
- # return field_type
- if '.' in field_type:
- classname = field_type.split('.')[-1][:-2]
- return classname
- else:
- classname = re.findall(r"'([^']*)'", field_type)[0]
- return classname
- # @root_validator
- # def on_on_property_change(cls, values):
- # """
- # 当属性改变时保存
- # :param values:
- # :return:
- # """
- # logger.info(f'property change auto save')
- # cls.save()
- @staticmethod
- def deep_get(obj, keys: str, default=None):
- """
- 递归获取模型的值
- :param obj:
- :param keys:
- :param default:
- :return:
- """
- if not isinstance(keys, list):
- keys = keys.split('.')
- value = obj
- try:
- for key in keys:
- value = getattr(value, key)
- except AttributeError:
- return default
- return value
- @staticmethod
- def deep_set(obj, keys: str, value) -> bool:
- if not isinstance(keys, list):
- keys = keys.split('.')
- current_obj = obj
- try:
- for key in keys[:-1]:
- current_obj = getattr(current_obj, key)
- setattr(current_obj, keys[-1], value)
- return True
- except (AttributeError, KeyError):
- return False
- # ----------------------------------- fastapi -----------------------------------
- def script_task(self, task: str) -> dict:
- """
- :param task: 同gui_args函数
- :return:
- """
- task = convert_to_underscore(task)
- task = getattr(self, task, None)
- if task is None:
- logger.warning(f'{task} is no inexistence')
- return {}
- def properties_groups(sch) -> dict:
- properties = {}
- for key, value in sch["properties"].items():
- properties[key] = re.search(r"/([^/]+)$", value['$ref']).group(1)
- return properties
- def extract_groups(sch):
- # 从schema 中提取未解析的group的数据
- properties = properties_groups(sch)
- result = {}
- for key, value in properties.items():
- result[key] = sch["definitions"][value]
- return result
- def merge_value(groups, jsons, definitions) -> list[dict]:
- # 将 groups的参数,同导出的json一起合并, 用于前端显示
- result = []
- for key, value in groups["properties"].items():
- item = {}
- item["name"] = key
- item["title"] = value["title"] if "title" in value else inflection.underscore(key)
- if "description" in value:
- item["description"] = value["description"]
- item["default"] = value["default"]
- item["value"] = jsons[key] if key in jsons else value["default"]
- item["type"] = value["type"] if "type" in value else "enum"
- if 'allOf' in value:
- # list
- enum_key = re.search(r"/([^/]+)$", value['allOf'][0]['$ref']).group(1)
- item["enumEnum"] = definitions[enum_key]["enum"]
- # TODO: 最大值最小值
- result.append(item)
- return result
- schema = task.schema()
- groups = extract_groups(schema)
- result: dict[str, list] = {}
- for key, value in task.dict().items():
- result[key] = merge_value(groups[key], value, schema["definitions"])
- return result
- def script_set_arg(self, task: str, group: str, argument: str, value) -> bool:
- # 验证参数
- task = convert_to_underscore(task)
- group = convert_to_underscore(group)
- argument = convert_to_underscore(argument)
- # pandtic验证
- if isinstance(value, str) and len(value) == 8:
- try:
- value = datetime.strptime(value, '%H:%M:%S').time()
- except ValueError:
- pass
- if isinstance(value, str) and len(value) == 11:
- try:
- date_time = datetime.strptime(value, '%d %H:%M:%S')
- value = TimeDelta(days=date_time.day, hours=date_time.hour, minutes=date_time.minute, seconds=date_time.second)
- except ValueError:
- pass
- if isinstance(value, str) and len(value) == 19:
- try:
- value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
- except ValueError:
- pass
- if isinstance(value, str) and value == 'true':
- value = True
- if isinstance(value, str) and value == 'false':
- value = False
- task_object = getattr(self, task, None)
- group_object = getattr(task_object, group, None)
- argument_object = getattr(group_object, argument, None)
- # print(group_object)
- # print(argument_object)
- if argument_object is None:
- logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
- return False
- # 设置参数
- try:
- setattr(group_object, argument, value)
- logger.info(f'Set arg {self.config_name}.{task}.{group}.{argument}.{value}')
- self.save() # 我是没有想到什么方法可以使得属性改变自动保存的
- return True
- except ValidationError as e:
- logger.error(e)
- return False
- if __name__ == "__main__":
- try:
- c = ConfigModel("oas1")
- except ValidationError as e:
- print(e)
- c = ConfigModel()
- # c.save()
- print(c.script_task('Orochi'))
|