app.py 51 KB

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