返回 Social Auto Upload
douyin.py
根目录 / sau_commands / douyin.py
1 """douyin 的命令参数与执行逻辑。"""
2 from __future__ import annotations
3 import sys
4 from dataclasses import dataclass
5 from datetime import datetime
6 from pathlib import Path
7 from uploader.douyin_uploader.main import (
8 DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
9 DOUYIN_PUBLISH_STRATEGY_SCHEDULED,
10 DouYinNote,
11 DouYinVideo,
12 cookie_auth as douyin_cookie_auth,
13 douyin_setup,
14 )
15 from sau_commands.arguments import (
16 SCHEDULE_FORMAT,
17 add_runtime_flags,
18 existing_file_path,
19 parse_image_files,
20 parse_tags,
21 resolve_account_file,
22 schedule_value,
23 )
24
25
26 def register(platform_parsers):
27 """声明本平台命令、参数及合法选项。"""
28 schedule_help = SCHEDULE_FORMAT.replace("%", "%%")
29 douyin_parser = platform_parsers.add_parser("douyin", help="Douyin operations")
30 douyin_actions = douyin_parser.add_subparsers(dest="action", required=True)
31
32 for action_name in ("login", "check"):
33 action_parser = douyin_actions.add_parser(action_name, help=f"Douyin {action_name}")
34 action_parser.add_argument("--account", required=True, help="Douyin user-defined account_name")
35 if action_name == "login":
36 add_runtime_flags(action_parser)
37
38 upload_video_parser = douyin_actions.add_parser("upload-video", help="Upload one video to Douyin")
39 upload_video_parser.add_argument("--account", required=True, help="Douyin user-defined account_name")
40 upload_video_parser.add_argument("--file", required=True, type=existing_file_path, help="Video file path")
41 upload_video_parser.add_argument("--title", required=True, help="Video title")
42 upload_video_parser.add_argument("--desc", default="", help="Optional video description")
43 upload_video_parser.add_argument("--tags", default="", help="Comma-separated tags, such as tag1,tag2")
44 upload_video_parser.add_argument("--schedule", type=schedule_value, help=f"Schedule time in {schedule_help}")
45 upload_video_parser.add_argument("--thumbnail", type=existing_file_path, help="Optional 3:4 portrait thumbnail path")
46 upload_video_parser.add_argument("--thumbnail-landscape", type=existing_file_path, help="Optional 4:3 landscape thumbnail path")
47 upload_video_parser.add_argument("--thumbnail-portrait", type=existing_file_path, help="Optional 3:4 portrait thumbnail path")
48 upload_video_parser.add_argument("--product-link", default="", help="Optional product link")
49 upload_video_parser.add_argument("--product-title", default="", help="Optional product title")
50 upload_video_parser.add_argument(
51 "--declaration",
52 help="Exact Douyin self-declaration option text; omitted means do not set one",
53 )
54 upload_video_parser.add_argument("--collection", default=None, help="Optional collection name to add the work into (must already exist)")
55 add_runtime_flags(upload_video_parser)
56
57 upload_note_parser = douyin_actions.add_parser("upload-note", help="Upload one note to Douyin")
58 upload_note_parser.add_argument("--account", required=True, help="Douyin user-defined account_name")
59 upload_note_parser.add_argument("--images", required=True, nargs="+", type=existing_file_path, help="Image file paths")
60 upload_note_parser.add_argument("--title", required=True, help="Note title")
61 upload_note_parser.add_argument("--note", default="", help="Optional note content")
62 upload_note_parser.add_argument("--notef", default="", help="Read note content from file (txt/md)")
63 upload_note_parser.add_argument("--tags", default="", help="Comma-separated tags, such as tag1,tag2")
64 upload_note_parser.add_argument("--bgm", default="", help="BGM music name to search and select")
65 upload_note_parser.add_argument("--schedule", type=schedule_value, help=f"Schedule time in {schedule_help}")
66 add_runtime_flags(upload_note_parser)
67
68
69 @dataclass(slots=True)
70 class DouyinVideoUploadRequest:
71 account_name: str
72 video_file: Path
73 title: str
74 description: str
75 tags: list[str]
76 publish_date: datetime | int
77 thumbnail_file: Path | None = None
78 thumbnail_landscape_file: Path | None = None
79 thumbnail_portrait_file: Path | None = None
80 product_link: str = ""
81 product_title: str = ""
82 publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE
83 debug: bool = True
84 headless: bool = True
85 declaration: str | None = None
86 collection_name: str | None = None
87
88
89 @dataclass(slots=True)
90 class DouyinNoteUploadRequest:
91 account_name: str
92 image_files: list[Path]
93 title: str
94 note: str
95 tags: list[str]
96 publish_date: datetime | int
97 publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE
98 debug: bool = True
99 headless: bool = True
100 bgm: str = ""
101
102
103 async def login_douyin_account(account_name: str, headless: bool = True) -> dict:
104 account_file = resolve_account_file("douyin", account_name)
105 return await douyin_setup(str(account_file), handle=True, return_detail=True, headless=headless)
106
107
108 async def check_douyin_account(account_name: str) -> bool:
109 account_file = resolve_account_file("douyin", account_name)
110 if not account_file.exists():
111 return False
112 return await douyin_cookie_auth(str(account_file))
113
114
115 async def upload_video(request: DouyinVideoUploadRequest) -> Path:
116 account_file = resolve_account_file("douyin", request.account_name)
117 is_ready = await douyin_setup(str(account_file), handle=False)
118 if not is_ready:
119 raise RuntimeError(
120 f"Douyin cookie is missing or expired: {account_file}. Run `sau douyin login --account {request.account_name}` first."
121 )
122
123 app = DouYinVideo(
124 request.title,
125 str(request.video_file),
126 request.tags,
127 request.publish_date,
128 str(account_file),
129 desc=request.description,
130 thumbnail_landscape_path=(
131 str(request.thumbnail_landscape_file) if request.thumbnail_landscape_file else None
132 ),
133 thumbnail_portrait_path=str(
134 request.thumbnail_portrait_file or request.thumbnail_file
135 ) if request.thumbnail_portrait_file or request.thumbnail_file else None,
136 productLink=request.product_link,
137 productTitle=request.product_title,
138 declaration=request.declaration,
139 publish_strategy=request.publish_strategy,
140 debug=request.debug,
141 headless=request.headless,
142 collection_name=request.collection_name,
143 )
144 await app.douyin_upload_video()
145 return account_file
146
147
148 async def upload_note(request: DouyinNoteUploadRequest) -> Path:
149 account_file = resolve_account_file("douyin", request.account_name)
150 is_ready = await douyin_setup(str(account_file), handle=False)
151 if not is_ready:
152 raise RuntimeError(
153 f"Douyin cookie is missing or expired: {account_file}. Run `sau douyin login --account {request.account_name}` first."
154 )
155
156 app = DouYinNote(
157 image_paths=[str(path) for path in request.image_files],
158 title=request.title,
159 note=request.note,
160 tags=request.tags,
161 publish_date=request.publish_date,
162 account_file=str(account_file),
163 publish_strategy=request.publish_strategy,
164 debug=request.debug,
165 headless=request.headless,
166 bgm=request.bgm,
167 )
168 await app.douyin_upload_note()
169 return account_file
170
171
172 async def run(args):
173 """执行本平台命令;发布结果由平台实现核验。"""
174 if args.action == "login":
175 result = await login_douyin_account(args.account, headless=args.headless)
176 if not result["success"]:
177 raise RuntimeError(result["message"])
178 print(f"Douyin login flow completed: {result['account_file']}")
179 return 0
180
181 if args.action == "check":
182 is_valid = await check_douyin_account(args.account)
183 print("valid" if is_valid else "invalid")
184 return 0 if is_valid else 1
185
186 publish_strategy = DOUYIN_PUBLISH_STRATEGY_SCHEDULED if args.schedule else DOUYIN_PUBLISH_STRATEGY_IMMEDIATE
187
188 if args.action == "upload-video":
189 request = DouyinVideoUploadRequest(
190 account_name=args.account,
191 video_file=args.file,
192 title=args.title,
193 description=args.desc,
194 tags=parse_tags(args.tags),
195 publish_date=args.schedule or 0,
196 thumbnail_file=args.thumbnail,
197 thumbnail_landscape_file=args.thumbnail_landscape,
198 thumbnail_portrait_file=args.thumbnail_portrait,
199 product_link=args.product_link,
200 product_title=args.product_title,
201 declaration=args.declaration,
202 publish_strategy=publish_strategy,
203 debug=args.debug,
204 headless=args.headless,
205 collection_name=args.collection,
206 )
207 await upload_video(request)
208 print(f"Douyin video upload submitted: {request.video_file}")
209 return 0
210
211 if args.action == "upload-note":
212 # 如果指定了 --notef,读取文件内容作为 note
213 note_content = args.note
214 if args.notef:
215 note_file = Path(args.notef)
216 if not note_file.exists():
217 print(f"错误:文件不存在: {note_file}", file=sys.stderr)
218 return 1
219 note_content = note_file.read_text(encoding="utf-8")
220
221 request = DouyinNoteUploadRequest(
222 account_name=args.account,
223 image_files=parse_image_files(args.images),
224 title=args.title,
225 note=note_content,
226 tags=parse_tags(args.tags),
227 publish_date=args.schedule or 0,
228 publish_strategy=publish_strategy,
229 debug=args.debug,
230 headless=args.headless,
231 bgm=args.bgm or "",
232 )
233 await upload_note(request)
234 print(f"Douyin note upload submitted: {len(request.image_files)} images")
235 return 0
236
237 raise RuntimeError(f"Unsupported Douyin action: {args.action}")
238
238 lines PYTHON