Просмотр исходного кода

Merge pull request #161 from runhey/dev

Destructive update
huangrunheng 2 лет назад
Родитель
Сommit
a73f2af1a4
100 измененных файлов с 2382 добавлено и 342 удалено
  1. 10 10
      README.md
  2. 15 4
      config/template.json
  3. 5 8
      dev_tools/assets_extract.py
  4. 54 0
      dev_tools/generate_requirements.py
  5. 123 0
      module/base/retry.py
  6. 32 2
      module/config/config.py
  7. 2 2
      module/config/config_manual.py
  8. 10 2
      module/config/config_menu.py
  9. 122 3
      module/config/config_model.py
  10. 1 0
      module/config/utils.py
  11. 2 7
      module/device/device.py
  12. 2 2
      module/device/method/droidcast.py
  13. 3 3
      module/gui/qml/MainWindow.qml
  14. 108 146
      module/logger.py
  15. 2 2
      module/notify/notify.py
  16. 1 1
      module/ocr/sub_ocr.py
  17. 5 0
      module/server/__init__.py
  18. 65 0
      module/server/app.py
  19. 57 0
      module/server/config.py
  20. 94 0
      module/server/config_manager.py
  21. 62 0
      module/server/home_router.py
  22. 101 0
      module/server/main_manager.py
  23. 157 0
      module/server/script_process.py
  24. 168 0
      module/server/script_router.py
  25. 38 0
      module/server/script_websocket.py
  26. 92 0
      module/server/setting.py
  27. 130 0
      module/server/updater.py
  28. 3 2
      requirements-in.txt
  29. 35 30
      requirements.txt
  30. 5 10
      script.py
  31. 63 0
      server.py
  32. 1 1
      tasks/ActivityShikigami/config.py
  33. 1 1
      tasks/AreaBoss/assets.py
  34. 2 2
      tasks/AreaBoss/res/image.json
  35. BIN
      tasks/AreaBoss/res/res_fire.png
  36. 2 2
      tasks/BondlingFairyland/config.py
  37. 18 0
      tasks/CollectiveMissions/assets.py
  38. 2 1
      tasks/CollectiveMissions/config.py
  39. 20 0
      tasks/CollectiveMissions/feed/feed.json
  40. 30 0
      tasks/CollectiveMissions/feed/feed_click.json
  41. BIN
      tasks/CollectiveMissions/feed/feed_feed_heap.png
  42. BIN
      tasks/CollectiveMissions/feed/feed_feed_submit.png
  43. 54 26
      tasks/CollectiveMissions/script_task.py
  44. 2 2
      tasks/Component/BaseActivity/config_activity.py
  45. 8 0
      tasks/Component/Buy/buy.py
  46. 1 1
      tasks/Component/GeneralInvite/config_invite.py
  47. 17 0
      tasks/Component/ReplaceShikigami/assets.py
  48. 11 0
      tasks/Component/ReplaceShikigami/replace_shikigami.py
  49. 65 0
      tasks/Component/ReplaceShikigami/rs/detect_image.json
  50. BIN
      tasks/Component/ReplaceShikigami/rs/rs_detect_empty_1.png
  51. BIN
      tasks/Component/ReplaceShikigami/rs/rs_detect_empty_2.png
  52. BIN
      tasks/Component/ReplaceShikigami/rs/rs_detect_empty_3.png
  53. BIN
      tasks/Component/ReplaceShikigami/rs/rs_detect_empty_4.png
  54. BIN
      tasks/Component/ReplaceShikigami/rs/rs_detect_empty_5.png
  55. BIN
      tasks/Component/ReplaceShikigami/rs/rs_detect_empty_6.png
  56. 40 16
      tasks/Component/config_base.py
  57. 3 3
      tasks/Component/config_scheduler.py
  58. 1 1
      tasks/DemonEncounter/script_task.py
  59. 2 2
      tasks/Duel/config.py
  60. 2 2
      tasks/EternitySea/config.py
  61. 2 2
      tasks/EvoZone/config.py
  62. 2 12
      tasks/EvoZone/script_task.py
  63. 2 2
      tasks/FallenSun/config.py
  64. 1 1
      tasks/GameUi/assets.py
  65. BIN
      tasks/GameUi/page/page_check_daily.png
  66. 2 2
      tasks/GameUi/page/page_img_3.json
  67. 2 2
      tasks/GoryouRealm/config.py
  68. 0 1
      tasks/Hunt/config.py
  69. 12 4
      tasks/KekkaiActivation/script_task.py
  70. 4 8
      tasks/KekkaiUtilize/script_task.py
  71. 44 0
      tasks/MetaDemon/assets.py
  72. 27 0
      tasks/MetaDemon/config.py
  73. 92 0
      tasks/MetaDemon/md/image.json
  74. BIN
      tasks/MetaDemon/md/md_md_battle_failure.png
  75. BIN
      tasks/MetaDemon/md/md_md_enter.png
  76. BIN
      tasks/MetaDemon/md/md_md_extreme.png
  77. BIN
      tasks/MetaDemon/md/md_md_find.png
  78. BIN
      tasks/MetaDemon/md/md_md_fire.png
  79. BIN
      tasks/MetaDemon/md/md_md_fire_common.png
  80. BIN
      tasks/MetaDemon/md/md_md_fire_power.png
  81. BIN
      tasks/MetaDemon/md/md_md_gift_box.png
  82. BIN
      tasks/MetaDemon/md/md_md_hard.png
  83. BIN
      tasks/MetaDemon/md/md_md_main.png
  84. 29 0
      tasks/MetaDemon/md/ocr.json
  85. 172 0
      tasks/MetaDemon/script_task.py
  86. 2 2
      tasks/MysteryShop/config.py
  87. 5 0
      tasks/Nian/assets.py
  88. 8 0
      tasks/Nian/nian/click.json
  89. 17 2
      tasks/Nian/script_task.py
  90. 2 2
      tasks/Orochi/config.py
  91. 1 1
      tasks/Pets/assets.py
  92. 1 1
      tasks/Pets/pet/image.json
  93. BIN
      tasks/Pets/pet/pet_pet_house.png
  94. 1 1
      tasks/Restart/assets.py
  95. 1 1
      tasks/Restart/login.py
  96. 1 1
      tasks/Restart/login/ocr.json
  97. 1 1
      tasks/Restart/script_task.py
  98. 1 1
      tasks/RichMan/mall/medal.py
  99. 1 1
      tasks/RichMan/mall/special.py
  100. 100 0
      tasks/RyouToppa/assets.py

+ 10 - 10
README.md

@@ -1,7 +1,5 @@
 <div align="center">
 
-<br><br>
-
 # OnmyojiAutoScript
 
 <br>
@@ -20,11 +18,10 @@
 </div>
 <br>
 
-阴阳师 自动化 脚本 
+阴阳师自动化脚本 
 
-基于图像识别技术,一键托管
+一键托管
 
-绝赞更新中✿✿ヽ(°▽°)ノ✿<br>
 
 ### [文档](https://runhey.github.io/OnmyojiAutoScript-website/)
 
@@ -45,13 +42,16 @@ This project is licensed under the GNU General Public License v3.0.
 本软件开源、免费,仅供学习交流使用。开发者团队拥有本项目的最终解释权。使用本软件产生的所有问题与本项目与开发者团队无关。
 
 ## 相关项目 Relative Repositories
-- [Alas](https://github.com/LmeSzinc/AzurLaneAutoScript): 碧蓝航线的自动化脚本,OAS 在其架构上开发
-- [SRC](https://github.com/LmeSzinc/StarRailCopilot): 崩坏:星穹铁道脚本,基于下一代Alas框架
+OAS 基于 Alas 框架开发
+- [Alas](https://github.com/LmeSzinc/AzurLaneAutoScript): 碧蓝航线的自动化脚本
+- [SRC](https://github.com/LmeSzinc/StarRailCopilot): 星铁速溶茶,崩坏:星穹铁道脚本,基于下一代Alas框架。
+- [NikkeAutoScript](https://github.com/takagisanmie/NIKKEAutoScript): 胜利女神:NIKKE 自动日常脚本
+- [AAS](https://github.com/TheFunny/ArisuAutoSweeper): 蔚蓝档案自动化脚本
+- [MAA](https://github.com/MaaAssistantArknights/MaaAssistantArknights): 明日方舟小助手,全日常一键长草
+- [FGO-py](https://github.com/hgjazhgj/FGO-py): 全自动免配置跨平台开箱即用的Fate/Grand Order助手.启动脚本,上床睡觉,养肝护发,满加成圣诞了解一下?
 - [OAS-website](https://github.com/runhey/OnmyojiAutoScript-website): OAS 的文档网站,使用 [docusaurus](https://docusaurus.io/) 构建
-- [FluentUI](https://github.com/zhuzichu520/FluentUI): GUI 库,使用 QML 语言
-- [Uowl](https://github.com/runhey/Uowl): 作者早期的 Onmyoji 脚本,已停止维护
 - [ppocr-onnx](https://github.com/triwinds/ppocr-onnx): OCR 库,基于 onnxruntime 和 PaddleOCR
-- [gurs](https://github.com/2833844911/gurs): 基于赛贝尔曲线模拟滑动轨迹
+- [gurs](https://github.com/2833844911/gurs): 基于赛贝尔曲线模拟滑动轨迹, 引入其轨迹模拟人手滑动
 
 ## 联系/加入我们 Contact/Join Us
 

+ 15 - 4
config/template.json

@@ -548,7 +548,7 @@
     "general_climb": {
       "limit_time": "00:30:00",
       "limit_count": 50,
-      "ap_game_max": 999,
+      "ap_game_max": 300,
       "ap_mode": "ap_activity",
       "activity_toggle": false
     },
@@ -562,6 +562,17 @@
       "random_click_swipt_enable": false
     }
   },
+  "meta_demon": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "interval": "00 03:00:00"
+    },
+    "meta_demon_config": {
+      "auto_tea": false,
+      "extreme_notify": false
+    }
+  },
   "bondling_fairyland": {
     "scheduler": {
       "enable": false,
@@ -860,7 +871,8 @@
       "server_update": "09:00:00"
     },
     "missions_config": {
-      "missions_rule": "契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一"
+      "missions_rule": "契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一 > 远远不够",
+      "setup_when_bondling": true
     }
   },
   "hunt": {
@@ -875,7 +887,6 @@
     "hunt_config": {
       "kirin_group_team": "-1,-1",
       "netherworld_group_team": "-1,-1"
-    },
-    "exit_battle": false
+    }
   }
 }

+ 5 - 8
dev_tools/assets_extract.py

@@ -26,7 +26,6 @@ from module.atom.list import RuleList
 IMPORT_EXP = IMPORT_EXP.strip().split('MODULE_FOLDER') + ['']
 
 
-
 def name_transform(name: str) -> str:
     """
     转换名称, 把小写的转化为大写的, 带有数字的不变,有下划线继续有下划线,
@@ -40,6 +39,7 @@ def name_transform(name: str) -> str:
         return name.upper()
     return name.upper()
 
+
 class ImageExtractor:
 
     def __init__(self, file: str, data: list) -> None:
@@ -59,7 +59,6 @@ class ImageExtractor:
     def result(self) -> str:
         return self._result
 
-
     def extract_item(self, item) -> str:
         """
         解析每一项,返回字符串
@@ -75,6 +74,7 @@ class ImageExtractor:
                     f'file="./{self.image_path}/{item["imageName"]}")\n'
         return description + name
 
+
 class ClickExtractor:
 
     def __init__(self, file: str, data: list) -> None:
@@ -103,6 +103,7 @@ class ClickExtractor:
                     f'name="{item["itemName"]}")\n'
         return description + name
 
+
 class LongClickExtractor:
 
     def __init__(self, file: str, data: list) -> None:
@@ -132,6 +133,7 @@ class LongClickExtractor:
                     f'name="{item["itemName"]}")\n'
         return description + name
 
+
 class SwipeExtractor:
 
     def __init__(self, file: str, data: list) -> None:
@@ -161,6 +163,7 @@ class SwipeExtractor:
                     f'name="{item["itemName"]}")\n'
         return description + name
 
+
 class OcrExtractor:
     def __init__(self, file: str, data: list) -> None:
         """
@@ -240,9 +243,6 @@ class ListExtractor:
         return description + name
 
 
-
-
-
 class AssetsExtractor:
 
     def __init__(self, task_path: str) -> None:
@@ -262,7 +262,6 @@ class AssetsExtractor:
             self._result += import_exp
         self._result += self.class_name
 
-
     def all_json_file(self) -> list:
         """
         获取所有json文件
@@ -353,7 +352,6 @@ class AssetsExtractor:
             return True
         return False
 
-
     def write_file(self) -> None:
         """
         将自身的_resule写入文件
@@ -418,6 +416,5 @@ class AllAssetsExtractor:
         me.extract()
 
 
-
 if __name__ == "__main__":
     AllAssetsExtractor()

+ 54 - 0
dev_tools/generate_requirements.py

@@ -0,0 +1,54 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import argparse
+import subprocess
+import time
+
+from module.logger import logger
+
+def generate(qml: bool=False):
+    content = ''
+    if not qml:
+        with open("requirements-in.txt", "r", encoding="utf-8") as f:
+            content = f.read()
+            content = content.replace("pyside6==6.4.3\n", "")
+        with open("requirements-in.txt", "w", encoding="utf-8") as f:
+            f.write(content)
+        logger.info("requirements-in.txt generated")
+    else:
+        with open("requirements-in.txt", "r", encoding="utf-8") as f:
+            content = f.read()
+            if content.find("pyside6==6.4.3\n") == -1:
+                content.index("pyside6==6.4.3\n")
+        with open("requirements-in.txt", "w", encoding="utf-8") as f:
+            f.write(content)
+        logger.info("requirements-in.txt generated")
+
+
+    # 执行命令 pip-compile --annotation-style=line --output-file=requirements.txt requirements-in.txt
+    subprocess.run(["pip-compile", "--annotation-style=line", "--output-file=requirements.txt", "requirements-in.txt"])
+
+    content = ''
+    with open("requirements.txt", "r", encoding="utf-8") as f:
+        content = f.read()
+        content = content.replace('''--index-url https://pypi.tuna.tsinghua.edu.cn/simple
+--trusted-host pypi.tuna.tsinghua.edu.cn''', '')
+    with open("requirements.txt", "w", encoding="utf-8") as f:
+        f.write(content)
+    logger.info("requirements.txt generated")
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(description="Generate requirements.txt")
+    parser.add_argument(
+        "--qml",
+        action="store_true",
+        help="Use qml",
+    )
+    args, _ = parser.parse_known_args()
+    qml = True if args.qml else False
+    logger.attr("QML", qml)
+
+    generate(qml)
+
+

+ 123 - 0
module/base/retry.py

@@ -0,0 +1,123 @@
+import functools
+import random
+import time
+from functools import partial
+
+from module.logger import logger as logging_logger
+
+"""
+Copied from Alas
+"""
+
+try:
+    from decorator import decorator
+except ImportError:
+    def decorator(caller):
+        """ Turns caller into a decorator.
+        Unlike decorator module, function signature is not preserved.
+
+        :param caller: caller(f, *args, **kwargs)
+        """
+
+        def decor(f):
+            @functools.wraps(f)
+            def wrapper(*args, **kwargs):
+                return caller(f, *args, **kwargs)
+
+            return wrapper
+
+        return decor
+
+
+def __retry_internal(f, exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff=1, jitter=0,
+                     logger=logging_logger):
+    """
+    Executes a function and retries it if it failed.
+
+    :param f: the function to execute.
+    :param exceptions: an exception or a tuple of exceptions to catch. default: Exception.
+    :param tries: the maximum number of attempts. default: -1 (infinite).
+    :param delay: initial delay between attempts. default: 0.
+    :param max_delay: the maximum value of delay. default: None (no limit).
+    :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).
+    :param jitter: extra seconds added to delay between attempts. default: 0.
+                   fixed if a number, random if a range tuple (min, max)
+    :param logger: logger.warning(fmt, error, delay) will be called on failed attempts.
+                   default: retry.logging_logger. if None, logging is disabled.
+    :returns: the result of the f function.
+    """
+    _tries, _delay = tries, delay
+    while _tries:
+        try:
+            return f()
+        except exceptions as e:
+            _tries -= 1
+            if not _tries:
+                # Difference, raise same exception
+                raise e
+
+            if logger is not None:
+                # Difference, show exception
+                logger.exception(e)
+                logger.warning(f'{type(e).__name__}({e}), retrying in {_delay} seconds...')
+
+            time.sleep(_delay)
+            _delay *= backoff
+
+            if isinstance(jitter, tuple):
+                _delay += random.uniform(*jitter)
+            else:
+                _delay += jitter
+
+            if max_delay is not None:
+                _delay = min(_delay, max_delay)
+
+
+def retry(exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff=1, jitter=0, logger=logging_logger):
+    """Returns a retry decorator.
+
+    :param exceptions: an exception or a tuple of exceptions to catch. default: Exception.
+    :param tries: the maximum number of attempts. default: -1 (infinite).
+    :param delay: initial delay between attempts. default: 0.
+    :param max_delay: the maximum value of delay. default: None (no limit).
+    :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).
+    :param jitter: extra seconds added to delay between attempts. default: 0.
+                   fixed if a number, random if a range tuple (min, max)
+    :param logger: logger.warning(fmt, error, delay) will be called on failed attempts.
+                   default: retry.logging_logger. if None, logging is disabled.
+    :returns: a retry decorator.
+    """
+
+    @decorator
+    def retry_decorator(f, *fargs, **fkwargs):
+        args = fargs if fargs else list()
+        kwargs = fkwargs if fkwargs else dict()
+        return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter,
+                                logger)
+
+    return retry_decorator
+
+
+def retry_call(f, fargs=None, fkwargs=None, exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff=1,
+               jitter=0,
+               logger=logging_logger):
+    """
+    Calls a function and re-executes it if it failed.
+
+    :param f: the function to execute.
+    :param fargs: the positional arguments of the function to execute.
+    :param fkwargs: the named arguments of the function to execute.
+    :param exceptions: an exception or a tuple of exceptions to catch. default: Exception.
+    :param tries: the maximum number of attempts. default: -1 (infinite).
+    :param delay: initial delay between attempts. default: 0.
+    :param max_delay: the maximum value of delay. default: None (no limit).
+    :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).
+    :param jitter: extra seconds added to delay between attempts. default: 0.
+                   fixed if a number, random if a range tuple (min, max)
+    :param logger: logger.warning(fmt, error, delay) will be called on failed attempts.
+                   default: retry.logging_logger. if None, logging is disabled.
+    :returns: the result of the f function.
+    """
+    args = fargs if fargs else list()
+    kwargs = fkwargs if fkwargs else dict()
+    return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter, logger)

+ 32 - 2
module/config/config.py

@@ -158,6 +158,9 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         except:
             logger.exception(f'have no arg {task}.{group}.{argument}')
 
+    def reload(self):
+        self.model = ConfigModel(config_name=self.config_name)
+
     def save(self) -> None:
         """
         保存配置文件
@@ -209,6 +212,7 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         if self.pending_task:
             logger.info(f"Pending tasks: {[f.command for f in self.pending_task]}")
             task = self.pending_task[0]
+            self.task = task
             logger.attr("Task", task)
             return task
 
@@ -224,6 +228,29 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
             logger.critical("Please enable at least one task")
             raise RequestHumanTakeover
 
+    def get_schedule_data(self) -> dict[str, dict]:
+        """
+        获取调度器的数据, 但是你必须使用update_scheduler来更新信息
+        :return:
+        """
+        running = {}
+        if self.task is not None and self.task.next_run < datetime.now():
+            running = {"name": self.task.command, "next_run": str(self.task.next_run)}
+
+        pending = []
+        for p in self.pending_task[1:]:
+            item = {"name": p.command, "next_run": str(p.next_run)}
+            pending.append(item)
+
+        waiting = []
+        for w in self.waiting_task:
+            item = {"name": w.command, "next_run": str(w.next_run)}
+            waiting.append(item)
+
+        data = {"running": running, "pending": pending, "waiting": waiting}
+        return data
+
+
     def task_call(self, task: str=None, force_call=True):
         """
         回调任务,这会是在任务结束后调用
@@ -259,6 +286,7 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         :param finish: 是完成任务后的时间为基准还是开始任务的时间为基准
         :return:
         """
+        self.reload()
         # 任务预处理
         if not task:
             task = self.task.command
@@ -317,7 +345,7 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         logger.info(f"Delay task `{task}` to {next_run} ({kv})")
 
         # 强制设定下一次的运行时间
-        if server and scheduler.server_update != time(hour=9):
+        if server and hasattr(scheduler, 'server_update') and scheduler.server_update != time(hour=9):
             next_run = parse_tomorrow_server(scheduler.server_update)
 
 
@@ -325,11 +353,13 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         self.lock_config.acquire()
         try:
             scheduler.next_run = next_run
+
+            self.save()
         finally:
             self.lock_config.release()
         # 设置
         logger.attr(f'{task}.scheduler.next_run', next_run)
-        self.save()
+
 
     @cached_property
     def notifier(self):

+ 2 - 2
module/config/config_manual.py

@@ -9,7 +9,7 @@ class ConfigManual:
 
     SCHEDULER_PRIORITY = """
         Restart
-        >KekkaiUtilize > KekkaiActivation > DemonEncounter
+        > KekkaiUtilize > KekkaiActivation > DemonEncounter
         > AreaBoss > GoldYoukai > ExperienceYoukai > Nian > Tako > RealmRaid > RyouToppa > DailyTrifles > Exploration
         > Hunt 
         > Orochi > OrochiMoans > OrochiJudgement > Sougenbi > FallenSun > EternitySea
@@ -18,7 +18,7 @@ class ConfigManual:
         > TrueOrochi > RichMan
         > CollectiveMissions
         > Pets > TalismanPass > SoulsTidy > Delegation
-        > Secret > WeeklyTrifles > MysteryShop > Duel
+        > Secret > WeeklyTrifles > MysteryShop > Duel > MetaDemon
         """
 
     DEVICE_OVER_HTTP = False

+ 10 - 2
module/config/config_menu.py

@@ -8,6 +8,7 @@ from pydantic import BaseModel, ValidationError, validator, Field
 
 from module.config.utils import *
 
+
 class ConfigMenu:
     # 手动的代码配置菜单
     def __init__(self) -> None:
@@ -24,14 +25,14 @@ class ConfigMenu:
                                    'TalismanPass', 'DemonEncounter', 'Pets', 'SoulsTidy', 'Delegation', 'WantedQuests',
                                    'Tako']
         # 很肝的任务
-        self.menu["Liver Emperor Exclusive"] = ['BondlingFairyland', 'EvoZone', 'GoryouRealm', 'Exploration']
+        self.menu["Liver Emperor Exclusive"] = ['BondlingFairyland', 'EvoZone', 'GoryouRealm', 'Exploration',]
         # 阴阳寮
         self.menu["Guild"] = ['KekkaiUtilize', 'KekkaiActivation', 'RealmRaid', 'RyouToppa', 'CollectiveMissions',
                               'Hunt']
         # 每周任务
         self.menu["Weekly Task"] = ['TrueOrochi', 'RichMan', 'Secret', 'WeeklyTrifles', 'MysteryShop', 'Duel']
         # 活动的任务
-        self.menu["Activity Task"] = ['ActivityShikigami']
+        self.menu["Activity Task"] = ['ActivityShikigami', 'MetaDemon']
         # 开发工具
         self.menu["Tools"] = ['Image Rule', 'Ocr Rule', 'Click Rule', 'Long Click Rule', 'Swipe Rule', 'List Rule']
 
@@ -43,6 +44,13 @@ class ConfigMenu:
         """
         return json.dumps(self.menu, ensure_ascii=False, sort_keys=False, default=str)
 
+    @cached_property
+    def gui_menu_list(self) -> dict:
+        del self.menu['TaskList']
+        del self.menu['Tools']
+        return self.menu
+
+
 if __name__ == "__main__":
     try:
         m = ConfigMenu()

+ 122 - 3
module/config/config_model.py

@@ -1,7 +1,10 @@
 # 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
@@ -10,7 +13,7 @@ from module.config.utils import *
 from module.logger import logger
 
 # 导入配置的Python文件
-from tasks.Component.config_base import ConfigBase
+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
@@ -43,6 +46,7 @@ from tasks.Hunt.config import Hunt
 
 # 这一部分是活动的配置-----------------------------------------------------------------------------------------------------
 from tasks.ActivityShikigami.config import ActivityShikigami
+from tasks.MetaDemon.config import MetaDemon
 # ----------------------------------------------------------------------------------------------------------------------
 
 # 肝帝专属---------------------------------------------------------------------------------------------------------------
@@ -94,6 +98,7 @@ class ConfigModel(ConfigBase):
 
     # 这些是活动的
     activity_shikigami: ActivityShikigami = Field(default_factory=ActivityShikigami)
+    meta_demon: MetaDemon = Field(default_factory=MetaDemon)
 
     # 这些是肝帝专属
     bondling_fairyland: BondlingFairyland = Field(default_factory=BondlingFairyland)
@@ -265,6 +270,121 @@ class ConfigModel(ConfigBase):
         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:
@@ -274,7 +394,6 @@ if __name__ == "__main__":
         c = ConfigModel()
 
     # c.save()
-    print(c.gui_args('Script'))
-    # print(c.deep_get(c, 'area_boss.scheduler.success_interval'))
+    print(c.script_task('Orochi'))
 
 

+ 1 - 0
module/config/utils.py

@@ -166,6 +166,7 @@ def convert_to_underscore(text: str) -> str:
     if '_' in text:
         # If text already contains underscore, assume it's in the correct format
         return text
+    text = text.replace(' ', '')
 
     result = ''
     for i, char in enumerate(text):

+ 2 - 7
module/device/device.py

@@ -85,13 +85,8 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
 
         try:
             super().screenshot()
-        except RequestHumanTakeover:
-            if not self.ascreencap_available:
-                logger.error('aScreenCap unavailable on current device, fallback to auto')
-                self.run_simple_screenshot_benchmark()
-                super().screenshot()
-            else:
-                raise
+        except RequestHumanTakeover as e:
+            raise RequestHumanTakeover
 
         if self.handle_night_commission():
             super().screenshot()

+ 2 - 2
module/device/method/droidcast.py

@@ -292,5 +292,5 @@ class DroidCast(Uiautomator2):
 
 if __name__ == '__main__':
     dc = DroidCast(config='oas1')
-    cv2.imshow("iiii", dc.screenshot_uiautomator2())
-    cv2.waitKey(0)
+    cv2.imshow("iiii", dc.screenshot_droidcast())
+    cv2.waitKey(0)

+ 3 - 3
module/gui/qml/MainWindow.qml

@@ -68,9 +68,9 @@ FluWindow {
 //            process_manager.create_all()
         }
     }
-    Notity{
-        id: notity
-    }
+//    Notity{
+//        id: notity
+//    }
 
     FluNavigationView{
         id:nav_view

+ 108 - 146
module/logger.py

@@ -37,86 +37,81 @@ class RichFileHandler(RichHandler):
     # Rename
     pass
 
-class LogStream(TextIOBase):
-    def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
-        super().__init__(*args, **kwargs)
-        self._func = func
-
-    def write(self, msg: str) -> int:
-        if isinstance(msg, bytes):
-            msg = msg.decode("utf-8")
-        self._func(msg)
-        return len(msg)
-    
-class RichStreamHandler(RichHandler):
-    pass
 
 
-class RichRenderableHandler(RichHandler):
-    """
-    Pass renderable into a function
-    主要是传入一个回调函数
-    """
-
-    def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
-        super().__init__(*args, **kwargs)
-        self._func = func
-
-    def emit(self, record: logging.LogRecord) -> None:
-        message = self.format(record)
-        tb = None
-        if (
-            self.rich_tracebacks
-            and record.exc_info
-            and record.exc_info != (None, None, None)
-        ):
-            exc_type, exc_value, exc_traceback = record.exc_info
-            traceback.print_tb(exc_traceback)
-            self._func(exc_traceback)
-            assert exc_type is not None
-            assert exc_value is not None
-            tb = Traceback.from_exception(
-                exc_type,
-                exc_value,
-                exc_traceback,
-                width=self.tracebacks_width,
-                extra_lines=self.tracebacks_extra_lines,
-                theme=self.tracebacks_theme,
-                word_wrap=self.tracebacks_word_wrap,
-                show_locals=self.tracebacks_show_locals,
-                locals_max_length=self.locals_max_length,
-                locals_max_string=self.locals_max_string,
-            )
-            # 这个好理解转化为特定格式, getMessage()返回寸str
-            message = record.getMessage()
-            if self.formatter:
-                record.message = record.getMessage()
-                formatter = self.formatter
-                if hasattr(formatter, "usesTime") and formatter.usesTime():
-                    record.asctime = formatter.formatTime(
-                        record, formatter.datefmt)
-                message = formatter.formatMessage(record)
-
-        # 这个message_renderable是一个Text对象
-        message_renderable = self.render_message(record, message)
-        log_renderable: ConsoleRenderable = self.render(
-            record=record, traceback=tb, message_renderable=message_renderable
-        )
-
-        # msg2 = Text.from_markup(message).markup
-
-        # 这个message_renderable是一个Text对象
-        # traceback是表示异常的对象
-        # Directly put renderable into function
-        self._func(log_renderable)
-
-    def handle(self, record: logging.LogRecord) -> bool:
-        if not self._func:
-            return True
-        super().handle(record)
-
+#
+# class FlutterHandler(RichHandler):
+#     """
+#     Pass renderable into a function
+#     主要是传入一个回调函数
+#     """
+#
+#     def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
+#         super().__init__(*args, **kwargs)
+#         self._func = func
+#
+#     def emit(self, record: logging.LogRecord) -> None:
+#         message = self.format(record)
+#         tb = None
+#         if (
+#             self.rich_tracebacks
+#             and record.exc_info
+#             and record.exc_info != (None, None, None)
+#         ):
+#             exc_type, exc_value, exc_traceback = record.exc_info
+#             traceback.print_tb(exc_traceback)
+#             self._func(exc_traceback)
+#             assert exc_type is not None
+#             assert exc_value is not None
+#             tb = Traceback.from_exception(
+#                 exc_type,
+#                 exc_value,
+#                 exc_traceback,
+#                 width=self.tracebacks_width,
+#                 extra_lines=self.tracebacks_extra_lines,
+#                 theme=self.tracebacks_theme,
+#                 word_wrap=self.tracebacks_word_wrap,
+#                 show_locals=self.tracebacks_show_locals,
+#                 locals_max_length=self.locals_max_length,
+#                 locals_max_string=self.locals_max_string,
+#             )
+#             # 这个好理解转化为特定格式, getMessage()返回寸str
+#             message = record.getMessage()
+#             if self.formatter:
+#                 record.message = record.getMessage()
+#                 formatter = self.formatter
+#                 if hasattr(formatter, "usesTime") and formatter.usesTime():
+#                     record.asctime = formatter.formatTime(
+#                         record, formatter.datefmt)
+#                 message = formatter.formatMessage(record)
+#
+#         # 这个message_renderable是一个Text对象
+#         message_renderable = self.render_message(record, message)
+#         log_renderable: ConsoleRenderable = self.render(
+#             record=record, traceback=tb, message_renderable=message_renderable
+#         )
+#
+#         # msg2 = Text.from_markup(message).markup
+#
+#         # 这个message_renderable是一个Text对象
+#         # traceback是表示异常的对象
+#         # Directly put renderable into function
+#         if log_renderable:
+#             if log_renderable is not str:
+#                 print(f'-------------------------------------------------------log is not str{log_renderable}')
+#                 log_renderable = str(log_renderable)
+#             self._func(log_renderable)
+#
+#     def handle(self, record: logging.LogRecord) -> bool:
+#         if not self._func:
+#             return True
+#         super().handle(record)
+
+class FlutterHandler(RichHandler):
+    # Rename
+    pass
 
-class HTMLConsole(Console):
+class FlutterConsole(Console):
     """
     Force full feature console
     but not working lol :(
@@ -133,35 +128,16 @@ class HTMLConsole(Console):
             is_terminal=False,
         )
 
+class FlutterLogStream(TextIOBase):
+    def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
+        super().__init__(*args, **kwargs)
+        self._func = func
 
-class Highlighter(RegexHighlighter):
-    base_style = 'web.'
-    highlights = [
-        # (r'(?P<datetime>(\d{2}|\d{4})(?:\-)?([0]{1}\d{1}|[1]{1}[0-2]{1})'
-        #  r'(?:\-)?([0-2]{1}\d{1}|[3]{1}[0-1]{1})(?:\s)?([0-1]{1}\d{1}|'
-        #  r'[2]{1}[0-3]{1})(?::)?([0-5]{1}\d{1})(?::)?([0-5]{1}\d{1}).\d+\b)'),
-        (r'(?P<time>([0-1]{1}\d{1}|[2]{1}[0-3]{1})(?::)?'
-         r'([0-5]{1}\d{1})(?::)?([0-5]{1}\d{1})(.\d+\b))'),
-        r"(?P<brace>[\{\[\(\)\]\}])",
-        r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b",
-        r"(?P<path>(([A-Za-z]\:)|.)?\B([\/\\][\w\.\-\_\+]+)*[\/\\])(?P<filename>[\w\.\-\_\+]*)?",
-        # r"(?<![\\\w])(?P<str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
-    ]
-
-
-WEB_THEME = Theme({
-    "web.brace": Style(bold=True),
-    "web.bool_true": Style(color="bright_green", italic=True),
-    "web.bool_false": Style(color="bright_red", italic=True),
-    "web.none": Style(color="magenta", italic=True),
-    "web.path": Style(color="magenta"),
-    "web.filename": Style(color="bright_magenta"),
-    "web.str": Style(color="green", italic=False, bold=False),
-    "web.time": Style(color="cyan"),
-    "rule.text": Style(bold=True),
-})
-
-
+    def write(self, msg: str) -> int:
+        if isinstance(msg, bytes):
+            msg = msg.decode("utf-8")
+        self._func(msg)
+        return len(msg)
 
 
 def show_handlers(handlers):
@@ -193,14 +169,9 @@ file_formatter = logging.Formatter(
     fmt='%(asctime)s.%(msecs)03d | %(levelname)8s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
 console_formatter = logging.Formatter(
     fmt='%(asctime)s.%(msecs)03d │ %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
-web_formatter = logging.Formatter(
-    fmt='%(asctime)s.%(msecs)03d │ %(message)s', datefmt='%H:%M:%S')
+flutter_formatter = logging.Formatter(
+    fmt='| %(asctime)s.%(msecs)03d | %(message)08s', datefmt='%H:%M:%S')
 
-# Add console logger
-# console = logging.StreamHandler(stream=sys.stdout)
-# console.setFormatter(formatter)
-# console.flush = sys.stdout.flush
-# logger.addHandler(console)
 
 # Add rich console logger
 # ======================================================================================================================
@@ -219,27 +190,9 @@ logger.addHandler(console_hdlr)
 
 # Ensure running in Alas root folder
 os.chdir(os.path.join(os.path.dirname(__file__), '../'))
-
 # Add file logger
 pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
-# 这个函数貌似没有用到
-def _set_file_logger(name=pyw_name):
-    if '_' in name:
-        name = name.split('_', 1)[0]
-    log_file = f'./log/{datetime.date.today()}_{name}.txt'
-    try:
-        file = logging.FileHandler(log_file, encoding='utf-8')
-    except FileNotFoundError:
-        os.mkdir('./log')
-        file = logging.FileHandler(log_file, encoding='utf-8')
-    file.setFormatter(file_formatter)
-
-    logger.handlers = [h for h in logger.handlers if not isinstance(
-        h, (logging.FileHandler, RichFileHandler))]
-    logger.addHandler(file)
-    logger.log_file = log_file
-
 
 def set_file_logger(name=pyw_name):
     if '_' in name:
@@ -255,7 +208,7 @@ def set_file_logger(name=pyw_name):
         file=file,
         no_color=True,
         highlight=False,
-        width=120,
+        width=80,
     )
 
     hdlr = RichFileHandler(
@@ -276,20 +229,19 @@ def set_file_logger(name=pyw_name):
     logger.addHandler(hdlr)
     logger.log_file = log_file
 
-# 给web设置
+# 给flutter设置
 def set_func_logger(func):
-
-    stream = LogStream(func=func)
-    file_console = Console(
+    stream = FlutterLogStream(func=func)
+    stream_console = Console(
         file=stream,
         force_terminal=False,
         force_interactive=False,
         no_color=True,
         highlight=False,
-        width=120,
+        width=80,
     )
-    hdlr = RichStreamHandler(
-        console=file_console,
+    hdlr = FlutterHandler(
+        console=stream_console,
         show_path=False,
         show_time=False,
         show_level=True,
@@ -298,7 +250,7 @@ def set_func_logger(func):
         tracebacks_extra_lines=3,
         highlighter=NullHighlighter(),
     )
-    hdlr.setFormatter(web_formatter)
+    hdlr.setFormatter(flutter_formatter)
     logger.addHandler(hdlr)
 
 
@@ -329,9 +281,9 @@ def _get_renderables(
 
 def print(*objects: ConsoleRenderable, **kwargs):
     for hdlr in logger.handlers:
-        if isinstance(hdlr, RichRenderableHandler):
+        if isinstance(hdlr, FlutterHandler):
             for renderable in _get_renderables(hdlr.console, *objects, **kwargs):
-                hdlr._func(renderable)
+                hdlr.console.file._func(str(renderable))
         elif isinstance(hdlr, RichHandler):
             hdlr.console.print(*objects)
 
@@ -342,12 +294,26 @@ class GuiRule(Rule):
         options.max_width = 80
         return super().__rich_console__(console, options)
 
+    def __str__(self):
+        total_width = 80
+        cell_len = len(self.title) + 2
+        aside_len = (total_width - cell_len) // 2
+        left = self.characters * aside_len
+        right = self.characters * (total_width - cell_len - aside_len)
+        if self.title:
+            space = ' '
+        else:
+            space = self.characters
+        return f"{left}{space}{self.title}{space}{right}\n"
+
+    def __repr__(self):
+        return self.__str__()
+
 def rule(title="", *, characters="─", style="rule.line", end="\n", align="center"):
     rule = GuiRule(title=title, characters=characters,
                 style=style, end=end)
     print(rule)
 
-
 def hr(title, level=3):
     title = str(title).upper()
     if level == 1:
@@ -363,18 +329,15 @@ def hr(title, level=3):
         logger.rule(title, characters='─')
         logger.rule(characters='═')
 
-
 def attr(name, text):
     logger.info('[%s] %s' % (str(name), str(text)))
 
-
 def attr_align(name, text, front='', align=22):
     name = str(name).rjust(align)
     if front:
         name = front + name[len(front):]
     logger.info('%s: %s' % (name, str(text)))
 
-
 def show():
     logger.info('INFO')
     logger.warning('WARNING')
@@ -393,7 +356,6 @@ def show():
     raise Exception("Exception")
     # Line below exception
 
-
 def error_convert(func):
     def error_wrapper(msg, *args, **kwargs):
         if isinstance(msg, Exception):

+ 2 - 2
module/notify/notify.py

@@ -21,11 +21,11 @@ class Notifier:
 
         if not self.enable:
             return
+        config = {}
         try:
-            config = {}
             for item in yaml.safe_load_all(_config):
                 config.update(item)
-        except Exception:
+        except Exception as e:
             logger.error("Fail to load onepush config, skip sending")
             return
         self.config = config

+ 1 - 1
module/ocr/sub_ocr.py

@@ -158,7 +158,7 @@ class Duration(Single):
     def after_process(self, result):
         result = super().after_process(result)
         result = result.replace('I', '1').replace('D', '0').replace('S', '5')
-        result = result.replace('B', '8')
+        result = result.replace('B', '8').replace(':', ':')
         return result
 
     @staticmethod

+ 5 - 0
module/server/__init__.py

@@ -0,0 +1,5 @@
+# This must be the first to import
+from module.logger import logger  # Change folder
+import deploy.logger
+
+deploy.logger.logger = logger

+ 65 - 0
module/server/app.py

@@ -0,0 +1,65 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import argparse
+from fastapi import FastAPI
+
+from module.logger import logger
+
+from module.server.home_router import home_app
+from module.server.script_router import script_app
+
+app = FastAPI(
+    title='OAS',
+    description='OAS web service',
+    version='0.0.0',
+)
+app.include_router(home_app)
+app.include_router(script_app)
+
+@app.on_event("startup")
+async def startup_event():
+    logger.info('OAS web service startup done')
+    pass
+
+@app.on_event("shutdown")
+async def shutdown_event():
+    logger.info('OAS web service shutdown done')
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+def fastapi_app():
+    parser = argparse.ArgumentParser(description="OAS web service")
+    parser.add_argument(
+        "-k", "--key", type=str, help="Password of OAS. No password by default"
+    )
+    parser.add_argument(
+        "--cdn",
+        action="store_true",
+        help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.",
+    )
+    parser.add_argument(
+        "--run",
+        nargs="+",
+        type=str,
+        help="Run OAS by config names on startup",
+    )
+    args, _ = parser.parse_known_args()
+
+
+    return app

+ 57 - 0
module/server/config.py

@@ -0,0 +1,57 @@
+"""
+Copy from https://github.com/LmeSzinc/AzurLaneAutoScript
+"""
+from typing import Optional, Union
+from filelock import FileLock
+
+from deploy.config import DeployConfig as _DeployConfig
+from deploy.utils import *
+
+
+def poor_yaml_read_with_lock(file):
+    if not os.path.exists(file):
+        return {}
+
+    with FileLock(f"{file}.lock"):
+        return poor_yaml_read(file)
+
+
+def poor_yaml_write_with_lock(data, file, template_file=DEPLOY_TEMPLATE):
+    folder = os.path.dirname(file)
+    if not os.path.exists(folder):
+        os.mkdir(folder)
+
+    with FileLock(f"{file}.lock"):
+        with FileLock(f"{DEPLOY_TEMPLATE}.lock"):
+            return poor_yaml_write(data, file, template_file)
+
+
+class DeployConfig(_DeployConfig):
+    def show_config(self):
+        pass
+
+    def read(self):
+        """
+        Read and update deploy config, copy `self.configs` to properties.
+        """
+        self.config = poor_yaml_read_with_lock(DEPLOY_TEMPLATE)
+        self.config.update(poor_yaml_read_with_lock(self.file))
+
+        for key, value in self.config.items():
+            if hasattr(self, key):
+                super().__setattr__(key, value)
+
+    def write(self):
+        """
+        Write `self.config` into deploy config.
+        """
+        poor_yaml_write_with_lock(self.config, self.file)
+
+    def __setattr__(self, key: str, value):
+        """
+        Catch __setattr__, copy to `self.config`, write deploy config.
+        """
+        super().__setattr__(key, value)
+        if key[0].isupper() and key in self.config:
+            self.config[key] = value
+            self.write()

+ 94 - 0
module/server/config_manager.py

@@ -0,0 +1,94 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import re
+from pathlib import Path
+
+from module.logger import logger
+
+class ConfigManager:
+
+    @staticmethod
+    def all_script_files() -> list[str]:
+        """
+        获取所有的脚本文件 除了tmplate
+        :return: ['oas1', 'oas2']
+        """
+        # 获取某个路径的所有json文件名
+        config_path = Path.cwd() / 'config'
+        json_files = config_path.glob('*.json')
+        result = []
+        for json in json_files:
+            if json.stem == 'template':
+                continue
+            result.append(json.stem)
+        if len(result) == 0:
+            # 如果没有脚本文件 则创建一个
+            ConfigManager.copy(file='oas1', template='template')
+            result.append('oas1')
+        return result
+
+    @staticmethod
+    def all_json_file() -> list:
+        """
+        获取所有的json文件
+        :return: ['oas1', 'oas2']
+        """
+        # 获取某个路径的所有json文件名
+        config_path = Path.cwd() / 'config'
+        json_files = config_path.glob('*.json')
+        result = []
+        for json in json_files:
+            if json.stem == 'template':
+                result.insert(0, json.stem)
+            else:
+                result.append(json.stem)
+        return result
+
+    @staticmethod
+    def copy(file: str, template: str = 'template') -> None:
+        """
+        复制一个配置文件
+        :param file:  不带json后缀
+        :param template:
+        :return:
+        """
+        config_path = Path.cwd() / 'config'
+        template_path = config_path / f'{template}.json'
+        file_path = config_path / f'{file}.json'
+        if file_path.exists():
+            logger.error(f'{file_path} is exists')
+            return
+
+        with open(template_path, 'r', encoding='utf-8') as f:
+            template_content = f.read()
+        with open(file_path, 'w', encoding='utf-8') as f:
+            f.write(template_content)
+        logger.info(f'copy {template_path} to {file_path}')
+
+
+    @staticmethod
+    def generate_script_name() -> str:
+        """
+        生成一个新的配置的名字
+        :return:
+        """
+        all_script_files = ConfigManager.all_script_files()
+        if not all_script_files:
+            return 'oas1'
+
+        script_numbers = []
+        for script_file in all_script_files:
+            match = re.search(r'\d+', script_file)
+            if match:
+                script_number = int(match.group())
+                script_numbers.append(script_number)
+
+        if not script_numbers:
+            return 'oas1'
+        script_numbers.sort()
+        new_script_number = script_numbers[-1] + 1
+        return f'oas{new_script_number}'
+
+
+

+ 62 - 0
module/server/home_router.py

@@ -0,0 +1,62 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from fastapi import APIRouter
+
+from module.logger import logger
+from module.server.main_manager import MainManager
+from module.server.updater import Updater
+
+home_app = APIRouter(
+    prefix="/home",
+    tags=["home"],
+)
+
+
+@home_app.get('/test')
+async def home_test():
+    return {'message': 'test'}
+
+
+#  gcc -Wall -pedantic -shared -fPIC -o group_work.so group_work.c -lwiringPi
+@home_app.get('/home_menu')
+async def home_menu():
+    return {'Home': [], 'Updater': [], 'Tool': []}
+
+
+@home_app.post('/notify_test')
+async def notify_test(setting: str, title: str, content: str):
+    from module.notify.notify import Notifier
+    try:
+        notifier = Notifier(setting, True)
+        if notifier.push(title=title, content=content):
+            del notifier
+            return True
+        else:
+            del notifier
+            return False
+    except Exception as e:
+        logger.exception(e)
+        return str(e)
+
+
+@home_app.get('/kill_server')
+async def kill_server():
+    MainManager.signal_kill_server = True
+    return 'success'
+
+
+@home_app.get('/update_info')
+async def update_info():
+    try:
+        updater = Updater()
+        result = {'is_update': updater.check_update(),
+                  'branch': updater.current_branch(),
+                  'current_commit': updater.current_commit(),
+                  'latest_commit': updater.latest_commit(),
+                  'commit': updater.get_commit(n=15),
+                  }
+        return result
+    except Exception as e:
+        logger.error(e)
+        return None

+ 101 - 0
module/server/main_manager.py

@@ -0,0 +1,101 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# 主进程的管理
+# github https://github.com/runhey
+import asyncio
+import sys
+import os
+import signal
+from asyncio.tasks import Task
+from threading import Thread
+
+from module.logger import logger
+from module.config.config import Config
+from module.server.script_process import ScriptProcess, ScriptState
+from module.server.config_manager import ConfigManager
+
+
+class MainManager(ConfigManager):
+    # config_cache: Config = None  # 缓存当前切换的配置
+    script_process: dict[str: ScriptProcess] = None  # 脚本进程
+    push_data_thread: Thread = None  # 数据推送线程
+    signal_kill_server: bool = False
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.script_process: dict[str: ScriptProcess] = {}  # 脚本进程
+        self._all_script_files = self.all_script_files()
+        for script_name in self._all_script_files:
+            self.script_process[script_name] = ScriptProcess(script_name)
+        self.push_data_thread = Thread(target=self.start_push_data_thread, daemon=True)
+        self.push_data_thread.start()
+
+    # def ensure_config_cache(self, config_name: str, reload: bool = False):
+    #     if self.config_cache is None:
+    #         if config_name not in self._all_script_files:
+    #             logger.warning(f'[{config_name}] script file does not exist')
+    #             return None
+    #         self.config_cache = Config(config_name)
+    #     elif self.config_cache.config_name != config_name:
+    #         self.config_cache = Config(config_name)
+    #     if reload:
+    #         self.config_cache = Config(config_name)
+    #     return self.config_cache
+
+    def add_script_file(self, file_name: str):
+        # 当你添加了新的脚本文件后,需要添加缓存的列表
+        if file_name in self._all_script_files:
+            logger.warning(f'[{file_name}] script file already exists')
+            return
+        self._all_script_files = self.all_script_files()
+        self.script_process[file_name] = ScriptProcess(file_name)
+
+    def start_push_data_thread(self):
+        try:
+            asyncio.run(self.push_data_handle())
+        except SystemExit as e:
+            logger.info('Kill the main process')
+            # sys.exit(0)
+            try:
+                os.kill(os.getpid(), signal.SIGILL)
+                print("Process killed successfully.")
+            except OSError:
+                print("Failed to kill the process.")
+
+        except Exception as e:
+            logger.exception(e)
+            sys.exit(0)
+
+    async def push_data_handle(self):
+        tasks: dict[str, Task] = {}
+        from asyncio import sleep
+        while 1:
+            await sleep(3)
+            if MainManager.signal_kill_server:  # 结束所有的进程
+                logger.info('Kill all server')
+                for script_p in self.script_process.values():
+                    await script_p.stop()
+                logger.info('Kill push data thread')
+                sys.exit(0)
+            # logger.info(asyncio.all_tasks())
+            for name, script_p in self.script_process.items():
+                # 遍历所有的
+                # 如果 这个进程未激活 跳过
+                # 如果 已经存在了 对应的协程 跳过
+                # 如果这个进程异常/运行中 那这个协程也应该存在
+                # logger.info(f'检测脚本的process: {name}')
+                if script_p.state == ScriptState.INACTIVE:
+                    continue
+                coroutine_state_name = f'coroutine_state_{name}'
+                if coroutine_state_name not in tasks:
+                    tasks[coroutine_state_name] = asyncio.create_task(script_p.coroutine_broadcast_state(),
+                                                                      name=coroutine_state_name)
+                coroutine_log_name = f'coroutine_log_{name}'
+                if coroutine_log_name not in tasks:
+                    tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
+                                                                    name=coroutine_log_name)
+
+    @staticmethod
+    def config_cache(name: str) -> Config:
+        return Config(name)
+

+ 157 - 0
module/server/script_process.py

@@ -0,0 +1,157 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# 脚本进程
+# github https://github.com/runhey
+import multiprocessing
+from asyncio import QueueEmpty, CancelledError, sleep
+from enum import Enum
+
+from module.logger import logger
+
+from module.server.script_websocket import ScriptWSManager
+
+class ScriptState(int, Enum):
+    INACTIVE = 0
+    RUNNING = 1
+    WARNING = 2
+    UPDATING = 3
+
+class ScriptProcess(ScriptWSManager):
+
+    def __init__(self, config_name: str) -> None:
+        super().__init__()
+        self.config_name = config_name  # config_name
+        self.log_pipe_out, self.log_pipe_in = multiprocessing.Pipe(False)
+        self.state_queue = multiprocessing.Queue()
+        self.state: ScriptState = ScriptState.INACTIVE
+        self._process = None
+
+
+
+
+    async def start(self):
+        self.state = ScriptState.RUNNING
+        await self.broadcast_state({"state": self.state})
+        if self._process:
+            logger.warning(f'Script {self.config_name} is initialized')
+        if self._process and self._process.is_alive():
+            logger.warning(f'Script {self.config_name} is already running and first stop it')
+            self.stop()
+        self._process = multiprocessing.Process(target=func,
+                                                args=(self.config_name, self.state_queue, self.log_pipe_in,),
+                                                name=self.config_name,
+                                                daemon=True)
+        self._process.start()
+
+
+    async def stop(self):
+        self.state = ScriptState.INACTIVE
+        await self.broadcast_state({"state": self.state})
+        if self._process is None:
+            logger.warning(f'Script {self.config_name} process is removed')
+            return
+        if not self._process.is_alive():
+            logger.warning(f'Script {self.config_name} is not running')
+            return
+        self._process.terminate()
+        self._process = None
+
+    async def coroutine_broadcast_state(self):
+        try:
+            while 1:
+                if self.state == ScriptState.INACTIVE:
+                    await sleep(1)
+                    continue
+                await sleep(0.1)
+                try:
+                    if self.state_queue.empty():
+                        await sleep(1)
+                        continue
+                    data = self.state_queue.get_nowait()
+                    if not data:
+                        await sleep(0.5)
+                        continue
+                    if 'state' in data and data['state'] == ScriptState.WARNING:
+                        self.state = ScriptState.WARNING
+                    await self.broadcast_state(data)
+                except QueueEmpty as e:
+                    logger.warning(f'QueueEmpty: {e}')
+                    await sleep(0.5)
+                    continue
+                except Exception as e:
+                    logger.error(f'Error: {e}')
+                    continue
+        except CancelledError as e:
+            logger.warning(f'{self.config_name} state coroutine is cancelled')
+            return
+
+    async def coroutine_broadcast_log(self):
+        try:
+            while 1:
+                if self.state == ScriptState.INACTIVE:
+                    await sleep(1)
+                    continue
+                await sleep(0.05)
+                try:
+                    if not self.log_pipe_out.poll():
+                        await sleep(0.3)
+                        continue
+                    log = self.log_pipe_out.recv()
+                    if not log:
+                        await sleep(0.5)
+                        continue
+                    await self.broadcast_log(log)
+                except EOFError as e:
+                    await sleep(0.5)
+                    logger.warning(f'EOFError: {e}')
+                    continue
+                except Exception as e:
+                    logger.error(f'Log Error: {e}')
+                    continue
+        except CancelledError as e:
+            logger.warning(f'{self.config_name} log coroutine is cancelled')
+            return
+
+
+def func(config: str, state_queue: multiprocessing.Queue, log_pipe_in) -> None:
+
+    def start_log() -> None:
+        try:
+            from module.logger import set_file_logger, set_func_logger
+            set_file_logger(name=config)
+            set_func_logger(log_pipe_in.send)
+        except Exception as e:
+            logger.exception(f'Start log error')
+            logger.error(f'Error: {e}')
+            raise
+    start_log()
+    import time
+    try:
+        # while 1:
+        #     time.sleep(1)
+        #     logger.info(f'Script {config} is running')
+        #     state_queue.put({"state": ScriptState.RUNNING})
+        from script import Script
+        script = Script(config_name=config)
+        script.state_queue = state_queue
+        script.loop()
+    except SystemExit as e:
+        logger.info(f'Script {config} process exit')
+        logger.error(f'Error: {e}')
+        state_queue.put({"state": ScriptState.WARNING})
+        time.sleep(0.1)
+        exit(-1)
+    except Exception as e:
+        logger.exception(f'Run script {config} error')
+        logger.error(f'Error: {e}')
+        raise
+
+
+if __name__ == '__main__':
+    p = ScriptProcess('oas1')
+    p.start()
+    from time import sleep
+    sleep(10)
+    logger.info(p._process.exitcode)
+
+

+ 168 - 0
module/server/script_router.py

@@ -0,0 +1,168 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import asyncio
+from fastapi import APIRouter, HTTPException
+from fastapi.responses import StreamingResponse
+from fastapi import WebSocket, WebSocketDisconnect
+from datetime import datetime
+from module.config.config import Config
+
+from module.logger import logger
+from module.server.main_manager import MainManager
+from module.server.script_process import ScriptProcess
+
+from tasks.Component.config_base import TimeDelta
+
+
+script_app = APIRouter()
+mm = MainManager()
+
+@script_app.get('/test')
+async def script_test():
+    return 'success'
+
+@script_app.get('/script_menu')
+async def script_menu():
+    return mm.config_cache('template').gui_menu_list
+# ----------------------------------   配置文件管理   ----------------------------------
+@script_app.get('/config_list')
+async def config_list():
+    return mm.all_script_files()
+
+@script_app.post('/config_copy')
+async def config_copy(file: str, template: str = 'template'):
+    mm.copy(file, template)
+    return mm.all_script_files()
+
+@script_app.get('/config_new_name')
+async def config_new_name():
+    return mm.generate_script_name()
+
+@script_app.get('/config_all')
+async def config_all():
+    return mm.all_json_file()
+
+
+# ---------------------------------   脚本实例管理   ----------------------------------
+@script_app.get('/{script_name}/start')
+async def script_start(script_name: str):
+    if script_name not in mm.script_process:
+        mm.script_process[script_name] = ScriptProcess(script_name)
+    mm.script_process[script_name].start()
+    return
+
+@script_app.get('/{script_name}/stop')
+async def script_stop(script_name: str):
+    if script_name not in mm.script_process:
+        logger.warning(f'[{script_name}] script process does not exist')
+        return
+    mm.script_process[script_name].stop()
+    return
+
+@script_app.get('/{script_name}/{task}/args')
+async def script_task(script_name: str, task: str):
+    return mm.config_cache(script_name).model.script_task(task)
+
+@script_app.put('/{script_name}/{task}/{group}/{argument}/value')
+async def script_task(script_name: str, task: str, group: str, argument: str, types: str, value):
+    try:
+        match types:
+            case 'integer':
+                value = int(value)
+            case 'number':
+                value = float(value)
+            case 'boolean':
+                if isinstance(value, str):
+                    logger.warning(f'[{script_name}] script argument {argument} value is string, try to convert to bool')
+                    if value.lower() in ['true', '1']:
+                        value = True
+                    elif value.lower() in ['false', '0']:
+                        value = False
+                value = bool(value)
+            case 'string':
+                pass
+            case 'date_time':
+                value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
+            case 'time_delta':
+                # strptime 是个好东西,但是不能解析00的天数
+                day = int(value[1])
+                date_time = datetime.strptime(value[3:], '%H:%M:%S')
+                value = TimeDelta(days=day, hours=date_time.hour, minutes=date_time.minute, seconds=date_time.second)
+            case 'time':
+                value = datetime.strptime(value, '%H:%M:%S').time()
+            case _: pass
+    except Exception as e:
+        # 类型不正确
+        raise HTTPException(status_code=400, detail=f'Argument type error: {e}')
+    return mm.config_cache(script_name).model.script_set_arg(task, group, argument, value)
+
+# --------------------------------------  SSE  --------------------------------------
+@script_app.get('/{script_name}/state')
+async def script_task_state(script_name: str):
+    async def state_generate_events():
+        while True:
+            # 生成 SSE 事件数据
+            event_data = "data: Hello, SSE!\n\n"
+            yield event_data
+
+            # 模拟异步操作,可以替换为您的实际处理逻辑
+            await asyncio.sleep(1)
+
+    response = StreamingResponse(state_generate_events(), media_type="text/event-stream")
+    response.headers["Cache-Control"] = "no-cache"
+    return response
+
+@script_app.get('/{script_name}/log')
+async def script_task_log(script_name: str):
+    async def log_generate_events():
+        while True:
+            # 生成 SSE 事件数据
+            event_data = "data: log\n"
+            yield event_data
+
+            # 模拟异步操作,可以替换为您的实际处理逻辑
+            await asyncio.sleep(1)
+
+    response = StreamingResponse(log_generate_events(), media_type="text/event-stream")
+    response.headers["Cache-Control"] = "no-cache"
+    return response
+
+# -------------------------------------- websocket --------------------------------------
+
+@script_app.websocket("/ws/{script_name}")
+async def websocket_endpoint(websocket: WebSocket, script_name: str):
+    if script_name not in mm.script_process:
+        mm.script_process[script_name] = ScriptProcess(script_name)
+    script_process = mm.script_process[script_name]
+    await script_process.connect(websocket)
+    await script_process.broadcast_state({"state": script_process.state})
+    config = mm.config_cache(script_name)
+    config.get_next()
+    await script_process.broadcast_state({"schedule": config.get_schedule_data()})
+
+    try:
+        while True:
+            # 初次进入,广播state schedule
+            data = await websocket.receive_text()
+            if data == 'get_state':
+                await script_process.broadcast_state({"state": script_process.state})
+            elif data == 'get_schedule':
+                config = mm.config_cache(script_name)
+                config.get_next()
+                await script_process.broadcast_state({"schedule": config.get_schedule_data()})
+            elif data == 'start':
+                await script_process.start()
+            elif data == 'stop':
+                await script_process.stop()
+
+    except WebSocketDisconnect:
+        logger.warning(f'[{script_name}] websocket disconnect')
+        script_process.disconnect(websocket)
+
+
+
+
+
+
+

+ 38 - 0
module/server/script_websocket.py

@@ -0,0 +1,38 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+
+class ScriptWSManager:
+
+    def __init__(self):
+        self.active_connections: list[WebSocket] = []
+
+    async def connect(self, ws: WebSocket):
+        # 等待连接
+        await ws.accept()
+        self.active_connections.append(ws)
+
+    def disconnect(self, ws: WebSocket):
+        # 关闭时 移除ws对象
+        self.active_connections.remove(ws)
+
+    async def broadcast(self, message: str):
+        # 广播消息
+        for connection in self.active_connections:
+            await connection.send_text(message)
+
+    async def broadcast_state(self, data: dict):
+        # 广播自身的状态
+        for connection in self.active_connections:
+            await connection.send_json(data)
+
+    async def broadcast_log(self, log: str):
+        # 广播日志
+        for connection in self.active_connections:
+            await connection.send_text(log)
+
+
+
+
+

+ 92 - 0
module/server/setting.py

@@ -0,0 +1,92 @@
+"""
+Copy from https://github.com/LmeSzinc/AzurLaneAutoScript
+"""
+import multiprocessing
+import threading
+from multiprocessing.managers import SyncManager
+from typing import TYPE_CHECKING, Callable, Generic, TypeVar
+
+if TYPE_CHECKING:
+    from module.config.config_updater import ConfigUpdater
+    from module.server.config import DeployConfig
+
+T = TypeVar("T")
+
+
+class cached_class_property(Generic[T]):
+    """
+    Code from https://github.com/dssg/dickens
+    Add typing support
+
+    Descriptor decorator implementing a class-level, read-only
+    property, which caches its results on the class(es) on which it
+    operates.
+    Inheritance is supported, insofar as the descriptor is never hidden
+    by its cache; rather, it stores values under its access name with
+    added underscores. For example, when wrapping getters named
+    "choices", "choices_" or "_choices", each class's result is stored
+    on the class at "_choices_"; decoration of a getter named
+    "_choices_" would raise an exception.
+    """
+
+    class AliasConflict(ValueError):
+        pass
+
+    def __init__(self, func: Callable[..., T]):
+        self.__func__ = func
+        self.__cache_name__ = '_{}_'.format(func.__name__.strip('_'))
+        if self.__cache_name__ == func.__name__:
+            raise self.AliasConflict(self.__cache_name__)
+
+    def __get__(self, instance, cls=None) -> T:
+        if cls is None:
+            cls = type(instance)
+
+        try:
+            return vars(cls)[self.__cache_name__]
+        except KeyError:
+            result = self.__func__(cls)
+            setattr(cls, self.__cache_name__, result)
+            return result
+
+
+class State:
+    """
+    Shared settings
+    """
+
+    _init = False
+    _clearup = False
+
+    restart_event: threading.Event = None
+    manager: SyncManager = None
+
+    @classmethod
+    def init(cls):
+        cls.manager = multiprocessing.Manager()
+        cls._init = True
+
+    @classmethod
+    def clearup(cls):
+        cls.manager.shutdown()
+        cls._clearup = True
+
+    @cached_class_property
+    def deploy_config(self) -> "DeployConfig":
+        """
+        Returns:
+            DeployConfig:
+        """
+        from module.server.config import DeployConfig
+
+        return DeployConfig()
+
+    @cached_class_property
+    def config_updater(self) -> "ConfigUpdater":
+        """
+        Returns:
+            ConfigUpdater:
+        """
+        from module.config.config_updater import ConfigUpdater
+
+        return ConfigUpdater()

+ 130 - 0
module/server/updater.py

@@ -0,0 +1,130 @@
+import datetime
+import subprocess
+import threading
+import time
+import requests
+from typing import Generator, List, Tuple
+
+
+from deploy.config import ExecutionError
+from deploy.git import GitManager
+from deploy.pip import PipManager
+from deploy.utils import DEPLOY_CONFIG
+from module.logger import logger
+from module.base.retry import retry
+from module.server.config import DeployConfig
+
+
+class Updater(DeployConfig, GitManager, PipManager):
+    def __init__(self, file=DEPLOY_CONFIG):
+        super().__init__(file=file)
+        self.state = 0
+
+    @property
+    def delay(self):
+        self.read()
+        return int(self.CheckUpdateInterval) * 60
+
+    @property
+    def schedule_time(self):
+        self.read()
+        t = self.AutoRestartTime
+        if t is not None:
+            return datetime.time.fromisoformat(t)
+        else:
+            return None
+
+    def execute_output(self, command) -> str:
+        command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
+        log = subprocess.run(
+            command, capture_output=True, text=True, encoding="utf8", shell=True
+        ).stdout
+        return log
+
+    def get_commit(self, revision="", n=1, short_sha1=False) -> Tuple:
+        """
+        Return:
+            (sha1, author, isotime, message,)
+        """
+        ph = "h" if short_sha1 else "H"
+
+        log = self.execute_output(
+            f'"{self.git}" log {revision} --pretty=format:"%{ph}---%an---%ad---%s" --date=iso -{n}'
+        )
+
+        if not log:
+            return None, None, None, None
+
+        logs = log.split("\n")
+        logs = list(map(lambda log: tuple(log.split("---")), logs))
+
+        if n == 1:
+            return logs[0]
+        else:
+            return logs
+
+    def current_branch(self) -> str:
+        log : str = subprocess.run(
+            'git branch --show-current', capture_output=True, text=True, encoding="utf8", shell=True
+        ).stdout
+        log.replace('\n', '')
+        return log
+
+    def current_commit(self) -> str:
+        return self.get_commit()
+
+    def latest_commit(self) -> str:
+        source = "origin"
+        return self.get_commit(f"{source}/{self.Branch}")
+
+    def check_update(self) -> bool:
+        self.state = "checking"
+
+        # if State.deploy_config.GitOverCdn:
+        #     status = self.goc_client.get_status()
+        #     if status == "uptodate":
+        #         logger.info(f"No update")
+        #         return False
+        #     elif status == "behind":
+        #         logger.info(f"New update available")
+        #         return True
+        #     else:
+        #         # failed, should fallback to `git pull`
+        #         pass
+
+        source = "origin"
+        for _ in range(3):
+            if self.execute(
+                    f'"{self.git}" fetch {source} {self.Branch}', allow_failure=True
+            ):
+                break
+        else:
+            logger.warning("Git fetch failed")
+            return False
+
+        log = self.execute_output(
+            f'"{self.git}" log --not --remotes={source}/* -1 --oneline'
+        )
+        if log:
+            logger.info(
+                f"Cannot find local commit {log.split()[0]} in upstream, skip update"
+            )
+            return False
+
+        sha1, _, _, message = self.get_commit(f"..{source}/{self.Branch}")
+
+        if sha1:
+            logger.info(f"New update available")
+            logger.info(f"{sha1[:8]} - {message}")
+            return True
+        else:
+            logger.info(f"No update")
+            return False
+
+
+if __name__ == "__main__":
+    updater = Updater()
+    print(updater.latest_commit())
+
+
+

+ 3 - 2
requirements-in.txt

@@ -1,4 +1,3 @@
-pyside6==6.4.3
 adbutils==0.11.0
 uiautomator2==2.16.17
 uiautomator2cache==0.3.0.1
@@ -17,4 +16,6 @@ inflection==0.5.1
 tqdm==4.65.0
 ppocr-onnx==0.0.3.9
 onepush==1.2.0
-paho-mqtt==1.6.1
+paho-mqtt==1.6.1
+fastapi==0.104.1
+uvicorn==0.23.2

+ 35 - 30
requirements.txt

@@ -5,76 +5,81 @@
 #    pip-compile --annotation-style=line --output-file=requirements.txt requirements-in.txt
 #
 
+
 adbutils==0.11.0          # via -r requirements-in.txt, uiautomator2
+anyio==3.7.1              # via fastapi, starlette
 anytree==2.8.0            # via -r requirements-in.txt
 apkutils2==1.0.0          # via adbutils
 cached-property==1.5.2    # via uiautomator2
-certifi==2023.5.7         # via requests
-cffi==1.15.1              # via gevent
-charset-normalizer==3.1.0  # via requests
+certifi==2023.11.17       # via requests
+cffi==1.16.0              # via gevent
+charset-normalizer==3.3.2  # via requests
 cigam==0.0.3              # via apkutils2
-colorama==0.4.6           # via logzero, tqdm
+click==8.1.7              # via uvicorn
+colorama==0.4.6           # via click, logzero, tqdm
 coloredlogs==15.0.1       # via onnxruntime
 decorator==5.1.1          # via retry
-deprecated==1.2.13        # via uiautomator2
+deprecated==1.2.14        # via uiautomator2
 deprecation==2.1.0        # via adbutils
-filelock==3.12.0          # via uiautomator2
+exceptiongroup==1.2.0     # via anyio
+fastapi==0.104.1          # via -r requirements-in.txt
+filelock==3.13.1          # via uiautomator2
 flatbuffers==23.5.26      # via onnxruntime
 future==0.18.3            # via zerorpc
-gevent==22.10.2           # via zerorpc
-greenlet==2.0.2           # via gevent
+gevent==23.9.1            # via zerorpc
+greenlet==3.0.3           # via gevent
+h11==0.14.0               # via uvicorn
 humanfriendly==10.0       # via coloredlogs
-idna==3.4                 # via requests
+idna==3.6                 # via anyio, requests
 inflection==0.5.1         # via -r requirements-in.txt
 logzero==1.7.0            # via uiautomator2
-lxml==4.9.2               # via uiautomator2
+lxml==5.0.0               # via uiautomator2
 markdown-it-py==2.2.0     # via rich
 mdurl==0.1.2              # via markdown-it-py
 mpmath==1.3.0             # via sympy
-msgpack==1.0.5            # via zerorpc
+msgpack==1.0.7            # via zerorpc
 numpy==1.24.3             # via -r requirements-in.txt, onnxruntime, opencv-python, ppocr-onnx, shapely
 onepush==1.2.0            # via -r requirements-in.txt
-onnxruntime==1.15.0       # via ppocr-onnx
+onnxruntime==1.16.3       # via ppocr-onnx
 opencv-python==4.7.0.72   # via -r requirements-in.txt, ppocr-onnx
 packaging==20.9           # via deprecation, onnxruntime, uiautomator2
 paho-mqtt==1.6.1          # via -r requirements-in.txt
-pillow==9.5.0             # via ppocr-onnx, uiautomator2
+pillow==10.2.0            # via ppocr-onnx, uiautomator2
 ppocr-onnx==0.0.3.9       # via -r requirements-in.txt
 progress==1.6             # via uiautomator2
-protobuf==4.23.3          # via onnxruntime
+protobuf==4.25.1          # via onnxruntime
 py==1.11.0                # via retry
-pyclipper==1.3.0.post4    # via ppocr-onnx
+pyclipper==1.3.0.post5    # via ppocr-onnx
 pycparser==2.21           # via cffi
-pydantic==1.10.7          # via -r requirements-in.txt
-pyelftools==0.29          # via apkutils2
-pygments==2.15.1          # via rich
-pyparsing==3.0.9          # via packaging
+pydantic==1.10.7          # via -r requirements-in.txt, fastapi
+pyelftools==0.30          # via apkutils2
+pygments==2.17.2          # via rich
+pyparsing==3.1.1          # via packaging
 pyreadline3==3.4.1        # via humanfriendly
-pyside6==6.4.3            # via -r requirements-in.txt
-pyside6-addons==6.4.3     # via pyside6
-pyside6-essentials==6.4.3  # via pyside6, pyside6-addons
 pywin32==306              # via -r requirements-in.txt
 pyyaml==6.0               # via -r requirements-in.txt
-pyzmq==25.0.2             # via zerorpc
-requests==2.30.0          # via adbutils, onepush, ppocr-onnx, uiautomator2
+pyzmq==25.1.2             # via zerorpc
+requests==2.31.0          # via adbutils, onepush, ppocr-onnx, uiautomator2
 retry==0.9.2              # via adbutils, uiautomator2
 rich==13.3.5              # via -r requirements-in.txt
-shapely==2.0.1            # via ppocr-onnx
-shiboken6==6.4.3          # via pyside6, pyside6-addons, pyside6-essentials
+shapely==2.0.2            # via ppocr-onnx
 six==1.16.0               # via adbutils, anytree, uiautomator2
+sniffio==1.3.0            # via anyio
+starlette==0.27.0         # via fastapi
 sympy==1.12               # via onnxruntime
 tqdm==4.65.0              # via -r requirements-in.txt
-typing-extensions==4.5.0  # via pydantic
+typing-extensions==4.9.0  # via fastapi, pydantic, uvicorn
 uiautomator2==2.16.17     # via -r requirements-in.txt
 uiautomator2cache==0.3.0.1  # via -r requirements-in.txt
-urllib3==2.0.2            # via requests
+urllib3==2.1.0            # via requests
+uvicorn==0.23.2           # via -r requirements-in.txt
 websockets==11.0.3        # via -r requirements-in.txt
 whichcraft==0.6.1         # via adbutils, uiautomator2
 wrapt==1.15.0             # via -r requirements-in.txt, deprecated
 xmltodict==0.13.0         # via apkutils2
 zerorpc==0.6.3            # via -r requirements-in.txt
-zope-event==4.6           # via gevent
-zope-interface==6.0       # via gevent
+zope-event==5.0           # via gevent
+zope-interface==6.1       # via gevent
 
 # The following packages are considered to be unsafe in a requirements file:
 # setuptools

+ 5 - 10
script.py

@@ -1,6 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+
 import zerorpc
 import zmq
 import msgpack
@@ -18,8 +19,8 @@ from datetime import datetime, timedelta
 from pathlib import Path
 from cached_property import cached_property
 from pydantic import BaseModel, ValidationError
-from PySide6.QtGui import QImage
 from threading import Thread
+from multiprocessing.queues import Queue
 
 
 from module.config.utils import convert_to_underscore
@@ -35,6 +36,7 @@ class Script:
     def __init__(self, config_name: str ='oas') -> None:
         logger.hr('Start', level=0)
         self.server = None
+        self.state_queue: Queue = None
         self.gui_update_task: Callable = None  # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
         self.config_name = config_name
         # Skip first restart
@@ -238,7 +240,6 @@ class Script:
         if self.gui_update_task is not None:
             self.gui_update_task(data)
 
-
     def gui_task_list(self) -> str:
         """
         获取给gui显示的任务列表
@@ -263,13 +264,6 @@ class Script:
 
 
 
-
-
-
-
-
-
-
     def wait_until(self, future):
         """
         Wait until a specific time.
@@ -304,7 +298,8 @@ class Script:
         while 1:
             task = self.config.get_next()
             self.config.task = task
-            self._gui_update_tasks()
+            if self.state_queue:
+                self.state_queue.put({"schedule": self.config.get_schedule_data()})
 
             # from module.base.resource import release_resources
             # if self.config.task.command != 'Alas':

+ 63 - 0
server.py

@@ -0,0 +1,63 @@
+# This Python file uses the following encoding: utf-8
+# Copy from https://github.com/LmeSzinc/AzurLaneAutoScript/gui.py
+import threading
+
+from module.logger import logger
+from module.server.setting import State
+
+def fun(ev: threading.Event):
+    import argparse
+    import asyncio
+    import sys
+
+    import uvicorn
+
+    # 不知道干啥的照着抄就行了
+    if sys.platform.startswith("win"):
+        asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
+
+    State.restart_event = ev
+
+    parser = argparse.ArgumentParser(description="Alas web service")
+    parser.add_argument(
+        "--host",
+        type=str,
+        help="Host to listen. Default to WebuiHost in deploy setting",
+    )
+    parser.add_argument(
+        "-p",
+        "--port",
+        type=int,
+        help="Port to listen. Default to WebuiPort in deploy setting",
+    )
+    parser.add_argument(
+        "-k", "--key", type=str, help="Password of alas. No password by default"
+    )
+    parser.add_argument(
+        "--cdn",
+        action="store_true",
+        help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.",
+    )
+    parser.add_argument(
+        "--run",
+        nargs="+",
+        type=str,
+        help="Run alas by config names on startup",
+    )
+    args, _ = parser.parse_known_args()
+
+    host = args.host or State.deploy_config.WebuiHost or "0.0.0.0"
+    port = args.port or int(State.deploy_config.WebuiPort) or 22270
+
+    logger.hr("Launcher config")
+    logger.attr("Host", host)
+    logger.attr("Port", port)
+    logger.attr("Reload", ev is not None)
+
+    uvicorn.run("module.server.app:fastapi_app", host=host, port=port, factory=True)
+
+
+
+if __name__ == "__main__":
+    fun(None)
+

+ 1 - 1
tasks/ActivityShikigami/config.py

@@ -10,7 +10,7 @@ from tasks.Component.config_base import ConfigBase, TimeDelta
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 
 class ShikigamiConfig(BaseModel):
-    limit_time: timedelta = Field(default=timedelta(hours=0, minutes=30, seconds=0), description='limit_time_help')
+    limit_time: TimeDelta = Field(default=TimeDelta(hours=0, minutes=30, seconds=0), description='limit_time_help')
     limit_count: int = Field(default=10, description='limit_count_help')
 
 

+ 1 - 1
tasks/AreaBoss/assets.py

@@ -26,7 +26,7 @@ class AreaBossAssets:
 	# 选中第三个鬼王的 
 	I_BATTLE_3 = RuleImage(roi_front=(1071,521,100,100), roi_back=(1071,521,100,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_battle_3.png")
 	# 点击挑战 
-	I_FIRE = RuleImage(roi_front=(1108,492,100,100), roi_back=(1108,492,100,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_fire.png")
+	I_FIRE = RuleImage(roi_front=(1109,490,100,73), roi_back=(1075,463,150,158), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_fire.png")
 	# 跟buff冲突弃用 
 	I_CLOSE_RED = RuleImage(roi_front=(1190,24,37,38), roi_back=(1190,24,37,38), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_close_red.png")
 	# 红色关闭 

+ 2 - 2
tasks/AreaBoss/res/image.json

@@ -65,8 +65,8 @@
   {
     "itemName": "fire",
     "imageName": "res_fire.png",
-    "roiFront": "1108,492,100,100",
-    "roiBack": "1108,492,100,100",
+    "roiFront": "1109,490,100,73",
+    "roiBack": "1075,463,150,158",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "点击挑战"

BIN
tasks/AreaBoss/res/res_fire.png


+ 2 - 2
tasks/BondlingFairyland/config.py

@@ -7,7 +7,7 @@ from datetime import datetime, time
 
 from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase
+from tasks.Component.config_base import ConfigBase, DateTime, TimeDelta, Time
 from tasks.BondlingFairyland.config_battle import BattleConfig
 
 class BondlingMode(str, Enum):
@@ -31,7 +31,7 @@ class BondlingClass(str, Enum):
 
 class BondlingConfig(ConfigBase):
     bondling_mode: BondlingMode = Field(default=BondlingMode.MODE1, description='bondling_mode_help')
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     limit_count: int = Field(default=30, description='limit_count_help')
     bondling_stone_enable: bool = Field(default=False, description='bondling_stone_enable_help')
     bondling_stone_class: BondlingClass = Field(default=BondlingClass.TOMB_GUARD, description='bondling_stone_class_help')

+ 18 - 0
tasks/CollectiveMissions/assets.py

@@ -78,6 +78,24 @@ class CollectiveMissionsAssets:
 	S_CM_MATTER_4 = RuleSwipe(roi_front=(689,524,21,22), roi_back=(903,518,46,32), mode="default", name="cm_matter_4")
 
 
+	# Image Rule Assets
+	# 堆叠 
+	I_FEED_HEAP = RuleImage(roi_front=(20,543,42,59), roi_back=(20,543,42,59), threshold=0.8, method="Template matching", file="./tasks/CollectiveMissions/feed/feed_feed_heap.png")
+	# 提交 
+	I_FEED_SUBMIT = RuleImage(roi_front=(703,340,114,54), roi_back=(703,340,114,54), threshold=0.8, method="Template matching", file="./tasks/CollectiveMissions/feed/feed_feed_submit.png")
+
+
+	# Long Click Rule Assets
+	# description 
+	L_FEED_CLICK_1 = RuleLongClick(roi_front=(160,531,100,100), roi_back=(160,531,100,100), duration=1500, name="feed_click_1")
+	# description 
+	L_FEED_CLICK_2 = RuleLongClick(roi_front=(293,533,100,100), roi_back=(293,533,100,100), duration=1500, name="feed_click_2")
+	# description 
+	L_FEED_CLICK_3 = RuleLongClick(roi_front=(430,530,100,100), roi_back=(430,530,100,100), duration=1500, name="feed_click_3")
+	# description 
+	L_FEED_CLICK_4 = RuleLongClick(roi_front=(576,529,100,100), roi_back=(576,529,100,100), duration=1500, name="feed_click_4")
+
+
 	# Image Rule Assets
 	# 提交 
 	I_SL_SUBMIT = RuleImage(roi_front=(835,588,145,61), roi_back=(835,588,145,61), threshold=0.8, method="Template matching", file="./tasks/CollectiveMissions/soul/soul_sl_submit.png")

+ 2 - 1
tasks/CollectiveMissions/config.py

@@ -14,8 +14,9 @@ from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig
 
 class MissionsConfig(BaseModel):
     # 契灵 > 觉醒二 > 觉醒一 > 御灵二 > 御灵一 > 御魂五 > 御魂四
-    missions_rule: MultiLine = Field(default='契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一',
+    missions_rule: MultiLine = Field(default='契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一 > 远远不够',
                                      description='missions_rule_help')
+    setup_when_bondling: bool = Field(default=True, description='setup_when_bondling_help')
 
     @validator('missions_rule', pre=True, always=True)
     def mr_validator(cls, v):

+ 20 - 0
tasks/CollectiveMissions/feed/feed.json

@@ -0,0 +1,20 @@
+[
+  {
+    "itemName": "feed_heap",
+    "imageName": "feed_feed_heap.png",
+    "roiFront": "20,543,42,59",
+    "roiBack": "20,543,42,59",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "堆叠"
+  },
+  {
+    "itemName": "feed_submit",
+    "imageName": "feed_feed_submit.png",
+    "roiFront": "703,340,114,54",
+    "roiBack": "703,340,114,54",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "提交"
+  }
+]

+ 30 - 0
tasks/CollectiveMissions/feed/feed_click.json

@@ -0,0 +1,30 @@
+[
+  {
+    "itemName": "feed_click_1",
+    "roiFront": "160,531,100,100",
+    "roiBack": "160,531,100,100",
+    "duration": 1500,
+    "description": "description"
+  },
+  {
+    "itemName": "feed_click_2",
+    "roiFront": "293,533,100,100",
+    "roiBack": "293,533,100,100",
+    "duration": 1500,
+    "description": "description"
+  },
+  {
+    "itemName": "feed_click_3",
+    "roiFront": "430,530,100,100",
+    "roiBack": "430,530,100,100",
+    "duration": 1500,
+    "description": "description"
+  },
+  {
+    "itemName": "feed_click_4",
+    "roiFront": "576,529,100,100",
+    "roiBack": "576,529,100,100",
+    "duration": 1500,
+    "description": "description"
+  }
+]

BIN
tasks/CollectiveMissions/feed/feed_feed_heap.png


BIN
tasks/CollectiveMissions/feed/feed_feed_submit.png


+ 54 - 26
tasks/CollectiveMissions/script_task.py

@@ -28,8 +28,9 @@ class MC(str, Enum):
     GR3 = '御灵三'
     SO1 = '御魂一'
     SO2 = '御魂二'
-    FRIEND = '好友'
+    FRIEND = '结伴同行'
     UNKNOWN = '未知'
+    FEED = '远远不够'  # 喂N卡
 
 class ScriptTask(GameUi, CollectiveMissionsAssets):
     missions: list = []  # 用于记录三个的任务的种类
@@ -65,6 +66,9 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
         if mission == MC.BL:
             # 契灵单独处理
             self._bondling_fairyland(index)
+        elif mission == MC.FEED:
+            # 单独喂一个 N 卡
+            self._feed(index)
         elif mission == MC.AW1 or mission == MC.AW2 or mission == MC.AW3 \
                 or mission == MC.GR1 or mission == MC.GR2 or mission == MC.GR3:
             # 其他就捐材料
@@ -103,9 +107,9 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
             return MC.FRIEND
         elif result_1 == '契灵探查':
             return MC.BL
-        if result_1 != '远远不够':
+        if result_1 == '远远不够':
             logger.warning(f'Ocr task name: {result_1}')
-            return MC.UNKNOWN
+            return MC.FEED
         if result_2 == '觉醒一':
             return MC.AW1
         elif result_2 == '觉醒二':
@@ -129,30 +133,23 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
         自动寻找最好的任务并返回,期间记录三个任务的类型
         :return: 任务类型, 0/1/2
         """
-        best_index = 0
-        best_class = self.detect_one(self.O_CM_1, self.O_CM_2)
-        self.missions.append(best_class)
-        # 判断第二个,是否比第一个好
-        last_index = self.rule.index(best_class)
-        now_class = self.detect_one(self.O_CM_3, self.O_CM_4)
-        self.missions.append(now_class)
-        now_index = self.rule.index(now_class)
-        if now_index < last_index:
-            best_index = 1
-            best_class = now_class
-        # 判断第三个,是否比前两个好
-        last_index = self.rule.index(best_class)
-        now_class = self.detect_one(self.O_CM_5, self.O_CM_6)
-        self.missions.append(now_class)
-        if now_class == MC.FRIEND:
-            logger.info('The third mission is friend')
-            return best_class, best_index
-        now_index = self.rule.index(now_class)
-        if now_index < last_index:
-            best_index = 2
-            best_class = now_class
+        first_class = self.detect_one(self.O_CM_1, self.O_CM_2)
+        second_class = self.detect_one(self.O_CM_3, self.O_CM_4)
+        third_class = self.detect_one(self.O_CM_5, self.O_CM_6)
+        first_order = self.rule.index(first_class) if first_class in self.rule else 100
+        second_order = self.rule.index(second_class) if second_class in self.rule else 101
+        third_order = self.rule.index(third_class) if third_class in self.rule else 102
+        logger.info(f'first_class: {first_class}, second_class: {second_class}, third_class: {third_class}')
+        logger.info(f'first_order: {first_order}, second_order: {second_order}, third_order: {third_order}')
+        if first_order > second_order and first_order > third_order:
+            best_index, best_class = 0, first_class
+        elif second_order > first_order and second_order > third_order:
+            best_index, best_class = 1, second_class
+        elif third_order > first_order and third_order > second_order:
+            best_index, best_class = 2, third_class
         return best_class, best_index
 
+
     def _bondling_fairyland(self, index: int):
         """
         如果御灵已经做了那么就领取奖励
@@ -170,7 +167,7 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
                 logger.error('The scheduler of bondling_fairyland is not enable')
                 logger.error('Please enable it in config file')
                 raise RequestHumanTakeover
-            self.set_next_run(task='CollectiveMissions', success=True, finish=True, target=self.start_time+ timedelta(hours=2))
+            self.set_next_run(task='CollectiveMissions', success=True, finish=True, target=self.start_time + timedelta(hours=2))
             return True
         # 领取奖励
         logger.info('Start to collect bondling rewards')
@@ -325,7 +322,38 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
         logger.info('Finish to collect soul rewards')
         self.wait_until_appear(self.I_CM_RECORDS)
 
+    def _feed(self, index: int):
+        logger.info('Start to feed soul')
+        match_click = {
+            0: self.C_CM_1,
+            1: self.C_CM_2,
+            2: self.C_CM_3,
+        }
+        self.ui_click(match_click[index], self.I_FEED_HEAP)
+        logger.info('Submit to feed soul')
+        click_list = random.sample([self.L_FEED_CLICK_1, self.L_FEED_CLICK_2, self.L_FEED_CLICK_3, self.L_FEED_CLICK_4], 2)
+        while 1:
+            self.screenshot()
+            if self.appear(self.I_FEED_SUBMIT):
+                break
+            for click in click_list:
+                self.click(click)
+        logger.info('Finish to feed soul')
+        # 还有一点很重要的,捐赠会有双倍的,需要领两次
+        reward_number = 0
+        while 1:
+            self.screenshot()
 
+            if reward_number >= 2:
+                break
+            if self.ui_reward_appear_click(False):
+                reward_number += 1
+                continue
+            if self.appear_then_click(self.I_FEED_SUBMIT, interval=1):
+                continue
+        self.ui_reward_appear_click(True)
+        logger.info('Donate finished')
+        return True
 
 
 

+ 2 - 2
tasks/Component/BaseActivity/config_activity.py

@@ -7,7 +7,7 @@ from enum import Enum
 
 from module.logger import logger
 
-from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Component.config_base import ConfigBase, TimeDelta, Time
 
 class ApMode(str, Enum):
     AP_ACTIVITY = 'ap_activity'
@@ -16,7 +16,7 @@ class ApMode(str, Enum):
 
 class GeneralClimb(ConfigBase):
     # 限制执行的时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制执行的次数
     limit_count: int = Field(default=50, description='limit_count_help')
     # 每日使用体力挑战的最大次数,默认是300

+ 8 - 0
tasks/Component/Buy/buy.py

@@ -80,20 +80,28 @@ class Buy(BaseTask, BuyAssets):
         :param number: 不指定就是拉满
         :return:
         """
+        try_click_count = 0
         while 1:
             self.screenshot()
 
             if self.appear(self.I_BUY_PLUS):
                 break
+            if try_click_count >= 5:
+                logger.warning(f'Buy_more failed, try_click_count: {try_click_count}')
+                logger.warning('Close the purchase')
+                return
 
             if isinstance(start_click, RuleImage):
                 if self.appear_then_click(start_click, interval=1):
+                    try_click_count += 1
                     continue
             elif isinstance(start_click, RuleOcr):
                 if self.ocr_appear_click(start_click, interval=1):
+                    try_click_count += 1
                     continue
             elif isinstance(start_click, RuleClick):
                 if self.click(start_click, interval=1):
+                    try_click_count += 1
                     continue
         # 设置购买的数量
         if number is None:

+ 1 - 1
tasks/Component/GeneralInvite/config_invite.py

@@ -21,7 +21,7 @@ class InviteConfig(BaseModel):
     friend_1: str = Field(default='', description='friend_name_help')
     friend_2: str = Field(default='', description='friend_2_name_help')
     find_mode: FindMode = Field(default=FindMode.AUTO_FIND, description='find_mode_help')
-    wait_time: time = Field(default=time(minute=2), description='wait_time_help')
+    wait_time: Time = Field(default=Time(minute=2), description='wait_time_help')
     default_invite: bool = Field(default=True, description='default_invite_help')
 
     # @validator('wait_time', pre=False, always=False)

+ 17 - 0
tasks/Component/ReplaceShikigami/assets.py

@@ -31,6 +31,23 @@ class ReplaceShikigamiAssets:
 	C_SHIKIGAMI_LEFT_8 = RuleClick(roi_front=(1033,490,100,180), roi_back=(1033,490,100,180), name="shikigami_left_8")
 
 
+	# Image Rule Assets
+	# description 
+	I_DETECT_EMPTY_1 = RuleImage(roi_front=(64,262,100,100), roi_back=(38,227,158,177), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_detect_empty_1.png")
+	# description 
+	I_DETECT_EMPTY_2 = RuleImage(roi_front=(281,263,100,100), roi_back=(238,234,178,168), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_detect_empty_2.png")
+	# description 
+	I_DETECT_EMPTY_3 = RuleImage(roi_front=(495,263,100,100), roi_back=(470,234,150,150), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_detect_empty_3.png")
+	# description 
+	I_DETECT_EMPTY_4 = RuleImage(roi_front=(703,256,100,100), roi_back=(681,229,157,174), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_detect_empty_4.png")
+	# description 
+	I_DETECT_EMPTY_5 = RuleImage(roi_front=(914,257,100,100), roi_back=(872,221,198,190), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_detect_empty_5.png")
+	# description 
+	I_DETECT_EMPTY_6 = RuleImage(roi_front=(1135,253,100,100), roi_back=(1091,229,156,159), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_detect_empty_6.png")
+	# description 
+	I_NEW = RuleImage(roi_front=(0,0,100,100), roi_back=(0,0,100,100), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/image_name.png")
+
+
 	# Image Rule Assets
 	# description 
 	I_RS_NO_ADD = RuleImage(roi_front=(276,222,100,212), roi_back=(28,181,1232,293), threshold=0.8, method="Template matching", file="./tasks/Component/ReplaceShikigami/rs/rs_rs_no_add.png")

+ 11 - 0
tasks/Component/ReplaceShikigami/replace_shikigami.py

@@ -97,3 +97,14 @@ class ReplaceShikigami(BaseTask, ReplaceShikigamiAssets):
             if self.click(click_match, interval=1.5):
                 continue
         logger.info('Set shikigami: %d' % shikigami_order)
+
+    def detect_no_shikigami(self) -> bool:
+        self.screenshot()
+        if self.appear(self.I_DETECT_EMPTY_1)\
+            and self.appear(self.I_DETECT_EMPTY_2) \
+                and self.appear(self.I_DETECT_EMPTY_3) \
+                and self.appear(self.I_DETECT_EMPTY_4) \
+                and self.appear(self.I_DETECT_EMPTY_5) \
+                and self.appear(self.I_DETECT_EMPTY_6):
+            return True
+        return False

+ 65 - 0
tasks/Component/ReplaceShikigami/rs/detect_image.json

@@ -0,0 +1,65 @@
+[
+  {
+    "itemName": "detect_empty_1",
+    "imageName": "rs_detect_empty_1.png",
+    "roiFront": "64,262,100,100",
+    "roiBack": "38,227,158,177",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "detect_empty_2",
+    "imageName": "rs_detect_empty_2.png",
+    "roiFront": "281,263,100,100",
+    "roiBack": "238,234,178,168",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "detect_empty_3",
+    "imageName": "rs_detect_empty_3.png",
+    "roiFront": "495,263,100,100",
+    "roiBack": "470,234,150,150",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "detect_empty_4",
+    "imageName": "rs_detect_empty_4.png",
+    "roiFront": "703,256,100,100",
+    "roiBack": "681,229,157,174",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "detect_empty_5",
+    "imageName": "rs_detect_empty_5.png",
+    "roiFront": "914,257,100,100",
+    "roiBack": "872,221,198,190",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "detect_empty_6",
+    "imageName": "rs_detect_empty_6.png",
+    "roiFront": "1135,253,100,100",
+    "roiBack": "1091,229,156,159",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "new",
+    "imageName": "image_name.png",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  }
+]

BIN
tasks/Component/ReplaceShikigami/rs/rs_detect_empty_1.png


BIN
tasks/Component/ReplaceShikigami/rs/rs_detect_empty_2.png


BIN
tasks/Component/ReplaceShikigami/rs/rs_detect_empty_3.png


BIN
tasks/Component/ReplaceShikigami/rs/rs_detect_empty_4.png


BIN
tasks/Component/ReplaceShikigami/rs/rs_detect_empty_5.png


BIN
tasks/Component/ReplaceShikigami/rs/rs_detect_empty_6.png


+ 40 - 16
tasks/Component/config_base.py

@@ -3,7 +3,7 @@
 # github https://github.com/runhey
 from typing import Any
 from collections.abc import Callable, Generator
-from datetime import timedelta, time
+from datetime import timedelta, time, datetime
 
 from pydantic import BaseModel, datetime_parse
 from pydantic.fields import ModelField
@@ -16,20 +16,6 @@ def format_timedelta(tdelta: timedelta):
     minutes, seconds = divmod(rem, 60)
     return f"{days:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
 
-class TimeDelta(timedelta):
-    def __str__(self):
-        return format_timedelta(self)
-
-    def __repr__(self):
-        return format_timedelta(self)
-
-class ConfigBase(BaseModel):
-    class Config:
-        json_encoders = {
-            TimeDelta: format_timedelta
-        }
-
-
 
 class MultiLine(str):
     # @classmethod
@@ -47,6 +33,29 @@ class MultiLine(str):
         if field:
             field_schema['type'] = 'multi_line'
 
+class TimeDelta(timedelta):
+    def __str__(self):
+        return format_timedelta(self)
+
+    def __repr__(self):
+        return format_timedelta(self)
+
+    @classmethod
+    def __modify_schema__(
+            cls, field_schema: dict[str, Any], field: ModelField | None
+    ):
+        if field:
+            field_schema['type'] = 'time_delta'
+
+class DateTime(datetime):
+    @classmethod
+    def __modify_schema__(
+            cls, field_schema: dict[str, Any], field: ModelField | None
+    ):
+        if field:
+            field_schema['type'] = 'date_time'
+
+
 class Time(time):
     """
     尝试将字符串转换为time对象, 但是不生效
@@ -57,7 +66,7 @@ class Time(time):
 
     @classmethod
     def validate(cls, value):
-        print('validate', value)
+        # print(f' Time validate: {value} type: {type(value)}')
         if isinstance(value, str):
             hour, minute, second = map(int, value.split(":"))
             return cls(hour, minute, second)
@@ -65,3 +74,18 @@ class Time(time):
             return value
         else:
             raise ValueError("Invalid time format")
+
+    @classmethod
+    def __modify_schema__(
+            cls, field_schema: dict[str, Any], field: ModelField | None
+    ):
+        if field:
+            field_schema['type'] = 'time'
+
+# ---------------------------------------------------------------------------------------------------------------------
+class ConfigBase(BaseModel):
+    # 这个是导出json时候的配置,但是新的是导出dict,所以的无效
+    class Config:
+        json_encoders = {
+            TimeDelta: format_timedelta
+        }

+ 3 - 3
tasks/Component/config_scheduler.py

@@ -6,16 +6,16 @@ from enum import Enum
 from datetime import datetime, timedelta, time
 from pydantic import BaseModel, ValidationError, validator, Field
 
-from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Component.config_base import ConfigBase, TimeDelta, DateTime, Time
 
 class Scheduler(ConfigBase):
     enable: bool = Field(default=False, description='enable_help')
-    next_run: datetime = Field(default="2023-01-01 00:00:00", description='next_run_help')
+    next_run: DateTime = Field(default="2023-01-01 00:00:00", description='next_run_help')
     priority: int = Field(default=5, description='priority_help')
 
     success_interval: TimeDelta = Field(default=TimeDelta(days=1), description='success_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(days=1), description='failure_interval_help')
-    server_update: time = Field(default=time(hour=9, minute=0, second=0), description='server_update_help')
+    server_update: Time = Field(default=Time(hour=9, minute=0, second=0), description='server_update_help')
 
     @validator('next_run', pre=True, always=True)
     def parse_next_run(cls, value):

+ 1 - 1
tasks/DemonEncounter/script_task.py

@@ -145,7 +145,7 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets):
             if cu == 0 and re == 4:
                 break
 
-            if self.appear_then_click(self.I_DE_FIND, interval=1):
+            if self.appear_then_click(self.I_DE_FIND, interval=2.5):
                 continue
         logger.info('Lantern count success')
         # 然后领取红色达摩

+ 2 - 2
tasks/Duel/config.py

@@ -5,14 +5,14 @@ from pydantic import BaseModel, Field
 from datetime import time
 
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase
+from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType
 
 class DuelConfig(ConfigBase):
     # 一键切换斗技御魂
     switch_all_soul: bool = Field(default=False, description='switch_all_soul_help')
     # 限制时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 目标分数
     target_score: int = Field(default=2000, description='target_score_help')
     # 刷满荣誉就退出

+ 2 - 2
tasks/EternitySea/config.py

@@ -6,7 +6,7 @@ from enum import Enum
 from datetime import datetime, time
 
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase
+from tasks.Component.config_base import ConfigBase, Time
 from tasks.Orochi.config import UserStatus
 
 
@@ -22,7 +22,7 @@ class EternitySeaConfig(ConfigBase):
     # 层数
     layer: Layer = Field(default=Layer.FOUR, description='layer_help')
     # 限制时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制次数
     limit_count: int = Field(default=50, description='limit_count_help')
 

+ 2 - 2
tasks/EvoZone/config.py

@@ -6,7 +6,7 @@ from enum import Enum
 from datetime import datetime, time
 
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.GeneralInvite.config_invite import InviteConfig
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 
@@ -44,7 +44,7 @@ class EvoZoneConfig(ConfigBase):
     # 层数
     layer: Layer = Field(default=Layer.TEN, description='layer_help')
     # 限制时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制次数
     limit_count: int = Field(default=30, description='limit_count_help')
     # 是否开启觉醒加成

+ 2 - 12
tasks/EvoZone/script_task.py

@@ -321,7 +321,7 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
             if self.appear_then_click(self.I_BACK_BL, interval=1):
                 continue
 
-        self.ui_current = page_soul_zones
+        self.ui_current = page_awake_zones
         self.ui_goto(page_main)
 
 
@@ -338,26 +338,16 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
 if __name__ == '__main__':
     from module.config.config import Config
     from module.device.device import Device
-    from memory_profiler import profile
     c = Config('oas1')
     d = Device(c)
     t = ScriptTask(c, d)
 
-    # t.run()
+    t.run()
 
     # t.check_layer('悲')
 
     from module.base.timer import timer
 
-    @timer
-    @profile
-    def test_memory():
-        t.screenshot()
-        print(t.ocr_appear(t.O_O_TEST_OCR))
-        print(t.L_LAYER_LIST.image_appear(t.device.image, '悲'))
-    for i in range(4):
-        test_memory()
-        print('=====================')
 
 
 

+ 2 - 2
tasks/FallenSun/config.py

@@ -7,7 +7,7 @@ from datetime import datetime, time
 
 from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.GeneralInvite.config_invite import InviteConfig
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 
@@ -29,7 +29,7 @@ class FallenSunConfig(ConfigBase):
     # 层数
     layer: Layer = Field(default=Layer.THREE, description='layer_help')
     # 限制时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制次数
     limit_count: int = Field(default=50, description='limit_count_help')
 

+ 1 - 1
tasks/GameUi/assets.py

@@ -143,7 +143,7 @@ class GameUiAssets:
 	# description 
 	I_CHECK_FRIENDS = RuleImage(roi_front=(1011,592,133,60), roi_back=(1011,592,133,60), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_friends.png")
 	# description 
-	I_CHECK_DAILY = RuleImage(roi_front=(28,510,69,87), roi_back=(28,510,69,87), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_daily.png")
+	I_CHECK_DAILY = RuleImage(roi_front=(27,515,69,62), roi_back=(1,489,155,127), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_daily.png")
 	# description 
 	I_CHECK_MALL = RuleImage(roi_front=(239,502,100,100), roi_back=(239,502,100,100), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_mall.png")
 	# description 

BIN
tasks/GameUi/page/page_check_daily.png


+ 2 - 2
tasks/GameUi/page/page_img_3.json

@@ -101,8 +101,8 @@
   {
     "itemName": "check_daily",
     "imageName": "page_check_daily.png",
-    "roiFront": "28,510,69,87",
-    "roiBack": "28,510,69,87",
+    "roiFront": "27,515,69,62",
+    "roiBack": "1,489,155,127",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"

+ 2 - 2
tasks/GoryouRealm/config.py

@@ -6,7 +6,7 @@ from enum import Enum
 from datetime import datetime, time
 
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase
+from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 
@@ -19,7 +19,7 @@ class GoryouClass(str, Enum):
 
 class GoryouConfig(ConfigBase):
     # 限制时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制次数
     limit_count: int = Field(default=30, description='limit_count_help')
     # 类型

+ 0 - 1
tasks/Hunt/config.py

@@ -15,4 +15,3 @@ class HuntConfig(BaseModel):
 class Hunt(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     hunt_config: HuntConfig = Field(default_factory=HuntConfig)
-    exit_battle: bool = Field(default=False, description='exit_battle_help')

+ 12 - 4
tasks/KekkaiActivation/script_task.py

@@ -10,7 +10,7 @@ from module.base.timer import Timer
 from module.atom.image_grid import ImageGrid
 from module.atom.image import RuleImage
 from module.logger import logger
-from module.exception import TaskEnd
+from module.exception import TaskEnd, GameStuckError
 
 from tasks.KekkaiUtilize.script_task import ScriptTask as KU
 from tasks.KekkaiUtilize.utils import CardClass
@@ -193,6 +193,10 @@ class ScriptTask(KU, KekkaiActivationAssets):
         if not isinstance(delta, timedelta):
             logger.warning('OCR error')
             return None
+        if delta == timedelta(0):
+            logger.error('The remaining time detected for this card is 0')
+            logger.error('This may be due to the fact that the card has not yet been collected')
+            raise GameStuckError
         return delta
 
     def screening_card(self, rule: str):
@@ -337,14 +341,18 @@ class ScriptTask(KU, KekkaiActivationAssets):
             self.set_shikigami(shikigami_order=7, stop_image=self.I_RS_NO_ADD)
         else:
             logger.info('No max level shikigami')
+        if self.detect_no_shikigami():
+            logger.warning('There are no any shikigami grow room')
+            self.set_shikigami(shikigami_order=7, stop_image=self.I_RS_NO_ADD)
 
         # 回到结界界面
         while 1:
             self.screenshot()
 
-            if self.appear(self.I_REALM_SHIN):
-                break
-            if self.appear(self.I_SHI_GROWN):
+            if self.appear(self.I_REALM_SHIN) and self.appear(self.I_SHI_GROWN):
+                self.screenshot()
+                if not self.appear(self.I_REALM_SHIN):
+                    continue
                 break
             if self.appear_then_click(self.I_UI_BACK_BLUE, interval=1):
                 continue

+ 4 - 8
tasks/KekkaiUtilize/script_task.py

@@ -178,17 +178,9 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             time_exp.start()
             while 1:
                 self.screenshot()
-
-                if self.appear_then_click(self.I_BOX_EXP, threshold=0.6, interval=1):
-                    continue
-                if self.appear_then_click(self.I_EXP_EXTRACT, interval=1):
-                    continue
-
                 # 如果出现结界皮肤, 表示收取好了
                 if self.appear(self.I_REALM_SHIN) and not self.appear(self.I_BOX_EXP, threshold=0.6):
                     break
-
-
                 # 如果出现收取确认,表明进入到了有满级的
                 if self.appear(self.I_UI_CONFIRM):
                     self.screenshot()
@@ -215,6 +207,10 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
                     if cur == totol and cur + res == totol:
                         logger.info('Exp box reach max do not collect')
                         break
+                if self.appear_then_click(self.I_BOX_EXP, threshold=0.6, interval=1):
+                    continue
+                if self.appear_then_click(self.I_EXP_EXTRACT, interval=1):
+                    continue
 
                 if time_exp.reached():
                     logger.warning('Extract exp box timeout')

+ 44 - 0
tasks/MetaDemon/assets.py

@@ -0,0 +1,44 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+from module.atom.ocr import RuleOcr
+from module.atom.list import RuleList
+
+# This file was automatically generated by ./dev_tools/assets_extract.py.
+# Don't modify it manually.
+class MetaDemonAssets: 
+
+
+	# Image Rule Assets
+	# description 
+	I_MD_ENTER = RuleImage(roi_front=(426,463,60,80), roi_back=(239,369,547,215), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_enter.png")
+	# description 
+	I_MD_MAIN = RuleImage(roi_front=(658,156,41,139), roi_back=(636,133,100,245), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_main.png")
+	# description 
+	I_MD_FIND = RuleImage(roi_front=(1112,581,100,100), roi_back=(1112,581,100,100), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_find.png")
+	# 高 
+	I_MD_HARD = RuleImage(roi_front=(513,515,26,27), roi_back=(513,515,26,27), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_hard.png")
+	# description 
+	I_MD_FIRE = RuleImage(roi_front=(1107,563,109,113), roi_back=(1107,563,109,113), threshold=0.7, method="Template matching", file="./tasks/MetaDemon/md/md_md_fire.png")
+	# description 
+	I_MD_GIFT_BOX = RuleImage(roi_front=(1184,182,42,50), roi_back=(1184,182,42,50), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_gift_box.png")
+	# 难度 
+	I_MD_EXTREME = RuleImage(roi_front=(512,516,30,25), roi_back=(512,516,30,25), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_extreme.png")
+	# description 
+	I_MD_FIRE_COMMON = RuleImage(roi_front=(1065,499,100,36), roi_back=(1065,499,100,36), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_fire_common.png")
+	# description 
+	I_MD_FIRE_POWER = RuleImage(roi_front=(1159,498,100,37), roi_back=(1159,498,100,37), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_fire_power.png")
+	# 失败 
+	I_MD_BATTLE_FAILURE = RuleImage(roi_front=(412,105,100,100), roi_back=(412,105,100,100), threshold=0.8, method="Template matching", file="./tasks/MetaDemon/md/md_md_battle_failure.png")
+
+
+	# Ocr Rule Assets
+	# Ocr-description 
+	O_MD_EXHAUSTION = RuleOcr(roi=(1096,18,89,31), area=(1096,18,89,31), mode="DigitCounter", method="Default", keyword="", name="md_exhaustion")
+	# Ocr-description 
+	O_MD_TICKET = RuleOcr(roi=(923,18,82,30), area=(923,18,82,30), mode="DigitCounter", method="Default", keyword="", name="md_ticket")
+	# Ocr-description 
+	O_MD_COUNT_INFO = RuleOcr(roi=(94,314,161,37), area=(94,314,161,37), mode="Single", method="Default", keyword="击败奖励结算中", name="md_count_info")
+
+

+ 27 - 0
tasks/MetaDemon/config.py

@@ -0,0 +1,27 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from tasks.Component.config_base import ConfigBase, TimeDelta, DateTime, Time
+from pydantic import BaseModel, ValidationError, validator, Field
+from enum import Enum
+
+# 鬼王的难度为: 易、中、高、难、极 五个 对应英文:easy、medium、hard、difficult、extreme
+
+class Scheduler(ConfigBase):
+    enable: bool = Field(default=False, description='enable_help')
+    next_run: DateTime = Field(default="2023-01-01 00:00:00", description='next_run_help')
+    priority: int = Field(default=5, description='priority_help')
+    interval: TimeDelta = Field(default=TimeDelta(hours=3), description='interval_help')
+
+class MetaDemonConfig(ConfigBase):
+    auto_tea: bool = Field(default=False, description='auto_tea_help')
+    extreme_notify: bool = Field(default=False, description='extreme_notify_help')
+
+
+class MetaDemon(ConfigBase):
+    scheduler: Scheduler = Field(default_factory=Scheduler)
+    meta_demon_config: MetaDemonConfig = Field(default_factory=MetaDemonConfig)
+
+
+
+

+ 92 - 0
tasks/MetaDemon/md/image.json

@@ -0,0 +1,92 @@
+[
+  {
+    "itemName": "md_enter",
+    "imageName": "md_md_enter.png",
+    "roiFront": "426,463,60,80",
+    "roiBack": "239,369,547,215",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "md_main",
+    "imageName": "md_md_main.png",
+    "roiFront": "658,156,41,139",
+    "roiBack": "636,133,100,245",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "md_find",
+    "imageName": "md_md_find.png",
+    "roiFront": "1112,581,100,100",
+    "roiBack": "1112,581,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "md_hard",
+    "imageName": "md_md_hard.png",
+    "roiFront": "513,515,26,27",
+    "roiBack": "513,515,26,27",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "高"
+  },
+  {
+    "itemName": "md_fire",
+    "imageName": "md_md_fire.png",
+    "roiFront": "1107,563,109,113",
+    "roiBack": "1107,563,109,113",
+    "method": "Template matching",
+    "threshold": 0.7,
+    "description": "description"
+  },
+  {
+    "itemName": "md_gift_box",
+    "imageName": "md_md_gift_box.png",
+    "roiFront": "1184,182,42,50",
+    "roiBack": "1184,182,42,50",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "md_extreme",
+    "imageName": "md_md_extreme.png",
+    "roiFront": "512,516,30,25",
+    "roiBack": "512,516,30,25",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "难度"
+  },
+  {
+    "itemName": "md_fire_common",
+    "imageName": "md_md_fire_common.png",
+    "roiFront": "1065,499,100,36",
+    "roiBack": "1065,499,100,36",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "md_fire_power",
+    "imageName": "md_md_fire_power.png",
+    "roiFront": "1159,498,100,37",
+    "roiBack": "1159,498,100,37",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "md_battle_failure",
+    "imageName": "md_md_battle_failure.png",
+    "roiFront": "412,105,100,100",
+    "roiBack": "412,105,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "失败"
+  }
+]

BIN
tasks/MetaDemon/md/md_md_battle_failure.png


BIN
tasks/MetaDemon/md/md_md_enter.png


BIN
tasks/MetaDemon/md/md_md_extreme.png


BIN
tasks/MetaDemon/md/md_md_find.png


BIN
tasks/MetaDemon/md/md_md_fire.png


BIN
tasks/MetaDemon/md/md_md_fire_common.png


BIN
tasks/MetaDemon/md/md_md_fire_power.png


BIN
tasks/MetaDemon/md/md_md_gift_box.png


BIN
tasks/MetaDemon/md/md_md_hard.png


BIN
tasks/MetaDemon/md/md_md_main.png


+ 29 - 0
tasks/MetaDemon/md/ocr.json

@@ -0,0 +1,29 @@
+[
+  {
+    "itemName": "md_exhaustion",
+    "roiFront": "1096,18,89,31",
+    "roiBack": "1096,18,89,31",
+    "mode": "DigitCounter",
+    "method": "Default",
+    "keyword": "",
+    "description": "Ocr-description"
+  },
+  {
+    "itemName": "md_ticket",
+    "roiFront": "923,18,82,30",
+    "roiBack": "923,18,82,30",
+    "mode": "DigitCounter",
+    "method": "Default",
+    "keyword": "",
+    "description": "Ocr-description"
+  },
+  {
+    "itemName": "md_count_info",
+    "roiFront": "94,314,161,37",
+    "roiBack": "94,314,161,37",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "击败奖励结算中",
+    "description": "Ocr-description"
+  }
+]

+ 172 - 0
tasks/MetaDemon/script_task.py

@@ -0,0 +1,172 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from cached_property import cached_property
+from datetime import datetime
+from time import sleep
+
+from tasks.Component.config_base import ConfigBase, TimeDelta, DateTime, Time
+from tasks.Component.GeneralBattle.general_battle import GeneralBattle
+from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
+from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
+from tasks.GameUi.game_ui import GameUi
+from tasks.GameUi.page import page_main
+from tasks.MetaDemon.config import MetaDemon
+from tasks.MetaDemon.assets import MetaDemonAssets
+
+from module.logger import logger
+from module.exception import TaskEnd
+
+class ScriptTask(GeneralBattle, SwitchSoul, GameUi, MetaDemonAssets):
+
+    def run(self):
+        self.ui_get_current_page()
+        self.ui_goto(page_main)
+        while 1:
+            self.screenshot()
+            if self.appear(self.I_MD_FIND):
+                break
+            if self.appear(self.I_MD_FIRE):
+                break
+            if self.appear_then_click(self.I_MD_ENTER, interval=1.5):
+                continue
+            if self.appear_then_click(self.I_MD_MAIN, interval=1.5):
+                continue
+
+        config: MetaDemon = self.config.model.meta_demon
+        # 主循环
+        while 1:
+            self.screenshot()
+            if not self.appear(self.I_MD_GIFT_BOX):
+                continue
+            # 检查是否有票
+            if not self.ensure_ticket():
+                logger.info('There is no common ticket')
+                self.set_next_run('MetaDemon', finish=True,
+                                  target=config.scheduler.interval + datetime.now().replace(second=0, microsecond=0))
+                break
+            # 检查疲劳°
+            if not self.check_exhaustion():
+                logger.info('Exhaustion is more than 100')
+                if config.meta_demon_config.auto_tea:
+                    logger.info('Try to buy tea')
+                    self.buy_tea()
+                    continue
+                else:
+                    logger.info('Stop because of exhaustion is more than 100')
+                    interval_delta = TimeDelta(minutes=self.current_exhaustion())
+                    self.set_next_run('MetaDemon', finish=True,
+                                      target=interval_delta + datetime.now().replace(second=0, microsecond=0))
+                    break
+            # 寻找鬼王
+            if self.appear_then_click(self.I_MD_FIND, interval=1.5):
+                continue
+            #
+            if self.appear(self.I_MD_FIRE) and self.appear(self.I_MD_FIRE_COMMON):
+                if self.ocr_appear(self.O_MD_COUNT_INFO):
+                    # 结算中
+                    logger.info('Waiting for settlement')
+                    sleep(1)
+                    continue
+                # 是否为极
+                if self.appear(self.I_MD_EXTREME):
+                    logger.info('Find extreme Demon')
+                    if config.meta_demon_config.extreme_notify:
+                        self.config.notifier.push(title='超鬼王', content=f"发现极鬼王")
+                        self.set_next_run('MetaDemon', finish=True,
+                                          target=config.scheduler.interval + datetime.now().replace(second=0, microsecond=0))
+                        break
+                    else:
+                        pass
+                while 1:
+                    self.screenshot()
+                    if self.appear(self.I_MD_FIRE) and self.appear(self.I_MD_FIRE_COMMON):
+                        pass
+                    else:
+                        break
+                    if self.appear_then_click(self.I_MD_FIRE, interval=2):
+                        continue
+                self.run_general_battle(config=self.battle_config)
+        # exit
+        while 1:
+            self.screenshot()
+            if self.appear(self.I_CHECK_MAIN):
+                logger.info('Exit MetaDemon')
+                break
+            if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=1):
+                continue
+        raise TaskEnd
+
+
+
+
+
+    @cached_property
+    def battle_config(self):
+        config = GeneralBattleConfig()
+        config.lock_team_enable = False
+        return config
+
+    def ensure_ticket(self, screenshot: bool = False) -> bool:
+        if screenshot:
+            self.screenshot()
+        cu, res, total = self.O_MD_TICKET.ocr(self.device.image)
+        if cu <= 0:
+            return False
+        return True
+
+    def check_exhaustion(self, screenshot: bool = False) -> bool:
+        # EXHAUSTION
+        if screenshot:
+            self.screenshot()
+        cu, res, total = self.O_MD_EXHAUSTION.ocr(self.device.image)
+        if cu >= 100:
+            return False
+        return True
+
+    def current_exhaustion(self) -> int:
+        self.screenshot()
+        cu, res, total = self.O_MD_EXHAUSTION.ocr(self.device.image)
+        return int(cu)
+
+    def click_fire(self):
+        while 1:
+            self.screenshot()
+            if not self.appear(self.I_MD_FIRE):
+                self.screenshot()
+                if not self.appear(self.I_MD_FIRE):
+                    break
+            if self.appear_then_click(self.I_MD_FIRE, interval=2):
+                continue
+
+    def buy_tea(self):
+        pass
+
+    def battle_wait(self, random_click_swipt_enable: bool) -> bool:
+        # 重写
+        self.device.stuck_record_add('BATTLE_STATUS_S')
+        self.device.click_record_clear()
+        logger.info("Start battle process")
+        while 1:
+            self.screenshot()
+            # if self.appear_then_click(self.I_WIN, interval=1):
+            #     continue
+            if self.appear(self.I_WIN):
+                logger.info('Win battle')
+                self.ui_click_until_disappear(self.I_WIN)
+                return True
+
+            if self.appear(self.I_MD_BATTLE_FAILURE):
+                logger.warning('False battle')
+                self.ui_click_until_disappear(self.I_MD_BATTLE_FAILURE)
+                return False
+
+if __name__ == '__main__':
+    from module.config.config import Config
+    from module.device.device import Device
+    c = Config('oas1')
+    d = Device(c)
+    t = ScriptTask(c, d)
+
+    t.run()
+

+ 2 - 2
tasks/MysteryShop/config.py

@@ -5,10 +5,10 @@ from datetime import timedelta, datetime, time
 from pydantic import BaseModel, Field
 
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase
+from tasks.Component.config_base import ConfigBase, Time
 
 class ShopConfig(BaseModel):
-    time_of_mystery: time = Field(default=time(hour=0, minute=0, second=0), description='time_of_mystery_help')
+    time_of_mystery: Time = Field(default=Time(hour=0, minute=0, second=0), description='time_of_mystery_help')
     mystery_amulet: bool = Field(default=False)
     black_daruma_scrap: bool = Field(default=False)
     shop_kaiko_3: bool = Field(default=False)

+ 5 - 0
tasks/Nian/assets.py

@@ -10,6 +10,11 @@ from module.atom.list import RuleList
 class NianAssets: 
 
 
+	# Click Rule Assets
+	# description 
+	C_CLIC_SAFE = RuleClick(roi_front=(242,25,100,65), roi_back=(242,25,100,65), name="clic_safe")
+
+
 	# Image Rule Assets
 	# 自动匹配 
 	I_AUTO_MATCHING = RuleImage(roi_front=(698,598,180,64), roi_back=(698,598,180,64), threshold=0.8, method="Template matching", file="./tasks/Nian/nian/nian_auto_matching.png")

+ 8 - 0
tasks/Nian/nian/click.json

@@ -0,0 +1,8 @@
+[
+  {
+    "itemName": "clic_safe",
+    "roiFront": "242,25,100,65",
+    "roiBack": "242,25,100,65",
+    "description": "description"
+  }
+]

+ 17 - 2
tasks/Nian/script_task.py

@@ -90,6 +90,16 @@ class ScriptTask(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, NianAssets):
                 else:
                     break
             # 如果时间到了
+            if click_timer and click_timer.reached():
+                logger.warning('It has waited for 240s , but the battle has not started.')
+                logger.warning('It will be waited for 240s and try again.')
+                self.screenshot()
+                self.click(self.C_CLIC_SAFE)
+                click_timer = None
+                self.device.stuck_record_clear()
+                self.device.stuck_record_add('LOGIN_CHECK')
+                continue
+
             if check_timer.reached():
                 logger.warning('Nian match timeout')
                 while 1:
@@ -123,8 +133,12 @@ class ScriptTask(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, NianAssets):
         if not isinstance(result, str):
             logger.error(f'OCR error {result}')
             return False
-        result = re.search(r'(\d+)时(\d+)分后可', result)
-        time_delta = timedelta(hours=int(result.group(1)), minutes=int(result.group(2)))
+        try:
+            result = re.search(r'(\d+)时(\d+)分后可', result)
+            time_delta = timedelta(hours=int(result.group(1)), minutes=int(result.group(2)))
+        except Exception as e:
+            logger.error(f'{e} {result}')
+            time_delta = timedelta(hours=4)
         return time_delta
 
     @cached_property
@@ -142,3 +156,4 @@ if __name__ == '__main__':
 
     t.run()
 
+

+ 2 - 2
tasks/Orochi/config.py

@@ -7,7 +7,7 @@ from datetime import datetime, time
 
 from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.GeneralInvite.config_invite import InviteConfig
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 
@@ -38,7 +38,7 @@ class OrochiConfig(ConfigBase):
     # 层数
     layer: Layer = Field(default=Layer.ELEVEN, description='layer_help')
     # 限制时间
-    limit_time: time = Field(default=time(minute=30), description='limit_time_help')
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制次数
     limit_count: int = Field(default=30, description='limit_count_help')
     # 是否开启御魂加成

+ 1 - 1
tasks/Pets/assets.py

@@ -12,7 +12,7 @@ class PetsAssets:
 
 	# Image Rule Assets
 	# 宠物小屋 
-	I_PET_HOUSE = RuleImage(roi_front=(1015,431,27,31), roi_back=(952,412,144,60), threshold=0.7, method="Template matching", file="./tasks/Pets/pet/pet_pet_house.png")
+	I_PET_HOUSE = RuleImage(roi_front=(1055,434,27,31), roi_back=(952,412,144,60), threshold=0.7, method="Template matching", file="./tasks/Pets/pet/pet_pet_house.png")
 	# 爪印 
 	I_PET_CLAW = RuleImage(roi_front=(1171,625,55,56), roi_back=(1171,625,55,56), threshold=0.8, method="Template matching", file="./tasks/Pets/pet/pet_pet_claw.png")
 	# 其乐融融 

+ 1 - 1
tasks/Pets/pet/image.json

@@ -2,7 +2,7 @@
   {
     "itemName": "pet_house",
     "imageName": "pet_pet_house.png",
-    "roiFront": "1015,431,27,31",
+    "roiFront": "1055,434,27,31",
     "roiBack": "952,412,144,60",
     "method": "Template matching",
     "threshold": 0.7,

BIN
tasks/Pets/pet/pet_pet_house.png


+ 1 - 1
tasks/Restart/assets.py

@@ -68,6 +68,6 @@ class RestartAssets:
 	# 点击屏幕跳过 
 	O_LOGIN_SKIP_1 = RuleOcr(roi=(1046,35,130,37), area=(1046,35,130,37), mode="Single", method="Default", keyword="点击屏幕跳过", name="login_skip_1")
 	# 登录指定角色,默认第一个 
-	O_LOGIN_SPECIFIC_SERVE = RuleOcr(roi=(524,600,242,53), area=(516,75,662,585), mode="Single", method="Default", keyword="游戏", name="login_specific_serve")
+	O_LOGIN_SPECIFIC_SERVE = RuleOcr(roi=(694,605,59,34), area=(516,75,662,585), mode="Single", method="Default", keyword="游戏", name="login_specific_serve")
 
 

+ 1 - 1
tasks/Restart/login.py

@@ -34,7 +34,7 @@ class LoginHandler(BaseTask, RestartAssets):
             self.screenshot()
 
             # 确认进入庭院
-            if self.appear_then_click(self.I_LOGIN_SCROOLL_CLOSE, interval=2):
+            if self.appear_then_click(self.I_LOGIN_SCROOLL_CLOSE, interval=2, threshold=0.85):
                 logger.info('Open scroll')
                 continue
             if self.appear(self.I_LOGIN_SCROOLL_OPEN, interval=0.2):

+ 1 - 1
tasks/Restart/login/ocr.json

@@ -28,7 +28,7 @@
   },
   {
     "itemName": "login_specific_serve",
-    "roiFront": "524,600,242,53",
+    "roiFront": "694,605,59,34",
     "roiBack": "516,75,662,585",
     "mode": "Single",
     "method": "Default",

+ 1 - 1
tasks/Restart/script_task.py

@@ -53,7 +53,7 @@ if __name__ == '__main__':
     config = Config('oas2')
     device = Device(config)
     task = ScriptTask(config, device)
-    task.app_start()
+    task.app_restart()
 
 
 

+ 1 - 1
tasks/RichMan/mall/medal.py

@@ -67,7 +67,7 @@ if __name__ == '__main__':
     from module.config.config import Config
     from module.device.device import Device
 
-    c = Config('test')
+    c = Config('oas1')
     d = Device(c)
     t = Medal(c, d)
 

+ 1 - 1
tasks/RichMan/mall/special.py

@@ -161,7 +161,7 @@ class Special(Buy, MallNavbar):
         # logger.info(f'上中点是:{upper_midpoint}')
         # logger.info(f'数字的ROI是: {self.O_SP_RES_NUMBER.roi}')
         result = self.O_SP_RES_NUMBER.ocr(self.device.image)
-        result = result.replace('?', '2').replace('?', '2').replace(':', ';')
+        result = result.replace('?', '2').replace('?', '2').replace(':', ';').replace('火', '次').replace('教', '数')
         try:
             if ':' in result:
                 result = re.findall(r'剩余购买次数:(\d+)', result)[0]

+ 100 - 0
tasks/RyouToppa/assets.py

@@ -10,6 +10,106 @@ from module.atom.list import RuleList
 class RyouToppaAssets: 
 
 
+	# Click Rule Assets
+	# area1 
+	C_AREA_1 = RuleClick(roi_front=(533,162,177,74), roi_back=(533,162,177,74), name="area_1")
+	# area2 
+	C_AREA_2 = RuleClick(roi_front=(863,164,181,71), roi_back=(863,164,181,71), name="area_2")
+	# area3 
+	C_AREA_3 = RuleClick(roi_front=(532,292,181,87), roi_back=(532,292,181,87), name="area_3")
+	# area4 
+	C_AREA_4 = RuleClick(roi_front=(863,301,171,62), roi_back=(863,301,171,62), name="area_4")
+	# area5 
+	C_AREA_5 = RuleClick(roi_front=(540,432,169,68), roi_back=(540,432,169,68), name="area_5")
+	# area6 
+	C_AREA_6 = RuleClick(roi_front=(876,432,165,74), roi_back=(876,432,165,74), name="area_6")
+	# area7 
+	C_AREA_7 = RuleClick(roi_front=(538,557,149,71), roi_back=(538,557,149,71), name="area_7")
+	# area8 
+	C_AREA_8 = RuleClick(roi_front=(876,562,150,67), roi_back=(876,562,150,67), name="area_8")
+	# 在点击进攻后如果未进入战斗画面则点击的安全区域 
+	C_SAFE_AREA = RuleClick(roi_front=(182,213,160,229), roi_back=(182,213,160,229), name="safe_area")
+
+
+	# Image Rule Assets
+	# 区域1攻略失败 
+	I_AREA_1_IS_FAILURE = RuleImage(roi_front=(673,146,63,32), roi_back=(421,127,325,134), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域2攻略失败 
+	I_AREA_2_IS_FAILURE = RuleImage(roi_front=(1011,146,63,30), roi_back=(757,125,327,140), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域3攻略失败 
+	I_AREA_3_IS_FAILURE = RuleImage(roi_front=(665,283,73,40), roi_back=(419,254,327,144), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域4攻略失败 
+	I_AREA_4_IS_FAILURE = RuleImage(roi_front=(1000,283,72,38), roi_back=(756,260,325,139), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域5攻略失败 
+	I_AREA_5_IS_FAILURE = RuleImage(roi_front=(669,419,65,29), roi_back=(418,392,328,142), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域6攻略失败 
+	I_AREA_6_IS_FAILURE = RuleImage(roi_front=(988,416,84,37), roi_back=(755,395,328,141), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域7攻略失败 
+	I_AREA_7_IS_FAILURE = RuleImage(roi_front=(672,556,61,37), roi_back=(420,530,326,127), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域8攻略失败 
+	I_AREA_8_IS_FAILURE = RuleImage(roi_front=(1004,556,64,29), roi_back=(756,530,327,124), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_1.png")
+	# 区域1攻略失败(最近一次) 
+	I_AREA_1_IS_FAILURE_NEW = RuleImage(roi_front=(673,146,63,32), roi_back=(421,123,325,138), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区域2攻略失败(最近一次) 
+	I_AREA_2_IS_FAILURE_NEW = RuleImage(roi_front=(1011,146,63,30), roi_back=(757,126,327,139), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区域3攻略失败(最近一次) 
+	I_AREA_3_IS_FAILURE_NEW = RuleImage(roi_front=(665,283,73,40), roi_back=(419,261,327,137), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区4攻略失败(最近一次) 
+	I_AREA_4_IS_FAILURE_NEW = RuleImage(roi_front=(1000,283,72,38), roi_back=(756,258,325,141), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区域5攻略失败(最近一次) 
+	I_AREA_5_IS_FAILURE_NEW = RuleImage(roi_front=(669,419,65,29), roi_back=(418,394,328,140), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区域6攻略失败(最近一次) 
+	I_AREA_6_IS_FAILURE_NEW = RuleImage(roi_front=(988,416,84,37), roi_back=(755,395,328,141), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区域7攻略失败(最近一次) 
+	I_AREA_7_IS_FAILURE_NEW = RuleImage(roi_front=(672,556,61,37), roi_back=(420,533,326,124), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+	# 区域8攻略失败(最近一次) 
+	I_AREA_8_IS_FAILURE_NEW = RuleImage(roi_front=(1004,556,64,29), roi_back=(756,532,327,122), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/loser_sign_2.png")
+
+
+	# Image Rule Assets
+	# 区域1已攻破 
+	I_AREA_1_FINISHED = RuleImage(roi_front=(658,141,93,91), roi_back=(421,127,325,134), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域2已攻破 
+	I_AREA_2_FINISHED = RuleImage(roi_front=(983,137,100,100), roi_back=(757,125,327,140), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域3已攻破 
+	I_AREA_3_FINISHED = RuleImage(roi_front=(681,312,47,37), roi_back=(419,254,327,144), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域4已攻破 
+	I_AREA_4_FINISHED = RuleImage(roi_front=(996,271,100,100), roi_back=(756,260,325,139), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域5已攻破 
+	I_AREA_5_FINISHED = RuleImage(roi_front=(647,404,100,100), roi_back=(418,392,328,142), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域6已攻破 
+	I_AREA_6_FINISHED = RuleImage(roi_front=(1015,448,56,35), roi_back=(755,395,328,141), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域7已攻破 
+	I_AREA_7_FINISHED = RuleImage(roi_front=(643,543,100,100), roi_back=(420,530,326,127), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域8已攻破 
+	I_AREA_8_FINISHED = RuleImage(roi_front=(983,541,100,100), roi_back=(756,530,327,124), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_1.png")
+	# 区域1已攻破新 
+	I_AREA_1_FINISHED_NEW = RuleImage(roi_front=(658,141,93,91), roi_back=(421,127,325,134), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域2已攻破新 
+	I_AREA_2_FINISHED_NEW = RuleImage(roi_front=(983,137,100,100), roi_back=(757,125,327,140), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域3已攻破新 
+	I_AREA_3_FINISHED_NEW = RuleImage(roi_front=(681,312,47,37), roi_back=(419,254,327,144), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域4已攻破新 
+	I_AREA_4_FINISHED_NEW = RuleImage(roi_front=(996,271,100,100), roi_back=(756,260,325,139), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域5已攻破新 
+	I_AREA_5_FINISHED_NEW = RuleImage(roi_front=(647,404,100,100), roi_back=(418,392,328,142), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域6已攻破新 
+	I_AREA_6_FINISHED_NEW = RuleImage(roi_front=(1015,448,56,35), roi_back=(755,395,328,141), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域7已攻破新 
+	I_AREA_7_FINISHED_NEW = RuleImage(roi_front=(643,543,100,100), roi_back=(420,530,326,127), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+	# 区域8已攻破新 
+	I_AREA_8_FINISHED_NEW = RuleImage(roi_front=(983,541,100,100), roi_back=(756,530,327,124), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/finished_2.png")
+
+
+	# Image Rule Assets
+	# description 
+	I_TOPPA_RECORD = RuleImage(roi_front=(66,628,64,39), roi_back=(66,628,64,39), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/res_toppa_record.png")
+	# description 
+	I_TOPPA_LOCK_TEAM = RuleImage(roi_front=(201,601,30,36), roi_back=(201,601,30,36), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/dev_toppa_lock_team.png")
+	# description 
+	I_TOPPA_UNLOCK_TEAM = RuleImage(roi_front=(199,603,31,31), roi_back=(199,603,31,31), threshold=0.8, method="Template matching", file="./tasks/RyouToppa/dev/dev_toppa_unlock_team.png")
+
+
 	# Click Rule Assets
 	# 选择第一个寮 
 	C_SELECT_FIRST_RYOU = RuleClick(roi_front=(1148,138,21,22), roi_back=(1148,138,21,22), name="select_first_ryou")

Некоторые файлы не были показаны из-за большого количества измененных файлов