Merge pull request #271 from carolius123/pr/baijiahao-uploader

feat(baijiahao): rewrite uploader on BaseVideoUploader and add CLI
This commit is contained in:
Alleria
2026-08-19 18:04:42 +08:00
committed by GitHub
3 changed files with 767 additions and 461 deletions
+111
View File
@@ -0,0 +1,111 @@
# -*- coding: utf-8 -*-
"""百家号(headless)扫码登录 → 保存 cookie。
说明:
- 无头浏览器打开百家号登录页并提取登录二维码,放大截图后保存为 png,
并用终端 ASCII 二维码展示;你手机/百度APP扫码登录。
- 扫码成功后自动把登录态写入 cookies/baijiahao_uploader/account.json。
用法:
python examples/get_baijiahao_cookie_headless.py
"""
from pathlib import Path
from playwright.async_api import async_playwright
from conf import BASE_DIR
from utils.login_qrcode import (
build_login_qrcode_path,
print_terminal_qrcode,
)
from uploader.baijiahao_uploader.main import cookie_auth, baijiahao_logger
QR_SELECTOR = 'img[src^="https://passport.baidu.com/v2/api/qrcode"]'
LOGIN_BTN_TEXT = "登录"
LOGIN_URL = "https://baijiahao.baidu.com/builder/theme/bjh/login"
async def _grab_qr(page, qrcode_path: Path) -> str:
qr = page.locator(QR_SELECTOR).first
await qr.wait_for(state="attached", timeout=60000)
src = await qr.get_attribute("src")
if src and src.startswith("https://"):
resp = await page.context.request.get(src)
qrcode_path.parent.mkdir(parents=True, exist_ok=True)
qrcode_path.write_bytes(await resp.body())
else:
await qr.screenshot(path=str(qrcode_path))
qrcode_content = ""
try:
import cv2
img = cv2.imread(str(qrcode_path))
if img is not None:
h, w = img.shape[:2]
up = cv2.resize(img, (w * 3, h * 3), interpolation=cv2.INTER_CUBIC)
qrcode_content = cv2.QRCodeDetector().detectAndDecode(up)[0] or ""
except Exception:
pass
return qrcode_content or ""
async def _wait_login(page, max_checks: int = 120, interval: int = 3) -> bool:
import asyncio
async def _logged_in():
if "login" in page.url:
return False
ctx = page.context
cookies = await ctx.cookies()
if any(c.get("name") in ("BDUSS", "STOKEN") for c in cookies):
return True
return False
for _ in range(max_checks):
if await _logged_in():
return True
await asyncio.sleep(interval)
return False
async def main():
account_file = Path(BASE_DIR / "cookies" / "baijiahao_uploader" / "account.json")
account_file.parent.mkdir(parents=True, exist_ok=True)
import os
if os.path.exists(account_file) and await cookie_auth(str(account_file)):
baijiahao_logger.success("[+] cookie 已有效,无需重新登录")
return
qrcode_path = build_login_qrcode_path(str(account_file))
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(
headless=True, args=["--no-sandbox", "--disable-blink-features=AutomationControlled"]
)
context = await browser.new_context()
page = await context.new_page()
await page.goto(LOGIN_URL, timeout=60000, wait_until="domcontentloaded")
await page.wait_for_timeout(4000)
# 进入登录弹窗
await page.get_by_text(LOGIN_BTN_TEXT, exact=True).first.click(timeout=10000)
await page.wait_for_timeout(4000)
qrcode_content = await _grab_qr(page, qrcode_path)
baijiahao_logger.info(f"🖼️ 二维码已保存: {qrcode_path}")
if qrcode_content:
print_terminal_qrcode(qrcode_content, qrcode_path, "百度APP/手机百度")
else:
print(f"未能解码二维码,请直接打开文件扫码:\n {qrcode_path}")
if await _wait_login(page):
baijiahao_logger.success("[+] 扫码登录成功,正在保存 cookie...")
await context.storage_state(path=str(account_file))
baijiahao_logger.success(f"[+] cookie 已保存: {account_file}")
else:
baijiahao_logger.error("[-] 等待扫码超时(约 6 分钟),未完成登录。")
await browser.close()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
+104
View File
@@ -9,6 +9,11 @@ from pathlib import Path
from typing import Iterable, Sequence
from conf import BASE_DIR
from uploader.baijiahao_uploader.main import (
BaiJiaHaoVideo,
baijiahao_setup,
cookie_auth as baijiahao_cookie_auth,
)
from uploader.bilibili_uploader.runtime import run_biliup_command
from uploader.douyin_uploader.main import (
DOUYIN_PUBLISH_STRATEGY_IMMEDIATE,
@@ -168,6 +173,19 @@ class TencentVideoUploadRequest:
headless: bool = True
@dataclass(slots=True)
class BaijiahaoVideoUploadRequest:
account_name: str
video_file: Path
title: str
description: str
tags: list[str]
thumbnail_file: Path | None = None
collection_name: str | None = None
debug: bool = True
headless: bool = True
@dataclass(slots=True)
class YouTubeVideoUploadRequest:
account_name: str
@@ -549,6 +567,41 @@ async def upload_tencent_video(request: TencentVideoUploadRequest) -> Path:
return account_file
async def login_baijiahao_account(account_name: str, headless: bool = True, qrcode_callback=None) -> dict:
account_file = resolve_account_file("baijiahao", account_name)
return await baijiahao_setup(str(account_file), handle=True, return_detail=True, headless=headless, qrcode_callback=qrcode_callback)
async def check_baijiahao_account(account_name: str) -> bool:
account_file = resolve_account_file("baijiahao", account_name)
if not account_file.exists():
return False
return await baijiahao_cookie_auth(str(account_file))
async def upload_baijiahao_video(request: BaijiahaoVideoUploadRequest) -> Path:
account_file = resolve_account_file("baijiahao", request.account_name)
is_ready = await baijiahao_setup(str(account_file), handle=False)
if not is_ready:
raise RuntimeError(
f"Baijiahao cookie is missing or expired: {account_file}. Run `sau baijiahao login --account {request.account_name}` first."
)
app = BaiJiaHaoVideo(
title=request.title,
file_path=str(request.video_file),
tags=request.tags,
account_file=str(account_file),
desc=request.description,
thumbnail_path=str(request.thumbnail_file) if request.thumbnail_file else None,
collection_name=request.collection_name,
debug=request.debug,
headless=request.headless,
)
await app.main()
return account_file
def existing_file_path(value: str) -> Path:
path = Path(value)
if not path.is_file():
@@ -736,6 +789,26 @@ def build_parser() -> argparse.ArgumentParser:
youtube_upload_video_parser.add_argument(
"--visibility", default="public", choices=["public", "unlisted", "private"], help="Video visibility")
add_runtime_flags(youtube_upload_video_parser)
baijiahao_parser = platform_parsers.add_parser("baijiahao", help="Baidu Baijiahao operations")
baijiahao_actions = baijiahao_parser.add_subparsers(dest="action", required=True)
for action_name in ("login", "check"):
action_parser = baijiahao_actions.add_parser(action_name, help=f"Baijiahao {action_name}")
action_parser.add_argument("--account", required=True, help="Baijiahao user-defined account_name")
if action_name == "login":
add_runtime_flags(action_parser)
baijiahao_upload_video_parser = baijiahao_actions.add_parser("upload-video", help="Upload one video to Baijiahao")
baijiahao_upload_video_parser.add_argument("--account", required=True, help="Baijiahao user-defined account_name")
baijiahao_upload_video_parser.add_argument("--file", required=True, type=existing_file_path, help="Video file path")
baijiahao_upload_video_parser.add_argument("--title", required=True, help="Video title")
baijiahao_upload_video_parser.add_argument("--desc", default="", help="Optional video description")
baijiahao_upload_video_parser.add_argument("--tags", default="", help="Comma-separated tags, such as tag1,tag2")
baijiahao_upload_video_parser.add_argument("--thumbnail", type=existing_file_path, help="Optional cover image path")
baijiahao_upload_video_parser.add_argument("--collection", default=None, help="Optional collection name")
add_runtime_flags(baijiahao_upload_video_parser)
return parser
@@ -1016,6 +1089,37 @@ async def dispatch(args: argparse.Namespace) -> int:
raise RuntimeError(f"Unsupported YouTube action: {args.action}")
if args.platform == "baijiahao":
if args.action == "login":
result = await login_baijiahao_account(args.account, headless=args.headless)
if not result["success"]:
raise RuntimeError(result["message"])
print(f"Baijiahao login flow completed: {result['account_file']}")
return 0
if args.action == "check":
is_valid = await check_baijiahao_account(args.account)
print("valid" if is_valid else "invalid")
return 0 if is_valid else 1
if args.action == "upload-video":
request = BaijiahaoVideoUploadRequest(
account_name=args.account,
video_file=args.file,
title=args.title,
description=args.desc,
tags=parse_tags(args.tags),
thumbnail_file=args.thumbnail,
collection_name=args.collection,
debug=args.debug,
headless=args.headless,
)
await upload_baijiahao_video(request)
print(f"Baijiahao video upload submitted: {request.video_file}")
return 0
raise RuntimeError(f"Unsupported Baijiahao action: {args.action}")
raise RuntimeError(f"Unsupported platform: {args.platform}")
File diff suppressed because it is too large Load Diff