app.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. def call_nodejs_api(method: str, endpoint: str, data: dict = None, params: dict = None) -> dict:
  135. """调用 Node.js 内部 API"""
  136. url = f"{NODEJS_API_BASE_URL}/api/internal{endpoint}"
  137. headers = {
  138. 'Content-Type': 'application/json',
  139. 'X-Internal-API-Key': INTERNAL_API_KEY,
  140. }
  141. try:
  142. if method.upper() == 'GET':
  143. response = requests.get(url, headers=headers, params=params, timeout=30)
  144. elif method.upper() == 'POST':
  145. response = requests.post(url, headers=headers, json=data, timeout=30)
  146. else:
  147. raise ValueError(f"Unsupported HTTP method: {method}")
  148. response.raise_for_status()
  149. return response.json()
  150. except requests.exceptions.RequestException as e:
  151. print(f"[API Error] 调用 Node.js API 失败: {e}", flush=True)
  152. raise
  153. # ==================== 签名相关(小红书专用) ====================
  154. @app.route("/sign", methods=["POST"])
  155. def sign_endpoint():
  156. """小红书签名接口"""
  157. try:
  158. from platforms.xiaohongshu import XiaohongshuPublisher
  159. data = request.json
  160. publisher = XiaohongshuPublisher(headless=True)
  161. result = asyncio.run(publisher.get_sign(
  162. data.get("uri", ""),
  163. data.get("data"),
  164. data.get("a1", ""),
  165. data.get("web_session", "")
  166. ))
  167. return jsonify(result)
  168. except Exception as e:
  169. traceback.print_exc()
  170. return jsonify({"error": str(e)}), 500
  171. # ==================== 统一发布接口 ====================
  172. @app.route("/publish", methods=["POST"])
  173. def publish_video():
  174. """
  175. 统一发布接口
  176. 请求体:
  177. {
  178. "platform": "douyin", # douyin | xiaohongshu | weixin | kuaishou
  179. "cookie": "cookie字符串或JSON",
  180. "title": "视频标题",
  181. "description": "视频描述(可选)",
  182. "video_path": "视频文件绝对路径",
  183. "cover_path": "封面图片绝对路径(可选)",
  184. "tags": ["话题1", "话题2"],
  185. "post_time": "定时发布时间(可选,格式:2024-01-20 12:00:00)",
  186. "location": "位置(可选,默认:重庆市)"
  187. }
  188. 响应:
  189. {
  190. "success": true,
  191. "platform": "douyin",
  192. "video_id": "xxx",
  193. "video_url": "xxx",
  194. "message": "发布成功"
  195. }
  196. """
  197. try:
  198. data = request.json
  199. # 获取参数
  200. platform = data.get("platform", "").lower()
  201. cookie_str = data.get("cookie", "")
  202. title = data.get("title", "")
  203. description = data.get("description", "")
  204. video_path = data.get("video_path", "")
  205. cover_path = data.get("cover_path")
  206. tags = data.get("tags", [])
  207. post_time = data.get("post_time")
  208. location = data.get("location", "重庆市")
  209. # 调试日志
  210. print(f"[Publish] 收到请求: platform={platform}, title={title}, video_path={video_path}")
  211. # 参数验证
  212. if not platform:
  213. print("[Publish] 错误: 缺少 platform 参数")
  214. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  215. if platform not in PLATFORM_MAP:
  216. print(f"[Publish] 错误: 不支持的平台 {platform}")
  217. return jsonify({
  218. "success": False,
  219. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  220. }), 400
  221. if not cookie_str:
  222. print("[Publish] 错误: 缺少 cookie 参数")
  223. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  224. if not title:
  225. print("[Publish] 错误: 缺少 title 参数")
  226. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  227. if not video_path:
  228. print("[Publish] 错误: 缺少 video_path 参数")
  229. return jsonify({"success": False, "error": "缺少 video_path 参数"}), 400
  230. # 视频文件验证(增加详细信息)
  231. if not os.path.exists(video_path):
  232. print(f"[Publish] 错误: 视频文件不存在: {video_path}")
  233. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  234. if not os.path.isfile(video_path):
  235. print(f"[Publish] 错误: 路径不是文件: {video_path}")
  236. return jsonify({"success": False, "error": f"路径不是文件: {video_path}"}), 400
  237. # 解析发布时间
  238. publish_date = parse_datetime(post_time) if post_time else None
  239. # 创建发布参数
  240. params = PublishParams(
  241. title=title,
  242. video_path=video_path,
  243. description=description,
  244. cover_path=cover_path,
  245. tags=tags,
  246. publish_date=publish_date,
  247. location=location
  248. )
  249. print("=" * 60)
  250. print(f"[Publish] 平台: {platform}")
  251. print(f"[Publish] 标题: {title}")
  252. print(f"[Publish] 视频: {video_path}")
  253. print(f"[Publish] 封面: {cover_path}")
  254. print(f"[Publish] 话题: {tags}")
  255. print(f"[Publish] 定时: {publish_date}")
  256. print("=" * 60)
  257. # 获取对应平台的发布器
  258. PublisherClass = get_publisher(platform)
  259. publisher = PublisherClass(headless=HEADLESS_MODE)
  260. # 执行发布
  261. result = asyncio.run(publisher.run(cookie_str, params))
  262. response_data = {
  263. "success": result.success,
  264. "platform": result.platform,
  265. "video_id": result.video_id,
  266. "video_url": result.video_url,
  267. "message": result.message,
  268. "error": result.error,
  269. "need_captcha": result.need_captcha,
  270. "captcha_type": result.captcha_type,
  271. "screenshot_base64": result.screenshot_base64,
  272. "page_url": result.page_url,
  273. "status": result.status
  274. }
  275. # 如果需要验证码,打印明确的日志
  276. if result.need_captcha:
  277. print(f"[Publish] 需要验证码: type={result.captcha_type}")
  278. return jsonify(response_data)
  279. except Exception as e:
  280. traceback.print_exc()
  281. return jsonify({"success": False, "error": str(e)}), 500
  282. # ==================== AI 辅助发布接口 ====================
  283. # 存储活跃的发布会话
  284. active_publish_sessions = {}
  285. @app.route("/publish/ai-assisted", methods=["POST"])
  286. def publish_ai_assisted():
  287. """
  288. AI 辅助发布接口
  289. 与普通发布接口的区别:
  290. 1. 发布过程中会返回截图供 AI 分析
  291. 2. 如果检测到需要验证码,返回截图和状态,等待外部处理
  292. 3. 支持继续发布(输入验证码后)
  293. 请求体:
  294. {
  295. "platform": "douyin",
  296. "cookie": "cookie字符串",
  297. "title": "视频标题",
  298. "video_path": "视频文件路径",
  299. ...
  300. "return_screenshot": true // 是否返回截图
  301. }
  302. 响应:
  303. {
  304. "success": true/false,
  305. "status": "success|failed|need_captcha|processing",
  306. "screenshot_base64": "...", // 当前页面截图
  307. "page_url": "...",
  308. ...
  309. }
  310. """
  311. # 立即打印请求日志,确保能看到
  312. print("\n" + "!" * 60, flush=True)
  313. print("!!! [AI-Assisted Publish] 收到请求 !!!", flush=True)
  314. print("!" * 60 + "\n", flush=True)
  315. try:
  316. data = request.json
  317. print(f"[AI-Assisted Publish] 请求数据: platform={data.get('platform')}, title={data.get('title')}", flush=True)
  318. # 获取参数
  319. platform = data.get("platform", "").lower()
  320. cookie_str = data.get("cookie", "")
  321. title = data.get("title", "")
  322. description = data.get("description", "")
  323. video_path = data.get("video_path", "")
  324. cover_path = data.get("cover_path")
  325. tags = data.get("tags", [])
  326. post_time = data.get("post_time")
  327. location = data.get("location", "重庆市")
  328. return_screenshot = data.get("return_screenshot", True)
  329. # 支持请求级别的 headless 参数,用于验证码场景下的有头浏览器模式
  330. headless = data.get("headless", HEADLESS_MODE)
  331. if isinstance(headless, str):
  332. headless = headless.lower() == 'true'
  333. # 参数验证
  334. if not platform:
  335. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  336. if platform not in PLATFORM_MAP:
  337. return jsonify({"success": False, "error": f"不支持的平台: {platform}"}), 400
  338. if not cookie_str:
  339. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  340. if not title:
  341. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  342. if not video_path or not os.path.exists(video_path):
  343. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  344. # 解析发布时间
  345. publish_date = parse_datetime(post_time) if post_time else None
  346. # 创建发布参数
  347. params = PublishParams(
  348. title=title,
  349. video_path=video_path,
  350. description=description,
  351. cover_path=cover_path,
  352. tags=tags,
  353. publish_date=publish_date,
  354. location=location
  355. )
  356. print("=" * 60)
  357. print(f"[AI Publish] 平台: {platform}")
  358. print(f"[AI Publish] 标题: {title}")
  359. print(f"[AI Publish] 视频: {video_path}")
  360. print(f"[AI Publish] Headless: {headless}")
  361. print("=" * 60)
  362. # 获取对应平台的发布器
  363. PublisherClass = get_publisher(platform)
  364. publisher = PublisherClass(headless=headless) # 使用请求参数中的 headless 值
  365. # 执行发布
  366. result = asyncio.run(publisher.run(cookie_str, params))
  367. response_data = {
  368. "success": result.success,
  369. "platform": result.platform,
  370. "video_id": result.video_id,
  371. "video_url": result.video_url,
  372. "message": result.message,
  373. "error": result.error,
  374. "need_captcha": result.need_captcha,
  375. "captcha_type": result.captcha_type,
  376. "status": result.status or ("success" if result.success else "failed"),
  377. "page_url": result.page_url
  378. }
  379. # 如果请求返回截图
  380. if return_screenshot and result.screenshot_base64:
  381. response_data["screenshot_base64"] = result.screenshot_base64
  382. return jsonify(response_data)
  383. except Exception as e:
  384. traceback.print_exc()
  385. return jsonify({"success": False, "error": str(e), "status": "error"}), 500
  386. # ==================== 批量发布接口 ====================
  387. @app.route("/publish/batch", methods=["POST"])
  388. def publish_batch():
  389. """
  390. 批量发布接口 - 发布到多个平台
  391. 请求体:
  392. {
  393. "platforms": ["douyin", "xiaohongshu"],
  394. "cookies": {
  395. "douyin": "cookie字符串",
  396. "xiaohongshu": "cookie字符串"
  397. },
  398. "title": "视频标题",
  399. "video_path": "视频文件绝对路径",
  400. ...
  401. }
  402. """
  403. try:
  404. data = request.json
  405. platforms = data.get("platforms", [])
  406. cookies = data.get("cookies", {})
  407. if not platforms:
  408. return jsonify({"success": False, "error": "缺少 platforms 参数"}), 400
  409. results = []
  410. for platform in platforms:
  411. platform = platform.lower()
  412. cookie_str = cookies.get(platform, "")
  413. if not cookie_str:
  414. results.append({
  415. "platform": platform,
  416. "success": False,
  417. "error": f"缺少 {platform} 的 cookie"
  418. })
  419. continue
  420. try:
  421. # 创建参数
  422. params = PublishParams(
  423. title=data.get("title", ""),
  424. video_path=data.get("video_path", ""),
  425. description=data.get("description", ""),
  426. cover_path=data.get("cover_path"),
  427. tags=data.get("tags", []),
  428. publish_date=parse_datetime(data.get("post_time")),
  429. location=data.get("location", "重庆市")
  430. )
  431. # 发布
  432. PublisherClass = get_publisher(platform)
  433. publisher = PublisherClass(headless=HEADLESS_MODE)
  434. result = asyncio.run(publisher.run(cookie_str, params))
  435. results.append({
  436. "platform": result.platform,
  437. "success": result.success,
  438. "video_id": result.video_id,
  439. "message": result.message,
  440. "error": result.error
  441. })
  442. except Exception as e:
  443. results.append({
  444. "platform": platform,
  445. "success": False,
  446. "error": str(e)
  447. })
  448. # 统计成功/失败数量
  449. success_count = sum(1 for r in results if r.get("success"))
  450. return jsonify({
  451. "success": success_count > 0,
  452. "total": len(platforms),
  453. "success_count": success_count,
  454. "fail_count": len(platforms) - success_count,
  455. "results": results
  456. })
  457. except Exception as e:
  458. traceback.print_exc()
  459. return jsonify({"success": False, "error": str(e)}), 500
  460. # ==================== Cookie 验证接口 ====================
  461. @app.route("/check_cookie", methods=["POST"])
  462. def check_cookie():
  463. """检查 cookie 是否有效"""
  464. try:
  465. data = request.json
  466. platform = data.get("platform", "").lower()
  467. cookie_str = data.get("cookie", "")
  468. if not cookie_str:
  469. return jsonify({"valid": False, "error": "缺少 cookie 参数"}), 400
  470. # 目前只支持小红书的 cookie 验证
  471. if platform == "xiaohongshu":
  472. try:
  473. from platforms.xiaohongshu import XiaohongshuPublisher, XHS_SDK_AVAILABLE
  474. if XHS_SDK_AVAILABLE:
  475. from xhs import XhsClient
  476. publisher = XiaohongshuPublisher()
  477. xhs_client = XhsClient(cookie_str, sign=publisher.sign_sync)
  478. info = xhs_client.get_self_info()
  479. if info:
  480. return jsonify({
  481. "valid": True,
  482. "user_info": {
  483. "user_id": info.get("user_id"),
  484. "nickname": info.get("nickname"),
  485. "avatar": info.get("images")
  486. }
  487. })
  488. except Exception as e:
  489. return jsonify({"valid": False, "error": str(e)})
  490. # 其他平台返回格式正确但未验证
  491. return jsonify({
  492. "valid": True,
  493. "message": "Cookie 格式正确,但未进行在线验证"
  494. })
  495. except Exception as e:
  496. traceback.print_exc()
  497. return jsonify({"valid": False, "error": str(e)})
  498. # ==================== 获取作品列表接口 ====================
  499. @app.route("/works", methods=["POST"])
  500. def get_works():
  501. """
  502. 获取作品列表
  503. 请求体:
  504. {
  505. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  506. "cookie": "cookie字符串或JSON",
  507. "page": 0, # 页码(从0开始,可选,默认0)
  508. "page_size": 20 # 每页数量(可选,默认20)
  509. }
  510. 响应:
  511. {
  512. "success": true,
  513. "platform": "douyin",
  514. "works": [...],
  515. "total": 100,
  516. "has_more": true
  517. }
  518. """
  519. try:
  520. data = request.json
  521. platform = data.get("platform", "").lower()
  522. cookie_str = data.get("cookie", "")
  523. page = data.get("page", 0)
  524. page_size = data.get("page_size", 20)
  525. print(f"[Works] 收到请求: platform={platform}, page={page}, page_size={page_size}")
  526. if not platform:
  527. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  528. if platform not in PLATFORM_MAP:
  529. return jsonify({
  530. "success": False,
  531. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  532. }), 400
  533. if not cookie_str:
  534. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  535. # 获取对应平台的发布器
  536. PublisherClass = get_publisher(platform)
  537. publisher = PublisherClass(headless=HEADLESS_MODE)
  538. # 执行获取作品
  539. result = asyncio.run(publisher.run_get_works(cookie_str, page, page_size))
  540. return jsonify(result.to_dict())
  541. except Exception as e:
  542. traceback.print_exc()
  543. return jsonify({"success": False, "error": str(e)}), 500
  544. # ==================== 保存作品日统计数据接口 ====================
  545. @app.route("/work_day_statistics", methods=["POST"])
  546. def save_work_day_statistics():
  547. """
  548. 保存作品每日统计数据
  549. 当天的数据走更新流,日期变化走新增流
  550. 请求体:
  551. {
  552. "statistics": [
  553. {
  554. "work_id": 1,
  555. "fans_count": 1000,
  556. "play_count": 5000,
  557. "like_count": 200,
  558. "comment_count": 50,
  559. "share_count": 30,
  560. "collect_count": 100
  561. },
  562. ...
  563. ]
  564. }
  565. 响应:
  566. {
  567. "success": true,
  568. "inserted": 5,
  569. "updated": 3,
  570. "message": "保存成功"
  571. }
  572. """
  573. print("=" * 60, flush=True)
  574. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  575. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  576. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  577. print("=" * 60, flush=True)
  578. try:
  579. data = request.json
  580. statistics_list = data.get("statistics", [])
  581. if not statistics_list:
  582. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  583. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  584. # 调用 Node.js API 保存数据
  585. result = call_nodejs_api('POST', '/work-day-statistics', {
  586. 'statistics': statistics_list
  587. })
  588. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  589. return jsonify(result)
  590. except Exception as e:
  591. traceback.print_exc()
  592. return jsonify({"success": False, "error": str(e)}), 500
  593. @app.route("/work_day_statistics/trend", methods=["GET"])
  594. def get_statistics_trend():
  595. """
  596. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  597. 查询参数:
  598. user_id: 用户ID (必填)
  599. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  600. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  601. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  602. account_id: 账号ID (可选,不填则查询所有账号)
  603. 响应:
  604. {
  605. "success": true,
  606. "data": {
  607. "dates": ["01-16", "01-17", "01-18", ...],
  608. "fans": [100, 120, 130, ...],
  609. "views": [1000, 1200, 1500, ...],
  610. "likes": [50, 60, 70, ...],
  611. "comments": [10, 12, 15, ...],
  612. "shares": [5, 6, 8, ...],
  613. "collects": [20, 25, 30, ...]
  614. }
  615. }
  616. """
  617. try:
  618. user_id = request.args.get("user_id")
  619. days = request.args.get("days")
  620. start_date = request.args.get("start_date")
  621. end_date = request.args.get("end_date")
  622. account_id = request.args.get("account_id")
  623. if not user_id:
  624. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  625. # 调用 Node.js API 获取数据
  626. params = {"user_id": user_id}
  627. if days:
  628. params["days"] = days
  629. if start_date:
  630. params["start_date"] = start_date
  631. if end_date:
  632. params["end_date"] = end_date
  633. if account_id:
  634. params["account_id"] = account_id
  635. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  636. return jsonify(result)
  637. except Exception as e:
  638. traceback.print_exc()
  639. return jsonify({"success": False, "error": str(e)}), 500
  640. @app.route("/work_day_statistics/platforms", methods=["GET"])
  641. def get_statistics_by_platform():
  642. """
  643. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  644. 数据来源:
  645. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  646. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  647. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  648. 查询参数:
  649. user_id: 用户ID (必填)
  650. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  651. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  652. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  653. 响应:
  654. {
  655. "success": true,
  656. "data": [
  657. {
  658. "platform": "douyin",
  659. "fansCount": 1000,
  660. "fansIncrease": 50,
  661. "viewsCount": 5000,
  662. "likesCount": 200,
  663. "commentsCount": 30,
  664. "collectsCount": 100
  665. },
  666. ...
  667. ]
  668. }
  669. """
  670. try:
  671. user_id = request.args.get("user_id")
  672. days = request.args.get("days")
  673. start_date = request.args.get("start_date")
  674. end_date = request.args.get("end_date")
  675. if not user_id:
  676. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  677. # 调用 Node.js API 获取数据
  678. params = {"user_id": user_id}
  679. if days:
  680. params["days"] = days
  681. if start_date:
  682. params["start_date"] = start_date
  683. if end_date:
  684. params["end_date"] = end_date
  685. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  686. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  687. return jsonify(result)
  688. except Exception as e:
  689. traceback.print_exc()
  690. return jsonify({"success": False, "error": str(e)}), 500
  691. @app.route("/work_day_statistics/batch", methods=["POST"])
  692. def get_work_statistics_history():
  693. """
  694. 批量获取作品的历史统计数据
  695. 请求体:
  696. {
  697. "work_ids": [1, 2, 3],
  698. "start_date": "2025-01-01", # 可选
  699. "end_date": "2025-01-21" # 可选
  700. }
  701. 响应:
  702. {
  703. "success": true,
  704. "data": {
  705. "1": [
  706. {"record_date": "2025-01-20", "play_count": 100, ...},
  707. {"record_date": "2025-01-21", "play_count": 150, ...}
  708. ],
  709. ...
  710. }
  711. }
  712. """
  713. try:
  714. data = request.json
  715. work_ids = data.get("work_ids", [])
  716. start_date = data.get("start_date")
  717. end_date = data.get("end_date")
  718. if not work_ids:
  719. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  720. # 调用 Node.js API 获取数据
  721. request_data = {"work_ids": work_ids}
  722. if start_date:
  723. request_data["start_date"] = start_date
  724. if end_date:
  725. request_data["end_date"] = end_date
  726. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  727. return jsonify(result)
  728. except Exception as e:
  729. traceback.print_exc()
  730. return jsonify({"success": False, "error": str(e)}), 500
  731. # ==================== 获取评论列表接口 ====================
  732. @app.route("/comments", methods=["POST"])
  733. def get_comments():
  734. """
  735. 获取作品评论
  736. 请求体:
  737. {
  738. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  739. "cookie": "cookie字符串或JSON",
  740. "work_id": "作品ID",
  741. "cursor": "" # 分页游标(可选)
  742. }
  743. 响应:
  744. {
  745. "success": true,
  746. "platform": "douyin",
  747. "work_id": "xxx",
  748. "comments": [...],
  749. "total": 50,
  750. "has_more": true,
  751. "cursor": "xxx"
  752. }
  753. """
  754. try:
  755. data = request.json
  756. platform = data.get("platform", "").lower()
  757. cookie_str = data.get("cookie", "")
  758. work_id = data.get("work_id", "")
  759. cursor = data.get("cursor", "")
  760. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  761. if not platform:
  762. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  763. if platform not in PLATFORM_MAP:
  764. return jsonify({
  765. "success": False,
  766. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  767. }), 400
  768. if not cookie_str:
  769. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  770. if not work_id:
  771. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  772. # 获取对应平台的发布器
  773. PublisherClass = get_publisher(platform)
  774. publisher = PublisherClass(headless=HEADLESS_MODE)
  775. # 执行获取评论
  776. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  777. result_dict = result.to_dict()
  778. # 添加 cursor 到响应
  779. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  780. result_dict['cursor'] = result.__dict__['cursor']
  781. return jsonify(result_dict)
  782. except Exception as e:
  783. traceback.print_exc()
  784. return jsonify({"success": False, "error": str(e)}), 500
  785. # ==================== 获取所有作品评论接口 ====================
  786. @app.route("/all_comments", methods=["POST"])
  787. def get_all_comments():
  788. """
  789. 获取所有作品的评论(一次性获取)
  790. 请求体:
  791. {
  792. "platform": "douyin", # douyin | xiaohongshu
  793. "cookie": "cookie字符串或JSON"
  794. }
  795. 响应:
  796. {
  797. "success": true,
  798. "platform": "douyin",
  799. "work_comments": [
  800. {
  801. "work_id": "xxx",
  802. "title": "作品标题",
  803. "cover_url": "封面URL",
  804. "comments": [...]
  805. }
  806. ],
  807. "total": 5
  808. }
  809. """
  810. try:
  811. data = request.json
  812. platform = data.get("platform", "").lower()
  813. cookie_str = data.get("cookie", "")
  814. print(f"[AllComments] 收到请求: platform={platform}")
  815. if not platform:
  816. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  817. if platform not in ['douyin', 'xiaohongshu']:
  818. return jsonify({
  819. "success": False,
  820. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  821. }), 400
  822. if not cookie_str:
  823. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  824. # 获取对应平台的发布器
  825. PublisherClass = get_publisher(platform)
  826. publisher = PublisherClass(headless=HEADLESS_MODE)
  827. # 执行获取所有评论
  828. result = asyncio.run(publisher.get_all_comments(cookie_str))
  829. return jsonify(result)
  830. except Exception as e:
  831. traceback.print_exc()
  832. return jsonify({"success": False, "error": str(e)}), 500
  833. # ==================== 登录状态检查接口 ====================
  834. @app.route("/check_login", methods=["POST"])
  835. def check_login():
  836. """
  837. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  838. 请求体:
  839. {
  840. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  841. "cookie": "cookie字符串或JSON"
  842. }
  843. 响应:
  844. {
  845. "success": true,
  846. "valid": true, # Cookie 是否有效
  847. "need_login": false, # 是否需要重新登录
  848. "message": "登录状态有效"
  849. }
  850. """
  851. try:
  852. data = request.json
  853. platform = data.get("platform", "").lower()
  854. cookie_str = data.get("cookie", "")
  855. print(f"[CheckLogin] 收到请求: platform={platform}")
  856. if not platform:
  857. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  858. if platform not in PLATFORM_MAP:
  859. return jsonify({
  860. "success": False,
  861. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  862. }), 400
  863. if not cookie_str:
  864. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  865. # 获取对应平台的发布器
  866. PublisherClass = get_publisher(platform)
  867. publisher = PublisherClass(headless=HEADLESS_MODE)
  868. # 执行登录检查
  869. result = asyncio.run(publisher.check_login_status(cookie_str))
  870. return jsonify(result)
  871. except Exception as e:
  872. traceback.print_exc()
  873. return jsonify({
  874. "success": False,
  875. "valid": False,
  876. "need_login": True,
  877. "error": str(e)
  878. }), 500
  879. # ==================== 获取账号信息接口 ====================
  880. @app.route("/account_info", methods=["POST"])
  881. def get_account_info():
  882. """
  883. 获取账号信息
  884. 请求体:
  885. {
  886. "platform": "baijiahao", # 平台
  887. "cookie": "cookie字符串或JSON"
  888. }
  889. 响应:
  890. {
  891. "success": true,
  892. "account_id": "xxx",
  893. "account_name": "用户名",
  894. "avatar_url": "头像URL",
  895. "fans_count": 0,
  896. "works_count": 0
  897. }
  898. """
  899. try:
  900. data = request.json
  901. platform = data.get("platform", "").lower()
  902. cookie_str = data.get("cookie", "")
  903. print(f"[AccountInfo] 收到请求: platform={platform}")
  904. if not platform:
  905. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  906. if platform not in PLATFORM_MAP:
  907. return jsonify({
  908. "success": False,
  909. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  910. }), 400
  911. if not cookie_str:
  912. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  913. # 获取对应平台的发布器
  914. PublisherClass = get_publisher(platform)
  915. publisher = PublisherClass(headless=HEADLESS_MODE)
  916. # 检查是否有 get_account_info 方法
  917. if hasattr(publisher, 'get_account_info'):
  918. result = asyncio.run(publisher.get_account_info(cookie_str))
  919. return jsonify(result)
  920. else:
  921. return jsonify({
  922. "success": False,
  923. "error": f"平台 {platform} 不支持获取账号信息"
  924. }), 400
  925. except Exception as e:
  926. traceback.print_exc()
  927. return jsonify({"success": False, "error": str(e)}), 500
  928. # ==================== 健康检查 ====================
  929. @app.route("/health", methods=["GET"])
  930. def health_check():
  931. """健康检查"""
  932. # 检查 xhs SDK 是否可用
  933. xhs_available = False
  934. try:
  935. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  936. xhs_available = XHS_SDK_AVAILABLE
  937. except:
  938. pass
  939. return jsonify({
  940. "status": "ok",
  941. "xhs_sdk": xhs_available,
  942. "supported_platforms": list(PLATFORM_MAP.keys()),
  943. "headless_mode": HEADLESS_MODE
  944. })
  945. @app.route("/", methods=["GET"])
  946. def index():
  947. """首页"""
  948. return jsonify({
  949. "name": "多平台视频发布服务",
  950. "version": "1.2.0",
  951. "endpoints": {
  952. "GET /": "服务信息",
  953. "GET /health": "健康检查",
  954. "POST /publish": "发布视频",
  955. "POST /publish/batch": "批量发布",
  956. "POST /works": "获取作品列表",
  957. "POST /comments": "获取作品评论",
  958. "POST /all_comments": "获取所有作品评论",
  959. "POST /work_day_statistics": "保存作品每日统计数据",
  960. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  961. "POST /check_cookie": "检查 Cookie",
  962. "POST /sign": "小红书签名"
  963. },
  964. "supported_platforms": list(PLATFORM_MAP.keys())
  965. })
  966. # ==================== 命令行启动 ====================
  967. def main():
  968. parser = argparse.ArgumentParser(description='多平台视频发布服务')
  969. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  970. # 从环境变量读取 HOST,默认仅本地访问
  971. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  972. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  973. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  974. parser.add_argument('--debug', action='store_true', help='调试模式')
  975. args = parser.parse_args()
  976. global HEADLESS_MODE
  977. HEADLESS_MODE = args.headless.lower() == 'true'
  978. # 检查 xhs SDK
  979. xhs_status = "未安装"
  980. try:
  981. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  982. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  983. except:
  984. pass
  985. print("=" * 60)
  986. print("多平台视频发布服务")
  987. print("=" * 60)
  988. print(f"XHS SDK: {xhs_status}")
  989. print(f"Headless 模式: {HEADLESS_MODE}")
  990. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  991. print("=" * 60)
  992. print(f"启动服务: http://{args.host}:{args.port}")
  993. print("=" * 60)
  994. # 启用 debug 模式以获取详细日志,使用 use_reloader=False 避免重复启动
  995. app.run(host=args.host, port=args.port, debug=True, threaded=True, use_reloader=False)
  996. if __name__ == '__main__':
  997. main()