config_model.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from typing import Dict, Any
  5. import re
  6. import inflection
  7. from pathlib import Path
  8. from pydantic import BaseModel, ValidationError, Field
  9. from module.config.utils import *
  10. from module.logger import logger
  11. # 导入配置的Python文件
  12. from tasks.Component.config_base import ConfigBase, TimeDelta
  13. from tasks.Exploration.config import Exploration
  14. from tasks.RyouToppa.config import RyouToppa
  15. from tasks.Script.config import Script
  16. from tasks.Restart.config import Restart
  17. from tasks.GlobalGame.config import GlobalGame
  18. # 每日任务-----------------------------------------------------------------------------------------------------
  19. from tasks.AreaBoss.config import AreaBoss
  20. from tasks.ExperienceYoukai.config import ExperienceYoukai
  21. from tasks.GoldYoukai.config import GoldYoukai
  22. from tasks.Nian.config import Nian
  23. from tasks.KekkaiUtilize.config import KekkaiUtilize
  24. from tasks.KekkaiActivation.config import KekkaiActivation
  25. from tasks.DemonEncounter.config import DemonEncounter
  26. from tasks.DailyTrifles.config import DailyTrifles
  27. from tasks.TalismanPass.config import TalismanPass
  28. from tasks.Pets.config import Pets
  29. from tasks.SoulsTidy.config import SoulsTidy
  30. from tasks.Delegation.config import Delegation
  31. from tasks.WantedQuests.config import WantedQuests
  32. from tasks.Tako.config import Tako
  33. # ----------------------------------------------------------------------------------------------------------------------
  34. from tasks.Orochi.config import Orochi
  35. from tasks.OrochiMoans.config import OrochiMoans
  36. from tasks.Sougenbi.config import Sougenbi
  37. from tasks.FallenSun.config import FallenSun
  38. from tasks.EternitySea.config import EternitySea
  39. from tasks.RealmRaid.config import RealmRaid
  40. from tasks.CollectiveMissions.config import CollectiveMissions
  41. from tasks.Hunt.config import Hunt
  42. # 这一部分是活动的配置-----------------------------------------------------------------------------------------------------
  43. from tasks.ActivityShikigami.config import ActivityShikigami
  44. from tasks.MetaDemon.config import MetaDemon
  45. from tasks.FrogBoss.config import FrogBoss
  46. # ----------------------------------------------------------------------------------------------------------------------
  47. # 肝帝专属---------------------------------------------------------------------------------------------------------------
  48. from tasks.BondlingFairyland.config import BondlingFairyland
  49. from tasks.EvoZone.config import EvoZone
  50. from tasks.GoryouRealm.config import GoryouRealm
  51. from tasks.Hyakkiyakou.config import Hyakkiyakou
  52. # ----------------------------------------------------------------------------------------------------------------------
  53. # 每周任务---------------------------------------------------------------------------------------------------------------
  54. from tasks.TrueOrochi.config import TrueOrochi
  55. from tasks.RichMan.config import RichMan
  56. from tasks.Secret.config import Secret
  57. from tasks.WeeklyTrifles.config import WeeklyTrifles
  58. from tasks.MysteryShop.config import MysteryShop
  59. from tasks.Duel.config import Duel
  60. # ----------------------------------------------------------------------------------------------------------------------
  61. class ConfigModel(ConfigBase):
  62. config_name: str = "oas"
  63. script: Script = Field(default_factory=Script)
  64. restart: Restart = Field(default_factory=Restart)
  65. global_game: GlobalGame = Field(default_factory=GlobalGame)
  66. # 这些是每日任务的
  67. area_boss: AreaBoss = Field(default_factory=AreaBoss)
  68. experience_youkai: ExperienceYoukai = Field(default_factory=ExperienceYoukai)
  69. gold_youkai: GoldYoukai = Field(default_factory=GoldYoukai)
  70. nian: Nian = Field(default_factory=Nian)
  71. realm_raid: RealmRaid = Field(default_factory=RealmRaid)
  72. ryou_toppa: RyouToppa = Field(default_factory=RyouToppa)
  73. kekkai_utilize: KekkaiUtilize = Field(default_factory=KekkaiUtilize)
  74. kekkai_activation: KekkaiActivation = Field(default_factory=KekkaiActivation)
  75. demon_encounter: DemonEncounter = Field(default_factory=DemonEncounter)
  76. daily_trifles: DailyTrifles = Field(default_factory=DailyTrifles)
  77. talisman_pass: TalismanPass = Field(default_factory=TalismanPass)
  78. pets: Pets = Field(default_factory=Pets)
  79. souls_tidy: SoulsTidy = Field(default_factory=SoulsTidy)
  80. delegation: Delegation = Field(default_factory=Delegation)
  81. exploration: Exploration = Field(default_factory=Exploration)
  82. wanted_quests: WantedQuests = Field(default_factory=WantedQuests)
  83. tako: Tako = Field(default_factory=Tako)
  84. # 这些是刷御魂的
  85. orochi: Orochi = Field(default_factory=Orochi)
  86. orochi_moans: OrochiMoans = Field(default_factory=OrochiMoans)
  87. sougenbi: Sougenbi = Field(default_factory=Sougenbi)
  88. fallen_sun: FallenSun = Field(default_factory=FallenSun)
  89. eternity_sea: EternitySea = Field(default_factory=EternitySea)
  90. # 这些是活动的
  91. activity_shikigami: ActivityShikigami = Field(default_factory=ActivityShikigami)
  92. meta_demon: MetaDemon = Field(default_factory=MetaDemon)
  93. frog_boss: FrogBoss = Field(default_factory=FrogBoss)
  94. # 这些是肝帝专属
  95. bondling_fairyland: BondlingFairyland = Field(default_factory=BondlingFairyland)
  96. evo_zone: EvoZone = Field(default_factory=EvoZone)
  97. goryou_realm: GoryouRealm = Field(default_factory=GoryouRealm)
  98. hyakkiyakou: Hyakkiyakou = Field(default_factory=Hyakkiyakou)
  99. # 这些是每周任务
  100. true_orochi: TrueOrochi = Field(default_factory=TrueOrochi)
  101. rich_man: RichMan = Field(default_factory=RichMan)
  102. secret: Secret = Field(default_factory=Secret)
  103. weekly_trifles: WeeklyTrifles = Field(default_factory=WeeklyTrifles)
  104. mystery_shop: MysteryShop = Field(default_factory=MysteryShop)
  105. duel: Duel = Field(default_factory=Duel)
  106. # 阴阳寮
  107. collective_missions: CollectiveMissions = Field(default_factory=CollectiveMissions)
  108. hunt: Hunt = Field(default_factory=Hunt)
  109. # @validator('script')
  110. # def script_validator(cls, v):
  111. # if v is None:
  112. # return Script()
  113. def __init__(self, config_name: str=None) -> None:
  114. """
  115. :param config_name:
  116. """
  117. if not config_name:
  118. super().__init__()
  119. return
  120. data = self.read_json(config_name)
  121. data["config_name"] = config_name
  122. super().__init__(**data)
  123. def __setattr__(self, key, value):
  124. """
  125. 只要修改属性就会触发这个函数 自动保存
  126. :param key:
  127. :param value:
  128. :return:
  129. """
  130. super().__setattr__(key, value)
  131. logger.info("auto save config")
  132. self.save()
  133. @staticmethod
  134. def read_json(config_name: str) -> dict:
  135. """
  136. 读文件 没有额外操作
  137. :param config_name: 不带后缀
  138. :return:
  139. """
  140. filepath = Path.cwd() / "config" / f"{config_name}.json"
  141. return read_file(filepath)
  142. @staticmethod
  143. def write_json(config_name: str, data) -> None:
  144. """
  145. :param config_name: 不带后缀
  146. :param data: 字典而不是字符串
  147. :return:
  148. """
  149. filepath = Path.cwd() / "config" / f"{config_name}.json"
  150. write_file(filepath, data)
  151. def gui_args(self, task: str) -> str:
  152. """
  153. 返回提供给gui显示的参数
  154. :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
  155. :return: 返回的是pydantic给我们结构化的输出的信息, 如果不能获取就返回空的str
  156. """
  157. task = convert_to_underscore(task)
  158. task_gui = getattr(self, task, None)
  159. if task_gui is None:
  160. logger.warning(f'{task} is no inexistence')
  161. return ''
  162. schema2 = task_gui.schema()
  163. # https://github.com/pydantic/pydantic/discussions/5687
  164. if 'definitions' in schema2:
  165. if 'Scheduler' in schema2['definitions']:
  166. if 'properties' in schema2['definitions']['Scheduler']:
  167. properties = schema2['definitions']['Scheduler']['properties']
  168. if 'success_interval' in properties:
  169. properties['success_interval']['type'] = 'string'
  170. if 'failure_interval' in properties:
  171. properties['failure_interval']['type'] = 'string'
  172. return json.dumps(schema2)
  173. def gui_task(self, task: str) -> str:
  174. """
  175. 返回提供给gui显示的参数
  176. :param task:
  177. :return:
  178. """
  179. task_name = convert_to_underscore(task)
  180. task = getattr(self, task_name, None)
  181. if task is None:
  182. logger.warning(f'{task_name} is no inexistence')
  183. return ''
  184. return task.json()
  185. def save(self) -> None:
  186. """
  187. :return:
  188. """
  189. self.write_json(self.config_name, self.dict())
  190. @staticmethod
  191. def type(key: str) -> str:
  192. """
  193. 输入模型的键值,获取这个字段对象的类型 比如输入是orochi输出是Orochi
  194. :param key:
  195. :return:
  196. """
  197. field_type: str = str(ConfigModel.__annotations__[key])
  198. # return field_type
  199. if '.' in field_type:
  200. classname = field_type.split('.')[-1][:-2]
  201. return classname
  202. else:
  203. classname = re.findall(r"'([^']*)'", field_type)[0]
  204. return classname
  205. # @root_validator
  206. # def on_on_property_change(cls, values):
  207. # """
  208. # 当属性改变时保存
  209. # :param values:
  210. # :return:
  211. # """
  212. # logger.info(f'property change auto save')
  213. # cls.save()
  214. @staticmethod
  215. def deep_get(obj, keys: str, default=None):
  216. """
  217. 递归获取模型的值
  218. :param obj:
  219. :param keys:
  220. :param default:
  221. :return:
  222. """
  223. if not isinstance(keys, list):
  224. keys = keys.split('.')
  225. value = obj
  226. try:
  227. for key in keys:
  228. value = getattr(value, key)
  229. except AttributeError:
  230. return default
  231. return value
  232. @staticmethod
  233. def deep_set(obj, keys: str, value) -> bool:
  234. if not isinstance(keys, list):
  235. keys = keys.split('.')
  236. current_obj = obj
  237. try:
  238. for key in keys[:-1]:
  239. current_obj = getattr(current_obj, key)
  240. setattr(current_obj, keys[-1], value)
  241. return True
  242. except (AttributeError, KeyError):
  243. return False
  244. # ----------------------------------- fastapi -----------------------------------
  245. def script_task(self, task: str) -> dict:
  246. """
  247. :param task: 同gui_args函数
  248. :return:
  249. """
  250. task = convert_to_underscore(task)
  251. task = getattr(self, task, None)
  252. if task is None:
  253. logger.warning(f'{task} is no inexistence')
  254. return {}
  255. def properties_groups(sch) -> dict:
  256. properties = {}
  257. for key, value in sch["properties"].items():
  258. properties[key] = re.search(r"/([^/]+)$", value['$ref']).group(1)
  259. return properties
  260. def extract_groups(sch):
  261. # 从schema 中提取未解析的group的数据
  262. properties = properties_groups(sch)
  263. result = {}
  264. for key, value in properties.items():
  265. result[key] = sch["definitions"][value]
  266. return result
  267. def merge_value(groups, jsons, definitions) -> list[dict]:
  268. # 将 groups的参数,同导出的json一起合并, 用于前端显示
  269. result = []
  270. for key, value in groups["properties"].items():
  271. item = {}
  272. item["name"] = key
  273. item["title"] = value["title"] if "title" in value else inflection.underscore(key)
  274. if "description" in value:
  275. item["description"] = value["description"]
  276. item["default"] = value["default"]
  277. item["value"] = jsons[key] if key in jsons else value["default"]
  278. item["type"] = value["type"] if "type" in value else "enum"
  279. if 'allOf' in value:
  280. # list
  281. enum_key = re.search(r"/([^/]+)$", value['allOf'][0]['$ref']).group(1)
  282. item["enumEnum"] = definitions[enum_key]["enum"]
  283. # TODO: 最大值最小值
  284. result.append(item)
  285. return result
  286. schema = task.schema()
  287. groups = extract_groups(schema)
  288. result: dict[str, list] = {}
  289. for key, value in task.dict().items():
  290. result[key] = merge_value(groups[key], value, schema["definitions"])
  291. return result
  292. def script_set_arg(self, task: str, group: str, argument: str, value) -> bool:
  293. # 验证参数
  294. task = convert_to_underscore(task)
  295. group = convert_to_underscore(group)
  296. argument = convert_to_underscore(argument)
  297. # pandtic验证
  298. if isinstance(value, str) and len(value) == 8:
  299. try:
  300. value = datetime.strptime(value, '%H:%M:%S').time()
  301. except ValueError:
  302. pass
  303. if isinstance(value, str) and len(value) == 11:
  304. try:
  305. date_time = datetime.strptime(value, '%d %H:%M:%S')
  306. value = TimeDelta(days=date_time.day, hours=date_time.hour, minutes=date_time.minute, seconds=date_time.second)
  307. except ValueError:
  308. pass
  309. if isinstance(value, str) and len(value) == 19:
  310. try:
  311. value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
  312. except ValueError:
  313. pass
  314. if isinstance(value, str) and value == 'true':
  315. value = True
  316. if isinstance(value, str) and value == 'false':
  317. value = False
  318. task_object = getattr(self, task, None)
  319. group_object = getattr(task_object, group, None)
  320. argument_object = getattr(group_object, argument, None)
  321. # print(group_object)
  322. # print(argument_object)
  323. if argument_object is None:
  324. logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
  325. return False
  326. # 设置参数
  327. try:
  328. setattr(group_object, argument, value)
  329. logger.info(f'Set arg {self.config_name}.{task}.{group}.{argument}.{value}')
  330. self.save() # 我是没有想到什么方法可以使得属性改变自动保存的
  331. return True
  332. except ValidationError as e:
  333. logger.error(e)
  334. return False
  335. if __name__ == "__main__":
  336. try:
  337. c = ConfigModel("oas1")
  338. except ValidationError as e:
  339. print(e)
  340. c = ConfigModel()
  341. # c.save()
  342. print(c.script_task('Orochi'))