config_model.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import re
  5. from pathlib import Path
  6. from pydantic import BaseModel, ValidationError, Field
  7. from module.config.utils import *
  8. from module.logger import logger
  9. # 导入配置的Python文件
  10. from tasks.Component.config_base import ConfigBase
  11. from tasks.Script.config import Script
  12. from tasks.Restart.config import Restart
  13. from tasks.GlobalGame.config import GlobalGame
  14. from tasks.AreaBoss.config import AreaBoss
  15. from tasks.ExperienceYoukai.config import ExperienceYoukai
  16. from tasks.GoldYoukai.config import GoldYoukai
  17. from tasks.Nian.config import Nian
  18. from tasks.Orochi.config import Orochi
  19. from tasks.OrochiMoans.config import OrochiMoans
  20. from tasks.Sougenbi.config import Sougenbi
  21. from tasks.FallenSun.config import FallenSun
  22. from tasks.EternitySea.config import EternitySea
  23. from tasks.RealmRaid.config import RealmRaid
  24. # 这一部分是活动的配置-----------------------------------------------------------------------------------------------------
  25. from tasks.ActivityShikigami.config import ActivityShikigami
  26. # ----------------------------------------------------------------------------------------------------------------------
  27. # 肝帝专属---------------------------------------------------------------------------------------------------------------
  28. from tasks.BondlingFairyland.config import BondlingFairyland
  29. # ----------------------------------------------------------------------------------------------------------------------
  30. class ConfigModel(ConfigBase):
  31. config_name: str = "oas"
  32. script: Script = Field(default_factory=Script)
  33. restart: Restart = Field(default_factory=Restart)
  34. global_game: GlobalGame = Field(default_factory=GlobalGame)
  35. # 这些是每日任务的
  36. area_boss: AreaBoss = Field(default_factory=AreaBoss)
  37. experience_youkai: ExperienceYoukai = Field(default_factory=ExperienceYoukai)
  38. gold_youkai: GoldYoukai = Field(default_factory=GoldYoukai)
  39. nian: Nian = Field(default_factory=Nian)
  40. realm_raid: RealmRaid = Field(default_factory=RealmRaid)
  41. # 这些是刷御魂的
  42. orochi: Orochi = Field(default_factory=Orochi)
  43. orochi_moans: OrochiMoans = Field(default_factory=OrochiMoans)
  44. sougenbi: Sougenbi = Field(default_factory=Sougenbi)
  45. fallen_sun: FallenSun = Field(default_factory=FallenSun)
  46. eternity_sea: EternitySea = Field(default_factory=EternitySea)
  47. # 这些是活动的
  48. activity_shikigami: ActivityShikigami = Field(default_factory=ActivityShikigami)
  49. # 这些是肝帝专属
  50. bondling_fairyland: BondlingFairyland = Field(default_factory=BondlingFairyland)
  51. # @validator('script')
  52. # def script_validator(cls, v):
  53. # if v is None:
  54. # return Script()
  55. def __init__(self, config_name: str=None) -> None:
  56. """
  57. :param config_name:
  58. """
  59. if not config_name:
  60. super().__init__()
  61. return
  62. data = self.read_json(config_name)
  63. data["config_name"] = config_name
  64. super().__init__(**data)
  65. def __setattr__(self, key, value):
  66. """
  67. 只要修改属性就会触发这个函数 自动保存
  68. :param key:
  69. :param value:
  70. :return:
  71. """
  72. super().__setattr__(key, value)
  73. logger.info("auto save config")
  74. self.save()
  75. @staticmethod
  76. def read_json(config_name: str) -> dict:
  77. """
  78. 读文件 没有额外操作
  79. :param config_name: 不带后缀
  80. :return:
  81. """
  82. filepath = Path.cwd() / "config" / f"{config_name}.json"
  83. return read_file(filepath)
  84. @staticmethod
  85. def write_json(config_name: str, data) -> None:
  86. """
  87. :param config_name: 不带后缀
  88. :param data: 字典而不是字符串
  89. :return:
  90. """
  91. filepath = Path.cwd() / "config" / f"{config_name}.json"
  92. write_file(filepath, data)
  93. def gui_args(self, task: str) -> str:
  94. """
  95. 返回提供给gui显示的参数
  96. :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
  97. :return: 返回的是pydantic给我们结构化的输出的信息, 如果不能获取就返回空的str
  98. """
  99. task = convert_to_underscore(task)
  100. task_gui = getattr(self, task, None)
  101. if task_gui is None:
  102. logger.warning(f'{task} is no inexistence')
  103. return ''
  104. schema2 = task_gui.schema()
  105. # https://github.com/pydantic/pydantic/discussions/5687
  106. if 'definitions' in schema2:
  107. if 'Scheduler' in schema2['definitions']:
  108. if 'properties' in schema2['definitions']['Scheduler']:
  109. properties = schema2['definitions']['Scheduler']['properties']
  110. if 'success_interval' in properties:
  111. properties['success_interval']['type'] = 'string'
  112. if 'failure_interval' in properties:
  113. properties['failure_interval']['type'] = 'string'
  114. return json.dumps(schema2)
  115. def gui_task(self, task: str) -> str:
  116. """
  117. 返回提供给gui显示的参数
  118. :param task:
  119. :return:
  120. """
  121. task_name = convert_to_underscore(task)
  122. task = getattr(self, task_name, None)
  123. if task is None:
  124. logger.warning(f'{task_name} is no inexistence')
  125. return ''
  126. return task.json()
  127. def save(self) -> None:
  128. """
  129. :return:
  130. """
  131. self.write_json(self.config_name, self.dict())
  132. @staticmethod
  133. def type(key: str) -> str:
  134. """
  135. 输入模型的键值,获取这个字段对象的类型 比如输入是orochi输出是Orochi
  136. :param key:
  137. :return:
  138. """
  139. field_type: str = str(ConfigModel.__annotations__[key])
  140. # return field_type
  141. if '.' in field_type:
  142. classname = field_type.split('.')[-1][:-2]
  143. return classname
  144. else:
  145. classname = re.findall(r"'([^']*)'", field_type)[0]
  146. return classname
  147. # @root_validator
  148. # def on_on_property_change(cls, values):
  149. # """
  150. # 当属性改变时保存
  151. # :param values:
  152. # :return:
  153. # """
  154. # logger.info(f'property change auto save')
  155. # cls.save()
  156. @staticmethod
  157. def deep_get(obj, keys: str, default=None):
  158. """
  159. 递归获取模型的值
  160. :param obj:
  161. :param keys:
  162. :param default:
  163. :return:
  164. """
  165. if not isinstance(keys, list):
  166. keys = keys.split('.')
  167. value = obj
  168. try:
  169. for key in keys:
  170. value = getattr(value, key)
  171. except AttributeError:
  172. return default
  173. return value
  174. @staticmethod
  175. def deep_set(obj, keys: str, value) -> bool:
  176. if not isinstance(keys, list):
  177. keys = keys.split('.')
  178. current_obj = obj
  179. try:
  180. for key in keys[:-1]:
  181. current_obj = getattr(current_obj, key)
  182. setattr(current_obj, keys[-1], value)
  183. return True
  184. except (AttributeError, KeyError):
  185. return False
  186. if __name__ == "__main__":
  187. try:
  188. c = ConfigModel("oas1")
  189. except ValidationError as e:
  190. print(e)
  191. c = ConfigModel()
  192. # c.save()
  193. print(c.deep_get(c, 'area_boss.scheduler.success_interval'))