script.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from functools import wraps
  5. import zerorpc
  6. import zmq
  7. import msgpack
  8. import random
  9. import re
  10. import cv2
  11. import time
  12. import os
  13. import inflection
  14. import asyncio
  15. import json
  16. from datetime import date
  17. import threading
  18. from typing import Callable
  19. from datetime import datetime, timedelta
  20. from pathlib import Path
  21. from cached_property import cached_property
  22. from pydantic import BaseModel, ValidationError
  23. from threading import Thread
  24. from multiprocessing.queues import Queue
  25. from module.config.utils import convert_to_underscore
  26. from module.config.config import Config
  27. from module.config.config_model import ConfigModel
  28. from module.config.instance_guard import InstanceGuard
  29. from module.config.anti_ban import AntiBanGuard
  30. from module.device.device import Device
  31. from module.device.env import IS_WINDOWS
  32. from module.base.utils import load_module
  33. from module.base.decorator import del_cached_property
  34. from module.logger import logger
  35. from module.exception import *
  36. from module.server.i18n import I18n
  37. from module.ocr.rpc import ensure_ocr_server_started
  38. _log_switch_lock = threading.Lock()#线程锁
  39. class Script:
  40. def __init__(self, config_name: str ='oas') -> None:
  41. logger.hr('Start', level=0)
  42. self.server = None
  43. self.state_queue: Queue = None
  44. self._emulator_down = False
  45. self.gui_update_task: Callable = None # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
  46. self.config_name = config_name
  47. # Skip first restart
  48. self.is_first_task = True
  49. # Failure count of tasks
  50. # Key: str, task name, value: int, failure count
  51. self.failure_record = {}
  52. # 运行loop的线程
  53. self.loop_thread: Thread = None
  54. # 跨进程排队管理器(仅在 queue_mode=True 时初始化)
  55. self.instance_guard: InstanceGuard = None
  56. self.anti_ban_guard: AntiBanGuard = AntiBanGuard()
  57. @cached_property
  58. def config(self) -> "Config":
  59. try:
  60. from module.config.config import Config
  61. config = Config(config_name=self.config_name)
  62. return config
  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 device(self) -> "Device":
  71. try:
  72. from module.device.device import Device
  73. device = Device(config=self.config)
  74. return device
  75. except RequestHumanTakeover:
  76. logger.critical('Request human takeover')
  77. exit(1)
  78. except Exception as e:
  79. logger.exception(e)
  80. exit(1)
  81. @cached_property
  82. def checker(self):
  83. """
  84. 占位函数,在alas中是检查服务器是否正常的
  85. :return:
  86. """
  87. return None
  88. def save_error_log(self):
  89. """
  90. Save last 60 screenshots in ./log/error/<timestamp>
  91. Save logs to ./log/error/<timestamp>/log.txt
  92. """
  93. from module.base.utils import save_image
  94. from module.handler.sensitive_info import (handle_sensitive_image,
  95. handle_sensitive_logs)
  96. if self.config.script.error.save_error:
  97. if not os.path.exists('./log/error'):
  98. os.mkdir('./log/error')
  99. folder_name = str(int(time.time() * 1000))
  100. folder = f'./log/error/{folder_name}'
  101. logger.warning(f'Saving error: {folder}')
  102. logger.info('保存详细错误的日志和截图到路径:')
  103. logger.info(f'{str( Path.cwd() / "log" / "error" / folder_name)}')
  104. os.mkdir(folder)
  105. for data in self.device.screenshot_deque:
  106. image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
  107. image = handle_sensitive_image(data['image'])
  108. save_image(image, f'{folder}/{image_time}.png')
  109. with open(logger.log_file, 'r', encoding='utf-8') as f:
  110. lines = f.readlines()
  111. start = 0
  112. for index, line in enumerate(lines):
  113. line = line.strip(' \r\t\n')
  114. if re.match('^═{15,}$', line):
  115. start = index
  116. lines = lines[start - 2:]
  117. lines = handle_sensitive_logs(lines)
  118. with open(f'{folder}/log.txt', 'w', encoding='utf-8') as f:
  119. f.writelines(lines)
  120. def init_server(self, port: int) -> int:
  121. """
  122. 初始化zerorpc服务,返回端口号
  123. :return:
  124. """
  125. self.server = zerorpc.Server(self)
  126. try:
  127. self.server.bind(f'tcp://127.0.0.1:{port}')
  128. return port
  129. except zmq.error.ZMQError:
  130. logger.error(f"Ocr server cannot bind on port {port}")
  131. return None
  132. def run_server(self) -> None:
  133. """
  134. 启动zerorpc服务
  135. :return:
  136. """
  137. self.server.run()
  138. def gui_args(self, task: str) -> str:
  139. """
  140. 获取给gui显示的参数
  141. :return:
  142. """
  143. return self.config.gui_args(task=task)
  144. def gui_menu(self) -> str:
  145. """
  146. 获取给gui显示的菜单
  147. :return:
  148. """
  149. return self.config.gui_menu
  150. def gui_task(self, task: str) -> str:
  151. """
  152. 获取给gui显示的任务 的参数的具体值
  153. :return:
  154. """
  155. return self.config.model.gui_task(task=task)
  156. def gui_set_task(self, task: str, group: str, argument: str, value) -> bool:
  157. """
  158. 设置给gui显示的任务 的参数的具体值
  159. :return:
  160. """
  161. # 验证参数
  162. task = convert_to_underscore(task)
  163. group = convert_to_underscore(group)
  164. argument = convert_to_underscore(argument)
  165. # pandtic验证
  166. if isinstance(value, str):
  167. if len(value) == 8:
  168. try:
  169. value = datetime.strptime(value, '%H:%M:%S').time()
  170. except ValueError:
  171. pass
  172. path = f'{task}.{group}.{argument}'
  173. task_object = getattr(self.config.model, task, None)
  174. group_object = getattr(task_object, group, None)
  175. argument_object = getattr(group_object, argument, None)
  176. if argument_object is None:
  177. logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
  178. return False
  179. try:
  180. setattr(group_object, argument, value)
  181. argument_object = getattr(group_object, argument, None)
  182. logger.info(f'Set arg {task}.{group}.{argument}.{argument_object}')
  183. self.config.save() # 我是没有想到什么方法可以使得属性改变自动保存的
  184. return True
  185. except ValidationError as e:
  186. logger.error(e)
  187. return False
  188. @zerorpc.stream
  189. def gui_mirror_image(self):
  190. """
  191. 获取给gui显示的镜像
  192. :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
  193. """
  194. # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
  195. img = cv2.cvtColor(self.device.screenshot(), cv2.COLOR_RGB2BGR)
  196. self.device.stuck_record_clear()
  197. ret, buffer = cv2.imencode('.jpg', img)
  198. yield buffer.tobytes()
  199. def _gui_update_tasks(self) -> None:
  200. """
  201. 获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
  202. :return:
  203. """
  204. data = {}
  205. pending = []
  206. waiting = []
  207. task = {}
  208. if self.config.task is not None and self.config.task.next_run < datetime.now():
  209. task["name"] = self.config.task.command
  210. task["next_run"] = str(self.config.task.next_run)
  211. data["task"] = task
  212. for p in self.config.pending_task[1:]:
  213. item = {"name": p.command, "next_run": str(p.next_run)}
  214. pending.append(item)
  215. for w in self.config.waiting_task:
  216. item = {"name": w.command, "next_run": str(w.next_run)}
  217. waiting.append(item)
  218. data["pending"] = pending
  219. data["waiting"] = waiting
  220. if self.gui_update_task is not None:
  221. self.gui_update_task(data)
  222. def _gui_set_status(self, status: str) -> None:
  223. """
  224. 设置给gui显示的状态
  225. :param status: 可以在gui中显示的状态 有 "Init", "Empty"(不显示), "Run"(运行中), "Error", "Free"(空闲)
  226. :return:
  227. """
  228. data = {"status": status}
  229. if self.gui_update_task is not None:
  230. self.gui_update_task(data)
  231. def gui_task_list(self) -> str:
  232. """
  233. 获取给gui显示的任务列表
  234. :return:
  235. """
  236. result = {}
  237. for key, value in self.config.model.dict().items():
  238. if isinstance(value, str):
  239. continue
  240. if key == "restart":
  241. continue
  242. if "scheduler" not in value:
  243. continue
  244. scheduler = value["scheduler"]
  245. item = {"enable": scheduler["enable"],
  246. "next_run": str(scheduler["next_run"])}
  247. key = self.config.model.type(key)
  248. result[key] = item
  249. return json.dumps(result)
  250. def _release_token_before_wait(func):
  251. @wraps(func)
  252. def wrapper(self, future):
  253. if self.instance_guard and self.instance_guard.should_release(
  254. pending_task=self.config.pending_task,
  255. waiting_task=self.config.waiting_task,
  256. idle_threshold_minutes=self.config.script.optimization.queue_idle_threshold
  257. ):
  258. self.instance_guard.release()
  259. return func(self, future)
  260. return wrapper
  261. @_release_token_before_wait
  262. def wait_until(self, future):
  263. """
  264. Wait until a specific time.
  265. Args:
  266. future (datetime):
  267. Returns:
  268. bool: True if wait finished, False if config changed.
  269. """
  270. future = future + timedelta(seconds=1)
  271. self.config.start_watching()
  272. while 1:
  273. if datetime.now() > future:
  274. return True
  275. # if self.stop_event is not None:
  276. # if self.stop_event.is_set():
  277. # logger.info("Update event detected")
  278. # logger.info(f"[{self.config_name}] exited. Reason: Update")
  279. # exit(0)
  280. time.sleep(5)
  281. if self.config.should_reload():
  282. return False
  283. def get_next_task(self) -> str:
  284. """
  285. 获取下一个任务的名字, 大驼峰。
  286. 仅在当前任务执行结束后调用;防风控收尾在此处执行,不中断正在运行的任务。
  287. :return:
  288. """
  289. while True:
  290. task = self.config.get_next()
  291. self.config.task = task
  292. if self.state_queue:
  293. self.state_queue.put({"schedule": self.config.get_schedule_data()})
  294. now = datetime.now()
  295. antiban_wake = self.anti_ban_guard.wake_time(now, self.config.script.anti_ban)
  296. next_run = task.next_run
  297. if antiban_wake is not None:
  298. next_run = max(next_run, antiban_wake)
  299. if not self._try_acquire_queue_token():
  300. del_cached_property(self, "config")
  301. continue
  302. # 任务时间到了返回任务名称
  303. if next_run <= now:
  304. return task.command
  305. # 根据策略执行等待逻辑
  306. if not self._handle_wait_during_idle(next_run, anti_ban=antiban_wake is not None):
  307. # 若等待被打断, 则刷新配置
  308. del_cached_property(self, "config")
  309. def _try_acquire_queue_token(self) -> bool:
  310. """
  311. 尝试获取排队执行权。
  312. 如果排队模式未启用,返回 True。
  313. 如果排队模式启用但未能获取到执行权,进入等待循环直到获取成功或配置变更。
  314. Returns:
  315. True: 获取得执行权,可以执行任务
  316. False: 等待被配置变更打断,调用方应重新加载配置后重试
  317. """
  318. # 是否开启排队模式
  319. if not self.config.script.optimization.queue_mode:
  320. if self.instance_guard:
  321. self.instance_guard.remove_from_queue()
  322. self.instance_guard = None
  323. return True
  324. # 懒加载instance_guard
  325. if self.instance_guard is None:
  326. try:
  327. self.instance_guard = InstanceGuard(self.config_name)
  328. logger.info(f"[Queue] Queue mode enabled for '{self.config_name}'")
  329. except Exception:
  330. self.instance_guard = None
  331. return True
  332. # 尝试获取执行权
  333. if self.instance_guard.try_acquire():
  334. return True
  335. # 执行权获取失败,关闭模拟器并进入等待循环
  336. logger.info(f"[Queue] '{self.config_name}' waiting for execution token...")
  337. if (self.config.script.optimization.when_task_queue_empty == 'close_game'
  338. and not self._emulator_down
  339. and 'device' in self.__dict__):
  340. try:
  341. self.device.emulator_stop()
  342. self._emulator_down = True
  343. logger.info(f"[Queue] Emulator closed during queue wait")
  344. except Exception:
  345. pass
  346. self.config.start_watching()
  347. while True:
  348. time.sleep(30)
  349. if self.config.should_reload():
  350. logger.info(f"[Queue] Config changed, re-evaluating")
  351. return False
  352. if self.instance_guard.try_acquire():
  353. return True
  354. def _handle_wait_during_idle(self, next_run: datetime, anti_ban: bool = False) -> bool:
  355. """
  356. 处理任务空闲期间的行为策略
  357. :param next_run: 下一个任务的时间
  358. :param anti_ban: 防风控休息时立即按所选策略收尾,不应用普通空闲的关闭阈值
  359. :return: True 表示等待成功完成, False 表示等待被中断
  360. """
  361. method = self.config.script.optimization.when_task_queue_empty
  362. if anti_ban:
  363. logger.info(f"Anti-ban rest until {next_run}, cleanup: {method}")
  364. strategy_map = {
  365. "close_game": self._wait_close_game,
  366. "goto_main": self._wait_goto_main,
  367. }
  368. func = strategy_map.get(method)
  369. if func is None:
  370. logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
  371. return self._wait_stay_there(next_run)
  372. return func(next_run, anti_ban=anti_ban)
  373. @staticmethod
  374. def _time_to_timedelta(value) -> timedelta:
  375. if value is None:
  376. return timedelta(0)
  377. return timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)
  378. def _wait_until_with_emulator_preheat(self, next_run: datetime) -> bool:
  379. """Wait until next_run; if emulator is down, preheat startup before next task."""
  380. if not self._emulator_down:
  381. return self.wait_until(next_run)
  382. startup_lead = self._time_to_timedelta(self.config.script.optimization.emulator_startup_lead_time)
  383. now = datetime.now()
  384. wake_time = next_run - startup_lead if startup_lead > timedelta(0) else next_run
  385. if wake_time < now:
  386. wake_time = now
  387. now = datetime.now()
  388. if wake_time > now:
  389. logger.info(f"Wait before wake emulator: {wake_time.strftime('%Y-%m-%d %H:%M:%S')}")
  390. if not self.wait_until(wake_time):
  391. return False
  392. if self._emulator_down:
  393. logger.info("Wake emulator before next task")
  394. if not self._try_acquire_queue_token():
  395. return False
  396. self.device = Device(self.config)
  397. self._emulator_down = False
  398. if wake_time < next_run:
  399. return self.wait_until(next_run)
  400. return True
  401. def _wait_close_game(self, next_run: datetime, anti_ban: bool = False) -> bool:
  402. if self._emulator_down:
  403. if anti_ban:
  404. return self.wait_until(next_run)
  405. logger.info("Emulator is down, skip close_game/goto_main action and wait with preheat")
  406. return self._wait_until_with_emulator_preheat(next_run)
  407. close_game_wait_duration = self.config.script.optimization.close_game_wait_duration
  408. close_game_wait = self._time_to_timedelta(close_game_wait_duration)
  409. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  410. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  411. if not anti_ban and close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  412. logger.info("Close emulator during wait")
  413. self.device.emulator_stop()
  414. self._emulator_down = True
  415. if not self._wait_until_with_emulator_preheat(next_run):
  416. return False
  417. self.run("Restart")
  418. return True
  419. if anti_ban or close_game_wait <= timedelta(0):
  420. logger.info("Close game during wait")
  421. self.device.app_stop()
  422. self.device.release_during_wait()
  423. if not self.wait_until(next_run):
  424. return False
  425. self.run("Restart")
  426. return True
  427. if next_run > datetime.now() + close_game_wait:
  428. logger.info("Close game during wait")
  429. self.device.app_stop()
  430. self.device.release_during_wait()
  431. if not self.wait_until(next_run):
  432. return False
  433. self.run("Restart")
  434. return True
  435. logger.info("Wait without closing game (close_game wait duration not reached)")
  436. self.device.release_during_wait()
  437. if not self.wait_until(next_run):
  438. return False
  439. return True
  440. def _wait_goto_main(self, next_run: datetime, anti_ban: bool = False) -> bool:
  441. if self._emulator_down:
  442. if anti_ban:
  443. return self.wait_until(next_run)
  444. logger.info("Emulator is down, skip goto_main and wait with preheat")
  445. return self._wait_until_with_emulator_preheat(next_run)
  446. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  447. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  448. if not anti_ban and close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  449. logger.info("Close emulator during wait")
  450. self.device.emulator_stop()
  451. self._emulator_down = True
  452. if not self._wait_until_with_emulator_preheat(next_run):
  453. return False
  454. self.run("Restart")
  455. return True
  456. logger.info("Goto main page during wait")
  457. self.run("GotoMain")
  458. self.device.release_during_wait()
  459. return self.wait_until(next_run)
  460. def _wait_stay_there(self, next_run: datetime) -> bool:
  461. if self._emulator_down:
  462. logger.info("Stay_there during wait (emulator is down, with preheat)")
  463. return self._wait_until_with_emulator_preheat(next_run)
  464. logger.info("Stay_there (no action) during wait")
  465. self.device.release_during_wait()
  466. return self.wait_until(next_run)
  467. def exception_handler(self, e: Exception, command: str) -> None:
  468. # 处理御魂溢出
  469. from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
  470. image = getattr(self.device, 'image', None)
  471. # image为None则不做处理
  472. if image is None:
  473. return
  474. analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
  475. if analyse_type == AnalyzeType.SoulOverflow:
  476. self.config.task_call('SoulsTidy')
  477. time.sleep(1)
  478. def run(self, command: str) -> bool:
  479. """
  480. :param command: 大写驼峰命名的任务名字
  481. :return:
  482. """
  483. if command == 'start' or command == 'goto_main':
  484. logger.error(f'Invalid command `{command}`')
  485. if not self._try_acquire_queue_token():
  486. return False
  487. if self.instance_guard and self.instance_guard.token_lost:
  488. logger.warning(f'Token lost, stopping emulator and rejoining queue')
  489. try:
  490. self.device.emulator_stop()
  491. except Exception:
  492. pass
  493. self._emulator_down = True
  494. self.instance_guard.release()
  495. return False
  496. try:
  497. self.device.screenshot()
  498. module_name = 'script_task'
  499. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  500. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  501. task_module = load_module(module_name, module_path)
  502. task_module.ScriptTask(config=self.config, device=self.device).run()
  503. except TaskEnd:
  504. return True
  505. except GameNotRunningError as e:
  506. logger.warning(e)
  507. self.exception_handler(e=e, command=command)
  508. self.config.task_call('Restart')
  509. return True
  510. except GameOcrError as e:
  511. logger.error(e)
  512. try:
  513. self.save_error_log()
  514. except Exception:
  515. logger.exception('Failed to save OCR error log')
  516. logger.warning('Restarting game after repeated OCR failures')
  517. # 定时 Restart 可能被禁用,故障恢复直接执行重启任务。
  518. running_task = self.config.model.running_task
  519. try:
  520. self.config.model.running_task = 'Restart'
  521. self.run('Restart')
  522. finally:
  523. self.config.model.running_task = running_task
  524. return False
  525. except (GameStuckError, GameTooManyClickError) as e:
  526. logger.error(e)
  527. self.save_error_log()
  528. self.exception_handler(e=e, command=command)
  529. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  530. logger.warning('If you are playing by hand, please stop Alas')
  531. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  532. self.config.task_call('Restart')
  533. self.device.sleep(10)
  534. return False
  535. except GameBugError as e:
  536. logger.warning(e)
  537. self.save_error_log()
  538. self.exception_handler(e=e, command=command)
  539. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  540. logger.warning(f'Restarting {self.device.package} to fix it')
  541. self.config.task_call('Restart')
  542. self.device.sleep(10)
  543. return False
  544. except GamePageUnknownError as e:
  545. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  546. # 这个还不重要 留着坑填
  547. logger.critical('Game page unknown')
  548. self.save_error_log()
  549. self.exception_handler(e=e, command=command)
  550. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GamePageUnknownError")
  551. self.config.task_call('Restart')
  552. self.device.sleep(10)
  553. return False
  554. except ScriptError as e:
  555. logger.critical(e)
  556. self.exception_handler(e=e, command=command)
  557. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  558. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> ScriptError")
  559. exit(1)
  560. except RequestHumanTakeover as e:
  561. logger.critical(e)
  562. self.exception_handler(e=e, command=command)
  563. logger.critical('Request human takeover')
  564. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> RequestHumanTakeover")
  565. exit(1)
  566. except Exception as e:
  567. logger.exception(e)
  568. self.exception_handler(e=e, command=command)
  569. self.save_error_log()
  570. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> Exception occured")
  571. exit(1)
  572. def loop(self):
  573. """
  574. Main loop of scheduler.
  575. :return:
  576. """
  577. with _log_switch_lock:
  578. logger.set_file_logger(self.config_name, do_cleanup=True)
  579. start_day = date.today()
  580. logger.info(f'Start scheduler loop: {self.config_name}')
  581. self.config.model.running_task = ''
  582. self.anti_ban_guard.reset()
  583. # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
  584. if not self.config.script.device.run_background_only and IS_WINDOWS:
  585. from module.device.platform2.platform_windows import minimize_by_name, show_window_by_name
  586. target_window_name = self.config.script.device.handle # 在这里输入你的具体窗口名称
  587. if self.config.script.device.emulator_window_minimize:
  588. minimize_by_name(target_window_name)
  589. logger.info(f'重新显示: {target_window_name}')
  590. else:
  591. show_window_by_name(target_window_name)
  592. while 1:
  593. if date.today() > start_day:
  594. with _log_switch_lock:
  595. logger.set_file_logger(self.config_name, do_cleanup=True)
  596. start_day = date.today()
  597. # Check update event from GUI
  598. # if self.stop_event is not None:
  599. # if self.stop_event.is_set():
  600. # logger.info("Update event detected")
  601. # logger.info(f"Alas [{self.config_name}] exited.")
  602. # break
  603. # Check game server maintenance
  604. # self.checker.wait_until_available()
  605. # if self.checker.is_recovered():
  606. # # There is an accidental bug hard to reproduce
  607. # # Sometimes, config won't be updated due to blocking
  608. # # even though it has been changed
  609. # # So update it once recovered
  610. # del_cached_property(self, 'config')
  611. # logger.info('Server or network is recovered. Restart game client')
  612. # self.config.task_call('Restart')
  613. # 上一轮 self.run() 已返回,才检查防风控并调度下一个任务。
  614. task = self.get_next_task()
  615. # Skip first restart
  616. if self.is_first_task and task == 'Restart':
  617. logger.info('Skip task `Restart` at scheduler start')
  618. self.config.task_delay(task='Restart', success=True, server=True)
  619. del_cached_property(self, 'config')
  620. continue
  621. if self._emulator_down:
  622. self.device = Device(self.config)
  623. self._emulator_down = False
  624. else:
  625. _ = self.device
  626. # 桌面模式:客户端刚被自动拉起时停在登录页(_desktop_login_done=False),
  627. # 此时 app_is_running() 返回 False。若下一个任务是 gameplay,先强制走 Restart
  628. # 登录流程把游戏带到庭院主界面,避免 gameplay 在登录页盲点后被迫重启。
  629. # 注意:不能只靠 task_call('Restart') 排队,因为 get_next_task 按 next_run 取最早
  630. # 到期的任务,Exploration 等的 next_run 是 2023 永远更优先,Restart 永远排不上去,
  631. # 所以这里直接把 task 改写成 Restart 并落进下方 Run 分支执行。
  632. if task != 'Restart' and getattr(self.device, 'is_desktop', False) \
  633. and not self.device.app_is_running():
  634. logger.info('Desktop client not logged in, run `Restart` to login first')
  635. task = 'Restart'
  636. self.is_first_task = False
  637. # Run
  638. logger.info(f'Scheduler: Start task `{task}`')
  639. self.device.stuck_record_clear()
  640. self.device.click_record_clear()
  641. logger.hr(task, level=0)
  642. self.config.model.running_task = task
  643. _task_start = datetime.now()
  644. success = self.run(inflection.camelize(task))
  645. self.config.model.running_task = ''
  646. logger.info(f'Scheduler: End task `{task}`')
  647. self.is_first_task = False
  648. self.anti_ban_guard.record_active((datetime.now() - _task_start).total_seconds())
  649. # Check failures
  650. # failed = deep_get(self.failure_record, keys=task, default=0)
  651. failed = self.failure_record[task] if task in self.failure_record else 0
  652. failed = 0 if success else failed + 1
  653. # deep_set(self.failure_record, keys=task, value=failed)
  654. self.failure_record[task] = failed
  655. if failed >= 3:
  656. logger.critical(f"Task `{task}` failed 3 or more times.")
  657. logger.critical("Possible reason #1: You haven't used it correctly. "
  658. "Please read the help text of the options.")
  659. logger.critical("Possible reason #2: There is a problem with this task. "
  660. "Please contact developers or try to fix it yourself.")
  661. logger.critical('Request human takeover')
  662. # 添加失败三次的推送通知
  663. self.config.notifier.push(
  664. title=f'{I18n.trans_zh_cn(task)}{task}',
  665. content=f"<{self.config_name}> 任务连续失败三次,请上线查看"
  666. )
  667. # 关闭模拟器
  668. if self.config.script.error.error_repeated:
  669. self.device.emulator_stop()
  670. exit(1)
  671. if success:
  672. del_cached_property(self, 'config')
  673. continue
  674. elif self.config.script.error.handle_error:
  675. # self.config.task_delay(success=False)
  676. del_cached_property(self, 'config')
  677. # self.checker.check_now()
  678. continue
  679. else:
  680. break
  681. def start_loop(self) -> None:
  682. """
  683. 创建一个线程,运行loop
  684. :return:
  685. """
  686. if self.loop_thread is None:
  687. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  688. self.loop_thread.start()
  689. if __name__ == "__main__":
  690. ensure_ocr_server_started()
  691. script = Script("oas1")
  692. script.loop()