script.py 20 KB

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