config_model.py 15 KB

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