script.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. :return:
  287. """
  288. while True:
  289. task = self.config.get_next()
  290. self.config.task = task
  291. if self.state_queue:
  292. self.state_queue.put({"schedule": self.config.get_schedule_data()})
  293. now = datetime.now()
  294. antiban_wake = self.anti_ban_guard.wake_time(now, self.config.script.anti_ban)
  295. if antiban_wake is not None:
  296. task.next_run = max(task.next_run, antiban_wake)
  297. if not self._try_acquire_queue_token():
  298. del_cached_property(self, "config")
  299. continue
  300. # 任务时间到了返回任务名称
  301. if task.next_run <= now:
  302. return task.command
  303. # 根据策略执行等待逻辑
  304. if not self._handle_wait_during_idle(task.next_run):
  305. # 若等待被打断, 则刷新配置
  306. del_cached_property(self, "config")
  307. def _try_acquire_queue_token(self) -> bool:
  308. """
  309. 尝试获取排队执行权。
  310. 如果排队模式未启用,返回 True。
  311. 如果排队模式启用但未能获取到执行权,进入等待循环直到获取成功或配置变更。
  312. Returns:
  313. True: 获取得执行权,可以执行任务
  314. False: 等待被配置变更打断,调用方应重新加载配置后重试
  315. """
  316. # 是否开启排队模式
  317. if not self.config.script.optimization.queue_mode:
  318. if self.instance_guard:
  319. self.instance_guard.remove_from_queue()
  320. self.instance_guard = None
  321. return True
  322. # 懒加载instance_guard
  323. if self.instance_guard is None:
  324. try:
  325. self.instance_guard = InstanceGuard(self.config_name)
  326. logger.info(f"[Queue] Queue mode enabled for '{self.config_name}'")
  327. except Exception:
  328. self.instance_guard = None
  329. return True
  330. # 尝试获取执行权
  331. if self.instance_guard.try_acquire():
  332. return True
  333. # 执行权获取失败,关闭模拟器并进入等待循环
  334. logger.info(f"[Queue] '{self.config_name}' waiting for execution token...")
  335. if (self.config.script.optimization.when_task_queue_empty == 'close_game'
  336. and not self._emulator_down
  337. and 'device' in self.__dict__):
  338. try:
  339. self.device.emulator_stop()
  340. self._emulator_down = True
  341. logger.info(f"[Queue] Emulator closed during queue wait")
  342. except Exception:
  343. pass
  344. self.config.start_watching()
  345. while True:
  346. time.sleep(30)
  347. if self.config.should_reload():
  348. logger.info(f"[Queue] Config changed, re-evaluating")
  349. return False
  350. if self.instance_guard.try_acquire():
  351. return True
  352. def _handle_wait_during_idle(self, next_run: datetime) -> bool:
  353. """
  354. 处理任务空闲期间的行为策略
  355. :param next_run: 下一个任务的时间
  356. :return: True 表示等待成功完成, False 表示等待被中断
  357. """
  358. method = self.config.script.optimization.when_task_queue_empty
  359. strategy_map = {
  360. "close_game": self._wait_close_game,
  361. "goto_main": self._wait_goto_main,
  362. }
  363. func = strategy_map.get(method)
  364. if func is None:
  365. logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
  366. func = self._wait_stay_there
  367. return func(next_run)
  368. @staticmethod
  369. def _time_to_timedelta(value) -> timedelta:
  370. if value is None:
  371. return timedelta(0)
  372. return timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)
  373. def _wait_until_with_emulator_preheat(self, next_run: datetime) -> bool:
  374. """Wait until next_run; if emulator is down, preheat startup before next task."""
  375. if not self._emulator_down:
  376. return self.wait_until(next_run)
  377. startup_lead = self._time_to_timedelta(self.config.script.optimization.emulator_startup_lead_time)
  378. now = datetime.now()
  379. wake_time = next_run - startup_lead if startup_lead > timedelta(0) else next_run
  380. if wake_time < now:
  381. wake_time = now
  382. now = datetime.now()
  383. if wake_time > now:
  384. logger.info(f"Wait before wake emulator: {wake_time.strftime('%Y-%m-%d %H:%M:%S')}")
  385. if not self.wait_until(wake_time):
  386. return False
  387. if self._emulator_down:
  388. logger.info("Wake emulator before next task")
  389. if not self._try_acquire_queue_token():
  390. return False
  391. self.device = Device(self.config)
  392. self._emulator_down = False
  393. if wake_time < next_run:
  394. return self.wait_until(next_run)
  395. return True
  396. def _wait_close_game(self, next_run: datetime) -> bool:
  397. if self._emulator_down:
  398. logger.info("Emulator is down, skip close_game/goto_main action and wait with preheat")
  399. return self._wait_until_with_emulator_preheat(next_run)
  400. close_game_wait_duration = self.config.script.optimization.close_game_wait_duration
  401. close_game_wait = self._time_to_timedelta(close_game_wait_duration)
  402. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  403. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  404. if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  405. logger.info("Close emulator during wait")
  406. self.device.emulator_stop()
  407. self._emulator_down = True
  408. if not self._wait_until_with_emulator_preheat(next_run):
  409. return False
  410. self.run("Restart")
  411. return True
  412. if close_game_wait <= timedelta(0):
  413. logger.info("Close game during wait")
  414. self.device.app_stop()
  415. self.device.release_during_wait()
  416. if not self.wait_until(next_run):
  417. return False
  418. self.run("Restart")
  419. return True
  420. if next_run > datetime.now() + close_game_wait:
  421. logger.info("Close game during wait")
  422. self.device.app_stop()
  423. self.device.release_during_wait()
  424. if not self.wait_until(next_run):
  425. return False
  426. self.run("Restart")
  427. return True
  428. logger.info("Wait without closing game (close_game wait duration not reached)")
  429. self.device.release_during_wait()
  430. if not self.wait_until(next_run):
  431. return False
  432. return True
  433. def _wait_goto_main(self, next_run: datetime) -> bool:
  434. if self._emulator_down:
  435. logger.info("Emulator is down, skip goto_main and wait with preheat")
  436. return self._wait_until_with_emulator_preheat(next_run)
  437. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  438. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  439. if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  440. logger.info("Close emulator during wait")
  441. self.device.emulator_stop()
  442. self._emulator_down = True
  443. if not self._wait_until_with_emulator_preheat(next_run):
  444. return False
  445. self.run("Restart")
  446. return True
  447. logger.info("Goto main page during wait")
  448. self.run("GotoMain")
  449. self.device.release_during_wait()
  450. return self.wait_until(next_run)
  451. def _wait_stay_there(self, next_run: datetime) -> bool:
  452. if self._emulator_down:
  453. logger.info("Stay_there during wait (emulator is down, with preheat)")
  454. return self._wait_until_with_emulator_preheat(next_run)
  455. logger.info("Stay_there (no action) during wait")
  456. self.device.release_during_wait()
  457. return self.wait_until(next_run)
  458. def exception_handler(self, e: Exception, command: str) -> None:
  459. # 处理御魂溢出
  460. from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
  461. image = getattr(self.device, 'image', None)
  462. # image为None则不做处理
  463. if image is None:
  464. return
  465. analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
  466. if analyse_type == AnalyzeType.SoulOverflow:
  467. self.config.task_call('SoulsTidy')
  468. time.sleep(1)
  469. def run(self, command: str) -> bool:
  470. """
  471. :param command: 大写驼峰命名的任务名字
  472. :return:
  473. """
  474. if command == 'start' or command == 'goto_main':
  475. logger.error(f'Invalid command `{command}`')
  476. if not self._try_acquire_queue_token():
  477. return False
  478. if self.instance_guard and self.instance_guard.token_lost:
  479. logger.warning(f'Token lost, stopping emulator and rejoining queue')
  480. try:
  481. self.device.emulator_stop()
  482. except Exception:
  483. pass
  484. self._emulator_down = True
  485. self.instance_guard.release()
  486. return False
  487. try:
  488. try:
  489. self.device.screenshot()
  490. except GameNotRunningError:
  491. # 桌面版窗口不在时预截图必抛;Restart 的职责就是拉起客户端,
  492. # 不能让它被这层拦住(实测恢复循环里 Restart 永远跑不到)
  493. if command != 'Restart':
  494. raise
  495. logger.info('Client window gone, skip pre-screenshot and let Restart recover it')
  496. module_name = 'script_task'
  497. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  498. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  499. task_module = load_module(module_name, module_path)
  500. task_module.ScriptTask(config=self.config, device=self.device).run()
  501. except TaskEnd:
  502. return True
  503. except GameNotRunningError as e:
  504. logger.warning(e)
  505. self.exception_handler(e=e, command=command)
  506. self.config.task_call('Restart')
  507. return True
  508. except (GameStuckError, GameTooManyClickError) as e:
  509. logger.error(e)
  510. self.save_error_log()
  511. self.exception_handler(e=e, command=command)
  512. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  513. logger.warning('If you are playing by hand, please stop Alas')
  514. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  515. self.config.task_call('Restart')
  516. self.device.sleep(10)
  517. return False
  518. except GameBugError as e:
  519. logger.warning(e)
  520. self.save_error_log()
  521. self.exception_handler(e=e, command=command)
  522. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  523. logger.warning(f'Restarting {self.device.package} to fix it')
  524. self.config.task_call('Restart')
  525. self.device.sleep(10)
  526. return False
  527. except GamePageUnknownError as e:
  528. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  529. # 这个还不重要 留着坑填
  530. logger.critical('Game page unknown')
  531. self.save_error_log()
  532. self.exception_handler(e=e, command=command)
  533. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GamePageUnknownError")
  534. self.config.task_call('Restart')
  535. self.device.sleep(10)
  536. return False
  537. except ScriptError as e:
  538. logger.critical(e)
  539. self.exception_handler(e=e, command=command)
  540. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  541. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> ScriptError")
  542. exit(1)
  543. except RequestHumanTakeover as e:
  544. logger.critical(e)
  545. self.exception_handler(e=e, command=command)
  546. logger.critical('Request human takeover')
  547. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> RequestHumanTakeover")
  548. exit(1)
  549. except Exception as e:
  550. logger.exception(e)
  551. self.exception_handler(e=e, command=command)
  552. self.save_error_log()
  553. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> Exception occured")
  554. exit(1)
  555. def loop(self):
  556. """
  557. Main loop of scheduler.
  558. :return:
  559. """
  560. with _log_switch_lock:
  561. logger.set_file_logger(self.config_name, do_cleanup=True)
  562. start_day = date.today()
  563. logger.info(f'Start scheduler loop: {self.config_name}')
  564. self.config.model.running_task = ''
  565. self.anti_ban_guard.reset()
  566. # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
  567. if not self.config.script.device.run_background_only and IS_WINDOWS:
  568. from module.device.platform2.platform_windows import minimize_by_name, show_window_by_name
  569. target_window_name = self.config.script.device.handle # 在这里输入你的具体窗口名称
  570. if self.config.script.device.emulator_window_minimize:
  571. minimize_by_name(target_window_name)
  572. logger.info(f'重新显示: {target_window_name}')
  573. else:
  574. show_window_by_name(target_window_name)
  575. while 1:
  576. if date.today() > start_day:
  577. with _log_switch_lock:
  578. logger.set_file_logger(self.config_name, do_cleanup=True)
  579. start_day = date.today()
  580. # Check update event from GUI
  581. # if self.stop_event is not None:
  582. # if self.stop_event.is_set():
  583. # logger.info("Update event detected")
  584. # logger.info(f"Alas [{self.config_name}] exited.")
  585. # break
  586. # Check game server maintenance
  587. # self.checker.wait_until_available()
  588. # if self.checker.is_recovered():
  589. # # There is an accidental bug hard to reproduce
  590. # # Sometimes, config won't be updated due to blocking
  591. # # even though it has been changed
  592. # # So update it once recovered
  593. # del_cached_property(self, 'config')
  594. # logger.info('Server or network is recovered. Restart game client')
  595. # self.config.task_call('Restart')
  596. # Get task
  597. task = self.get_next_task()
  598. # Skip first restart
  599. if self.is_first_task and task == 'Restart':
  600. logger.info('Skip task `Restart` at scheduler start')
  601. self.config.task_delay(task='Restart', success=True, server=True)
  602. del_cached_property(self, 'config')
  603. continue
  604. if self._emulator_down:
  605. self.device = Device(self.config)
  606. self._emulator_down = False
  607. else:
  608. _ = self.device
  609. # 桌面模式:客户端刚被自动拉起时停在登录页(_desktop_login_done=False),
  610. # 此时 app_is_running() 返回 False。若下一个任务是 gameplay,先强制走 Restart
  611. # 登录流程把游戏带到庭院主界面,避免 gameplay 在登录页盲点后被迫重启。
  612. # 注意:不能只靠 task_call('Restart') 排队,因为 get_next_task 按 next_run 取最早
  613. # 到期的任务,Exploration 等的 next_run 是 2023 永远更优先,Restart 永远排不上去,
  614. # 所以这里直接把 task 改写成 Restart 并落进下方 Run 分支执行。
  615. if task != 'Restart' and getattr(self.device, 'is_desktop', False) \
  616. and not self.device.app_is_running():
  617. logger.info('Desktop client not logged in, run `Restart` to login first')
  618. task = 'Restart'
  619. self.is_first_task = False
  620. # Run
  621. logger.info(f'Scheduler: Start task `{task}`')
  622. self.device.stuck_record_clear()
  623. self.device.click_record_clear()
  624. logger.hr(task, level=0)
  625. self.config.model.running_task = task
  626. _task_start = datetime.now()
  627. success = self.run(inflection.camelize(task))
  628. self.config.model.running_task = ''
  629. logger.info(f'Scheduler: End task `{task}`')
  630. self.is_first_task = False
  631. self.anti_ban_guard.record_active((datetime.now() - _task_start).total_seconds())
  632. # Check failures
  633. # failed = deep_get(self.failure_record, keys=task, default=0)
  634. failed = self.failure_record[task] if task in self.failure_record else 0
  635. failed = 0 if success else failed + 1
  636. # deep_set(self.failure_record, keys=task, value=failed)
  637. self.failure_record[task] = failed
  638. if failed >= 3:
  639. logger.critical(f"Task `{task}` failed 3 or more times.")
  640. logger.critical("Possible reason #1: You haven't used it correctly. "
  641. "Please read the help text of the options.")
  642. logger.critical("Possible reason #2: There is a problem with this task. "
  643. "Please contact developers or try to fix it yourself.")
  644. logger.critical('Request human takeover')
  645. # 添加失败三次的推送通知
  646. self.config.notifier.push(
  647. title=f'{I18n.trans_zh_cn(task)}{task}',
  648. content=f"<{self.config_name}> 任务连续失败三次,请上线查看"
  649. )
  650. # 关闭模拟器
  651. if self.config.script.error.error_repeated:
  652. self.device.emulator_stop()
  653. exit(1)
  654. if success:
  655. del_cached_property(self, 'config')
  656. continue
  657. elif self.config.script.error.handle_error:
  658. # self.config.task_delay(success=False)
  659. del_cached_property(self, 'config')
  660. # self.checker.check_now()
  661. continue
  662. else:
  663. break
  664. def start_loop(self) -> None:
  665. """
  666. 创建一个线程,运行loop
  667. :return:
  668. """
  669. if self.loop_thread is None:
  670. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  671. self.loop_thread.start()
  672. if __name__ == "__main__":
  673. ensure_ocr_server_started()
  674. script = Script("oas1")
  675. script.loop()