保留 Git 自动更新并简化 MAA 任务流程,加入 MaaEnd
This commit is contained in:
+76
-130
@@ -1,139 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import asyncio
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
# time record
|
||||
def fprint(s:str)->None:
|
||||
print(s)
|
||||
sys.stdout.flush()
|
||||
|
||||
fprint("-------------------------------------------------------")
|
||||
fprint(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
||||
fprint("-------------------------------------------------------")
|
||||
time.sleep(1)
|
||||
|
||||
class CommandProcessor:
|
||||
|
||||
def Command(self, s: str) -> int:
|
||||
fprint("_> " + s)
|
||||
if (t := os.system(s)) != 0:
|
||||
fprint("Fatal Error: Command Failed:" + s)
|
||||
fprint("Error Number: " + str(t))
|
||||
return t
|
||||
return 0
|
||||
|
||||
def CommandWithNoProxy(self, s: str) -> int:
|
||||
fprint("_> " + s)
|
||||
# 保存并删除
|
||||
old_http = os.environ.pop('http_proxy', None)
|
||||
old_https = os.environ.pop('https_proxy', None)
|
||||
|
||||
t = os.system(s)
|
||||
|
||||
# 立即恢复
|
||||
if old_http:
|
||||
os.environ['http_proxy'] = old_http
|
||||
if old_https:
|
||||
os.environ['https_proxy'] = old_https
|
||||
|
||||
if t != 0:
|
||||
fprint("Fatal Error: Command Failed:" + s)
|
||||
fprint("Error Number: " + str(t))
|
||||
return t
|
||||
|
||||
def RetryCommand(self,s:str,retry:int=3) -> int:
|
||||
result = 0
|
||||
while retry > 0:
|
||||
result = cp.Command(s)
|
||||
if result == 0:
|
||||
break
|
||||
retry-=1
|
||||
time.sleep(1)
|
||||
return result
|
||||
|
||||
def RetryCommandWithNoProxy(self,s:str,retry:int=3) -> int:
|
||||
result = 0
|
||||
while retry > 0:
|
||||
result = cp.CommandWithNoProxy(s)
|
||||
if result == 0:
|
||||
break
|
||||
retry-=1
|
||||
time.sleep(1)
|
||||
return result
|
||||
|
||||
async def AsyncCommand(self,command:str,regex:str):
|
||||
self._asyncCommand = command
|
||||
fprint("_> await! " + command)
|
||||
process = await asyncio.create_subprocess_shell(command,stderr=asyncio.subprocess.PIPE)
|
||||
while True:
|
||||
line = (await process.stderr.readline()).decode()
|
||||
fprint(line)
|
||||
if re.search(regex, line):
|
||||
fprint("done")
|
||||
break
|
||||
ADDRESS = os.getenv("ADB_ADDRESS", "127.0.0.1:5555")
|
||||
REDROID = os.getenv("REDROID_CONTAINER", "redroid")
|
||||
TASKS = ["startup", "recruit", "infrast", "fight", "mall", "award"]
|
||||
DIRECT = {k: v for k, v in os.environ.items() if k.lower() not in ("http_proxy", "https_proxy", "all_proxy")}
|
||||
|
||||
|
||||
|
||||
|
||||
# cp.Command("command")
|
||||
# cp.RetryCommand("command",retry_time:int)
|
||||
# asyncio.run(cp.AsyncCommand("command","stop track regex"))
|
||||
# script_dir = os.path.dirname((os.path.abspath(__file__)))
|
||||
cp = CommandProcessor()
|
||||
haveError = False
|
||||
def TaskFailRetry(command:str)->int:
|
||||
retry = 3
|
||||
result = 0
|
||||
while retry > 0:
|
||||
retry -= 1
|
||||
result = cp.RetryCommand(command)
|
||||
if result == 0:
|
||||
return 0
|
||||
fprint(f"Task Command is {command}, ret code is {result}")
|
||||
fprint("Task Failed, retrying...")
|
||||
cp.RetryCommand("maa closedown")
|
||||
cp.RetryCommand("maa run startup")
|
||||
return result
|
||||
def command(args, proxy=False):
|
||||
print(f"[{datetime.now():%H:%M:%S}] {' '.join(args)}", flush=True)
|
||||
return subprocess.run(args, env=os.environ if proxy else DIRECT).returncode
|
||||
|
||||
def TaskFailRetryWithNoProxy(command:str)->int:
|
||||
retry = 3
|
||||
result = 0
|
||||
while retry > 0:
|
||||
retry -= 1
|
||||
result = cp.RetryCommandWithNoProxy(command)
|
||||
if result == 0:
|
||||
return 0
|
||||
fprint(f"Task Command is {command}, ret code is {result}")
|
||||
fprint("Task Failed, retrying...")
|
||||
cp.RetryCommand("maa closedown")
|
||||
cp.RetryCommand("maa run startup")
|
||||
return result
|
||||
# update
|
||||
cp.Command("maa update")
|
||||
cp.Command("maa self update")
|
||||
# fire it up
|
||||
cp.Command("docker stop redroid")
|
||||
redroid_path = os.getenv('redroid_path', "/home/lichx/.config/redroid-rk3588/")
|
||||
adb_address = os.getenv('adb_address', "localhost:5555")
|
||||
log_dir = os.getenv('MAA_LOG', "/home/lichx/.config/redroid-rk3588/log/")
|
||||
os.chdir(redroid_path)
|
||||
cp.Command("docker compose up -d")
|
||||
time.sleep(15)
|
||||
cp.RetryCommand(f"adb connect {adb_address}")
|
||||
cp.RetryCommand(f"adb -s {adb_address} shell am start --windowingMode 4 com.hypergryph.arknights/com.u8.sdk.U8UnityContext")
|
||||
# run maa
|
||||
haveError |= TaskFailRetryWithNoProxy("maa run startup") != 0
|
||||
haveError |= TaskFailRetryWithNoProxy("maa run recruit") != 0
|
||||
haveError |= TaskFailRetryWithNoProxy("maa run infrast") != 0
|
||||
haveError |= TaskFailRetryWithNoProxy("maa run fight") != 0
|
||||
haveError |= TaskFailRetryWithNoProxy("maa run mall") != 0
|
||||
haveError |= TaskFailRetryWithNoProxy("maa run award") != 0
|
||||
# storage error log
|
||||
if haveError:
|
||||
cp.Command(f"cp {log_dir}/maa_pyshell.log {log_dir}/maa_pyshell.{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.log")
|
||||
# shutdown
|
||||
cp.RetryCommand("maa closedown")
|
||||
cp.Command("docker stop redroid")
|
||||
|
||||
def retry(args):
|
||||
for attempt in range(3):
|
||||
if command(args) == 0:
|
||||
return True
|
||||
print(f"命令失败,第 {attempt + 1}/3 次", flush=True)
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def maa(*args):
|
||||
return ["maa", *args, "--batch", "-a", ADDRESS]
|
||||
|
||||
|
||||
def wait_android():
|
||||
print("等待 Android 启动……", flush=True)
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
subprocess.run(["adb", "connect", ADDRESS], env=DIRECT, capture_output=True, timeout=10)
|
||||
result = subprocess.run(["adb", "-s", ADDRESS, "shell", "getprop", "sys.boot_completed"],
|
||||
env=DIRECT, capture_output=True, text=True, timeout=10)
|
||||
if result.returncode == 0 and result.stdout.strip() == "1":
|
||||
return True
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
time.sleep(2)
|
||||
print("Android 启动超时", flush=True)
|
||||
return False
|
||||
|
||||
|
||||
def task(name):
|
||||
for _ in range(3):
|
||||
if retry(maa("run", name)):
|
||||
return True
|
||||
print(f"任务 {name} 失败,重新打开游戏后重试", flush=True)
|
||||
retry(maa("closedown"))
|
||||
retry(maa("run", "startup"))
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
# 更新走代理;失败时仍尝试使用已有版本,与原脚本一致。
|
||||
command(["maa", "update"], proxy=True)
|
||||
command(["maa", "self", "update"], proxy=True)
|
||||
if command(["docker", "restart", REDROID]):
|
||||
return 1
|
||||
failed = False
|
||||
ready = False
|
||||
try:
|
||||
ready = wait_android()
|
||||
if not ready:
|
||||
return 1
|
||||
retry(["adb", "-s", ADDRESS, "shell", "am", "start", "--windowingMode", "4",
|
||||
"com.hypergryph.arknights/com.u8.sdk.U8UnityContext"])
|
||||
for name in TASKS:
|
||||
if not task(name):
|
||||
failed = True
|
||||
finally:
|
||||
if ready and not retry(maa("closedown")):
|
||||
failed = True
|
||||
if command(["docker", "stop", REDROID]):
|
||||
failed = True
|
||||
return int(failed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Reference in New Issue
Block a user