first commit

This commit is contained in:
xgh 2026-10-17 10:46:29 +08:00
commit ba3ae8bd6e
30 changed files with 12774 additions and 0 deletions

53
.gitignore vendored Normal file
View File

@ -0,0 +1,53 @@
# Python virtual environments and packaging artifacts
.venv/
venv/
env/
ENV/
*.egg-info/
dist/
build/
pip-wheel-metadata/
# Python bytecode and test/tool caches
__pycache__/
*.py[cod]
*$py.class
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
.coverage.*
htmlcov/
.hypothesis/
# IDE and local editor files
.idea/
.vscode/
*.swp
*.swo
.DS_Store
# Local environment and secrets
.env
.env.*
!.env.example
# Playwright browser binaries and local browser profiles
playwright-report/
blob-report/
test-results/
playwright/.cache/
data/browser_profiles/
data/playwright/
# Application runtime state and generated diagnostics
*.ses
data/logs/*.log
data/logs/screenshots/
# Auto.js/editor generated files
autojs6/**/.idea/
autojs6/**/node_modules/
autojs6/**/dist/
autojs6/**/build/

36
README.md Normal file
View File

@ -0,0 +1,36 @@
# Web 群控工作台 MVP
这是一个本地运行的网页多实例控制台:输入网址和实例数量后,会并行创建隔离的 Playwright 浏览器上下文,打开页面、按文字尝试点击,并持续回传每个实例的实时画面。实例会保持运行,直到在控制台点击“停止任务”。
点击实例画面可进入放大操作界面。放大界面支持点击、双击、滚轮、键盘输入和粘贴文字,操作会转发到对应的浏览器实例。
## 启动
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
playwright install chromium
uvicorn app:app --reload
```
浏览器打开 <http://127.0.0.1:8000>。
## 浏览器容器版
这是一个独立桌面窗口,每个实例都是可直接操作的 Qt WebEngine 浏览器容器,不依赖截图流:
```bash
./.venv/bin/pip install -r requirements.txt
./.venv/bin/python desktop_app.py
```
窗口中输入网址和实例数量,点击“启动实例”即可。每个实例使用独立的持久化 Cookie、本地存储和浏览器 Session,重启桌面程序后仍可复用登录状态。
网址输入框会自动保存最近 20 条地址,点击下拉框即可重新选择;“清除缓存”会清理当前实例的 HTTP 缓存、Cookie 和页面存储。
脚本区域可以选择“Home → 应用宝”或“Home → 支付宝”,点击“开始脚本”后,所有已打开的实例会并行执行:等待页面加载完成,点击云手机画面底部导航栏的 Home 圆形按钮,再抓取各自浏览器画面,用 RapidOCR 查找目标文字,最后使用原生鼠标点击。每个实例的脚本状态会显示在自己的容器底部。浏览器容器按云手机画面比例固定尺寸,多个实例以 3 列排列。
脚本调试日志会实时显示在桌面窗口底部,完整文件位于 `data/logs/fengyun.log`。日志包含页面 URL、截图尺寸、设备像素比、OCR 每一条识别文本及坐标、目标映射坐标、DOM 命中结果和原生鼠标回退结果。每次 OCR 命中还会在 `data/logs/screenshots/` 保存一张标注图:红框是 OCR 识别框,绿点是 OCR 中心点。
当前版本的任务状态只保存在进程内,服务重启后会清空。请只对你有权操作的网站使用自动化功能,并遵守目标网站规则。

347
app.py Normal file
View File

@ -0,0 +1,347 @@
from __future__ import annotations
import asyncio
import base64
import json
import re
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, field_validator
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
RUNS_DIR = STATIC_DIR / "runs"
RUNS_DIR.mkdir(parents=True, exist_ok=True)
app = FastAPI(title="Web 群控工作台")
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
class RunRequest(BaseModel):
url: str
instances: int = Field(default=3, ge=1, le=12)
action_text: str = Field(default="", max_length=120)
@field_validator("url")
@classmethod
def validate_url(cls, value: str) -> str:
value = value.strip()
parsed = urlparse(value)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("请输入完整的网址,例如 https://example.com")
return value
@dataclass
class InstanceState:
id: int
status: str = "等待中"
message: str = ""
title: str = ""
frame: bytes | None = field(default=None, repr=False)
frame_version: int = field(default=0, repr=False)
page: Any | None = field(default=None, repr=False)
control_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
@dataclass
class RunState:
id: str
url: str
instances: list[InstanceState]
status: str = "运行中"
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
error: str = ""
stop_event: asyncio.Event = field(default_factory=asyncio.Event, repr=False)
task: asyncio.Task[Any] | None = field(default=None, repr=False)
subscribers: set[asyncio.Queue[dict[str, Any]]] = field(default_factory=set, repr=False)
runs: dict[str, RunState] = {}
def publish_run(run: RunState) -> None:
snapshot = public_run(run)
for queue in tuple(run.subscribers):
if queue.full():
try:
queue.get_nowait()
except asyncio.QueueEmpty:
pass
queue.put_nowait(snapshot)
def public_run(run: RunState) -> dict[str, Any]:
return {
"id": run.id,
"url": run.url,
"status": run.status,
"created_at": run.created_at,
"error": run.error,
"instances": [
{
"id": instance.id,
"status": instance.status,
"message": instance.message,
"title": instance.title,
"stream": f"/api/runs/{run.id}/instances/{instance.id}/stream",
"control": f"/ws/runs/{run.id}/instances/{instance.id}",
}
for instance in run.instances
],
}
async def control_instance(browser: Any, run: RunState, state: InstanceState, action_text: str) -> None:
context = await browser.new_context(viewport={"width": 1365, "height": 860})
page = await context.new_page()
state.page = page
cdp = None
try:
cdp = await context.new_cdp_session(page)
def receive_frame(payload: dict[str, Any]) -> None:
state.frame = base64.b64decode(payload["data"])
state.frame_version += 1
asyncio.create_task(
cdp.send("Page.screencastFrameAck", {"sessionId": payload["sessionId"]})
)
cdp.on("Page.screencastFrame", receive_frame)
await cdp.send(
"Page.startScreencast",
{"format": "jpeg", "quality": 72, "maxWidth": 1365, "maxHeight": 860},
)
state.status = "打开页面"
publish_run(run)
await page.goto(run.url, wait_until="domcontentloaded", timeout=30_000)
state.title = await page.title()
publish_run(run)
if run.stop_event.is_set():
state.status = "已停止"
publish_run(run)
return
if action_text:
state.status = "识别文字"
publish_run(run)
locator = page.get_by_text(re.compile(re.escape(action_text), re.IGNORECASE)).first
try:
await locator.wait_for(state="visible", timeout=5_000)
await locator.click(timeout=5_000)
state.message = f"已点击“{action_text}”"
except Exception:
state.message = f"未找到“{action_text}”,已保留页面"
else:
state.message = "页面已打开"
publish_run(run)
state.status = "实时监控"
publish_run(run)
await run.stop_event.wait()
state.status = "已停止"
state.message = "实时画面已停止"
publish_run(run)
except Exception as exc:
state.status = "失败"
state.message = str(exc)[:180]
publish_run(run)
finally:
if cdp is not None:
try:
await cdp.send("Page.stopScreencast")
except Exception:
pass
await context.close()
state.page = None
async def execute_run(run: RunState, action_text: str) -> None:
try:
from playwright.async_api import async_playwright
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=True)
try:
await asyncio.gather(
*(control_instance(browser, run, state, action_text) for state in run.instances)
)
finally:
await browser.close()
if run.stop_event.is_set():
run.status = "已停止"
elif any(item.status == "失败" for item in run.instances):
run.status = "部分失败"
else:
run.status = "已完成"
publish_run(run)
except Exception as exc:
run.status = "失败"
run.error = "浏览器启动失败,请先执行:playwright install chromium"
for state in run.instances:
if state.status == "等待中":
state.status = "失败"
state.message = str(exc)[:180]
publish_run(run)
@app.get("/")
async def index() -> FileResponse:
return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-store, max-age=0"})
@app.get("/api/health")
async def health() -> dict[str, str]:
return {"status": "ok"}
@app.post("/api/runs")
async def create_run(request: RunRequest) -> dict[str, Any]:
run_id = uuid.uuid4().hex[:10]
run = RunState(
id=run_id,
url=request.url,
instances=[InstanceState(id=index + 1) for index in range(request.instances)],
)
runs[run_id] = run
run.task = asyncio.create_task(execute_run(run, request.action_text.strip()))
return public_run(run)
@app.get("/api/runs/{run_id}")
async def get_run(run_id: str) -> dict[str, Any]:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
return public_run(run)
@app.get("/api/runs/{run_id}/events")
async def run_events(run_id: str) -> StreamingResponse:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=3)
run.subscribers.add(queue)
queue.put_nowait(public_run(run))
async def event_stream():
try:
while True:
snapshot = await queue.get()
yield f"data: {json.dumps(snapshot, ensure_ascii=False)}\n\n"
if snapshot["status"] not in {"运行中", "停止中"}:
break
finally:
run.subscribers.discard(queue)
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
)
@app.get("/api/runs/{run_id}/instances/{instance_id}/stream")
async def instance_stream(run_id: str, instance_id: int) -> StreamingResponse:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
state = next((item for item in run.instances if item.id == instance_id), None)
if state is None:
raise HTTPException(status_code=404, detail="实例不存在")
async def frame_stream():
last_version = -1
while True:
if state.frame is not None and state.frame_version != last_version:
last_version = state.frame_version
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n"
b"Cache-Control: no-cache\r\n\r\n"
+ state.frame
+ b"\r\n"
)
if run.status not in {"运行中", "停止中"} and last_version == state.frame_version:
break
await asyncio.sleep(0.08)
return StreamingResponse(
frame_stream(),
media_type="multipart/x-mixed-replace; boundary=frame",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
)
@app.websocket("/ws/runs/{run_id}/instances/{instance_id}")
async def instance_control(websocket: WebSocket, run_id: str, instance_id: int) -> None:
run = runs.get(run_id)
state = next((item for item in run.instances if item.id == instance_id), None) if run else None
if run is None or state is None:
await websocket.close(code=1008, reason="任务或实例不存在")
return
await websocket.accept()
try:
while True:
message = await websocket.receive_json()
page = state.page
if page is None:
await websocket.send_json({"type": "error", "message": "实例尚未准备好"})
continue
async with state.control_lock:
event_type = message.get("type")
if event_type == "click":
await page.mouse.click(
float(message["x"]),
float(message["y"]),
button=message.get("button", "left"),
click_count=int(message.get("clickCount", 1)),
)
elif event_type == "wheel":
await page.mouse.wheel(float(message.get("deltaX", 0)), float(message.get("deltaY", 0)))
elif event_type == "key":
key = str(message["key"])
modifiers = [str(item) for item in message.get("modifiers", [])]
if len(key) == 1 and not modifiers:
await page.keyboard.insert_text(key)
else:
combo = "+".join([*modifiers, key]) if modifiers else key
await page.keyboard.press(combo)
elif event_type == "text":
await page.keyboard.insert_text(str(message.get("value", "")))
else:
await websocket.send_json({"type": "error", "message": "不支持的操作"})
continue
await websocket.send_json({"type": "ack", "event": event_type})
except WebSocketDisconnect:
return
except Exception as exc:
try:
await websocket.send_json({"type": "error", "message": str(exc)[:180]})
except Exception:
return
@app.post("/api/runs/{run_id}/stop")
async def stop_run(run_id: str) -> dict[str, Any]:
run = runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="任务不存在")
run.stop_event.set()
if run.status == "运行中":
run.status = "停止中"
publish_run(run)
return public_run(run)

48
app_logging.py Normal file
View File

@ -0,0 +1,48 @@
from __future__ import annotations
import logging
from pathlib import Path
from PySide6.QtCore import QObject, Signal
_configured = False
_ui_handler: logging.Handler | None = None
class LogEmitter(QObject):
message = Signal(str)
class QtLogHandler(logging.Handler):
def __init__(self, emitter: LogEmitter) -> None:
super().__init__(logging.DEBUG)
self.emitter = emitter
def emit(self, record: logging.LogRecord) -> None:
self.emitter.message.emit(self.format(record))
def configure_ui_logging(emitter: LogEmitter) -> None:
global _ui_handler
logger = logging.getLogger("fengyun")
if _ui_handler:
logger.removeHandler(_ui_handler)
_ui_handler = QtLogHandler(emitter)
_ui_handler.setFormatter(logging.Formatter("%(asctime)s [%(instance)s] %(levelname)s %(message)s", "%H:%M:%S"))
logger.addHandler(_ui_handler)
def get_instance_logger(instance_id: int) -> logging.LoggerAdapter:
global _configured
log_dir = Path(__file__).resolve().parent / "data" / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
logger = logging.getLogger("fengyun")
if not _configured:
logger.setLevel(logging.DEBUG)
logger.propagate = False
handler = logging.FileHandler(log_dir / "fengyun.log", encoding="utf-8")
handler.setFormatter(logging.Formatter("%(asctime)s [instance=%(instance)s] %(levelname)s %(message)s"))
logger.addHandler(handler)
_configured = True
return logging.LoggerAdapter(logger, {"instance": instance_id})

54
autojs6/README.md Normal file
View File

@ -0,0 +1,54 @@
# AutoJS 6 脚本
## 卸载当天安装的应用
独立脚本:`uninstall_today_apps.js`,复制到目标 Android 设备后在 AutoJS 6 中直接运行,不依赖应用宝脚本、无障碍或 OCR。
运行流程:
1. 读取当前用户已安装、且对 AutoJS 可见的应用。
2. 按设备本地日期,筛选 `firstInstallTime` 位于今天零点至次日零点之间的应用。今天仅更新、首次安装在以前的应用不会命中。
3. 跳过系统应用(含更新过的系统应用)、运行脚本的 AutoJS 自身及保留名单。
4. 先在日志中输出完整的待卸载包名列表,通过 `id` 检查执行身份,再逐个执行 `pm uninstall <包名>`,输出成功、失败及汇总结果。明确返回失败时继续后续应用;命令超时、结果未知时停止整批操作。
**默认会真实卸载并删除应用数据,不会弹窗二次确认。** 使用前请确认设备日期、时区及保留名单。卸载需要 Root 权限,默认通过独立进程执行 `/system/xbin/mus -c`,不再调用可能卡住的 AutoJS `shell(command, true)`。未授权或身份检查超时时停止,不会改用 UI 卸载或尝试其他提权方式。
可修改脚本顶部配置:
```javascript
var CONFIG = {
dryRun: true, // true:只输出列表;false:执行卸载(默认)
shellRoot: true, // 默认通过 mus 提权;false 不会自动赋予卸载权限
commandTimeoutMs: 30000, // 身份检查及每条卸载命令的超时
progressIntervalMs: 5000, // 等待期间每 5 秒输出一次进度
keepPackages: [
"com.tencent.android.qqdownloader" // 示例:保留应用宝
]
};
```
注意:
- Android 11 及以上的应用可见性限制可能使列表不完整,需要 AutoJS 具有相应的包查询权限;空列表不一定代表今天没有安装应用。
- `pm uninstall` 不带 `-k` 或 `--user`,使用系统命令默认卸载行为;在多用户设备上可能影响其他用户,请勿当作“仅当前用户卸载”使用。
- 日期范围在脚本启动时固定;卸载失败的详细原因(如权限不足、设备管理限制)见日志中的退出码和命令输出。
- 使用 Java `ProcessBuilder` 启动命令,把输出重定向到 AutoJS 私有缓存临时文件,通过非阻塞 `exitValue()` 轮询,不等待输出管道 EOF;命令默认 30 秒超时。运行结束会清理临时文件。
- 超时会尝试销毁直接子进程,但不能保证终止 `mus` 派生的所有进程,因此不会自动重试或继续下一包;请先核实实际安装状态。
- 需要设备的 `/system/xbin/mus` 可从 AutoJS 进程使用并允许提权。身份检查和卸载命令均已由 `su -c` 改为 `mus -c`,使用绝对路径,不依赖 PATH。adb 环境中的 `mus -c id` 已验证能返回 Root,但不代表 AutoJS 进程也能使用;如果 `mus -c id` 在 AutoJS 中仍超时,需排查云手机的进程域权限限制。
### 旧版停在“执行:pm uninstall ...”
这表示旧版同步 `shell()` 没有返回,不能仅凭该日志判断应用是否卸载成功,也不能确定具体是授权、命令执行还是输出管道阻塞。
先停止旧任务;若 AutoJS 无法停止,重启 AutoJS 后重新打开。将更新后的 `uninstall_today_apps.js` 覆盖到设备的实际运行路径并重新运行(只覆盖文件不会更新正在运行的脚本)。新版先输出身份检查,等待中每 5 秒输出进度,命令默认 30 秒超时;若仍失败,请提供从“检查执行身份”开始的完整日志。
本地离线验证(不会连接设备或卸载应用):
```bash
node --check uninstall_today_apps.js
node --test tests/uninstall_today_apps.test.js
```
## 应用宝任务
见 [`home_yibao/README.md`](home_yibao/README.md)。

View File

@ -0,0 +1,180 @@
# AutoJS 6:Home → 应用宝
这是 `data/scripts/home_yibao.json` 的 AutoJS 6 OCR 版本,运行在云手机 Android 内部。
云手机画面是 Canvas/视频流,无障碍树没有对应按钮节点,因此本版本使用 AutoJS 截图 OCR:
- 应用宝通过包名 `com.tencent.android.qqdownloader` 启动;
- 页面文字通过 OCR 识别;
- OCR 返回文字框后,点击文字框中心;“应用宝”会自动向上偏移到图标本体;
- 找不到“去观看”时通过滑动页面继续 OCR 查找;“去观看”只通过“看视频赚积分”标题锚点定位同一行后点击(不再直接文本匹配,避免单字容错误点其他任务行的“去完成”等按钮),按钮文字 OCR 不到时依次回退局部放大 OCR 和固定布局坐标;
- 广告关闭按钮按照 Android 屏幕比例点击。
主任务奖励发放后,若出现“继续做任务得额外奖励”横幅,脚本会自动执行额外任务“下载并打开浏览,多得 40 积分”:
1. 点击“立即下载”入口 → 跳转到应用详情页(应用名称/权限详情/隐私协议);
2. 详情页再次点击“立即下载”,等待“已下载n%”进度完成;
3. 安装器点击“下一步”,等待安装完成跳回应用宝;
4. 详情页点击“打开”跳转第三方应用,浏览 5 秒后返回应用宝,点左上角 X;
5. 出现“打开浏览 5 秒,多得 40 积分”弹窗后点“立即打开应用”,浏览 10 秒后返回应用宝;
6. 点右上角 X 结束当次任务。
未出现该横幅则当次任务完成。额外任务全程容错:任何步骤失败只记日志、不重跑主任务(`CONFIG.extraTask` 可调各阶段超时)。“跳回应用宝”通过无障碍前台检测验证,返回键优先、按包名拉起兜底(`backToYibao`)。
额外任务的按钮文案与路径适配(实测于腾讯地图 164MB 包):
- **入口按钮文案随状态变化**:未下载“立即下载”/APK 已缓存“立即安装”/已安装“打开”或“立即打开”,点击目标已全部覆盖;APK 已缓存时点击入口会**直达安装器**(跳过详情页与下载等待),步骤 2 同时等待“详情页或安装器”两条路径。
- **“打开”误匹配防护**:详情页头部“应用名称…11.6.01 开发者…”归一化后,滑窗“1开”曾以汉明距离 1 误命中“打开”,把 25% 下载进度误判成完成并误点头部。现在:① 全中文目标不与含数字/字母的窗口做单字容错(`isCjkText`);② 按钮/状态判定只认独立短文本(`filterShortTextMatches`,长度 <=6);③ 按钮类点击传 `preferShortText`,多命中时短文本优先。
- **安装器“下一步”用标定坐标**:系统 PackageInstaller 布局固定但底部小按钮 OCR 不稳(常只识别到标题“个软件安装”),确认前台包名为 `com.android.packageinstaller` 后直接点标定坐标 `installNextButton`。
- **安装后回页两种可能**:正常路径回详情页(点左上角 X 关闭),直达安装器路径回奖励页(跳过 X),步骤 5 按页面内容判断。
- **中断恢复**:上次运行中断后残留的奖励页/详情页/安装器会在下次启动时被 `enterYibaoTaskCenter` 识别(返回 `reward_page`/`detail_page`/`installer_page`),从中断处继续补完额外任务而不是按“未进入任务中心”失败重跑。
## 当前流程补充说明
### 主任务 4/6 后直达第三方应用
主任务第 4 步点击“立即下载/了解详情/查看详情/立即体验”等广告按钮后,可能不会留在应用宝广告页,而是直接拉起第三方应用。脚本会在点击后等待 5 秒检查前台包名:
- 前台不是应用宝、安装器、AutoJS、桌面时,视为已经进入第三方应用;
- 直接复用额外任务第 7 步逻辑:在第三方应用浏览 `CONFIG.extraTask.reopenWaitMs`(默认 10 秒)→ 返回应用宝 → 关闭右上角 X;
- 相关函数:`isThirdPartyForeground()`、`waitThirdPartyForeground()`、`handleThirdPartyAsExtraStep7()`。
### 主任务 5/6 与 6/6 的关闭按钮区别
两个关闭按钮位置不同,不能混用:
- **主任务 5/6**:广告观看结束后点击左侧 X,坐标使用 `CONFIG.adClose`。
- **主任务 6/6**:奖励/残留广告页点击右上角带圆圈的 X。
- 优先通过无障碍 `desc="点击退出关闭视频"` 点击;
- 无障碍失败时兜底点击坐标 `(664, 142)`,比例为 `CONFIG.adCircleClose = { x: 0.9222, y: 0.1109 }`;
- 再兜底尝试 `adPageClose`、`rewardClose`、`detailClose`。
右上角圆圈 X 没有稳定 OCR 文本,不依赖 OCR 识别 X 本身。相关函数:`clickByAccessibilityDesc()`、`closeYibaoTaskPage()`。
### 主任务 6/6 OCR 等待策略
主任务 6/6 主要用于判断是否出现“继续做任务得额外奖励”入口。为避免静态画面下 `captureScreen()` 单帧阻塞导致长时间 OCR,当前等待策略为:
- `CONFIG.extraTask.entryWaitMs = 10000`:最多等待 10 秒检查额外任务入口;
- 未出现入口后,先尝试无障碍 `desc="点击退出关闭视频"` 关闭右上角圆圈 X;
- `CONFIG.extraTask.residualWaitMs = 3000`:无障碍未找到时,仅短暂检查“看15秒/恭喜已获得”等残留页关键词。
### 额外任务 #2
整体任务结束后,应用宝可能出现“恭喜您 / 再看一条再领”等提示,表示触发了新的额外任务 #2。脚本处理方式:
1. 任务结束后等待 `CONFIG.extraTask2.checkDelayMs`(默认 3 秒);
2. 每 `checkIntervalMs`(默认 1 秒)检查一次,持续 `checkWindowMs`(默认 7 秒);
3. 真正触发以 `再看一条再领 / 再看一条 / 再领` 按钮为准,`恭喜您` 只作为标题候选,避免和普通“恭喜已获得”奖励页容错混淆;
4. 命中后等待 `reenterWaitMs`(默认 10 秒),再确认是否重新进入主任务 4/6;
5. 若仍停留在“再看一条/再领”弹窗,会尝试点击该按钮进入下一条广告;
6. 默认 `maxRounds = 1`,避免无限循环。
相关函数:`findExtraTask2Trigger()`、`waitExtraTask2TriggerWindow()`、`waitForAdActionOrThirdParty()`、`checkAndRunExtraTask2()`、`runMainTaskTail()`。
脚本优先使用 Google ML Kit 中文插件。该插件通过 AutoJS6 共享接口暴露为 `ocr.detect()`,不会创建 `gmlkit` 全局对象;日志会显示 `Google ML Kit 中文插件(AutoJS6 共享接口 ocr.detect)`。脚本同时兼容 `gmlkit.ocr(image, "zh")`、`paddle.ocr(image)`、`ocr.recognize()`、`mlkit.ocr()`、`$ocr.recognize()` 和函数式 `ocr(image)`。
## 使用方式
1. 将 `autojs6/home_yibao/` 整个目录复制到 AutoJS 6 的脚本目录。
2. 在云手机中允许 AutoJS 6 的截图/录屏权限,并安装或启用 OCR 插件。
3. 用 AutoJS 6 打开 `ad_view_2.js`,点击运行。
### 惊喜任务脚本 `ad_view_3.js`
在 AutoJS 6 中单独打开 `ad_view_3.js` 运行即可,不需要先运行其他脚本。项目默认入口仍为 `ad_view_2.js`,不影响原有任务。
新脚本返回桌面、启动应用宝并进入赚钱任务中心,定位 **“惊喜任务赚积分 兑豪礼”** 后,按屏幕从上到下处理已启用的任务。当前配置启用 **“去下载”“去浏览”和“领积分”**,由 `ad_view_3.js` 顶部的 `CONFIG.adView3.enabledTaskTexts` 控制:
```javascript
// 当前配置:执行“去下载”“去浏览”和“领积分”
enabledTaskTexts: ["去下载", "去浏览", "领积分"],
// 若只执行“去下载”,改为:
// enabledTaskTexts: ["去下载"],
// 恢复全部任务时改为:
// enabledTaskTexts: ["去观看", "去浏览", "去下载", "领积分"],
// 也可以只开启多种指定任务:
// enabledTaskTexts: ["去下载", "去浏览"],
```
不要删改 `actionTexts`:它保留全部按钮类型,以便在只剩禁用任务的页面仍能识别列表。开关仅控制**列表任务入口**;“去下载”内部的安装后返回、“去浏览”弹窗及浏览步骤仍会执行,即使列表“去浏览”类型被禁用。
各类任务启用后的处理方式如下:
| 列表按钮 | 处理流程 |
| --- | --- |
| 去观看 | 沿用 `ad_view_2.js` 的广告观看、关闭、领奖及额外任务流程。 |
| 去下载 | 独立流程,不套用 `ad_view_2.js`:下载 → 下一步/安装/完成 → 回应用宝并多次返回到“去浏览”弹窗 → 点击去浏览 → 停留20秒 → 返回应用宝。 |
| 去浏览 | 在弹窗内点“去浏览”(不再强制要求先识别到“任务未完成 / 打开APP再浏览”标题),确认进入第三方应用,停留 **20 秒**后返回应用宝。 |
| 领积分 | 执行随后出现的额外任务 #1(下载并打开浏览)。 |
| 已领取 | 视为该任务已完成,不再点击。 |
每次任务结束都会重新识别列表,不复用旧坐标,也不以子流程执行结束代替“已领取”状态。四类按钮采用精确匹配,避免单字容错混淆“去观看 / 去浏览 / 去下载”。启动定位前会向上回查,防止上次停在列表底部而漏掉前面的任务。
总体终止条件:**有效滚动后**,同一帧稳定 OCR 同时确认页面出现 **“任务中心问题反馈”**,且 **没有当前启用的可执行任务**,就结束任务。无需连续多次滚动或 OCR 结果不变,也不要求全部显示“已领取”。被 `enabledTaskTexts` 禁用的类型不算可执行任务;边缘被截断的启用按钮仍按待执行处理,避免提前终止。反馈入口支持同一行拆框识别,仅有反馈入口、没有任务按钮时也可以结束。
即使出现反馈入口,只要仍有可执行任务就继续处理;同一任务反复执行仍未完成时按重试上限报错,不能假装总体终止。任务执行完会重新识别、滚动,再检查终止条件。OCR 不变仅用于防空转:连续 **6 次有效滚动**均无变化且仍不满足终止条件时,停止扫描并截图报错。OCR 结果有变化或滚动未被系统接受都会重置停滞计数;截图失败、空白页和达到总扫描上限都不会作为正常结束。失败截图前缀为 `/sdcard/Download/home_yibao_ad_view_3_`。
#### 下载详情页与 PackageInstaller
“去下载”可能直接进入应用宝普通详情页(例如 QQ 音乐、淘宝),并自动开始下载。此页面使用“软件介绍 / 评分 / 包体大小”等标签,底部仅显示 `37.4%`、`78.7%` 这类进度,不会出现广告详情页的“应用名称 / 权限详情 / 隐私协议”。脚本单独识别此路径:
- 识别到普通详情页即进入下载等待,不再受入口识别的 20 秒超时限制;下载等待使用 `CONFIG.extraTask.downloadTimeoutMs`(默认 300000 毫秒)。
- 记录底部百分比,下载中不会点击进度按钮,防止误暂停。
- 通过前台包名确认 PackageInstaller 后,严格执行“下一步/安装 → 等待安装结束 → 点击完成 → 确认安装器退出 → 回到应用宝”。不能仅凭安装器消失或应用宝已在前台就跳过点击“完成”。
- “完成”漏识别时局部放大 OCR 查找,不使用返回键或直接拉起应用宝来替代;点击后若安装器仍未退出,会重新识别再点,最多 3 次。未点击完成或未确认退出则报错,禁止开始逐级返回。安装确认页的“下一步/安装”漏识别时才允许使用已标定坐标兜底。
- 安装失败或超时停止后续步骤。安装结束后先确认应用宝前台,再在应用宝中逐级按返回键,直到出现“任务未完成 / 打开APP再浏览 / 去浏览”弹窗;不点击普通详情页的“打开”,不套用广告页的 X 坐标。
- 出现弹窗立即停止返回,点击弹窗“去浏览”进入第三方应用,停留 20 秒后按包名拉起应用宝,并连续两次确认前台包名。第三方应用若拦截返回键,不影响按包名返回。
- 未点击“完成”前,安装器若意外退出或打开第三方应用,会报告安装步骤异常;不以自动打开代替点击“完成”。点击“完成”后若意外跳转第三方应用,则按包名返回应用宝,再逐级退到“去浏览”弹窗。
- 默认最多返回 `downloadBackMaxAttempts = 10` 次,总查找时限 `downloadBrowseDialogTimeoutMs = 120000` 毫秒。未找到弹窗会截图报错,不以“安装成功”代替任务完成。
- 脚本重启时支持从残留的普通详情页、下载进度或 PackageInstaller 继续,不必手动退回桌面清理页面。
关键步骤追加写入 `/sdcard/Download/home_yibao_ad_view_3_trace.log`,便于第三方应用刷屏导致 logcat 覆盖后继续排查。每轮输出“列表识别结果:待执行=[...],已识别但禁用=[...]”,区分 OCR 未识别和任务开关过滤。修改本地开关后必须同步到云手机 `/sdcard/脚本/ad_view_3.js`,停止旧运行再重新启动;仅覆盖文件不会改变已在运行的脚本配置。赚钱入口仅精确匹配“赚钱 / 点击赚钱”,避免误点“看短剧狂赚金币”等推广文案。
“去浏览”弹窗按钮支持同一行拆框识别及局部放大 OCR;与背景列表按钮同名时优先居中的弹窗按钮。点击后未打开第三方应用时,会重新识别当前坐标再点击,最多 3 次,失败不会进入浏览计时。相关日志包含候选数量、点击次数和未命中时的 OCR 文本,便于排查漏点。
参数位于 `CONFIG.adView3`:`enabledTaskTexts`(启用的列表任务类型,非空数组)、`browseWaitMs`(浏览时长)、`browseEntryTimeoutMs`(浏览入口识别总超时)、`browseOpenWaitMs`(每次点击后等待跳转时长)、`browseClickMaxAttempts`(浏览按钮点击上限)、`downloadBackMaxAttempts`(安装后返回次数上限)、`downloadBrowseDialogTimeoutMs`(安装后查找去浏览弹窗时限)、`bottomFeedbackText`(结束标志,默认“任务中心问题反馈”)、`rewindStableScans`(启动向上回查的稳定次数,默认 3,不参与总体终止判断)、`stalledScrollLimit`(未满足终止条件时的停滞滑动上限,默认 6)、`maxTaskAttempts`(同页同任务重试次数)、`maxRounds`(扫描上限)。脚本的截图权限、OCR 插件等要求与 `ad_view_2.js` 相同。
本地离线检查(不连接手机、不执行真实点击):
```bash
node --check home_yibao/ad_view_3.js
node --test home_yibao/tests/ad_view_3.test.js
```
如果你的应用宝包名不同,修改所运行脚本(如 `ad_view_2.js` 或 `ad_view_3.js`)顶部的:
```javascript
yibaoPackage: "com.tencent.android.qqdownloader"
```
## 可靠性策略(速度换成功率)
云手机视频流小字误读、偶发漏检和点击丢失是失败主因,脚本内置四层保障:
1. **容错匹配**:目标词除精确匹配外,还接受单字误读(等长滑窗汉明距离 <=1,如“赚钱→账钱”)和按钮边缘截断(目标缺头/缺尾一个字,如“放弃福利→放弃福”);命中时会输出 `OCR 容错命中` 日志。注意汉明容错对纯汉字目标会跳过含数字/字母的滑窗(详见上文“打开”误匹配防护),避免“11601 开发者”里的“1开”误命中“打开”这类 2 字按钮。
2. **多帧确认**:目标需连续 `reliability.confirmFrames`(默认 2)帧 OCR 命中且位置稳定(24px 桶化容差)才允许点击,过滤视频流偶发误检。
3. **点击后验证重试**:点击后等待 `verifyDelayMs`(默认 1500ms)再 OCR;目标仍在原位则判定未生效并重试,最多 `clickVerifyRetries`(默认 3)次。
4. **整体重试**:流程失败时保存现场截图到 `/sdcard/Download/home_yibao_*.png`,返回桌面后重跑整个流程(`flowMaxAttempts`,默认 2 次)。
各阶段等待/扫描超时均已放宽(如广告按钮等待 30 秒、滚动扫描 30 轮);确认帧间隔 `frameIntervalMs` 默认 800ms,脚本整体会比旧版慢,这是有意为之。
**执行追踪**:主任务各阶段有“阶段切换”日志;额外任务 8 步每步进入时都会输出“步骤标记: 额外任务 n/8 …”日志(`setStep`)。失败时当前步骤会随异常日志(`step=`)与失败现场截图文件名一起带出——logcat 缓冲溢出丢行或脚本中断后,也能判断执行到了哪一步。
## 已知问题(本云手机 ROM)
- **不要在脚本里调用 AutoJS6 内置的 `currentPackage()` / `currentActivity()`**:它们内部自起子进程读 stdout,在本云手机上输出管道不关闭,`readLine()` 会永久阻塞脚本线程(症状:日志停在“返回 Android 桌面”后无任何输出)。前台应用检测改用无障碍服务的活动窗口缓存 `auto.rootInActiveWindow.getPackageName()`(纯 Java API,不走 shell,毫秒级返回;实测应用宝/桌面包名均准确)。
- **AutoJS6 Rhino 引擎:循环体内声明的 `const` 从第二次迭代起赋值静默失效**(`let`/`var` 正常)。例如 `for (...) { const v = "v" + k; }` 中 `v` 恒为首次的值,不报错、难察觉。这曾导致所有 OCR 匹配逻辑只比较第一条文本(长期“识别率低”的真正原因)。**本脚本已全部改用 `var`,后续新增代码禁止在循环体内用 `const`。**
- **画面完全静止时 `captureScreen()` 会抛出 "Failed to capture screen image"**:云手机视频流不产生新帧时,AutoJS6 的 ImageReader 等满内部超时(约 10 秒)后抛错。脚本内置 `captureCurrentScreen()` 重试(3 次),失败间隙用一次 1px 拖动(`forceScreenRefresh()`)强制刷新画面;OCR 循环单帧采样失败会跳过该帧而不是中止流程。
- `dumpsys window` 的 `mCurrentFocus`/`mFocusedApp` 均为 null,解析会失败;脚本已回退到 `dumpsys activity activities` 的 `mResumedActivity`。且探针实测:`mus` 从 AutoJS app 进程调用会永久挂死(仅 adb shell 域可用,app 域被阻塞而非报错),裸 `dumpsys` 是 Permission Denial——因此 `foregroundDumpEnabled` 默认 false,dumpsys 路径仅作无障碍不可用设备的回退。
排查方法:`adb shell "mus -c 'kill -3 <autojs_pid>'"` 触发线程转储,再用 `mus -c 'cat /data/anr/trace_01'` 拉取分析卡住的线程栈;AutoJS6 进程的 `System.err` 堆栈(如 `Failed to capture screen image`)可在 logcat 中按 pid 过滤获取。
## 与桌面版的区别
这个脚本必须在云手机 Android 内运行。桌面版 Qt 浏览器中看到的是云手机的视频流,桌面端无法直接读取云手机内部的 Android 无障碍控件树;因此 AutoJS 6 脚本应部署到每个实际的云手机实例中。
脚本日志会输出当前识别阶段、可用 OCR 接口和异常堆栈。如果仍失败,请把包含 `OCR 开始,接口=` 或 `脚本失败 phase=` 的日志发回来。

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
// 只截图并比较 OCR 返回值,不点击、不滑动、不启动业务流程。
function report(message) {
console.log("[ocr_probe] " + message);
}
function inspect(name, value) {
report(name + " type=" + typeof value + " array=" + Array.isArray(value));
try { report(name + " value=" + String(value).slice(0, 1600)); } catch (e) {}
try { report(name + " keys=" + Object.keys(value).slice(0, 30).join(",")); } catch (e) {}
try {
if (value && value.length > 0) {
var first = value[0];
report(name + " count=" + value.length + " firstType=" + typeof first);
report(name + " first=" + String(first));
report(name + " text=" + String(first.text) + " label=" + String(first.label) +
" bounds=" + String(first.bounds) + " confidence=" + String(first.confidence));
}
} catch (e) { report(name + " inspect error=" + e); }
}
try {
report("start (no clicks)");
if (!requestScreenCapture(false)) { throw new Error("截图权限未允许"); }
sleep(1500);
var frame = captureScreen();
report("image=" + frame.getWidth() + "x" + frame.getHeight());
inspect("recognizeText", ocr.recognizeText(frame));
inspect("detect", ocr.detect(frame));
report("done");
} catch (error) {
report("failed=" + String(error.stack || error));
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 739 KiB

View File

@ -0,0 +1,6 @@
{
"name": "home_yibao",
"main": "ad_view_2.js",
"versionName": "1.0.0",
"versionCode": 1
}

View File

@ -0,0 +1,735 @@
// Node 离线测试:只加载函数,屏蔽 AutoJS 入口,不申请权限/点击真实设备。
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '..', 'ad_view_3.js'), 'utf8');
function load(useDefaultTasks = false) {
const context = vm.createContext({
auto: { waitFor() {} }, device: { width: 720, height: 1280 },
console: { log() {} }, sleep() {},
});
const entry = source.lastIndexOf('\ntry {\n // 截图权限只申请一次');
assert.ok(entry > 0, '应找到独立 AutoJS 入口');
vm.runInContext(source.slice(0, entry), context);
// 显式设置测试开关,避免用户日常调整 enabledTaskTexts 时影响流程测试。
context.CONFIG.adView3.enabledTaskTexts = useDefaultTasks ? ['去下载'] : context.CONFIG.adView3.actionTexts.slice();
context.failWithCapture = message => { throw new Error(message); };
return context;
}
function item(text, x = 600, y = 600) {
return { text, centerX: x, centerY: y, bounds: {
left: x - 35, top: y - 15, right: x + 35, bottom: y + 15,
} };
}
function claimedPage(c, title = '任务甲', y = 600) {
return c.makeAdView3Snapshot([item(title, 220, y), item('已领取', 600, y), item('任务中心问题反馈', 360, 1130)]);
}
test('只启用去下载时,其他按钮仍识别为列表但不会执行', () => {
const c = load(true);
assert.deepEqual(Array.from(c.enabledAdView3Tasks()), ['去下载']);
const page = c.makeAdView3Snapshot([
item('去观看', 600, 400), item('去浏览', 600, 500),
item('去下载', 600, 600), item('领积分', 600, 700),
]);
assert.deepEqual(Array.from(page.actions, action => action.target), ['去下载']);
assert.equal(page.ignored.length, 3);
assert.equal(page.noPendingEnabled, false);
});
test('只下载模式仍查找下载任务,不点击禁用类型;滚动后反馈入口且无可执行任务即结束', () => {
const c = load(true);
const skipped = () => c.makeAdView3Snapshot([
item('去观看', 600, 400), item('领积分', 600, 700), item('任务中心问题反馈', 360, 1130),
]);
const pages = [skipped(), c.makeAdView3Snapshot([item('去下载')]), skipped(), skipped()];
const calls = [];
c.scanAdView3Page = () => pages.shift();
c.clickOcrMatch = match => calls.push(match.target);
c.runAdView3DownloadTask = () => calls.push('download');
c.runMainTaskTail = c.runAdView3BrowseTask = () => assert.fail('不应该执行禁用任务');
c.restoreAdView3List = () => {};
c.scrollPageUp = () => true;
c.runAdView3Tasks();
assert.deepEqual(calls, ['去下载', 'download']);
assert.equal(pages.length, 0);
assert.equal(skipped().allClaimed, false, '忽略任务不能冒充已领取');
assert.equal(skipped().noPendingEnabled, true);
});
test('列表日志明确区分已识别但禁用的去浏览,不误报为未识别', () => {
const c = load(true);
const logs = [];
c.log = message => logs.push(message);
c.scanAdView3Page = () => c.makeAdView3Snapshot([
item('去浏览', 600, 400), item('已领取', 600, 600), item('任务中心问题反馈', 360, 1130),
]);
c.scrollPageUp = () => true;
c.clickOcrMatch = () => assert.fail('禁用的去浏览不能点击');
c.runAdView3Tasks();
assert.ok(logs.some(message => message.includes('待执行=[],已识别但禁用=[去浏览]')));
});
test('同时启用下载和浏览时,识别到列表去浏览就进入浏览子流程', () => {
const c = load(true);
c.CONFIG.adView3.enabledTaskTexts = ['去下载', '去浏览'];
let browsed = false;
c.scanAdView3Page = () => browsed ? claimedPage(c) : c.makeAdView3Snapshot([item('去浏览', 600, 600)]);
c.clickOcrMatch = match => assert.equal(match.target, '去浏览');
c.runAdView3BrowseTask = () => { browsed = true; };
c.restoreAdView3List = () => {};
c.scrollPageUp = () => true;
c.runAdView3Tasks();
assert.ok(browsed);
});
test('任务开关可恢复全开、选择多类,并拒绝空数组和未知类型', () => {
const c = load();
const items = [item('去观看', 600, 400), item('去下载', 600, 600), item('去浏览', 600, 800)];
assert.equal(c.makeAdView3Snapshot(items).actions.length, 3);
c.CONFIG.adView3.enabledTaskTexts = ['去下载', '去浏览'];
assert.deepEqual(Array.from(c.makeAdView3Snapshot(items).actions, action => action.target), ['去下载', '去浏览']);
c.CONFIG.adView3.enabledTaskTexts = [];
assert.throws(() => c.enabledAdView3Tasks(), /非空/);
c.CONFIG.adView3.enabledTaskTexts = ['去下栽'];
assert.throws(() => c.enabledAdView3Tasks(), /未知任务/);
});
test('只下载模式下,未知待办、边缘下载按钮和空白页仍不能判为完成', () => {
const c = load(true);
assert.equal(c.makeAdView3Snapshot([item('领积分'), item('去完成', 600, 800)]).noPendingEnabled, false);
assert.equal(c.makeAdView3Snapshot([item('已领取'), item('去下载', 600, 1205)]).noPendingEnabled, false);
assert.equal(c.makeAdView3Snapshot([]).noPendingEnabled, false);
});
test('标题支持空格、兑好礼和同一行拆框,但不匹配其他专区', () => {
const c = load();
assert.ok(c.findAdView3Section([item('惊喜任务赚积分 兑豪礼', 300, 300)]));
assert.ok(c.findAdView3Section([
item('惊喜任务', 130, 300), item('赚积分', 300, 300), item('兑好礼', 480, 300),
]));
assert.equal(c.findAdView3Section([item('看视频赚积分 兑豪礼')]), null);
});
test('四类按钮精确区分,忽略说明、上方其他专区以及已领取按钮', () => {
const c = load();
const items = [
item('去观看', 600, 180), item('惊喜任务赚积分 兑豪礼', 300, 300),
item('去观看', 600, 400), item('去浏览', 600, 500),
item('去下载', 600, 600), item('领积分', 600, 700),
item('已领取', 600, 800), item('点击去下载赚积分', 250, 900),
item('去完成', 600, 1000),
];
const page = c.makeAdView3Snapshot(items);
assert.deepEqual(Array.from(page.actions, action => action.target), ['去观看', '去浏览', '去下载', '领积分']);
assert.equal(page.claimed.length, 1);
assert.equal(page.allClaimed, false);
});
test('空白、去浏览弹窗、未知按钮和边缘未完成任务都不能判为全部领取', () => {
const c = load();
assert.equal(c.makeAdView3Snapshot([]).allClaimed, false);
assert.equal(c.isAdView3List([item('任务未完成'), item('打开APP再浏览'), item('去浏览')]), false);
assert.equal(c.isAdView3List([item('去浏览'), item('应用名称'), item('隐私协议')]), false);
assert.equal(c.makeAdView3Snapshot([item('已领取'), item('去完成', 600, 800)]).allClaimed, false);
assert.equal(c.makeAdView3Snapshot([item('已领取'), item('去观看', 600, 1205)]).allClaimed, false);
assert.equal(claimedPage(c).allClaimed, true);
});
test('页面比较容忍少量 OCR 抖动,但区分相同状态、不同任务或位置', () => {
const c = load();
assert.ok(c.sameAdView3Page(claimedPage(c), claimedPage(c, '任务甲', 605)));
assert.equal(c.sameAdView3Page(claimedPage(c), claimedPage(c, '任务乙')), false);
assert.equal(c.sameAdView3Page(claimedPage(c), claimedPage(c, '任务甲', 650)), false);
});
test('滚动后反馈入口且没有可执行任务即总体终止,不要求多次滚动或OCR不变', () => {
const c = load();
const pages = [claimedPage(c, '上页任务'), claimedPage(c, '滚动后的不同任务')];
let scrolls = 0;
c.scanAdView3Page = () => pages.shift();
c.scrollPageUp = () => { scrolls++; return true; };
c.runAdView3Tasks();
assert.equal(scrolls, 1);
assert.equal(pages.length, 0);
});
test('反馈入口支持同一行拆框、空格和靠近底部位置,无按钮也能识别为列表', () => {
const c = load();
const items = [item('问题反馈', 430, 1235), item('任务中心', 290, 1235)];
assert.equal(c.hasAdView3BottomFeedback(items), true);
assert.equal(c.isAdView3List(items), true);
assert.equal(c.makeAdView3Snapshot(items).hasBottomFeedback, true);
assert.equal(c.hasAdView3BottomFeedback([item('任务中心 问题反馈', 360, 1235)]), true);
assert.equal(c.hasAdView3BottomFeedback([item('任务中心', 290, 300), item('问题反馈', 430, 1000)]), false);
});
test('仅有反馈文字也能在一次有效滑动后结束,无需已领取状态', () => {
const c = load();
let scrolls = 0;
c.scanAdView3Page = () => c.makeAdView3Snapshot([item('任务中心问题反馈', 360, 1235)]);
c.scrollPageUp = () => { scrolls++; return true; };
c.runAdView3Tasks();
assert.equal(scrolls, 1);
});
test('底部仅有非支持的按钮,不视为当前可执行任务', () => {
const c = load();
c.scanAdView3Page = () => c.makeAdView3Snapshot([item('去安装', 600, 600), item('任务中心问题反馈', 360, 1130)]);
c.scrollPageUp = () => true;
c.runAdView3Tasks();
});
test('底部仍有启用的可执行任务时不得总体终止,持续未完成应有限重试报错', () => {
const c = load();
let clicks = 0;
c.scanAdView3Page = () => c.makeAdView3Snapshot([item('去浏览'), item('任务中心问题反馈', 360, 1130)]);
c.clickOcrMatch = () => { clicks++; };
c.runAdView3BrowseTask = c.restoreAdView3List = () => {};
c.scrollPageUp = () => true;
assert.throws(() => c.runAdView3Tasks(), /反复执行仍未变为已领取/);
assert.equal(clicks, c.CONFIG.adView3.maxTaskAttempts);
});
test('OCR一直不变但没有反馈文字时停止重复扫描并报错,不误报正常结束', () => {
const c = load();
let scrolls = 0;
c.scanAdView3Page = () => c.makeAdView3Snapshot([item('已领取')]);
c.scrollPageUp = () => { scrolls++; return true; };
assert.throws(() => c.runAdView3Tasks(), /仍未满足.*总体终止条件/);
assert.equal(scrolls, c.CONFIG.adView3.stalledScrollLimit);
});
test('滚动后出现反馈入口但仍有任务时先执行,完成后重新滚动识别再总体终止', () => {
const c = load();
const pages = [
c.makeAdView3Snapshot([item('已领取')]),
c.makeAdView3Snapshot([item('去浏览'), item('任务中心问题反馈', 360, 1130)]),
claimedPage(c), claimedPage(c),
];
let scrolls = 0;
let browsed = 0;
c.scanAdView3Page = () => pages.shift();
c.clickOcrMatch = () => {};
c.runAdView3BrowseTask = () => { browsed++; };
c.restoreAdView3List = () => {};
c.scrollPageUp = () => { scrolls++; return true; };
c.runAdView3Tasks();
assert.equal(browsed, 1);
assert.equal(scrolls, 2);
assert.equal(pages.length, 0);
});
test('反馈入口旁仍有边缘截断的启用按钮时,不将其当作无可执行任务', () => {
const c = load(true);
const items = [item('去下载', 600, 1205), item('任务中心问题反馈', 360, 1130)];
const page = c.makeAdView3Snapshot(items);
assert.equal(page.actions.length, 0);
assert.equal(page.hasExecutableTasks, true);
c.CONFIG.adView3.maxRounds = 3;
c.scanAdView3Page = () => page;
c.scrollPageUp = () => true;
assert.throws(() => c.runAdView3Tasks(), /尚未确认/);
});
test('滚动未被系统接受不能计入完成次数', () => {
const c = load();
c.CONFIG.adView3.maxRounds = 5;
c.scanAdView3Page = () => claimedPage(c);
c.scrollPageUp = () => false;
assert.throws(() => c.runAdView3Tasks(), /尚未确认/);
});
test('OCR 失败不算完成', () => {
const c = load();
c.scanAdView3Page = () => null;
assert.throws(() => c.runAdView3Tasks(), /OCR 无法稳定确认/);
});
test('执行四类任务后重新识别列表,直到全部领取并到达底部', () => {
const c = load();
const calls = [];
const pages = ['去观看', '去浏览', '去下载', '领积分'].map(text =>
c.makeAdView3Snapshot([item(text)]));
pages.push(claimedPage(c), claimedPage(c));
c.scanAdView3Page = () => pages.shift();
c.clickOcrMatch = match => calls.push(match.target);
c.runMainTaskTail = () => calls.push('watch');
c.runAdView3BrowseTask = () => calls.push('browse');
c.runAdView3DownloadTask = () => calls.push('download/extra1');
c.restoreAdView3List = () => calls.push('restore');
c.scrollPageUp = () => true;
c.runAdView3Tasks();
assert.deepEqual(calls, [
'去观看', 'watch', 'restore', '去浏览', 'browse', 'restore',
'去下载', 'download/extra1', 'restore', '领积分', 'download/extra1', 'restore',
]);
});
test('同一任务持续不变会有限重试并报错,不假装成功', () => {
const c = load();
c.scanAdView3Page = () => c.makeAdView3Snapshot([item('去观看')]);
c.clickOcrMatch = c.runMainTaskTail = c.restoreAdView3List = () => {};
assert.throws(() => c.runAdView3Tasks(), /反复执行仍未变为已领取/);
});
test('去浏览:点弹窗按钮,确认第三方应用,停留 20 秒并返回应用宝', () => {
const c = load();
const sleeps = [];
const clicked = [];
let returned = false;
c.sleep = ms => sleeps.push(ms);
c.getForegroundApp = () => ({ packageName: c.CONFIG.yibaoPackage });
c.recognizeScreenSafe = () => [item('任务未完成'), item('打开APP再浏览'), item('去浏览')];
c.clickOcrMatch = match => clicked.push(match.target);
c.waitThirdPartyForeground = () => ({ packageName: 'third.party' });
c.backToYibao = () => { returned = true; return true; };
c.runAdView3BrowseTask();
assert.deepEqual(clicked, ['去浏览']);
assert.ok(sleeps.includes(20000));
assert.ok(returned);
});
function browseContext() {
const c = load();
let now = 0;
const sleeps = [];
const clicks = [];
c.Date = { now: () => now };
c.sleep = ms => { now += ms; sleeps.push(ms); };
c.getForegroundApp = () => ({ packageName: c.CONFIG.yibaoPackage });
c.clickOcrMatch = match => clicks.push({ x: match.item.centerX, y: match.item.centerY, target: match.target });
c.recognizeAdButtonRegion = () => [];
c.waitThirdPartyForeground = () => clicks.length > 0 ? { packageName: 'third.party' } : null;
c.backToYibao = () => true;
return { c, sleeps, clicks };
}
test('去浏览:标题漏识别、APP 文案变化和底部按钮均不阻止点击', () => {
for (const items of [
[item('去浏览')],
[item('打开APP浏览'), item('去浏览')],
[item('任务未完戌'), item('打开应用再浏览'), item('去浏览')],
[item('去浏览', 360, 1230)],
[item('去瀏覽')],
]) {
const { c, sleeps, clicks } = browseContext();
c.recognizeScreenSafe = () => items;
c.runAdView3BrowseTask();
assert.equal(clicks.length, 1);
assert.equal(clicks[0].target, '去浏览');
assert.ok(sleeps.includes(20000));
}
});
test('去浏览:同屏多个同名按钮优先点居中的弹窗按钮,而非背景列表', () => {
const { c, clicks } = browseContext();
c.recognizeScreenSafe = () => [item('去浏览', 600, 400), item('去浏览', 360, 800)];
c.runAdView3BrowseTask();
assert.deepEqual(clicks, [{ target: '去浏览', x: 360, y: 800 }]);
});
test('去浏览:支持同一行紧邻的“去”与“浏览”拆框,不拼接远处说明', () => {
const { c, clicks } = browseContext();
c.recognizeScreenSafe = () => [item('去', 320, 800), item('浏览', 390, 800)];
c.runAdView3BrowseTask();
assert.equal(clicks.length, 1);
assert.equal(clicks[0].x, 355);
assert.equal(c.findAdView3BrowseButtons([item('去', 130, 500), item('浏览', 600, 800)]).length, 0);
assert.equal(c.findAdView3BrowseButtons([item('去观看'), item('点击去浏览赚积分')]).length, 0);
});
test('去浏览:全屏识别不到按钮时使用弹窗局部放大 OCR', () => {
const { c, clicks } = browseContext();
const crops = [];
c.recognizeScreenSafe = () => [item('任务未完成')];
c.recognizeAdButtonRegion = (targets, crop) => {
crops.push(crop);
return [item('去浏览', 360, 800)];
};
c.runAdView3BrowseTask();
assert.equal(clicks.length, 1);
assert.ok(crops.length >= 2);
assert.equal(crops[0].y, 0.18);
});
test('去浏览:首次点击无效会重新识别坐标再点击,而非直接退出', () => {
const { c, clicks } = browseContext();
c.recognizeScreenSafe = () => [item('去浏览', 360, clicks.length > 0 ? 820 : 800)];
c.waitThirdPartyForeground = () => clicks.length >= 2 ? { packageName: 'third.party' } : null;
c.runAdView3BrowseTask();
assert.deepEqual(clicks.map(click => click.y), [800, 820]);
});
test('去浏览:无法打开第三方应用时只有限重试,不开始 20 秒计时', () => {
const { c, sleeps, clicks } = browseContext();
c.recognizeScreenSafe = () => [item('去浏览')];
c.waitThirdPartyForeground = () => null;
assert.throws(() => c.runAdView3BrowseTask(), /已点击 3 次/);
assert.equal(clicks.length, 3);
assert.equal(sleeps.includes(20000), false);
});
test('去浏览:截图失败和找不到按钮时记录失败,绝不盲点坐标', () => {
for (const items of [null, [item('打开APP浏览')]]) {
const { c, clicks } = browseContext();
c.recognizeScreenSafe = () => items;
c.waitThirdPartyForeground = () => null;
assert.throws(() => c.runAdView3BrowseTask(), /已点击 0 次/);
assert.equal(clicks.length, 0);
}
});
function downloadContext() {
const { c, sleeps, clicks } = browseContext();
c.waitThirdPartyForeground = () => null;
c.recognizeScreenSafe = () => [];
return { c, sleeps, clicks };
}
function nativeDetail(progress = '78.7%') {
return [item('详情 评价', 180, 105), item('软件介绍', 130, 600),
item('评分', 65, 500), item('包体大小', 320, 500), item(progress, 360, 1200)];
}
test('日志回归:QQ音乐37.4%和淘宝78.7%普通详情页不是广告详情页,但应识别下载落点', () => {
for (const progress of ['37.4%', '78.7%']) {
const { c } = downloadContext();
c.recognizeScreenSafe = () => nativeDetail(progress);
assert.equal(c.adView3NativeDetailSeen(nativeDetail(progress)), true);
assert.equal(c.adView3DetailSeen(nativeDetail(progress)), false);
assert.equal(c.waitAdView3DownloadDestination(), 'native_detail');
}
});
test('普通详情页下载超过20秒后才进入安装器仍继续等待,绝不点击百分比暂停下载', () => {
const { c, sleeps, clicks } = downloadContext();
let installing = false;
let finished = false;
let installerCalls = 0;
let browseCalls = 0;
c.getForegroundApp = () => ({ packageName: installing ? c.CONFIG.extraTask.installerPackage : c.CONFIG.yibaoPackage });
c.recognizeScreenSafe = () => finished ? [item('任务未完成'), item('去浏览', 360, 800)] : nativeDetail();
c.runAdView3BrowseTask = () => { browseCalls++; };
let now = 0;
c.Date = { now: () => now };
c.sleep = ms => {
sleeps.push(ms);
now += ms;
if (now > 25000 && !finished) installing = true;
};
c.waitAdView3InstallerAndFinish = () => {
installerCalls++;
finished = true;
installing = false;
return true;
};
c.runAdView3NativeDownloadTask();
assert.equal(installerCalls, 1);
assert.equal(browseCalls, 1);
assert.equal(clicks.length, 0);
assert.ok(sleeps.reduce((sum, value) => sum + value, 0) > 20000);
});
test('安装器:下一步、安装、安装中、完成逐步执行,不能只点一次就空等', () => {
const { c, clicks } = downloadContext();
let stage = 0;
let installingFrames = 0;
let returned = false;
c.getForegroundApp = () => ({ packageName: stage >= 4 ? c.CONFIG.yibaoPackage : c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => {
if (stage === 2 && ++installingFrames > 1) stage = 3;
return [
[item('软件安装'), item('下一步', 520, 1193)],
[item('软件安装'), item('安装', 520, 1193)],
[item('正在安装')],
[item('安装完成'), item('完成', 200, 1193), item('打开', 520, 1193)],
][stage];
};
c.clickOcrMatch = match => { clicks.push(match.target); stage++; };
c.clickRatio = () => assert.fail('识别出按钮时不应使用坐标兜底');
c.backToYibao = () => { returned = true; return true; };
assert.equal(c.waitAdView3InstallerAndFinish(30000), true);
assert.deepEqual(clicks, ['下一步', '安装', '完成']);
assert.ok(returned);
});
test('安装器:下一步OCR漏识别时使用已标定坐标,安装中不再乱点', () => {
const { c } = downloadContext();
let stage = 0;
let coordinateClicks = 0;
let samples = 0;
c.getForegroundApp = () => ({ packageName: stage >= 3 ? c.CONFIG.yibaoPackage : c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => {
if (stage === 1 && ++samples > 2) stage = 2;
return stage === 0 ? [item('软件安装'), item('要安装此应用吗')] : stage === 1 ? [item('正在安装')] : [item('安装完成'), item('完成', 200, 1193)];
};
c.clickRatio = point => {
assert.equal(point, c.CONFIG.extraTask.installNextButton);
coordinateClicks++;
stage = 1;
};
c.clickOcrMatch = match => { assert.equal(match.target, '完成'); stage = 3; };
assert.equal(c.waitAdView3InstallerAndFinish(30000), true);
assert.equal(coordinateClicks, 1);
});
test('安装器:安装失败必须返回失败,不能继续点击打开', () => {
const { c, clicks } = downloadContext();
c.getForegroundApp = () => ({ packageName: c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => [item('应用未安装'), item('完成', 200, 1193)];
assert.equal(c.waitAdView3InstallerAndFinish(10000), false);
assert.equal(clicks.length, 0);
});
test('安装器:已在前台时不依赖截图即可判定下载完成和恢复入口', () => {
const { c } = downloadContext();
c.getForegroundApp = () => ({ packageName: c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => assert.fail('此路径不应先采样截图');
assert.equal(c.waitDownloadComplete(10000), true);
assert.equal(c.enterYibaoTaskCenter(), 'installer_page');
assert.equal(c.waitAdView3DownloadDestination(), 'installer');
});
test('普通详情页中断恢复,不再作为赚钱入口超时报错', () => {
const { c } = downloadContext();
c.recognizeScreenSafe = () => nativeDetail();
assert.equal(c.enterYibaoTaskCenter(), 'native_detail_page');
});
test('普通详情页下载超时或安装失败会终止,不冒充下载完成', () => {
const { c } = downloadContext();
c.CONFIG.extraTask.downloadTimeoutMs = 3000;
c.recognizeScreenSafe = () => nativeDetail();
assert.throws(() => c.runAdView3NativeDownloadTask(), /下载等待超时/);
c.getForegroundApp = () => ({ packageName: c.CONFIG.extraTask.installerPackage });
c.waitAdView3InstallerAndFinish = () => false;
assert.throws(() => c.runAdView3NativeDownloadTask(), /安装未完成/);
});
test('普通详情页落点进入独立下载流程,不再误走广告额外任务', () => {
const { c } = downloadContext();
let called = false;
c.waitAdView3DownloadDestination = () => 'native_detail';
c.runAdView3NativeDownloadTask = () => { called = true; };
c.runExtraDownloadTask = () => assert.fail('普通详情页不应走广告页入口');
c.runAdView3DownloadTask();
assert.ok(called);
});
test('去下载:安装后连续返回详情页和搜索页,出现弹窗立即停止返回并点击去浏览', () => {
const { c, clicks } = downloadContext();
let backs = 0;
let browseCalls = 0;
c.recognizeScreenSafe = () => backs === 0 ? nativeDetail('打开') : backs === 1 ?
[item('搜索'), item('美颜相机'), item('打开', 630, 500)] :
[item('任务未完成'), item('打开APP再浏览'), item('去浏览', 360, 800)];
c.back = () => { backs++; };
c.runAdView3BrowseTask = () => { browseCalls++; };
c.returnAdView3DownloadToBrowseDialog();
assert.equal(backs, 2);
assert.equal(browseCalls, 1);
assert.equal(clicks.length, 0, '不能点击详情页或搜索结果的打开');
});
test('去下载:安装后只显示打开按钮时不打开应用,而是退回去浏览弹窗', () => {
const { c, clicks } = downloadContext();
let backs = 0;
c.recognizeScreenSafe = () => backs === 0 ? nativeDetail('打开') :
[item('任务未完成'), item('去浏览', 360, 800)];
c.back = () => { backs++; };
let browsed = false;
c.runAdView3BrowseTask = () => { browsed = true; };
c.runAdView3NativeDownloadTask();
assert.ok(browsed);
assert.equal(backs, 1);
assert.equal(clicks.length, 0);
});
test('去下载:点击完成后意外跳转第三方应用也先回应用宝,再退回弹窗', () => {
const { c } = downloadContext();
let foreground = c.CONFIG.extraTask.installerPackage;
let returned = 0;
c.getForegroundApp = () => ({ packageName: foreground });
c.waitAdView3InstallerAndFinish = () => { foreground = 'third.party'; return true; };
c.backToYibao = () => { returned++; foreground = c.CONFIG.yibaoPackage; return true; };
c.recognizeScreenSafe = () => {
assert.equal(foreground, c.CONFIG.yibaoPackage, '第三方前台时必须先回应用宝,不能盲读页面');
return [item('任务未完成'), item('去浏览', 360, 800)];
};
let browsed = false;
c.runAdView3BrowseTask = () => { browsed = true; };
c.runAdView3NativeDownloadTask();
assert.ok(returned > 0);
assert.ok(browsed);
});
test('去下载:找不到去浏览弹窗只有限返回,不把安装成功当成任务完成', () => {
const { c } = downloadContext();
let backs = 0;
c.CONFIG.adView3.downloadBackMaxAttempts = 3;
c.recognizeScreenSafe = () => nativeDetail('打开');
c.back = () => { backs++; };
assert.throws(() => c.returnAdView3DownloadToBrowseDialog(), /已返回 3 次/);
assert.equal(backs, 3);
});
test('去下载:独立处理直达安装器,不调用领积分的额外任务 #1', () => {
const { c } = downloadContext();
const calls = [];
c.waitAdView3DownloadDestination = () => 'installer';
c.waitAdView3InstallerAndFinish = () => { calls.push('install'); return true; };
c.returnAdView3DownloadToBrowseDialog = () => calls.push('back-to-browse');
c.runExtraDownloadTask = () => assert.fail('去下载不应套用额外任务 #1');
c.runAdView3DownloadTask('去下载');
assert.deepEqual(calls, ['install', 'back-to-browse']);
});
function returnContext() {
const c = load();
let now = 0;
c.Date = { now: () => now };
c.sleep = ms => { now += ms; };
return c;
}
test('返回应用宝:直接按包名拉起,连续确认前台,不在第三方应用里乱按返回', () => {
const c = returnContext();
let foreground = 'third.party';
let launches = 0;
let samples = 0;
c.getForegroundApp = () => { samples++; return { packageName: foreground }; };
c.app = { launchPackage(pkg) { launches++; foreground = pkg; return true; } };
c.back = () => assert.fail('不应该依赖第三方应用返回键');
assert.equal(c.backToYibao(10000), true);
assert.equal(launches, 1);
assert.ok(samples >= 3);
});
test('返回应用宝:首次拉起无效时先回桌面再拉起;持续无效必须报告失败', () => {
const c = returnContext();
let foreground = 'third.party';
let launches = 0;
let homes = 0;
c.getForegroundApp = () => ({ packageName: foreground });
c.app = { launchPackage(pkg) { if (++launches >= 2) foreground = pkg; return true; } };
c.home = () => { homes++; };
assert.equal(c.backToYibao(15000), true);
assert.equal(launches, 2);
assert.equal(homes, 1);
foreground = 'third.party';
c.app.launchPackage = () => false;
assert.equal(c.backToYibao(7000), false);
});
test('浏览返回:等待20秒后调用返回;计时异常时也会尝试返回', () => {
const { c, sleeps } = downloadContext();
let returns = 0;
c.backToYibao = () => { returns++; return true; };
c.browseAdView3ThirdPartyAndReturn(20000, '测试');
assert.ok(sleeps.includes(20000));
assert.equal(returns, 1);
c.sleep = () => { throw new Error('模拟计时异常'); };
assert.throws(() => c.browseAdView3ThirdPartyAndReturn(20000, '测试'), /模拟计时异常/);
assert.equal(returns, 2);
});
test('赚钱入口只允许独立赚钱/点击赚钱,不再误点看短剧狂赚金币', () => {
const c = load();
const entries = c.findAdView3TaskCenterEntries([
item('看短剧狂赚金币', 270, 337), item('赚钱任务中心'),
item('赚钱', 600, 1230), item('点击赚钱', 360, 1100),
]);
assert.deepEqual(Array.from(entries, entry => entry.item.text), ['赚钱', '点击赚钱']);
});
test('安装器未点击完成就退出到应用宝,不再当作安装步骤成功', () => {
const { c } = downloadContext();
let samples = 0;
c.getForegroundApp = () => ({ packageName: samples++ === 0 ? c.CONFIG.extraTask.installerPackage : c.CONFIG.yibaoPackage });
c.recognizeScreenSafe = () => [item('正在安装')];
c.backToYibao = () => assert.fail('未点击完成不能开始返回应用宝');
assert.equal(c.waitAdView3InstallerAndFinish(10000), false);
});
test('严格顺序:安装中等待 → 点击完成 → 确认回到应用宝 → 才开始逐级返回', () => {
const { c } = downloadContext();
const events = [];
let completedClick = false;
let samples = 0;
c.getForegroundApp = () => ({ packageName: completedClick ? c.CONFIG.yibaoPackage : c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => ++samples < 3 ? [item('正在安装')] :
[item('安装完成'), item('完成', 200, 1193), item('打开', 520, 1193)];
c.clickOcrMatch = match => {
assert.equal(match.target, '完成');
completedClick = true;
events.push('click-finish');
};
c.backToYibao = () => { assert.ok(completedClick); events.push('confirm-yibao'); return true; };
c.returnAdView3DownloadToBrowseDialog = () => events.push('back-levels');
c.runAdView3DownloadOnlyTask('installer');
assert.deepEqual(events, ['click-finish', 'confirm-yibao', 'back-levels']);
});
test('完成按钮未生效且仍在安装器时重新识别点击,不提前拉起应用宝', () => {
const { c } = downloadContext();
let clicks = 0;
c.getForegroundApp = () => ({ packageName: clicks >= 2 ? c.CONFIG.yibaoPackage : c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => [item('安装完成'), item('完成', 200, 1193)];
c.clickOcrMatch = match => { assert.equal(match.target, '完成'); clicks++; };
c.backToYibao = () => { assert.equal(clicks, 2); return true; };
assert.equal(c.waitAdView3InstallerAndFinish(10000), true);
});
test('完成按钮漏识别则局部放大后点击,绝不以返回键或打开代替', () => {
const { c } = downloadContext();
let clicked = false;
c.getForegroundApp = () => ({ packageName: clicked ? c.CONFIG.yibaoPackage : c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => [item('安装完成'), item('打开', 520, 1193)];
c.recognizeAdButtonRegion = (targets, crop) => {
assert.deepEqual(Array.from(targets), ['完成']);
assert.equal(crop.y, 0.80);
return [item('完成', 200, 1193)];
};
c.back = c.clickRatio = () => assert.fail('不能用返回键或安装坐标代替点击完成');
c.clickOcrMatch = match => { assert.equal(match.target, '完成'); clicked = true; };
assert.equal(c.waitAdView3InstallerAndFinish(10000), true);
assert.ok(clicked);
});
test('未找到完成按钮或完成点击后安装器不退出,不能开始逐级返回', () => {
for (const showFinish of [false, true]) {
const { c } = downloadContext();
c.CONFIG.extraTask.installTimeoutMs = 10000;
c.getForegroundApp = () => ({ packageName: c.CONFIG.extraTask.installerPackage });
c.recognizeScreenSafe = () => showFinish ? [item('安装完成'), item('完成', 200, 1193)] : [item('安装完成')];
c.back = c.backToYibao = c.returnAdView3DownloadToBrowseDialog = c.clickRatio = () =>
assert.fail('未完成点击/退出确认不能开始返回流程');
assert.throws(() => c.runAdView3DownloadOnlyTask('installer'), /未安装完成/);
}
});
test('去下载未确认点击完成就进入第三方应用时,不跳过安装收尾', () => {
const { c } = downloadContext();
c.returnAdView3DownloadToBrowseDialog = () => assert.fail('未确认完成不能逐级返回');
for (const destination of ['third_party', 'reopen']) {
assert.throws(() => c.runAdView3DownloadOnlyTask(destination), /尚未确认点击/);
}
c.getForegroundApp = () => ({ packageName: 'third.party' });
assert.throws(() => c.runAdView3NativeDownloadTask(), /尚未确认点击/);
});
test('下载/领积分根据落点复用额外任务 #1,失败必须向上报告', () => {
for (const destination of ['entry', 'detail', 'installer']) {
const c = load();
let resume = 'not-called';
c.waitAdView3DownloadDestination = () => destination;
c.runExtraDownloadTask = value => { resume = value; return true; };
c.runAdView3DownloadTask('领积分');
assert.equal(resume, destination === 'entry' ? undefined : destination);
c.runExtraDownloadTask = () => false;
assert.throws(() => c.runAdView3DownloadTask('领积分'), /额外任务 #1 未完成/);
}
});

View File

@ -0,0 +1,227 @@
// 离线模拟 Android PackageManager 和进程,不卸载真实应用。
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '..', 'uninstall_today_apps.js'), 'utf8');
function load(infos = []) {
const logs = [];
const calls = [];
const pm = { getInstalledPackages: () => ({
size: () => infos.length,
get: i => infos[i],
}) };
const c = vm.createContext({
console: { log: message => logs.push(message) },
context: {
getPackageName: () => 'org.autojs.autojs6',
getPackageManager: () => pm,
},
});
const entry = source.lastIndexOf('\ntry {\n main();');
assert.ok(entry > 0);
vm.runInContext(source.slice(0, entry), c);
const realRunCommand = c.runCommand;
c.runCommand = command => {
calls.push({ command, root: c.CONFIG.shellRoot });
return { code: 0, result: command === 'id' ? 'uid=0(root) gid=0(root)' : 'Success\n', error: '' };
};
return { c, logs, calls, pm, realRunCommand };
}
function info(name, time, flags = 0) {
return { packageName: name, firstInstallTime: time, applicationInfo: { flags } };
}
test('本地自然日包含零点但不包含次日零点', () => {
const { c } = load();
const now = new Date(2026, 6, 3, 15, 20);
const range = c.getDayRange(now);
assert.equal(range.start, new Date(2026, 6, 3).getTime());
assert.equal(range.end, new Date(2026, 6, 4).getTime());
assert.equal(c.isEligible(info('com.example.start', range.start), range, 'self'), true);
assert.equal(c.isEligible(info('com.example.end', range.end), range, 'self'), false);
assert.equal(c.isEligible(info('com.example.old', range.start - 1), range, 'self'), false);
});
test('过滤系统应用、自身、保留项、无效时间及非法包名,去重排序', () => {
const infos = [
info('com.example.z', 100), info('com.example.a', 100), info('com.example.z', 100),
info('com.example.system', 100, 1), info('com.example.updatedsystem', 100, 128),
info('org.autojs.autojs6', 100), info('com.example.keep', 100),
info('com.example.bad;id', 100), info('com.example.nan', NaN),
{ packageName: 'com.example.noinfo', firstInstallTime: 100 },
];
const { c, pm } = load(infos);
c.CONFIG.keepPackages = ['com.example.keep'];
assert.deepEqual(Array.from(c.collectPackages(pm, { start: 100, end: 200 }, 'org.autojs.autojs6')),
['com.example.a', 'com.example.z']);
});
test('只看 firstInstallTime,不把今天更新的旧应用算进来', () => {
const { c } = load();
const app = info('com.example.old', 10);
app.lastUpdateTime = 150;
assert.equal(c.isEligible(app, { start: 100, end: 200 }, 'self'), false);
});
test('先打印完整列表,再逐个执行 root pm uninstall', () => {
const now = Date.now();
const { c, logs, calls } = load([info('com.example.b', now), info('com.example.a', now)]);
c.runCommand = command => {
assert.ok(logs.some(line => line.includes('["com.example.a","com.example.b"]')));
calls.push({ command, root: c.CONFIG.shellRoot });
return { code: 0, result: command === 'id' ? 'uid=0(root)' : 'Success\n', error: '' };
};
c.main();
assert.deepEqual(calls, [
{ command: 'id', root: true },
{ command: 'pm uninstall com.example.a', root: true },
{ command: 'pm uninstall com.example.b', root: true },
]);
assert.ok(logs.some(line => line.includes('成功 2 个,失败/状态未知 0 个')));
assert.ok(logs.some(line => line.includes('/system/xbin/mus -c id')));
});
test('仅查看模式及空列表均不执行 shell', () => {
const { c, calls } = load([info('com.example.a', Date.now())]);
c.CONFIG.dryRun = true;
c.main();
assert.equal(calls.length, 0);
const empty = load();
empty.c.main();
assert.equal(empty.calls.length, 0);
});
test('pm 返回失败、异常或没有 Success 时继续下一包,并汇总失败', () => {
const now = Date.now();
const { c, calls, logs } = load(['a', 'b', 'c', 'd'].map(n => info('com.example.' + n, now)));
c.runCommand = command => {
if (command === 'id') return { code: 0, result: 'uid=0(root)' };
calls.push(command);
if (command.endsWith('.a')) return { code: 0, result: 'Failure [DELETE_FAILED_INTERNAL_ERROR]' };
if (command.endsWith('.b')) throw new Error('Root denied');
if (command.endsWith('.c')) return { code: 1, result: 'Success' };
return { code: 0, result: 'Success' };
};
c.main();
assert.equal(calls.length, 4);
assert.ok(logs.some(line => line.includes('成功 1 个,失败/状态未知 3 个')));
assert.ok(logs.some(line => line.includes('失败/状态未知包名列表:["com.example.a","com.example.b","com.example.c"]')));
});
test('包名命令注入被拒绝;无法识别自身时不开始卸载', () => {
const { c, calls } = load([info('com.example.a', Date.now())]);
assert.throws(() => c.uninstallPackage('com.example.a; reboot'), /非法包名/);
c.context.getPackageName = () => '';
assert.throws(() => c.main(), /自身包名/);
assert.equal(calls.length, 0);
});
function mockProcess(env, { finishAt = 0, code = 0, output = 'Success\n', startError = null } = {}) {
const { c, realRunCommand } = env;
let clock = 0;
let destroyed = 0;
let deleted = 0;
c.runCommand = realRunCommand;
c.monotonicMillis = () => clock;
c.sleep = ms => { clock += ms; };
c.CONFIG.commandTimeoutMs = 1000;
c.CONFIG.progressIntervalMs = 400;
c.createOutputFile = () => ({
getAbsolutePath: () => '/cache/output.log',
delete: () => { deleted++; },
});
c.files = { read: () => output };
c.startCommandProcess = () => {
if (startError) throw startError;
return {
exitValue() {
if (clock < finishAt) throw new Error('IllegalThreadStateException');
return code;
},
destroy: () => { destroyed++; },
};
};
return { clock: () => clock, destroyed: () => destroyed, deleted: () => deleted };
}
test('进程未结束时轮询,退出后从文件取结果并清理,不读取输出管道', () => {
const env = load();
const state = mockProcess(env, { finishAt: 600 });
const result = env.c.runCommand('pm uninstall com.example.a');
assert.equal(result.code, 0);
assert.equal(result.result, 'Success\n');
assert.equal(state.clock(), 600);
assert.equal(state.destroyed(), 1);
assert.equal(state.deleted(), 1);
assert.ok(env.logs.some(line => line.includes('等待命令完成')));
});
test('进程永久不返回时在超时后销毁进程,携带超时标记及输出', () => {
const env = load();
const state = mockProcess(env, { finishAt: Infinity, output: 'waiting for root' });
assert.throws(() => env.c.runCommand('id'), error =>
error.commandTimedOut === true && /命令超时/.test(error.message) && /waiting for root/.test(error.message));
assert.equal(state.clock(), 1000);
assert.equal(state.destroyed(), 1);
assert.equal(state.deleted(), 1);
});
test('启动进程失败时也清理临时文件', () => {
const env = load();
const state = mockProcess(env, { startError: new Error('cannot start') });
assert.throws(() => env.c.runCommand('id'), /cannot start/);
assert.equal(state.destroyed(), 0);
assert.equal(state.deleted(), 1);
});
test('Root 检查未获授权或超时时,不执行任何卸载', () => {
const env = load([info('com.example.a', Date.now())]);
const commands = [];
env.c.runCommand = command => {
commands.push(command);
return { code: 0, result: 'uid=10123(u0_a123)' };
};
assert.throws(() => env.c.main(), /未获得 Root/);
assert.deepEqual(commands, ['id']);
mockProcess(env, { finishAt: Infinity });
assert.throws(() => env.c.main(), error => error.commandTimedOut === true);
});
test('卸载超时立即停止整批,输出尚未处理列表', () => {
const env = load(['a', 'b'].map(n => info('com.example.' + n, Date.now())));
const commands = [];
env.c.runCommand = command => {
commands.push(command);
if (command === 'id') return { code: 0, result: 'uid=0(root)' };
const error = new Error('命令超时');
error.commandTimedOut = true;
throw error;
};
env.c.main();
assert.deepEqual(commands, ['id', 'pm uninstall com.example.a']);
assert.ok(env.logs.some(line => line.includes('尚未处理包名列表:["com.example.b"]')));
assert.ok(env.logs.some(line => line.includes('上一条卸载结果未知')));
});
test('默认通过 mus 执行单条命令,外层重定向覆盖提权输出,正确引用特殊路径', () => {
const { c } = load();
let captured;
c.java = { lang: {
String,
reflect: { Array: { newInstance: () => new Array(3) } },
ProcessBuilder: function(args) {
captured = Array.from(args);
this.start = () => ({ marker: 'process' });
},
} };
assert.equal(c.startCommandProcess('pm uninstall com.example.a', "/cache/a'b.log").marker, 'process');
assert.equal(captured[0], '/system/bin/sh');
assert.equal(captured[1], '-c');
assert.equal(captured[2], "exec /system/xbin/mus -c 'pm uninstall com.example.a' > '/cache/a'\\''b.log' 2>&1");
c.CONFIG.shellRoot = false;
c.startCommandProcess('id', '/cache/test.log');
assert.equal(captured[2], "exec /system/bin/sh -c 'id' > '/cache/test.log' 2>&1");
});

View File

@ -0,0 +1,224 @@
/*
* AutoJS 6:列出今天首次安装的应用,再逐个执行 pm uninstall。
* 不需要无障碍、截图或 OCR;卸载需要 Root 权限。
* 注意:默认真实卸载并删除应用数据。只看列表时将 dryRun 改为 true。
*/
var CONFIG = {
dryRun: false,
shellRoot: true,
commandTimeoutMs: 30000,
progressIntervalMs: 5000,
// 不希望卸载的应用包名,例如 "com.tencent.android.qqdownloader"。
keepPackages: []
};
function report(message) {
console.log("[uninstall_today_apps] " + message);
}
function getDayRange(now) {
var start = new Date(now.getTime());
start.setHours(0, 0, 0, 0);
var end = new Date(start.getTime());
// 按本地自然日计算,不能简单加 24 小时(兼容夏令时)。
end.setDate(end.getDate() + 1);
return { start: start.getTime(), end: end.getTime() };
}
function isValidPackageName(name) {
return /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(name);
}
function isEligible(info, range, selfPackage) {
var name = String(info.packageName);
var installedAt = Number(info.firstInstallTime);
if (!isValidPackageName(name) || name === selfPackage ||
CONFIG.keepPackages.indexOf(name) !== -1) {
return false;
}
// FLAG_SYSTEM=1,FLAG_UPDATED_SYSTEM_APP=128;两类系统应用均不处理。
if (!info.applicationInfo || (Number(info.applicationInfo.flags) & (1 | 128)) !== 0) {
return false;
}
// 用首次安装时间,不把今天更新的老应用算作今天安装。
return installedAt >= range.start && installedAt < range.end;
}
function collectPackages(pm, range, selfPackage) {
// 不含 GET_UNINSTALLED_PACKAGES:仅扫描当前用户已安装且对 AutoJS 可见的应用。
var installed = pm.getInstalledPackages(0);
var result = [];
var seen = {};
for (var i = 0; i < installed.size(); i++) {
var info = installed.get(i);
var name = String(info.packageName);
if (isEligible(info, range, selfPackage) && !seen["$" + name]) {
seen["$" + name] = true;
result.push(name);
}
}
result.sort();
return result;
}
function quoteShell(value) {
return "'" + String(value).replace(/'/g, "'\\''") + "'";
}
function monotonicMillis() {
return Number(android.os.SystemClock.elapsedRealtime());
}
function createOutputFile() {
return java.io.File.createTempFile("uninstall_today_", ".log", context.getCacheDir());
}
function startCommandProcess(command, outputPath) {
// 不调用 AutoJS shell(),也不 readLine()/waitFor():避免 mus 或输出管道无限等待。
// 在外层 sh 重定向,连 mus 自身的授权错误也写入文件,不等待子进程关闭输出管道。
// 使用已确认的绝对路径,不依赖 AutoJS 进程的 PATH。
var executable = CONFIG.shellRoot ? "/system/xbin/mus" : "/system/bin/sh";
var script = "exec " + executable + " -c " + quoteShell(command) +
" > " + quoteShell(outputPath) + " 2>&1";
var args = java.lang.reflect.Array.newInstance(java.lang.String, 3);
args[0] = "/system/bin/sh";
args[1] = "-c";
args[2] = script;
return new java.lang.ProcessBuilder(args).start();
}
function runCommand(command) {
if (!(CONFIG.commandTimeoutMs > 0) || !(CONFIG.progressIntervalMs > 0)) {
throw new Error("命令超时和进度间隔必须大于 0");
}
var outputFile = createOutputFile();
var outputPath = String(outputFile.getAbsolutePath());
var process = null;
var started = monotonicMillis();
var nextProgress = CONFIG.progressIntervalMs;
try {
process = startCommandProcess(command, outputPath);
while (true) {
var code = null;
try {
code = Number(process.exitValue());
} catch (running) {
// Java Process.exitValue() 在进程仍运行时抛 IllegalThreadStateException。
}
if (code !== null) {
return { code: code, result: String(files.read(outputPath)), error: "" };
}
var elapsed = monotonicMillis() - started;
if (elapsed >= CONFIG.commandTimeoutMs) {
var partialOutput;
try {
partialOutput = String(files.read(outputPath)).slice(-4000);
} catch (readError) {
partialOutput = "无法读取输出:" + String(readError);
}
var timeout = new Error("命令超时(" + Math.floor(elapsed / 1000) +
" 秒):" + command + ";输出=" + partialOutput);
timeout.commandTimedOut = true;
throw timeout;
}
if (elapsed >= nextProgress) {
report("等待命令完成(" + Math.floor(elapsed / 1000) + " 秒):" + command);
nextProgress = elapsed + CONFIG.progressIntervalMs;
}
sleep(200);
}
} finally {
if (process !== null) {
try { process.destroy(); } catch (ignoreDestroy) {}
}
try { outputFile.delete(); } catch (ignoreDelete) {}
}
}
function checkCommandPermission() {
report("检查执行身份(" + (CONFIG.shellRoot ? "/system/xbin/mus -c id" : "sh -c id") +
"),最长等待 " + Math.ceil(CONFIG.commandTimeoutMs / 1000) + " 秒");
var identity = runCommand("id");
var output = String(identity.result).trim();
report("执行身份:" + output);
if (identity.code !== 0 || (CONFIG.shellRoot && !/(^|\s)uid=0\b/.test(output))) {
throw new Error("未获得 Root 执行身份,请检查 /system/xbin/mus 是否可从 AutoJS 进程使用及其 Root 权限;" +
"code=" + identity.code + " 输出=" + output);
}
}
function uninstallPackage(name) {
// 即使单独调用,也不允许未校验的包名拼进命令。
if (!isValidPackageName(name)) {
throw new Error("非法包名:" + name);
}
var command = "pm uninstall " + name;
report("执行:" + command);
var result = runCommand(command);
var stdout = result && result.result != null ? String(result.result).trim() : "";
var stderr = result && result.error != null ? String(result.error).trim() : "";
// 不能只看退出码,部分 ROM 的 pm 失败时退出码仍可能为 0。
if (!result || Number(result.code) !== 0 || !/^Success$/m.test(stdout)) {
throw new Error("code=" + (result ? result.code : "无结果") +
" stdout=" + stdout + " stderr=" + stderr);
}
}
function main() {
var selfPackage = String(context.getPackageName());
if (!isValidPackageName(selfPackage)) {
throw new Error("无法获取 AutoJS 自身包名,已停止以防误卸载");
}
var now = new Date();
var range = getDayRange(now);
var pm = context.getPackageManager();
var packages = collectPackages(pm, range, selfPackage);
report("设备本地日期:" + now.toLocaleDateString() + ";按首次安装时间筛选");
// 必须先完成扫描并输出整个列表,再开始卸载。
report("当天安装的待卸载包名列表(已过滤保护项):" + JSON.stringify(packages));
report("共 " + packages.length + " 个;已跳过系统应用、AutoJS 自身和保留名单");
if (CONFIG.dryRun) {
report("仅查看模式,不执行卸载");
return;
}
if (packages.length === 0) {
report("没有需要卸载的应用");
return;
}
// 先用无副作用的 id 检查提权,避免每个包都等待一次 mus 提权超时。
checkCommandPermission();
var succeeded = 0;
var failed = [];
var unprocessed = [];
for (var i = 0; i < packages.length; i++) {
var name = packages[i];
try {
uninstallPackage(name);
succeeded++;
report("卸载成功:" + name);
} catch (error) {
failed.push(name);
report("卸载失败:" + name + ";" + String(error));
if (error.commandTimedOut) {
// destroy() 不保证终止 mus 派生的所有子进程,不能并发继续或自动重试。
unprocessed = packages.slice(i + 1);
report("上一条卸载结果未知,已停止本批任务;请核实安装状态后再运行");
break;
}
}
}
report("处理完毕:成功 " + succeeded + " 个,失败/状态未知 " + failed.length + " 个");
if (failed.length > 0) {
report("失败/状态未知包名列表:" + JSON.stringify(failed));
}
if (unprocessed.length > 0) {
report("尚未处理包名列表:" + JSON.stringify(unprocessed));
}
}
try {
main();
} catch (error) {
report("脚本失败:" + String(error.stack || error));
throw error;
}

43
data/logs/probe_a11y.js Normal file
View File

@ -0,0 +1,43 @@
// 诊断:无障碍服务能否提供前台应用(getWindows / rootInActiveWindow 的包名)。
function dumpWindows(tag) {
try {
var svc = auto.service;
if (!svc) {
console.log("[probe_a11y] " + tag + " 无 auto.service");
return;
}
var ws = svc.getWindows();
var n = ws ? ws.size() : 0;
console.log("[probe_a11y] " + tag + " windows=" + n);
for (var i = 0; i < n && i < 12; i++) {
var w = ws.get(i);
console.log("[probe_a11y] " + tag + " win" + i +
" pkg=" + w.getPackageName() +
" active=" + w.isActive() +
" focused=" + w.isFocused() +
" layer=" + w.getLayer() +
" type=" + w.getType());
}
} catch (e) {
console.log("[probe_a11y] " + tag + " windows err=" + e);
}
try {
var root = auto.rootInActiveWindow;
console.log("[probe_a11y] " + tag + " rootInActiveWindow=" + root +
(root ? " pkg=" + root.getPackageName() + " cls=" + root.getClassName() : ""));
} catch (e) {
console.log("[probe_a11y] " + tag + " root err=" + e);
}
}
console.log("[probe_a11y] start");
dumpWindows("AutoJS前台");
try {
app.launchPackage("com.tencent.android.qqdownloader");
console.log("[probe_a11y] 已请求启动应用宝");
} catch (e) {
console.log("[probe_a11y] launch err=" + e);
}
sleep(8000);
dumpWindows("应用宝前台");
console.log("[probe_a11y] done");

59
data/logs/probe_a11y2.js Normal file
View File

@ -0,0 +1,59 @@
// 诊断第二轮:精确读取无障碍前台信息,先取关键字段再打印对象。
function reportRoot(tag) {
try {
var root = auto.rootInActiveWindow;
if (!root) {
console.log("[probe_a2] " + tag + " root=null");
return;
}
console.log("[probe_a2] " + tag + " rootPkg=" + root.getPackageName() +
" rootCls=" + root.getClassName() +
" childCount=" + root.getChildCount());
} catch (e) {
console.log("[probe_a2] " + tag + " root err=" + e);
}
}
function reportWindows(tag) {
try {
var ws = auto.service.getWindows();
var n = ws ? ws.size() : 0;
console.log("[probe_a2] " + tag + " windowCount=" + n);
for (var i = 0; i < n; i++) {
var w = ws.get(i);
var cls = w.getClass().getName();
var methodNames = [];
var methods = w.getClass().getMethods();
for (var m = 0; m < methods.length; m++) {
var name = String(methods[m].getName());
if (name.indexOf("ackage") >= 0 || name.indexOf("ctive") >= 0 || name.indexOf("ocused") >= 0) {
methodNames.push(name);
}
}
console.log("[probe_a2] " + tag + " win" + i + " cls=" + cls +
" methods=" + methodNames.join(","));
try {
console.log("[probe_a2] " + tag + " win" + i + " toString=" + String(w).substring(0, 120));
} catch (e2) {}
}
} catch (e) {
console.log("[probe_a2] " + tag + " windows err=" + e);
}
}
console.log("[probe_a2] start");
reportRoot("AutoJS前台");
reportWindows("AutoJS前台");
try {
app.launchPackage("com.tencent.android.qqdownloader");
} catch (e) {
console.log("[probe_a2] launch err=" + e);
}
sleep(8000);
reportRoot("应用宝前台");
reportWindows("应用宝前台");
home();
sleep(2000);
reportRoot("桌面");
reportWindows("桌面");
console.log("[probe_a2] done");

View File

@ -0,0 +1,127 @@
# 脚本步骤 JSON 字段手册
适用范围:`data/scripts/*.json` 脚本文件、右侧「实时调试面板」粘贴的步骤 JSON、Python `ScriptStep`。
改 JSON 存盘即生效(无需重启客户端)。
---
## 一、脚本级字段(JSON 顶层)
| 字段 | 类型 | 必填 | 含义 |
|---|---|---|---|
| `script_id` | str | 是 | 脚本唯一标识,下拉框选中后传给 `create_script()` 的值(如 `yibao_video`) |
| `label` | str | 是 | 脚本在下拉框里的显示名 |
| `target_text` | str | 否 | 实例卡片上显示的"识别目标"提示文字(纯展示) |
| `click_offset_y_ratio` | float | 否 | 本脚本 OCR 点击的全局 Y 轴比例偏移。负值 = 上移,补偿图标下方带文字说明导致 OCR 中心点偏低的场景(如云手机桌面"应用宝"图标下方有名称文字,用 `-0.06` 上移点到图标本体) |
| `steps` | array | 是 | 步骤列表,按序执行,索引从 0 开始(`loop_to` / `skip_to` 引用的就是此索引) |
---
## 二、步骤通用字段(所有 kind 可用)
| 字段 | 类型 | 默认 | 含义 |
|---|---|---|---|
| `kind` | str | 必填 | 步骤类型,见下文「步骤类型」 |
| `label` | str | 必填 | 步骤说明(日志显示;调试面板粘贴单步时可省略,自动补"调试步骤 N") |
---
## 三、目标与守卫字段(OCR 类步骤)
### 正向目标(点什么 / 等什么)
| 字段 | 类型 | 默认 | 含义 |
|---|---|---|---|
| `text` | str | `""` | OCR 查找并点击的主文本 |
| `alt_texts` | array | `[]` | 同一动作的替代文本。广告模板会换 CTA 文案(`立即体验`/`立即下载`/`了解详情`/`查看详情`),点击**第一个出现**的(`text` 优先) |
| `anchor` | str | `""` | 仅 `scroll_ocr_click`:锚行文本(如 `兑好礼`)。`text` 必须出现在**锚行右侧**才算命中,防止点中页面其他位置的同名词 |
### 正向守卫(条件类步骤的触发条件)
| 字段 | 类型 | 默认 | 含义 |
|---|---|---|---|
| `confirm` | str | `""` | 扫描等待的确认文本——**出现在屏上后**步骤才执行动作。用于"等倒计时结束/等页面就绪" |
| `alt_confirms` | array | `[]` | 确认文本的替代候选。`confirm` / `alt_confirms` **任一出现**即触发(banner 文案会换:`看15秒` ↔ `恭喜已获得`) |
### 反向守卫(拦截条件)
| 字段 | 类型 | 默认 | 含义 |
|---|---|---|---|
| `absent` | str **或** array | `""` | 拦截文本——**只要任一还在屏上**,即使 confirm 已命中也**不许触发**,继续等待;**全部消失**后才允许触发。解决"同一段文字在不同场景含义不同":视频页通知栏常驻`恭喜已获得奖励`是背景装饰,必须等`继续浏览N秒`倒计时消失后命中的才是真正的结束。数组形态等价于 `absent`(首个)+ `alt_absents`(其余),两种写法可混用合并 |
**安全边界**:反向守卫不会死循环——扫满 `max_scans` 次后放行并**跳过**该步(跳过而非终止脚本)。
---
## 四、坐标字段(比例类点击)
所有比例坐标均相对 **stream_rect**(云手机画面区域,由 DOM 自动探测),不是相对整个浏览器视图。
换算:`点击像素 = 比例 × stream_rect 宽高 + stream_rect 左上角`。
| 字段 | 类型 | 默认 | 含义 |
|---|---|---|---|
| `x_ratio` | float | `0.0` | 目标点 X 占画面宽度的比例(0~1);`gray_end` 步骤中为检测区域左上角 X |
| `y_ratio` | float | `0.0` | 目标点 Y 占画面高度的比例(0~1);`gray_end` 步骤中为检测区域左上角 Y |
| `w_ratio` | float | `1.0` | 仅 `gray_end`:检测区域宽占画面宽度比例 |
| `h_ratio` | float | `1.0` | 仅 `gray_end`:检测区域高占画面高度比例 |
| `gray_threshold` | float | `0.03` | 仅 `gray_end`:区域内“彩色像素”(HSV 饱和度≥60 且明度≥60)占比 ≤ 此值 → 判定全灰 → **以“脚本完成”结束整个流程**(任务按钮领完后变灰,全灰 = 奖励领完) |
| `offset_y_ratio` | float | `0.0` | OCR 点击的 Y 轴比例微调。负值 = 上移(补偿 OCR 文本框中心相对图标中心的偏低),可覆盖脚本级 `click_offset_y_ratio` |
**标定方法**:从 `data/logs/screenshots/instance-N-ratio-M.png`(点击时刻 raw 截图)定位图标亮块中心 → 换算 CSS 坐标 → 除以 stream_rect 尺寸得比例。
---
## 五、时序与控制字段
| 字段 | 类型 | 默认 | 含义 |
|---|---|---|---|
| `await_ms` | int | `10000` | 仅 `await_click`:confirm 出现后,等待 `text`/`alt_texts` 的最长时间(毫秒),超时放弃 |
| `delay_ms` | int | `20000` | 仅 `delay_click` / `delay_home`:动作前的固定等待毫秒数 |
| `max_scans` | int | `20` | 条件类步骤的扫描次数上限。每次扫描约 1 秒。扫满未见 confirm → 跳过该步(或走 `skip_to`),**不会终止脚本** |
| `optional` | bool | `false` | 目标模板相关:未出现时不让脚本判失败(奖励弹窗等按广告模板有无的元素) |
| `loop_to` | int | `-1` | 仅 `loop`:跳回的步骤索引(循环体起点) |
| `loop_times` | int | `1` | 仅 `loop`:循环体总执行轮数(含首轮)。跑满后继续往下走 |
| `skip_to` | int | `-1` | 仅 `cond_ocr_click`:confirm 在 `max_scans` 内始终未出现时,跳到此索引而非下一步——**整体跳过一个条件分支**(如下载分支不存在时跳过整个安装流程) |
| `pick_top` | bool | `false` | OCR 命中多个同文本时,取**最靠上**的一个而非置信度最高的(下载页上下重复出现`立即下载`按钮) |
---
## 六、步骤类型(kind)
| kind | 行为 | 常用字段 |
|---|---|---|
| `home` | 点击云手机 Home 键 | — |
| `ocr_click` | OCR 找到 `text`(或 alt_texts)并点击 | `text`, `alt_texts`, `offset_y_ratio` |
| `scroll_ocr_click` | 找 `text` 于 `anchor` 行右侧;未找到则下滑重试,直到命中或页面停止滚动 | `text`, `anchor` |
| `await_click` | `confirm` 出现后,最多等 `await_ms` 毫秒点 `text`/`alt_texts`;都未出现则放弃 | `confirm`, `text`, `alt_texts`, `await_ms` |
| `delay_click` | 固定等 `delay_ms` 毫秒后点击流内比例坐标(无 OCR 文本的图标目标) | `delay_ms`, `x_ratio`, `y_ratio` |
| `cond_ratio_click` | 扫描直到 confirm 命中(且 absent 全消失)→ 点击比例坐标;扫满跳过 | `confirm`, `alt_confirms`, `absent`, `x_ratio`, `y_ratio`, `max_scans` |
| `cond_ocr_click` | 扫描直到 confirm 命中 → 点击 `text`(首个出现的);未见则走 `skip_to` 跳过整个分支 | `confirm`, `text`, `alt_texts`, `max_scans`, `skip_to`, `pick_top` |
| `delay_home` | 固定等 `delay_ms` 毫秒后点 Home 键 | `delay_ms` |
| `gray_end` | 扫描检测区域:彩色像素占比 ≤ `gray_threshold` → 以“脚本完成”结束整个流程;不灰则跳过继续。扫满 `max_scans` 未灰也跳过继续 | `x_ratio`, `y_ratio`, `w_ratio`, `h_ratio`, `gray_threshold`, `max_scans` |
| `loop` | 跳回 `loop_to`,循环体共跑 `loop_times` 轮 | `loop_to`, `loop_times` |
**执行语义速查**:
- 正向守卫 `confirm`/`alt_confirms`:**任一出现 → 触发**
- 反向守卫 `absent`(str 或 array):**任一在屏 → 拦截;全消失 → 放行**
- `max_scans` 耗尽:跳过(cond_ocr_click 走 `skip_to`),不失败
- `optional`:目标缺失不判失败
---
## 七、调试面板用法
底部右侧输入框粘贴**单个步骤对象或步骤数组**(JSON 格式与脚本文件中的 steps 元素完全一致),点「运行调试步骤」即在所有实例上执行。`label` 可省略(自动补全)。典型用法——单独调一个坐标:
```json
{
"kind": "cond_ratio_click",
"confirm": "看15秒",
"alt_confirms": ["恭喜已获得"],
"absent": ["应用版本"],
"x_ratio": 0.924,
"y_ratio": 0.111,
"label": "点击广告页右上角关闭按钮(X)返回任务列表",
"max_scans": 8
}
```

View File

@ -0,0 +1,74 @@
{
"script_id": "home_yibao",
"label": "Home → 应用宝 → 赚钱 → 去观看 → 了解详情 → 关闭广告 → 放弃福利 → 关闭广告页",
"target_text": "应用宝",
"click_offset_y_ratio": -0.06,
"steps": [
{
"kind": "home",
"label": "点击云手机 Home 按钮"
},
{
"kind": "ocr_click",
"text": "应用宝",
"offset_y_ratio": -0.06,
"label": "打开“应用宝”"
},
{
"kind": "ocr_click",
"text": "赚钱",
"label": "点击“赚钱”"
},
{
"kind": "scroll_ocr_click",
"text": "去观看",
"anchor": "精彩视频",
"label": "查找“看精彩视频领积分”旁的“去观看”"
},
{
"kind": "await_click",
"text": "了解详情",
"alt_texts": [
"立即体验"
],
"confirm": "可获得奖励",
"label": "等待“了解详情/立即体验”出现并点击",
"await_ms": 10000,
"max_scans": 10
},
{
"kind": "delay_click",
"delay_ms": 20000,
"x_ratio": 0.158,
"y_ratio": 0.065,
"label": "等待 20 秒后点击广告页关闭按钮(X)"
},
{
"kind": "cond_ratio_click",
"confirm": "恭喜已获得",
"x_ratio": 0.935,
"y_ratio": 0.083,
"label": "等待奖励弹窗并点击右上角关闭(X/遮罩)",
"max_scans": 10
},
{
"kind": "await_click",
"text": "放弃福利",
"label": "点击“放弃福利”",
"await_ms": 8000,
"max_scans": 10,
"optional": true
},
{
"kind": "cond_ratio_click",
"confirm": "看15秒",
"alt_confirms": [
"恭喜已获得"
],
"x_ratio": 0.933,
"y_ratio": 0.108,
"label": "点击广告页/通知栏右上角关闭按钮(X)",
"max_scans": 5
}
]
}

View File

@ -0,0 +1,88 @@
{
"script_id": "yibao_video",
"label": "Home → 应用宝 → 赚钱 → 看视频赚积分 兑好礼(10 轮)",
"target_text": "应用宝",
"click_offset_y_ratio": -0.06,
"steps": [
{"kind": "home", "label": "点击云手机 Home 按钮"},
{"kind": "ocr_click", "text": "应用宝", "offset_y_ratio": -0.06, "label": "打开“应用宝”"},
{"kind": "ocr_click", "text": "赚钱", "label": "点击“赚钱”"},
{"kind": "scroll_ocr_click", "text": "全观看", "anchor": "兑好礼", "label": "查找“看视频赚积分 兑好礼”旁的“全观看”"},
{
"kind": "await_click",
"text": "立即体验",
"alt_texts": ["立即下载", "了解详情", "查看详情", "下载应用"],
"confirm": "看15秒",
"label": "等待提示语并点击“立即体验/立即下载/了解详情/查看详情/下载应用”",
"await_ms": 10000,
"max_scans": 10
},
{
"kind": "cond_ratio_click",
"confirm": "恭喜已获得",
"absent": "继续浏览",
"x_ratio": 0.172,
"y_ratio": 0.098,
"label": "等待倒计时结束后点击标题栏关闭按钮(X)",
"max_scans": 25
},
{
"kind": "cond_ratio_click",
"confirm": "应用版本",
"x_ratio": 0.067,
"y_ratio": 0.083,
"label": "若倒计时后跳到下载详情页,点击左上角关闭按钮(X)",
"max_scans": 3
},
{
"kind": "cond_ocr_click",
"text": "立即下载",
"confirm": "下载并打开浏览",
"label": "若出现“下载并打开浏览”,点击“立即下载”",
"max_scans": 4,
"skip_to": 14
},
{
"kind": "cond_ocr_click",
"text": "立即下载",
"confirm": "已下载",
"pick_top": true,
"label": "等待下载进度后点击第一个“立即下载”",
"max_scans": 15
},
{
"kind": "cond_ocr_click",
"text": "下一步",
"confirm": "软件安装",
"label": "等待“软件安装”界面并点击“下一步”",
"max_scans": 15
},
{
"kind": "cond_ocr_click",
"text": "打开",
"confirm": "打开",
"label": "回到下载界面点击“打开”",
"max_scans": 10
},
{"kind": "delay_home", "delay_ms": 20000, "label": "等待 20 秒后返回桌面"},
{"kind": "ocr_click", "text": "应用宝", "offset_y_ratio": -0.06, "label": "回到桌面后打开“应用宝”"},
{
"kind": "delay_click",
"delay_ms": 2000,
"x_ratio": 0.172,
"y_ratio": 0.098,
"label": "点击 (0.172, 0.108) 按钮返回广告页"
},
{
"kind": "cond_ratio_click",
"confirm": "看15秒",
"alt_confirms": ["恭喜已获得"],
"absent": "应用版本",
"x_ratio": 0.924,
"y_ratio": 0.111,
"label": "点击广告页右上角关闭按钮(X)返回任务列表",
"max_scans": 8
},
{"kind": "loop", "label": "循环观看下一集(共 10 轮)", "loop_to": 3, "loop_times": 10}
]
}

908
desktop_app.py Normal file
View File

@ -0,0 +1,908 @@
from __future__ import annotations
import json
import sys
from pathlib import Path
from urllib.parse import urlparse
from PySide6.QtCore import QSettings, QStandardPaths, QPoint, QPointF, QUrl, Qt, QTimer
from PySide6.QtGui import QColor, QPainter, QPen, QWheelEvent
from PySide6.QtWidgets import (
QApplication,
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QComboBox,
QPushButton,
QPlainTextEdit,
QScrollArea,
QSizePolicy,
QSpinBox,
QVBoxLayout,
QWidget,
)
from PySide6.QtTest import QTest
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile
from PySide6.QtWebEngineWidgets import QWebEngineView
from app_logging import LogEmitter, configure_ui_logging, get_instance_logger
from ocr_task import OCRService, qimage_to_bgr
from scripts import create_script, script_options
from scripts.base import BrowserScript
from scripts.loader import build_debug_script_class
APP_STYLE = """
QMainWindow, QWidget { background: #f7f8f5; color: #202826; font-family: Arial, 'PingFang SC'; }
QLineEdit, QSpinBox { background: white; border: 1px solid #dce3dd; padding: 9px 11px; min-height: 18px; }
QLineEdit:focus, QSpinBox:focus { border: 1px solid #94a83c; }
QPushButton { background: #202826; color: white; border: 0; padding: 10px 17px; font-weight: bold; }
QPushButton:hover { background: #35413c; }
QPushButton:disabled { background: #aab4ae; }
QPushButton#stop { background: #d96552; }
QPushButton#logToggle { background: #e7ebe4; color: #55605a; border: 1px solid #d3dcd2;
padding: 2px 10px; font-weight: normal; font-size: 11px; }
QPushButton#logToggle:hover { background: #d8e0d4; }
QLabel#eyebrow { color: #74807b; font-size: 10px; font-weight: bold; }
QLabel#title { font-size: 25px; font-weight: bold; }
QLabel#hint { color: #74807b; font-size: 12px; }
QFrame#instance { background: white; border: 1px solid #dce3dd; }
QLabel#instanceTitle { font-size: 13px; font-weight: bold; }
QLabel#instanceStatus { color: #74807b; font-size: 12px; }
QLabel#error { color: #d96552; }
QComboBox { background: white; border: 1px solid #dce3dd; padding: 9px 11px; min-width: 170px; }
"""
# The cloud-phone page renders its Home/Back/Recents controls in the toolbar strip
# below the video stream (420x330 view, stream bottom ~y294, Home button center ~y312).
CLOUD_PHONE_VIEW_WIDTH = 420
CLOUD_PHONE_VIEW_HEIGHT = 330
CLOUD_PHONE_HOME_Y_RATIO = 0.945
# Standard fx-cloudphone-h5 layout: the phone-stream video sits at this CSS rect.
# Fallback for ratio clicks when the live DOM probe has not answered yet.
DEFAULT_STREAM_RECT = {"x": 128, "y": 0, "width": 165, "height": 294}
def profile_root() -> Path:
root = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
candidates = []
if root:
candidates.append(Path(root) / "browser-profiles")
candidates.append(Path(__file__).resolve().parent / "data" / "browser-profiles")
for path in candidates:
try:
path.mkdir(parents=True, exist_ok=True)
return path
except OSError:
continue
raise RuntimeError("无法创建浏览器 Session 存储目录")
def valid_url(value: str) -> bool:
parsed = urlparse(value.strip())
return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
class ClickIndicator(QWidget):
"""Small blue ring flashed at a click point for visual feedback."""
def __init__(self, parent: QWidget) -> None:
super().__init__(parent)
# Let synthetic clicks pass through to the web content underneath.
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
def paintEvent(self, event) -> None: # noqa: N802 - Qt naming
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(QPen(QColor(58, 122, 254, 235), 2))
painter.setBrush(QColor(58, 122, 254, 60))
painter.drawEllipse(3, 3, self.width() - 6, self.height() - 6)
painter.setBrush(QColor(58, 122, 254, 230))
radius = max(2, self.width() // 8)
painter.drawEllipse(
self.width() // 2 - radius,
self.height() // 2 - radius,
radius * 2,
radius * 2,
)
class BrowserInstance(QFrame):
def __init__(
self,
instance_id: int,
ocr_service: OCRService,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setObjectName("instance")
self.setFixedWidth(CLOUD_PHONE_VIEW_WIDTH)
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Preferred)
self.instance_id = instance_id
self.action_text = ""
self.ocr_service = ocr_service
self.page_ready = False
self.pending_script: "str | BrowserScript | None" = None
self.active_script = None
# CSS rect of the phone-stream element (video/canvas); cached for scrolling.
self.stream_rect: dict | None = None
self.logger = get_instance_logger(instance_id)
header = QHBoxLayout()
header.setContentsMargins(14, 12, 14, 10)
title = QLabel(f"INSTANCE {instance_id:02d}")
title.setObjectName("instanceTitle")
self.status = QLabel("等待中")
self.status.setObjectName("instanceStatus")
header.addWidget(title)
header.addStretch()
header.addWidget(self.status)
self.view = QWebEngineView()
self.view.setFixedSize(CLOUD_PHONE_VIEW_WIDTH, CLOUD_PHONE_VIEW_HEIGHT)
self.view.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
# Each instance has its own persistent profile: cookies, local storage and sessions survive restarts.
self.profile = QWebEngineProfile(f"fengyun-instance-{instance_id}", self)
storage = profile_root() / f"instance-{instance_id}"
storage.mkdir(parents=True, exist_ok=True)
self.profile.setPersistentStoragePath(str(storage))
self.profile.setCachePath(str(storage / "cache"))
self.profile.setPersistentCookiesPolicy(
QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies
)
self.page = QWebEnginePage(self.profile, self.view)
self.view.setPage(self.page)
self.view.loadStarted.connect(lambda: self.set_status("加载页面"))
self.view.loadFinished.connect(self._loaded)
self.page.titleChanged.connect(self._title_changed)
self.message = QLabel("尚未打开页面")
self.message.setObjectName("hint")
self.message.setWordWrap(True)
self.message.setContentsMargins(14, 8, 14, 12)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addLayout(header)
layout.addWidget(self.view, 1)
layout.addWidget(self.message)
def set_status(self, value: str) -> None:
self.status.setText(value)
def open(self, url: str, action_text: str) -> None:
self.action_text = action_text.strip()
self.page_ready = False
self.message.setText("正在打开页面")
self.logger.info("open url=%s action_text=%r", url, action_text)
self.view.setUrl(QUrl(url.strip()))
def _title_changed(self, title: str) -> None:
if title:
self.message.setText(title)
def _loaded(self, ok: bool) -> None:
self.logger.info("load_finished ok=%s url=%s title=%r", ok, self.page.url().toString(), self.page.title())
if not ok:
self.page_ready = False
self.set_status("加载失败")
self.message.setText("页面加载失败,请检查网址或网络")
return
self.page_ready = True
self.set_status("已打开")
self.message.setText("可直接点击、输入和滚动操作")
if self.pending_script:
pending = self.pending_script
self.pending_script = None
if isinstance(pending, str):
QTimer.singleShot(250, lambda: self.start_script(pending))
else:
# An ad-hoc script object parked by BrowserScript.start().
QTimer.singleShot(250, pending.start)
if self.action_text:
QTimer.singleShot(350, lambda: self._click_text(self.action_text))
def start_script(self, script_id: str) -> None:
if self.active_script and self.active_script.running:
return
self.active_script = create_script(script_id, self, self.ocr_service, self.logger)
self.active_script.start()
def run_script_class(self, script_class: type[BrowserScript]) -> None:
"""Run an ad-hoc script class (live debug panel) on this instance."""
if self.active_script and self.active_script.running:
return
self.active_script = script_class(self, self.ocr_service, self.logger)
self.active_script.start()
def stop_script(self) -> None:
if self.active_script:
self.active_script.stop()
def _web_event_target(self) -> QWidget:
"""Return the widget that actually receives web input events.
QWebEngineView renders its page inside an internal QQuickWidget child that fills
the view. QTest mouse events sent to the view itself are dropped (QWidget ignores
them and they propagate to the parent), so synthetic clicks must be delivered to
that child widget. It sits at (0, 0), so view coordinates work unchanged.
"""
children = [
child
for child in self.view.findChildren(QWidget)
if child.isVisible() and child.width() > 0 and child.height() > 0
]
if children:
return max(children, key=lambda child: child.width() * child.height())
return self.view
def _send_mouse_click(self, x: int, y: int) -> QWidget:
"""Deliver a synthetic left click to the web content at view coordinates (x, y)."""
target = self._web_event_target()
self.view.setFocus(Qt.FocusReason.OtherFocusReason)
QTest.mouseMove(target, QPoint(x, y))
QTest.mousePress(target, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, QPoint(x, y))
QTest.qWait(50)
QTest.mouseRelease(target, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, QPoint(x, y))
self.show_click_feedback(x, y)
return target
def show_click_feedback(self, x: int, y: int) -> None:
"""Flash a small blue ring at view coordinates (x, y) for 0.5s."""
size = 34
indicator = ClickIndicator(self)
indicator.setGeometry(
self.view.x() + x - size // 2,
self.view.y() + y - size // 2,
size,
size,
)
indicator.raise_()
indicator.show()
QTimer.singleShot(500, indicator.deleteLater)
def click_cloud_home(self, attempt: int = 1) -> None:
"""Click the Home control in the toolbar the cloud-phone page renders below the stream."""
script = """
(() => {
const candidates = [...document.querySelectorAll(
'canvas, video, img, iframe, [class*="canvas"], [class*="screen"], [class*="stream"], [class*="phone"]'
)]
.map((element) => {
const rect = element.getBoundingClientRect();
return {rect, area: rect.width * rect.height};
})
.filter((item) => item.rect.width > 80 && item.rect.height > 80)
.sort((left, right) => right.area - left.area);
const streamRect = candidates.length ? candidates[0].rect : null;
// Home/Back/Recents are page controls in the strip below the phone stream,
// not part of the streamed video, so aim for the middle of that strip.
const stripTop = streamRect ? streamRect.bottom : window.innerHeight * 0.9;
const probeX = streamRect ? streamRect.left + streamRect.width * 0.5 : window.innerWidth * 0.5;
const probeY = (stripTop + window.innerHeight) * 0.5;
let button = null;
let bestDistance = Infinity;
for (const element of document.querySelectorAll('button, [role="button"], [onclick]')) {
const rect = element.getBoundingClientRect();
if (!rect.width || !rect.height) continue;
if (rect.y < stripTop - 5) continue;
const distance = Math.hypot(
rect.x + rect.width * 0.5 - probeX,
rect.y + rect.height * 0.5 - probeY
);
if (distance < bestDistance) {
bestDistance = distance;
button = rect;
}
}
let target;
if (button && bestDistance <= 90) {
target = {
x: button.x + button.width * 0.5,
y: button.y + button.height * 0.5,
source: 'DOM toolbar button'
};
} else {
target = {x: probeX, y: probeY, source: 'below-stream strip'};
}
return JSON.stringify({
stream: streamRect
? {x: streamRect.x, y: streamRect.y, width: streamRect.width, height: streamRect.height}
: null,
probe: {x: probeX, y: probeY},
buttonDistance: button ? Math.round(bestDistance) : null,
target: target
});
})();
"""
def clicked(raw_stream: object) -> None:
data: object = raw_stream
if isinstance(raw_stream, str):
try:
data = json.loads(raw_stream)
except json.JSONDecodeError:
self.logger.warning("cloud home DOM probe returned invalid JSON=%r", raw_stream)
data = {}
if not isinstance(data, dict):
data = {}
if isinstance(data.get("stream"), dict):
self.stream_rect = data["stream"]
self.logger.info("cloud home DOM probe attempt=%d result=%r", attempt, data)
x = self.view.width() // 2
y = int(self.view.height() * CLOUD_PHONE_HOME_Y_RATIO)
source = "view fallback"
target = data.get("target")
if isinstance(target, dict):
try:
x = int(float(target["x"]))
y = int(float(target["y"]))
source = str(target.get("source") or "DOM target")
except (KeyError, TypeError, ValueError):
self.logger.warning("cloud home DOM target invalid=%r; using fallbacks", target)
if source == "view fallback":
detected = self._detect_cloud_home_point()
if detected is not None:
x, y = detected
source = "screenshot dark navigation bar"
self._send_mouse_click(x, y)
self.logger.info(
"cloud home clicked coord=(%d,%d) source=%s view=%dx%d probe=%r",
x,
y,
source,
self.view.width(),
self.view.height(),
data,
)
# Neither stream nor toolbar button means the page is still booting.
page_ready = bool(data.get("stream") or data.get("buttonDistance") is not None)
if attempt < 2 and not page_ready:
QTimer.singleShot(500, lambda: self.click_cloud_home(attempt + 1))
self.page.runJavaScript(script, clicked)
def probe_stream_rect(self, callback=None) -> None:
"""Locate the phone-stream element and cache its CSS rect (used for scrolling)."""
script = """
(() => {
const candidates = [...document.querySelectorAll(
'canvas, video, iframe, [class*="canvas"], [class*="screen"], [class*="stream"], [class*="phone"]'
)]
.map((element) => {
const rect = element.getBoundingClientRect();
return {rect, area: rect.width * rect.height};
})
.filter((item) => item.rect.width > 80 && item.rect.height > 80)
.sort((left, right) => right.area - left.area);
const rect = candidates.length ? candidates[0].rect : null;
return JSON.stringify({
stream: rect
? {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
: null
});
})();
"""
def probed(raw: object) -> None:
data: object = raw
if isinstance(raw, str):
try:
data = json.loads(raw)
except json.JSONDecodeError:
data = {}
if isinstance(data, dict) and isinstance(data.get("stream"), dict):
self.stream_rect = data["stream"]
self.logger.info("stream rect probed rect=%r", self.stream_rect)
else:
self.logger.warning("stream rect probe found nothing result=%r", data)
if callback:
callback(self.stream_rect)
self.page.runJavaScript(script, probed)
def scroll_stream(self, delta_y: int = -240) -> None:
"""Scroll the phone stream; negative delta_y scrolls the content down."""
x = self.view.width() // 2
y = self.view.height() // 2
rect = self.stream_rect if isinstance(self.stream_rect, dict) else None
if rect is not None:
try:
x = int(float(rect["x"]) + float(rect["width"]) * 0.5)
y = int(float(rect["y"]) + float(rect["height"]) * 0.5)
except (KeyError, TypeError, ValueError):
self.logger.warning("stream rect invalid for scroll rect=%r", rect)
target = self._web_event_target()
self.view.setFocus(Qt.FocusReason.OtherFocusReason)
QTest.mouseMove(target, QPoint(x, y))
global_point = self.view.mapToGlobal(QPoint(x, y))
event = QWheelEvent(
QPointF(x, y),
QPointF(global_point),
QPoint(0, 0),
QPoint(0, delta_y),
Qt.MouseButton.NoButton,
Qt.KeyboardModifier.NoModifier,
Qt.ScrollPhase.NoScrollPhase,
False,
)
QApplication.sendEvent(target, event)
self.logger.info(
"stream scroll sent delta=%d coord=(%d,%d) widget=%s",
delta_y,
x,
y,
target.metaObject().className(),
)
def click_stream_ratio(self, x_ratio: float, y_ratio: float, callback=None) -> None:
"""Click a stream-relative point (icon targets OCR cannot read, e.g. an ad close X).
The point is expressed as a ratio of the phone-stream rect so it stays correct
if the H5 layout shifts; falls back to the default stream layout when the DOM
probe has not produced a rect.
"""
rect = self.stream_rect if isinstance(self.stream_rect, dict) else None
if rect is None:
self.logger.warning("stream ratio click without probed rect; using default layout")
rect = DEFAULT_STREAM_RECT
try:
x = int(float(rect["x"]) + float(rect["width"]) * x_ratio)
y = int(float(rect["y"]) + float(rect["height"]) * y_ratio)
except (KeyError, TypeError, ValueError):
self.logger.warning("stream rect invalid for ratio click rect=%r", rect)
return
target = self._send_mouse_click(x, y)
self.logger.info(
"stream ratio click x_ratio=%.3f y_ratio=%.3f coord=(%d,%d) rect=%r widget=%s",
x_ratio,
y_ratio,
x,
y,
rect,
target.metaObject().className(),
)
if callback:
callback(x, y)
def _detect_cloud_home_point(self) -> tuple[int, int] | None:
"""Find the center of the dark navigation toolbar below the phone stream."""
image = self.view.grab().toImage()
frame = qimage_to_bgr(image)
if frame.size == 0:
return None
height, width = frame.shape[:2]
gray = frame.mean(axis=2)
left = int(width * 0.2)
right = int(width * 0.8)
dark_fraction = (gray[:, left:right] < 55).mean(axis=1)
minimum_run = max(8, int(height * 0.04))
runs: list[tuple[int, int]] = []
run_start: int | None = None
for row, is_dark in enumerate(dark_fraction > 0.55):
if is_dark and run_start is None:
run_start = row
elif not is_dark and run_start is not None:
if row - run_start >= minimum_run:
runs.append((run_start, row))
run_start = None
if run_start is not None and height - run_start >= minimum_run:
runs.append((run_start, height))
lower_runs = [run for run in runs if run[0] >= int(height * 0.5)]
if not lower_runs:
self.logger.debug("cloud home screenshot detection found no dark navigation bar")
return None
start, end = lower_runs[-1]
dpr = float(image.devicePixelRatio() or 1.0)
point = (int((width * 0.5) / dpr), int(((start + end) * 0.5) / dpr))
self.logger.info(
"cloud home screenshot detection image=%dx%d dpr=%.3f dark_run=(%d,%d) point=(%d,%d)",
width,
height,
dpr,
start,
end,
point[0],
point[1],
)
return point
def click_ocr_point(self, x: int, y: int, match: object, callback) -> None:
# Inspect the DOM for diagnostics, then use a real WebEngine mouse event. Many sites ignore
# JavaScript-created MouseEvents because they are not trusted user input.
self.logger.info(
"click start coord=(%d,%d) view=%dx%d url=%s text=%r",
x,
y,
self.view.width(),
self.view.height(),
self.page.url().toString(),
match.text,
)
script = """
(() => {
const x = %d;
const y = %d;
const node = document.elementFromPoint(x, y);
const describe = (element) => {
if (!element) return null;
const rect = element.getBoundingClientRect();
return {
tag: element.tagName,
id: element.id || null,
className: typeof element.className === 'string' ? element.className.slice(0, 160) : null,
text: (element.innerText || element.getAttribute('aria-label') || '').trim().slice(0, 160),
rect: {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
};
};
const metrics = {
devicePixelRatio: window.devicePixelRatio,
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
scrollX: window.scrollX,
scrollY: window.scrollY
};
if (!node) return JSON.stringify({metrics, node: null, clickable: null});
const target = node.closest('a, button, input, label, [role="button"], [onclick]');
return JSON.stringify({metrics, node: describe(node), clickable: describe(target)});
})();
""" % (x, y)
def inspected(raw_result: object) -> None:
result: object = raw_result
if isinstance(raw_result, str):
try:
result = json.loads(raw_result)
except json.JSONDecodeError:
result = {"raw": raw_result}
self.logger.info("click DOM probe result=%r", result)
target = self._send_mouse_click(x, y)
method = "原生鼠标"
self.logger.info(
"native mouse click sent coord=(%d,%d) widget=%s",
x,
y,
target.metaObject().className(),
)
callback({"method": method, "dom_probe": result}, match, x, y)
QTimer.singleShot(500, self._log_click_state)
self.page.runJavaScript(script, inspected)
def _log_click_state(self) -> None:
self.page.runJavaScript(
"""
(() => JSON.stringify({
url: location.href,
title: document.title,
active: document.activeElement ? {
tag: document.activeElement.tagName,
id: document.activeElement.id || null,
text: (document.activeElement.innerText || '').trim().slice(0, 120)
} : null
}))();
""",
lambda result: self.logger.info("click post-check result=%r", result),
)
def _click_text(self, text: str) -> None:
script = """
(function(targetText) {
const wanted = targetText.trim().toLowerCase();
const nodes = document.querySelectorAll('button, a, input, [role="button"], [onclick], label');
for (const node of nodes) {
const visible = !!(node.offsetWidth || node.offsetHeight || node.getClientRects().length);
const content = (node.innerText || node.value || node.getAttribute('aria-label') || '').trim().toLowerCase();
if (visible && content.includes(wanted)) {
node.click();
return true;
}
}
return false;
})(%s);
""" % json.dumps(text, ensure_ascii=False)
def result(value: object) -> None:
if value:
self.message.setText(f"已点击“{text}”")
else:
self.message.setText(f"未找到“{text}”,页面保持打开")
self.page.runJavaScript(script, result)
def close_browser(self) -> None:
if self.active_script:
self.active_script.stop()
self.active_script = None
self.pending_script = None
self.action_text = ""
self.page_ready = False
self.view.stop()
self.view.setUrl(QUrl("about:blank"))
def clear_cache(self) -> None:
self.profile.clearHttpCache()
self.profile.clearAllVisitedLinks()
self.profile.cookieStore().deleteAllCookies()
self.page.runJavaScript("window.localStorage.clear(); window.sessionStorage.clear();")
self.message.setText("缓存、Cookie 和当前页面存储已清除,请重新加载页面")
self.set_status("已清理")
class MainWindow(QMainWindow):
def __init__(self) -> None:
super().__init__()
self.setWindowTitle("Web 群控工作台 · 浏览器容器版")
self.resize(1440, 920)
self.instances: list[BrowserInstance] = []
self.ocr_service = OCRService()
self.settings = QSettings("Fengyun", "WebControl")
self.log_emitter = LogEmitter()
configure_ui_logging(self.log_emitter)
central = QWidget()
root = QVBoxLayout(central)
root.setContentsMargins(24, 20, 24, 20)
root.setSpacing(14)
eyebrow = QLabel("BROWSER CONTAINER / PYTHON + QT WEBENGINE")
eyebrow.setObjectName("eyebrow")
title = QLabel("Web 群控工作台")
title.setObjectName("title")
hint = QLabel("每个实例都是独立的真实浏览器容器,可直接操作页面。")
hint.setObjectName("hint")
root.addWidget(eyebrow)
root.addWidget(title)
root.addWidget(hint)
controls = QHBoxLayout()
controls.setSpacing(9)
self.url = QComboBox()
self.url.setEditable(True)
self.url.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
self.url.setMinimumWidth(380)
self.url.setPlaceholderText("目标网址,例如 https://example.com")
self._load_url_history()
self.count = QSpinBox()
self.count.setRange(1, 12)
self.count.setValue(1)
self.action_text = QLineEdit()
self.action_text.setPlaceholderText("可选:页面文字")
self.action_text.setMinimumWidth(180)
self.script = QComboBox()
for script_id, label in script_options():
self.script.addItem(label, script_id)
start = QPushButton("启动实例")
start.clicked.connect(self.start_instances)
run_script = QPushButton("开始脚本")
run_script.clicked.connect(self.start_script)
stop_script = QPushButton("停止脚本")
stop_script.clicked.connect(self.stop_scripts)
clear_cache = QPushButton("清除缓存")
clear_cache.clicked.connect(self.clear_cache)
stop = QPushButton("停止全部")
stop.setObjectName("stop")
stop.clicked.connect(self.stop_instances)
controls.addWidget(QLabel("网址"))
controls.addWidget(self.url, 1)
controls.addWidget(QLabel("数量"))
controls.addWidget(self.count)
controls.addWidget(self.action_text)
controls.addWidget(self.script)
controls.addWidget(start)
controls.addWidget(run_script)
controls.addWidget(stop_script)
controls.addWidget(clear_cache)
controls.addWidget(stop)
root.addLayout(controls)
self.error = QLabel("")
self.error.setObjectName("error")
root.addWidget(self.error)
self.log_view = QPlainTextEdit()
self.log_view.setReadOnly(True)
self.log_view.setMaximumBlockCount(600)
self.log_view.setPlaceholderText("脚本日志会显示在这里;完整日志保存在 data/logs/fengyun.log")
self.log_view.setMinimumHeight(140)
self.log_emitter.message.connect(self.log_view.appendPlainText)
# Bottom panel: a slim toggle bar (small arrow button) above the content,
# log on the left half, live step-debug input on the right. Collapsing the
# content hands the freed height back to the device grid above.
self.bottom_host = QWidget()
bottom = QVBoxLayout(self.bottom_host)
bottom.setContentsMargins(0, 0, 0, 0)
bottom.setSpacing(0)
toggle_bar = QHBoxLayout()
toggle_bar.setContentsMargins(0, 0, 0, 4)
self.log_toggle = QPushButton("▾ 隐藏日志")
self.log_toggle.setObjectName("logToggle")
self.log_toggle.setCursor(Qt.CursorShape.PointingHandCursor)
self.log_toggle.setFixedWidth(96)
self.log_toggle.clicked.connect(self.toggle_log_panel)
toggle_bar.addStretch()
toggle_bar.addWidget(self.log_toggle)
bottom.addLayout(toggle_bar)
self.bottom_content = QWidget()
content = QHBoxLayout(self.bottom_content)
content.setContentsMargins(0, 0, 0, 0)
content.setSpacing(14)
log_pane = QVBoxLayout()
log_pane.setSpacing(4)
log_pane.addWidget(QLabel("实时调试日志"))
log_pane.addWidget(self.log_view, 1)
content.addLayout(log_pane, 1)
debug_pane = QVBoxLayout()
debug_pane.setSpacing(4)
debug_pane.addWidget(QLabel("实时调试(粘贴步骤 JSON,点“运行调试步骤”立即执行)"))
self.debug_input = QPlainTextEdit()
self.debug_input.setPlaceholderText(
'单个步骤或步骤数组,例如:\n'
'{"kind": "cond_ratio_click", "confirm": "看15秒", '
'"alt_confirms": ["恭喜已获得"], "absent": "应用版本", '
'"x_ratio": 0.924, "y_ratio": 0.111, "label": "点击广告页右上角 X", "max_scans": 8}'
)
debug_pane.addWidget(self.debug_input, 1)
debug_row = QHBoxLayout()
debug_run = QPushButton("运行调试步骤")
debug_run.clicked.connect(self.run_debug_steps)
self.debug_error = QLabel("")
self.debug_error.setObjectName("error")
self.debug_error.setWordWrap(True)
debug_row.addWidget(debug_run)
debug_row.addWidget(self.debug_error, 1)
debug_pane.addLayout(debug_row)
content.addLayout(debug_pane, 1)
bottom.addWidget(self.bottom_content)
self.grid_host = QWidget()
self.grid = QGridLayout(self.grid_host)
self.grid.setContentsMargins(0, 0, 0, 0)
self.grid.setSpacing(14)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(self.grid_host)
root.addWidget(scroll, 1)
root.addWidget(self.bottom_host)
self.setCentralWidget(central)
def start_instances(self) -> None:
target = self.url.currentText().strip()
if not valid_url(target):
self.error.setText("请输入完整的网址,例如 https://example.com")
return
self.error.setText("")
self._save_url(target)
self.stop_instances()
for index in range(self.count.value()):
card = BrowserInstance(index + 1, self.ocr_service, self.grid_host)
self.instances.append(card)
self.grid.addWidget(
card,
index // 3,
index % 3,
Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
)
card.open(target, self.action_text.text())
def _refresh_script_options(self) -> None:
"""Reload script definitions so edited/new JSON files show up without a restart."""
selected = self.script.currentData()
self.script.blockSignals(True)
self.script.clear()
for script_id, label in script_options():
self.script.addItem(label, script_id)
self.script.blockSignals(False)
if selected:
index = self.script.findData(selected)
if index >= 0:
self.script.setCurrentIndex(index)
def start_script(self) -> None:
if not self.instances:
self.error.setText("请先启动浏览器实例")
return
self.error.setText("")
self._refresh_script_options()
script_id = self.script.currentData()
if not script_id:
self.error.setText("没有可用的脚本,请检查 data/scripts/*.json")
return
for card in self.instances:
card.start_script(script_id)
def toggle_log_panel(self) -> None:
"""Collapse/expand the bottom log+debug content so the device grid can go fullscreen."""
expanded = not self.bottom_content.isVisible()
self.bottom_content.setVisible(expanded)
self.log_toggle.setText("▾ 隐藏日志" if expanded else "▴ 打开日志")
def run_debug_steps(self) -> None:
"""Parse the pasted step JSON and run it as an ad-hoc script on every instance."""
if not self.instances:
self.debug_error.setText("请先启动浏览器实例")
return
raw = self.debug_input.toPlainText().strip()
if not raw:
self.debug_error.setText("请输入步骤 JSON")
return
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
self.debug_error.setText(f"JSON 解析失败:{exc}")
return
steps = data if isinstance(data, list) else [data]
try:
script_class = build_debug_script_class(steps)
except (ValueError, TypeError) as exc:
self.debug_error.setText(f"步骤校验失败:{exc}")
return
self.debug_error.setText("")
self.error.setText("")
for card in self.instances:
card.run_script_class(script_class)
def stop_scripts(self) -> None:
for card in self.instances:
card.stop_script()
def clear_cache(self) -> None:
if not self.instances:
self.error.setText("请先启动浏览器实例")
return
for card in self.instances:
card.clear_cache()
self.error.setText("已清除所有实例的缓存、Cookie 和页面存储")
def _load_url_history(self) -> None:
history = self.settings.value("url_history", [])
if isinstance(history, str):
history = [history]
for url in history or []:
if isinstance(url, str) and valid_url(url):
self.url.addItem(url)
if self.url.count() == 0:
self.url.addItem("https://example.com")
def _save_url(self, url: str) -> None:
history = [self.url.itemText(index) for index in range(self.url.count())]
history = [item for item in history if item and item != url]
history.insert(0, url)
history = history[:20]
self.settings.setValue("url_history", history)
self.url.clear()
self.url.addItems(history)
self.url.setCurrentText(url)
def stop_instances(self) -> None:
for card in self.instances:
card.close_browser()
card.deleteLater()
self.instances.clear()
def closeEvent(self, event) -> None: # type: ignore[no-untyped-def]
self.stop_instances()
event.accept()
def main() -> int:
app = QApplication(sys.argv)
app.setStyle("Fusion")
app.setStyleSheet(APP_STYLE)
window = MainWindow()
window.show()
return app.exec()
if __name__ == "__main__":
raise SystemExit(main())

207
ocr_task.py Normal file
View File

@ -0,0 +1,207 @@
from __future__ import annotations
import threading
from dataclasses import dataclass
from logging import LoggerAdapter
import numpy as np
from PySide6.QtCore import QObject, QRunnable, Signal
from PySide6.QtGui import QImage
from rapidocr_onnxruntime import RapidOCR
@dataclass(frozen=True)
class OCRMatch:
text: str
score: float
center_x: float
center_y: float
image_width: int
image_height: int
box: tuple[tuple[float, float], ...]
def _normalized(text: str) -> str:
return "".join(str(text).split()).lower()
def text_matches(candidate: str, target: str) -> bool:
"""True when the candidate plausibly is the target text.
Small streamed text is often misread by one glyph ("赚钱" -> "账钱"), merged
with its neighbours ("首页秒玩赚钱商城我的"), or truncated at the label edge
("放弃福利" -> "放弃福"), so besides an exact substring match we accept any
window of the candidate that differs from the target by at most one
character, and a candidate that is the target missing exactly one character.
"""
hay = _normalized(candidate)
needle = _normalized(target)
if not needle or needle in hay:
return True
if len(needle) < 2 or len(hay) < 2:
return False
if len(hay) < len(needle):
# Truncated detection: accept a contiguous piece missing exactly one glyph.
return len(hay) == len(needle) - 1 and hay in needle
for start in range(len(hay) - len(needle) + 1):
window = hay[start : start + len(needle)]
if sum(a != b for a, b in zip(window, needle)) <= 1:
return True
return False
def aim_at_target(match: OCRMatch, target: str) -> OCRMatch:
"""Shift the click center onto the target's position inside a wider detection.
When several labels merge into one detection ("首页秒玩赚钱商城我的"), the box
center falls on the middle tab, not on the wanted one; aim at the target's own
characters instead (CJK glyphs are roughly uniform width).
"""
hay = _normalized(match.text)
needle = _normalized(target)
if not hay or len(needle) >= len(hay):
return match
best_start: int | None = None
best_diff: int | None = None
for start in range(len(hay) - len(needle) + 1):
diff = sum(a != b for a, b in zip(hay[start : start + len(needle)], needle))
if best_diff is None or diff < best_diff:
best_start, best_diff = start, diff
if diff == 0:
break
if best_start is None:
return match
xs = [point[0] for point in match.box]
x0, x1 = min(xs), max(xs)
ratio = (best_start + len(needle) / 2) / len(hay)
return OCRMatch(
text=match.text,
score=match.score,
center_x=x0 + (x1 - x0) * ratio,
center_y=match.center_y,
image_width=match.image_width,
image_height=match.image_height,
box=match.box,
)
class OCRService:
"""One shared OCR model. Inference is serialized because model loading is expensive."""
def __init__(self) -> None:
self._engine: RapidOCR | None = None
self._lock = threading.Lock()
def _get_engine(self) -> RapidOCR:
if self._engine is None:
self._engine = RapidOCR()
return self._engine
def scan(self, image: np.ndarray, logger: LoggerAdapter | None = None) -> list[OCRMatch]:
"""Run OCR on the frame and return every detection."""
with self._lock:
result, _ = self._get_engine()(image)
detections = result or []
if logger:
logger.debug("ocr detections=%d", len(detections))
matches: list[OCRMatch] = []
for index, line in enumerate(detections):
box, text, score = line
try:
score_value = float(score)
except (TypeError, ValueError):
score_value = None
if logger:
logger.debug(
"ocr detection[%d] text=%r score=%r score_float=%s box=%s",
index,
text,
score,
score_value,
box,
)
if score_value is None:
if logger:
logger.warning("ocr detection=%r has invalid score=%r", text, score)
continue
points = np.asarray(box, dtype=float)
center = points.mean(axis=0)
matches.append(
OCRMatch(
text=str(text),
score=score_value,
center_x=float(center[0]),
center_y=float(center[1]),
image_width=int(image.shape[1]),
image_height=int(image.shape[0]),
box=tuple((float(point[0]), float(point[1])) for point in box),
)
)
return matches
def find_text(self, image: np.ndarray, target: str, logger: LoggerAdapter | None = None) -> OCRMatch | None:
matches = self.scan(image, logger)
wanted = _normalized(target)
exact = [match for match in matches if wanted in _normalized(match.text)]
if exact:
# Prefer the detection whose length matches the target: the clickable
# label equals the target, while hint sentences merely contain it
# ("确定要放弃福利吗" vs the actual "放弃福利" button).
best = min(exact, key=lambda match: (abs(len(_normalized(match.text)) - len(wanted)), -match.score))
return aim_at_target(best, target)
fuzzy = [match for match in matches if text_matches(match.text, target)]
if fuzzy:
best = min(fuzzy, key=lambda match: (abs(len(_normalized(match.text)) - len(wanted)), -match.score))
if logger:
logger.info("ocr fuzzy match target=%r via=%r score=%.4f", target, best.text, best.score)
return aim_at_target(best, target)
return None
class OCRSignals(QObject):
finished = Signal(object, object)
class OCRWorker(QRunnable):
def __init__(self, service: OCRService, image: np.ndarray, target: str, logger: LoggerAdapter | None = None) -> None:
super().__init__()
self.service = service
self.image = image
self.target = target
self.logger = logger
self.signals = OCRSignals()
def run(self) -> None:
try:
self.signals.finished.emit(self.service.find_text(self.image, self.target, self.logger), None)
except Exception as exc:
if self.logger:
self.logger.exception("ocr worker exception target=%r", self.target)
self.signals.finished.emit(None, exc)
class OCRScanWorker(QRunnable):
"""Async wrapper around OCRService.scan; reports every detection on the frame."""
def __init__(self, service: OCRService, image: np.ndarray, logger: LoggerAdapter | None = None) -> None:
super().__init__()
self.service = service
self.image = image
self.logger = logger
self.signals = OCRSignals()
def run(self) -> None:
try:
self.signals.finished.emit(self.service.scan(self.image, self.logger), None)
except Exception as exc:
if self.logger:
self.logger.exception("ocr scan worker exception")
self.signals.finished.emit(None, exc)
def qimage_to_bgr(image: QImage) -> np.ndarray:
converted = image.convertToFormat(QImage.Format.Format_RGBA8888)
width, height = converted.width(), converted.height()
data = converted.bits().tobytes()
rgba = np.frombuffer(data, dtype=np.uint8).reshape((height, width, 4))
return np.ascontiguousarray(rgba[:, :, :3][:, :, ::-1])

5
requirements.txt Normal file
View File

@ -0,0 +1,5 @@
fastapi>=0.115,<1
uvicorn[standard]>=0.30,<1
playwright>=1.48,<2
PySide6>=6.7,<7
rapidocr_onnxruntime==1.2.3

4
scripts/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from .loader import load_script_classes
from .registry import create_script, script_options
__all__ = ["create_script", "load_script_classes", "script_options"]

883
scripts/base.py Normal file
View File

@ -0,0 +1,883 @@
from __future__ import annotations
import re
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
import cv2
from PySide6.QtCore import QThreadPool, QTimer
from PySide6.QtGui import QColor, QPainter, QPen
from ocr_task import (
OCRMatch,
OCRScanWorker,
OCRService,
OCRWorker,
aim_at_target,
qimage_to_bgr,
text_matches,
)
if TYPE_CHECKING:
from logging import LoggerAdapter
from desktop_app import BrowserInstance
# Status-bar clocks change every minute and would break "stream stopped moving" detection.
CLOCK_TEXT = re.compile(r"^\d{1,2}:\d{2}$")
# OCR boxes jitter by a pixel or two between identical frames; quantize before comparing.
SIGNATURE_GRID = 4
# A side-by-side target must sit to the right of the anchor row (small slack for rounding).
RIGHT_SIDE_SLACK = 8.0
@dataclass(frozen=True)
class ScriptStep:
"""One action in a script flow.
kind:
- "home": click the cloud-phone Home control
- "ocr_click": find step text via OCR and click it
- "scroll_ocr_click": find step text to the right of the anchor row; scroll
down and retry until found or the stream stops moving
- "await_click": once the confirm text shows up, wait at most await_ms for
step text (or any of alt_texts) and click it; give up when neither appears
- "delay_click": wait delay_ms, then click a stream-relative point (icon
targets that carry no OCR-readable text, e.g. an ad close X)
- "cond_ratio_click": scan until the confirm text shows up, then click a
stream-relative point; skip the step when the text never appears
- "loop": jump back to step `loop_to` until the body has run `loop_times`
times in total
- "delay_home": wait delay_ms, then click the cloud-phone Home control
- "cond_ocr_click": scan until the confirm text shows up, then click the
step text (first of text/alt_texts); skip the whole branch via skip_to
when the confirm never appears
- "gray_end": scan a stream-relative region; when it turns fully gray
(colored-pixel share at or below gray_threshold, e.g. finished task
buttons losing their color), end the whole script as completed
"""
kind: str
label: str
text: str = ""
# Alternative texts accepted for the same action: await_click clicks the first
# of text/alt_texts that shows up (ad templates swap the CTA label, e.g.
# "了解详情" / "立即体验").
alt_texts: tuple[str, ...] = ()
anchor: str = ""
confirm: str = ""
# Alternative confirm texts for cond_ratio_click: the step fires when any of
# confirm/alt_confirms shows up (ad templates swap the banner label, e.g.
# "看15秒" vs the reward notification bar "恭喜已获得").
alt_confirms: tuple[str, ...] = ()
# Countdown guard for cond_ratio_click: while any of these texts is on
# screen the confirm must not fire, so a reward notification bar
# ("恭喜已获得奖励…") cannot trigger the click before the "继续浏览15秒"
# countdown finishes, and other always-on markers cannot fake the confirm.
absent: str = ""
alt_absents: tuple[str, ...] = ()
await_ms: int = 10_000
delay_ms: int = 20_000
x_ratio: float = 0.0
y_ratio: float = 0.0
# "gray_end" step: detection region size as fractions of the stream rect;
# the whole stream when left at defaults.
w_ratio: float = 1.0
h_ratio: float = 1.0
# "gray_end" step: the region counts as "fully gray" when the colored-pixel
# share (HSV saturation >= 60 and value >= 60) drops to or below this
# threshold — finished task buttons lose their color, so a fully gray task
# row means every reward has been claimed.
gray_threshold: float = 0.03
offset_y_ratio: float = 0.0
max_scans: int = 20
# Template-dependent targets skip forward instead of failing the script when
# they never show up (e.g. reward popups whose close flow differs per ad).
optional: bool = False
# "loop" step: index to jump back to and how many times the loop body runs.
loop_to: int = -1
loop_times: int = 1
# "cond_ocr_click" step: when the confirm never appears within max_scans,
# jump straight to this step index instead of the next one, skipping the
# whole conditional branch.
skip_to: int = -1
# Pick the first (topmost) among multiple same-text matches instead of the
# best-scoring one (download pages repeat the 立即下载 button).
pick_top: bool = False
def _box_bounds(match: OCRMatch) -> tuple[float, float, float, float]:
xs = [point[0] for point in match.box]
ys = [point[1] for point in match.box]
return min(xs), max(xs), min(ys), max(ys)
class BrowserScript(ABC):
script_id: str
label: str
target_text: str
# Home-screen app names are rendered below their icons, so the touch target is above the OCR label.
click_offset_y_ratio: float = 0.0
# Multi-step flow; None keeps the legacy "Home → click target_text" two-step script.
steps: list[ScriptStep] | None = None
def __init__(self, instance: "BrowserInstance", ocr_service: OCRService, logger: "LoggerAdapter") -> None:
self.instance = instance
self.ocr_service = ocr_service
self.logger = logger
self.running = False
self.attempts = 0
self.step_index = 0
self.scan_index = 0
self.static_scans = 0
self.frame_signature: tuple | None = None
# Monotonic deadline for await_click steps; None until the landmark is seen.
self.await_deadline: float | None = None
self.workers: list[OCRWorker] = []
self.scan_workers: list[OCRScanWorker] = []
self.last_capture = None
# Executions of each "loop" step so far, keyed by step index.
self.loop_counts: dict[int, int] = {}
def plan_steps(self) -> list[ScriptStep]:
if self.steps is not None:
return list(self.steps)
return [
ScriptStep(kind="home", label="点击云手机 Home 按钮"),
ScriptStep(
kind="ocr_click",
label=f"OCR 查找“{self.target_text}”",
text=self.target_text,
offset_y_ratio=self.click_offset_y_ratio,
),
]
def start(self) -> None:
if self.running:
return
if not self.instance.page_ready:
self.logger.info("script=%s delayed: page is not ready", self.script_id)
# Store the instance itself so ad-hoc scripts (live debug panel)
# resume without a registry lookup.
self.instance.pending_script = self
self.instance.set_status("等待页面")
self.instance.message.setText("页面加载完成后自动开始脚本")
return
self.running = True
self.instance.active_script = self
self.attempts = 0
self.step_index = 0
self.loop_counts = {}
self.logger.info("script=%s started target=%s url=%s", self.script_id, self.target_text, self.instance.page.url().toString())
self.run_current_step()
def stop(self) -> None:
if self.running:
self.logger.info("script=%s stopped by user", self.script_id)
self.running = False
self.instance.pending_script = None
self.instance.set_status("已暂停")
self.instance.message.setText("脚本已停止,浏览器保持打开")
def run_current_step(self) -> None:
if not self.running:
return
steps = self.plan_steps()
step = steps[self.step_index]
self.instance.message.setText(f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}")
if step.kind == "home":
self.instance.set_status("Task: Home")
self.instance.click_cloud_home()
self.logger.debug("cloud phone Home navigation click requested")
QTimer.singleShot(600, self.advance_step)
elif step.kind == "ocr_click":
self.instance.set_status("Task: OCR")
self.attempts = 0
self.find_target()
elif step.kind == "scroll_ocr_click":
self.instance.set_status("Task: OCR")
self.scan_index = 0
self.static_scans = 0
self.frame_signature = None
self.instance.probe_stream_rect()
# Give the freshly opened screen a moment to settle before the first scan.
QTimer.singleShot(800, self.find_scan)
elif step.kind == "await_click":
self.instance.set_status("Task: OCR")
self.scan_index = 0
self.await_deadline = None
# The freshly opened screen needs a moment before the first scan.
QTimer.singleShot(800, self.find_scan)
elif step.kind == "cond_ratio_click":
self.instance.set_status("Task: OCR")
self.scan_index = 0
# Cache the stream rect so the conditional click uses live geometry.
self.instance.probe_stream_rect()
# The screen may still be mid-transition; give it a moment first.
QTimer.singleShot(800, self.find_scan)
elif step.kind == "delay_click":
self.instance.set_status("Task: Wait")
# Cache the stream rect now so the click after the wait uses live geometry.
self.instance.probe_stream_rect()
QTimer.singleShot(step.delay_ms, self.click_stream_point)
elif step.kind == "gray_end":
self.instance.set_status("Task: OCR")
self.scan_index = 0
# Cache the stream rect so the region check uses live geometry.
self.instance.probe_stream_rect()
# The freshly opened screen needs a moment before the first check.
QTimer.singleShot(800, self.gray_check)
elif step.kind == "loop":
executed = self.loop_counts.get(self.step_index, 0) + 1
self.loop_counts[self.step_index] = executed
if executed < step.loop_times:
self.logger.info(
"loop round=%d/%d jumping to step=%d",
executed,
step.loop_times,
step.loop_to,
)
self.step_index = step.loop_to
self.run_current_step()
else:
self.advance_step(f"已循环完成 {step.loop_times} 轮")
elif step.kind == "delay_home":
self.instance.set_status("Task: Wait")
self.logger.info("delay_home waiting %dms before going Home", step.delay_ms)
QTimer.singleShot(step.delay_ms, self.delay_home_click)
elif step.kind == "cond_ocr_click":
self.instance.set_status("Task: OCR")
self.scan_index = 0
# The freshly entered screen needs a moment before the first scan.
QTimer.singleShot(800, self.find_scan)
else:
self.logger.error("script=%s unknown step kind=%r", self.script_id, step.kind)
self.finish("脚本失败", f"未知步骤类型:{step.kind}")
def advance_step(self, note: str = "") -> None:
if not self.running:
return
self.step_index += 1
if self.step_index >= len(self.plan_steps()):
self.finish("脚本完成", note or "全部步骤已完成")
return
self.run_current_step()
# --- ocr_click step ------------------------------------------------------
def find_target(self) -> None:
if not self.running:
return
self.attempts += 1
steps = self.plan_steps()
step = steps[self.step_index]
self.instance.set_status("Task: OCR")
self.instance.message.setText(
f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}(第 {self.attempts} 次)"
)
image = self.instance.view.grab().toImage()
self.last_capture = image.copy()
frame = qimage_to_bgr(image)
self.logger.info(
"ocr attempt=%d target=%s image=%dx%d dpr=%.3f view=%dx%d url=%s",
self.attempts,
step.text,
frame.shape[1],
frame.shape[0],
image.devicePixelRatio(),
self.instance.view.width(),
self.instance.view.height(),
self.instance.page.url().toString(),
)
worker = OCRWorker(self.ocr_service, frame, step.text, self.logger)
self.workers.append(worker)
worker.signals.finished.connect(self.ocr_finished)
QThreadPool.globalInstance().start(worker)
def ocr_finished(self, match: object, error: object) -> None:
if self.workers:
self.workers.pop(0)
if not self.running:
return
if error is not None:
self.logger.error("ocr failed error=%r", error)
self.finish("OCR 失败", f"OCR 执行失败:{error}")
return
if match is None:
step = self.plan_steps()[self.step_index]
self.logger.warning("ocr attempt=%d target=%s: no match", self.attempts, step.text)
if self.attempts < 8:
QTimer.singleShot(700, self.find_target)
else:
self.finish("未找到目标", f"OCR 未找到“{step.text}”,浏览器保持打开")
return
step = self.plan_steps()[self.step_index]
x, y = self.click_point_of(step, match)
self.logger.info(
"ocr match text=%r score=%.4f box_center=(%.1f,%.1f) image=%dx%d click_offset_y_ratio=%.3f mapped_click=(%d,%d)",
match.text,
match.score,
match.center_x,
match.center_y,
match.image_width,
match.image_height,
step.offset_y_ratio,
x,
y,
)
self.save_debug_capture(match, x, y, "ocr")
self.instance.click_ocr_point(x, y, match, self.click_finished)
# --- scroll_ocr_click step -----------------------------------------------
def find_scan(self) -> None:
if not self.running:
return
steps = self.plan_steps()
step = steps[self.step_index]
self.scan_index += 1
self.instance.set_status("Task: OCR")
self.instance.message.setText(
f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}(第 {self.scan_index} 次扫描)"
)
image = self.instance.view.grab().toImage()
self.last_capture = image.copy()
frame = qimage_to_bgr(image)
self.logger.info(
"ocr scan=%d anchor=%s confirm=%s target=%s image=%dx%d dpr=%.3f view=%dx%d url=%s",
self.scan_index,
step.anchor,
step.confirm,
step.text,
frame.shape[1],
frame.shape[0],
image.devicePixelRatio(),
self.instance.view.width(),
self.instance.view.height(),
self.instance.page.url().toString(),
)
worker = OCRScanWorker(self.ocr_service, frame, self.logger)
self.scan_workers.append(worker)
worker.signals.finished.connect(self.scan_finished)
QThreadPool.globalInstance().start(worker)
def scan_finished(self, detections: object, error: object) -> None:
if self.scan_workers:
self.scan_workers.pop(0)
if not self.running:
return
if error is not None:
self.logger.error("ocr scan failed error=%r", error)
self.finish("OCR 失败", f"OCR 执行失败:{error}")
return
step = self.plan_steps()[self.step_index]
items = [detection for detection in (detections or []) if isinstance(detection, OCRMatch)]
if step.kind == "await_click":
self.await_scan_finished(step, items)
return
if step.kind == "cond_ratio_click":
self.cond_scan_finished(step, items)
return
if step.kind == "cond_ocr_click":
self.cond_click_scan_finished(step, items)
return
target = self.match_beside_anchor(items, step.anchor, step.text)
if target is not None:
x, y = self.click_point_of(step, target)
self.logger.info(
"scan match text=%r score=%.4f box_center=(%.1f,%.1f) anchor=%r mapped_click=(%d,%d)",
target.text,
target.score,
target.center_x,
target.center_y,
step.anchor,
x,
y,
)
self.save_debug_capture(target, x, y, "scan")
self.instance.click_ocr_point(x, y, target, self.click_finished)
return
self.logger.warning(
"ocr scan=%d anchor=%s target=%s: no side-by-side match",
self.scan_index,
step.anchor,
step.text,
)
signature = self.frame_signature_of(items)
if signature == self.frame_signature:
self.static_scans += 1
else:
self.static_scans = 0
self.frame_signature = signature
if self.static_scans >= 2:
self.logger.info("scan=%d stream stopped moving: reached the bottom", self.scan_index)
self.finish("未找到目标", f"已滚动到底部,未见“{step.text}”")
return
if self.scan_index >= step.max_scans:
self.logger.warning("scan=%d reached max scans=%d", self.scan_index, step.max_scans)
self.finish("未找到目标", f"扫描 {self.scan_index} 次仍未找到“{step.text}”")
return
self.instance.scroll_stream()
self.logger.info("stream scroll down requested after scan=%d", self.scan_index)
QTimer.singleShot(1500, self.find_scan)
# --- await_click step ----------------------------------------------------
def await_scan_finished(self, step: ScriptStep, items: list[OCRMatch]) -> None:
"""Handle one await_click scan: click the target as soon as it shows up."""
wanted = [text for text in (step.text, *step.alt_texts) if text]
target = None
target_text = ""
best_rank = None
for detection in items:
for wanted_text in wanted:
if not text_matches(detection.text, wanted_text):
continue
# Prefer the detection whose length matches the wanted text: the CTA
# button label equals the target, while hint sentences merely contain
# it ("确定要放弃福利吗" vs the actual "放弃福利" button).
rank = (abs(len(detection.text.strip()) - len(wanted_text)), -detection.score)
if best_rank is None or rank < best_rank:
best_rank = rank
target = detection
target_text = wanted_text
if target is not None:
target = aim_at_target(target, target_text)
x, y = self.click_point_of(step, target)
self.logger.info(
"await match text=%r score=%.4f box_center=(%.1f,%.1f) target=%r mapped_click=(%d,%d)",
target.text,
target.score,
target.center_x,
target.center_y,
target_text,
x,
y,
)
self.save_debug_capture(target, x, y, "scan")
self.instance.click_ocr_point(x, y, target, self.click_finished)
return
display = "/".join(wanted)
now = time.monotonic()
landmark_seen = not step.confirm or any(
text_matches(detection.text, step.confirm) for detection in items
)
if landmark_seen and self.await_deadline is None:
self.await_deadline = now + step.await_ms / 1000.0
self.logger.info(
"await landmark=%r confirmed; waiting up to %.0fs for %r",
step.confirm,
step.await_ms / 1000.0,
display,
)
if self.await_deadline is not None:
if now >= self.await_deadline:
if step.optional:
self.logger.info(
"await scan=%d target=%r not shown within %dms; optional, continuing",
self.scan_index,
display,
step.await_ms,
)
self.advance_step(f"等待 {step.await_ms // 1000} 秒未见“{display}”,跳过")
return
self.logger.warning(
"await scan=%d target=%r not shown within %dms",
self.scan_index,
display,
step.await_ms,
)
self.finish("未找到目标", f"等待 {step.await_ms // 1000} 秒未见“{display}”,任务终止")
return
elif self.scan_index >= step.max_scans:
# The landmark never showed up: probably not on the expected page at all.
if step.optional:
self.logger.info(
"await scan=%d landmark=%r not seen; optional, continuing",
self.scan_index,
step.confirm,
)
self.advance_step(f"未见“{step.confirm}”提示,跳过")
return
self.logger.warning(
"await scan=%d landmark=%r not seen", self.scan_index, step.confirm
)
self.finish("未找到目标", f"未见“{step.confirm}”提示,任务终止")
return
QTimer.singleShot(1000, self.find_scan)
# --- cond_ratio_click step ------------------------------------------------
def cond_scan_finished(self, step: ScriptStep, items: list[OCRMatch]) -> None:
"""Handle one cond_ratio_click scan: click the stream point once the confirm text shows up."""
confirms = [text for text in (step.confirm, *step.alt_confirms) if text]
blockers = [text for text in (step.absent, *step.alt_absents) if text]
if blockers:
blocker = next(
(
detection
for detection in items
if any(text_matches(detection.text, wanted) for wanted in blockers)
),
None,
)
if blocker is not None and self.scan_index < step.max_scans:
# A blocker text is still on screen: the confirm seen now would
# be an always-on marker (notification bar / other page), not
# the finished countdown.
self.logger.debug(
"cond confirm=%r blocked by absent text=%r; waiting",
"/".join(confirms),
blocker.text,
)
QTimer.singleShot(1000, self.find_scan)
return
for wanted in confirms:
hit = next(
(detection for detection in items if text_matches(detection.text, wanted)),
None,
)
if hit is not None:
self.logger.info(
"cond match text=%r confirmed via=%r; clicking stream point (%.3f, %.3f)",
hit.text,
wanted,
step.x_ratio,
step.y_ratio,
)
self.instance.set_status("Task: Click")
self.last_capture = self.instance.view.grab().toImage().copy()
self.save_raw_capture("ratio")
self.instance.click_stream_ratio(step.x_ratio, step.y_ratio, self.stream_click_finished)
return
if self.scan_index >= step.max_scans:
self.logger.info(
"cond scan=%d confirm=%r not seen; skipping step",
self.scan_index,
"/".join(confirms),
)
self.advance_step(f"未见“{'/'.join(confirms)}”,跳过")
return
QTimer.singleShot(1000, self.find_scan)
# --- delay_click step ----------------------------------------------------
def click_stream_point(self) -> None:
"""Click the fixed stream-relative point of a delay_click step."""
if not self.running:
return
step = self.plan_steps()[self.step_index]
self.instance.set_status("Task: Click")
self.last_capture = self.instance.view.grab().toImage().copy()
self.save_raw_capture("ratio")
self.instance.click_stream_ratio(step.x_ratio, step.y_ratio, self.stream_click_finished)
def stream_click_finished(self, x: int, y: int) -> None:
self.logger.info("stream ratio click done coord=(%d,%d)", x, y)
self.advance_step(f"已点击坐标 ({x},{y})")
# --- gray_end step ---------------------------------------------------------
def gray_check(self) -> None:
"""Handle one gray_end scan: end the script when the region turns fully gray."""
if not self.running:
return
steps = self.plan_steps()
step = steps[self.step_index]
self.scan_index += 1
self.instance.set_status("Task: OCR")
self.instance.message.setText(
f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}(第 {self.scan_index} 次扫描)"
)
image = self.instance.view.grab().toImage()
self.last_capture = image.copy()
frame = qimage_to_bgr(image)
rect = self.instance.stream_rect if isinstance(self.instance.stream_rect, dict) else None
if rect is None:
# No probed rect: fall back to the whole view as the stream region.
rect = {
"x": 0,
"y": 0,
"width": self.instance.view.width(),
"height": self.instance.view.height(),
}
try:
scale_x = frame.shape[1] / max(1, self.instance.view.width())
scale_y = frame.shape[0] / max(1, self.instance.view.height())
left = max(0, int((float(rect["x"]) + float(rect["width"]) * step.x_ratio) * scale_x))
top = max(0, int((float(rect["y"]) + float(rect["height"]) * step.y_ratio) * scale_y))
right = min(
frame.shape[1],
int((float(rect["x"]) + float(rect["width"]) * (step.x_ratio + step.w_ratio)) * scale_x),
)
bottom = min(
frame.shape[0],
int((float(rect["y"]) + float(rect["height"]) * (step.y_ratio + step.h_ratio)) * scale_y),
)
except (KeyError, TypeError, ValueError):
self.logger.warning("gray check region invalid rect=%r", rect)
self.advance_step("无法定位检测区域,跳过")
return
region = frame[top:bottom, left:right]
if region.size == 0:
self.logger.warning(
"gray check region empty left=%d top=%d right=%d bottom=%d",
left,
top,
right,
bottom,
)
self.advance_step("检测区域为空,跳过")
return
hsv = cv2.cvtColor(region, cv2.COLOR_BGR2HSV)
colored = float(((hsv[..., 1] >= 60) & (hsv[..., 2] >= 60)).mean())
self.logger.info(
"gray check scan=%d region=%dx%d+%d,%d colored=%.1f%% threshold=%.1f%%",
self.scan_index,
right - left,
bottom - top,
left,
top,
colored * 100,
step.gray_threshold * 100,
)
if colored <= step.gray_threshold:
self.save_raw_capture("gray")
self.logger.info(
"gray check scan=%d region fully gray (%.1f%% colored); ending script",
self.scan_index,
colored * 100,
)
self.finish(
"脚本完成",
f"检测到任务区已全灰(彩色像素 {colored * 100:.1f}%),奖励已领完,流程结束",
)
return
if self.scan_index >= step.max_scans:
self.logger.info(
"gray check scan=%d region still colored (%.1f%%); continuing script",
self.scan_index,
colored * 100,
)
self.advance_step(f"任务区未全灰(彩色像素 {colored * 100:.1f}%),继续流程")
return
QTimer.singleShot(1000, self.gray_check)
# --- delay_home step ------------------------------------------------------
def delay_home_click(self) -> None:
"""Click the cloud-phone Home control after the delay_home wait."""
if not self.running:
return
self.instance.set_status("Task: Home")
self.instance.click_cloud_home()
self.logger.info("delay_home clicked the cloud phone Home control")
QTimer.singleShot(600, self.advance_step)
# --- cond_ocr_click step ---------------------------------------------------
def cond_click_scan_finished(self, step: ScriptStep, items: list[OCRMatch]) -> None:
"""Handle one cond_ocr_click scan: click the step text once the confirm text shows up."""
confirmed = not step.confirm or any(
text_matches(detection.text, step.confirm) for detection in items
)
if confirmed:
wanted = [text for text in (step.text, *step.alt_texts) if text]
candidates = [
detection
for detection in items
if any(text_matches(detection.text, text) for text in wanted)
]
if candidates:
if step.pick_top:
# Repeated same-text buttons (download pages): take the first
# on screen, not the best-scoring one.
target = min(candidates, key=lambda detection: detection.center_y)
else:
target = max(candidates, key=lambda detection: detection.score)
target_text = next(
text for text in wanted if text_matches(target.text, text)
)
target = aim_at_target(target, target_text)
x, y = self.click_point_of(step, target)
self.logger.info(
"cond click match text=%r score=%.4f box_center=(%.1f,%.1f) target=%r pick_top=%s mapped_click=(%d,%d)",
target.text,
target.score,
target.center_x,
target.center_y,
target_text,
step.pick_top,
x,
y,
)
self.save_debug_capture(target, x, y, "scan")
self.instance.click_ocr_point(x, y, target, self.click_finished)
return
# Confirm hit but no clickable text: treat the confirm itself as the
# trigger and click the step text anyway on the next pass.
self.logger.warning(
"cond click confirm=%r seen but no %r candidate; rescanning",
step.confirm,
"/".join(wanted),
)
if self.scan_index >= step.max_scans:
if step.skip_to >= 0:
self.logger.info(
"cond click scan=%d confirm=%r not seen; skipping branch to step=%d",
self.scan_index,
step.confirm,
step.skip_to,
)
self.step_index = step.skip_to
self.run_current_step()
return
self.logger.warning(
"cond click scan=%d confirm=%r not seen; skipping step",
self.scan_index,
step.confirm,
)
self.advance_step(f"未见“{step.confirm}”,跳过")
return
QTimer.singleShot(1000, self.find_scan)
def match_beside_anchor(self, detections: list[OCRMatch], anchor: str, target: str) -> OCRMatch | None:
"""Return the best `target` detection sitting to the right of the anchor text row."""
candidates = [detection for detection in detections if text_matches(detection.text, target)]
if not anchor:
return max(candidates, key=lambda detection: detection.score) if candidates else None
anchors = [detection for detection in detections if text_matches(detection.text, anchor)]
best: OCRMatch | None = None
for anchor_match in sorted(anchors, key=lambda detection: -detection.score):
_, anchor_x1, anchor_y0, anchor_y1 = _box_bounds(anchor_match)
for candidate in sorted(candidates, key=lambda detection: -detection.score):
candidate_x0, _, candidate_y0, candidate_y1 = _box_bounds(candidate)
same_row = anchor_y0 < candidate_y1 and candidate_y0 < anchor_y1
to_the_right = candidate_x0 >= anchor_x1 - RIGHT_SIDE_SLACK
if same_row and to_the_right and (best is None or candidate.score > best.score):
best = candidate
if best is None:
# OCR often merges the anchor row and its button into one detection
# ("看精彩视频领积分去观看"); aim straight at the target inside that box.
merged = [
detection
for detection in candidates
if text_matches(detection.text, anchor)
]
if merged:
best = aim_at_target(max(merged, key=lambda detection: detection.score), target)
return best
def frame_signature_of(self, detections: list[OCRMatch]) -> tuple:
"""Fingerprint of the phone-screen text; equal fingerprints mean the stream did not move."""
dpr = float(self.last_capture.devicePixelRatio() or 1.0) if self.last_capture else 1.0
rect = self.instance.stream_rect if isinstance(self.instance.stream_rect, dict) else None
items = []
for detection in detections:
if CLOCK_TEXT.match(detection.text.strip()):
continue
x0, x1, y0, y1 = _box_bounds(detection)
if rect is not None:
try:
left = float(rect["x"]) * dpr
top = float(rect["y"]) * dpr
right = left + float(rect["width"]) * dpr
bottom = top + float(rect["height"]) * dpr
except (KeyError, TypeError, ValueError):
left = top = right = bottom = None
if right is not None and not (left <= detection.center_x <= right and top <= detection.center_y <= bottom):
# H5 toolbar / page text outside the phone screen; ignore it.
continue
items.append(
(
detection.text,
round(x0 / SIGNATURE_GRID),
round(y0 / SIGNATURE_GRID),
round(x1 / SIGNATURE_GRID),
round(y1 / SIGNATURE_GRID),
)
)
return tuple(sorted(items))
# --- shared helpers -------------------------------------------------------
def click_point_of(self, step: ScriptStep, match: OCRMatch) -> tuple[int, int]:
click_center_y = match.center_y + step.offset_y_ratio * match.image_height
click_center_y = max(0.0, min(float(match.image_height), click_center_y))
x = int(match.center_x * self.instance.view.width() / match.image_width)
y = int(click_center_y * self.instance.view.height() / match.image_height)
return x, y
def save_debug_capture(self, match: object, x: int, y: int, tag: str) -> None:
if self.last_capture is None:
return
image = self.last_capture.copy()
painter = QPainter(image)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(QPen(QColor("#ff3b30"), 3))
points = [
(int(px), int(py))
for px, py in match.box
]
for index, point in enumerate(points):
next_point = points[(index + 1) % len(points)]
painter.drawLine(point[0], point[1], next_point[0], next_point[1])
painter.setPen(QPen(QColor("#00d26a"), 4))
painter.drawEllipse(int(match.center_x) - 8, int(match.center_y) - 8, 16, 16)
click_image_x = x * image.width() / max(1, self.instance.view.width())
click_image_y = y * image.height() / max(1, self.instance.view.height())
painter.setPen(QPen(QColor("#1769ff"), 4))
painter.drawEllipse(int(click_image_x) - 10, int(click_image_y) - 10, 20, 20)
painter.end()
output_dir = Path(__file__).resolve().parent.parent / "data" / "logs" / "screenshots"
output_dir.mkdir(parents=True, exist_ok=True)
sequence = self.attempts if tag == "ocr" else self.scan_index
output = output_dir / f"instance-{self.instance.instance_id}-{tag}-{sequence}.png"
if image.save(str(output), "PNG"):
self.logger.info(
"debug image saved path=%s ocr_center=(%.1f,%.1f) click_marker=(%.1f,%.1f) mapped_click=(%d,%d)",
output,
match.center_x,
match.center_y,
click_image_x,
click_image_y,
x,
y,
)
else:
self.logger.warning("debug image save failed path=%s", output)
def save_raw_capture(self, tag: str) -> None:
"""Save the current capture without annotations (icon-click diagnostics)."""
if self.last_capture is None:
return
output_dir = Path(__file__).resolve().parent.parent / "data" / "logs" / "screenshots"
output_dir.mkdir(parents=True, exist_ok=True)
output = output_dir / f"instance-{self.instance.instance_id}-{tag}-{self.step_index + 1}.png"
if self.last_capture.save(str(output), "PNG"):
self.logger.info("raw capture saved path=%s", output)
else:
self.logger.warning("raw capture save failed path=%s", output)
def click_finished(self, result: object, match: object, x: int, y: int) -> None:
self.logger.info("click result=%r coord=(%d,%d) match=%r", result, x, y, match.text)
method = result.get("method", "unknown") if isinstance(result, dict) else "unknown"
self.advance_step(f"已点击“{match.text}”(置信度 {match.score:.2f},{method})")
def finish(self, status: str, message: str) -> None:
self.running = False
self.instance.set_status(status)
self.instance.message.setText(message)
self.logger.info("script=%s finished status=%s message=%s", self.script_id, status, message)
@abstractmethod
def name(self) -> str:
raise NotImplementedError

180
scripts/loader.py Normal file
View File

@ -0,0 +1,180 @@
from __future__ import annotations
import json
import threading
from pathlib import Path
from typing import TYPE_CHECKING
from .base import BrowserScript, ScriptStep
if TYPE_CHECKING:
from logging import LoggerAdapter
from desktop_app import BrowserInstance
from ocr_task import OCRService
# Script definitions live here as JSON files; editing or adding one takes effect
# on the next script start (or dropdown refresh) without restarting the client.
SCRIPT_DIR = Path(__file__).resolve().parent.parent / "data" / "scripts"
STEP_KINDS = {
"home",
"ocr_click",
"scroll_ocr_click",
"await_click",
"delay_click",
"cond_ratio_click",
"cond_ocr_click",
"gray_end",
"delay_home",
"loop",
}
_lock = threading.Lock()
# path -> (mtime, class) cache; refreshed whenever the file changes on disk.
_cache: dict[Path, tuple[float, type[BrowserScript]]] = {}
# path -> last error message; kept so broken files are reported once per change.
_errors: dict[Path, str] = {}
def _normalize_absent(raw: dict) -> None:
"""Let "absent" be a single text or a list of texts (any one blocks).
Splits an array form into absent (first text) + alt_absents (the rest) so
ScriptStep stays a flat str/tuple pair.
"""
absent = raw.get("absent")
if isinstance(absent, list):
texts = [text for text in absent if text]
extras = [text for text in (raw.get("alt_absents") or []) if text]
raw["absent"] = texts[0] if texts else ""
raw["alt_absents"] = texts[1:] + extras
def _validate(spec: dict, path: Path) -> list[ScriptStep]:
"""Check one script spec and turn its steps into ScriptStep objects."""
for key in ("script_id", "label", "steps"):
if not spec.get(key):
raise ValueError(f"missing required field {key!r}")
raw_steps = spec["steps"]
if not isinstance(raw_steps, list) or not raw_steps:
raise ValueError("'steps' must be a non-empty list")
steps: list[ScriptStep] = []
for index, raw in enumerate(raw_steps):
if not isinstance(raw, dict):
raise ValueError(f"step {index} must be an object")
kind = raw.get("kind")
if kind not in STEP_KINDS:
raise ValueError(f"step {index}: unknown kind {kind!r}")
if not raw.get("label"):
raise ValueError(f"step {index}: missing label")
_normalize_absent(raw)
for field in ("alt_texts", "alt_confirms", "alt_absents"):
if field in raw and isinstance(raw[field], list):
raw[field] = tuple(raw[field])
steps.append(ScriptStep(**raw))
total = len(steps)
for index, step in enumerate(steps):
for field, minimum in (("loop_to", 0), ("skip_to", 0)):
value = getattr(step, field)
if value >= minimum and value >= total:
raise ValueError(
f"step {index}: {field}={value} out of range (script has {total} steps)"
)
return steps
def _build_class(spec: dict, steps: list[ScriptStep], path: Path) -> type[BrowserScript]:
def name(self: BrowserScript) -> str:
return self.label
return type(
f"JsonScript_{spec['script_id']}",
(BrowserScript,),
{
"script_id": str(spec["script_id"]),
"label": str(spec["label"]),
"target_text": str(spec.get("target_text", "")),
"click_offset_y_ratio": float(spec.get("click_offset_y_ratio", 0.0)),
"steps": steps,
"name": name,
"__module__": f"data.scripts.{path.stem}",
},
)
def build_debug_script_class(raw_steps: list) -> type[BrowserScript]:
"""Build an ad-hoc script class from raw step dicts (the live debug panel).
Accepts the same step objects as the JSON files; missing labels are filled
in so a pasted single step runs as-is.
"""
if not isinstance(raw_steps, list) or not raw_steps:
raise ValueError("需要至少一个步骤对象")
steps: list[ScriptStep] = []
for index, raw in enumerate(raw_steps):
if not isinstance(raw, dict):
raise ValueError(f"step {index} 必须是 JSON 对象")
raw = dict(raw)
raw.setdefault("label", f"调试步骤 {index + 1}")
kind = raw.get("kind")
if kind not in STEP_KINDS:
raise ValueError(f"step {index}: unknown kind {kind!r}")
_normalize_absent(raw)
for field in ("alt_texts", "alt_confirms", "alt_absents"):
if field in raw and isinstance(raw[field], list):
raw[field] = tuple(raw[field])
try:
steps.append(ScriptStep(**raw))
except TypeError as exc:
raise ValueError(f"step {index}: {exc}") from exc
total = len(steps)
for index, step in enumerate(steps):
for field in ("loop_to", "skip_to"):
value = getattr(step, field)
if value >= total:
raise ValueError(
f"step {index}: {field}={value} 超出范围(共 {total} 步)"
)
return _build_class({"script_id": "_debug", "label": "实时调试步骤"}, steps, Path("debug"))
def load_script_classes(logger: "LoggerAdapter | None" = None) -> list[type[BrowserScript]]:
"""Return every valid script class from data/scripts/*.json.
Files are re-read whenever their mtime changes, so editing a script takes
effect immediately; broken files are skipped with one error logged per change.
"""
with _lock:
SCRIPT_DIR.mkdir(parents=True, exist_ok=True)
classes: list[type[BrowserScript]] = []
for path in sorted(SCRIPT_DIR.glob("*.json")):
try:
mtime = path.stat().st_mtime
except OSError:
continue
cached = _cache.get(path)
if cached is not None and cached[0] == mtime:
classes.append(cached[1])
continue
try:
spec = json.loads(path.read_text(encoding="utf-8"))
steps = _validate(spec, path)
script_class = _build_class(spec, steps, path)
except (json.JSONDecodeError, ValueError, TypeError) as exc:
message = f"invalid script file {path.name}: {exc}"
if _errors.get(path) != message:
_errors[path] = message
(logger or __import__("logging").getLogger(__name__)).error(message)
_cache.pop(path, None)
continue
_errors.pop(path, None)
_cache[path] = (mtime, script_class)
classes.append(script_class)
# Drop cache entries for files deleted from disk.
for path in list(_cache):
if not path.exists():
del _cache[path]
_errors.pop(path, None)
return classes

27
scripts/registry.py Normal file
View File

@ -0,0 +1,27 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from .base import BrowserScript
from .loader import load_script_classes
if TYPE_CHECKING:
from logging import LoggerAdapter
from desktop_app import BrowserInstance
from ocr_task import OCRService
def script_options(logger: "LoggerAdapter | None" = None) -> list[tuple[str, str]]:
"""List (script_id, label) pairs of every valid JSON script, re-reading changed files."""
return [
(script.script_id, script.label)
for script in load_script_classes(logger)
]
def create_script(script_id: str, instance: "BrowserInstance", ocr_service: "OCRService", logger: "LoggerAdapter") -> BrowserScript:
for script_class in load_script_classes(logger):
if script_class.script_id == script_id:
return script_class(instance, ocr_service, logger)
raise ValueError(f"未知脚本:{script_id}")

200
static/app.js Normal file
View File

@ -0,0 +1,200 @@
const form = document.querySelector("#run-form");
const instancesInput = document.querySelector("#instance-count");
const errorBox = document.querySelector("#form-error");
const runStatus = document.querySelector("#run-status");
const stopButton = document.querySelector("#stop-button");
const emptyState = document.querySelector("#empty-state");
const instanceGrid = document.querySelector("#instance-results");
const submitButton = form.querySelector("button[type=submit]");
let currentRunId = null;
let eventSource = null;
const imageModal = document.querySelector("#image-modal");
const modalImage = document.querySelector("#modal-image");
const modalCaption = document.querySelector("#modal-caption");
const interactionLayer = document.querySelector("#interaction-layer");
let controlSocket = null;
let activeInstance = null;
const VIEWPORT_WIDTH = 1365;
const VIEWPORT_HEIGHT = 860;
document.querySelectorAll("[data-step]").forEach((button) => {
button.addEventListener("click", () => {
const next = Math.max(1, Math.min(12, Number(instancesInput.value) + Number(button.dataset.step)));
instancesInput.value = next;
});
});
function setBusy(busy) {
submitButton.disabled = busy;
submitButton.querySelector("span").textContent = busy ? "运行中..." : "启动任务";
stopButton.disabled = !busy;
}
function closeLiveUpdates() {
if (eventSource) {
eventSource.close();
eventSource = null;
}
}
function connectLiveUpdates() {
closeLiveUpdates();
eventSource = new EventSource(`/api/runs/${currentRunId}/events`);
eventSource.onmessage = (event) => {
const run = JSON.parse(event.data);
renderRun(run);
if (!["运行中", "停止中"].includes(run.status)) closeLiveUpdates();
};
eventSource.onerror = () => {
if (eventSource?.readyState === EventSource.CLOSED) {
errorBox.textContent = "实时连接已断开,请刷新页面后重试";
setBusy(false);
}
};
}
function renderRun(run) {
runStatus.textContent = run.status;
errorBox.textContent = run.error || "";
const active = ["运行中", "停止中"].includes(run.status);
setBusy(active);
emptyState.hidden = true;
instanceGrid.hidden = false;
instanceGrid.replaceChildren();
run.instances.forEach((item) => {
const card = document.createElement("article");
card.className = "instance-card";
const top = document.createElement("div");
top.className = "instance-top";
const name = document.createElement("span");
name.className = "instance-name";
name.textContent = `INSTANCE ${String(item.id).padStart(2, "0")}`;
const status = document.createElement("span");
status.className = `instance-status ${item.status === "已完成" ? "done" : item.status === "失败" ? "failed" : ""}`;
status.textContent = item.status;
top.append(name, status);
card.append(top);
if (["打开页面", "识别文字", "实时监控", "已停止"].includes(item.status)) {
const image = document.createElement("img");
image.className = "thumb live-view zoomable";
image.src = `${item.stream}?v=${Date.now()}`;
image.alt = `实例 ${item.id} 实时画面`;
image.title = "点击放大实时画面";
image.addEventListener("click", () => {
activeInstance = item;
modalImage.src = `${item.stream}?view=large&v=${Date.now()}`;
modalCaption.textContent = `INSTANCE ${String(item.id).padStart(2, "0")} · 实时画面 · ${item.title || "加载中"}`;
imageModal.hidden = false;
document.body.classList.add("modal-open");
connectControlSocket(item.control);
interactionLayer.focus({ preventScroll: true });
});
card.append(image);
} else {
const placeholder = document.createElement("div");
placeholder.className = "thumb-placeholder";
placeholder.textContent = "正在连接实时画面";
card.append(placeholder);
}
const bottom = document.createElement("div");
bottom.className = "instance-bottom";
bottom.textContent = item.message || item.title || "正在准备...";
card.append(bottom);
instanceGrid.append(card);
});
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
errorBox.textContent = "";
const data = {
url: document.querySelector("#url").value,
instances: Number(instancesInput.value),
action_text: document.querySelector("#action-text").value,
};
try {
setBusy(true);
const response = await fetch("/api/runs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
const payload = await response.json();
if (!response.ok) throw new Error(payload.detail?.[0]?.msg || payload.detail || "任务创建失败");
currentRunId = payload.id;
renderRun(payload);
connectLiveUpdates();
} catch (error) {
errorBox.textContent = error.message;
setBusy(false);
}
});
stopButton.addEventListener("click", async () => {
if (!currentRunId) return;
await fetch(`/api/runs/${currentRunId}/stop`, { method: "POST" });
});
function closeImageModal() {
closeControlSocket();
imageModal.hidden = true;
modalImage.removeAttribute("src");
document.body.classList.remove("modal-open");
}
function connectControlSocket(path) {
closeControlSocket();
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
controlSocket = new WebSocket(`${protocol}//${window.location.host}${path}`);
}
function closeControlSocket() {
if (controlSocket) {
controlSocket.close();
controlSocket = null;
}
}
function sendControl(event) {
if (controlSocket?.readyState === WebSocket.OPEN) {
controlSocket.send(JSON.stringify(event));
}
}
interactionLayer.addEventListener("click", (event) => {
const rect = interactionLayer.getBoundingClientRect();
const x = ((event.clientX - rect.left) / rect.width) * VIEWPORT_WIDTH;
const y = ((event.clientY - rect.top) / rect.height) * VIEWPORT_HEIGHT;
sendControl({ type: "click", x, y, clickCount: event.detail || 1 });
});
interactionLayer.addEventListener("wheel", (event) => {
event.preventDefault();
sendControl({ type: "wheel", deltaX: event.deltaX, deltaY: event.deltaY });
}, { passive: false });
interactionLayer.addEventListener("keydown", (event) => {
if (["Control", "Meta", "Alt", "Shift"].includes(event.key)) return;
event.preventDefault();
const modifiers = [];
if (event.ctrlKey) modifiers.push("Control");
if (event.metaKey) modifiers.push("Meta");
if (event.altKey) modifiers.push("Alt");
if (event.shiftKey) modifiers.push("Shift");
sendControl({ type: "key", key: event.key, modifiers });
});
interactionLayer.addEventListener("paste", (event) => {
const text = event.clipboardData?.getData("text") || "";
if (text) {
event.preventDefault();
sendControl({ type: "text", value: text });
}
});
document.querySelector("#close-modal").addEventListener("click", closeImageModal);
imageModal.addEventListener("click", (event) => {
if (event.target === imageModal) closeImageModal();
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && !imageModal.hidden) closeImageModal();
});

110
static/index.html Normal file
View File

@ -0,0 +1,110 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Web 群控工作台</title>
<link rel="stylesheet" href="/static/style.css?v=20260825-2" />
</head>
<body>
<main class="shell">
<header class="topbar">
<div class="brand-mark">W</div>
<div>
<p class="eyebrow">LOCAL AUTOMATION CONSOLE</p>
<h1>Web 群控工作台</h1>
</div>
<span class="connection"><i></i> 本地服务已连接</span>
</header>
<section class="hero">
<div>
<p class="eyebrow">PLAYWRIGHT / PARALLEL SESSIONS</p>
<h2>同时打开多个页面,<br /><em>观察并执行同一项操作。</em></h2>
<p class="lede">输入一个可访问的网址,创建隔离的浏览器实例。每个实例都会持续返回当前页面画面和运行状态。</p>
</div>
<div class="hero-note">
<span class="note-number">01</span>
<span>任务控制<br />实时反馈</span>
</div>
</section>
<section class="workspace">
<form id="run-form" class="control-panel">
<div class="panel-heading">
<div>
<p class="eyebrow">NEW RUN</p>
<h3>创建控制任务</h3>
</div>
<span class="panel-index">A / 01</span>
</div>
<label for="url">目标网址</label>
<div class="url-input input-wrap">
<span>↗</span>
<input id="url" name="url" type="url" placeholder="https://example.com" required />
</div>
<div class="field-grid">
<div>
<label for="instance-count">并发实例</label>
<div class="stepper input-wrap">
<button type="button" data-step="-1" aria-label="减少实例">−</button>
<input id="instance-count" name="instances" type="number" min="1" max="12" value="3" />
<button type="button" data-step="1" aria-label="增加实例">+</button>
</div>
</div>
<div>
<label for="action-text">识别并点击文字 <span>可选</span></label>
<input id="action-text" name="action_text" type="text" maxlength="120" placeholder="例如:登录 / 提交" />
</div>
</div>
<div class="form-foot">
<p>每次任务最多运行 12 个隔离实例</p>
<button class="primary-button" type="submit"><span>启动任务</span><b>→</b></button>
</div>
<p id="form-error" class="form-error" role="alert"></p>
</form>
<aside class="info-panel">
<div class="panel-heading">
<div>
<p class="eyebrow">HOW IT WORKS</p>
<h3>执行流程</h3>
</div>
<span class="panel-index">B / 02</span>
</div>
<ol class="steps">
<li><span>01</span><div><strong>打开页面</strong><p>为每个实例创建独立会话</p></div></li>
<li><span>02</span><div><strong>识别内容</strong><p>按页面文字寻找目标元素</p></div></li>
<li><span>03</span><div><strong>实时监控</strong><p>持续显示每个浏览器当前画面</p></div></li>
</ol>
<div class="safe-note"><b>i</b><span>仅用于你有权操作的网站。请遵守目标网站的使用规则。</span></div>
</aside>
</section>
<section class="results-section">
<div class="results-heading">
<div><p class="eyebrow">LIVE MONITOR</p><h3>运行结果</h3></div>
<div class="run-meta"><span id="run-status">尚未启动任务</span><button id="stop-button" class="quiet-button" type="button" disabled>停止任务</button></div>
</div>
<div id="empty-state" class="empty-state"><span class="empty-icon">◎</span><p>填写网址后启动任务</p><small>实例状态会显示在这里</small></div>
<div id="instance-results" class="instance-grid" hidden></div>
</section>
<footer><span>WEB CONTROL / MVP 01</span><span>运行数据仅保存在当前进程内</span></footer>
</main>
<div id="image-modal" class="image-modal" hidden>
<div class="image-modal-content" role="dialog" aria-modal="true" aria-label="放大实时画面">
<button id="close-modal" class="modal-close" type="button" aria-label="关闭实时画面">×</button>
<div id="interactive-stage" class="interactive-stage">
<img id="modal-image" alt="放大后的实例实时画面" />
<div id="interaction-layer" class="interaction-layer" tabindex="0" aria-label="实例操作区域"></div>
</div>
<p id="modal-caption"></p>
</div>
</div>
<script src="/static/app.js?v=20260825-2"></script>
</body>
</html>

91
static/style.css Normal file
View File

@ -0,0 +1,91 @@
:root {
--ink: #202826;
--muted: #74807b;
--line: #dce3dd;
--paper: #f7f8f5;
--panel: #ffffff;
--lime: #d7f247;
--mint: #e8f1e7;
--red: #d96552;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; background: var(--paper); color: var(--ink); font-family: Inter, "PingFang SC", "Microsoft YaHei", sans-serif; }
.shell { width: min(1180px, calc(100% - 48px)); margin: 0 auto; }
.topbar { min-height: 104px; display: flex; align-items: center; gap: 14px; border-bottom: 1px solid var(--line); }
.brand-mark { width: 38px; height: 38px; display: grid; place-items: center; background: var(--ink); color: var(--lime); font-size: 19px; font-weight: 800; }
.eyebrow { margin: 0 0 8px; color: var(--muted); font: 600 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: 0; }
h1, h2, h3, p { margin-top: 0; }
h1 { margin: 0; font-size: 18px; letter-spacing: 0; }
.connection { margin-left: auto; display: inline-flex; align-items: center; gap: 8px; color: #59645f; font-size: 12px; }
.connection i { width: 7px; height: 7px; border-radius: 50%; background: #62bc68; box-shadow: 0 0 0 4px #dff0df; }
.hero { padding: 72px 0 63px; display: flex; justify-content: space-between; align-items: end; }
.hero > div:first-child { max-width: 780px; }
h2 { max-width: 780px; margin-bottom: 20px; font-size: clamp(38px, 4.7vw, 60px); line-height: 1.05; letter-spacing: -1px; }
h2 em { color: #788b28; font-style: normal; }
.lede { max-width: 580px; margin: 0; color: var(--muted); font-size: 15px; line-height: 1.8; }
.hero-note { display: flex; gap: 12px; align-items: start; color: #637069; font: 600 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
.note-number { color: var(--red); font-size: 22px; line-height: 1; }
.workspace { display: grid; grid-template-columns: minmax(0, 1.45fr) minmax(300px, .75fr); gap: 16px; }
.control-panel, .info-panel { background: var(--panel); border: 1px solid var(--line); padding: 30px; }
.panel-heading, .results-heading { display: flex; align-items: start; justify-content: space-between; gap: 16px; }
h3 { margin: 0; font-size: 22px; letter-spacing: 0; }
.panel-index { color: #aab4ae; font: 600 10px ui-monospace, SFMono-Regular, Menlo, monospace; }
label { display: block; margin: 32px 0 9px; color: #4f5b55; font-size: 12px; font-weight: 700; }
label span { color: #9da7a0; font-size: 10px; font-weight: 500; }
.input-wrap, input { height: 50px; border: 1px solid var(--line); background: #fbfcfa; }
.input-wrap { display: flex; align-items: center; }
.input-wrap input { width: 100%; border: 0; background: transparent; outline: 0; padding: 0 15px; color: var(--ink); font: inherit; }
.url-input > span { padding-left: 16px; color: var(--red); font-size: 19px; }
.field-grid { display: grid; grid-template-columns: 160px minmax(0, 1fr); gap: 18px; }
.field-grid label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.stepper { justify-content: space-between; padding: 0 6px; }
.stepper button { width: 36px; height: 36px; border: 0; background: transparent; color: #6f7d75; cursor: pointer; font-size: 24px; }
.stepper input { padding: 0; text-align: center; }
.field-grid > div:last-child input { width: 100%; padding: 0 15px; outline: 0; color: var(--ink); font: inherit; }
.form-foot { display: flex; align-items: center; justify-content: space-between; gap: 18px; margin-top: 31px; }
.form-foot p { margin: 0; color: #9aa39e; font-size: 11px; }
.primary-button { min-width: 132px; display: inline-flex; align-items: center; justify-content: space-between; gap: 24px; border: 0; padding: 0 15px 0 18px; height: 46px; background: var(--ink); color: white; cursor: pointer; font-weight: 700; }
.primary-button b { color: var(--lime); font-size: 22px; font-weight: 400; }
.primary-button:disabled { cursor: wait; opacity: .55; }
.form-error { min-height: 18px; margin: 12px 0 0; color: var(--red); font-size: 12px; }
.steps { list-style: none; padding: 0; margin: 34px 0 29px; }
.steps li { display: flex; gap: 15px; padding: 16px 0; border-top: 1px solid var(--line); }
.steps li:last-child { border-bottom: 1px solid var(--line); }
.steps li > span { color: var(--red); font: 600 11px ui-monospace, SFMono-Regular, Menlo, monospace; }
.steps strong { display: block; margin-bottom: 5px; font-size: 13px; }
.steps p { margin: 0; color: var(--muted); font-size: 11px; }
.safe-note { display: flex; gap: 10px; align-items: start; color: #7c8880; font-size: 11px; line-height: 1.6; }
.safe-note b { width: 16px; height: 16px; flex: 0 0 16px; display: grid; place-items: center; border-radius: 50%; background: var(--mint); color: #719071; font-size: 10px; }
.results-section { margin-top: 64px; padding-bottom: 64px; }
.run-meta { display: flex; align-items: center; gap: 17px; color: var(--muted); font-size: 12px; }
.quiet-button { border: 0; border-bottom: 1px solid #c4ccc5; padding: 4px 0; background: transparent; color: var(--red); cursor: pointer; font-size: 12px; }
.quiet-button:disabled { color: #adb6b0; cursor: not-allowed; }
.empty-state { margin-top: 22px; min-height: 180px; display: grid; place-items: center; align-content: center; border: 1px dashed #cfd8d1; color: var(--muted); }
.empty-icon { margin-bottom: 10px; color: #a9b6ad; font-size: 32px; }
.empty-state p { margin: 0 0 7px; font-size: 14px; }
.empty-state small { color: #a4ada7; font-size: 11px; }
.instance-grid { margin-top: 22px; display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
.instance-card { overflow: hidden; border: 1px solid var(--line); background: var(--panel); }
.instance-top { display: flex; justify-content: space-between; padding: 17px 17px 13px; }
.instance-name { font: 700 12px ui-monospace, SFMono-Regular, Menlo, monospace; }
.instance-status { color: #77847c; font-size: 11px; }
.instance-status.done { color: #5b9a58; }.instance-status.failed { color: var(--red); }
.thumb { width: 100%; aspect-ratio: 1.58; display: block; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); background: #edf1ed; object-fit: cover; }
.zoomable { cursor: zoom-in; transition: opacity .15s ease; }
.zoomable:hover { opacity: .78; }
.live-view { object-fit: contain; background: #151b18; }
.thumb-placeholder { aspect-ratio: 1.58; display: grid; place-items: center; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); color: #a2ada5; font-size: 12px; }
.instance-bottom { min-height: 53px; padding: 12px 17px; color: var(--muted); font-size: 11px; line-height: 1.5; }
footer { display: flex; justify-content: space-between; padding: 19px 0 25px; border-top: 1px solid var(--line); color: #a8b0aa; font: 10px ui-monospace, SFMono-Regular, Menlo, monospace; }
.modal-open { overflow: hidden; }
.image-modal { position: fixed; inset: 0; z-index: 20; display: grid; place-items: center; padding: 34px; background: rgba(22, 29, 26, .86); }
.image-modal-content { position: relative; width: min(1180px, 96vw); max-height: 92vh; display: grid; place-items: center; }
.interactive-stage { position: relative; width: min(1180px, 96vw); max-height: 82vh; aspect-ratio: 1365 / 860; background: #151b18; box-shadow: 0 18px 60px rgba(0, 0, 0, .28); }
.interactive-stage img { width: 100%; height: 100%; display: block; object-fit: contain; }
.interaction-layer { position: absolute; inset: 0; outline: 0; cursor: crosshair; }
.interaction-layer:focus { box-shadow: inset 0 0 0 2px rgba(215, 242, 71, .7); }
.image-modal-content p { margin: 14px 0 0; color: #dce6df; font: 11px ui-monospace, SFMono-Regular, Menlo, monospace; }
.modal-close { position: absolute; top: -28px; right: -6px; width: 36px; height: 36px; border: 1px solid rgba(255, 255, 255, .35); background: transparent; color: #fff; cursor: pointer; font-size: 25px; line-height: 1; }
@media (max-width: 720px) { .shell { width: min(100% - 28px, 1180px); }.topbar { min-height: 78px; }.connection { font-size: 0; }.hero { padding: 48px 0 40px; }.hero-note { display: none; } h2 { font-size: 40px; }.workspace { grid-template-columns: 1fr; }.control-panel, .info-panel { padding: 22px; }.field-grid { grid-template-columns: 1fr; gap: 0; }.form-foot, .results-heading, footer { align-items: start; flex-direction: column; }.results-section { margin-top: 42px; }.run-meta { width: 100%; justify-content: space-between; } }