app.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 多平台视频发布服务 - 统一入口
  5. 支持平台: 抖音、小红书、视频号、快手
  6. 参考项目: matrix (https://github.com/kebenxiaoming/matrix)
  7. 使用方式:
  8. python app.py # 启动 HTTP 服务 (端口 5005)
  9. python app.py --port 8080 # 指定端口
  10. python app.py --headless false # 显示浏览器窗口
  11. """
  12. import asyncio
  13. import os
  14. import sys
  15. import argparse
  16. # 禁用输出缓冲,确保 print 立即输出
  17. os.environ['PYTHONUNBUFFERED'] = '1'
  18. # 修复 Windows 终端中文输出乱码
  19. if sys.platform == 'win32':
  20. import io
  21. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace', line_buffering=True)
  22. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace', line_buffering=True)
  23. # 设置环境变量
  24. os.environ['PYTHONIOENCODING'] = 'utf-8'
  25. import traceback
  26. import requests
  27. from datetime import datetime, date
  28. from pathlib import Path
  29. # 确保当前目录在 Python 路径中
  30. CURRENT_DIR = Path(__file__).parent.resolve()
  31. if str(CURRENT_DIR) not in sys.path:
  32. sys.path.insert(0, str(CURRENT_DIR))
  33. # 从 server/.env 文件加载环境变量
  34. def load_env_file():
  35. """从 server/.env 文件加载环境变量"""
  36. env_path = CURRENT_DIR.parent / '.env'
  37. if env_path.exists():
  38. print(f"[Config] Loading env from: {env_path}")
  39. with open(env_path, 'r', encoding='utf-8') as f:
  40. for line in f:
  41. line = line.strip()
  42. if line and not line.startswith('#') and '=' in line:
  43. key, value = line.split('=', 1)
  44. key = key.strip()
  45. value = value.strip()
  46. # 移除引号
  47. if value.startswith('"') and value.endswith('"'):
  48. value = value[1:-1]
  49. elif value.startswith("'") and value.endswith("'"):
  50. value = value[1:-1]
  51. # 只在环境变量未设置时加载
  52. if key not in os.environ:
  53. os.environ[key] = value
  54. print(f"[Config] Loaded: {key}=***" if 'PASSWORD' in key or 'SECRET' in key else f"[Config] Loaded: {key}={value}")
  55. else:
  56. print(f"[Config] .env file not found: {env_path}")
  57. # 加载环境变量
  58. load_env_file()
  59. from flask import Flask, request, jsonify
  60. from flask_cors import CORS
  61. from platforms import get_publisher, PLATFORM_MAP
  62. from platforms.base import PublishParams
  63. def parse_datetime(date_str: str):
  64. """解析日期时间字符串"""
  65. if not date_str:
  66. return None
  67. formats = [
  68. "%Y-%m-%d %H:%M:%S",
  69. "%Y-%m-%d %H:%M",
  70. "%Y/%m/%d %H:%M:%S",
  71. "%Y/%m/%d %H:%M",
  72. "%Y-%m-%dT%H:%M:%S",
  73. "%Y-%m-%dT%H:%M:%SZ",
  74. ]
  75. for fmt in formats:
  76. try:
  77. return datetime.strptime(date_str, fmt)
  78. except ValueError:
  79. continue
  80. return None
  81. def validate_video_file(video_path: str) -> bool:
  82. """验证视频文件是否有效"""
  83. if not video_path:
  84. return False
  85. if not os.path.exists(video_path):
  86. return False
  87. if not os.path.isfile(video_path):
  88. return False
  89. valid_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv', '.webm']
  90. ext = os.path.splitext(video_path)[1].lower()
  91. if ext not in valid_extensions:
  92. return False
  93. if os.path.getsize(video_path) < 1024:
  94. return False
  95. return True
  96. # 创建 Flask 应用
  97. app = Flask(__name__)
  98. CORS(app)
  99. # 配置日志以显示所有 HTTP 请求
  100. import logging
  101. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
  102. # 让 werkzeug 日志显示
  103. werkzeug_logger = logging.getLogger('werkzeug')
  104. werkzeug_logger.setLevel(logging.INFO)
  105. # 添加 StreamHandler 确保输出到控制台
  106. handler = logging.StreamHandler(sys.stdout)
  107. handler.setLevel(logging.DEBUG)
  108. werkzeug_logger.addHandler(handler)
  109. # 添加请求钩子,打印所有收到的请求
  110. @app.before_request
  111. def log_request_info():
  112. """在处理每个请求前打印详细信息"""
  113. print(f"\n{'='*60}", flush=True)
  114. print(f"[HTTP Request] {request.method} {request.path}", flush=True)
  115. print(f"[HTTP Request] From: {request.remote_addr}", flush=True)
  116. if request.content_type and 'json' in request.content_type:
  117. try:
  118. data = request.get_json(silent=True)
  119. if data:
  120. # 打印部分参数,避免太长
  121. keys = list(data.keys()) if data else []
  122. print(f"[HTTP Request] JSON keys: {keys}", flush=True)
  123. except:
  124. pass
  125. print(f"{'='*60}\n", flush=True)
  126. # 全局配置
  127. HEADLESS_MODE = os.environ.get('HEADLESS', 'true').lower() == 'true'
  128. print(f"[Config] HEADLESS env value: '{os.environ.get('HEADLESS', 'NOT SET')}'", flush=True)
  129. print(f"[Config] HEADLESS_MODE: {HEADLESS_MODE}", flush=True)
  130. # Node.js API 配置
  131. NODEJS_API_BASE_URL = os.environ.get('NODEJS_API_URL', 'http://localhost:3000')
  132. INTERNAL_API_KEY = os.environ.get('INTERNAL_API_KEY', 'internal-api-key-default')
  133. print(f"[API Config] Node.js API: {NODEJS_API_BASE_URL}", flush=True)
  134. class NodeApiError(Exception):
  135. """用于把 Node 内部接口的错误状态码/内容透传给调用方。"""
  136. def __init__(self, status_code: int, payload: dict):
  137. super().__init__(payload.get("error") or payload.get("message") or "Node API error")
  138. self.status_code = status_code
  139. self.payload = payload
  140. def call_nodejs_api(method: str, endpoint: str, data: dict = None, params: dict = None) -> dict:
  141. """调用 Node.js 内部 API"""
  142. url = f"{NODEJS_API_BASE_URL}/api/internal{endpoint}"
  143. headers = {
  144. 'Content-Type': 'application/json',
  145. 'X-Internal-API-Key': INTERNAL_API_KEY,
  146. }
  147. try:
  148. if method.upper() == 'GET':
  149. response = requests.get(url, headers=headers, params=params, timeout=30)
  150. elif method.upper() == 'POST':
  151. response = requests.post(url, headers=headers, json=data, timeout=30)
  152. else:
  153. raise ValueError(f"Unsupported HTTP method: {method}")
  154. # 兼容 Node 可能返回非 JSON 的情况
  155. try:
  156. payload = response.json()
  157. except Exception:
  158. payload = {
  159. "success": False,
  160. "error": "Node.js API 返回非 JSON 响应",
  161. "status": response.status_code,
  162. "text": (response.text or "")[:2000],
  163. "url": url,
  164. "endpoint": endpoint,
  165. }
  166. if response.status_code >= 400:
  167. # 把真实状态码/返回体抛出去,由路由决定如何返回给前端
  168. if isinstance(payload, dict):
  169. payload.setdefault("success", False)
  170. payload.setdefault("status", response.status_code)
  171. payload.setdefault("url", url)
  172. payload.setdefault("endpoint", endpoint)
  173. raise NodeApiError(response.status_code, payload if isinstance(payload, dict) else {
  174. "success": False,
  175. "error": "Node.js API 调用失败",
  176. "status": response.status_code,
  177. "data": payload,
  178. "url": url,
  179. "endpoint": endpoint,
  180. })
  181. return payload
  182. except requests.exceptions.RequestException as e:
  183. # 连接失败/超时等(此时通常拿不到 response)
  184. print(f"[API Error] 调用 Node.js API 失败: {e}", flush=True)
  185. raise NodeApiError(502, {
  186. "success": False,
  187. "error": f"无法连接 Node.js API: {str(e)}",
  188. "status": 502,
  189. "url": url,
  190. "endpoint": endpoint,
  191. })
  192. # ==================== 签名相关(小红书专用) ====================
  193. @app.route("/sign", methods=["POST"])
  194. def sign_endpoint():
  195. """小红书签名接口"""
  196. try:
  197. from platforms.xiaohongshu import XiaohongshuPublisher
  198. data = request.json
  199. publisher = XiaohongshuPublisher(headless=True)
  200. result = asyncio.run(publisher.get_sign(
  201. data.get("uri", ""),
  202. data.get("data"),
  203. data.get("a1", ""),
  204. data.get("web_session", "")
  205. ))
  206. return jsonify(result)
  207. except Exception as e:
  208. traceback.print_exc()
  209. return jsonify({"error": str(e)}), 500
  210. # ==================== 统一发布接口 ====================
  211. @app.route("/publish", methods=["POST"])
  212. def publish_video():
  213. """
  214. 统一发布接口
  215. 请求体:
  216. {
  217. "platform": "douyin", # douyin | xiaohongshu | weixin | kuaishou
  218. "cookie": "cookie字符串或JSON",
  219. "title": "视频标题",
  220. "description": "视频描述(可选)",
  221. "video_path": "视频文件绝对路径",
  222. "cover_path": "封面图片绝对路径(可选)",
  223. "tags": ["话题1", "话题2"],
  224. "post_time": "定时发布时间(可选,格式:2024-01-20 12:00:00)",
  225. "location": "位置(可选,默认:重庆市)"
  226. }
  227. 响应:
  228. {
  229. "success": true,
  230. "platform": "douyin",
  231. "video_id": "xxx",
  232. "video_url": "xxx",
  233. "message": "发布成功"
  234. }
  235. """
  236. try:
  237. data = request.json
  238. # 获取参数
  239. platform = data.get("platform", "").lower()
  240. cookie_str = data.get("cookie", "")
  241. title = data.get("title", "")
  242. description = data.get("description", "")
  243. video_path = data.get("video_path", "")
  244. cover_path = data.get("cover_path")
  245. tags = data.get("tags", [])
  246. post_time = data.get("post_time")
  247. location = data.get("location", "重庆市")
  248. # 调试日志
  249. print(f"[Publish] 收到请求: platform={platform}, title={title}, video_path={video_path}")
  250. # 参数验证
  251. if not platform:
  252. print("[Publish] 错误: 缺少 platform 参数")
  253. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  254. if platform not in PLATFORM_MAP:
  255. print(f"[Publish] 错误: 不支持的平台 {platform}")
  256. return jsonify({
  257. "success": False,
  258. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  259. }), 400
  260. if not cookie_str:
  261. print("[Publish] 错误: 缺少 cookie 参数")
  262. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  263. if not title:
  264. print("[Publish] 错误: 缺少 title 参数")
  265. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  266. if not video_path:
  267. print("[Publish] 错误: 缺少 video_path 参数")
  268. return jsonify({"success": False, "error": "缺少 video_path 参数"}), 400
  269. # 视频文件验证(增加详细信息)
  270. if not os.path.exists(video_path):
  271. print(f"[Publish] 错误: 视频文件不存在: {video_path}")
  272. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  273. if not os.path.isfile(video_path):
  274. print(f"[Publish] 错误: 路径不是文件: {video_path}")
  275. return jsonify({"success": False, "error": f"路径不是文件: {video_path}"}), 400
  276. # 解析发布时间
  277. publish_date = parse_datetime(post_time) if post_time else None
  278. # 创建发布参数
  279. params = PublishParams(
  280. title=title,
  281. video_path=video_path,
  282. description=description,
  283. cover_path=cover_path,
  284. tags=tags,
  285. publish_date=publish_date,
  286. location=location
  287. )
  288. print("=" * 60)
  289. print(f"[Publish] 平台: {platform}")
  290. print(f"[Publish] 标题: {title}")
  291. print(f"[Publish] 视频: {video_path}")
  292. print(f"[Publish] 封面: {cover_path}")
  293. print(f"[Publish] 话题: {tags}")
  294. print(f"[Publish] 定时: {publish_date}")
  295. print("=" * 60)
  296. # 获取对应平台的发布器
  297. PublisherClass = get_publisher(platform)
  298. publisher = PublisherClass(headless=HEADLESS_MODE)
  299. # 执行发布
  300. result = asyncio.run(publisher.run(cookie_str, params))
  301. response_data = {
  302. "success": result.success,
  303. "platform": result.platform,
  304. "video_id": result.video_id,
  305. "video_url": result.video_url,
  306. "message": result.message,
  307. "error": result.error,
  308. "need_captcha": result.need_captcha,
  309. "captcha_type": result.captcha_type,
  310. "screenshot_base64": result.screenshot_base64,
  311. "page_url": result.page_url,
  312. "status": result.status
  313. }
  314. # 如果需要验证码,打印明确的日志
  315. if result.need_captcha:
  316. print(f"[Publish] 需要验证码: type={result.captcha_type}")
  317. return jsonify(response_data)
  318. except Exception as e:
  319. traceback.print_exc()
  320. return jsonify({"success": False, "error": str(e)}), 500
  321. # ==================== AI 辅助发布接口 ====================
  322. # 存储活跃的发布会话
  323. active_publish_sessions = {}
  324. @app.route("/publish/ai-assisted", methods=["POST"])
  325. def publish_ai_assisted():
  326. """
  327. AI 辅助发布接口
  328. 与普通发布接口的区别:
  329. 1. 发布过程中会返回截图供 AI 分析
  330. 2. 如果检测到需要验证码,返回截图和状态,等待外部处理
  331. 3. 支持继续发布(输入验证码后)
  332. 请求体:
  333. {
  334. "platform": "douyin",
  335. "cookie": "cookie字符串",
  336. "title": "视频标题",
  337. "video_path": "视频文件路径",
  338. ...
  339. "return_screenshot": true // 是否返回截图
  340. }
  341. 响应:
  342. {
  343. "success": true/false,
  344. "status": "success|failed|need_captcha|processing",
  345. "screenshot_base64": "...", // 当前页面截图
  346. "page_url": "...",
  347. ...
  348. }
  349. """
  350. # 立即打印请求日志,确保能看到
  351. print("\n" + "!" * 60, flush=True)
  352. print("!!! [AI-Assisted Publish] 收到请求 !!!", flush=True)
  353. print("!" * 60 + "\n", flush=True)
  354. try:
  355. data = request.json
  356. print(f"[AI-Assisted Publish] 请求数据: platform={data.get('platform')}, title={data.get('title')}", flush=True)
  357. # 获取参数
  358. platform = data.get("platform", "").lower()
  359. cookie_str = data.get("cookie", "")
  360. title = data.get("title", "")
  361. description = data.get("description", "")
  362. video_path = data.get("video_path", "")
  363. cover_path = data.get("cover_path")
  364. tags = data.get("tags", [])
  365. post_time = data.get("post_time")
  366. location = data.get("location", "重庆市")
  367. return_screenshot = data.get("return_screenshot", True)
  368. # 支持请求级别的 headless 参数,用于验证码场景下的有头浏览器模式
  369. headless = data.get("headless", HEADLESS_MODE)
  370. if isinstance(headless, str):
  371. headless = headless.lower() == 'true'
  372. # 参数验证
  373. if not platform:
  374. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  375. if platform not in PLATFORM_MAP:
  376. return jsonify({"success": False, "error": f"不支持的平台: {platform}"}), 400
  377. if not cookie_str:
  378. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  379. if not title:
  380. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  381. if not video_path or not os.path.exists(video_path):
  382. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  383. # 解析发布时间
  384. publish_date = parse_datetime(post_time) if post_time else None
  385. # 创建发布参数
  386. params = PublishParams(
  387. title=title,
  388. video_path=video_path,
  389. description=description,
  390. cover_path=cover_path,
  391. tags=tags,
  392. publish_date=publish_date,
  393. location=location
  394. )
  395. print("=" * 60)
  396. print(f"[AI Publish] 平台: {platform}")
  397. print(f"[AI Publish] 标题: {title}")
  398. print(f"[AI Publish] 视频: {video_path}")
  399. print(f"[AI Publish] Headless: {headless}")
  400. print("=" * 60)
  401. # 获取对应平台的发布器
  402. PublisherClass = get_publisher(platform)
  403. publisher = PublisherClass(headless=headless) # 使用请求参数中的 headless 值
  404. # 执行发布
  405. result = asyncio.run(publisher.run(cookie_str, params))
  406. response_data = {
  407. "success": result.success,
  408. "platform": result.platform,
  409. "video_id": result.video_id,
  410. "video_url": result.video_url,
  411. "message": result.message,
  412. "error": result.error,
  413. "need_captcha": result.need_captcha,
  414. "captcha_type": result.captcha_type,
  415. "status": result.status or ("success" if result.success else "failed"),
  416. "page_url": result.page_url
  417. }
  418. # 如果请求返回截图
  419. if return_screenshot and result.screenshot_base64:
  420. response_data["screenshot_base64"] = result.screenshot_base64
  421. return jsonify(response_data)
  422. except Exception as e:
  423. traceback.print_exc()
  424. return jsonify({"success": False, "error": str(e), "status": "error"}), 500
  425. # ==================== 批量发布接口 ====================
  426. @app.route("/publish/batch", methods=["POST"])
  427. def publish_batch():
  428. """
  429. 批量发布接口 - 发布到多个平台
  430. 请求体:
  431. {
  432. "platforms": ["douyin", "xiaohongshu"],
  433. "cookies": {
  434. "douyin": "cookie字符串",
  435. "xiaohongshu": "cookie字符串"
  436. },
  437. "title": "视频标题",
  438. "video_path": "视频文件绝对路径",
  439. ...
  440. }
  441. """
  442. try:
  443. data = request.json
  444. platforms = data.get("platforms", [])
  445. cookies = data.get("cookies", {})
  446. if not platforms:
  447. return jsonify({"success": False, "error": "缺少 platforms 参数"}), 400
  448. results = []
  449. for platform in platforms:
  450. platform = platform.lower()
  451. cookie_str = cookies.get(platform, "")
  452. if not cookie_str:
  453. results.append({
  454. "platform": platform,
  455. "success": False,
  456. "error": f"缺少 {platform} 的 cookie"
  457. })
  458. continue
  459. try:
  460. # 创建参数
  461. params = PublishParams(
  462. title=data.get("title", ""),
  463. video_path=data.get("video_path", ""),
  464. description=data.get("description", ""),
  465. cover_path=data.get("cover_path"),
  466. tags=data.get("tags", []),
  467. publish_date=parse_datetime(data.get("post_time")),
  468. location=data.get("location", "重庆市")
  469. )
  470. # 发布
  471. PublisherClass = get_publisher(platform)
  472. publisher = PublisherClass(headless=HEADLESS_MODE)
  473. result = asyncio.run(publisher.run(cookie_str, params))
  474. results.append({
  475. "platform": result.platform,
  476. "success": result.success,
  477. "video_id": result.video_id,
  478. "message": result.message,
  479. "error": result.error
  480. })
  481. except Exception as e:
  482. results.append({
  483. "platform": platform,
  484. "success": False,
  485. "error": str(e)
  486. })
  487. # 统计成功/失败数量
  488. success_count = sum(1 for r in results if r.get("success"))
  489. return jsonify({
  490. "success": success_count > 0,
  491. "total": len(platforms),
  492. "success_count": success_count,
  493. "fail_count": len(platforms) - success_count,
  494. "results": results
  495. })
  496. except Exception as e:
  497. traceback.print_exc()
  498. return jsonify({"success": False, "error": str(e)}), 500
  499. # ==================== Cookie 验证接口 ====================
  500. @app.route("/check_cookie", methods=["POST"])
  501. def check_cookie():
  502. """检查 cookie 是否有效"""
  503. try:
  504. data = request.json
  505. platform = data.get("platform", "").lower()
  506. cookie_str = data.get("cookie", "")
  507. if not cookie_str:
  508. return jsonify({"valid": False, "error": "缺少 cookie 参数"}), 400
  509. # 目前只支持小红书的 cookie 验证
  510. if platform == "xiaohongshu":
  511. try:
  512. from platforms.xiaohongshu import XiaohongshuPublisher, XHS_SDK_AVAILABLE
  513. if XHS_SDK_AVAILABLE:
  514. from xhs import XhsClient
  515. publisher = XiaohongshuPublisher()
  516. xhs_client = XhsClient(cookie_str, sign=publisher.sign_sync)
  517. info = xhs_client.get_self_info()
  518. if info:
  519. return jsonify({
  520. "valid": True,
  521. "user_info": {
  522. "user_id": info.get("user_id"),
  523. "nickname": info.get("nickname"),
  524. "avatar": info.get("images")
  525. }
  526. })
  527. except Exception as e:
  528. return jsonify({"valid": False, "error": str(e)})
  529. # 其他平台返回格式正确但未验证
  530. return jsonify({
  531. "valid": True,
  532. "message": "Cookie 格式正确,但未进行在线验证"
  533. })
  534. except Exception as e:
  535. traceback.print_exc()
  536. return jsonify({"valid": False, "error": str(e)})
  537. # ==================== 获取作品列表接口 ====================
  538. @app.route("/works", methods=["POST"])
  539. def get_works():
  540. """
  541. 获取作品列表
  542. 请求体:
  543. {
  544. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  545. "cookie": "cookie字符串或JSON",
  546. "page": 0, # 页码(从0开始,可选,默认0)
  547. "page_size": 20 # 每页数量(可选,默认20)
  548. }
  549. 响应:
  550. {
  551. "success": true,
  552. "platform": "douyin",
  553. "works": [...],
  554. "total": 100,
  555. "has_more": true
  556. }
  557. """
  558. try:
  559. data = request.json
  560. platform = data.get("platform", "").lower()
  561. cookie_str = data.get("cookie", "")
  562. page = data.get("page", 0)
  563. page_size = data.get("page_size", 20)
  564. print(f"[Works] 收到请求: platform={platform}, page={page}, page_size={page_size}")
  565. if not platform:
  566. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  567. if platform not in PLATFORM_MAP:
  568. return jsonify({
  569. "success": False,
  570. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  571. }), 400
  572. if not cookie_str:
  573. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  574. # 获取对应平台的发布器
  575. PublisherClass = get_publisher(platform)
  576. publisher = PublisherClass(headless=HEADLESS_MODE)
  577. # 执行获取作品
  578. result = asyncio.run(publisher.run_get_works(cookie_str, page, page_size))
  579. return jsonify(result.to_dict())
  580. except Exception as e:
  581. traceback.print_exc()
  582. return jsonify({"success": False, "error": str(e)}), 500
  583. # ==================== 保存作品日统计数据接口 ====================
  584. @app.route("/work_day_statistics", methods=["POST"])
  585. def save_work_day_statistics():
  586. """
  587. 保存作品每日统计数据
  588. 当天的数据走更新流,日期变化走新增流
  589. 请求体:
  590. {
  591. "statistics": [
  592. {
  593. "work_id": 1,
  594. "fans_count": 1000,
  595. "play_count": 5000,
  596. "like_count": 200,
  597. "comment_count": 50,
  598. "share_count": 30,
  599. "collect_count": 100
  600. },
  601. ...
  602. ]
  603. }
  604. 响应:
  605. {
  606. "success": true,
  607. "inserted": 5,
  608. "updated": 3,
  609. "message": "保存成功"
  610. }
  611. """
  612. print("=" * 60, flush=True)
  613. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  614. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  615. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  616. print("=" * 60, flush=True)
  617. try:
  618. data = request.json
  619. statistics_list = data.get("statistics", [])
  620. if not statistics_list:
  621. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  622. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  623. # 调用 Node.js API 保存数据
  624. result = call_nodejs_api('POST', '/work-day-statistics', {
  625. 'statistics': statistics_list
  626. })
  627. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  628. return jsonify(result)
  629. except Exception as e:
  630. traceback.print_exc()
  631. return jsonify({"success": False, "error": str(e)}), 500
  632. @app.route("/work_day_statistics/trend", methods=["GET"])
  633. def get_statistics_trend():
  634. """
  635. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  636. 查询参数:
  637. user_id: 用户ID (必填)
  638. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  639. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  640. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  641. account_id: 账号ID (可选,不填则查询所有账号)
  642. 响应:
  643. {
  644. "success": true,
  645. "data": {
  646. "dates": ["01-16", "01-17", "01-18", ...],
  647. "fans": [100, 120, 130, ...],
  648. "views": [1000, 1200, 1500, ...],
  649. "likes": [50, 60, 70, ...],
  650. "comments": [10, 12, 15, ...],
  651. "shares": [5, 6, 8, ...],
  652. "collects": [20, 25, 30, ...]
  653. }
  654. }
  655. """
  656. try:
  657. user_id = request.args.get("user_id")
  658. days = request.args.get("days")
  659. start_date = request.args.get("start_date")
  660. end_date = request.args.get("end_date")
  661. account_id = request.args.get("account_id")
  662. if not user_id:
  663. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  664. # 调用 Node.js API 获取数据
  665. params = {"user_id": user_id}
  666. if days:
  667. params["days"] = days
  668. if start_date:
  669. params["start_date"] = start_date
  670. if end_date:
  671. params["end_date"] = end_date
  672. if account_id:
  673. params["account_id"] = account_id
  674. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  675. return jsonify(result)
  676. except Exception as e:
  677. traceback.print_exc()
  678. return jsonify({"success": False, "error": str(e)}), 500
  679. @app.route("/work_day_statistics/platforms", methods=["GET"])
  680. def get_statistics_by_platform():
  681. """
  682. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  683. 数据来源:
  684. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  685. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  686. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  687. 查询参数:
  688. user_id: 用户ID (必填)
  689. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  690. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  691. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  692. 响应:
  693. {
  694. "success": true,
  695. "data": [
  696. {
  697. "platform": "douyin",
  698. "fansCount": 1000,
  699. "fansIncrease": 50,
  700. "viewsCount": 5000,
  701. "likesCount": 200,
  702. "commentsCount": 30,
  703. "collectsCount": 100
  704. },
  705. ...
  706. ]
  707. }
  708. """
  709. try:
  710. user_id = request.args.get("user_id")
  711. days = request.args.get("days")
  712. start_date = request.args.get("start_date")
  713. end_date = request.args.get("end_date")
  714. if not user_id:
  715. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  716. # 调用 Node.js API 获取数据
  717. params = {"user_id": user_id}
  718. if days:
  719. params["days"] = days
  720. if start_date:
  721. params["start_date"] = start_date
  722. if end_date:
  723. params["end_date"] = end_date
  724. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  725. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  726. return jsonify(result)
  727. except Exception as e:
  728. traceback.print_exc()
  729. return jsonify({"success": False, "error": str(e)}), 500
  730. @app.route("/work_day_statistics/batch", methods=["POST"])
  731. def get_work_statistics_history():
  732. """
  733. 批量获取作品的历史统计数据
  734. 请求体:
  735. {
  736. "work_ids": [1, 2, 3],
  737. "start_date": "2025-01-01", # 可选
  738. "end_date": "2025-01-21" # 可选
  739. }
  740. 响应:
  741. {
  742. "success": true,
  743. "data": {
  744. "1": [
  745. {"record_date": "2025-01-20", "play_count": 100, ...},
  746. {"record_date": "2025-01-21", "play_count": 150, ...}
  747. ],
  748. ...
  749. }
  750. }
  751. """
  752. try:
  753. data = request.json
  754. work_ids = data.get("work_ids", [])
  755. start_date = data.get("start_date")
  756. end_date = data.get("end_date")
  757. if not work_ids:
  758. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  759. # 调用 Node.js API 获取数据
  760. request_data = {"work_ids": work_ids}
  761. if start_date:
  762. request_data["start_date"] = start_date
  763. if end_date:
  764. request_data["end_date"] = end_date
  765. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  766. return jsonify(result)
  767. except Exception as e:
  768. traceback.print_exc()
  769. return jsonify({"success": False, "error": str(e)}), 500
  770. @app.route("/work_day_statistics/overview", methods=["GET"])
  771. def get_overview():
  772. """
  773. 获取数据总览(账号列表和汇总统计)
  774. 查询参数:
  775. user_id: 用户ID (必填)
  776. 响应:
  777. {
  778. "success": true,
  779. "data": {
  780. "accounts": [
  781. {
  782. "id": 1,
  783. "nickname": "账号名称",
  784. "username": "账号ID",
  785. "avatarUrl": "头像URL",
  786. "platform": "douyin",
  787. "groupId": 1,
  788. "fansCount": 1000,
  789. "totalIncome": null,
  790. "yesterdayIncome": null,
  791. "totalViews": 5000,
  792. "yesterdayViews": 100,
  793. "yesterdayComments": 10,
  794. "yesterdayLikes": 50,
  795. "yesterdayFansIncrease": 5,
  796. "updateTime": "2025-01-26T10:00:00Z",
  797. "status": "active"
  798. },
  799. ...
  800. ],
  801. "summary": {
  802. "totalAccounts": 5,
  803. "totalIncome": 0,
  804. "yesterdayIncome": 0,
  805. "totalViews": 10000,
  806. "yesterdayViews": 200,
  807. "totalFans": 5000,
  808. "yesterdayComments": 20,
  809. "yesterdayLikes": 100,
  810. "yesterdayFansIncrease": 10
  811. }
  812. }
  813. }
  814. """
  815. try:
  816. user_id = request.args.get("user_id")
  817. if not user_id:
  818. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  819. # 调用 Node.js API 获取数据
  820. params = {"user_id": user_id}
  821. result = call_nodejs_api('GET', '/work-day-statistics/overview', params=params)
  822. return jsonify(result)
  823. except NodeApiError as e:
  824. # 透传 Node 的真实状态码/错误内容,避免所有错误都变成 500
  825. return jsonify(e.payload), e.status_code
  826. except Exception as e:
  827. traceback.print_exc()
  828. return jsonify({"success": False, "error": str(e)}), 500
  829. # ==================== 获取评论列表接口 ====================
  830. @app.route("/comments", methods=["POST"])
  831. def get_comments():
  832. """
  833. 获取作品评论
  834. 请求体:
  835. {
  836. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  837. "cookie": "cookie字符串或JSON",
  838. "work_id": "作品ID",
  839. "cursor": "" # 分页游标(可选)
  840. }
  841. 响应:
  842. {
  843. "success": true,
  844. "platform": "douyin",
  845. "work_id": "xxx",
  846. "comments": [...],
  847. "total": 50,
  848. "has_more": true,
  849. "cursor": "xxx"
  850. }
  851. """
  852. try:
  853. data = request.json
  854. platform = data.get("platform", "").lower()
  855. cookie_str = data.get("cookie", "")
  856. work_id = data.get("work_id", "")
  857. cursor = data.get("cursor", "")
  858. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  859. if not platform:
  860. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  861. if platform not in PLATFORM_MAP:
  862. return jsonify({
  863. "success": False,
  864. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  865. }), 400
  866. if not cookie_str:
  867. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  868. if not work_id:
  869. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  870. # 获取对应平台的发布器
  871. PublisherClass = get_publisher(platform)
  872. publisher = PublisherClass(headless=HEADLESS_MODE)
  873. # 执行获取评论
  874. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  875. result_dict = result.to_dict()
  876. # 添加 cursor 到响应
  877. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  878. result_dict['cursor'] = result.__dict__['cursor']
  879. return jsonify(result_dict)
  880. except Exception as e:
  881. traceback.print_exc()
  882. return jsonify({"success": False, "error": str(e)}), 500
  883. # ==================== 获取所有作品评论接口 ====================
  884. @app.route("/all_comments", methods=["POST"])
  885. def get_all_comments():
  886. """
  887. 获取所有作品的评论(一次性获取)
  888. 请求体:
  889. {
  890. "platform": "douyin", # douyin | xiaohongshu
  891. "cookie": "cookie字符串或JSON"
  892. }
  893. 响应:
  894. {
  895. "success": true,
  896. "platform": "douyin",
  897. "work_comments": [
  898. {
  899. "work_id": "xxx",
  900. "title": "作品标题",
  901. "cover_url": "封面URL",
  902. "comments": [...]
  903. }
  904. ],
  905. "total": 5
  906. }
  907. """
  908. try:
  909. data = request.json
  910. platform = data.get("platform", "").lower()
  911. cookie_str = data.get("cookie", "")
  912. print(f"[AllComments] 收到请求: platform={platform}")
  913. if not platform:
  914. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  915. if platform not in ['douyin', 'xiaohongshu']:
  916. return jsonify({
  917. "success": False,
  918. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  919. }), 400
  920. if not cookie_str:
  921. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  922. # 获取对应平台的发布器
  923. PublisherClass = get_publisher(platform)
  924. publisher = PublisherClass(headless=HEADLESS_MODE)
  925. # 执行获取所有评论
  926. result = asyncio.run(publisher.get_all_comments(cookie_str))
  927. return jsonify(result)
  928. except Exception as e:
  929. traceback.print_exc()
  930. return jsonify({"success": False, "error": str(e)}), 500
  931. # ==================== 登录状态检查接口 ====================
  932. @app.route("/check_login", methods=["POST"])
  933. def check_login():
  934. """
  935. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  936. 请求体:
  937. {
  938. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  939. "cookie": "cookie字符串或JSON"
  940. }
  941. 响应:
  942. {
  943. "success": true,
  944. "valid": true, # Cookie 是否有效
  945. "need_login": false, # 是否需要重新登录
  946. "message": "登录状态有效"
  947. }
  948. """
  949. try:
  950. data = request.json
  951. platform = data.get("platform", "").lower()
  952. cookie_str = data.get("cookie", "")
  953. print(f"[CheckLogin] 收到请求: platform={platform}")
  954. if not platform:
  955. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  956. if platform not in PLATFORM_MAP:
  957. return jsonify({
  958. "success": False,
  959. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  960. }), 400
  961. if not cookie_str:
  962. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  963. # 获取对应平台的发布器
  964. PublisherClass = get_publisher(platform)
  965. publisher = PublisherClass(headless=HEADLESS_MODE)
  966. # 执行登录检查
  967. result = asyncio.run(publisher.check_login_status(cookie_str))
  968. return jsonify(result)
  969. except Exception as e:
  970. traceback.print_exc()
  971. return jsonify({
  972. "success": False,
  973. "valid": False,
  974. "need_login": True,
  975. "error": str(e)
  976. }), 500
  977. # ==================== 获取账号信息接口 ====================
  978. @app.route("/account_info", methods=["POST"])
  979. def get_account_info():
  980. """
  981. 获取账号信息
  982. 请求体:
  983. {
  984. "platform": "baijiahao", # 平台
  985. "cookie": "cookie字符串或JSON"
  986. }
  987. 响应:
  988. {
  989. "success": true,
  990. "account_id": "xxx",
  991. "account_name": "用户名",
  992. "avatar_url": "头像URL",
  993. "fans_count": 0,
  994. "works_count": 0
  995. }
  996. """
  997. try:
  998. data = request.json
  999. platform = data.get("platform", "").lower()
  1000. cookie_str = data.get("cookie", "")
  1001. print(f"[AccountInfo] 收到请求: platform={platform}")
  1002. if not platform:
  1003. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1004. if platform not in PLATFORM_MAP:
  1005. return jsonify({
  1006. "success": False,
  1007. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1008. }), 400
  1009. if not cookie_str:
  1010. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1011. # 获取对应平台的发布器
  1012. PublisherClass = get_publisher(platform)
  1013. publisher = PublisherClass(headless=HEADLESS_MODE)
  1014. # 检查是否有 get_account_info 方法
  1015. if hasattr(publisher, 'get_account_info'):
  1016. result = asyncio.run(publisher.get_account_info(cookie_str))
  1017. return jsonify(result)
  1018. else:
  1019. return jsonify({
  1020. "success": False,
  1021. "error": f"平台 {platform} 不支持获取账号信息"
  1022. }), 400
  1023. except Exception as e:
  1024. traceback.print_exc()
  1025. return jsonify({"success": False, "error": str(e)}), 500
  1026. # ==================== 健康检查 ====================
  1027. @app.route("/health", methods=["GET"])
  1028. def health_check():
  1029. """健康检查"""
  1030. # 检查 xhs SDK 是否可用
  1031. xhs_available = False
  1032. try:
  1033. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1034. xhs_available = XHS_SDK_AVAILABLE
  1035. except:
  1036. pass
  1037. return jsonify({
  1038. "status": "ok",
  1039. "xhs_sdk": xhs_available,
  1040. "supported_platforms": list(PLATFORM_MAP.keys()),
  1041. "headless_mode": HEADLESS_MODE
  1042. })
  1043. @app.route("/", methods=["GET"])
  1044. def index():
  1045. """首页"""
  1046. return jsonify({
  1047. "name": "多平台视频发布服务",
  1048. "version": "1.2.0",
  1049. "endpoints": {
  1050. "GET /": "服务信息",
  1051. "GET /health": "健康检查",
  1052. "POST /publish": "发布视频",
  1053. "POST /publish/batch": "批量发布",
  1054. "POST /works": "获取作品列表",
  1055. "POST /comments": "获取作品评论",
  1056. "POST /all_comments": "获取所有作品评论",
  1057. "POST /work_day_statistics": "保存作品每日统计数据",
  1058. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  1059. "POST /check_cookie": "检查 Cookie",
  1060. "POST /sign": "小红书签名"
  1061. },
  1062. "supported_platforms": list(PLATFORM_MAP.keys())
  1063. })
  1064. # ==================== 命令行启动 ====================
  1065. def main():
  1066. parser = argparse.ArgumentParser(description='多平台视频发布服务')
  1067. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  1068. # 从环境变量读取 HOST,默认仅本地访问
  1069. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  1070. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  1071. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  1072. parser.add_argument('--debug', action='store_true', help='调试模式')
  1073. args = parser.parse_args()
  1074. global HEADLESS_MODE
  1075. HEADLESS_MODE = args.headless.lower() == 'true'
  1076. # 检查 xhs SDK
  1077. xhs_status = "未安装"
  1078. try:
  1079. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1080. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  1081. except:
  1082. pass
  1083. print("=" * 60)
  1084. print("多平台视频发布服务")
  1085. print("=" * 60)
  1086. print(f"XHS SDK: {xhs_status}")
  1087. print(f"Headless 模式: {HEADLESS_MODE}")
  1088. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  1089. print("=" * 60)
  1090. print(f"启动服务: http://{args.host}:{args.port}")
  1091. print("=" * 60)
  1092. # 启用 debug 模式以获取详细日志,使用 use_reloader=False 避免重复启动
  1093. app.run(host=args.host, port=args.port, debug=True, threaded=True, use_reloader=False)
  1094. if __name__ == '__main__':
  1095. main()