app.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  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. auto_paging = bool(data.get("auto_paging", False))
  566. print(f"[Works] 收到请求: platform={platform}, page={page}, page_size={page_size}, auto_paging={auto_paging}")
  567. if not platform:
  568. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  569. if platform not in PLATFORM_MAP:
  570. return jsonify({
  571. "success": False,
  572. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  573. }), 400
  574. if not cookie_str:
  575. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  576. # 获取对应平台的发布器
  577. PublisherClass = get_publisher(platform)
  578. publisher = PublisherClass(headless=HEADLESS_MODE)
  579. # 执行获取作品
  580. if platform == "xiaohongshu" and auto_paging and hasattr(publisher, "get_all_works"):
  581. result = asyncio.run(publisher.get_all_works(cookie_str))
  582. else:
  583. result = asyncio.run(publisher.run_get_works(cookie_str, page, page_size))
  584. return jsonify(result.to_dict())
  585. except Exception as e:
  586. traceback.print_exc()
  587. return jsonify({"success": False, "error": str(e)}), 500
  588. # ==================== 保存作品日统计数据接口 ====================
  589. @app.route("/work_day_statistics", methods=["POST"])
  590. def save_work_day_statistics():
  591. """
  592. 保存作品每日统计数据
  593. 当天的数据走更新流,日期变化走新增流
  594. 请求体:
  595. {
  596. "statistics": [
  597. {
  598. "work_id": 1,
  599. "fans_count": 1000,
  600. "play_count": 5000,
  601. "like_count": 200,
  602. "comment_count": 50,
  603. "share_count": 30,
  604. "collect_count": 100
  605. },
  606. ...
  607. ]
  608. }
  609. 响应:
  610. {
  611. "success": true,
  612. "inserted": 5,
  613. "updated": 3,
  614. "message": "保存成功"
  615. }
  616. """
  617. print("=" * 60, flush=True)
  618. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  619. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  620. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  621. print("=" * 60, flush=True)
  622. try:
  623. data = request.json
  624. statistics_list = data.get("statistics", [])
  625. if not statistics_list:
  626. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  627. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  628. # 调用 Node.js API 保存数据
  629. result = call_nodejs_api('POST', '/work-day-statistics', {
  630. 'statistics': statistics_list
  631. })
  632. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  633. return jsonify(result)
  634. except Exception as e:
  635. traceback.print_exc()
  636. return jsonify({"success": False, "error": str(e)}), 500
  637. @app.route("/work_day_statistics/trend", methods=["GET"])
  638. def get_statistics_trend():
  639. """
  640. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  641. 查询参数:
  642. user_id: 用户ID (必填)
  643. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  644. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  645. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  646. account_id: 账号ID (可选,不填则查询所有账号)
  647. 响应:
  648. {
  649. "success": true,
  650. "data": {
  651. "dates": ["01-16", "01-17", "01-18", ...],
  652. "fans": [100, 120, 130, ...],
  653. "views": [1000, 1200, 1500, ...],
  654. "likes": [50, 60, 70, ...],
  655. "comments": [10, 12, 15, ...],
  656. "shares": [5, 6, 8, ...],
  657. "collects": [20, 25, 30, ...]
  658. }
  659. }
  660. """
  661. try:
  662. user_id = request.args.get("user_id")
  663. days = request.args.get("days")
  664. start_date = request.args.get("start_date")
  665. end_date = request.args.get("end_date")
  666. account_id = request.args.get("account_id")
  667. if not user_id:
  668. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  669. # 调用 Node.js API 获取数据
  670. params = {"user_id": user_id}
  671. if days:
  672. params["days"] = days
  673. if start_date:
  674. params["start_date"] = start_date
  675. if end_date:
  676. params["end_date"] = end_date
  677. if account_id:
  678. params["account_id"] = account_id
  679. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  680. return jsonify(result)
  681. except Exception as e:
  682. traceback.print_exc()
  683. return jsonify({"success": False, "error": str(e)}), 500
  684. @app.route("/work_day_statistics/platforms", methods=["GET"])
  685. def get_statistics_by_platform():
  686. """
  687. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  688. 数据来源:
  689. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  690. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  691. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  692. 查询参数:
  693. user_id: 用户ID (必填)
  694. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  695. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  696. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  697. 响应:
  698. {
  699. "success": true,
  700. "data": [
  701. {
  702. "platform": "douyin",
  703. "fansCount": 1000,
  704. "fansIncrease": 50,
  705. "viewsCount": 5000,
  706. "likesCount": 200,
  707. "commentsCount": 30,
  708. "collectsCount": 100
  709. },
  710. ...
  711. ]
  712. }
  713. """
  714. try:
  715. user_id = request.args.get("user_id")
  716. days = request.args.get("days")
  717. start_date = request.args.get("start_date")
  718. end_date = request.args.get("end_date")
  719. if not user_id:
  720. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  721. # 调用 Node.js API 获取数据
  722. params = {"user_id": user_id}
  723. if days:
  724. params["days"] = days
  725. if start_date:
  726. params["start_date"] = start_date
  727. if end_date:
  728. params["end_date"] = end_date
  729. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  730. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  731. return jsonify(result)
  732. except Exception as e:
  733. traceback.print_exc()
  734. return jsonify({"success": False, "error": str(e)}), 500
  735. @app.route("/work_day_statistics/batch", methods=["POST"])
  736. def get_work_statistics_history():
  737. """
  738. 批量获取作品的历史统计数据
  739. 请求体:
  740. {
  741. "work_ids": [1, 2, 3],
  742. "start_date": "2025-01-01", # 可选
  743. "end_date": "2025-01-21" # 可选
  744. }
  745. 响应:
  746. {
  747. "success": true,
  748. "data": {
  749. "1": [
  750. {"record_date": "2025-01-20", "play_count": 100, ...},
  751. {"record_date": "2025-01-21", "play_count": 150, ...}
  752. ],
  753. ...
  754. }
  755. }
  756. """
  757. try:
  758. data = request.json
  759. work_ids = data.get("work_ids", [])
  760. start_date = data.get("start_date")
  761. end_date = data.get("end_date")
  762. if not work_ids:
  763. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  764. # 调用 Node.js API 获取数据
  765. request_data = {"work_ids": work_ids}
  766. if start_date:
  767. request_data["start_date"] = start_date
  768. if end_date:
  769. request_data["end_date"] = end_date
  770. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  771. return jsonify(result)
  772. except Exception as e:
  773. traceback.print_exc()
  774. return jsonify({"success": False, "error": str(e)}), 500
  775. @app.route("/work_day_statistics/overview", methods=["GET"])
  776. def get_overview():
  777. """
  778. 获取数据总览(账号列表和汇总统计)
  779. 查询参数:
  780. user_id: 用户ID (必填)
  781. 响应:
  782. {
  783. "success": true,
  784. "data": {
  785. "accounts": [
  786. {
  787. "id": 1,
  788. "nickname": "账号名称",
  789. "username": "账号ID",
  790. "avatarUrl": "头像URL",
  791. "platform": "douyin",
  792. "groupId": 1,
  793. "fansCount": 1000,
  794. "totalIncome": null,
  795. "yesterdayIncome": null,
  796. "totalViews": 5000,
  797. "yesterdayViews": 100,
  798. "yesterdayComments": 10,
  799. "yesterdayLikes": 50,
  800. "yesterdayFansIncrease": 5,
  801. "updateTime": "2025-01-26T10:00:00Z",
  802. "status": "active"
  803. },
  804. ...
  805. ],
  806. "summary": {
  807. "totalAccounts": 5,
  808. "totalIncome": 0,
  809. "yesterdayIncome": 0,
  810. "totalViews": 10000,
  811. "yesterdayViews": 200,
  812. "totalFans": 5000,
  813. "yesterdayComments": 20,
  814. "yesterdayLikes": 100,
  815. "yesterdayFansIncrease": 10
  816. }
  817. }
  818. }
  819. """
  820. try:
  821. user_id = request.args.get("user_id")
  822. if not user_id:
  823. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  824. # 调用 Node.js API 获取数据
  825. params = {"user_id": user_id}
  826. result = call_nodejs_api('GET', '/work-day-statistics/overview', params=params)
  827. return jsonify(result)
  828. except NodeApiError as e:
  829. # 透传 Node 的真实状态码/错误内容,避免所有错误都变成 500
  830. return jsonify(e.payload), e.status_code
  831. except Exception as e:
  832. traceback.print_exc()
  833. return jsonify({"success": False, "error": str(e)}), 500
  834. # ==================== 获取评论列表接口 ====================
  835. @app.route("/comments", methods=["POST"])
  836. def get_comments():
  837. """
  838. 获取作品评论
  839. 请求体:
  840. {
  841. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  842. "cookie": "cookie字符串或JSON",
  843. "work_id": "作品ID",
  844. "cursor": "" # 分页游标(可选)
  845. }
  846. 响应:
  847. {
  848. "success": true,
  849. "platform": "douyin",
  850. "work_id": "xxx",
  851. "comments": [...],
  852. "total": 50,
  853. "has_more": true,
  854. "cursor": "xxx"
  855. }
  856. """
  857. try:
  858. data = request.json
  859. platform = data.get("platform", "").lower()
  860. cookie_str = data.get("cookie", "")
  861. work_id = data.get("work_id", "")
  862. cursor = data.get("cursor", "")
  863. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  864. if not platform:
  865. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  866. if platform not in PLATFORM_MAP:
  867. return jsonify({
  868. "success": False,
  869. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  870. }), 400
  871. if not cookie_str:
  872. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  873. if not work_id:
  874. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  875. # 获取对应平台的发布器
  876. PublisherClass = get_publisher(platform)
  877. publisher = PublisherClass(headless=HEADLESS_MODE)
  878. # 执行获取评论
  879. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  880. result_dict = result.to_dict()
  881. # 添加 cursor 到响应
  882. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  883. result_dict['cursor'] = result.__dict__['cursor']
  884. return jsonify(result_dict)
  885. except Exception as e:
  886. traceback.print_exc()
  887. return jsonify({"success": False, "error": str(e)}), 500
  888. # ==================== 获取所有作品评论接口 ====================
  889. @app.route("/all_comments", methods=["POST"])
  890. def get_all_comments():
  891. """
  892. 获取所有作品的评论(一次性获取)
  893. 请求体:
  894. {
  895. "platform": "douyin", # douyin | xiaohongshu
  896. "cookie": "cookie字符串或JSON"
  897. }
  898. 响应:
  899. {
  900. "success": true,
  901. "platform": "douyin",
  902. "work_comments": [
  903. {
  904. "work_id": "xxx",
  905. "title": "作品标题",
  906. "cover_url": "封面URL",
  907. "comments": [...]
  908. }
  909. ],
  910. "total": 5
  911. }
  912. """
  913. try:
  914. data = request.json
  915. platform = data.get("platform", "").lower()
  916. cookie_str = data.get("cookie", "")
  917. print(f"[AllComments] 收到请求: platform={platform}")
  918. if not platform:
  919. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  920. if platform not in ['douyin', 'xiaohongshu']:
  921. return jsonify({
  922. "success": False,
  923. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  924. }), 400
  925. if not cookie_str:
  926. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  927. # 获取对应平台的发布器
  928. PublisherClass = get_publisher(platform)
  929. publisher = PublisherClass(headless=HEADLESS_MODE)
  930. # 执行获取所有评论
  931. result = asyncio.run(publisher.get_all_comments(cookie_str))
  932. return jsonify(result)
  933. except Exception as e:
  934. traceback.print_exc()
  935. return jsonify({"success": False, "error": str(e)}), 500
  936. # ==================== 登录状态检查接口 ====================
  937. @app.route("/check_login", methods=["POST"])
  938. def check_login():
  939. """
  940. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  941. 请求体:
  942. {
  943. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  944. "cookie": "cookie字符串或JSON"
  945. }
  946. 响应:
  947. {
  948. "success": true,
  949. "valid": true, # Cookie 是否有效
  950. "need_login": false, # 是否需要重新登录
  951. "message": "登录状态有效"
  952. }
  953. """
  954. try:
  955. data = request.json
  956. platform = data.get("platform", "").lower()
  957. cookie_str = data.get("cookie", "")
  958. print(f"[CheckLogin] 收到请求: platform={platform}")
  959. if not platform:
  960. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  961. if platform not in PLATFORM_MAP:
  962. return jsonify({
  963. "success": False,
  964. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  965. }), 400
  966. if not cookie_str:
  967. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  968. # 获取对应平台的发布器
  969. PublisherClass = get_publisher(platform)
  970. publisher = PublisherClass(headless=HEADLESS_MODE)
  971. # 执行登录检查
  972. result = asyncio.run(publisher.check_login_status(cookie_str))
  973. return jsonify(result)
  974. except Exception as e:
  975. traceback.print_exc()
  976. return jsonify({
  977. "success": False,
  978. "valid": False,
  979. "need_login": True,
  980. "error": str(e)
  981. }), 500
  982. # ==================== 获取账号信息接口 ====================
  983. @app.route("/account_info", methods=["POST"])
  984. def get_account_info():
  985. """
  986. 获取账号信息
  987. 请求体:
  988. {
  989. "platform": "baijiahao", # 平台
  990. "cookie": "cookie字符串或JSON"
  991. }
  992. 响应:
  993. {
  994. "success": true,
  995. "account_id": "xxx",
  996. "account_name": "用户名",
  997. "avatar_url": "头像URL",
  998. "fans_count": 0,
  999. "works_count": 0
  1000. }
  1001. """
  1002. try:
  1003. data = request.json
  1004. platform = data.get("platform", "").lower()
  1005. cookie_str = data.get("cookie", "")
  1006. print(f"[AccountInfo] 收到请求: platform={platform}")
  1007. if not platform:
  1008. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1009. if platform not in PLATFORM_MAP:
  1010. return jsonify({
  1011. "success": False,
  1012. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1013. }), 400
  1014. if not cookie_str:
  1015. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1016. # 获取对应平台的发布器
  1017. PublisherClass = get_publisher(platform)
  1018. publisher = PublisherClass(headless=HEADLESS_MODE)
  1019. # 检查是否有 get_account_info 方法
  1020. if hasattr(publisher, 'get_account_info'):
  1021. result = asyncio.run(publisher.get_account_info(cookie_str))
  1022. return jsonify(result)
  1023. else:
  1024. return jsonify({
  1025. "success": False,
  1026. "error": f"平台 {platform} 不支持获取账号信息"
  1027. }), 400
  1028. except Exception as e:
  1029. traceback.print_exc()
  1030. return jsonify({"success": False, "error": str(e)}), 500
  1031. # ==================== 健康检查 ====================
  1032. @app.route("/health", methods=["GET"])
  1033. def health_check():
  1034. """健康检查"""
  1035. # 检查 xhs SDK 是否可用
  1036. xhs_available = False
  1037. try:
  1038. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1039. xhs_available = XHS_SDK_AVAILABLE
  1040. except:
  1041. pass
  1042. return jsonify({
  1043. "status": "ok",
  1044. "xhs_sdk": xhs_available,
  1045. "supported_platforms": list(PLATFORM_MAP.keys()),
  1046. "headless_mode": HEADLESS_MODE
  1047. })
  1048. @app.route("/", methods=["GET"])
  1049. def index():
  1050. """首页"""
  1051. return jsonify({
  1052. "name": "多平台视频发布服务",
  1053. "version": "1.2.0",
  1054. "endpoints": {
  1055. "GET /": "服务信息",
  1056. "GET /health": "健康检查",
  1057. "POST /publish": "发布视频",
  1058. "POST /publish/batch": "批量发布",
  1059. "POST /works": "获取作品列表",
  1060. "POST /comments": "获取作品评论",
  1061. "POST /all_comments": "获取所有作品评论",
  1062. "POST /work_day_statistics": "保存作品每日统计数据",
  1063. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  1064. "POST /check_cookie": "检查 Cookie",
  1065. "POST /sign": "小红书签名"
  1066. },
  1067. "supported_platforms": list(PLATFORM_MAP.keys())
  1068. })
  1069. # ==================== 命令行启动 ====================
  1070. def main():
  1071. parser = argparse.ArgumentParser(description='多平台视频发布服务')
  1072. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  1073. # 从环境变量读取 HOST,默认仅本地访问
  1074. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  1075. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  1076. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  1077. parser.add_argument('--debug', action='store_true', help='调试模式')
  1078. args = parser.parse_args()
  1079. global HEADLESS_MODE
  1080. HEADLESS_MODE = args.headless.lower() == 'true'
  1081. # 检查 xhs SDK
  1082. xhs_status = "未安装"
  1083. try:
  1084. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1085. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  1086. except:
  1087. pass
  1088. print("=" * 60)
  1089. print("多平台视频发布服务")
  1090. print("=" * 60)
  1091. print(f"XHS SDK: {xhs_status}")
  1092. print(f"Headless 模式: {HEADLESS_MODE}")
  1093. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  1094. print("=" * 60)
  1095. print(f"启动服务: http://{args.host}:{args.port}")
  1096. print("=" * 60)
  1097. # 启用 debug 模式以获取详细日志,使用 use_reloader=False 避免重复启动
  1098. app.run(host=args.host, port=args.port, debug=True, threaded=True, use_reloader=False)
  1099. @app.route('/auto-reply', methods=['POST'])
  1100. def auto_reply():
  1101. """
  1102. 微信视频号自动回复私信
  1103. POST /auto-reply
  1104. Body: {
  1105. "platform": "weixin",
  1106. "cookie": "..."
  1107. }
  1108. """
  1109. try:
  1110. data = request.json
  1111. platform = data.get('platform', '').lower()
  1112. cookie = data.get('cookie', '')
  1113. if platform != 'weixin':
  1114. return jsonify({
  1115. 'success': False,
  1116. 'error': '只支持微信视频号平台'
  1117. }), 400
  1118. if not cookie:
  1119. return jsonify({
  1120. 'success': False,
  1121. 'error': '缺少 Cookie'
  1122. }), 400
  1123. print(f"[API] 接收自动回复请求: platform={platform}")
  1124. # 创建 Publisher 实例
  1125. publisher = WeixinPublisher(headless=HEADLESS_MODE)
  1126. # 执行自动回复
  1127. loop = asyncio.new_event_loop()
  1128. asyncio.set_event_loop(loop)
  1129. result = loop.run_until_complete(publisher.auto_reply_private_messages(cookie))
  1130. loop.close()
  1131. print(f"[API] 自动回复结果: {result}")
  1132. return jsonify(result)
  1133. except Exception as e:
  1134. print(f"[API] 自动回复异常: {e}")
  1135. traceback.print_exc()
  1136. return jsonify({
  1137. 'success': False,
  1138. 'error': str(e)
  1139. }), 500
  1140. if __name__ == '__main__':
  1141. main()