script.py 21 KB

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