app.py 45 KB

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