config_model.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. class ConfigModel(ConfigBase):
  28. config_name: str = "oas"
  29. script: Script = Field(default_factory=Script)
  30. restart: Restart = Field(default_factory=Restart)
  31. global_game: GlobalGame = Field(default_factory=GlobalGame)
  32. # 这些是每日任务的
  33. area_boss: AreaBoss = Field(default_factory=AreaBoss)
  34. experience_youkai: ExperienceYoukai = Field(default_factory=ExperienceYoukai)
  35. gold_youkai: GoldYoukai = Field(default_factory=GoldYoukai)
  36. nian: Nian = Field(default_factory=Nian)
  37. realm_raid: RealmRaid = Field(default_factory=RealmRaid)
  38. # 这些是刷御魂的
  39. orochi: Orochi = Field(default_factory=Orochi)
  40. orochi_moans: OrochiMoans = Field(default_factory=OrochiMoans)
  41. sougenbi: Sougenbi = Field(default_factory=Sougenbi)
  42. fallen_sun: FallenSun = Field(default_factory=FallenSun)
  43. eternity_sea: EternitySea = Field(default_factory=EternitySea)
  44. # 这些是活动的
  45. activity_shikigami: ActivityShikigami = Field(default_factory=ActivityShikigami)
  46. # @validator('script')
  47. # def script_validator(cls, v):
  48. # if v is None:
  49. # return Script()
  50. def __init__(self, config_name: str=None) -> None:
  51. """
  52. :param config_name:
  53. """
  54. if not config_name:
  55. super().__init__()
  56. return
  57. data = self.read_json(config_name)
  58. data["config_name"] = config_name
  59. super().__init__(**data)
  60. def __setattr__(self, key, value):
  61. """
  62. 只要修改属性就会触发这个函数 自动保存
  63. :param key:
  64. :param value:
  65. :return:
  66. """
  67. super().__setattr__(key, value)
  68. logger.info("auto save config")
  69. self.save()
  70. @staticmethod
  71. def read_json(config_name: str) -> dict:
  72. """
  73. 读文件 没有额外操作
  74. :param config_name: 不带后缀
  75. :return:
  76. """
  77. filepath = Path.cwd() / "config" / f"{config_name}.json"
  78. return read_file(filepath)
  79. @staticmethod
  80. def write_json(config_name: str, data) -> None:
  81. """
  82. :param config_name: 不带后缀
  83. :param data: 字典而不是字符串
  84. :return:
  85. """
  86. filepath = Path.cwd() / "config" / f"{config_name}.json"
  87. write_file(filepath, data)
  88. def gui_args(self, task: str) -> str:
  89. """
  90. 返回提供给gui显示的参数
  91. :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
  92. :return: 返回的是pydantic给我们结构化的输出的信息, 如果不能获取就返回空的str
  93. """
  94. task = convert_to_underscore(task)
  95. task_gui = getattr(self, task, None)
  96. if task_gui is None:
  97. logger.warning(f'{task} is no inexistence')
  98. return ''
  99. schema2 = task_gui.schema()
  100. # https://github.com/pydantic/pydantic/discussions/5687
  101. if 'definitions' in schema2:
  102. if 'Scheduler' in schema2['definitions']:
  103. if 'properties' in schema2['definitions']['Scheduler']:
  104. properties = schema2['definitions']['Scheduler']['properties']
  105. if 'success_interval' in properties:
  106. properties['success_interval']['type'] = 'string'
  107. if 'failure_interval' in properties:
  108. properties['failure_interval']['type'] = 'string'
  109. return json.dumps(schema2)
  110. def gui_task(self, task: str) -> str:
  111. """
  112. 返回提供给gui显示的参数
  113. :param task:
  114. :return:
  115. """
  116. task_name = convert_to_underscore(task)
  117. task = getattr(self, task_name, None)
  118. if task is None:
  119. logger.warning(f'{task_name} is no inexistence')
  120. return ''
  121. return task.json()
  122. def save(self) -> None:
  123. """
  124. :return:
  125. """
  126. self.write_json(self.config_name, self.dict())
  127. @staticmethod
  128. def type(key: str) -> str:
  129. """
  130. 输入模型的键值,获取这个字段对象的类型 比如输入是orochi输出是Orochi
  131. :param key:
  132. :return:
  133. """
  134. field_type: str = str(ConfigModel.__annotations__[key])
  135. # return field_type
  136. if '.' in field_type:
  137. classname = field_type.split('.')[-1][:-2]
  138. return classname
  139. else:
  140. classname = re.findall(r"'([^']*)'", field_type)[0]
  141. return classname
  142. # @root_validator
  143. # def on_on_property_change(cls, values):
  144. # """
  145. # 当属性改变时保存
  146. # :param values:
  147. # :return:
  148. # """
  149. # logger.info(f'property change auto save')
  150. # cls.save()
  151. if __name__ == "__main__":
  152. try:
  153. c = ConfigModel("oas1")
  154. except ValidationError as e:
  155. print(e)
  156. c = ConfigModel()
  157. c.gui_args('Nian')
  158. print(c.gui_task('Nian'))
  159. print(c.gui_task('AreaBoss'))
  160. print(c.dict()['nian']['scheduler']['success_interval'])
  161. c.save()