app.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  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}", flush=True)
  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("/sync_weixin_account_works_daily_stats", methods=["POST"])
  791. def sync_weixin_account_works_daily_stats():
  792. """
  793. 纯浏览器批量同步视频号账号下所有(在库)作品的每日数据到 work_day_statistics。
  794. 流程:打开 statistic/post → 单篇视频 → 近30天 → 遍历列表,按 exportId 匹配作品,
  795. 匹配则点击查看 → 详情页近30天 → 下载表格 → 解析 CSV 存入 work_day_statistics。
  796. 请求体: {
  797. "works": [{"work_id": 906, "platform_video_id": "export/xxx"}, ...],
  798. "cookie": "...",
  799. "show_browser": false
  800. }
  801. """
  802. try:
  803. data = request.json or {}
  804. works = data.get("works", [])
  805. cookie_str = data.get("cookie", "")
  806. if not works or not cookie_str:
  807. return jsonify({
  808. "success": False,
  809. "error": "缺少 works 或 cookie 参数",
  810. }), 400
  811. show_browser = data.get("show_browser", False)
  812. if isinstance(show_browser, str):
  813. show_browser = show_browser.lower() in ("true", "1", "yes")
  814. headless = not show_browser
  815. def save_fn(stats_list):
  816. if not stats_list:
  817. return {"inserted": 0, "updated": 0}
  818. return call_nodejs_api("POST", "/work-day-statistics/batch-dates", {"statistics": stats_list})
  819. def update_works_fn(updates):
  820. if not updates:
  821. return {"updated": 0}
  822. return call_nodejs_api("POST", "/works/batch-update-from-csv", {"updates": updates})
  823. publisher = WeixinPublisher(headless=headless)
  824. result = asyncio.run(publisher.sync_account_works_daily_stats_via_browser(
  825. cookie_str, works, save_fn=save_fn, update_works_fn=update_works_fn, headless=headless
  826. ))
  827. if not result.get("success"):
  828. return jsonify({
  829. "success": False,
  830. "error": result.get("error", "同步失败"),
  831. }), 200
  832. works_updated = result.get("works_updated", 0)
  833. msg = f"批量同步完成: 处理 {result.get('total_processed', 0)} 个作品, 跳过 {result.get('total_skipped', 0)} 个, 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条"
  834. if works_updated > 0:
  835. msg += f", works 表更新 {works_updated} 条"
  836. return jsonify({
  837. "success": True,
  838. "message": msg,
  839. "total_processed": result.get("total_processed", 0),
  840. "total_skipped": result.get("total_skipped", 0),
  841. "inserted": result.get("inserted", 0),
  842. "updated": result.get("updated", 0),
  843. "works_updated": works_updated,
  844. })
  845. except Exception as e:
  846. traceback.print_exc()
  847. return jsonify({"success": False, "error": str(e)}), 500
  848. @app.route("/sync_weixin_work_daily_stats", methods=["POST"])
  849. def sync_weixin_work_daily_stats():
  850. """
  851. 通过浏览器自动化同步单个视频号作品的每日数据到 work_day_statistics。
  852. 请求体: { "work_id": 906, "platform_video_id": "export/xxx", "cookie": "..." }
  853. """
  854. try:
  855. data = request.json or {}
  856. work_id = data.get("work_id")
  857. platform_video_id = (data.get("platform_video_id") or "").strip()
  858. cookie_str = data.get("cookie", "")
  859. if not work_id or not platform_video_id or not cookie_str:
  860. return jsonify({
  861. "success": False,
  862. "error": "缺少 work_id、platform_video_id 或 cookie 参数",
  863. }), 400
  864. work_id = int(work_id)
  865. # show_browser=True 时显示浏览器窗口,便于观察点击操作
  866. show_browser = data.get("show_browser", True)
  867. if isinstance(show_browser, str):
  868. show_browser = show_browser.lower() in ("true", "1", "yes")
  869. headless = not show_browser
  870. print(f"[SyncWXDailyStats] headless={headless} (show_browser={show_browser})", flush=True)
  871. publisher = WeixinPublisher(headless=headless)
  872. result = asyncio.run(publisher.sync_work_daily_stats_via_browser(
  873. cookie_str, work_id, platform_video_id
  874. ))
  875. if not result.get("success"):
  876. return jsonify({
  877. "success": False,
  878. "error": result.get("error", "同步失败"),
  879. }), 200
  880. stats = result.get("statistics") or []
  881. if not stats:
  882. return jsonify({
  883. "success": True,
  884. "message": "无新数据需要保存",
  885. "inserted": 0,
  886. "updated": 0,
  887. })
  888. save_result = call_nodejs_api("POST", "/work-day-statistics/batch-dates", {
  889. "statistics": stats,
  890. })
  891. return jsonify({
  892. "success": True,
  893. "message": f"同步成功: 新增 {save_result.get('inserted', 0)} 条, 更新 {save_result.get('updated', 0)} 条",
  894. "inserted": save_result.get("inserted", 0),
  895. "updated": save_result.get("updated", 0),
  896. })
  897. except Exception as e:
  898. traceback.print_exc()
  899. return jsonify({"success": False, "error": str(e)}), 500
  900. # ==================== 保存作品日统计数据接口 ====================
  901. @app.route("/work_day_statistics", methods=["POST"])
  902. def save_work_day_statistics():
  903. """
  904. 保存作品每日统计数据
  905. 当天的数据走更新流,日期变化走新增流
  906. 请求体:
  907. {
  908. "statistics": [
  909. {
  910. "work_id": 1,
  911. "fans_count": 1000,
  912. "play_count": 5000,
  913. "like_count": 200,
  914. "comment_count": 50,
  915. "share_count": 30,
  916. "collect_count": 100
  917. },
  918. ...
  919. ]
  920. }
  921. 响应:
  922. {
  923. "success": true,
  924. "inserted": 5,
  925. "updated": 3,
  926. "message": "保存成功"
  927. }
  928. """
  929. print("=" * 60, flush=True)
  930. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  931. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  932. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  933. print("=" * 60, flush=True)
  934. try:
  935. data = request.json
  936. statistics_list = data.get("statistics", [])
  937. if not statistics_list:
  938. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  939. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  940. # 调用 Node.js API 保存数据
  941. result = call_nodejs_api('POST', '/work-day-statistics', {
  942. 'statistics': statistics_list
  943. })
  944. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  945. return jsonify(result)
  946. except Exception as e:
  947. traceback.print_exc()
  948. return jsonify({"success": False, "error": str(e)}), 500
  949. @app.route("/work_day_statistics/trend", methods=["GET"])
  950. def get_statistics_trend():
  951. """
  952. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  953. 查询参数:
  954. user_id: 用户ID (必填)
  955. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  956. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  957. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  958. account_id: 账号ID (可选,不填则查询所有账号)
  959. 响应:
  960. {
  961. "success": true,
  962. "data": {
  963. "dates": ["01-16", "01-17", "01-18", ...],
  964. "fans": [100, 120, 130, ...],
  965. "views": [1000, 1200, 1500, ...],
  966. "likes": [50, 60, 70, ...],
  967. "comments": [10, 12, 15, ...],
  968. "shares": [5, 6, 8, ...],
  969. "collects": [20, 25, 30, ...]
  970. }
  971. }
  972. """
  973. try:
  974. user_id = request.args.get("user_id")
  975. days = request.args.get("days")
  976. start_date = request.args.get("start_date")
  977. end_date = request.args.get("end_date")
  978. account_id = request.args.get("account_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. if days:
  984. params["days"] = days
  985. if start_date:
  986. params["start_date"] = start_date
  987. if end_date:
  988. params["end_date"] = end_date
  989. if account_id:
  990. params["account_id"] = account_id
  991. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  992. return jsonify(result)
  993. except Exception as e:
  994. traceback.print_exc()
  995. return jsonify({"success": False, "error": str(e)}), 500
  996. @app.route("/work_day_statistics/platforms", methods=["GET"])
  997. def get_statistics_by_platform():
  998. """
  999. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  1000. 数据来源:
  1001. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  1002. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  1003. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  1004. 查询参数:
  1005. user_id: 用户ID (必填)
  1006. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  1007. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  1008. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  1009. 响应:
  1010. {
  1011. "success": true,
  1012. "data": [
  1013. {
  1014. "platform": "douyin",
  1015. "fansCount": 1000,
  1016. "fansIncrease": 50,
  1017. "viewsCount": 5000,
  1018. "likesCount": 200,
  1019. "commentsCount": 30,
  1020. "collectsCount": 100
  1021. },
  1022. ...
  1023. ]
  1024. }
  1025. """
  1026. try:
  1027. user_id = request.args.get("user_id")
  1028. days = request.args.get("days")
  1029. start_date = request.args.get("start_date")
  1030. end_date = request.args.get("end_date")
  1031. if not user_id:
  1032. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1033. # 调用 Node.js API 获取数据
  1034. params = {"user_id": user_id}
  1035. if days:
  1036. params["days"] = days
  1037. if start_date:
  1038. params["start_date"] = start_date
  1039. if end_date:
  1040. params["end_date"] = end_date
  1041. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  1042. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  1043. return jsonify(result)
  1044. except Exception as e:
  1045. traceback.print_exc()
  1046. return jsonify({"success": False, "error": str(e)}), 500
  1047. @app.route("/work_day_statistics/batch", methods=["POST"])
  1048. def get_work_statistics_history():
  1049. """
  1050. 批量获取作品的历史统计数据
  1051. 请求体:
  1052. {
  1053. "work_ids": [1, 2, 3],
  1054. "start_date": "2025-01-01", # 可选
  1055. "end_date": "2025-01-21" # 可选
  1056. }
  1057. 响应:
  1058. {
  1059. "success": true,
  1060. "data": {
  1061. "1": [
  1062. {"record_date": "2025-01-20", "play_count": 100, ...},
  1063. {"record_date": "2025-01-21", "play_count": 150, ...}
  1064. ],
  1065. ...
  1066. }
  1067. }
  1068. """
  1069. try:
  1070. data = request.json
  1071. work_ids = data.get("work_ids", [])
  1072. start_date = data.get("start_date")
  1073. end_date = data.get("end_date")
  1074. if not work_ids:
  1075. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  1076. # 调用 Node.js API 获取数据
  1077. request_data = {"work_ids": work_ids}
  1078. if start_date:
  1079. request_data["start_date"] = start_date
  1080. if end_date:
  1081. request_data["end_date"] = end_date
  1082. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  1083. return jsonify(result)
  1084. except Exception as e:
  1085. traceback.print_exc()
  1086. return jsonify({"success": False, "error": str(e)}), 500
  1087. @app.route("/work_day_statistics/overview", methods=["GET"])
  1088. def get_overview():
  1089. """
  1090. 获取数据总览(账号列表和汇总统计)
  1091. 查询参数:
  1092. user_id: 用户ID (必填)
  1093. 响应:
  1094. {
  1095. "success": true,
  1096. "data": {
  1097. "accounts": [
  1098. {
  1099. "id": 1,
  1100. "nickname": "账号名称",
  1101. "username": "账号ID",
  1102. "avatarUrl": "头像URL",
  1103. "platform": "douyin",
  1104. "groupId": 1,
  1105. "fansCount": 1000,
  1106. "totalIncome": null,
  1107. "yesterdayIncome": null,
  1108. "totalViews": 5000,
  1109. "yesterdayViews": 100,
  1110. "yesterdayComments": 10,
  1111. "yesterdayLikes": 50,
  1112. "yesterdayFansIncrease": 5,
  1113. "updateTime": "2025-01-26T10:00:00Z",
  1114. "status": "active"
  1115. },
  1116. ...
  1117. ],
  1118. "summary": {
  1119. "totalAccounts": 5,
  1120. "totalIncome": 0,
  1121. "yesterdayIncome": 0,
  1122. "totalViews": 10000,
  1123. "yesterdayViews": 200,
  1124. "totalFans": 5000,
  1125. "yesterdayComments": 20,
  1126. "yesterdayLikes": 100,
  1127. "yesterdayFansIncrease": 10
  1128. }
  1129. }
  1130. }
  1131. """
  1132. try:
  1133. user_id = request.args.get("user_id")
  1134. if not user_id:
  1135. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1136. # 调用 Node.js API 获取数据
  1137. params = {"user_id": user_id}
  1138. result = call_nodejs_api('GET', '/work-day-statistics/overview', params=params)
  1139. return jsonify(result)
  1140. except NodeApiError as e:
  1141. # 透传 Node 的真实状态码/错误内容,避免所有错误都变成 500
  1142. return jsonify(e.payload), e.status_code
  1143. except Exception as e:
  1144. traceback.print_exc()
  1145. return jsonify({"success": False, "error": str(e)}), 500
  1146. # ==================== 获取评论列表接口 ====================
  1147. @app.route("/comments", methods=["POST"])
  1148. def get_comments():
  1149. """
  1150. 获取作品评论
  1151. 请求体:
  1152. {
  1153. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  1154. "cookie": "cookie字符串或JSON",
  1155. "work_id": "作品ID",
  1156. "cursor": "" # 分页游标(可选)
  1157. }
  1158. 响应:
  1159. {
  1160. "success": true,
  1161. "platform": "douyin",
  1162. "work_id": "xxx",
  1163. "comments": [...],
  1164. "total": 50,
  1165. "has_more": true,
  1166. "cursor": "xxx"
  1167. }
  1168. """
  1169. try:
  1170. data = request.json
  1171. platform = data.get("platform", "").lower()
  1172. cookie_str = data.get("cookie", "")
  1173. work_id = data.get("work_id", "")
  1174. cursor = data.get("cursor", "")
  1175. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  1176. if not platform:
  1177. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1178. if platform not in PLATFORM_MAP:
  1179. return jsonify({
  1180. "success": False,
  1181. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1182. }), 400
  1183. if not cookie_str:
  1184. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1185. if not work_id:
  1186. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  1187. # 获取对应平台的发布器
  1188. PublisherClass = get_publisher(platform)
  1189. publisher = PublisherClass(headless=HEADLESS_MODE)
  1190. # 执行获取评论
  1191. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  1192. result_dict = result.to_dict()
  1193. # 添加 cursor 到响应
  1194. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  1195. result_dict['cursor'] = result.__dict__['cursor']
  1196. return jsonify(result_dict)
  1197. except Exception as e:
  1198. traceback.print_exc()
  1199. return jsonify({"success": False, "error": str(e)}), 500
  1200. # ==================== 获取所有作品评论接口 ====================
  1201. @app.route("/all_comments", methods=["POST"])
  1202. def get_all_comments():
  1203. """
  1204. 获取所有作品的评论(一次性获取)
  1205. 请求体:
  1206. {
  1207. "platform": "douyin", # douyin | xiaohongshu
  1208. "cookie": "cookie字符串或JSON"
  1209. }
  1210. 响应:
  1211. {
  1212. "success": true,
  1213. "platform": "douyin",
  1214. "work_comments": [
  1215. {
  1216. "work_id": "xxx",
  1217. "title": "作品标题",
  1218. "cover_url": "封面URL",
  1219. "comments": [...]
  1220. }
  1221. ],
  1222. "total": 5
  1223. }
  1224. """
  1225. try:
  1226. data = request.json
  1227. platform = data.get("platform", "").lower()
  1228. cookie_str = data.get("cookie", "")
  1229. print(f"[AllComments] 收到请求: platform={platform}")
  1230. if not platform:
  1231. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1232. if platform not in ['douyin', 'xiaohongshu']:
  1233. return jsonify({
  1234. "success": False,
  1235. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  1236. }), 400
  1237. if not cookie_str:
  1238. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1239. # 获取对应平台的发布器
  1240. PublisherClass = get_publisher(platform)
  1241. publisher = PublisherClass(headless=HEADLESS_MODE)
  1242. # 执行获取所有评论
  1243. result = asyncio.run(publisher.get_all_comments(cookie_str))
  1244. return jsonify(result)
  1245. except Exception as e:
  1246. traceback.print_exc()
  1247. return jsonify({"success": False, "error": str(e)}), 500
  1248. # ==================== 登录状态检查接口 ====================
  1249. @app.route("/check_login", methods=["POST"])
  1250. def check_login():
  1251. """
  1252. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  1253. 请求体:
  1254. {
  1255. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  1256. "cookie": "cookie字符串或JSON"
  1257. }
  1258. 响应:
  1259. {
  1260. "success": true,
  1261. "valid": true, # Cookie 是否有效
  1262. "need_login": false, # 是否需要重新登录
  1263. "message": "登录状态有效"
  1264. }
  1265. """
  1266. try:
  1267. data = request.json
  1268. platform = data.get("platform", "").lower()
  1269. cookie_str = data.get("cookie", "")
  1270. print(f"[CheckLogin] 收到请求: platform={platform}")
  1271. if not platform:
  1272. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1273. if platform not in PLATFORM_MAP:
  1274. return jsonify({
  1275. "success": False,
  1276. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1277. }), 400
  1278. if not cookie_str:
  1279. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1280. # 获取对应平台的发布器
  1281. PublisherClass = get_publisher(platform)
  1282. publisher = PublisherClass(headless=HEADLESS_MODE)
  1283. # 执行登录检查
  1284. result = asyncio.run(publisher.check_login_status(cookie_str))
  1285. return jsonify(result)
  1286. except Exception as e:
  1287. traceback.print_exc()
  1288. return jsonify({
  1289. "success": False,
  1290. "valid": False,
  1291. "need_login": True,
  1292. "error": str(e)
  1293. }), 500
  1294. # ==================== 获取账号信息接口 ====================
  1295. @app.route("/account_info", methods=["POST"])
  1296. def get_account_info():
  1297. """
  1298. 获取账号信息
  1299. 请求体:
  1300. {
  1301. "platform": "baijiahao", # 平台
  1302. "cookie": "cookie字符串或JSON"
  1303. }
  1304. 响应:
  1305. {
  1306. "success": true,
  1307. "account_id": "xxx",
  1308. "account_name": "用户名",
  1309. "avatar_url": "头像URL",
  1310. "fans_count": 0,
  1311. "works_count": 0
  1312. }
  1313. """
  1314. try:
  1315. data = request.json
  1316. platform = data.get("platform", "").lower()
  1317. cookie_str = data.get("cookie", "")
  1318. print(f"[AccountInfo] 收到请求: platform={platform}")
  1319. if not platform:
  1320. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1321. if platform not in PLATFORM_MAP:
  1322. return jsonify({
  1323. "success": False,
  1324. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1325. }), 400
  1326. if not cookie_str:
  1327. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1328. # 获取对应平台的发布器
  1329. PublisherClass = get_publisher(platform)
  1330. publisher = PublisherClass(headless=HEADLESS_MODE)
  1331. # 检查是否有 get_account_info 方法
  1332. if hasattr(publisher, 'get_account_info'):
  1333. result = asyncio.run(publisher.get_account_info(cookie_str))
  1334. return jsonify(result)
  1335. else:
  1336. return jsonify({
  1337. "success": False,
  1338. "error": f"平台 {platform} 不支持获取账号信息"
  1339. }), 400
  1340. except Exception as e:
  1341. traceback.print_exc()
  1342. return jsonify({"success": False, "error": str(e)}), 500
  1343. # ==================== 百家号作品每日数据辅助接口 ====================
  1344. @app.route("/baijiahao/article_stats", methods=["POST"])
  1345. def baijiahao_article_stats():
  1346. """
  1347. 百家号:代理调用 /author/eco/statistics/articleListStatistic
  1348. 请求体:
  1349. {
  1350. "cookie": "...",
  1351. "start_day": "YYYYMMDD",
  1352. "end_day": "YYYYMMDD",
  1353. "type": "small_video_v2|video|news",
  1354. "num": 1,
  1355. "count": 10
  1356. }
  1357. """
  1358. try:
  1359. data = request.json or {}
  1360. cookie_str = data.get("cookie", "")
  1361. start_day = data.get("start_day", "")
  1362. end_day = data.get("end_day", "")
  1363. stat_type = data.get("type", "video")
  1364. num = int(data.get("num", 1) or 1)
  1365. count = int(data.get("count", 10) or 10)
  1366. if not cookie_str:
  1367. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1368. if not start_day or not end_day:
  1369. return jsonify({"success": False, "error": "缺少 start_day 或 end_day 参数"}), 400
  1370. PublisherClass = get_publisher("baijiahao")
  1371. publisher = PublisherClass(headless=HEADLESS_MODE)
  1372. result = asyncio.run(
  1373. publisher.get_article_stats(
  1374. cookie_str,
  1375. start_day=start_day,
  1376. end_day=end_day,
  1377. stat_type=stat_type,
  1378. num=num,
  1379. count=count,
  1380. )
  1381. )
  1382. return jsonify(result)
  1383. except Exception as e:
  1384. traceback.print_exc()
  1385. return jsonify({"success": False, "error": str(e)}), 500
  1386. @app.route("/baijiahao/trend_data", methods=["POST"])
  1387. def baijiahao_trend_data():
  1388. """
  1389. 百家号:代理调用 /author/eco/statistic/gettrenddata
  1390. 请求体:
  1391. {
  1392. "cookie": "...",
  1393. "nid": "文章/视频 nid 或 article_id"
  1394. }
  1395. """
  1396. try:
  1397. data = request.json or {}
  1398. cookie_str = data.get("cookie", "")
  1399. nid = data.get("nid", "")
  1400. if not cookie_str:
  1401. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1402. if not nid:
  1403. return jsonify({"success": False, "error": "缺少 nid 参数"}), 400
  1404. PublisherClass = get_publisher("baijiahao")
  1405. publisher = PublisherClass(headless=HEADLESS_MODE)
  1406. result = asyncio.run(
  1407. publisher.get_trend_data(
  1408. cookie_str,
  1409. nid=str(nid),
  1410. )
  1411. )
  1412. return jsonify(result)
  1413. except Exception as e:
  1414. traceback.print_exc()
  1415. return jsonify({"success": False, "error": str(e)}), 500
  1416. # ==================== 健康检查 ====================
  1417. @app.route("/health", methods=["GET"])
  1418. def health_check():
  1419. """健康检查"""
  1420. # 检查 xhs SDK 是否可用
  1421. xhs_available = False
  1422. try:
  1423. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1424. xhs_available = XHS_SDK_AVAILABLE
  1425. except:
  1426. pass
  1427. return jsonify({
  1428. "status": "ok",
  1429. "xhs_sdk": xhs_available,
  1430. "supported_platforms": list(PLATFORM_MAP.keys()),
  1431. "headless_mode": HEADLESS_MODE
  1432. })
  1433. @app.route("/", methods=["GET"])
  1434. def index():
  1435. """首页"""
  1436. return jsonify({
  1437. "name": "智媒通视频发布服务",
  1438. "version": "1.2.0",
  1439. "endpoints": {
  1440. "GET /": "服务信息",
  1441. "GET /health": "健康检查",
  1442. "POST /publish": "发布视频",
  1443. "POST /publish/batch": "批量发布",
  1444. "POST /works": "获取作品列表",
  1445. "POST /comments": "获取作品评论",
  1446. "POST /all_comments": "获取所有作品评论",
  1447. "POST /work_day_statistics": "保存作品每日统计数据",
  1448. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  1449. "POST /check_cookie": "检查 Cookie",
  1450. "POST /sign": "小红书签名"
  1451. },
  1452. "supported_platforms": list(PLATFORM_MAP.keys())
  1453. })
  1454. # ==================== 命令行启动 ====================
  1455. def main():
  1456. parser = argparse.ArgumentParser(description='智媒通视频发布服务')
  1457. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  1458. # 从环境变量读取 HOST,默认仅本地访问
  1459. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  1460. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  1461. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  1462. parser.add_argument('--debug', action='store_true', help='调试模式')
  1463. args = parser.parse_args()
  1464. global HEADLESS_MODE
  1465. HEADLESS_MODE = args.headless.lower() == 'true'
  1466. # 检查 xhs SDK
  1467. xhs_status = "未安装"
  1468. try:
  1469. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1470. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  1471. except:
  1472. pass
  1473. print("=" * 60)
  1474. print("智媒通视频发布服务")
  1475. print("=" * 60)
  1476. print(f"XHS SDK: {xhs_status}")
  1477. print(f"Headless 模式: {HEADLESS_MODE}")
  1478. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  1479. print("=" * 60)
  1480. print(f"启动服务: http://{args.host}:{args.port}")
  1481. print("=" * 60)
  1482. app.run(host=args.host, port=args.port, debug=bool(args.debug), threaded=True, use_reloader=False)
  1483. @app.route('/auto-reply', methods=['POST'])
  1484. def auto_reply():
  1485. """
  1486. 微信视频号自动回复私信
  1487. POST /auto-reply
  1488. Body: {
  1489. "platform": "weixin",
  1490. "cookie": "..."
  1491. }
  1492. """
  1493. try:
  1494. data = request.json
  1495. platform = data.get('platform', '').lower()
  1496. cookie = data.get('cookie', '')
  1497. if platform != 'weixin':
  1498. return jsonify({
  1499. 'success': False,
  1500. 'error': '只支持微信视频号平台'
  1501. }), 400
  1502. if not cookie:
  1503. return jsonify({
  1504. 'success': False,
  1505. 'error': '缺少 Cookie'
  1506. }), 400
  1507. print(f"[API] 接收自动回复请求: platform={platform}")
  1508. # 创建 Publisher 实例
  1509. publisher = WeixinPublisher(headless=HEADLESS_MODE)
  1510. # 执行自动回复
  1511. loop = asyncio.new_event_loop()
  1512. asyncio.set_event_loop(loop)
  1513. result = loop.run_until_complete(publisher.auto_reply_private_messages(cookie))
  1514. loop.close()
  1515. print(f"[API] 自动回复结果: {result}")
  1516. return jsonify(result)
  1517. except Exception as e:
  1518. print(f"[API] 自动回复异常: {e}")
  1519. traceback.print_exc()
  1520. return jsonify({
  1521. 'success': False,
  1522. 'error': str(e)
  1523. }), 500
  1524. if __name__ == '__main__':
  1525. main()