script.py 18 KB

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