chore: 删除抖音养号任务类型,平台只保留 generic_steps

tasks/douyin/(task_type=douyin_nurture)整体删除,唯一任务类型是 generic_steps。
所有默认值/文档/接口示例同步改成 generic_steps:

- tasks/:删 douyin 包;__init__ 只注册 generic;base.py/generic 注释改为照 generic 抄
- 默认值:core/models.py(列默认 + 旧 JSON 迁移默认)、core/task_manager.py TaskJob、
  web/tasks_api.py 建任务默认、static/admin/tasks.js 新建任务默认
- core/task_manager.py:去掉 douyin 专属的"清理废弃 comment 参数"迁移块,改为**启动时告警**
  仍残留已删类型的任务(只告警不改数据);run_job_now 对已删类型直接返回明确错误,
  不再"报已触发、线程里静默失败"
- 清理残留:douyin_running 状态位(无任何读取方)、core/__init__、core/actions/*、
  core/logger.py 注释里的抖音示例
- 文档:README(特性/目录树/类型表/参数表/示例)、TASK_DEV(目录树/注册说明/模板引用)、
  ARCHITECTURE(注册示例/action 注册表示例)、API.md(task_types 与任务 JSON 示例)、
  AI_TASK_GEN(P1 去掉 douyin 预设)、DEVELOPMENT
- 注:示例里"抖音"作为**App 名**(MCP 列应用、AI 建任务的需求举例)保留,与任务类型无关

自测(全部通过):类型列表只剩 generic_steps;建任务不传类型默认 generic_steps;传
douyin_nurture 被 400 拒;库里塞残留旧类型任务 → 启动日志告警 + 执行返回明确错误 +
不自动删用户数据;前端新建任务下拉 1 项且默认选中、界面建任务成功;监控页卡片两个按钮 +
覆盖设备正常。临时任务/数据验完已清理,任务集合复原。
This commit is contained in:
2026-09-10 21:43:08 +08:00
parent 86c65236a2
commit 98cdc39224
23 changed files with 75 additions and 555 deletions
+1 -1
View File
@@ -7,7 +7,7 @@
from .base import BaseTask, register_task, list_task_types, get_task_class
# 导入所有任务包,触发 @register_task 注册
from .douyin import task # noqa: F401
# 当前只有一个任务类型:generic_steps(通用步骤,前端步骤编辑器编排)
from .generic import task # noqa: F401
__all__ = ["BaseTask", "register_task", "list_task_types", "get_task_class"]
+1 -1
View File
@@ -12,7 +12,7 @@
base.py — 本任务的操作基类 + 注册器
xxx.py — 具体操作
新增任务步骤(照着 tasks/douyin/ 抄即可):
新增任务步骤(照着 tasks/generic/ 抄即可):
1. 在 tasks/ 下新建 my_task/ 子包(文件夹 + __init__.py)
2. 在 my_task/task.py 顶部写默认参数:
-9
View File
@@ -1,9 +0,0 @@
"""抖音养号任务包。
本包自包含:任务定义(task.py)+ 抖音专属操作(actions/)。
抖音的点赞/评论 xpath 只适用于抖音,不放全局,避免和其他任务混淆。
加新抖音操作:在 actions/ 下建 .py,继承本包 BaseAction + @register_action,
在 actions/__init__.py import。
"""
from . import task # noqa: F401 触发 @register_task 注册抖音任务
-21
View File
@@ -1,21 +0,0 @@
"""抖音操作注册包。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
@@ -1,51 +0,0 @@
"""抖音操作基类与注册机制。
操作 = 抖音养号主循环里某个时机执行的一次具体行为(点赞/评论/关注等)。
这里的注册表只对抖音任务生效,其他任务有自己的 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)
-108
View File
@@ -1,108 +0,0 @@
"""抖音点赞操作。
两种方式:
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
# 找不到点赞按钮:跳过本次,不点屏幕,避免误触(如直播/无点赞按钮的页面)
worker.set_action("点赞(未找到,跳过)")
return False
# 仅在明确选择 double_click 方式时才双击屏幕
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
@@ -1,269 +0,0 @@
"""抖音养号任务定义。
本文件自包含所有抖音养号参数(观看、滑动、操作等),不依赖 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, serial, params=None):
super().__init__(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, 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(serial, params=merged)
+1 -1
View File
@@ -1,6 +1,6 @@
"""通用步骤任务包。
通过前端步骤编辑器编排任务流程,worker 按 steps 顺序执行。
与 douyin_nurture 共存,互不影响。
当前平台唯一的任务类型(task_type=generic_steps)。
"""
from . import task # noqa: F401 触发 @register_task 注册通用步骤任务
+1 -1
View File
@@ -167,7 +167,7 @@ class GenericStepsWorker(BaseWorker):
finally:
elapsed = self.elapsed()
summary = f"完成步骤链,运行 {elapsed//60}m{elapsed%60}s"
_update_status(self.serial, douyin_running=False, current_action=summary)
_update_status(self.serial, current_action=summary)
def _exec_steps(self, d, steps, depth=0):
"""执行步骤列表。depth 防止无限嵌套。"""