app.py 54 KB

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