重构douyin上传,增加douyin图文
修复douyin视频封面上传
This commit is contained in:
@@ -0,0 +1,67 @@
|
|||||||
|
# CLI 使用说明
|
||||||
|
|
||||||
|
项目现在提供一个更直接的抖音 CLI 入口,默认推荐使用 `sau`。
|
||||||
|
|
||||||
|
实现说明:
|
||||||
|
|
||||||
|
- `sau_cli.py` 是当前 CLI 的主入口和唯一主要实现文件
|
||||||
|
|
||||||
|
## 抖音 CLI 子命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sau douyin login --account creator
|
||||||
|
sau douyin check --account creator
|
||||||
|
sau douyin upload-video --account creator --file videos/demo.mp4 --title "示例标题" --tags 运动,训练
|
||||||
|
sau douyin upload-note --account creator --images videos/1.png videos/2.png --note "图文示例" --tags 图文,测试
|
||||||
|
```
|
||||||
|
|
||||||
|
## 定时发布
|
||||||
|
|
||||||
|
视频和图文都支持 `--schedule`。只要传了 `--schedule`,CLI 就会自动切换到 `scheduled` 发布策略;不传则默认立即发布。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sau douyin upload-video --account creator --file videos/demo.mp4 --title "示例标题" --schedule "2026-03-24 21:30"
|
||||||
|
sau douyin upload-note --account creator --images videos/1.png videos/2.png --note "图文示例" --schedule "2026-03-24 21:30"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 运行时参数
|
||||||
|
|
||||||
|
CLI 将 `debug` 和 `headless` 拆成了两个独立维度:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
--debug
|
||||||
|
--headless
|
||||||
|
--headed
|
||||||
|
```
|
||||||
|
|
||||||
|
- `--debug`: 打开调试行为,例如失败时保留更多调试信息
|
||||||
|
- `--headless`: 无头模式运行
|
||||||
|
- `--headed`: 有头模式运行
|
||||||
|
|
||||||
|
如果都不传,CLI 当前默认按 `headless=True` 运行。
|
||||||
|
|
||||||
|
## 视频上传参数
|
||||||
|
|
||||||
|
```bash
|
||||||
|
--file videos/demo.mp4
|
||||||
|
--title "示例标题"
|
||||||
|
--tags 运动,训练
|
||||||
|
--thumbnail videos/demo.png
|
||||||
|
--product-link https://example.com/item
|
||||||
|
--product-title 示例商品
|
||||||
|
```
|
||||||
|
|
||||||
|
## 图文上传参数
|
||||||
|
|
||||||
|
```bash
|
||||||
|
--images videos/1.png videos/2.png videos/3.png
|
||||||
|
--note "图文内容"
|
||||||
|
--tags 图文,测试
|
||||||
|
```
|
||||||
|
|
||||||
|
图文上传当前限制:
|
||||||
|
|
||||||
|
- 最多 35 张图片
|
||||||
|
- 不支持 GIF
|
||||||
|
|
||||||
|
仓库内的轻量 skill 源位于 `skills/douyin-cli/`,后续维护 CLI 时应优先以这里和 `social_auto_upload/` 下的新入口为准。
|
||||||
-101
@@ -1,101 +0,0 @@
|
|||||||
import argparse
|
|
||||||
import asyncio
|
|
||||||
from datetime import datetime
|
|
||||||
from os.path import exists
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from conf import BASE_DIR
|
|
||||||
from uploader.douyin_uploader.main import douyin_setup, DouYinVideo
|
|
||||||
from uploader.ks_uploader.main import ks_setup, KSVideo
|
|
||||||
from uploader.tencent_uploader.main import weixin_setup, TencentVideo
|
|
||||||
from uploader.tk_uploader.main_chrome import tiktok_setup, TiktokVideo
|
|
||||||
from utils.base_social_media import get_supported_social_media, get_cli_action, SOCIAL_MEDIA_DOUYIN, \
|
|
||||||
SOCIAL_MEDIA_TENCENT, SOCIAL_MEDIA_TIKTOK, SOCIAL_MEDIA_KUAISHOU
|
|
||||||
from utils.constant import TencentZoneTypes
|
|
||||||
from utils.files_times import get_title_and_hashtags
|
|
||||||
|
|
||||||
|
|
||||||
def parse_schedule(schedule_raw):
|
|
||||||
if schedule_raw:
|
|
||||||
schedule = datetime.strptime(schedule_raw, '%Y-%m-%d %H:%M')
|
|
||||||
else:
|
|
||||||
schedule = None
|
|
||||||
return schedule
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
# 主解析器
|
|
||||||
parser = argparse.ArgumentParser(description="Upload video to multiple social-media.")
|
|
||||||
parser.add_argument("platform", metavar='platform', choices=get_supported_social_media(), help="Choose social-media platform: douyin tencent tiktok kuaishou")
|
|
||||||
|
|
||||||
parser.add_argument("account_name", type=str, help="Account name for the platform: xiaoA")
|
|
||||||
subparsers = parser.add_subparsers(dest="action", metavar='action', help="Choose action", required=True)
|
|
||||||
|
|
||||||
actions = get_cli_action()
|
|
||||||
for action in actions:
|
|
||||||
action_parser = subparsers.add_parser(action, help=f'{action} operation')
|
|
||||||
if action == 'login':
|
|
||||||
# Login 不需要额外参数
|
|
||||||
continue
|
|
||||||
elif action == 'upload':
|
|
||||||
action_parser.add_argument("video_file", help="Path to the Video file")
|
|
||||||
action_parser.add_argument("-pt", "--publish_type", type=int, choices=[0, 1],
|
|
||||||
help="0 for immediate, 1 for scheduled", default=0)
|
|
||||||
action_parser.add_argument('-t', '--schedule', help='Schedule UTC time in %Y-%m-%d %H:%M format')
|
|
||||||
|
|
||||||
# 解析命令行参数
|
|
||||||
args = parser.parse_args()
|
|
||||||
# 参数校验
|
|
||||||
if args.action == 'upload':
|
|
||||||
if not exists(args.video_file):
|
|
||||||
raise FileNotFoundError(f'Could not find the video file at {args["video_file"]}')
|
|
||||||
if args.publish_type == 1 and not args.schedule:
|
|
||||||
parser.error("The schedule must must be specified for scheduled publishing.")
|
|
||||||
|
|
||||||
account_file = Path(BASE_DIR / "cookies" / f"{args.platform}_{args.account_name}.json")
|
|
||||||
account_file.parent.mkdir(exist_ok=True)
|
|
||||||
|
|
||||||
# 根据 action 处理不同的逻辑
|
|
||||||
if args.action == 'login':
|
|
||||||
print(f"Logging in with account {args.account_name} on platform {args.platform}")
|
|
||||||
if args.platform == SOCIAL_MEDIA_DOUYIN:
|
|
||||||
await douyin_setup(str(account_file), handle=True)
|
|
||||||
elif args.platform == SOCIAL_MEDIA_TIKTOK:
|
|
||||||
await tiktok_setup(str(account_file), handle=True)
|
|
||||||
elif args.platform == SOCIAL_MEDIA_TENCENT:
|
|
||||||
await weixin_setup(str(account_file), handle=True)
|
|
||||||
elif args.platform == SOCIAL_MEDIA_KUAISHOU:
|
|
||||||
await ks_setup(str(account_file), handle=True)
|
|
||||||
elif args.action == 'upload':
|
|
||||||
title, tags = get_title_and_hashtags(args.video_file)
|
|
||||||
video_file = args.video_file
|
|
||||||
|
|
||||||
if args.publish_type == 0:
|
|
||||||
print("Uploading immediately...")
|
|
||||||
publish_date = 0
|
|
||||||
else:
|
|
||||||
print("Scheduling videos...")
|
|
||||||
publish_date = parse_schedule(args.schedule)
|
|
||||||
|
|
||||||
if args.platform == SOCIAL_MEDIA_DOUYIN:
|
|
||||||
await douyin_setup(account_file, handle=False)
|
|
||||||
app = DouYinVideo(title, video_file, tags, publish_date, account_file)
|
|
||||||
elif args.platform == SOCIAL_MEDIA_TIKTOK:
|
|
||||||
await tiktok_setup(account_file, handle=True)
|
|
||||||
app = TiktokVideo(title, video_file, tags, publish_date, account_file)
|
|
||||||
elif args.platform == SOCIAL_MEDIA_TENCENT:
|
|
||||||
await weixin_setup(account_file, handle=True)
|
|
||||||
category = TencentZoneTypes.LIFESTYLE.value # 标记原创需要否则不需要传
|
|
||||||
app = TencentVideo(title, video_file, tags, publish_date, account_file, category)
|
|
||||||
elif args.platform == SOCIAL_MEDIA_KUAISHOU:
|
|
||||||
await ks_setup(account_file, handle=True)
|
|
||||||
app = KSVideo(title, video_file, tags, publish_date, account_file)
|
|
||||||
else:
|
|
||||||
print("Wrong platform, please check your input")
|
|
||||||
exit()
|
|
||||||
|
|
||||||
await app.main()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import asyncio
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from conf import BASE_DIR
|
||||||
|
from uploader.douyin_uploader.main import (
|
||||||
|
DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
|
||||||
|
DOUYIN_PUBLISH_STRATEGY_SCHEDULED,
|
||||||
|
DouYinNote,
|
||||||
|
DouYinVideo,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upload_video_to_douyin():
|
||||||
|
account_file = Path(BASE_DIR / "cookies" / "douyin_uploader" / "account.json")
|
||||||
|
video_file_path = Path(BASE_DIR) / "videos/demo.mp4"
|
||||||
|
video_meta_title = "男子为了心爱之人每天坚守❤️🩹"
|
||||||
|
video_meta_hashtags = ["坚持不懈", "爱情执着", "奋斗使者", "短视频"]
|
||||||
|
thumbnail_landscape_path = Path(BASE_DIR) / "videos/demo.png"
|
||||||
|
thumbnail_portrait_path = Path(BASE_DIR) / "videos/demo.png"
|
||||||
|
video_meta_publish_time = datetime.strptime("2026-3-25 12:13", "%Y-%m-%d %H:%M")
|
||||||
|
|
||||||
|
app = DouYinVideo(
|
||||||
|
title=video_meta_title,
|
||||||
|
file_path=video_file_path,
|
||||||
|
tags=video_meta_hashtags,
|
||||||
|
publish_date=video_meta_publish_time,
|
||||||
|
thumbnail_landscape_path=thumbnail_landscape_path,
|
||||||
|
thumbnail_portrait_path=thumbnail_portrait_path,
|
||||||
|
account_file=account_file,
|
||||||
|
publish_strategy=DOUYIN_PUBLISH_STRATEGY_SCHEDULED,
|
||||||
|
)
|
||||||
|
asyncio.run(app.douyin_upload_video())
|
||||||
|
|
||||||
|
|
||||||
|
def upload_note_to_douyin():
|
||||||
|
account_file = Path(BASE_DIR / "cookies" / "douyin_uploader" / "account.json")
|
||||||
|
image_paths = [Path(BASE_DIR) / "videos/demo.png", Path(BASE_DIR) / "videos/demo.png", Path(BASE_DIR) / "videos/demo.png"]
|
||||||
|
note = "图文内容示例"
|
||||||
|
tags = ["图文", "示例", "抖音图文"]
|
||||||
|
video_meta_publish_time = datetime.strptime("2026-3-25 12:13", "%Y-%m-%d %H:%M")
|
||||||
|
|
||||||
|
|
||||||
|
app = DouYinNote(
|
||||||
|
image_paths=image_paths,
|
||||||
|
note=note,
|
||||||
|
tags=tags,
|
||||||
|
publish_date=0,
|
||||||
|
account_file=account_file,
|
||||||
|
publish_strategy=DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
|
||||||
|
)
|
||||||
|
asyncio.run(app.douyin_upload_note())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# upload_video_to_douyin()
|
||||||
|
upload_note_to_douyin()
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from conf import BASE_DIR
|
|
||||||
from uploader.douyin_uploader.main import douyin_setup, DouYinVideo
|
|
||||||
from utils.files_times import generate_schedule_time_next_day, get_title_and_hashtags
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
filepath = Path(BASE_DIR) / "videos"
|
|
||||||
account_file = Path(BASE_DIR / "cookies" / "douyin_uploader" / "account.json")
|
|
||||||
# 获取视频目录
|
|
||||||
folder_path = Path(filepath)
|
|
||||||
# 获取文件夹中的所有文件
|
|
||||||
files = list(folder_path.glob("*.mp4"))
|
|
||||||
file_num = len(files)
|
|
||||||
publish_datetimes = generate_schedule_time_next_day(file_num, 1, daily_times=[16])
|
|
||||||
cookie_setup = asyncio.run(douyin_setup(account_file, handle=False))
|
|
||||||
for index, file in enumerate(files):
|
|
||||||
title, tags = get_title_and_hashtags(str(file))
|
|
||||||
thumbnail_path = file.with_suffix('.png')
|
|
||||||
# 打印视频文件名、标题和 hashtag
|
|
||||||
print(f"视频文件名:{file}")
|
|
||||||
print(f"标题:{title}")
|
|
||||||
print(f"Hashtag:{tags}")
|
|
||||||
# 暂时没有时间修复封面上传,故先隐藏掉该功能
|
|
||||||
# if thumbnail_path.exists():
|
|
||||||
# app = DouYinVideo(title, file, tags, publish_datetimes[index], account_file, thumbnail_path=thumbnail_path)
|
|
||||||
# else:
|
|
||||||
app = DouYinVideo(title, file, tags, publish_datetimes[index], account_file)
|
|
||||||
asyncio.run(app.main(), debug=False)
|
|
||||||
@@ -47,7 +47,7 @@ def post_video_DouYin(title,files,tags,account_file,category=TencentZoneTypes.LI
|
|||||||
print(f"标题:{title}")
|
print(f"标题:{title}")
|
||||||
print(f"Hashtag:{tags}")
|
print(f"Hashtag:{tags}")
|
||||||
app = DouYinVideo(title, str(file), tags, publish_datetimes[index], cookie, thumbnail_path, productLink, productTitle)
|
app = DouYinVideo(title, str(file), tags, publish_datetimes[index], cookie, thumbnail_path, productLink, productTitle)
|
||||||
asyncio.run(app.main(), debug=False)
|
asyncio.run(app.douyin_upload_video(), debug=False)
|
||||||
|
|
||||||
|
|
||||||
def post_video_ks(title,files,tags,account_file,category=TencentZoneTypes.LIFESTYLE.value,enableTimer=False,videos_per_day = 1, daily_times=None,start_days = 0):
|
def post_video_ks(title,files,tags,account_file,category=TencentZoneTypes.LIFESTYLE.value,enableTimer=False,videos_per_day = 1, daily_times=None,start_days = 0):
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=69"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "social-auto-upload"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Social media auto uploader"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.10,<3.13"
|
||||||
|
dependencies = [
|
||||||
|
"loguru==0.7.3",
|
||||||
|
"opencv-python>=4.13.0.92",
|
||||||
|
"patchright==1.58.2",
|
||||||
|
"qrcode==8.2",
|
||||||
|
"requests==2.32.3",
|
||||||
|
"segno>=1.6.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
sau = "sau_cli:main"
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
bilibili = [
|
||||||
|
"biliup==0.4.98",
|
||||||
|
]
|
||||||
|
|
||||||
|
web = [
|
||||||
|
"Flask[async]==3.1.1",
|
||||||
|
"flask-cors==6.0.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.uv]
|
||||||
|
package = true
|
||||||
|
|
||||||
|
[tool.setuptools]
|
||||||
|
py-modules = ["cli_main", "conf", "sau_cli"]
|
||||||
|
include-package-data = true
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
include = ["uploader*", "utils*", "myUtils*"]
|
||||||
|
|
||||||
|
[tool.setuptools.package-data]
|
||||||
|
utils = ["stealth.min.js"]
|
||||||
+266
@@ -0,0 +1,266 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Iterable, Sequence
|
||||||
|
|
||||||
|
from conf import BASE_DIR
|
||||||
|
from uploader.douyin_uploader.main import (
|
||||||
|
DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
|
||||||
|
DOUYIN_PUBLISH_STRATEGY_SCHEDULED,
|
||||||
|
DouYinNote,
|
||||||
|
DouYinVideo,
|
||||||
|
cookie_auth,
|
||||||
|
douyin_setup,
|
||||||
|
)
|
||||||
|
|
||||||
|
SCHEDULE_FORMAT = "%Y-%m-%d %H:%M"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class DouyinVideoUploadRequest:
|
||||||
|
account_name: str
|
||||||
|
video_file: Path
|
||||||
|
title: str
|
||||||
|
tags: list[str]
|
||||||
|
publish_date: datetime | int
|
||||||
|
thumbnail_file: Path | None = None
|
||||||
|
product_link: str = ""
|
||||||
|
product_title: str = ""
|
||||||
|
publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE
|
||||||
|
debug: bool = True
|
||||||
|
headless: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class DouyinNoteUploadRequest:
|
||||||
|
account_name: str
|
||||||
|
image_files: list[Path]
|
||||||
|
note: str
|
||||||
|
tags: list[str]
|
||||||
|
publish_date: datetime | int
|
||||||
|
publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE
|
||||||
|
debug: bool = True
|
||||||
|
headless: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_runtime_home() -> Path:
|
||||||
|
return Path(BASE_DIR)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_account_file(account_name: str) -> Path:
|
||||||
|
account_file = resolve_runtime_home() / "cookies" / f"douyin_{account_name}.json"
|
||||||
|
account_file.parent.mkdir(exist_ok=True)
|
||||||
|
return account_file
|
||||||
|
|
||||||
|
|
||||||
|
def parse_tags(raw_tags: str | None) -> list[str]:
|
||||||
|
if not raw_tags:
|
||||||
|
return []
|
||||||
|
|
||||||
|
tags: list[str] = []
|
||||||
|
for item in raw_tags.split(","):
|
||||||
|
cleaned = item.strip().lstrip("#")
|
||||||
|
if cleaned:
|
||||||
|
tags.append(cleaned)
|
||||||
|
return tags
|
||||||
|
|
||||||
|
|
||||||
|
def parse_image_files(raw_files: Iterable[Path]) -> list[Path]:
|
||||||
|
return [Path(file) for file in raw_files]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_schedule(raw_schedule: str | None) -> datetime | int:
|
||||||
|
if not raw_schedule:
|
||||||
|
return 0
|
||||||
|
return datetime.strptime(raw_schedule, SCHEDULE_FORMAT)
|
||||||
|
|
||||||
|
|
||||||
|
async def login_account(account_name: str) -> Path:
|
||||||
|
account_file = resolve_account_file(account_name)
|
||||||
|
await douyin_setup(str(account_file), handle=True)
|
||||||
|
return account_file
|
||||||
|
|
||||||
|
|
||||||
|
async def check_account(account_name: str) -> bool:
|
||||||
|
account_file = resolve_account_file(account_name)
|
||||||
|
if not account_file.exists():
|
||||||
|
return False
|
||||||
|
return await cookie_auth(str(account_file))
|
||||||
|
|
||||||
|
|
||||||
|
async def upload_video(request: DouyinVideoUploadRequest) -> Path:
|
||||||
|
account_file = resolve_account_file(request.account_name)
|
||||||
|
is_ready = await douyin_setup(str(account_file), handle=False)
|
||||||
|
if not is_ready:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Douyin cookie is missing or expired: {account_file}. Run `sau douyin login --account {request.account_name}` first."
|
||||||
|
)
|
||||||
|
|
||||||
|
app = DouYinVideo(
|
||||||
|
request.title,
|
||||||
|
str(request.video_file),
|
||||||
|
request.tags,
|
||||||
|
request.publish_date,
|
||||||
|
str(account_file),
|
||||||
|
thumbnail_portrait_path=str(request.thumbnail_file) if request.thumbnail_file else None,
|
||||||
|
productLink=request.product_link,
|
||||||
|
productTitle=request.product_title,
|
||||||
|
publish_strategy=request.publish_strategy,
|
||||||
|
debug=request.debug,
|
||||||
|
headless=request.headless,
|
||||||
|
)
|
||||||
|
await app.douyin_upload_video()
|
||||||
|
return account_file
|
||||||
|
|
||||||
|
|
||||||
|
async def upload_note(request: DouyinNoteUploadRequest) -> Path:
|
||||||
|
account_file = resolve_account_file(request.account_name)
|
||||||
|
is_ready = await douyin_setup(str(account_file), handle=False)
|
||||||
|
if not is_ready:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Douyin cookie is missing or expired: {account_file}. Run `sau douyin login --account {request.account_name}` first."
|
||||||
|
)
|
||||||
|
|
||||||
|
app = DouYinNote(
|
||||||
|
image_paths=[str(path) for path in request.image_files],
|
||||||
|
note=request.note,
|
||||||
|
tags=request.tags,
|
||||||
|
publish_date=request.publish_date,
|
||||||
|
account_file=str(account_file),
|
||||||
|
publish_strategy=request.publish_strategy,
|
||||||
|
debug=request.debug,
|
||||||
|
headless=request.headless,
|
||||||
|
)
|
||||||
|
await app.douyin_upload_note()
|
||||||
|
return account_file
|
||||||
|
|
||||||
|
|
||||||
|
def existing_file_path(value: str) -> Path:
|
||||||
|
path = Path(value)
|
||||||
|
if not path.is_file():
|
||||||
|
raise argparse.ArgumentTypeError(f"File not found: {value}")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def schedule_value(value: str):
|
||||||
|
try:
|
||||||
|
return parse_schedule(value)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise argparse.ArgumentTypeError(
|
||||||
|
f"Invalid schedule '{value}'. Expected format: {SCHEDULE_FORMAT}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def add_runtime_flags(parser: argparse.ArgumentParser) -> None:
|
||||||
|
parser.add_argument("--debug", action="store_true", help="Enable debug mode")
|
||||||
|
headless_group = parser.add_mutually_exclusive_group()
|
||||||
|
headless_group.add_argument("--headed", dest="headless", action="store_false", help="Run with browser UI")
|
||||||
|
headless_group.add_argument("--headless", dest="headless", action="store_true", help="Run in headless mode")
|
||||||
|
parser.set_defaults(headless=True)
|
||||||
|
|
||||||
|
|
||||||
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
|
schedule_help = SCHEDULE_FORMAT.replace("%", "%%")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="sau",
|
||||||
|
description="CLI for social-auto-upload.",
|
||||||
|
)
|
||||||
|
platform_parsers = parser.add_subparsers(dest="platform", required=True)
|
||||||
|
|
||||||
|
douyin_parser = platform_parsers.add_parser("douyin", help="Douyin operations")
|
||||||
|
douyin_actions = douyin_parser.add_subparsers(dest="action", required=True)
|
||||||
|
|
||||||
|
for action_name in ("login", "check"):
|
||||||
|
action_parser = douyin_actions.add_parser(action_name, help=f"Douyin {action_name}")
|
||||||
|
action_parser.add_argument("--account", required=True, help="Douyin account alias")
|
||||||
|
|
||||||
|
upload_video_parser = douyin_actions.add_parser("upload-video", help="Upload one video to Douyin")
|
||||||
|
upload_video_parser.add_argument("--account", required=True, help="Douyin account alias")
|
||||||
|
upload_video_parser.add_argument("--file", required=True, type=existing_file_path, help="Video file path")
|
||||||
|
upload_video_parser.add_argument("--title", required=True, help="Video title")
|
||||||
|
upload_video_parser.add_argument("--tags", default="", help="Comma-separated tags, such as tag1,tag2")
|
||||||
|
upload_video_parser.add_argument("--schedule", type=schedule_value, help=f"Schedule time in {schedule_help}")
|
||||||
|
upload_video_parser.add_argument("--thumbnail", type=existing_file_path, help="Optional thumbnail path")
|
||||||
|
upload_video_parser.add_argument("--product-link", default="", help="Optional product link")
|
||||||
|
upload_video_parser.add_argument("--product-title", default="", help="Optional product title")
|
||||||
|
add_runtime_flags(upload_video_parser)
|
||||||
|
|
||||||
|
upload_note_parser = douyin_actions.add_parser("upload-note", help="Upload one note to Douyin")
|
||||||
|
upload_note_parser.add_argument("--account", required=True, help="Douyin account alias")
|
||||||
|
upload_note_parser.add_argument("--images", required=True, nargs="+", type=existing_file_path, help="Image file paths")
|
||||||
|
upload_note_parser.add_argument("--note", required=True, help="Note content")
|
||||||
|
upload_note_parser.add_argument("--tags", default="", help="Comma-separated tags, such as tag1,tag2")
|
||||||
|
upload_note_parser.add_argument("--schedule", type=schedule_value, help=f"Schedule time in {schedule_help}")
|
||||||
|
add_runtime_flags(upload_note_parser)
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
async def dispatch(args: argparse.Namespace) -> int:
|
||||||
|
if args.platform != "douyin":
|
||||||
|
raise RuntimeError(f"Unsupported platform: {args.platform}")
|
||||||
|
|
||||||
|
if args.action == "login":
|
||||||
|
account_file = await login_account(args.account)
|
||||||
|
print(f"Douyin login flow completed: {account_file}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if args.action == "check":
|
||||||
|
is_valid = await check_account(args.account)
|
||||||
|
print("valid" if is_valid else "invalid")
|
||||||
|
return 0 if is_valid else 1
|
||||||
|
|
||||||
|
publish_strategy = DOUYIN_PUBLISH_STRATEGY_SCHEDULED if args.schedule else DOUYIN_PUBLISH_STRATEGY_IMMEDIATE
|
||||||
|
|
||||||
|
if args.action == "upload-video":
|
||||||
|
request = DouyinVideoUploadRequest(
|
||||||
|
account_name=args.account,
|
||||||
|
video_file=args.file,
|
||||||
|
title=args.title,
|
||||||
|
tags=parse_tags(args.tags),
|
||||||
|
publish_date=args.schedule or 0,
|
||||||
|
thumbnail_file=args.thumbnail,
|
||||||
|
product_link=args.product_link,
|
||||||
|
product_title=args.product_title,
|
||||||
|
publish_strategy=publish_strategy,
|
||||||
|
debug=args.debug,
|
||||||
|
headless=args.headless,
|
||||||
|
)
|
||||||
|
await upload_video(request)
|
||||||
|
print(f"Douyin video upload submitted: {request.video_file}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if args.action == "upload-note":
|
||||||
|
request = DouyinNoteUploadRequest(
|
||||||
|
account_name=args.account,
|
||||||
|
image_files=parse_image_files(args.images),
|
||||||
|
note=args.note,
|
||||||
|
tags=parse_tags(args.tags),
|
||||||
|
publish_date=args.schedule or 0,
|
||||||
|
publish_strategy=publish_strategy,
|
||||||
|
debug=args.debug,
|
||||||
|
headless=args.headless,
|
||||||
|
)
|
||||||
|
await upload_note(request)
|
||||||
|
print(f"Douyin note upload submitted: {len(request.image_files)} images")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
raise RuntimeError(f"Unsupported Douyin action: {args.action}")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: Sequence[str] | None = None) -> int:
|
||||||
|
parser = build_parser()
|
||||||
|
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||||
|
try:
|
||||||
|
return asyncio.run(dispatch(args))
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc), file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
class BaseVideoUploader:
|
||||||
|
SUPPORTED_VIDEO_EXTENSIONS = {
|
||||||
|
".mp4",
|
||||||
|
".mov",
|
||||||
|
".avi",
|
||||||
|
".mkv",
|
||||||
|
".m4v",
|
||||||
|
".webm",
|
||||||
|
".flv",
|
||||||
|
".wmv",
|
||||||
|
}
|
||||||
|
SUPPORTED_IMAGE_EXTENSIONS = {
|
||||||
|
".jpg",
|
||||||
|
".jpeg",
|
||||||
|
".png",
|
||||||
|
".webp",
|
||||||
|
".bmp",
|
||||||
|
}
|
||||||
|
MIN_SCHEDULE_LEAD_TIME = timedelta(hours=2)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate_video_file(cls, file_path: str | Path) -> Path:
|
||||||
|
path = Path(file_path).expanduser().resolve()
|
||||||
|
if not path.exists():
|
||||||
|
raise FileNotFoundError(f"视频文件不存在: {path}")
|
||||||
|
if not path.is_file():
|
||||||
|
raise ValueError(f"视频路径不是文件: {path}")
|
||||||
|
if path.suffix.lower() not in cls.SUPPORTED_VIDEO_EXTENSIONS:
|
||||||
|
raise ValueError(
|
||||||
|
f"不支持的视频格式: {path.suffix},当前支持: {', '.join(sorted(cls.SUPPORTED_VIDEO_EXTENSIONS))}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return path
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate_image_file(cls, file_path: str | Path) -> Path:
|
||||||
|
path = Path(file_path).expanduser().resolve()
|
||||||
|
if not path.exists():
|
||||||
|
raise FileNotFoundError(f"图片文件不存在: {path}")
|
||||||
|
if not path.is_file():
|
||||||
|
raise ValueError(f"图片路径不是文件: {path}")
|
||||||
|
if path.suffix.lower() not in cls.SUPPORTED_IMAGE_EXTENSIONS:
|
||||||
|
raise ValueError(
|
||||||
|
f"不支持的图片格式: {path.suffix},当前支持: {', '.join(sorted(cls.SUPPORTED_IMAGE_EXTENSIONS))}"
|
||||||
|
)
|
||||||
|
return path
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate_publish_date(cls, publish_date: datetime | int | None) -> datetime | int:
|
||||||
|
if publish_date in (None, 0):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if not isinstance(publish_date, datetime):
|
||||||
|
raise TypeError("publish_date 必须是 datetime 类型或 0")
|
||||||
|
|
||||||
|
now = datetime.now(tz=publish_date.tzinfo) if publish_date.tzinfo else datetime.now()
|
||||||
|
if publish_date <= now:
|
||||||
|
raise ValueError("定时发布时间必须晚于当前时间")
|
||||||
|
|
||||||
|
min_publish_time = now + cls.MIN_SCHEDULE_LEAD_TIME
|
||||||
|
if publish_date <= min_publish_time:
|
||||||
|
raise ValueError("定时发布时间必须大于当前时间 2 小时")
|
||||||
|
|
||||||
|
return publish_date
|
||||||
+525
-272
@@ -1,86 +1,214 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from playwright.async_api import Playwright, async_playwright, Page
|
|
||||||
import os
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import inspect
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from conf import LOCAL_CHROME_PATH, LOCAL_CHROME_HEADLESS
|
from patchright.async_api import Page
|
||||||
|
from patchright.async_api import Playwright
|
||||||
|
from patchright.async_api import async_playwright
|
||||||
|
|
||||||
|
from conf import DEBUG_MODE, LOCAL_CHROME_HEADLESS, LOCAL_CHROME_PATH
|
||||||
|
from uploader.base_video import BaseVideoUploader
|
||||||
from utils.base_social_media import set_init_script
|
from utils.base_social_media import set_init_script
|
||||||
|
from utils.login_qrcode import build_login_qrcode_path
|
||||||
|
from utils.login_qrcode import decode_qrcode_from_path
|
||||||
|
from utils.login_qrcode import print_terminal_qrcode
|
||||||
|
from utils.login_qrcode import remove_qrcode_file
|
||||||
|
from utils.login_qrcode import save_data_url_image
|
||||||
from utils.log import douyin_logger
|
from utils.log import douyin_logger
|
||||||
|
|
||||||
|
DOUYIN_PUBLISH_STRATEGY_IMMEDIATE = "immediate"
|
||||||
|
DOUYIN_PUBLISH_STRATEGY_SCHEDULED = "scheduled"
|
||||||
|
|
||||||
|
|
||||||
|
async def _emit_qrcode_callback(qrcode_callback, payload: dict):
|
||||||
|
if not qrcode_callback:
|
||||||
|
return
|
||||||
|
|
||||||
|
callback_result = qrcode_callback(payload)
|
||||||
|
if inspect.isawaitable(callback_result):
|
||||||
|
await callback_result
|
||||||
|
|
||||||
|
|
||||||
|
def _build_login_result(success: bool, status: str, message: str, account_file: str, qrcode: dict | None = None, current_url: str = "") -> dict:
|
||||||
|
return {
|
||||||
|
"success": success,
|
||||||
|
"status": status,
|
||||||
|
"message": message,
|
||||||
|
"account_file": str(account_file),
|
||||||
|
"qrcode": qrcode,
|
||||||
|
"current_url": current_url,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async def cookie_auth(account_file):
|
async def cookie_auth(account_file):
|
||||||
async with async_playwright() as playwright:
|
async with async_playwright() as playwright:
|
||||||
browser = await playwright.chromium.launch(headless=LOCAL_CHROME_HEADLESS)
|
browser = await playwright.chromium.launch(headless=True, channel="chrome")
|
||||||
context = await browser.new_context(storage_state=account_file)
|
context = await browser.new_context(storage_state=account_file)
|
||||||
context = await set_init_script(context)
|
context = await set_init_script(context)
|
||||||
# 创建一个新的页面
|
|
||||||
page = await context.new_page()
|
page = await context.new_page()
|
||||||
# 访问指定的 URL
|
|
||||||
await page.goto("https://creator.douyin.com/creator-micro/content/upload")
|
await page.goto("https://creator.douyin.com/creator-micro/content/upload")
|
||||||
try:
|
try:
|
||||||
await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload", timeout=5000)
|
await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload", timeout=5000)
|
||||||
except:
|
except Exception:
|
||||||
print("[+] 等待5秒 cookie 失效")
|
print("[+] 等待5秒 cookie 失效")
|
||||||
await context.close()
|
await context.close()
|
||||||
await browser.close()
|
await browser.close()
|
||||||
return False
|
return False
|
||||||
# 2024.06.17 抖音创作者中心改版
|
|
||||||
if await page.get_by_text('手机号登录').count() or await page.get_by_text('扫码登录').count():
|
if await page.get_by_text("手机号登录").count() or await page.get_by_text("扫码登录").count():
|
||||||
print("[+] 等待5秒 cookie 失效")
|
print("[+] 等待5秒 cookie 失效")
|
||||||
return False
|
return False
|
||||||
else:
|
|
||||||
print("[+] cookie 有效")
|
print("[+] cookie 有效")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def douyin_setup(account_file, handle=False):
|
async def douyin_setup(account_file, handle=False, return_detail=False, qrcode_callback=None):
|
||||||
if not os.path.exists(account_file) or not await cookie_auth(account_file):
|
if not os.path.exists(account_file) or not await cookie_auth(account_file):
|
||||||
if not handle:
|
if not handle:
|
||||||
# Todo alert message
|
result = _build_login_result(False, "cookie_invalid", "cookie文件不存在或已失效", account_file)
|
||||||
return False
|
return result if return_detail else False
|
||||||
douyin_logger.info('[+] cookie文件不存在或已失效,即将自动打开浏览器,请扫码登录,登陆后会自动生成cookie文件')
|
douyin_logger.info("[+] cookie文件不存在或已失效,即将自动打开浏览器,请扫码登录,登陆后会自动生成cookie文件")
|
||||||
await douyin_cookie_gen(account_file)
|
result = await douyin_cookie_gen(account_file, qrcode_callback=qrcode_callback)
|
||||||
return True
|
return result if return_detail else result["success"]
|
||||||
|
|
||||||
|
result = _build_login_result(True, "cookie_valid", "cookie有效", account_file)
|
||||||
|
return result if return_detail else True
|
||||||
|
|
||||||
|
|
||||||
async def douyin_cookie_gen(account_file):
|
async def _extract_douyin_qrcode_src(page: Page) -> str:
|
||||||
|
scan_login_tab = page.get_by_text("扫码登录", exact=True).first
|
||||||
|
await scan_login_tab.wait_for(timeout=30000)
|
||||||
|
|
||||||
|
qrcode_img = (
|
||||||
|
scan_login_tab
|
||||||
|
.locator("..")
|
||||||
|
.locator("xpath=following-sibling::div[1]")
|
||||||
|
.locator('img[aria-label="二维码"]')
|
||||||
|
.first
|
||||||
|
)
|
||||||
|
|
||||||
|
if not await qrcode_img.count():
|
||||||
|
qrcode_img = page.get_by_role("img", name="二维码").first
|
||||||
|
|
||||||
|
await qrcode_img.wait_for(state="visible", timeout=30000)
|
||||||
|
src = await qrcode_img.get_attribute("src")
|
||||||
|
if not src:
|
||||||
|
raise RuntimeError("未获取到抖音登录二维码地址")
|
||||||
|
|
||||||
|
return src
|
||||||
|
|
||||||
|
|
||||||
|
async def _save_douyin_qrcode(page: Page, account_file: str, previous_qrcode_path: Path | None = None, qrcode_callback=None) -> dict:
|
||||||
|
qrcode_src = await _extract_douyin_qrcode_src(page)
|
||||||
|
qrcode_path = save_data_url_image(qrcode_src, build_login_qrcode_path(account_file))
|
||||||
|
if previous_qrcode_path and previous_qrcode_path != qrcode_path:
|
||||||
|
if remove_qrcode_file(previous_qrcode_path):
|
||||||
|
douyin_logger.info(f"[+] 已删除临时二维码文件: {previous_qrcode_path}")
|
||||||
|
douyin_logger.info(f"[+] 已提取抖音登录二维码并保存到: {qrcode_path}")
|
||||||
|
qrcode_content = decode_qrcode_from_path(qrcode_path)
|
||||||
|
if qrcode_content:
|
||||||
|
print_terminal_qrcode(qrcode_content, qrcode_path, "抖音APP")
|
||||||
|
else:
|
||||||
|
douyin_logger.warning(f"[!] 无法将二维码打印到控制台,请打开 {qrcode_path} 扫码")
|
||||||
|
qrcode_info = {
|
||||||
|
"image_path": str(qrcode_path),
|
||||||
|
"image_data_url": qrcode_src,
|
||||||
|
}
|
||||||
|
await _emit_qrcode_callback(qrcode_callback, qrcode_info)
|
||||||
|
return qrcode_info
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_douyin_login(page: Page, account_file: str, qrcode_info: dict, qrcode_callback=None, poll_interval: int = 3, max_checks: int = 100) -> dict:
|
||||||
|
qrcode_path = Path(qrcode_info["image_path"])
|
||||||
|
for _ in range(max_checks):
|
||||||
|
if page.url.startswith("https://creator.douyin.com/creator-micro/home"):
|
||||||
|
douyin_logger.info(f"[+] 检测到已跳转到登录后页面: {page.url}")
|
||||||
|
return _build_login_result(True, "success", "抖音扫码登录成功", account_file, qrcode_info, page.url)
|
||||||
|
|
||||||
|
expired_box = page.get_by_text("二维码失效", exact=True).locator("..").first
|
||||||
|
if await expired_box.count() and await expired_box.is_visible():
|
||||||
|
douyin_logger.warning("[!] 二维码失效,正在刷新二维码...")
|
||||||
|
await expired_box.click()
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
qrcode_info = await _save_douyin_qrcode(page, account_file, qrcode_path, qrcode_callback=qrcode_callback)
|
||||||
|
qrcode_path = Path(qrcode_info["image_path"])
|
||||||
|
|
||||||
|
await asyncio.sleep(poll_interval)
|
||||||
|
|
||||||
|
return _build_login_result(False, "timeout", "等待抖音扫码登录超时", account_file, qrcode_info, page.url)
|
||||||
|
|
||||||
|
|
||||||
|
async def douyin_cookie_gen(account_file, qrcode_callback=None, poll_interval: int = 3, max_checks: int = 100):
|
||||||
async with async_playwright() as playwright:
|
async with async_playwright() as playwright:
|
||||||
options = {
|
browser = await playwright.chromium.launch(headless=True, channel="chrome")
|
||||||
'headless': LOCAL_CHROME_HEADLESS
|
context = await browser.new_context()
|
||||||
}
|
|
||||||
# Make sure to run headed.
|
|
||||||
browser = await playwright.chromium.launch(**options)
|
|
||||||
# Setup context however you like.
|
|
||||||
context = await browser.new_context() # Pass any options
|
|
||||||
context = await set_init_script(context)
|
context = await set_init_script(context)
|
||||||
# Pause the page, and start recording manually.
|
qrcode_path = None
|
||||||
page = await context.new_page()
|
result = _build_login_result(False, "failed", "抖音登录失败", account_file)
|
||||||
await page.goto("https://creator.douyin.com/")
|
try:
|
||||||
await page.pause()
|
page = await context.new_page()
|
||||||
# 点击调试器的继续,保存cookie
|
await page.goto("https://creator.douyin.com/")
|
||||||
await context.storage_state(path=account_file)
|
qrcode_info = await _save_douyin_qrcode(page, account_file, qrcode_callback=qrcode_callback)
|
||||||
|
qrcode_path = Path(qrcode_info["image_path"])
|
||||||
|
douyin_logger.info("[+] 等待扫码登录完成...")
|
||||||
|
result = await _wait_for_douyin_login(
|
||||||
|
page,
|
||||||
|
account_file,
|
||||||
|
qrcode_info,
|
||||||
|
qrcode_callback=qrcode_callback,
|
||||||
|
poll_interval=poll_interval,
|
||||||
|
max_checks=max_checks,
|
||||||
|
)
|
||||||
|
if result["success"]:
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
await context.storage_state(path=account_file)
|
||||||
|
except Exception as exc:
|
||||||
|
result = _build_login_result(False, "failed", str(exc), account_file, current_url=page.url if "page" in locals() else "")
|
||||||
|
finally:
|
||||||
|
if remove_qrcode_file(qrcode_path):
|
||||||
|
douyin_logger.info(f"[+] 已删除临时二维码文件: {qrcode_path}")
|
||||||
|
await context.close()
|
||||||
|
await browser.close()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
class DouYinVideo(object):
|
class DouYinBaseUploader(BaseVideoUploader):
|
||||||
def __init__(self, title, file_path, tags, publish_date: datetime, account_file, thumbnail_path=None, productLink='', productTitle=''):
|
def __init__(
|
||||||
self.title = title # 视频标题
|
self,
|
||||||
self.file_path = file_path
|
publish_date: datetime | int,
|
||||||
self.tags = tags
|
account_file,
|
||||||
|
publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
|
||||||
|
debug: bool = DEBUG_MODE,
|
||||||
|
headless: bool = LOCAL_CHROME_HEADLESS,
|
||||||
|
):
|
||||||
self.publish_date = publish_date
|
self.publish_date = publish_date
|
||||||
self.account_file = account_file
|
self.account_file = account_file
|
||||||
self.date_format = '%Y年%m月%d日 %H:%M'
|
self.publish_strategy = publish_strategy
|
||||||
|
self.debug = debug
|
||||||
|
self.date_format = "%Y年%m月%d日 %H:%M"
|
||||||
self.local_executable_path = LOCAL_CHROME_PATH
|
self.local_executable_path = LOCAL_CHROME_PATH
|
||||||
self.headless = LOCAL_CHROME_HEADLESS
|
self.headless = headless
|
||||||
self.thumbnail_path = thumbnail_path
|
|
||||||
self.productLink = productLink
|
async def validate_base_args(self):
|
||||||
self.productTitle = productTitle
|
if not os.path.exists(self.account_file):
|
||||||
|
raise RuntimeError(f"cookie文件不存在,请先完成抖音登录: {self.account_file}")
|
||||||
|
if not await cookie_auth(self.account_file):
|
||||||
|
raise RuntimeError(f"cookie文件已失效,请先完成抖音登录: {self.account_file}")
|
||||||
|
if self.publish_strategy not in {DOUYIN_PUBLISH_STRATEGY_IMMEDIATE, DOUYIN_PUBLISH_STRATEGY_SCHEDULED}:
|
||||||
|
raise ValueError(f"不支持的发布策略: {self.publish_strategy}")
|
||||||
|
|
||||||
|
if self.publish_strategy == DOUYIN_PUBLISH_STRATEGY_SCHEDULED:
|
||||||
|
self.publish_date = self.validate_publish_date(self.publish_date)
|
||||||
|
else:
|
||||||
|
self.publish_date = 0
|
||||||
|
|
||||||
async def set_schedule_time_douyin(self, page, publish_date):
|
async def set_schedule_time_douyin(self, page, publish_date):
|
||||||
# 选择包含特定文本内容的 label 元素
|
|
||||||
label_element = page.locator("[class^='radio']:has-text('定时发布')")
|
label_element = page.locator("[class^='radio']:has-text('定时发布')")
|
||||||
# 在选中的 label 元素下点击 checkbox
|
|
||||||
await label_element.click()
|
await label_element.click()
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
publish_date_hour = publish_date.strftime("%Y-%m-%d %H:%M")
|
publish_date_hour = publish_date.strftime("%Y-%m-%d %H:%M")
|
||||||
@@ -90,204 +218,33 @@ class DouYinVideo(object):
|
|||||||
await page.keyboard.press("Control+KeyA")
|
await page.keyboard.press("Control+KeyA")
|
||||||
await page.keyboard.type(str(publish_date_hour))
|
await page.keyboard.type(str(publish_date_hour))
|
||||||
await page.keyboard.press("Enter")
|
await page.keyboard.press("Enter")
|
||||||
|
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
async def handle_upload_error(self, page):
|
async def fill_title_and_description(self, page: Page, title: str, description: str, tags: list[str] | None = None):
|
||||||
douyin_logger.info('视频出错了,重新上传中')
|
description_section = (
|
||||||
await page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(self.file_path)
|
page.get_by_text("作品描述", exact=True)
|
||||||
|
.locator("xpath=ancestor::div[2]")
|
||||||
|
.locator("xpath=following-sibling::div[1]")
|
||||||
|
)
|
||||||
|
|
||||||
async def upload(self, playwright: Playwright) -> None:
|
title_input = description_section.locator('input[type="text"]').first
|
||||||
# 使用 Chromium 浏览器启动一个浏览器实例
|
await title_input.wait_for(state="visible", timeout=10000)
|
||||||
if self.local_executable_path:
|
await title_input.fill(title[:30])
|
||||||
browser = await playwright.chromium.launch(headless=self.headless, executable_path=self.local_executable_path)
|
|
||||||
else:
|
|
||||||
browser = await playwright.chromium.launch(headless=self.headless)
|
|
||||||
# 创建一个浏览器上下文,使用指定的 cookie 文件
|
|
||||||
context = await browser.new_context(storage_state=f"{self.account_file}")
|
|
||||||
context = await set_init_script(context)
|
|
||||||
|
|
||||||
# 创建一个新的页面
|
description_editor = description_section.locator('.zone-container[contenteditable="true"]').first
|
||||||
page = await context.new_page()
|
await description_editor.wait_for(state="visible", timeout=10000)
|
||||||
# 访问指定的 URL
|
await description_editor.click()
|
||||||
await page.goto("https://creator.douyin.com/creator-micro/content/upload")
|
await page.keyboard.press("Control+KeyA")
|
||||||
douyin_logger.info(f'[+]正在上传-------{self.title}.mp4')
|
await page.keyboard.press("Delete")
|
||||||
# 等待页面跳转到指定的 URL,没进入,则自动等待到超时
|
await page.keyboard.type(description)
|
||||||
douyin_logger.info(f'[-] 正在打开主页...')
|
|
||||||
await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload")
|
|
||||||
# 点击 "上传视频" 按钮
|
|
||||||
await page.locator("div[class^='container'] input").set_input_files(self.file_path)
|
|
||||||
|
|
||||||
# 等待页面跳转到指定的 URL 2025.01.08修改在原有基础上兼容两种页面
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
# 尝试等待第一个 URL
|
|
||||||
await page.wait_for_url(
|
|
||||||
"https://creator.douyin.com/creator-micro/content/publish?enter_from=publish_page", timeout=3000)
|
|
||||||
douyin_logger.info("[+] 成功进入version_1发布页面!")
|
|
||||||
break # 成功进入页面后跳出循环
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
# 如果第一个 URL 超时,再尝试等待第二个 URL
|
|
||||||
await page.wait_for_url(
|
|
||||||
"https://creator.douyin.com/creator-micro/content/post/video?enter_from=publish_page",
|
|
||||||
timeout=3000)
|
|
||||||
douyin_logger.info("[+] 成功进入version_2发布页面!")
|
|
||||||
|
|
||||||
break # 成功进入页面后跳出循环
|
|
||||||
except:
|
|
||||||
print(" [-] 超时未进入视频发布页面,重新尝试...")
|
|
||||||
await asyncio.sleep(0.5) # 等待 0.5 秒后重新尝试
|
|
||||||
# 填充标题和话题
|
|
||||||
# 检查是否存在包含输入框的元素
|
|
||||||
# 这里为了避免页面变化,故使用相对位置定位:作品标题父级右侧第一个元素的input子元素
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
douyin_logger.info(f' [-] 正在填充标题和话题...')
|
|
||||||
title_container = page.get_by_text('作品标题').locator("..").locator("xpath=following-sibling::div[1]").locator("input")
|
|
||||||
if await title_container.count():
|
|
||||||
await title_container.fill(self.title[:30])
|
|
||||||
else:
|
|
||||||
titlecontainer = page.locator(".notranslate")
|
|
||||||
await titlecontainer.click()
|
|
||||||
await page.keyboard.press("Backspace")
|
|
||||||
await page.keyboard.press("Control+KeyA")
|
|
||||||
await page.keyboard.press("Delete")
|
|
||||||
await page.keyboard.type(self.title)
|
|
||||||
await page.keyboard.press("Enter")
|
|
||||||
css_selector = ".zone-container"
|
|
||||||
for index, tag in enumerate(self.tags, start=1):
|
|
||||||
await page.type(css_selector, "#" + tag)
|
|
||||||
await page.press(css_selector, "Space")
|
|
||||||
douyin_logger.info(f'总共添加{len(self.tags)}个话题')
|
|
||||||
while True:
|
|
||||||
# 判断重新上传按钮是否存在,如果不存在,代表视频正在上传,则等待
|
|
||||||
try:
|
|
||||||
# 新版:定位重新上传
|
|
||||||
number = await page.locator('[class^="long-card"] div:has-text("重新上传")').count()
|
|
||||||
if number > 0:
|
|
||||||
douyin_logger.success(" [-]视频上传完毕")
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
douyin_logger.info(" [-] 正在上传视频中...")
|
|
||||||
await asyncio.sleep(2)
|
|
||||||
|
|
||||||
if await page.locator('div.progress-div > div:has-text("上传失败")').count():
|
|
||||||
douyin_logger.error(" [-] 发现上传出错了... 准备重试")
|
|
||||||
await self.handle_upload_error(page)
|
|
||||||
except:
|
|
||||||
douyin_logger.info(" [-] 正在上传视频中...")
|
|
||||||
await asyncio.sleep(2)
|
|
||||||
|
|
||||||
if self.productLink and self.productTitle:
|
|
||||||
douyin_logger.info(f' [-] 正在设置商品链接...')
|
|
||||||
await self.set_product_link(page, self.productLink, self.productTitle)
|
|
||||||
douyin_logger.info(f' [+] 完成设置商品链接...')
|
|
||||||
|
|
||||||
#上传视频封面
|
|
||||||
await self.set_thumbnail(page, self.thumbnail_path)
|
|
||||||
|
|
||||||
# 更换可见元素
|
|
||||||
await self.set_location(page, "")
|
|
||||||
|
|
||||||
|
|
||||||
# 頭條/西瓜
|
|
||||||
third_part_element = '[class^="info"] > [class^="first-part"] div div.semi-switch'
|
|
||||||
# 定位是否有第三方平台
|
|
||||||
if await page.locator(third_part_element).count():
|
|
||||||
# 检测是否是已选中状态
|
|
||||||
if 'semi-switch-checked' not in await page.eval_on_selector(third_part_element, 'div => div.className'):
|
|
||||||
await page.locator(third_part_element).locator('input.semi-switch-native-control').click()
|
|
||||||
|
|
||||||
if self.publish_date != 0:
|
|
||||||
await self.set_schedule_time_douyin(page, self.publish_date)
|
|
||||||
|
|
||||||
# 判断视频是否发布成功
|
|
||||||
while True:
|
|
||||||
# 判断视频是否发布成功
|
|
||||||
try:
|
|
||||||
publish_button = page.get_by_role('button', name="发布", exact=True)
|
|
||||||
if await publish_button.count():
|
|
||||||
await publish_button.click()
|
|
||||||
await page.wait_for_url("https://creator.douyin.com/creator-micro/content/manage**",
|
|
||||||
timeout=3000) # 如果自动跳转到作品页面,则代表发布成功
|
|
||||||
douyin_logger.success(" [-]视频发布成功")
|
|
||||||
break
|
|
||||||
except:
|
|
||||||
# 尝试处理封面问题
|
|
||||||
await self.handle_auto_video_cover(page)
|
|
||||||
douyin_logger.info(" [-] 视频正在发布中...")
|
|
||||||
await page.screenshot(full_page=True)
|
|
||||||
await asyncio.sleep(0.5)
|
|
||||||
|
|
||||||
await context.storage_state(path=self.account_file) # 保存cookie
|
|
||||||
douyin_logger.success(' [-]cookie更新完毕!')
|
|
||||||
await asyncio.sleep(2) # 这里延迟是为了方便眼睛直观的观看
|
|
||||||
# 关闭浏览器上下文和浏览器实例
|
|
||||||
await context.close()
|
|
||||||
await browser.close()
|
|
||||||
|
|
||||||
async def handle_auto_video_cover(self, page):
|
|
||||||
"""
|
|
||||||
处理必须设置封面的情况,点击推荐封面的第一个
|
|
||||||
"""
|
|
||||||
# 1. 判断是否出现 "请设置封面后再发布" 的提示
|
|
||||||
# 必须确保提示是可见的 (is_visible),因为 DOM 中可能存在隐藏的历史提示
|
|
||||||
if await page.get_by_text("请设置封面后再发布").first.is_visible():
|
|
||||||
print(" [-] 检测到需要设置封面提示...")
|
|
||||||
|
|
||||||
# 2. 定位“智能推荐封面”区域下的第一个封面
|
|
||||||
# 使用 class^= 前缀匹配,避免 hash 变化导致失效
|
|
||||||
recommend_cover = page.locator('[class^="recommendCover-"]').first
|
|
||||||
|
|
||||||
if await recommend_cover.count():
|
|
||||||
print(" [-] 正在选择第一个推荐封面...")
|
|
||||||
try:
|
|
||||||
await recommend_cover.click()
|
|
||||||
await asyncio.sleep(1) # 等待选中生效
|
|
||||||
|
|
||||||
# 3. 处理可能的确认弹窗 "是否确认应用此封面?"
|
|
||||||
# 并不一定每次都会出现,健壮性判断:如果出现弹窗,则点击确定
|
|
||||||
confirm_text = "是否确认应用此封面?"
|
|
||||||
if await page.get_by_text(confirm_text).first.is_visible():
|
|
||||||
print(f" [-] 检测到确认弹窗: {confirm_text}")
|
|
||||||
# 直接点击“确定”按钮,不依赖脆弱的 CSS 类名
|
|
||||||
await page.get_by_role("button", name="确定").click()
|
|
||||||
print(" [-] 已点击确认应用封面")
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
|
|
||||||
print(" [-] 已完成封面选择流程")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
print(f" [-] 选择封面失败: {e}")
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def set_thumbnail(self, page: Page, thumbnail_path: str):
|
|
||||||
if thumbnail_path:
|
|
||||||
douyin_logger.info(' [-] 正在设置视频封面...')
|
|
||||||
await page.click('text="选择封面"')
|
|
||||||
await page.wait_for_selector("div.dy-creator-content-modal")
|
|
||||||
await page.click('text="设置竖封面"')
|
|
||||||
await page.wait_for_timeout(2000) # 等待2秒
|
|
||||||
# 定位到上传区域并点击
|
|
||||||
await page.locator("div[class^='semi-upload upload'] >> input.semi-upload-hidden-input").set_input_files(thumbnail_path)
|
|
||||||
await page.wait_for_timeout(2000) # 等待2秒
|
|
||||||
await page.locator("div#tooltip-container button:visible:has-text('完成')").click()
|
|
||||||
# finish_confirm_element = page.locator("div[class^='confirmBtn'] >> div:has-text('完成')")
|
|
||||||
# if await finish_confirm_element.count():
|
|
||||||
# await finish_confirm_element.click()
|
|
||||||
# await page.locator("div[class^='footer'] button:has-text('完成')").click()
|
|
||||||
douyin_logger.info(' [+] 视频封面设置完成!')
|
|
||||||
# 等待封面设置对话框关闭
|
|
||||||
await page.wait_for_selector("div.extractFooter", state='detached')
|
|
||||||
|
|
||||||
|
for tag in tags or []:
|
||||||
|
await page.keyboard.type(" #" + tag)
|
||||||
|
await page.keyboard.press("Space")
|
||||||
|
|
||||||
async def set_location(self, page: Page, location: str = ""):
|
async def set_location(self, page: Page, location: str = ""):
|
||||||
if not location:
|
if not location:
|
||||||
return
|
return
|
||||||
# todo supoort location later
|
|
||||||
# await page.get_by_text('添加标签').locator("..").locator("..").locator("xpath=following-sibling::div").locator(
|
|
||||||
# "div.semi-select-single").nth(0).click()
|
|
||||||
await page.locator('div.semi-select span:has-text("输入地理位置")').click()
|
await page.locator('div.semi-select span:has-text("输入地理位置")').click()
|
||||||
await page.keyboard.press("Backspace")
|
await page.keyboard.press("Backspace")
|
||||||
await page.wait_for_timeout(2000)
|
await page.wait_for_timeout(2000)
|
||||||
@@ -296,99 +253,395 @@ class DouYinVideo(object):
|
|||||||
await page.locator('div[role="listbox"] [role="option"]').first.click()
|
await page.locator('div[role="listbox"] [role="option"]').first.click()
|
||||||
|
|
||||||
async def handle_product_dialog(self, page: Page, product_title: str):
|
async def handle_product_dialog(self, page: Page, product_title: str):
|
||||||
"""处理商品编辑弹窗"""
|
|
||||||
|
|
||||||
await page.wait_for_timeout(2000)
|
await page.wait_for_timeout(2000)
|
||||||
await page.wait_for_selector('input[placeholder="请输入商品短标题"]', timeout=10000)
|
await page.wait_for_selector('input[placeholder="请输入商品短标题"]', timeout=10000)
|
||||||
short_title_input = page.locator('input[placeholder="请输入商品短标题"]')
|
short_title_input = page.locator('input[placeholder="请输入商品短标题"]')
|
||||||
if not await short_title_input.count():
|
if not await short_title_input.count():
|
||||||
douyin_logger.error("[-] 未找到商品短标题输入框")
|
douyin_logger.error("[-] 未找到商品短标题输入框")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
product_title = product_title[:10]
|
product_title = product_title[:10]
|
||||||
await short_title_input.fill(product_title)
|
await short_title_input.fill(product_title)
|
||||||
# 等待一下让界面响应
|
|
||||||
await page.wait_for_timeout(1000)
|
await page.wait_for_timeout(1000)
|
||||||
|
|
||||||
finish_button = page.locator('button:has-text("完成编辑")')
|
finish_button = page.locator('button:has-text("完成编辑")')
|
||||||
if 'disabled' not in await finish_button.get_attribute('class'):
|
if "disabled" not in await finish_button.get_attribute("class"):
|
||||||
await finish_button.click()
|
await finish_button.click()
|
||||||
douyin_logger.debug("[+] 成功点击'完成编辑'按钮")
|
douyin_logger.debug("[+] 成功点击'完成编辑'按钮")
|
||||||
|
await page.wait_for_selector(".semi-modal-content", state="hidden", timeout=5000)
|
||||||
# 等待对话框关闭
|
|
||||||
await page.wait_for_selector('.semi-modal-content', state='hidden', timeout=5000)
|
|
||||||
return True
|
return True
|
||||||
else:
|
|
||||||
douyin_logger.error("[-] '完成编辑'按钮处于禁用状态,尝试直接关闭对话框")
|
|
||||||
# 如果按钮禁用,尝试点击取消或关闭按钮
|
|
||||||
cancel_button = page.locator('button:has-text("取消")')
|
|
||||||
if await cancel_button.count():
|
|
||||||
await cancel_button.click()
|
|
||||||
else:
|
|
||||||
# 点击右上角的关闭按钮
|
|
||||||
close_button = page.locator('.semi-modal-close')
|
|
||||||
await close_button.click()
|
|
||||||
|
|
||||||
await page.wait_for_selector('.semi-modal-content', state='hidden', timeout=5000)
|
douyin_logger.error("[-] '完成编辑'按钮处于禁用状态,尝试直接关闭对话框")
|
||||||
return False
|
cancel_button = page.locator('button:has-text("取消")')
|
||||||
|
if await cancel_button.count():
|
||||||
|
await cancel_button.click()
|
||||||
|
else:
|
||||||
|
close_button = page.locator(".semi-modal-close")
|
||||||
|
await close_button.click()
|
||||||
|
await page.wait_for_selector(".semi-modal-content", state="hidden", timeout=5000)
|
||||||
|
return False
|
||||||
|
|
||||||
async def set_product_link(self, page: Page, product_link: str, product_title: str):
|
async def set_product_link(self, page: Page, product_link: str, product_title: str):
|
||||||
"""设置商品链接功能"""
|
await page.wait_for_timeout(2000)
|
||||||
await page.wait_for_timeout(2000) # 等待2秒
|
|
||||||
try:
|
try:
|
||||||
# 定位"添加标签"文本,然后向上导航到容器,再找到下拉框
|
await page.wait_for_selector("text=添加标签", timeout=10000)
|
||||||
await page.wait_for_selector('text=添加标签', timeout=10000)
|
dropdown = page.get_by_text("添加标签").locator("..").locator("..").locator("..").locator(".semi-select").first
|
||||||
dropdown = page.get_by_text('添加标签').locator("..").locator("..").locator("..").locator(".semi-select").first
|
|
||||||
if not await dropdown.count():
|
if not await dropdown.count():
|
||||||
douyin_logger.error("[-] 未找到标签下拉框")
|
douyin_logger.error("[-] 未找到标签下拉框")
|
||||||
return False
|
return False
|
||||||
douyin_logger.debug("[-] 找到标签下拉框,准备选择'购物车'")
|
douyin_logger.debug("[-] 找到标签下拉框,准备选择'购物车'")
|
||||||
await dropdown.click()
|
await dropdown.click()
|
||||||
## 等待下拉选项出现
|
|
||||||
await page.wait_for_selector('[role="listbox"]', timeout=5000)
|
await page.wait_for_selector('[role="listbox"]', timeout=5000)
|
||||||
## 选择"购物车"选项
|
|
||||||
await page.locator('[role="option"]:has-text("购物车")').click()
|
await page.locator('[role="option"]:has-text("购物车")').click()
|
||||||
douyin_logger.debug("[+] 成功选择'购物车'")
|
douyin_logger.debug("[+] 成功选择'购物车'")
|
||||||
|
|
||||||
# 输入商品链接
|
|
||||||
## 等待商品链接输入框出现
|
|
||||||
await page.wait_for_selector('input[placeholder="粘贴商品链接"]', timeout=5000)
|
await page.wait_for_selector('input[placeholder="粘贴商品链接"]', timeout=5000)
|
||||||
# 输入
|
|
||||||
input_field = page.locator('input[placeholder="粘贴商品链接"]')
|
input_field = page.locator('input[placeholder="粘贴商品链接"]')
|
||||||
await input_field.fill(product_link)
|
await input_field.fill(product_link)
|
||||||
douyin_logger.debug(f"[+] 已输入商品链接: {product_link}")
|
douyin_logger.debug(f"[+] 已输入商品链接: {product_link}")
|
||||||
|
|
||||||
# 点击"添加链接"按钮
|
|
||||||
add_button = page.locator('span:has-text("添加链接")')
|
add_button = page.locator('span:has-text("添加链接")')
|
||||||
## 检查按钮是否可用(没有disable类)
|
button_class = await add_button.get_attribute("class")
|
||||||
button_class = await add_button.get_attribute('class')
|
if "disable" in button_class:
|
||||||
if 'disable' in button_class:
|
|
||||||
douyin_logger.error("[-] '添加链接'按钮不可用")
|
douyin_logger.error("[-] '添加链接'按钮不可用")
|
||||||
return False
|
return False
|
||||||
await add_button.click()
|
await add_button.click()
|
||||||
douyin_logger.debug("[+] 成功点击'添加链接'按钮")
|
douyin_logger.debug("[+] 成功点击'添加链接'按钮")
|
||||||
## 如果链接不可用
|
|
||||||
await page.wait_for_timeout(2000)
|
await page.wait_for_timeout(2000)
|
||||||
error_modal = page.locator('text=未搜索到对应商品')
|
error_modal = page.locator("text=未搜索到对应商品")
|
||||||
if await error_modal.count():
|
if await error_modal.count():
|
||||||
confirm_button = page.locator('button:has-text("确定")')
|
confirm_button = page.locator('button:has-text("确定")')
|
||||||
await confirm_button.click()
|
await confirm_button.click()
|
||||||
# await page.wait_for_selector('.semi-modal-content', state='hidden', timeout=5000)
|
|
||||||
douyin_logger.error("[-] 商品链接无效")
|
douyin_logger.error("[-] 商品链接无效")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 填写商品短标题
|
|
||||||
if not await self.handle_product_dialog(page, product_title):
|
if not await self.handle_product_dialog(page, product_title):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 等待链接添加完成
|
|
||||||
douyin_logger.debug("[+] 成功设置商品链接")
|
douyin_logger.debug("[+] 成功设置商品链接")
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
douyin_logger.error(f"[-] 设置商品链接时出错: {str(e)}")
|
douyin_logger.error(f"[-] 设置商品链接时出错: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
async def main(self):
|
|
||||||
|
class DouYinVideo(DouYinBaseUploader):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
title,
|
||||||
|
file_path,
|
||||||
|
tags,
|
||||||
|
publish_date: datetime | int,
|
||||||
|
account_file,
|
||||||
|
thumbnail_landscape_path=None,
|
||||||
|
productLink="",
|
||||||
|
productTitle="",
|
||||||
|
thumbnail_portrait_path=None,
|
||||||
|
publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
|
||||||
|
debug: bool = DEBUG_MODE,
|
||||||
|
headless: bool = LOCAL_CHROME_HEADLESS,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
publish_date=publish_date,
|
||||||
|
account_file=account_file,
|
||||||
|
publish_strategy=publish_strategy,
|
||||||
|
debug=debug,
|
||||||
|
headless=headless,
|
||||||
|
)
|
||||||
|
self.title = title
|
||||||
|
self.file_path = file_path
|
||||||
|
self.tags = tags
|
||||||
|
self.thumbnail_landscape_path = thumbnail_landscape_path
|
||||||
|
self.thumbnail_portrait_path = thumbnail_portrait_path
|
||||||
|
self.productLink = productLink
|
||||||
|
self.productTitle = productTitle
|
||||||
|
|
||||||
|
async def validate_upload_args(self):
|
||||||
|
await self.validate_base_args()
|
||||||
|
if not self.title or not str(self.title).strip():
|
||||||
|
raise ValueError("视频模式下,title 是必须的")
|
||||||
|
|
||||||
|
self.file_path = str(self.validate_video_file(self.file_path))
|
||||||
|
if self.thumbnail_landscape_path:
|
||||||
|
self.thumbnail_landscape_path = str(self.validate_image_file(self.thumbnail_landscape_path))
|
||||||
|
if self.thumbnail_portrait_path:
|
||||||
|
self.thumbnail_portrait_path = str(self.validate_image_file(self.thumbnail_portrait_path))
|
||||||
|
|
||||||
|
async def handle_upload_error(self, page):
|
||||||
|
douyin_logger.info("视频出错了,重新上传中")
|
||||||
|
await page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(self.file_path)
|
||||||
|
|
||||||
|
async def handle_auto_video_cover(self, page):
|
||||||
|
if await page.get_by_text("请设置封面后再发布").first.is_visible():
|
||||||
|
print(" [-] 检测到需要设置封面提示...")
|
||||||
|
recommend_cover = page.locator('[class^="recommendCover-"]').first
|
||||||
|
if await recommend_cover.count():
|
||||||
|
print(" [-] 正在选择第一个推荐封面...")
|
||||||
|
try:
|
||||||
|
await recommend_cover.click()
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
confirm_text = "是否确认应用此封面?"
|
||||||
|
if await page.get_by_text(confirm_text).first.is_visible():
|
||||||
|
print(f" [-] 检测到确认弹窗: {confirm_text}")
|
||||||
|
await page.get_by_role("button", name="确定").click()
|
||||||
|
print(" [-] 已点击确认应用封面")
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
print(" [-] 已完成封面选择流程")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [-] 选择封面失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def set_thumbnail(self, page: Page):
|
||||||
|
if not self.thumbnail_landscape_path and not self.thumbnail_portrait_path:
|
||||||
|
return
|
||||||
|
|
||||||
|
douyin_logger.info(" [-] 正在设置视频封面...")
|
||||||
|
await page.click('text="选择封面"')
|
||||||
|
cover_locator_str = 'div[id*="creator-content-modal"]'
|
||||||
|
cover_locator = page.locator(cover_locator_str)
|
||||||
|
await page.wait_for_selector(cover_locator_str)
|
||||||
|
|
||||||
|
upload_input = cover_locator.locator("div[class^='semi-upload upload'] >> input.semi-upload-hidden-input")
|
||||||
|
|
||||||
|
if self.thumbnail_landscape_path:
|
||||||
|
await page.wait_for_timeout(1000)
|
||||||
|
await upload_input.set_input_files(self.thumbnail_landscape_path)
|
||||||
|
await page.wait_for_timeout(2000)
|
||||||
|
douyin_logger.info(" [-] 横版封面上传完成")
|
||||||
|
|
||||||
|
if self.thumbnail_portrait_path:
|
||||||
|
await cover_locator.locator("div[class*='steps'] div").nth(1).click()
|
||||||
|
await page.wait_for_timeout(1000)
|
||||||
|
await upload_input.set_input_files(self.thumbnail_portrait_path)
|
||||||
|
await page.wait_for_timeout(2000)
|
||||||
|
douyin_logger.info(" [-] 竖版封面上传完成")
|
||||||
|
|
||||||
|
await cover_locator.locator('button:visible:has-text("完成")').click()
|
||||||
|
douyin_logger.info(" [+] 视频封面设置完成!")
|
||||||
|
await page.wait_for_selector("div.extractFooter", state="detached")
|
||||||
|
|
||||||
|
async def upload(self, playwright: Playwright) -> None:
|
||||||
|
douyin_logger.info("[-] 正在校验 cookie、视频文件、封面和发布时间...")
|
||||||
|
await self.validate_upload_args()
|
||||||
|
douyin_logger.info("[+] 上传前校验通过")
|
||||||
|
|
||||||
|
browser = await playwright.chromium.launch(headless=self.headless, channel="chrome")
|
||||||
|
context = await browser.new_context(
|
||||||
|
storage_state=f"{self.account_file}",
|
||||||
|
permissions=["geolocation"],
|
||||||
|
)
|
||||||
|
context = await set_init_script(context)
|
||||||
|
|
||||||
|
page = await context.new_page()
|
||||||
|
await page.goto("https://creator.douyin.com/creator-micro/content/upload")
|
||||||
|
douyin_logger.info(f"[+]正在上传-------{self.title}.mp4")
|
||||||
|
douyin_logger.info("[-] 正在打开主页...")
|
||||||
|
await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload")
|
||||||
|
await page.locator("div[class^='container'] input").set_input_files(self.file_path)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await page.wait_for_url(
|
||||||
|
"https://creator.douyin.com/creator-micro/content/publish?enter_from=publish_page",
|
||||||
|
timeout=3000,
|
||||||
|
)
|
||||||
|
douyin_logger.info("[+] 成功进入version_1发布页面!")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
await page.wait_for_url(
|
||||||
|
"https://creator.douyin.com/creator-micro/content/post/video?enter_from=publish_page",
|
||||||
|
timeout=3000,
|
||||||
|
)
|
||||||
|
douyin_logger.info("[+] 成功进入version_2发布页面!")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
print(" [-] 超时未进入视频发布页面,重新尝试...")
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
douyin_logger.info(" [-] 正在填充标题、描述和话题...")
|
||||||
|
await self.fill_title_and_description(page, self.title, self.title, self.tags)
|
||||||
|
douyin_logger.info(f"总共添加{len(self.tags)}个话题")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
number = await page.locator('[class^="long-card"] div:has-text("重新上传")').count()
|
||||||
|
if number > 0:
|
||||||
|
douyin_logger.success(" [-]视频上传完毕")
|
||||||
|
break
|
||||||
|
douyin_logger.info(" [-] 正在上传视频中...")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
if await page.locator('div.progress-div > div:has-text("上传失败")').count():
|
||||||
|
douyin_logger.error(" [-] 发现上传出错了... 准备重试")
|
||||||
|
await self.handle_upload_error(page)
|
||||||
|
except Exception:
|
||||||
|
douyin_logger.info(" [-] 正在上传视频中...")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
|
||||||
|
if self.productLink and self.productTitle:
|
||||||
|
douyin_logger.info(" [-] 正在设置商品链接...")
|
||||||
|
await self.set_product_link(page, self.productLink, self.productTitle)
|
||||||
|
douyin_logger.info(" [+] 完成设置商品链接...")
|
||||||
|
|
||||||
|
await self.set_thumbnail(page)
|
||||||
|
|
||||||
|
third_part_element = '[class^="info"] > [class^="first-part"] div div.semi-switch'
|
||||||
|
if await page.locator(third_part_element).count():
|
||||||
|
if "semi-switch-checked" not in await page.eval_on_selector(third_part_element, "div => div.className"):
|
||||||
|
await page.locator(third_part_element).locator("input.semi-switch-native-control").click()
|
||||||
|
|
||||||
|
if self.publish_strategy == DOUYIN_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0:
|
||||||
|
await self.set_schedule_time_douyin(page, self.publish_date)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
publish_button = page.get_by_role("button", name="发布", exact=True)
|
||||||
|
if await publish_button.count():
|
||||||
|
await publish_button.click()
|
||||||
|
await page.wait_for_url(
|
||||||
|
"https://creator.douyin.com/creator-micro/content/manage**",
|
||||||
|
timeout=3000,
|
||||||
|
)
|
||||||
|
douyin_logger.success(" [-]视频发布成功")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
await self.handle_auto_video_cover(page)
|
||||||
|
douyin_logger.info(" [-] 视频正在发布中...")
|
||||||
|
if self.debug:
|
||||||
|
await page.screenshot(full_page=True)
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
|
||||||
|
await context.storage_state(path=self.account_file)
|
||||||
|
douyin_logger.success(" [-]cookie更新完毕!")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
await context.close()
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
async def douyin_upload_video(self):
|
||||||
async with async_playwright() as playwright:
|
async with async_playwright() as playwright:
|
||||||
await self.upload(playwright)
|
await self.upload(playwright)
|
||||||
|
|
||||||
|
async def main(self):
|
||||||
|
await self.douyin_upload_video()
|
||||||
|
|
||||||
|
|
||||||
|
class DouYinNote(DouYinBaseUploader):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
image_paths,
|
||||||
|
note,
|
||||||
|
tags,
|
||||||
|
publish_date: datetime | int,
|
||||||
|
account_file,
|
||||||
|
publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
|
||||||
|
debug: bool = DEBUG_MODE,
|
||||||
|
headless: bool = LOCAL_CHROME_HEADLESS,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
publish_date=publish_date,
|
||||||
|
account_file=account_file,
|
||||||
|
publish_strategy=publish_strategy,
|
||||||
|
debug=debug,
|
||||||
|
headless=headless,
|
||||||
|
)
|
||||||
|
self.image_paths = image_paths
|
||||||
|
self.note = note
|
||||||
|
self.tags = tags or []
|
||||||
|
|
||||||
|
async def validate_upload_args(self):
|
||||||
|
await self.validate_base_args()
|
||||||
|
if not self.note or not str(self.note).strip():
|
||||||
|
raise ValueError("图文模式下,note 是必须的")
|
||||||
|
if not self.image_paths:
|
||||||
|
raise ValueError("图文模式下,图片是必须的")
|
||||||
|
|
||||||
|
if isinstance(self.image_paths, (str, Path)):
|
||||||
|
self.image_paths = [self.image_paths]
|
||||||
|
|
||||||
|
if len(self.image_paths) > 35:
|
||||||
|
raise ValueError("图文模式下最多只支持上传 35 张图片")
|
||||||
|
|
||||||
|
normalized_image_paths = []
|
||||||
|
for image_path in self.image_paths:
|
||||||
|
normalized_image_paths.append(str(self.validate_image_file(image_path)))
|
||||||
|
self.image_paths = normalized_image_paths
|
||||||
|
|
||||||
|
async def upload_note_content(self, page: Page) -> None:
|
||||||
|
douyin_logger.info(f"[+]正在上传图文,共 {len(self.image_paths)} 张图片")
|
||||||
|
douyin_logger.info("[-] 正在切换到图文发布...")
|
||||||
|
await page.get_by_text("发布图文", exact=True).click()
|
||||||
|
await page.wait_for_timeout(1000)
|
||||||
|
|
||||||
|
douyin_logger.info("[-] 正在上传图片...")
|
||||||
|
await page.locator("div[class^='container'] input[accept*='image']").set_input_files(self.image_paths)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await page.wait_for_url(
|
||||||
|
"**/creator-micro/content/post/image?**",
|
||||||
|
timeout=3000,
|
||||||
|
)
|
||||||
|
douyin_logger.info("[+] 成功进入图文发布页面!")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
douyin_logger.info(" [-] 正在上传图片中...")
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
douyin_logger.info(" [-] 正在填充标题、描述和话题...")
|
||||||
|
await self.fill_title_and_description(page, self.note, self.note, self.tags)
|
||||||
|
douyin_logger.info(f"总共添加{len(self.tags)}个话题")
|
||||||
|
|
||||||
|
if self.publish_strategy == DOUYIN_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0:
|
||||||
|
await self.set_schedule_time_douyin(page, self.publish_date)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
publish_button = page.get_by_role("button", name="发布", exact=True)
|
||||||
|
if await publish_button.count():
|
||||||
|
await publish_button.click()
|
||||||
|
await page.wait_for_url(
|
||||||
|
"**/creator-micro/content/manage?enter_from=publish**",
|
||||||
|
timeout=3000,
|
||||||
|
)
|
||||||
|
douyin_logger.success(" [-]图文发布成功")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
douyin_logger.info(" [-] 图文正在发布中...")
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
|
||||||
|
async def upload(self, playwright: Playwright) -> None:
|
||||||
|
douyin_logger.info("[-] 正在校验 cookie、图片和发布时间...")
|
||||||
|
await self.validate_upload_args()
|
||||||
|
douyin_logger.info("[+] 图文上传前校验通过")
|
||||||
|
|
||||||
|
browser = await playwright.chromium.launch(headless=self.headless, channel="chrome")
|
||||||
|
context = await browser.new_context(
|
||||||
|
storage_state=f"{self.account_file}",
|
||||||
|
permissions=["geolocation"],
|
||||||
|
)
|
||||||
|
context = await set_init_script(context)
|
||||||
|
|
||||||
|
upload_success = False
|
||||||
|
try:
|
||||||
|
page = await context.new_page()
|
||||||
|
await page.goto("https://creator.douyin.com/creator-micro/content/upload")
|
||||||
|
douyin_logger.info("[-] 正在打开图文发布页...")
|
||||||
|
await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload")
|
||||||
|
|
||||||
|
await self.upload_note_content(page)
|
||||||
|
upload_success = True
|
||||||
|
finally:
|
||||||
|
if upload_success:
|
||||||
|
await context.storage_state(path=self.account_file)
|
||||||
|
douyin_logger.success(" [-]cookie更新完毕!")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
await context.close()
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
async def douyin_upload_note(self):
|
||||||
|
async with async_playwright() as playwright:
|
||||||
|
await self.upload(playwright)
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from datetime import datetime
|
||||||
|
import base64
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import segno
|
||||||
|
|
||||||
|
|
||||||
|
def build_login_qrcode_path(account_file: str, suffix: str = "login_qrcode") -> Path:
|
||||||
|
account_path = Path(account_file)
|
||||||
|
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
return account_path.with_name(f"{account_path.stem}_{suffix}_{timestamp}.png")
|
||||||
|
|
||||||
|
|
||||||
|
def save_data_url_image(data_url: str, output_path: Path) -> Path:
|
||||||
|
if not data_url.startswith("data:image/"):
|
||||||
|
raise ValueError("二维码地址不是 data:image 格式")
|
||||||
|
|
||||||
|
header, encoded = data_url.split(",", 1)
|
||||||
|
if ";base64" not in header:
|
||||||
|
raise ValueError("二维码图片不是 base64 编码")
|
||||||
|
|
||||||
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output_path.write_bytes(base64.b64decode(encoded))
|
||||||
|
return output_path
|
||||||
|
|
||||||
|
|
||||||
|
def remove_qrcode_file(qrcode_path: Path | None) -> bool:
|
||||||
|
if qrcode_path and qrcode_path.exists():
|
||||||
|
qrcode_path.unlink()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def decode_qrcode_from_path(qrcode_path: Path) -> str | None:
|
||||||
|
image = cv2.imread(str(qrcode_path))
|
||||||
|
if image is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
detector = cv2.QRCodeDetector()
|
||||||
|
qrcode_content, _, _ = detector.detectAndDecode(image)
|
||||||
|
return qrcode_content or None
|
||||||
|
|
||||||
|
|
||||||
|
def print_terminal_qrcode(qrcode_content: str, qrcode_path: Path, app_name: str) -> None:
|
||||||
|
print()
|
||||||
|
print(f"请使用{app_name}扫描下方二维码登录:")
|
||||||
|
segno.make(qrcode_content, error='L', boost_error=False).terminal(compact=True, border=0)
|
||||||
|
print("在 Windows 下建议使用 Windows Terminal(支持 UTF-8,可完整显示二维码)")
|
||||||
|
print(f"否则请打开 {qrcode_path} 扫码")
|
||||||
|
print()
|
||||||
Reference in New Issue
Block a user