script.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import zerorpc
  5. import zmq
  6. import msgpack
  7. import random
  8. import re
  9. import cv2
  10. import time
  11. import os
  12. import inflection
  13. import asyncio
  14. import json
  15. from datetime import date
  16. import threading
  17. from typing import Callable
  18. from datetime import datetime, timedelta
  19. from pathlib import Path
  20. from cached_property import cached_property
  21. from pydantic import BaseModel, ValidationError
  22. from threading import Thread
  23. from multiprocessing.queues import Queue
  24. from module.config.utils import convert_to_underscore
  25. from module.config.config import Config
  26. from module.config.config_model import ConfigModel
  27. from module.device.device import Device
  28. from module.device.env import IS_WINDOWS
  29. from module.base.utils import load_module
  30. from module.base.decorator import del_cached_property
  31. from module.logger import logger
  32. from module.exception import *
  33. from module.server.i18n import I18n
  34. _log_switch_lock = threading.Lock()#线程锁
  35. class Script:
  36. def __init__(self, config_name: str ='oas') -> None:
  37. logger.hr('Start', level=0)
  38. self.server = None
  39. self.state_queue: Queue = None
  40. self.gui_update_task: Callable = None # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
  41. self.config_name = config_name
  42. # Skip first restart
  43. self.is_first_task = True
  44. # Failure count of tasks
  45. # Key: str, task name, value: int, failure count
  46. self.failure_record = {}
  47. # 运行loop的线程
  48. self.loop_thread: Thread = None
  49. @cached_property
  50. def config(self) -> "Config":
  51. try:
  52. from module.config.config import Config
  53. config = Config(config_name=self.config_name)
  54. return config
  55. except RequestHumanTakeover:
  56. logger.critical('Request human takeover')
  57. exit(1)
  58. except Exception as e:
  59. logger.exception(e)
  60. exit(1)
  61. @cached_property
  62. def device(self) -> "Device":
  63. try:
  64. from module.device.device import Device
  65. device = Device(config=self.config)
  66. return device
  67. except RequestHumanTakeover:
  68. logger.critical('Request human takeover')
  69. exit(1)
  70. except Exception as e:
  71. logger.exception(e)
  72. exit(1)
  73. @cached_property
  74. def checker(self):
  75. """
  76. 占位函数,在alas中是检查服务器是否正常的
  77. :return:
  78. """
  79. return None
  80. def save_error_log(self):
  81. """
  82. Save last 60 screenshots in ./log/error/<timestamp>
  83. Save logs to ./log/error/<timestamp>/log.txt
  84. """
  85. from module.base.utils import save_image
  86. from module.handler.sensitive_info import (handle_sensitive_image,
  87. handle_sensitive_logs)
  88. if self.config.script.error.save_error:
  89. if not os.path.exists('./log/error'):
  90. os.mkdir('./log/error')
  91. folder_name = str(int(time.time() * 1000))
  92. folder = f'./log/error/{folder_name}'
  93. logger.warning(f'Saving error: {folder}')
  94. logger.info('保存详细错误的日志和截图到路径:')
  95. logger.info(f'{str( Path.cwd() / "log" / "error" / folder_name)}')
  96. os.mkdir(folder)
  97. for data in self.device.screenshot_deque:
  98. image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
  99. image = handle_sensitive_image(data['image'])
  100. save_image(image, f'{folder}/{image_time}.png')
  101. with open(logger.log_file, 'r', encoding='utf-8') as f:
  102. lines = f.readlines()
  103. start = 0
  104. for index, line in enumerate(lines):
  105. line = line.strip(' \r\t\n')
  106. if re.match('^═{15,}$', line):
  107. start = index
  108. lines = lines[start - 2:]
  109. lines = handle_sensitive_logs(lines)
  110. with open(f'{folder}/log.txt', 'w', encoding='utf-8') as f:
  111. f.writelines(lines)
  112. def init_server(self, port: int) -> int:
  113. """
  114. 初始化zerorpc服务,返回端口号
  115. :return:
  116. """
  117. self.server = zerorpc.Server(self)
  118. try:
  119. self.server.bind(f'tcp://127.0.0.1:{port}')
  120. return port
  121. except zmq.error.ZMQError:
  122. logger.error(f"Ocr server cannot bind on port {port}")
  123. return None
  124. def run_server(self) -> None:
  125. """
  126. 启动zerorpc服务
  127. :return:
  128. """
  129. self.server.run()
  130. def gui_args(self, task: str) -> str:
  131. """
  132. 获取给gui显示的参数
  133. :return:
  134. """
  135. return self.config.gui_args(task=task)
  136. def gui_menu(self) -> str:
  137. """
  138. 获取给gui显示的菜单
  139. :return:
  140. """
  141. return self.config.gui_menu
  142. def gui_task(self, task: str) -> str:
  143. """
  144. 获取给gui显示的任务 的参数的具体值
  145. :return:
  146. """
  147. return self.config.model.gui_task(task=task)
  148. def gui_set_task(self, task: str, group: str, argument: str, value) -> bool:
  149. """
  150. 设置给gui显示的任务 的参数的具体值
  151. :return:
  152. """
  153. # 验证参数
  154. task = convert_to_underscore(task)
  155. group = convert_to_underscore(group)
  156. argument = convert_to_underscore(argument)
  157. # pandtic验证
  158. if isinstance(value, str):
  159. if len(value) == 8:
  160. try:
  161. value = datetime.strptime(value, '%H:%M:%S').time()
  162. except ValueError:
  163. pass
  164. path = f'{task}.{group}.{argument}'
  165. task_object = getattr(self.config.model, task, None)
  166. group_object = getattr(task_object, group, None)
  167. argument_object = getattr(group_object, argument, None)
  168. if argument_object is None:
  169. logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
  170. return False
  171. try:
  172. setattr(group_object, argument, value)
  173. argument_object = getattr(group_object, argument, None)
  174. logger.info(f'Set arg {task}.{group}.{argument}.{argument_object}')
  175. self.config.save() # 我是没有想到什么方法可以使得属性改变自动保存的
  176. return True
  177. except ValidationError as e:
  178. logger.error(e)
  179. return False
  180. @zerorpc.stream
  181. def gui_mirror_image(self):
  182. """
  183. 获取给gui显示的镜像
  184. :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
  185. """
  186. # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
  187. img = cv2.cvtColor(self.device.screenshot(), cv2.COLOR_RGB2BGR)
  188. self.device.stuck_record_clear()
  189. ret, buffer = cv2.imencode('.jpg', img)
  190. yield buffer.tobytes()
  191. def _gui_update_tasks(self) -> None:
  192. """
  193. 获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
  194. :return:
  195. """
  196. data = {}
  197. pending = []
  198. waiting = []
  199. task = {}
  200. if self.config.task is not None and self.config.task.next_run < datetime.now():
  201. task["name"] = self.config.task.command
  202. task["next_run"] = str(self.config.task.next_run)
  203. data["task"] = task
  204. for p in self.config.pending_task[1:]:
  205. item = {"name": p.command, "next_run": str(p.next_run)}
  206. pending.append(item)
  207. for w in self.config.waiting_task:
  208. item = {"name": w.command, "next_run": str(w.next_run)}
  209. waiting.append(item)
  210. data["pending"] = pending
  211. data["waiting"] = waiting
  212. if self.gui_update_task is not None:
  213. self.gui_update_task(data)
  214. def _gui_set_status(self, status: str) -> None:
  215. """
  216. 设置给gui显示的状态
  217. :param status: 可以在gui中显示的状态 有 "Init", "Empty"(不显示), "Run"(运行中), "Error", "Free"(空闲)
  218. :return:
  219. """
  220. data = {"status": status}
  221. if self.gui_update_task is not None:
  222. self.gui_update_task(data)
  223. def gui_task_list(self) -> str:
  224. """
  225. 获取给gui显示的任务列表
  226. :return:
  227. """
  228. result = {}
  229. for key, value in self.config.model.dict().items():
  230. if isinstance(value, str):
  231. continue
  232. if key == "restart":
  233. continue
  234. if "scheduler" not in value:
  235. continue
  236. scheduler = value["scheduler"]
  237. item = {"enable": scheduler["enable"],
  238. "next_run": str(scheduler["next_run"])}
  239. key = self.config.model.type(key)
  240. result[key] = item
  241. return json.dumps(result)
  242. def wait_until(self, future):
  243. """
  244. Wait until a specific time.
  245. Args:
  246. future (datetime):
  247. Returns:
  248. bool: True if wait finished, False if config changed.
  249. """
  250. future = future + timedelta(seconds=1)
  251. self.config.start_watching()
  252. while 1:
  253. if datetime.now() > future:
  254. return True
  255. # if self.stop_event is not None:
  256. # if self.stop_event.is_set():
  257. # logger.info("Update event detected")
  258. # logger.info(f"[{self.config_name}] exited. Reason: Update")
  259. # exit(0)
  260. time.sleep(5)
  261. if self.config.should_reload():
  262. return False
  263. def get_next_task(self) -> str:
  264. """
  265. 获取下一个任务的名字, 大驼峰。
  266. :return:
  267. """
  268. while True:
  269. task = self.config.get_next()
  270. self.config.task = task
  271. if self.state_queue:
  272. self.state_queue.put({"schedule": self.config.get_schedule_data()})
  273. now = datetime.now()
  274. # 任务时间到了返回任务名称
  275. if task.next_run <= now:
  276. return task.command
  277. # 根据策略执行等待逻辑
  278. if not self._handle_wait_during_idle(task.next_run):
  279. # 若等待被打断, 则刷新配置
  280. del_cached_property(self, "config")
  281. def _handle_wait_during_idle(self, next_run: datetime) -> bool:
  282. """
  283. 处理任务空闲期间的行为策略
  284. :param next_run: 下一个任务的时间
  285. :return: True 表示等待成功完成, False 表示等待被中断
  286. """
  287. method = self.config.script.optimization.when_task_queue_empty
  288. strategy_map = {
  289. "close_game": self._wait_close_game,
  290. "goto_main": self._wait_goto_main,
  291. }
  292. func = strategy_map.get(method)
  293. if not func:
  294. logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
  295. func = self._wait_stay_there
  296. return func(next_run)
  297. def _wait_close_game(self, next_run: datetime) -> bool:
  298. logger.info("Close game during wait")
  299. self.device.app_stop()
  300. self.device.release_during_wait()
  301. if not self.wait_until(next_run):
  302. return False
  303. self.run("Restart")
  304. return True
  305. def _wait_goto_main(self, next_run: datetime) -> bool:
  306. logger.info("Goto main page during wait")
  307. self.run("GotoMain")
  308. self.device.release_during_wait()
  309. return self.wait_until(next_run)
  310. def _wait_stay_there(self, next_run: datetime) -> bool:
  311. logger.info("Stay_there (no action) during wait")
  312. self.device.release_during_wait()
  313. return self.wait_until(next_run)
  314. def exception_handler(self, e: Exception, command: str) -> None:
  315. # 处理御魂溢出
  316. from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
  317. image = getattr(self.device, 'image', None)
  318. # image为None则不做处理
  319. if image is None:
  320. return
  321. analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
  322. if analyse_type == AnalyzeType.SoulOverflow:
  323. self.config.task_call('SoulsTidy')
  324. time.sleep(1)
  325. def run(self, command: str) -> bool:
  326. """
  327. :param command: 大写驼峰命名的任务名字
  328. :return:
  329. """
  330. if command == 'start' or command == 'goto_main':
  331. logger.error(f'Invalid command `{command}`')
  332. try:
  333. self.device.screenshot()
  334. module_name = 'script_task'
  335. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  336. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  337. task_module = load_module(module_name, module_path)
  338. task_module.ScriptTask(config=self.config, device=self.device).run()
  339. except TaskEnd:
  340. return True
  341. except GameNotRunningError as e:
  342. logger.warning(e)
  343. self.exception_handler(e=e, command=command)
  344. self.config.task_call('Restart')
  345. return True
  346. except (GameStuckError, GameTooManyClickError) as e:
  347. logger.error(e)
  348. self.save_error_log()
  349. self.exception_handler(e=e, command=command)
  350. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  351. logger.warning('If you are playing by hand, please stop Alas')
  352. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  353. self.config.task_call('Restart')
  354. self.device.sleep(10)
  355. return False
  356. except GameBugError as e:
  357. logger.warning(e)
  358. self.save_error_log()
  359. self.exception_handler(e=e, command=command)
  360. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  361. logger.warning(f'Restarting {self.device.package} to fix it')
  362. self.config.task_call('Restart')
  363. self.device.sleep(10)
  364. return False
  365. except GamePageUnknownError as e:
  366. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  367. # 这个还不重要 留着坑填
  368. logger.critical('Game page unknown')
  369. self.save_error_log()
  370. self.exception_handler(e=e, command=command)
  371. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GamePageUnknownError")
  372. self.config.task_call('Restart')
  373. self.device.sleep(10)
  374. return False
  375. except ScriptError as e:
  376. logger.critical(e)
  377. self.exception_handler(e=e, command=command)
  378. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  379. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> ScriptError")
  380. exit(1)
  381. except RequestHumanTakeover as e:
  382. logger.critical(e)
  383. self.exception_handler(e=e, command=command)
  384. logger.critical('Request human takeover')
  385. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> RequestHumanTakeover")
  386. exit(1)
  387. except Exception as e:
  388. logger.exception(e)
  389. self.exception_handler(e=e, command=command)
  390. self.save_error_log()
  391. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> Exception occured")
  392. exit(1)
  393. def loop(self):
  394. """
  395. Main loop of scheduler.
  396. :return:
  397. """
  398. with _log_switch_lock:
  399. logger.set_file_logger(self.config_name, do_cleanup=True)
  400. start_day = date.today()
  401. logger.info(f'Start scheduler loop: {self.config_name}')
  402. self.config.model.running_task = ''
  403. # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
  404. if not self.config.script.device.run_background_only and IS_WINDOWS:
  405. from module.device.platform2.platform_windows import minimize_by_name, show_window_by_name
  406. target_window_name = self.config.script.device.handle # 在这里输入你的具体窗口名称
  407. if self.config.script.device.emulator_window_minimize:
  408. minimize_by_name(target_window_name)
  409. logger.info(f'重新显示: {target_window_name}')
  410. else:
  411. show_window_by_name(target_window_name)
  412. while 1:
  413. if date.today() > start_day:
  414. with _log_switch_lock:
  415. logger.set_file_logger(self.config_name, do_cleanup=True)
  416. start_day = date.today()
  417. # Check update event from GUI
  418. # if self.stop_event is not None:
  419. # if self.stop_event.is_set():
  420. # logger.info("Update event detected")
  421. # logger.info(f"Alas [{self.config_name}] exited.")
  422. # break
  423. # Check game server maintenance
  424. # self.checker.wait_until_available()
  425. # if self.checker.is_recovered():
  426. # # There is an accidental bug hard to reproduce
  427. # # Sometimes, config won't be updated due to blocking
  428. # # even though it has been changed
  429. # # So update it once recovered
  430. # del_cached_property(self, 'config')
  431. # logger.info('Server or network is recovered. Restart game client')
  432. # self.config.task_call('Restart')
  433. # Get task
  434. task = self.get_next_task()
  435. _ = self.device
  436. # Skip first restart
  437. if self.is_first_task and task == 'Restart':
  438. logger.info('Skip task `Restart` at scheduler start')
  439. self.config.task_delay(task='Restart', success=True, server=True)
  440. del_cached_property(self, 'config')
  441. continue
  442. # Run
  443. logger.info(f'Scheduler: Start task `{task}`')
  444. self.device.stuck_record_clear()
  445. self.device.click_record_clear()
  446. logger.hr(task, level=0)
  447. self.config.model.running_task = task
  448. success = self.run(inflection.camelize(task))
  449. self.config.model.running_task = ''
  450. logger.info(f'Scheduler: End task `{task}`')
  451. self.is_first_task = False
  452. # Check failures
  453. # failed = deep_get(self.failure_record, keys=task, default=0)
  454. failed = self.failure_record[task] if task in self.failure_record else 0
  455. failed = 0 if success else failed + 1
  456. # deep_set(self.failure_record, keys=task, value=failed)
  457. self.failure_record[task] = failed
  458. if failed >= 3:
  459. logger.critical(f"Task `{task}` failed 3 or more times.")
  460. logger.critical("Possible reason #1: You haven't used it correctly. "
  461. "Please read the help text of the options.")
  462. logger.critical("Possible reason #2: There is a problem with this task. "
  463. "Please contact developers or try to fix it yourself.")
  464. logger.critical('Request human takeover')
  465. # 添加失败三次的推送通知
  466. self.config.notifier.push(
  467. title=f'{I18n.trans_zh_cn(task)}{task}',
  468. content=f"<{self.config_name}> 任务连续失败三次,请上线查看"
  469. )
  470. # 关闭模拟器
  471. if self.config.script.error.error_repeated:
  472. self.device.emulator_stop()
  473. exit(1)
  474. if success:
  475. del_cached_property(self, 'config')
  476. continue
  477. elif self.config.script.error.handle_error:
  478. # self.config.task_delay(success=False)
  479. del_cached_property(self, 'config')
  480. # self.checker.check_now()
  481. continue
  482. else:
  483. break
  484. def start_loop(self) -> None:
  485. """
  486. 创建一个线程,运行loop
  487. :return:
  488. """
  489. if self.loop_thread is None:
  490. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  491. self.loop_thread.start()
  492. if __name__ == "__main__":
  493. script = Script("oas1")
  494. script.loop()