合并代码

This commit is contained in:
zw
2025-09-01 22:12:30 +08:00
6 changed files with 352 additions and 318 deletions

105
.idea/workspace.xml generated
View File

@@ -4,7 +4,51 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="eceeff5e-51c1-459c-a911-d21ec090a423" name="Changes" comment="ai 开始测试" /> <list default="true" id="eceeff5e-51c1-459c-a911-d21ec090a423" name="Changes" comment="ai 开始测试">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Entity/Variables.py" beforeDir="false" afterPath="$PROJECT_DIR$/Entity/Variables.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.0/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.0/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.1/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.1/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.2/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.2/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.3.1/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.3.1/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.3/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.3/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.4/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.4/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.5/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.5/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.6.1/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.6.1/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.6/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.6/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.7/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.7/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.8/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/15.8/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.0/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.0/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.1/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.1/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.2/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.2/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.3.1/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.3.1/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.3/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.3/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.4/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.4/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.5/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.5/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.6/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.6/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.7/DeveloperDiskImage.dmg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/SupportFiles/16.7/DeveloperDiskImage.dmg.signature" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/Utils/DevDiskImageDeployer.py" beforeDir="false" afterPath="$PROJECT_DIR$/Utils/DevDiskImageDeployer.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
@@ -48,8 +92,6 @@
&quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;, &quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
&quot;Python.123.executor&quot;: &quot;Run&quot;, &quot;Python.123.executor&quot;: &quot;Run&quot;,
&quot;Python.Main.executor&quot;: &quot;Run&quot;, &quot;Python.Main.executor&quot;: &quot;Run&quot;,
&quot;Python.mac_wda_agent.executor&quot;: &quot;Run&quot;,
&quot;Python.windows_run.executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;, &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;, &quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;main&quot;, &quot;git-widget-placeholder&quot;: &quot;main&quot;,
@@ -118,56 +160,8 @@
<option name="INPUT_FILE" value="" /> <option name="INPUT_FILE" value="" />
<method v="2" /> <method v="2" />
</configuration> </configuration>
<configuration name="mac_wda_agent" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="iOSAI" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/script" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/script/mac_wda_agent.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="windows_run" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="iOSAI" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/script" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/script/windows_run.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<recent_temporary> <recent_temporary>
<list> <list>
<item itemvalue="Python.windows_run" />
<item itemvalue="Python.mac_wda_agent" />
<item itemvalue="Python.123" /> <item itemvalue="Python.123" />
</list> </list>
</recent_temporary> </recent_temporary>
@@ -216,11 +210,6 @@
<workItem from="1756370074173" duration="5000" /> <workItem from="1756370074173" duration="5000" />
<workItem from="1756370506697" duration="11274000" /> <workItem from="1756370506697" duration="11274000" />
<workItem from="1756389997073" duration="173000" /> <workItem from="1756389997073" duration="173000" />
<workItem from="1756447365905" duration="14443000" />
<workItem from="1756474554313" duration="72000" />
<workItem from="1756474770097" duration="1415000" />
<workItem from="1756476597268" duration="12000" />
<workItem from="1756722738193" duration="3859000" />
</task> </task>
<task id="LOCAL-00001" summary="ai 开始测试"> <task id="LOCAL-00001" summary="ai 开始测试">
<option name="closed" value="true" /> <option name="closed" value="true" />
@@ -245,9 +234,7 @@
<option name="LAST_COMMIT_MESSAGE" value="ai 开始测试" /> <option name="LAST_COMMIT_MESSAGE" value="ai 开始测试" />
</component> </component>
<component name="com.intellij.coverage.CoverageDataManagerImpl"> <component name="com.intellij.coverage.CoverageDataManagerImpl">
<SUITE FILE_PATH="coverage/iOSAI$Main.coverage" NAME="Main Coverage Results" MODIFIED="1756476597660" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" /> <SUITE FILE_PATH="coverage/iOSAI$Main.coverage" NAME="Main Coverage Results" MODIFIED="1756390027877" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" />
<SUITE FILE_PATH="coverage/iOSAI$mac_wda_agent.coverage" NAME="mac_wda_agent Coverage Results" MODIFIED="1756473148639" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/script" />
<SUITE FILE_PATH="coverage/iOSAI$123.coverage" NAME="123 覆盖结果" MODIFIED="1756300694280" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/test" /> <SUITE FILE_PATH="coverage/iOSAI$123.coverage" NAME="123 覆盖结果" MODIFIED="1756300694280" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/test" />
<SUITE FILE_PATH="coverage/iOSAI$windows_run.coverage" NAME="windows_run Coverage Results" MODIFIED="1756473558532" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/script" />
</component> </component>
</project> </project>

View File

@@ -126,6 +126,7 @@ class Deviceinfo(object):
# ---------------------------- # ----------------------------
def connectDevice(self, identifier: str): def connectDevice(self, identifier: str):
# 1) 连接 WDAUSBClient -> 设备 8100 # 1) 连接 WDAUSBClient -> 设备 8100
try: try:
d = wda.USBClient(identifier, 8100) d = wda.USBClient(identifier, 8100)
LogManager.info("启动 WDA 成功", identifier) LogManager.info("启动 WDA 成功", identifier)

View File

@@ -310,5 +310,19 @@ def monitorMessages():
return ResultData(data="").toJson() return ResultData(data="").toJson()
@app.route("/upLoadLogFile", methods=['POST'])
def upLoadLogFile():
ok = LogManager.upload_all_logs(
server_url="http://127.0.0.1:6000/upload",
extra_data={"project": "TikTokAuto", "env": "dev"}
)
if ok:
return ResultData(data="日志上传成功").toJson()
else:
return ResultData(data="", msg="日志上传失败").toJson()
if __name__ == '__main__': if __name__ == '__main__':
app.run("0.0.0.0", port=5000, debug=True, use_reloader=False) app.run("0.0.0.0", port=5000, debug=True, use_reloader=False)

View File

@@ -1,4 +1,3 @@
import os import os
import re import re
import cv2 import cv2
@@ -9,6 +8,7 @@ import xml.etree.ElementTree as ET
from lxml import etree from lxml import etree
from wda import Client from wda import Client
# 工具类 # 工具类
class AiUtils(object): class AiUtils(object):
@@ -64,7 +64,6 @@ class AiUtils(object):
return int(match.group()) # 将匹配到的数字转换为整数 return int(match.group()) # 将匹配到的数字转换为整数
return None # 如果没有找到数字,返回 None return None # 如果没有找到数字,返回 None
# 选择截图 # 选择截图
@classmethod @classmethod
def screenshot(cls): def screenshot(cls):
@@ -125,6 +124,7 @@ class AiUtils(object):
height, width, channels = heart_icon.shape height, width, channels = heart_icon.shape
roi = np.zeros((height, width, channels), dtype=np.uint8) roi = np.zeros((height, width, channels), dtype=np.uint8)
# 将爱心图标粘贴到透明背景上 # 将爱心图标粘贴到透明背景上
for c in range(channels): for c in range(channels):
roi[:, :, c] = np.where(mask_inv == 255, heart_icon[:, :, c], roi[:, :, c]) roi[:, :, c] = np.where(mask_inv == 255, heart_icon[:, :, c], roi[:, :, c])
@@ -142,7 +142,6 @@ class AiUtils(object):
else: else:
print("未选择有效区域。") print("未选择有效区域。")
# 根据名称获取图片完整地址 # 根据名称获取图片完整地址
@classmethod @classmethod
def imagePathWithName(cls, udid, name): def imagePathWithName(cls, udid, name):
@@ -166,7 +165,6 @@ class AiUtils(object):
# 返回根目录 # 返回根目录
return project_root return project_root
# 创建一个以udid命名的目录 # 创建一个以udid命名的目录
@classmethod @classmethod
def makeUdidDir(cls, udid): def makeUdidDir(cls, udid):
@@ -189,6 +187,8 @@ class AiUtils(object):
LogManager.info(f"目录 {udid_dir} 已存在,跳过创建", udid) LogManager.info(f"目录 {udid_dir} 已存在,跳过创建", udid)
print(f"目录 {udid_dir} 已存在,跳过创建") print(f"目录 {udid_dir} 已存在,跳过创建")
# 查找首页按钮 # 查找首页按钮
# uuid 设备id # uuid 设备id
# click 是否点击该按钮 # click 是否点击该按钮
@@ -209,7 +209,6 @@ class AiUtils(object):
print(e) print(e)
return None return None
# 查找关闭按钮 # 查找关闭按钮
@classmethod @classmethod
def findLiveCloseButton(cls, udid="eca000fcb6f55d7ed9b4c524055214c26a7de7aa"): def findLiveCloseButton(cls, udid="eca000fcb6f55d7ed9b4c524055214c26a7de7aa"):
@@ -277,7 +276,6 @@ class AiUtils(object):
client = wda.USBClient("eca000fcb6f55d7ed9b4c524055214c26a7de7aa") client = wda.USBClient("eca000fcb6f55d7ed9b4c524055214c26a7de7aa")
print(client.source()) print(client.source())
# 查找app主页上的收件箱按钮 # 查找app主页上的收件箱按钮
@classmethod @classmethod
def getMsgBoxButton(cls, session: Client): def getMsgBoxButton(cls, session: Client):
@@ -317,6 +315,7 @@ class AiUtils(object):
# 屏幕宽度 # 屏幕宽度
app = root.xpath('/XCUIElementTypeApplication') app = root.xpath('/XCUIElementTypeApplication')
screen_w = cls.parse_float(app[0], 'width', 414.0) if app else 414.0 screen_w = cls.parse_float(app[0], 'width', 414.0) if app else 414.0
# 找 Table 的可见范围 # 找 Table 的可见范围

View File

@@ -1,9 +1,96 @@
# import logging
# import os
# import sys
# import shutil
# from pathlib import Path
#
#
# class LogManager:
# # 运行根目录:打包后取 exe 目录;源码运行取项目目录
# if getattr(sys, "frozen", False):
# projectRoot = os.path.dirname(sys.executable)
# else:
# projectRoot = os.path.dirname(os.path.dirname(__file__))
#
# logDir = os.path.join(projectRoot, "log")
# _loggers = {}
#
# @classmethod
# def _setupLogger(cls, udid, name, logName, level=logging.INFO):
# """创建或获取 logger并绑定到文件"""
# deviceLogDir = os.path.join(cls.logDir, udid)
# os.makedirs(deviceLogDir, exist_ok=True)
# logFile = os.path.join(deviceLogDir, logName)
#
# logger_name = f"{udid}_{name}"
# logger = logging.getLogger(logger_name)
# logger.setLevel(level)
#
# # 避免重复添加 handler
# if not any(
# isinstance(h, logging.FileHandler) and h.baseFilename == os.path.abspath(logFile)
# for h in logger.handlers
# ):
# fileHandler = logging.FileHandler(logFile, mode="a", encoding="utf-8")
# formatter = logging.Formatter(
# "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
# datefmt="%Y-%m-%d %H:%M:%S"
# )
# fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
#
# return logger
#
# @classmethod
# def info(cls, text, udid="system"):
# cls._setupLogger(udid, "infoLogger", "info.log", level=logging.INFO).info(f"[{udid}] {text}")
#
# @classmethod
# def warning(cls, text, udid="system"):
# cls._setupLogger(udid, "warningLogger", "warning.log", level=logging.WARNING).warning(f"[{udid}] {text}")
#
# @classmethod
# def error(cls, text, udid="system"):
# cls._setupLogger(udid, "errorLogger", "error.log", level=logging.ERROR).error(f"[{udid}] {text}")
#
# # 清空日志
# @classmethod
# def clearLogs(cls):
# """启动时清空 log 目录下所有文件"""
# print("开始清空日志...")
#
# # 关闭所有 handler
# for name, logger in logging.Logger.manager.loggerDict.items():
# if isinstance(logger, logging.Logger):
# for handler in logger.handlers[:]:
# try:
# handler.close()
# except Exception:
# pass
# logger.removeHandler(handler)
#
# # 仅删除目录里的所有文件和子目录
# log_path = Path(cls.logDir)
# if log_path.exists():
# for item in log_path.iterdir():
# if item.is_file():
# item.unlink()
# elif item.is_dir():
# import shutil
# shutil.rmtree(item)
#
# print("日志清空完成")
import logging import logging
import os import os
import re
import sys import sys
import shutil import shutil
from pathlib import Path from pathlib import Path
import requests
class LogManager: class LogManager:
# 运行根目录:打包后取 exe 目录;源码运行取项目目录 # 运行根目录:打包后取 exe 目录;源码运行取项目目录
@@ -14,11 +101,46 @@ class LogManager:
logDir = os.path.join(projectRoot, "log") logDir = os.path.join(projectRoot, "log")
_loggers = {} _loggers = {}
_method_loggers = {} # 新增:缓存“设备+方法”的 logger
# ---------- 工具函数 ----------
@classmethod
def _safe_filename(cls, name: str, max_len: int = 80) -> str:
"""
将方法名/udid等转成安全文件名
- 允许字母数字、点、下划线、连字符
- 允许常见 CJK 字符(中日韩)
- 其他非法字符替换为下划线
- 合并多余下划线,裁剪长度
"""
if not name:
return "unknown"
name = str(name).strip()
# 替换 Windows 非法字符和控制符
name = re.sub(r'[\\/:*?"<>|\r\n\t]+', '_', name)
# 只保留 ① 英数._- ② CJK 统一表意文字、日文平/片假名、韩文音节
name = re.sub(rf'[^a-zA-Z0-9_.\-'
r'\u4e00-\u9fff' # 中
r'\u3040-\u30ff' # 日
r'\uac00-\ud7a3' # 韩
r']+', '_', name)
# 合并多余下划线,去两端空白与下划线
name = re.sub(r'_+', '_', name).strip(' _.')
# 避免空
name = name or "unknown"
# Windows 预留名避免CON/PRN/AUX/NUL/COM1…
if re.fullmatch(r'(?i)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])', name):
name = f"_{name}"
# 限长
return name[:max_len] or "unknown"
# ---------- 旧的:按级别写固定文件 ----------
@classmethod @classmethod
def _setupLogger(cls, udid, name, logName, level=logging.INFO): def _setupLogger(cls, udid, name, logName, level=logging.INFO):
"""创建或获取 logger并绑定到文件""" """创建或获取 logger并绑定到设备目录下的固定文件info.log / warning.log / error.log"""
deviceLogDir = os.path.join(cls.logDir, udid) deviceLogDir = os.path.join(cls.logDir, cls._safe_filename(udid))
os.makedirs(deviceLogDir, exist_ok=True) os.makedirs(deviceLogDir, exist_ok=True)
logFile = os.path.join(deviceLogDir, logName) logFile = os.path.join(deviceLogDir, logName)
@@ -53,6 +175,59 @@ class LogManager:
def error(cls, text, udid="system"): def error(cls, text, udid="system"):
cls._setupLogger(udid, "errorLogger", "error.log", level=logging.ERROR).error(f"[{udid}] {text}") cls._setupLogger(udid, "errorLogger", "error.log", level=logging.ERROR).error(f"[{udid}] {text}")
# ---------- 新增:按“设备+方法”分别写独立日志文件 ----------
@classmethod
def _setupMethodLogger(cls, udid: str, method: str, level=logging.INFO):
"""
为某设备的某个方法单独创建 logger
log/<udid>/<method>.log
"""
udid_key = cls._safe_filename(udid or "system")
method_key = cls._safe_filename(method or "general")
cache_key = (udid_key, method_key)
# 命中缓存
if cache_key in cls._method_loggers:
return cls._method_loggers[cache_key]
deviceLogDir = os.path.join(cls.logDir, udid_key)
os.makedirs(deviceLogDir, exist_ok=True)
logFile = os.path.join(deviceLogDir, f"{method_key}.log")
logger_name = f"{udid_key}.{method_key}"
logger = logging.getLogger(logger_name)
logger.setLevel(level)
logger.propagate = False # 避免向根 logger 传播导致控制台重复打印
# 避免重复添加 handler
if not any(
isinstance(h, logging.FileHandler) and h.baseFilename == os.path.abspath(logFile)
for h in logger.handlers
):
fileHandler = logging.FileHandler(logFile, mode="a", encoding="utf-8")
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
cls._method_loggers[cache_key] = logger
return logger
@classmethod
def method_info(cls, text, method, udid="system"):
"""按设备+方法写 INFO 到 log/<udid>/<method>.log"""
cls._setupMethodLogger(udid, method, level=logging.INFO).info(f"[{udid}][{method}] {text}")
@classmethod
def method_warning(cls, text, method, udid="system"):
cls._setupMethodLogger(udid, method, level=logging.WARNING).warning(f"[{udid}][{method}] {text}")
@classmethod
def method_error(cls, text, method, udid="system"):
cls._setupMethodLogger(udid, method, level=logging.ERROR).error(f"[{udid}][{method}] {text}")
# 清空日志 # 清空日志
@classmethod @classmethod
def clearLogs(cls): def clearLogs(cls):
@@ -69,14 +244,53 @@ class LogManager:
pass pass
logger.removeHandler(handler) logger.removeHandler(handler)
# 删除目录里的所有文件和子目录 # 删除 log 目录
log_path = Path(cls.logDir) log_path = Path(cls.logDir)
if log_path.exists(): if log_path.exists():
for item in log_path.iterdir(): for item in log_path.iterdir():
if item.is_file(): if item.is_file():
item.unlink() item.unlink()
elif item.is_dir(): elif item.is_dir():
import shutil
shutil.rmtree(item) shutil.rmtree(item)
# 清缓存
cls._method_loggers.clear()
print("日志清空完成") print("日志清空完成")
@classmethod
def upload_all_logs(cls, server_url: str, extra_data: dict = None):
"""
上传 log/ 目录下所有文件和子目录中的日志
"""
log_path = Path(cls.logDir)
if not log_path.exists():
print("[upload_all_logs] 日志目录不存在")
return False
success_files, failed_files = [], []
for file in log_path.rglob("*.log"): # 递归找到所有 .log 文件
try:
files = {"file": open(file, "rb")}
data = {"relative_path": str(file.relative_to(log_path))}
if extra_data:
data.update(extra_data)
resp = requests.post(server_url, files=files, data=data, timeout=15)
if resp.status_code == 200:
success_files.append(file.name)
else:
failed_files.append((file.name, resp.status_code))
except Exception as e:
failed_files.append((file.name, str(e)))
finally:
try:
files["file"].close()
except:
pass
print(f"[upload_all_logs] 成功上传: {success_files}")
if failed_files:
print(f"[upload_all_logs] 失败文件: {failed_files}")
return len(failed_files) == 0

View File

@@ -49,7 +49,7 @@ class ScriptManager():
time.sleep(1) time.sleep(1)
ControlUtils.openTikTok(session, udid) ControlUtils.openTikTok(session, udid)
time.sleep(3) time.sleep(3)
LogManager.info("养号重启tiktok", udid) LogManager.method_info("养号重启tiktok", "养号", udid)
AiUtils.makeUdidDir(udid) AiUtils.makeUdidDir(udid)
# ========= 主循环 ========= # ========= 主循环 =========
@@ -70,15 +70,15 @@ class ScriptManager():
if not el.exists: if not el.exists:
# 记录日志 # 记录日志
LogManager.error("找不到推荐按钮,养号出现问题,重启养号功能", udid=udid) LogManager.method_error("找不到推荐按钮,养号出现问题,重启养号功能", "养号", udid=udid)
# 手动的抛出异常 重启流程 # 手动的抛出异常 重启流程
raise Exception("找不到推荐按钮,养号出现问题,重启养号功能") raise Exception("找不到推荐按钮,养号出现问题,重启养号功能")
if el.value != "1": if el.value != "1":
LogManager.error("当前页面不是推荐页面,养号出现问题,重启养号功能", udid=udid) LogManager.method_error("当前页面不是推荐页面,养号出现问题,重启养号功能", "养号", udid=udid)
raise Exception("当前页面不是推荐页面,养号出现问题,重启养号功能") raise Exception("当前页面不是推荐页面,养号出现问题,重启养号功能")
LogManager.info("当前页面是推荐页面,开始养号") LogManager.method_info("当前页面是推荐页面,开始养号", "养号", udid=udid)
# 重新设置节点的深度,防止手机进行卡顿 # 重新设置节点的深度,防止手机进行卡顿
session.appium_settings({"snapshotMaxDepth": 0}) session.appium_settings({"snapshotMaxDepth": 0})
@@ -90,11 +90,11 @@ class ScriptManager():
os.makedirs(resource_dir, exist_ok=True) os.makedirs(resource_dir, exist_ok=True)
filePath = os.path.join(resource_dir, "bgv.png") filePath = os.path.join(resource_dir, "bgv.png")
img.save(filePath) img.save(filePath)
LogManager.info(f"保存屏幕图像成功 -> {filePath}", udid) LogManager.method_info(f"保存屏幕图像成功 -> {filePath}", "养号", udid)
print("保存了背景图:", filePath) print("保存了背景图:", filePath)
time.sleep(1) time.sleep(1)
except Exception as e: except Exception as e:
LogManager.error(f"截图或保存失败,失败原因:{e}", udid) LogManager.method_info(f"截图或保存失败,失败原因:{e}", "养号", udid)
raise Exception("截图或保存失败,重启养号功能") raise Exception("截图或保存失败,重启养号功能")
# ---- 视频逻辑 ---- # ---- 视频逻辑 ----
@@ -114,7 +114,7 @@ class ScriptManager():
needLike = random.randint(0, 100) needLike = random.randint(0, 100)
homeButton = AiUtils.findHomeButton(udid) homeButton = AiUtils.findHomeButton(udid)
if homeButton: if homeButton:
LogManager.info("有首页按钮,查看视频", udid) LogManager.method_info("有首页按钮,查看视频", "养号", udid)
videoTime = random.randint(5, 15) videoTime = random.randint(5, 15)
time.sleep(videoTime) time.sleep(videoTime)
@@ -124,27 +124,27 @@ class ScriptManager():
session.appium_settings({"snapshotMaxDepth": 0}) session.appium_settings({"snapshotMaxDepth": 0})
if needLike < 3: if needLike < 3:
LogManager.info("进行点赞", udid) LogManager.method_info("进行点赞", "养号", udid)
ControlUtils.clickLike(session, udid) ControlUtils.clickLike(session, udid)
LogManager.info("继续观看视频", udid) LogManager.method_info("继续观看视频", "养号", udid)
videoTime = random.randint(10, 30) videoTime = random.randint(10, 30)
time.sleep(videoTime) time.sleep(videoTime)
LogManager.info("准备划到下一个视频", udid) LogManager.method_info("准备划到下一个视频", "养号", udid)
client.swipe_up() client.swipe_up()
else: else:
LogManager.error("找不到首页按钮。出错了", udid) LogManager.method_error("找不到首页按钮。出错了", "养号", udid)
else: else:
nextTime = random.randint(1, 5) nextTime = random.randint(1, 5)
time.sleep(nextTime) time.sleep(nextTime)
client.swipe_up() client.swipe_up()
except Exception as e: except Exception as e:
LogManager.error(f"刷视频过程出现错误,重试", udid) LogManager.method_error(f"刷视频过程出现错误,重试", "养号", udid)
raise e # 抛出给上层,触发重生机制 raise e # 抛出给上层,触发重生机制
except Exception as e: except Exception as e:
LogManager.error(f"[{udid}] 养号出现异常,将重启流程: {e}", udid) LogManager.method_error(f"[{udid}] 养号出现异常,将重启流程: {e}", "养号", udid)
retries += 1 retries += 1
time.sleep(3) # 等待后重生 time.sleep(3) # 等待后重生
@@ -174,7 +174,7 @@ class ScriptManager():
if live_button.exists: if live_button.exists:
live_button.click() live_button.click()
else: else:
LogManager.error("无法找到直播间按钮 抛出异常 重新启动", udid) LogManager.method_error("无法找到直播间按钮 抛出异常 重新启动", "直播养号", udid)
# 抛出异常 # 抛出异常
raise Exception(f"找不到直播按钮,抛出异常 重新启动") raise Exception(f"找不到直播按钮,抛出异常 重新启动")
time.sleep(20) time.sleep(20)
@@ -202,14 +202,16 @@ class ScriptManager():
if not (el1.exists or el2.exists): if not (el1.exists or el2.exists):
print("当前页面不是直播间,重启刷直播") print("当前页面不是直播间,重启刷直播")
LogManager.error("当前页面不是直播间,重启刷直播", udid=udid) LogManager.method_error("当前页面不是直播间,重启刷直播", "直播养号", udid=udid)
raise Exception("当前页面不是直播间") raise Exception("当前页面不是直播间")
else: else:
print("当前页面是直播间,继续刷直播") print("当前页面是直播间,继续刷直播")
LogManager.method_info("当前页面是直播间,继续刷直播", "直播养号", udid=udid)
# PK 直接划走 # PK 直接划走
if session(xpath='//XCUIElementTypeOther[@name="kGBLInteractionViewMatchScoreBar"]').exists: if session(xpath='//XCUIElementTypeOther[@name="kGBLInteractionViewMatchScoreBar"]').exists:
print("✅ 当前是 PK跳过") print("✅ 当前是 PK跳过")
LogManager.method_info("✅ 当前是 PK跳过", "直播养号", udid=udid)
session.swipe_up() session.swipe_up()
continue continue
@@ -219,24 +221,29 @@ class ScriptManager():
if count > 1: if count > 1:
print("❌ 多窗口(有人连麦/分屏),划走") print("❌ 多窗口(有人连麦/分屏),划走")
LogManager.method_info("❌ 多窗口(有人连麦/分屏),划走", "直播养号", udid=udid)
session.swipe_up() session.swipe_up()
continue continue
else: else:
print("✅ 单窗口,(10%概率)开始点赞") print("✅ 单窗口,(10%概率)开始点赞")
LogManager.method_info("✅ 单窗口,(3%概率)开始点赞", "直播养号", udid=udid)
# 随机点赞(仍保留中途保护) # 随机点赞(仍保留中途保护)
if random.random() >= 0.97: if random.random() >= 0.97:
print("开始点赞") print("开始点赞")
LogManager.method_info("开始点赞", "直播养号", udid=udid)
for _ in range(random.randint(10, 30)): for _ in range(random.randint(10, 30)):
# 中途转PK/连麦立即跳过 # 中途转PK/连麦立即跳过
if session(xpath='//XCUIElementTypeOther[@name="kGBLInteractionViewMatchScoreBar"]').exists \ if session(xpath='//XCUIElementTypeOther[@name="kGBLInteractionViewMatchScoreBar"]').exists \
or AiUtils.count_add_by_xml(session) > 1: or AiUtils.count_add_by_xml(session) > 1:
print("❗ 中途发生 PK/连麦,跳过") print("❗ 中途发生 PK/连麦,跳过")
LogManager.method_info("❗ 中途发生 PK/连麦,跳过", "直播养号", udid=udid)
session.swipe_up() session.swipe_up()
break break
x = width // 3 + random.randint(-10, 10) x = width // 3 + random.randint(-10, 10)
y = height // 3 + random.randint(10, 20) y = height // 3 + random.randint(10, 20)
print("双击坐标:", x, y) print("双击坐标:", x, y)
session.double_tap(x, y) session.double_tap(x, y)
print("--------------------------------------------") print("--------------------------------------------")
@@ -248,7 +255,7 @@ class ScriptManager():
except Exception as e: except Exception as e:
retry_count += 1 retry_count += 1
LogManager.error(f"watchLiveForGrowth 异常(第{retry_count}次):{repr(e)}", udid) LogManager.method_error(f"watchLiveForGrowth 异常(第{retry_count}次):{repr(e)}", "直播养号", udid)
# 尝试轻量恢复一次,避免一些短暂性 session 失效 # 尝试轻量恢复一次,避免一些短暂性 session 失效
try: try:
client = wda.USBClient(udid) client = wda.USBClient(udid)
@@ -258,206 +265,6 @@ class ScriptManager():
time.sleep(backoff_sec) # 冷却后整段流程重来 time.sleep(backoff_sec) # 冷却后整段流程重来
continue continue
# # 关注打招呼以及回复主播消息
# def greetNewFollowers(self, udid, needReply, event):
# client = wda.USBClient(udid)
# session = client.session()
# print(f"是否要自动回复消息:{needReply}")
# # 先关闭Tik Tok
# ControlUtils.closeTikTok(session, udid)
# time.sleep(1)
#
# # 重新打开Tik Tok
# ControlUtils.openTikTok(session, udid)
# time.sleep(3)
#
# # 设置查找深度
# session.appium_settings({"snapshotMaxDepth": 15})
# # 点击搜索按钮
# ControlUtils.clickSearch(session)
#
# # 创建udid名称的目录
# AiUtils.makeUdidDir(udid)
#
# # 返回上一步
# def goBack(count):
# for i in range(count):
# ControlUtils.clickBack(session)
# time.sleep(2)
#
# # 循环条件。1、 循环关闭 2、 数据处理完毕
# while not event.is_set() or len(anchorList) > 0:
#
# # 查找输入框
# input = session.xpath('//XCUIElementTypeSearchField')
# # 如果找到了输入框,就点击并且输入内容
# input.click()
# # 稍作停顿
# time.sleep(1)
#
# # 获取一个主播
# anchor = anchorList[0]
# aid = anchor.anchorId
# anchorCountry = anchor.country
#
# input.clear_text()
# time.sleep(2)
# # 输入主播id
# input.set_text(aid + "\n")
#
# # 切换UI查找深度
# session.appium_settings({"snapshotMaxDepth": 25})
# # 定位 "关注" 按钮 通过关注按钮的位置点击主播首页
# follow_button = session.xpath("//XCUIElementTypeButton[@traits='Button' and @index='1']")
# time.sleep(2)
# if follow_button.exists:
# print(follow_button.bounds)
# # session.appium_settings({"snapshotMaxDepth": 10})
# print("找到关注按钮!")
# x = follow_button.bounds.x - 100
# y = follow_button.bounds.y
# print(x, y)
# client.click(x, y)
# print("进入主播首页啦")
# else:
# goBack(1)
# removeModelFromAnchorList(anchor)
# print("未找到关注按钮")
# continue
# time.sleep(3)
#
# session.appium_settings({"snapshotMaxDepth": 25})
# time.sleep(2)
#
# # 找到并点击第一个视频
# cellClickResult = ControlUtils.clickFirstVideoFromDetailPage(session)
# time.sleep(2)
#
# # 观看主播视频
# def viewAnchorVideo():
# print("开始查看视频,并且重新调整查询深度")
# session.appium_settings({"snapshotMaxDepth": 5})
# count = 3
# while count != 0:
# time.sleep(5)
# img = client.screenshot()
# time.sleep(1)
# filePath = f"resources/{udid}/bgv.png"
# img.save(filePath)
# LogManager.info("保存屏幕图像成功", udid)
# time.sleep(2)
# # 查找add图标
# r = ControlUtils.clickLike(session, udid)
# # 点赞成功。
# if r == True:
# count -= 1
#
# # 假装看几秒视频
# time.sleep(5)
# if count != 0:
# client.swipe_up()
#
# # 右滑返回
# client.swipe_right()
#
# # 如果打开视频失败。说明该主播没有视频
# if cellClickResult == True:
# # 观看主播视频
# LogManager.info("去查看主播视频", udid)
# viewAnchorVideo()
# time.sleep(3)
# LogManager.info("视频看完了,重置试图查询深度", udid)
# session.appium_settings({"snapshotMaxDepth": 25})
# # 点击关注按钮
# followButton = AiUtils.getFollowButton(session)
# if followButton is not None:
# LogManager.info("找到关注按钮了", udid)
# followButton.click()
# else:
# LogManager.info("没找到关注按钮", udid)
# removeModelFromAnchorList(anchor)
# goBack(3)
# continue
#
# time.sleep(2)
# msgButton = AiUtils.getSendMesageButton(session)
# time.sleep(2)
# if msgButton is not None:
# print("找到发消息按钮了")
# # 进入聊天页面
# msgButton.click()
# else:
# print("没有识别出发消息按钮")
# removeModelFromAnchorList(anchor)
# goBack(3)
# continue
#
# time.sleep(3)
# # 查找聊天界面中的输入框节点
# chatInput = session.xpath("//TextView")
# if chatInput.exists:
# print("找到输入框了, 准备发送一条打招呼消息")
# # 准备打招呼的文案
# text = random.choice(prologueList)
# # 翻译成主播国家的语言
# msg = Requester.translation(text, anchorCountry)
# # 准备发送一条信息
# chatInput.click()
# time.sleep(2)
# # 发送消息
# chatInput.set_text(msg + "\n")
# time.sleep(1)
# else:
# print("无法发送信息")
# LogManager.error(f"给主播{anchor.anchorId} 发送消息失败", udid)
#
# # 接着下一个主播
# removeModelFromAnchorList(anchor)
# goBack(4)
#
# else:
# print(f"{anchor.anchorId}:该主播没有视频")
# # 删除当前数据
# removeModelFromAnchorList(anchor)
# goBack(3)
# continue
#
# # 设置查找深度
# session.appium_settings({"snapshotMaxDepth": 15})
# time.sleep(2)
#
# print("即将要回复消息")
# if needReply:
# print("如果需要回复主播消息。走此逻辑")
# if AiUtils.getUnReadMsgCount(session) > 0:
#
# print("监控回复消息")
# # 执行回复消息逻辑
# self.monitorMessages(session, udid)
# homeButton = AiUtils.findHomeButton(udid)
# if homeButton.exists:
# homeButton.click()
# else:
# ControlUtils.closeTikTok(session, udid)
# time.sleep(2)
#
# ControlUtils.openTikTok(session, udid)
# time.sleep(3)
#
# print("重新创建wda会话 防止wda会话失效")
# client = wda.USBClient(udid)
# session = client.session()
#
# # 执行完成之后。继续点击搜索
# session.appium_settings({"snapshotMaxDepth": 15})
# # 点击搜索按钮
# ControlUtils.clickSearch(session)
#
# else:
# session.appium_settings({"snapshotMaxDepth": 15})
# # 点击搜索按钮
# ControlUtils.clickSearch(session)
""" """
外层包装,出现异常自动重试、 外层包装,出现异常自动重试、
关注打招呼以及回复主播消息 关注打招呼以及回复主播消息
@@ -472,9 +279,9 @@ class ScriptManager():
return # 成功执行就退出 return # 成功执行就退出
except Exception as e: except Exception as e:
retries += 1 retries += 1
LogManager.error(f"greetNewFollowers 出现异常: {e},准备第 {retries} 次重试", udid) LogManager.method_error(f"greetNewFollowers 出现异常: {e},准备第 {retries} 次重试", "关注打招呼", udid)
time.sleep(3) time.sleep(3)
LogManager.error("greetNewFollowers 重试次数耗尽,任务终止", udid) LogManager.method_error("greetNewFollowers 重试次数耗尽,任务终止", "关注打招呼", udid)
# 关注打招呼以及回复主播消息 # 关注打招呼以及回复主播消息
def greetNewFollowers(self, udid, needReply, event): def greetNewFollowers(self, udid, needReply, event):
@@ -483,7 +290,8 @@ class ScriptManager():
session = client.session() session = client.session()
print(f"是否要自动回复消息:{needReply}") print(f"是否要自动回复消息:{needReply}")
LogManager.info(f"是否要自动回复消息:{needReply}", udid) LogManager.method_info(f"是否要自动回复消息:{needReply}", "关注打招呼", udid)
# 先关闭Tik Tok # 先关闭Tik Tok
ControlUtils.closeTikTok(session, udid) ControlUtils.closeTikTok(session, udid)
time.sleep(1) time.sleep(1)
@@ -517,8 +325,10 @@ class ScriptManager():
# 强制刷新session # 强制刷新session
session.appium_settings({"snapshotMaxDepth": 15}) session.appium_settings({"snapshotMaxDepth": 15})
# 查找输入框 # 查找输入框
input = session.xpath('//XCUIElementTypeSearchField') input = session.xpath('//XCUIElementTypeSearchField')
# 如果找到了输入框,就点击并且输入内容 # 如果找到了输入框,就点击并且输入内容
if input.exists: if input.exists:
input.click() input.click()
@@ -526,6 +336,7 @@ class ScriptManager():
time.sleep(0.5) time.sleep(0.5)
else: else:
print(f"找不到输入框") print(f"找不到输入框")
input.clear_text() input.clear_text()
time.sleep(1) time.sleep(1)
# 输入主播id # 输入主播id
@@ -541,6 +352,8 @@ class ScriptManager():
except wda.WDAElementNotFoundError: except wda.WDAElementNotFoundError:
# 如果没有“关注”按钮,则不点击 # 如果没有“关注”按钮,则不点击
print("未找到‘关注’按钮,跳过点击。") print("未找到‘关注’按钮,跳过点击。")
LogManager.method_info("未找到‘关注’按钮,跳过点击。", "关注打招呼", udid)
goBack(2) goBack(2)
session.appium_settings({"snapshotMaxDepth": 15}) session.appium_settings({"snapshotMaxDepth": 15})
continue continue
@@ -576,7 +389,7 @@ class ScriptManager():
img.save(filePath) img.save(filePath)
LogManager.info("保存屏幕图像成功", udid) LogManager.method_info("保存屏幕图像成功", "关注打招呼", udid)
time.sleep(2) time.sleep(2)
# 查找add图标 # 查找add图标
r = ControlUtils.clickLike(session, udid) r = ControlUtils.clickLike(session, udid)
@@ -597,10 +410,10 @@ class ScriptManager():
# 如果打开视频失败。说明该主播没有视频 # 如果打开视频失败。说明该主播没有视频
if cellClickResult == True: if cellClickResult == True:
# 观看主播视频 # 观看主播视频
LogManager.info("去查看主播视频", udid) LogManager.method_info("去查看主播视频", "关注打招呼", udid)
viewAnchorVideo(workCount) viewAnchorVideo(workCount)
time.sleep(3) time.sleep(3)
LogManager.info("视频看完了,重置试图查询深度", udid) LogManager.method_info("视频看完了,重置试图查询深度", "关注打招呼", udid)
session.appium_settings({"snapshotMaxDepth": 25}) session.appium_settings({"snapshotMaxDepth": 25})
# 向上滑动 # 向上滑动
@@ -609,10 +422,10 @@ class ScriptManager():
# 点击关注按钮 # 点击关注按钮
followButton = AiUtils.getFollowButton(session) followButton = AiUtils.getFollowButton(session)
if followButton is not None: if followButton is not None:
LogManager.info("找到关注按钮了", udid) LogManager.method_info("找到关注按钮了", "关注打招呼", udid)
followButton.click() followButton.click()
else: else:
LogManager.info("没找到关注按钮", udid) LogManager.method_info("没找到关注按钮", "关注打招呼", udid)
goBack(3) goBack(3)
session.appium_settings({"snapshotMaxDepth": 15}) session.appium_settings({"snapshotMaxDepth": 15})
continue continue
@@ -621,10 +434,12 @@ class ScriptManager():
msgButton = AiUtils.getSendMesageButton(session) msgButton = AiUtils.getSendMesageButton(session)
time.sleep(2) time.sleep(2)
if msgButton is not None: if msgButton is not None:
LogManager.method_info("找到发消息按钮了", "关注打招呼", udid)
print("找到发消息按钮了") print("找到发消息按钮了")
# 进入聊天页面 # 进入聊天页面
msgButton.click() msgButton.click()
else: else:
LogManager.method_info("没有识别出发消息按钮", "关注打招呼", udid)
print("没有识别出发消息按钮") print("没有识别出发消息按钮")
goBack(3) goBack(3)
session.appium_settings({"snapshotMaxDepth": 15}) session.appium_settings({"snapshotMaxDepth": 15})
@@ -635,6 +450,7 @@ class ScriptManager():
chatInput = session.xpath("//TextView") chatInput = session.xpath("//TextView")
if chatInput.exists: if chatInput.exists:
print("找到输入框了, 准备发送一条打招呼消息") print("找到输入框了, 准备发送一条打招呼消息")
LogManager.method_info("找到输入框了, 准备发送一条打招呼消息", "关注打招呼", udid)
# 准备打招呼的文案 # 准备打招呼的文案
text = random.choice(prologueList) text = random.choice(prologueList)
# 翻译成主播国家的语言 # 翻译成主播国家的语言
@@ -647,16 +463,16 @@ class ScriptManager():
time.sleep(1) time.sleep(1)
else: else:
print("无法发送信息") print("无法发送信息")
LogManager.error(f"给主播{anchor.anchorId} 发送消息失败", udid) LogManager.method_info(f"给主播{anchor.anchorId} 发送消息失败", "关注打招呼", udid)
# 接着下一个主播 # 接着下一个主播
# removeModelFromAnchorList(anchor) # removeModelFromAnchorList(anchor)
session.appium_settings({"snapshotMaxDepth": 15}) session.appium_settings({"snapshotMaxDepth": 15})
goBack(4) goBack(4)
else: else:
print(f"{anchor.anchorId}:该主播没有视频") print(f"{anchor.anchorId}:该主播没有视频")
LogManager.method_info(f"{anchor.anchorId}:该主播没有视频", "关注打招呼", udid)
goBack(3) goBack(3)
session.appium_settings({"snapshotMaxDepth": 15}) session.appium_settings({"snapshotMaxDepth": 15})
continue continue
@@ -666,13 +482,16 @@ class ScriptManager():
time.sleep(2) time.sleep(2)
print("即将要回复消息") print("即将要回复消息")
LogManager.method_info("即将要回复消息", "关注打招呼", udid)
if needReply: if needReply:
print("如果需要回复主播消息。走此逻辑") print("如果需要回复主播消息。走此逻辑")
if AiUtils.getUnReadMsgCount(session) > 0: if AiUtils.getUnReadMsgCount(session) > 0:
print("监控回复消息") print("监控回复消息")
# 执行回复消息逻辑 # 执行回复消息逻辑
self.monitorMessages(session, udid) self.monitorMessages(session, udid)
homeButton = AiUtils.findHomeButton(udid) homeButton = AiUtils.findHomeButton(udid)
if homeButton.exists: if homeButton.exists:
homeButton.click() homeButton.click()
@@ -713,7 +532,7 @@ class ScriptManager():
# 调用检测消息的方法 # 调用检测消息的方法
self.monitorMessages(session, udid) self.monitorMessages(session, udid)
except Exception as e: except Exception as e:
LogManager.error(f"监控消息 出现异常: {e},重新启动监控直播", udid) LogManager.method_error(f"监控消息 出现异常: {e},重新启动监控直播", "检测消息", udid)
# 出现异常时,稍等再重启 TikTok 并重试 # 出现异常时,稍等再重启 TikTok 并重试
ControlUtils.closeTikTok(session, udid) ControlUtils.closeTikTok(session, udid)
time.sleep(2) time.sleep(2)
@@ -744,7 +563,7 @@ class ScriptManager():
el = session(xpath='//XCUIElementTypeButton[@name="a11y_vo_inbox"]') el = session(xpath='//XCUIElementTypeButton[@name="a11y_vo_inbox"]')
print("el", el) print("el", el)
if not el.exists: if not el.exists:
LogManager.error(f"检测不到收件箱", udid) LogManager.method_error(f"检测不到收件箱", "检测消息", udid)
raise Exception("当前页面找不到收件箱,重启") raise Exception("当前页面找不到收件箱,重启")
# break # break
@@ -759,14 +578,14 @@ class ScriptManager():
inbox_nodes = session.xpath(xpath_query).find_elements() inbox_nodes = session.xpath(xpath_query).find_elements()
if len(inbox_nodes) < 2: if len(inbox_nodes) < 2:
LogManager.error(f"当前页面不再收件箱页面,重启", udid) LogManager.method_error(f"当前页面不再收件箱页面,重启", "检测消息", udid)
raise Exception("当前页面不再收件箱页面,重启") raise Exception("当前页面不再收件箱页面,重启")
m = re.search(r'(\d+)', el.label) # 抓到的第一个数字串 m = re.search(r'(\d+)', el.label) # 抓到的第一个数字串
count = int(m.group(1)) if m else 0 count = int(m.group(1)) if m else 0
if not count: if not count:
LogManager.info(f"当前收件箱的总数量{count}", udid) LogManager.method_info(f"当前收件箱的总数量{count}", "检测消息", udid)
break break
# 新粉丝 # 新粉丝
@@ -809,9 +628,9 @@ class ScriptManager():
val = (user_text.info.get("value") or val = (user_text.info.get("value") or
user_text.info.get("label") or user_text.info.get("label") or
user_text.info.get("name")) user_text.info.get("name"))
LogManager.info(f"用户未读数量:{val}", udid) LogManager.method_info(f"用户未读数量:{val}", "检测消息", udid)
except Exception: except Exception:
LogManager.warning("当前屏幕没有找到 用户 未读徽标数字", udid) LogManager.method_warning("当前屏幕没有找到 用户 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 用户消息 未读徽标数字", udid) print("当前屏幕没有找到 用户消息 未读徽标数字", udid)
user_text = None user_text = None
info_count += 1 info_count += 1
@@ -846,7 +665,7 @@ class ScriptManager():
sel.clear_text() sel.clear_text()
sel.set_text(aiResult + "\n") sel.set_text(aiResult + "\n")
else: else:
LogManager.error("找不到输入框,重启", udid) LogManager.method_error("找不到输入框,重启", "检测消息", udid)
raise Exception("找不到输入框,重启") raise Exception("找不到输入框,重启")
else: else:
# 如果不是第一次发消息证明存储的有sessionId # 如果不是第一次发消息证明存储的有sessionId
@@ -859,7 +678,7 @@ class ScriptManager():
sel.clear_text() sel.clear_text()
sel.set_text(aiResult + "\n") sel.set_text(aiResult + "\n")
LogManager.info(f"存储的sessionId:{anchorWithSession}", udid) LogManager.method_info(f"存储的sessionId:{anchorWithSession}", "检测消息", udid)
time.sleep(1) time.sleep(1)
# 返回 # 返回
ControlUtils.clickBack(session) ControlUtils.clickBack(session)
@@ -874,14 +693,15 @@ class ScriptManager():
val = (badge_text.info.get("value") or val = (badge_text.info.get("value") or
badge_text.info.get("label") or badge_text.info.get("label") or
badge_text.info.get("name")) badge_text.info.get("name"))
LogManager.info(f"新粉丝未读数量:{val}", udid)
LogManager.method_info(f"新粉丝未读数量:{val}", "检测消息", udid)
if badge_text: if badge_text:
badge_text.tap() badge_text.tap()
time.sleep(1) time.sleep(1)
ControlUtils.clickBack(session) ControlUtils.clickBack(session)
time.sleep(1) time.sleep(1)
except Exception: except Exception:
LogManager.warning("当前屏幕没有找到 新粉丝 未读徽标数字", udid) LogManager.method_warning("当前屏幕没有找到 新粉丝 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 新粉丝 未读徽标数字", udid) print("当前屏幕没有找到 新粉丝 未读徽标数字", udid)
badge_text = None badge_text = None
info_count += 1 info_count += 1
@@ -893,33 +713,32 @@ class ScriptManager():
val = (badge_text.info.get("value") or val = (badge_text.info.get("value") or
badge_text.info.get("label") or badge_text.info.get("label") or
badge_text.info.get("name")) badge_text.info.get("name"))
LogManager.info(f"活动未读数量:{val}", udid) LogManager.method_info(f"活动未读数量:{val}", "检测消息", udid)
if badge_text: if badge_text:
badge_text.tap() badge_text.tap()
time.sleep(1) time.sleep(1)
ControlUtils.clickBack(session) ControlUtils.clickBack(session)
time.sleep(1) time.sleep(1)
except Exception: except Exception:
LogManager.warning("当前屏幕没有找到 活动 未读徽标数字", udid) LogManager.method_warning("当前屏幕没有找到 活动 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 活动 未读徽标数字", udid) print("当前屏幕没有找到 活动 未读徽标数字", udid)
badge_text = None badge_text = None
info_count += 1 info_count += 1
try: try:
# 如果 2 秒内找不到,会抛异常 # 如果 2 秒内找不到,会抛异常
badge_text = session.xpath(xp_system_badge).get(timeout=2.0) badge_text = session.xpath(xp_system_badge).get(timeout=2.0)
val = (badge_text.info.get("value") or val = (badge_text.info.get("value") or
badge_text.info.get("label") or badge_text.info.get("label") or
badge_text.info.get("name")) badge_text.info.get("name"))
LogManager.info(f"系统通知未读数量:{val}", udid) LogManager.method_info(f"系统通知未读数量:{val}", "检测消息", udid)
if badge_text: if badge_text:
badge_text.tap() badge_text.tap()
time.sleep(1) time.sleep(1)
ControlUtils.clickBack(session) ControlUtils.clickBack(session)
time.sleep(1) time.sleep(1)
except Exception: except Exception:
LogManager.warning("当前屏幕没有找到 系统通知 未读徽标数字", udid) LogManager.method_warning("当前屏幕没有找到 系统通知 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 系统通知 未读徽标数字", udid) print("当前屏幕没有找到 系统通知 未读徽标数字", udid)
badge_text = None badge_text = None
info_count += 1 info_count += 1
@@ -930,14 +749,14 @@ class ScriptManager():
val = (badge_text.info.get("value") or val = (badge_text.info.get("value") or
badge_text.info.get("label") or badge_text.info.get("label") or
badge_text.info.get("name")) badge_text.info.get("name"))
LogManager.info(f"消息请求未读数量:{val}", udid) LogManager.method_info(f"消息请求未读数量:{val}", "检测消息", udid)
if badge_text: if badge_text:
badge_text.tap() badge_text.tap()
time.sleep(1) time.sleep(1)
ControlUtils.clickBack(session) ControlUtils.clickBack(session)
time.sleep(1) time.sleep(1)
except Exception: except Exception:
LogManager.warning("当前屏幕没有找到 消息请求 未读徽标数字", udid) LogManager.method_warning("当前屏幕没有找到 消息请求 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 消息请求 未读徽标数字", udid) print("当前屏幕没有找到 消息请求 未读徽标数字", udid)
badge_text = None badge_text = None
info_count += 1 info_count += 1
@@ -948,10 +767,10 @@ class ScriptManager():
cx = int((r.x + r.width / 2) if hasattr(r, "x") else (r[0] + r[2] / 2)) cx = int((r.x + r.width / 2) if hasattr(r, "x") else (r[0] + r[2] / 2))
cy = int((r.y + r.height / 2) if hasattr(r, "y") else (r[1] + r[3] / 2)) cy = int((r.y + r.height / 2) if hasattr(r, "y") else (r[1] + r[3] / 2))
session.double_tap(cx, cy) # 可能抛异常:方法不存在 session.double_tap(cx, cy) # 可能抛异常:方法不存在
LogManager.info(f"双击收件箱 定位到信息", udid) LogManager.method_info(f"双击收件箱 定位到信息", "检测消息", udid)
else: else:
return return
else: else:
LogManager.error(f"检测不到收件箱", udid) LogManager.method_error(f"检测不到收件箱", "检测消息", udid)
raise Exception("当前页面找不到收件箱,重启") raise Exception("当前页面找不到收件箱,重启")