app.py 52 KB

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