chore: 初始化仓库(排除 adb 二进制文件以解决推送超时)

This commit is contained in:
2026-08-07 13:55:48 +08:00
commit bce48fc137
35 changed files with 6301 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
"""tasks 包:任务定义层。
每个任务一个独立子包(文件夹),自包含任务定义 + 专属操作 + 参数。
新增任务:在此目录新建 xxx/ 子包,定义 BaseTask 子类并用 @register_task 装饰,
然后在这里 import(from .xxx import task)。
"""
from .base import BaseTask, register_task, list_task_types, get_task_class
# 导入所有任务包,触发 @register_task 注册
from .douyin import task # noqa: F401
__all__ = ["BaseTask", "register_task", "list_task_types", "get_task_class"]
+120
View File
@@ -0,0 +1,120 @@
"""任务类型基类与注册机制。
目录约定:
config.py — 项目根配置(STF/adb/web 等,核心程序用,不放任务参数)
core/ — 核心程序(STF、adb、BaseWorker、任务管理器)
tasks/ — 任务包,每个任务一个子文件夹,自包含任务+专属操作+参数
tasks/<name>/
__init__.py — import task 触发注册
task.py — BaseTask 子类 + Worker + DEFAULT_PARAMS
actions/ — 该任务专属操作(xpath 等只适用于本任务,不污染全局)
__init__.py
base.py — 本任务的操作基类 + 注册器
xxx.py — 具体操作
新增任务步骤(照着 tasks/douyin/ 抄即可):
1. 在 tasks/ 下新建 my_task/ 子包(文件夹 + __init__.py)
2. 在 my_task/task.py 顶部写默认参数:
DEFAULT_PARAMS = {"loop": 10, "actions": {...}}
3. 写一个 BaseWorker 子类,实现 run_task(d):
from core.device_worker import BaseWorker, _update_status
class MyWorker(BaseWorker):
def run_task(self, d): # d 是 u2.Device,基类已连好
d.app_start("com.xxx", wait=True)
while not self.stopped():
self.set_action("干活中")
self.set_progress(done=1)
4. 写一个 BaseTask 子类,用 @register_task 装饰,实现 create_worker:
@register_task
class MyTask(BaseTask):
task_type = "my_task"
name = "我的任务"
default_params = dict(DEFAULT_PARAMS)
# 有专属操作时重写这两个方法,从 actions 包取
@classmethod
def list_action_types(cls):
from .actions import list_action_types
return list_action_types()
@classmethod
def get_action_class(cls, action_type):
from .actions import get_action_class
return get_action_class(action_type)
def create_worker(self, stf, serial, params):
return MyWorker(stf, serial, params=params)
5. 在 my_task/__init__.py 加:from . import task (触发注册)
6. 在 tasks/__init__.py 加:from .my_task import task (触发注册)
做完前端自动出现新任务。有专属操作时前端"操作"区自动列出。
BaseWorker 已封装好的(子类不用管):
- STF 占用/释放(try/finally 保证释放)
- adb 连接 / u2.connect
- 状态上报(status/current_action/last_error/model/remote_adb_url)
- 异常捕获(run_task 里抛异常 → status=error,设备仍会释放)
- stop 信号(self.stopped() 检查)
子类可用的工具:
self.stopped() — 是否被要求停止
self.set_action(s) — 上报当前动作
self.set_progress() — 上报进度字段
self.d — u2.Device
self.params — 任务参数 dict
core.u2_helper — 通用 u2 辅助函数(ensure_app_running/safe_click 等)
"""
class BaseTask:
"""任务类型基类。子类实现 create_worker。
有专属操作的任务重写 list_action_types / get_action_class,
从自己的 actions 子包取(操作 xpath 等只适用于本任务)。
"""
task_type = "base"
name = "基础任务"
description = ""
default_params = {}
def create_worker(self, stf, serial, params):
"""返回一个 threading.Thread(已启动或待启动),执行实际任务。"""
raise NotImplementedError
@classmethod
def list_action_types(cls):
"""返回本任务支持的操作列表。默认无操作,子类按需重写。"""
return []
@classmethod
def get_action_class(cls, action_type):
"""按 action_type 取操作类。默认无操作,子类按需重写。"""
return None
_TASK_TYPES = {}
def register_task(task_cls):
"""注册新任务类型。用作装饰器。"""
_TASK_TYPES[task_cls.task_type] = task_cls
return task_cls
def list_task_types():
"""返回所有已注册任务类型的元信息(供前端展示)。"""
return [{"task_type": t.task_type, "name": t.name, "description": t.description,
"default_params": t.default_params} for t in _TASK_TYPES.values()]
def get_task_class(task_type):
"""按 task_type 取任务类。"""
return _TASK_TYPES.get(task_type)
+9
View File
@@ -0,0 +1,9 @@
"""抖音养号任务包。
本包自包含:任务定义(task.py)+ 抖音专属操作(actions/)。
抖音的点赞/评论 xpath 只适用于抖音,不放全局,避免和其他任务混淆。
加新抖音操作:在 actions/ 下建 .py,继承本包 BaseAction + @register_action,
在 actions/__init__.py import。
"""
from . import task # noqa: F401 触发 @register_task 注册抖音任务
+21
View File
@@ -0,0 +1,21 @@
"""抖音操作注册包。import 触发各操作注册。
加新抖音操作:新建 xxx.py,在下面加一行 from . import xxx。
注意:必须先从 base 导入 ACTIONS,再导入各操作模块,否则循环导入。
"""
# 先初始化注册表(base.py 里定义了 ACTIONS = create_action_registry())
from .base import (
BaseAction, register_action, create_action_registry,
list_actions, get_action, should_trigger,
ACTIONS,
list_action_types, get_action_class,
)
# 再导入各操作模块,触发 @register_action(ACTIONS) 注册
from . import like # noqa: F401
__all__ = [
"BaseAction", "register_action", "create_action_registry",
"list_actions", "get_action", "should_trigger",
"ACTIONS", "list_action_types", "get_action_class",
]
+51
View File
@@ -0,0 +1,51 @@
"""抖音操作基类与注册机制。
操作 = 抖音养号主循环里某个时机执行的一次具体行为(点赞/评论/关注等)。
这里的注册表只对抖音任务生效,其他任务有自己的 actions 包。
设计:抖音的 ACTIONS 注册表是独立的 dict,用 core.actions 的
register_action(ACTIONS) 装饰器注册,和全局/其他 app 互不污染。
新增抖音操作步骤(照着 like.py 抄):
1. 在 tasks/douyin/actions/ 下新建 my_action.py
2. 写一个 BaseAction 子类,用 @register_action 装饰,实现 execute:
from core.actions import BaseAction, register_action, should_trigger
from . import ACTIONS # 本任务注册表
@register_action(ACTIONS)
class MyAction(BaseAction):
action_type = "my_action"
name = "我的操作"
description = "做什么"
default_params = {"rate": 0.5}
def execute(self, d, params, worker):
if not should_trigger(params["rate"]):
return False
# ... 用 d(xpath=...) / d(text=...) 操作
return True
3. 在 tasks/douyin/actions/__init__.py 加一行:from . import my_action
做完前端自动出现该操作的可勾选项。
"""
from core.actions import (
BaseAction, register_action, create_action_registry,
list_actions, get_action, should_trigger,
)
# 抖音专属操作注册表(独立 dict,不污染其他 app)
ACTIONS = create_action_registry()
# 兼容旧导入:tasks/douyin/actions/__init__.py 原来从这里导出
def list_action_types():
"""返回所有已注册抖音操作的元信息(供前端展示)。"""
return list_actions(ACTIONS)
def get_action_class(action_type):
"""按 action_type 取抖音操作类。"""
return get_action(ACTIONS, action_type)
+105
View File
@@ -0,0 +1,105 @@
"""抖音点赞操作。
两种方式:
by_element — 用 xpath 找右侧红心按钮点击(相对定位,不依赖视频卡片序号)
double_click — 双击屏幕中央(兜底,不依赖元素,抖音"双击点赞"手势)
定位器随抖音版本变,by_element 找不到会自动回退双击,不会卡住。
要适配新版本抖音:用 weditor 重新抓当前界面,调整下面定位逻辑。
"""
from core.actions import BaseAction, register_action, should_trigger
from core.logger import get_logger
from . import ACTIONS
_log = get_logger("action.like")
@register_action(ACTIONS)
class LikeAction(BaseAction):
action_type = "like"
name = "点赞"
description = "看完视频后随机点赞(找红心按钮,找不到回退双击)"
default_params = {
"rate": 0.3, # 触发概率 0~1
"method": "by_element", # by_element=找红心 | double_click=双击屏幕
}
def execute(self, d, params, worker):
rate = float(params.get("rate", 0.3))
if not should_trigger(rate):
return False
method = params.get("method", "by_element")
if method == "by_element":
if self._like_by_element(d):
worker.set_action("点赞(红心)")
return True
# 找不到红心,回退双击
ok = self._double_click_center(d)
if ok:
worker.set_action("点赞(双击)")
return ok
@staticmethod
def _like_by_element(d):
"""找右侧操作栏红心按钮点击,成功返回 True。
定位优先级:description 精确 → descriptionContains 模糊 → resourceId → xpath
每种方式找到即点即返回,找不到继续下一种。全程记日志。
"""
# 方式1:description 精确匹配(最稳,不依赖结构)
for desc in ("点赞", "未点赞", "like"):
el = d(description=desc)
if el.exists:
el.click()
_log.info(f"like 命中 description={desc}")
return True
# 方式2:descriptionContains 模糊匹配(适配不同版本文案)
for kw in ("赞", "like"):
el = d(descriptionContains=kw)
if el.exists:
el.click()
_log.info(f"like 命中 descriptionContains={kw}")
return True
# 方式3:resourceId 列表(扩充候选,覆盖更多抖音版本)
for rid in ("com.ss.android.ugc.aweme:id/aky",
"com.ss.android.ugc.aweme:id/d-like-view-icon",
"com.ss.android.ugc.aweme:id/h3r",
"com.ss.android.ugc.aweme:id/dfz",
"com.ss.android.ugc.aweme:id/c5w"):
el = d(resourceId=rid)
if el.exists:
el.click()
_log.info(f"like 命中 resourceId={rid}")
return True
# 方式4:xpath 相对定位——右侧操作栏 LinearLayout 的第一个 ImageView
# 定位思路:ViewPager 下当前 FrameLayout 里的 LinearLayout,
# 取其直接子 FrameLayout 里的第一个 ImageView(点赞在操作栏最上方)
try:
el = d.xpath(
'//androidx.viewpager.widget.ViewPager'
'/android.widget.FrameLayout'
'/com.bytedance.highperformanceview.layout.MeasureOnceRelativeLayout2'
'/com.bytedance.highperformanceview.layout.MeasureOnceRelativeLayout2'
'/android.widget.LinearLayout/android.widget.FrameLayout[2]'
'/android.widget.LinearLayout/android.widget.FrameLayout[1]'
'/android.widget.FrameLayout[1]/android.widget.ImageView'
)
if el.exists:
el.click()
_log.info("like 命中 xpath")
return True
except Exception as e:
_log.warning(f"like xpath 异常: {e}")
_log.info("like_by_element 全部失败,准备回退双击")
return False
@staticmethod
def _double_click_center(d):
"""双击屏幕中央点赞。按屏幕尺寸算坐标,适配不同分辨率。"""
try:
info = d.info
w, h = info["displayWidth"], info["displayHeight"]
d.double_click(int(w * 0.5), int(h * 0.5))
return True
except Exception:
return False
+269
View File
@@ -0,0 +1,269 @@
"""抖音养号任务定义。
本文件自包含所有抖音养号参数(观看、滑动、操作等),不依赖 core 的业务配置。
抖音专属操作(点赞/评论)在 actions/ 子包里,xpath 只适用于抖音。
修改养号行为:改下面 DEFAULT_PARAMS 默认值,或通过前端任务参数覆盖。
修改养号逻辑:改 DouyinNurtureWorker.run_task。
加新抖音操作:在 actions/ 下建 .py,继承 BaseAction + @register_action。
"""
import time
import random
from tasks.base import BaseTask, register_task
from .actions import list_action_types, get_action_class
from core.device_worker import BaseWorker, _update_status
from core.u2_helper import ensure_app_running, wait_for_app_home
from core.logger import get_logger
_log = get_logger("task.douyin")
# ================== 抖音养号参数(本任务专属,写在这里) ==================
DOUYIN_PKG = "com.ss.android.ugc.aweme"
DEFAULT_PARAMS = {
# 观看
"watch_count": 80, # 观看视频数量(0=不限数量,仅按 max_duration 终止)
"watch_min": 5.0, # 单个视频最短观看秒数
"watch_max": 35.0, # 单个视频最长观看秒数
# 运行时长终止(通用,0=不限时,按 watch_count 终止)
# 两个条件哪个先到就停;都为 0 则永不停止(需手动停止)
"max_duration": 0, # 最大运行时长(秒),如 1800=30分钟,0=不限时
# 滑动
"swipe_min": 0.25, # 上滑手势最短时长(秒)
"swipe_max": 0.50, # 上滑手势最长时长(秒)
"gap_min": 1.0, # 视频间隔最短秒数
"gap_max": 3.0, # 视频间隔最长秒数
# 操作(每个操作有 enabled 开关 + 自身参数)
"actions": {
"like": {
"enabled": True,
"params": {"rate": 0.3, "method": "by_element"},
},
},
}
class DouyinNurtureWorker(BaseWorker):
"""抖音养号 worker:看视频 + 按配置执行操作(点赞/评论等),被退出自动重连。
只需实现 run_task(d),STF 占用/释放、u2 连接、异常、状态上报由基类处理。
操作参数优先级:任务 params.actions > 本文件 DEFAULT_PARAMS.actions。
"""
def __init__(self, stf_client, serial, params=None):
super().__init__(stf_client, serial, params)
p = {**DEFAULT_PARAMS, **(self.params or {})}
self.watch_count = int(p["watch_count"])
self.watch_min = float(p["watch_min"])
self.watch_max = float(p["watch_max"])
# 通用运行时长终止(0=不限时)
self.max_duration = int(p.get("max_duration", 0))
self.swipe_min = float(p["swipe_min"])
self.swipe_max = float(p["swipe_max"])
self.gap_min = float(p["gap_min"])
self.gap_max = float(p["gap_max"])
# 操作配置:{action_type: {"enabled":bool, "params":{...}}}
self.actions_cfg = p.get("actions", {})
# 实例化所有启用的操作
self._actions = []
for atype, cfg in self.actions_cfg.items():
if not cfg.get("enabled"):
continue
cls = get_action_class(atype)
if cls:
self._actions.append(cls())
# 启动日志:打印终止条件 + 启用的 action,便于排查
stop_conds = []
if self.watch_count > 0:
stop_conds.append(f"数量={self.watch_count}")
if self.max_duration > 0:
stop_conds.append(f"时长={self.max_duration}s")
if not stop_conds:
stop_conds.append("无(需手动停止)")
_log.info(f"[{serial}] 终止条件: {', '.join(stop_conds)}")
if self._actions:
summary = ", ".join(
f"{a.action_type}(rate={self.actions_cfg.get(a.action_type, {}).get('params', {}).get('rate', '?')})"
for a in self._actions
)
_log.info(f"[{serial}] 启用操作: {summary}")
else:
_log.warning(f"[{serial}] 未启用任何操作,整个任务期间不会执行点赞")
def run_task(self, d):
"""抖音养号主逻辑。d 是 u2.Device,已由基类连好。
终止条件(哪个先到就停):
- watch_count > 0:看完指定数量视频
- max_duration > 0:达到最大运行时长
- 两者都为 0:永不停止,需手动停止
"""
def is_home(d):
return (d(descriptionContains="拍摄").exists
or d(descriptionContains="首页").exists)
# 启动运行时长计时(基类通用方法)
self._start_timer()
d.app_start(DOUYIN_PKG, wait=True)
if not wait_for_app_home(d, DOUYIN_PKG, is_home, timeout=40):
self.set_action("首页加载超时,继续尝试")
watched = 0
action_counts = {a.action_type: 0 for a in self._actions}
# 初始化通用进度上报
# total=0 时前端不显示百分比,只显示已看数量 + 运行时长
total = self.watch_count if self.watch_count > 0 else 0
self.set_progress(done=0, total=total, unit="视频",
action_counts=action_counts)
while not self.stopped():
# 终止条件检查
if self.watch_count > 0 and watched >= self.watch_count:
break
if self.is_time_up():
_log.info(f"[{self.serial}] 达到最大运行时长 {self.max_duration}s,停止")
break
if not ensure_app_running(d, DOUYIN_PKG):
_update_status(self.serial, status="error",
last_error="抖音连续重启失败,放弃该设备")
return
_update_status(self.serial, douyin_running=True, last_error="")
watch = random.uniform(self.watch_min, self.watch_max)
# 动作描述包含运行时长,便于前端观察
elapsed = self.elapsed()
time_info = f",已运行 {elapsed//60}m{elapsed%60}s" if elapsed > 0 else ""
self.set_action(f"观看视频 {watched+1},{watch:.0f}s{time_info}")
time.sleep(watch)
# 检测当前是否为可操作的正常视频页(有右侧操作栏 = 点赞/评论按钮)
# 营销广告、直播、异常页通常没有这些元素,直接滑过去不做操作
is_normal = self._is_normal_video(d)
if is_normal:
# 正常视频:执行所有启用的操作(看完视频后、滑动前)
if not self._actions:
_log.info(f"[{self.serial}] 视频{watched+1}: 正常视频但无启用操作")
for action in self._actions:
if self.stopped():
break
cfg = self.actions_cfg.get(action.action_type, {})
params = {**action.default_params, **cfg.get("params", {})}
rate = params.get("rate", "?")
try:
ok = action.execute(d, params, self)
_log.info(f"[{self.serial}] 视频{watched+1}: {action.action_type} "
f"rate={rate} execute={ok}")
if ok:
action_counts[action.action_type] += 1
time.sleep(random.uniform(0.5, 1.5))
except Exception as e:
_log.error(f"[{self.serial}] 视频{watched+1}: 操作 {action.action_type} "
f"异常: {e}")
else:
self.set_action(f"跳过广告/直播 {watched+1}")
_log.info(f"[{self.serial}] 视频{watched+1}: 非正常视频页,跳过操作")
if self.stopped():
break
d.swipe(500, 1000, 500, 300, random.uniform(self.swipe_min, self.swipe_max))
time.sleep(random.uniform(self.gap_min, self.gap_max))
watched += 1
# 上报通用进度(含运行时长,前端展示)
elapsed = self.elapsed()
self.set_progress(done=watched, total=total, unit="视频",
action_counts=dict(action_counts),
elapsed=elapsed)
# 终止原因汇总
stop_reason = ""
if self.stopped():
stop_reason = "(手动停止)"
elif self.is_time_up():
stop_reason = f"(达到时长 {self.max_duration}s)"
elif self.watch_count > 0 and watched >= self.watch_count:
stop_reason = f"(达到数量 {self.watch_count})"
summary = f"完成 {watched} 个视频" + "".join(
f",{k} {v}次" for k, v in action_counts.items() if v
) + stop_reason
_update_status(self.serial, douyin_running=False, current_action=summary)
@staticmethod
def _is_normal_video(d):
"""判断当前是否为可操作的正常视频页。
正常视频页右侧有操作栏(点赞/评论/分享按钮)。
营销广告、直播、异常页通常没有这些元素 → 返回 False,直接滑过去。
检测任一特征元素存在即认为是正常视频页。
定位优先级:description 精确 → descriptionContains 模糊 → resourceId 列表 → 兜底
每次返回 False 时记日志,便于定位"为什么操作没执行"。
"""
try:
# 1. description 精确匹配(最稳)
for desc in ("点赞", "未点赞", "评论", "未评论"):
if d(description=desc).exists:
return True
# 2. descriptionContains 模糊匹配(适配不同版本文案)
for kw in ("赞", "评论"):
if d(descriptionContains=kw).exists:
return True
# 3. resourceId 列表(扩充候选,覆盖更多抖音版本)
for rid in ("com.ss.android.ugc.aweme:id/aky",
"com.ss.android.ugc.aweme:id/akq",
"com.ss.android.ugc.aweme:id/d-like-view-icon",
"com.ss.android.ugc.aweme:id/d-comment-view-icon",
"com.ss.android.ugc.aweme:id/h3r"):
if d(resourceId=rid).exists:
return True
# 所有特征元素都没找到 → 非正常视频页(广告/直播/异常)
_log.info(f"_is_normal_video=False: 未找到点赞/评论特征元素")
return False
except Exception as e:
_log.warning(f"_is_normal_video 异常: {e}")
return False
@register_task
class DouyinNurtureTask(BaseTask):
"""抖音养号:看视频 + 按配置执行操作(点赞/评论等),被退出自动重连。"""
task_type = "douyin_nurture"
name = "抖音养号"
description = "自动观看抖音视频,按配置执行点赞/评论等操作,被退出自动重连"
default_params = dict(DEFAULT_PARAMS)
@classmethod
def list_action_types(cls):
"""返回本任务支持的抖音操作列表。"""
return list_action_types()
@classmethod
def get_action_class(cls, action_type):
"""按 action_type 取抖音操作类。"""
return get_action_class(action_type)
def create_worker(self, stf, serial, params):
merged = {**DEFAULT_PARAMS, **(params or {})}
# actions 字段深合并(参数级,保留前端没传的操作默认值)
# 确保即使前端只传 actions.like.enabled,like.params.rate 也能拿到默认 0.3
default_actions = DEFAULT_PARAMS["actions"]
merged_actions = params.get("actions", {}) if params else {}
for atype, dflt in default_actions.items():
if atype not in merged_actions:
# 前端完全没传这个操作 → 用默认
merged_actions[atype] = dflt
else:
# 前端传了 → 参数级深合并
cfg = merged_actions[atype]
merged_cfg = {}
for k in ("enabled", "params"):
merged_cfg[k] = cfg.get(k, dflt.get(k))
# params 再深合并一层
merged_params = dict(dflt.get("params", {}))
merged_params.update(cfg.get("params", {}))
merged_cfg["params"] = merged_params
merged_actions[atype] = merged_cfg
merged["actions"] = merged_actions
return DouyinNurtureWorker(stf, serial, params=merged)