app.py 47 KB

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