app.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963
  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. "screenshot_path": getattr(result, 'screenshot_path', '') or ''
  496. }
  497. # 如果需要验证码,打印明确的日志
  498. if result.need_captcha:
  499. print(f"[Publish] 需要验证码: type={result.captcha_type}")
  500. return jsonify(response_data)
  501. except Exception as e:
  502. traceback.print_exc()
  503. return jsonify({"success": False, "error": str(e)}), 500
  504. # ==================== AI 辅助发布接口 ====================
  505. # 存储活跃的发布会话
  506. active_publish_sessions = {}
  507. @app.route("/publish/ai-assisted", methods=["POST"])
  508. def publish_ai_assisted():
  509. """
  510. AI 辅助发布接口
  511. 与普通发布接口的区别:
  512. 1. 发布过程中会返回截图供 AI 分析
  513. 2. 如果检测到需要验证码,返回截图和状态,等待外部处理
  514. 3. 支持继续发布(输入验证码后)
  515. 请求体:
  516. {
  517. "platform": "douyin",
  518. "cookie": "cookie字符串",
  519. "title": "视频标题",
  520. "video_path": "视频文件路径",
  521. ...
  522. "return_screenshot": true // 是否返回截图
  523. }
  524. 响应:
  525. {
  526. "success": true/false,
  527. "status": "success|failed|need_captcha|processing",
  528. "screenshot_base64": "...", // 当前页面截图
  529. "page_url": "...",
  530. ...
  531. }
  532. """
  533. # 立即打印请求日志,确保能看到
  534. print("\n" + "!" * 60, flush=True)
  535. print("!!! [AI-Assisted Publish] 收到请求 !!!", flush=True)
  536. print("!" * 60 + "\n", flush=True)
  537. try:
  538. data = request.json
  539. print(f"[AI-Assisted Publish] 请求数据: platform={data.get('platform')}, title={data.get('title')}", flush=True)
  540. # 获取参数
  541. platform = data.get("platform", "").lower()
  542. cookie_str = data.get("cookie", "")
  543. title = data.get("title", "")
  544. description = data.get("description", "")
  545. video_path = data.get("video_path", "")
  546. cover_path = data.get("cover_path")
  547. tags = data.get("tags", [])
  548. post_time = data.get("post_time")
  549. location = data.get("location", "重庆市")
  550. return_screenshot = data.get("return_screenshot", True)
  551. # 支持请求级别的 headless 参数,用于验证码场景下的有头浏览器模式
  552. headless = data.get("headless", HEADLESS_MODE)
  553. if isinstance(headless, str):
  554. headless = headless.lower() == 'true'
  555. # 参数验证
  556. if not platform:
  557. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  558. if platform not in PLATFORM_MAP:
  559. return jsonify({"success": False, "error": f"不支持的平台: {platform}"}), 400
  560. if not cookie_str:
  561. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  562. if not title:
  563. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  564. if not video_path or not os.path.exists(video_path):
  565. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  566. # 解析发布时间
  567. publish_date = parse_datetime(post_time) if post_time else None
  568. # 创建发布参数
  569. params = PublishParams(
  570. title=title,
  571. video_path=video_path,
  572. description=description,
  573. cover_path=cover_path,
  574. tags=tags,
  575. publish_date=publish_date,
  576. location=location
  577. )
  578. print("=" * 60)
  579. print(f"[AI Publish] 平台: {platform}")
  580. print(f"[AI Publish] 标题: {title}")
  581. print(f"[AI Publish] 视频: {video_path}")
  582. print(f"[AI Publish] Headless: {headless}")
  583. print("=" * 60)
  584. # 获取对应平台的发布器
  585. PublisherClass = get_publisher(platform)
  586. publisher = PublisherClass(headless=headless) # 使用请求参数中的 headless 值
  587. proxy_payload = data.get('proxy')
  588. if isinstance(proxy_payload, dict) and proxy_payload.get('enabled'):
  589. provider = str(proxy_payload.get('provider') or 'shenlong').strip().lower()
  590. if provider == 'shenlong':
  591. proxy_payload_with_task = dict(proxy_payload)
  592. if data.get('publish_task_id') is not None:
  593. proxy_payload_with_task['publish_task_id'] = data.get('publish_task_id')
  594. publisher.proxy_config = _resolve_shenlong_proxy(proxy_payload_with_task)
  595. try:
  596. publisher.user_id = int(data.get("user_id")) if data.get("user_id") is not None else None
  597. except Exception:
  598. publisher.user_id = None
  599. try:
  600. publisher.publish_task_id = int(data.get("publish_task_id")) if data.get("publish_task_id") is not None else None
  601. except Exception:
  602. publisher.publish_task_id = None
  603. try:
  604. publisher.publish_account_id = int(data.get("publish_account_id")) if data.get("publish_account_id") is not None else None
  605. except Exception:
  606. publisher.publish_account_id = None
  607. # 执行发布
  608. result = asyncio.run(publisher.run(cookie_str, params))
  609. response_data = {
  610. "success": result.success,
  611. "platform": result.platform,
  612. "video_id": result.video_id,
  613. "video_url": result.video_url,
  614. "message": result.message,
  615. "error": result.error,
  616. "need_captcha": result.need_captcha,
  617. "captcha_type": result.captcha_type,
  618. "status": result.status or ("success" if result.success else "failed"),
  619. "page_url": result.page_url,
  620. "screenshot_path": getattr(result, 'screenshot_path', '') or ''
  621. }
  622. # 如果请求返回截图
  623. if return_screenshot and result.screenshot_base64:
  624. response_data["screenshot_base64"] = result.screenshot_base64
  625. return jsonify(response_data)
  626. except Exception as e:
  627. traceback.print_exc()
  628. return jsonify({"success": False, "error": str(e), "status": "error"}), 500
  629. # ==================== 批量发布接口 ====================
  630. @app.route("/publish/batch", methods=["POST"])
  631. def publish_batch():
  632. """
  633. 批量发布接口 - 发布到多个平台
  634. 请求体:
  635. {
  636. "platforms": ["douyin", "xiaohongshu"],
  637. "cookies": {
  638. "douyin": "cookie字符串",
  639. "xiaohongshu": "cookie字符串"
  640. },
  641. "title": "视频标题",
  642. "video_path": "视频文件绝对路径",
  643. ...
  644. }
  645. """
  646. try:
  647. data = request.json
  648. platforms = data.get("platforms", [])
  649. cookies = data.get("cookies", {})
  650. if not platforms:
  651. return jsonify({"success": False, "error": "缺少 platforms 参数"}), 400
  652. results = []
  653. for platform in platforms:
  654. platform = platform.lower()
  655. cookie_str = cookies.get(platform, "")
  656. if not cookie_str:
  657. results.append({
  658. "platform": platform,
  659. "success": False,
  660. "error": f"缺少 {platform} 的 cookie"
  661. })
  662. continue
  663. try:
  664. # 创建参数
  665. params = PublishParams(
  666. title=data.get("title", ""),
  667. video_path=data.get("video_path", ""),
  668. description=data.get("description", ""),
  669. cover_path=data.get("cover_path"),
  670. tags=data.get("tags", []),
  671. publish_date=parse_datetime(data.get("post_time")),
  672. location=data.get("location", "重庆市")
  673. )
  674. # 发布
  675. PublisherClass = get_publisher(platform)
  676. publisher = PublisherClass(headless=HEADLESS_MODE)
  677. result = asyncio.run(publisher.run(cookie_str, params))
  678. results.append({
  679. "platform": result.platform,
  680. "success": result.success,
  681. "video_id": result.video_id,
  682. "message": result.message,
  683. "error": result.error
  684. })
  685. except Exception as e:
  686. results.append({
  687. "platform": platform,
  688. "success": False,
  689. "error": str(e)
  690. })
  691. # 统计成功/失败数量
  692. success_count = sum(1 for r in results if r.get("success"))
  693. return jsonify({
  694. "success": success_count > 0,
  695. "total": len(platforms),
  696. "success_count": success_count,
  697. "fail_count": len(platforms) - success_count,
  698. "results": results
  699. })
  700. except Exception as e:
  701. traceback.print_exc()
  702. return jsonify({"success": False, "error": str(e)}), 500
  703. # ==================== Cookie 验证接口 ====================
  704. @app.route("/check_cookie", methods=["POST"])
  705. def check_cookie():
  706. """检查 cookie 是否有效"""
  707. try:
  708. data = request.json
  709. platform = data.get("platform", "").lower()
  710. cookie_str = data.get("cookie", "")
  711. if not cookie_str:
  712. return jsonify({"valid": False, "error": "缺少 cookie 参数"}), 400
  713. # 目前只支持小红书的 cookie 验证
  714. if platform == "xiaohongshu":
  715. try:
  716. from platforms.xiaohongshu import XiaohongshuPublisher, XHS_SDK_AVAILABLE
  717. if XHS_SDK_AVAILABLE:
  718. from xhs import XhsClient
  719. publisher = XiaohongshuPublisher()
  720. xhs_client = XhsClient(cookie_str, sign=publisher.sign_sync)
  721. info = xhs_client.get_self_info()
  722. if info:
  723. return jsonify({
  724. "valid": True,
  725. "user_info": {
  726. "user_id": info.get("user_id"),
  727. "nickname": info.get("nickname"),
  728. "avatar": info.get("images")
  729. }
  730. })
  731. except Exception as e:
  732. return jsonify({"valid": False, "error": str(e)})
  733. # 其他平台返回格式正确但未验证
  734. return jsonify({
  735. "valid": True,
  736. "message": "Cookie 格式正确,但未进行在线验证"
  737. })
  738. except Exception as e:
  739. traceback.print_exc()
  740. return jsonify({"valid": False, "error": str(e)})
  741. # ==================== 获取作品列表接口 ====================
  742. @app.route("/works", methods=["POST"])
  743. def get_works():
  744. """
  745. 获取作品列表
  746. 请求体:
  747. {
  748. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  749. "cookie": "cookie字符串或JSON",
  750. "page": 0, # 页码(从0开始,可选,默认0)
  751. "page_size": 20 # 每页数量(可选,默认20)
  752. }
  753. 响应:
  754. {
  755. "success": true,
  756. "platform": "douyin",
  757. "works": [...],
  758. "total": 100,
  759. "has_more": true
  760. }
  761. """
  762. try:
  763. data = request.json
  764. platform = data.get("platform", "").lower()
  765. cookie_str = data.get("cookie", "")
  766. page = data.get("page", 0)
  767. page_size = data.get("page_size", 20)
  768. auto_paging = bool(data.get("auto_paging", False))
  769. print(f"[Works] 收到请求: platform={platform}, page={page}, page_size={page_size}, auto_paging={auto_paging}", flush=True)
  770. if not platform:
  771. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  772. if platform not in PLATFORM_MAP:
  773. return jsonify({
  774. "success": False,
  775. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  776. }), 400
  777. if not cookie_str:
  778. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  779. # 获取对应平台的发布器
  780. PublisherClass = get_publisher(platform)
  781. publisher = PublisherClass(headless=HEADLESS_MODE)
  782. # 执行获取作品
  783. if platform == "xiaohongshu" and auto_paging and hasattr(publisher, "get_all_works"):
  784. result = asyncio.run(publisher.get_all_works(cookie_str))
  785. else:
  786. result = asyncio.run(publisher.run_get_works(cookie_str, page, page_size))
  787. return jsonify(result.to_dict())
  788. except Exception as e:
  789. traceback.print_exc()
  790. return jsonify({"success": False, "error": str(e)}), 500
  791. # ==================== 视频号同步作品每日数据(浏览器自动化) ====================
  792. @app.route("/sync_weixin_account_works_daily_stats", methods=["POST"])
  793. def sync_weixin_account_works_daily_stats():
  794. """
  795. 纯浏览器批量同步视频号账号下所有(在库)作品的每日数据到 work_day_statistics。
  796. 流程:打开 statistic/post → 单篇视频 → 近30天 → 遍历列表,按 exportId 匹配作品,
  797. 匹配则点击查看 → 详情页近30天 → 下载表格 → 解析 CSV 存入 work_day_statistics。
  798. 请求体: {
  799. "works": [{"work_id": 906, "platform_video_id": "export/xxx"}, ...],
  800. "cookie": "...",
  801. "show_browser": false
  802. }
  803. """
  804. try:
  805. data = request.json or {}
  806. works = data.get("works", [])
  807. cookie_str = data.get("cookie", "")
  808. if not works or not cookie_str:
  809. return jsonify({
  810. "success": False,
  811. "error": "缺少 works 或 cookie 参数",
  812. }), 400
  813. show_browser = data.get("show_browser", False)
  814. if isinstance(show_browser, str):
  815. show_browser = show_browser.lower() in ("true", "1", "yes")
  816. headless = not show_browser
  817. def save_fn(stats_list):
  818. if not stats_list:
  819. return {"inserted": 0, "updated": 0}
  820. return call_nodejs_api("POST", "/work-day-statistics/batch-dates", {"statistics": stats_list})
  821. def update_works_fn(updates):
  822. if not updates:
  823. return {"updated": 0}
  824. return call_nodejs_api("POST", "/works/batch-update-from-csv", {"updates": updates})
  825. publisher = WeixinPublisher(headless=headless)
  826. result = asyncio.run(publisher.sync_account_works_daily_stats_via_browser(
  827. cookie_str, works, save_fn=save_fn, update_works_fn=update_works_fn, headless=headless
  828. ))
  829. if not result.get("success"):
  830. return jsonify({
  831. "success": False,
  832. "error": result.get("error", "同步失败"),
  833. }), 200
  834. works_updated = result.get("works_updated", 0)
  835. msg = f"批量同步完成: 处理 {result.get('total_processed', 0)} 个作品, 跳过 {result.get('total_skipped', 0)} 个, 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条"
  836. if works_updated > 0:
  837. msg += f", works 表更新 {works_updated} 条"
  838. return jsonify({
  839. "success": True,
  840. "message": msg,
  841. "total_processed": result.get("total_processed", 0),
  842. "total_skipped": result.get("total_skipped", 0),
  843. "inserted": result.get("inserted", 0),
  844. "updated": result.get("updated", 0),
  845. "works_updated": works_updated,
  846. })
  847. except Exception as e:
  848. traceback.print_exc()
  849. return jsonify({"success": False, "error": str(e)}), 500
  850. @app.route("/sync_weixin_work_daily_stats", methods=["POST"])
  851. def sync_weixin_work_daily_stats():
  852. """
  853. 通过浏览器自动化同步单个视频号作品的每日数据到 work_day_statistics。
  854. 请求体: { "work_id": 906, "platform_video_id": "export/xxx", "cookie": "..." }
  855. """
  856. try:
  857. data = request.json or {}
  858. work_id = data.get("work_id")
  859. platform_video_id = (data.get("platform_video_id") or "").strip()
  860. cookie_str = data.get("cookie", "")
  861. if not work_id or not platform_video_id or not cookie_str:
  862. return jsonify({
  863. "success": False,
  864. "error": "缺少 work_id、platform_video_id 或 cookie 参数",
  865. }), 400
  866. work_id = int(work_id)
  867. # show_browser=True 时显示浏览器窗口,便于观察点击操作
  868. show_browser = data.get("show_browser", True)
  869. if isinstance(show_browser, str):
  870. show_browser = show_browser.lower() in ("true", "1", "yes")
  871. headless = not show_browser
  872. print(f"[SyncWXDailyStats] headless={headless} (show_browser={show_browser})", flush=True)
  873. publisher = WeixinPublisher(headless=headless)
  874. result = asyncio.run(publisher.sync_work_daily_stats_via_browser(
  875. cookie_str, work_id, platform_video_id
  876. ))
  877. if not result.get("success"):
  878. return jsonify({
  879. "success": False,
  880. "error": result.get("error", "同步失败"),
  881. }), 200
  882. stats = result.get("statistics") or []
  883. if not stats:
  884. return jsonify({
  885. "success": True,
  886. "message": "无新数据需要保存",
  887. "inserted": 0,
  888. "updated": 0,
  889. })
  890. save_result = call_nodejs_api("POST", "/work-day-statistics/batch-dates", {
  891. "statistics": stats,
  892. })
  893. return jsonify({
  894. "success": True,
  895. "message": f"同步成功: 新增 {save_result.get('inserted', 0)} 条, 更新 {save_result.get('updated', 0)} 条",
  896. "inserted": save_result.get("inserted", 0),
  897. "updated": save_result.get("updated", 0),
  898. })
  899. except Exception as e:
  900. traceback.print_exc()
  901. return jsonify({"success": False, "error": str(e)}), 500
  902. # ==================== 保存作品日统计数据接口 ====================
  903. @app.route("/work_day_statistics", methods=["POST"])
  904. def save_work_day_statistics():
  905. """
  906. 保存作品每日统计数据
  907. 当天的数据走更新流,日期变化走新增流
  908. 请求体:
  909. {
  910. "statistics": [
  911. {
  912. "work_id": 1,
  913. "fans_count": 1000,
  914. "play_count": 5000,
  915. "like_count": 200,
  916. "comment_count": 50,
  917. "share_count": 30,
  918. "collect_count": 100
  919. },
  920. ...
  921. ]
  922. }
  923. 响应:
  924. {
  925. "success": true,
  926. "inserted": 5,
  927. "updated": 3,
  928. "message": "保存成功"
  929. }
  930. """
  931. print("=" * 60, flush=True)
  932. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  933. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  934. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  935. print("=" * 60, flush=True)
  936. try:
  937. data = request.json
  938. statistics_list = data.get("statistics", [])
  939. if not statistics_list:
  940. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  941. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  942. # 调用 Node.js API 保存数据
  943. result = call_nodejs_api('POST', '/work-day-statistics', {
  944. 'statistics': statistics_list
  945. })
  946. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  947. return jsonify(result)
  948. except Exception as e:
  949. traceback.print_exc()
  950. return jsonify({"success": False, "error": str(e)}), 500
  951. @app.route("/work_day_statistics/trend", methods=["GET"])
  952. def get_statistics_trend():
  953. """
  954. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  955. 查询参数:
  956. user_id: 用户ID (必填)
  957. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  958. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  959. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  960. account_id: 账号ID (可选,不填则查询所有账号)
  961. 响应:
  962. {
  963. "success": true,
  964. "data": {
  965. "dates": ["01-16", "01-17", "01-18", ...],
  966. "fans": [100, 120, 130, ...],
  967. "views": [1000, 1200, 1500, ...],
  968. "likes": [50, 60, 70, ...],
  969. "comments": [10, 12, 15, ...],
  970. "shares": [5, 6, 8, ...],
  971. "collects": [20, 25, 30, ...]
  972. }
  973. }
  974. """
  975. try:
  976. user_id = request.args.get("user_id")
  977. days = request.args.get("days")
  978. start_date = request.args.get("start_date")
  979. end_date = request.args.get("end_date")
  980. account_id = request.args.get("account_id")
  981. if not user_id:
  982. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  983. # 调用 Node.js API 获取数据
  984. params = {"user_id": user_id}
  985. if days:
  986. params["days"] = days
  987. if start_date:
  988. params["start_date"] = start_date
  989. if end_date:
  990. params["end_date"] = end_date
  991. if account_id:
  992. params["account_id"] = account_id
  993. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  994. return jsonify(result)
  995. except Exception as e:
  996. traceback.print_exc()
  997. return jsonify({"success": False, "error": str(e)}), 500
  998. @app.route("/work_day_statistics/platforms", methods=["GET"])
  999. def get_statistics_by_platform():
  1000. """
  1001. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  1002. 数据来源:
  1003. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  1004. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  1005. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  1006. 查询参数:
  1007. user_id: 用户ID (必填)
  1008. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  1009. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  1010. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  1011. 响应:
  1012. {
  1013. "success": true,
  1014. "data": [
  1015. {
  1016. "platform": "douyin",
  1017. "fansCount": 1000,
  1018. "fansIncrease": 50,
  1019. "viewsCount": 5000,
  1020. "likesCount": 200,
  1021. "commentsCount": 30,
  1022. "collectsCount": 100
  1023. },
  1024. ...
  1025. ]
  1026. }
  1027. """
  1028. try:
  1029. user_id = request.args.get("user_id")
  1030. days = request.args.get("days")
  1031. start_date = request.args.get("start_date")
  1032. end_date = request.args.get("end_date")
  1033. if not user_id:
  1034. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1035. # 调用 Node.js API 获取数据
  1036. params = {"user_id": user_id}
  1037. if days:
  1038. params["days"] = days
  1039. if start_date:
  1040. params["start_date"] = start_date
  1041. if end_date:
  1042. params["end_date"] = end_date
  1043. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  1044. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  1045. return jsonify(result)
  1046. except Exception as e:
  1047. traceback.print_exc()
  1048. return jsonify({"success": False, "error": str(e)}), 500
  1049. @app.route("/work_day_statistics/batch", methods=["POST"])
  1050. def get_work_statistics_history():
  1051. """
  1052. 批量获取作品的历史统计数据
  1053. 请求体:
  1054. {
  1055. "work_ids": [1, 2, 3],
  1056. "start_date": "2025-01-01", # 可选
  1057. "end_date": "2025-01-21" # 可选
  1058. }
  1059. 响应:
  1060. {
  1061. "success": true,
  1062. "data": {
  1063. "1": [
  1064. {"record_date": "2025-01-20", "play_count": 100, ...},
  1065. {"record_date": "2025-01-21", "play_count": 150, ...}
  1066. ],
  1067. ...
  1068. }
  1069. }
  1070. """
  1071. try:
  1072. data = request.json
  1073. work_ids = data.get("work_ids", [])
  1074. start_date = data.get("start_date")
  1075. end_date = data.get("end_date")
  1076. if not work_ids:
  1077. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  1078. # 调用 Node.js API 获取数据
  1079. request_data = {"work_ids": work_ids}
  1080. if start_date:
  1081. request_data["start_date"] = start_date
  1082. if end_date:
  1083. request_data["end_date"] = end_date
  1084. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  1085. return jsonify(result)
  1086. except Exception as e:
  1087. traceback.print_exc()
  1088. return jsonify({"success": False, "error": str(e)}), 500
  1089. @app.route("/work_day_statistics/overview", methods=["GET"])
  1090. def get_overview():
  1091. """
  1092. 获取数据总览(账号列表和汇总统计)
  1093. 查询参数:
  1094. user_id: 用户ID (必填)
  1095. 响应:
  1096. {
  1097. "success": true,
  1098. "data": {
  1099. "accounts": [
  1100. {
  1101. "id": 1,
  1102. "nickname": "账号名称",
  1103. "username": "账号ID",
  1104. "avatarUrl": "头像URL",
  1105. "platform": "douyin",
  1106. "groupId": 1,
  1107. "fansCount": 1000,
  1108. "totalIncome": null,
  1109. "yesterdayIncome": null,
  1110. "totalViews": 5000,
  1111. "yesterdayViews": 100,
  1112. "yesterdayComments": 10,
  1113. "yesterdayLikes": 50,
  1114. "yesterdayFansIncrease": 5,
  1115. "updateTime": "2025-01-26T10:00:00Z",
  1116. "status": "active"
  1117. },
  1118. ...
  1119. ],
  1120. "summary": {
  1121. "totalAccounts": 5,
  1122. "totalIncome": 0,
  1123. "yesterdayIncome": 0,
  1124. "totalViews": 10000,
  1125. "yesterdayViews": 200,
  1126. "totalFans": 5000,
  1127. "yesterdayComments": 20,
  1128. "yesterdayLikes": 100,
  1129. "yesterdayFansIncrease": 10
  1130. }
  1131. }
  1132. }
  1133. """
  1134. try:
  1135. user_id = request.args.get("user_id")
  1136. if not user_id:
  1137. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1138. # 调用 Node.js API 获取数据
  1139. params = {"user_id": user_id}
  1140. result = call_nodejs_api('GET', '/work-day-statistics/overview', params=params)
  1141. return jsonify(result)
  1142. except NodeApiError as e:
  1143. # 透传 Node 的真实状态码/错误内容,避免所有错误都变成 500
  1144. return jsonify(e.payload), e.status_code
  1145. except Exception as e:
  1146. traceback.print_exc()
  1147. return jsonify({"success": False, "error": str(e)}), 500
  1148. # ==================== 获取评论列表接口 ====================
  1149. @app.route("/comments", methods=["POST"])
  1150. def get_comments():
  1151. """
  1152. 获取作品评论
  1153. 请求体:
  1154. {
  1155. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  1156. "cookie": "cookie字符串或JSON",
  1157. "work_id": "作品ID",
  1158. "cursor": "" # 分页游标(可选)
  1159. }
  1160. 响应:
  1161. {
  1162. "success": true,
  1163. "platform": "douyin",
  1164. "work_id": "xxx",
  1165. "comments": [...],
  1166. "total": 50,
  1167. "has_more": true,
  1168. "cursor": "xxx"
  1169. }
  1170. """
  1171. try:
  1172. data = request.json
  1173. platform = data.get("platform", "").lower()
  1174. cookie_str = data.get("cookie", "")
  1175. work_id = data.get("work_id", "")
  1176. cursor = data.get("cursor", "")
  1177. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  1178. if not platform:
  1179. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1180. if platform not in PLATFORM_MAP:
  1181. return jsonify({
  1182. "success": False,
  1183. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1184. }), 400
  1185. if not cookie_str:
  1186. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1187. if not work_id:
  1188. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  1189. # 获取对应平台的发布器
  1190. PublisherClass = get_publisher(platform)
  1191. publisher = PublisherClass(headless=HEADLESS_MODE)
  1192. # 执行获取评论
  1193. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  1194. result_dict = result.to_dict()
  1195. # 添加 cursor 到响应
  1196. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  1197. result_dict['cursor'] = result.__dict__['cursor']
  1198. return jsonify(result_dict)
  1199. except Exception as e:
  1200. traceback.print_exc()
  1201. return jsonify({"success": False, "error": str(e)}), 500
  1202. # ==================== 获取所有作品评论接口 ====================
  1203. @app.route("/all_comments", methods=["POST"])
  1204. def get_all_comments():
  1205. """
  1206. 获取所有作品的评论(一次性获取)
  1207. 请求体:
  1208. {
  1209. "platform": "douyin", # douyin | xiaohongshu
  1210. "cookie": "cookie字符串或JSON"
  1211. }
  1212. 响应:
  1213. {
  1214. "success": true,
  1215. "platform": "douyin",
  1216. "work_comments": [
  1217. {
  1218. "work_id": "xxx",
  1219. "title": "作品标题",
  1220. "cover_url": "封面URL",
  1221. "comments": [...]
  1222. }
  1223. ],
  1224. "total": 5
  1225. }
  1226. """
  1227. try:
  1228. data = request.json
  1229. platform = data.get("platform", "").lower()
  1230. cookie_str = data.get("cookie", "")
  1231. print(f"[AllComments] 收到请求: platform={platform}")
  1232. if not platform:
  1233. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1234. if platform not in ['douyin', 'xiaohongshu']:
  1235. return jsonify({
  1236. "success": False,
  1237. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  1238. }), 400
  1239. if not cookie_str:
  1240. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1241. # 获取对应平台的发布器
  1242. PublisherClass = get_publisher(platform)
  1243. publisher = PublisherClass(headless=HEADLESS_MODE)
  1244. # 执行获取所有评论
  1245. result = asyncio.run(publisher.get_all_comments(cookie_str))
  1246. return jsonify(result)
  1247. except Exception as e:
  1248. traceback.print_exc()
  1249. return jsonify({"success": False, "error": str(e)}), 500
  1250. # ==================== 登录状态检查接口 ====================
  1251. @app.route("/check_login", methods=["POST"])
  1252. def check_login():
  1253. """
  1254. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  1255. 请求体:
  1256. {
  1257. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  1258. "cookie": "cookie字符串或JSON"
  1259. }
  1260. 响应:
  1261. {
  1262. "success": true,
  1263. "valid": true, # Cookie 是否有效
  1264. "need_login": false, # 是否需要重新登录
  1265. "message": "登录状态有效"
  1266. }
  1267. """
  1268. try:
  1269. data = request.json
  1270. platform = data.get("platform", "").lower()
  1271. cookie_str = data.get("cookie", "")
  1272. print(f"[CheckLogin] 收到请求: platform={platform}")
  1273. if not platform:
  1274. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1275. if platform not in PLATFORM_MAP:
  1276. return jsonify({
  1277. "success": False,
  1278. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1279. }), 400
  1280. if not cookie_str:
  1281. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1282. # 获取对应平台的发布器
  1283. PublisherClass = get_publisher(platform)
  1284. publisher = PublisherClass(headless=HEADLESS_MODE)
  1285. # 执行登录检查
  1286. result = asyncio.run(publisher.check_login_status(cookie_str))
  1287. return jsonify(result)
  1288. except Exception as e:
  1289. traceback.print_exc()
  1290. return jsonify({
  1291. "success": False,
  1292. "valid": False,
  1293. "need_login": True,
  1294. "error": str(e)
  1295. }), 500
  1296. # ==================== 获取账号信息接口 ====================
  1297. @app.route("/account_info", methods=["POST"])
  1298. def get_account_info():
  1299. """
  1300. 获取账号信息
  1301. 请求体:
  1302. {
  1303. "platform": "baijiahao", # 平台
  1304. "cookie": "cookie字符串或JSON"
  1305. }
  1306. 响应:
  1307. {
  1308. "success": true,
  1309. "account_id": "xxx",
  1310. "account_name": "用户名",
  1311. "avatar_url": "头像URL",
  1312. "fans_count": 0,
  1313. "works_count": 0
  1314. }
  1315. """
  1316. try:
  1317. data = request.json
  1318. platform = data.get("platform", "").lower()
  1319. cookie_str = data.get("cookie", "")
  1320. print(f"[AccountInfo] 收到请求: platform={platform}")
  1321. if not platform:
  1322. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1323. if platform not in PLATFORM_MAP:
  1324. return jsonify({
  1325. "success": False,
  1326. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1327. }), 400
  1328. if not cookie_str:
  1329. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1330. # 获取对应平台的发布器
  1331. PublisherClass = get_publisher(platform)
  1332. publisher = PublisherClass(headless=HEADLESS_MODE)
  1333. # 检查是否有 get_account_info 方法
  1334. if hasattr(publisher, 'get_account_info'):
  1335. result = asyncio.run(publisher.get_account_info(cookie_str))
  1336. return jsonify(result)
  1337. else:
  1338. return jsonify({
  1339. "success": False,
  1340. "error": f"平台 {platform} 不支持获取账号信息"
  1341. }), 400
  1342. except Exception as e:
  1343. traceback.print_exc()
  1344. return jsonify({"success": False, "error": str(e)}), 500
  1345. # ==================== 百家号作品每日数据辅助接口 ====================
  1346. @app.route("/baijiahao/article_stats", methods=["POST"])
  1347. def baijiahao_article_stats():
  1348. """
  1349. 百家号:代理调用 /author/eco/statistics/articleListStatistic
  1350. 请求体:
  1351. {
  1352. "cookie": "...",
  1353. "start_day": "YYYYMMDD",
  1354. "end_day": "YYYYMMDD",
  1355. "type": "small_video_v2|video|news",
  1356. "num": 1,
  1357. "count": 10
  1358. }
  1359. """
  1360. try:
  1361. data = request.json or {}
  1362. cookie_str = data.get("cookie", "")
  1363. start_day = data.get("start_day", "")
  1364. end_day = data.get("end_day", "")
  1365. stat_type = data.get("type", "video")
  1366. num = int(data.get("num", 1) or 1)
  1367. count = int(data.get("count", 10) or 10)
  1368. if not cookie_str:
  1369. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1370. if not start_day or not end_day:
  1371. return jsonify({"success": False, "error": "缺少 start_day 或 end_day 参数"}), 400
  1372. PublisherClass = get_publisher("baijiahao")
  1373. publisher = PublisherClass(headless=HEADLESS_MODE)
  1374. result = asyncio.run(
  1375. publisher.get_article_stats(
  1376. cookie_str,
  1377. start_day=start_day,
  1378. end_day=end_day,
  1379. stat_type=stat_type,
  1380. num=num,
  1381. count=count,
  1382. )
  1383. )
  1384. return jsonify(result)
  1385. except Exception as e:
  1386. traceback.print_exc()
  1387. return jsonify({"success": False, "error": str(e)}), 500
  1388. @app.route("/baijiahao/trend_data", methods=["POST"])
  1389. def baijiahao_trend_data():
  1390. """
  1391. 百家号:代理调用 /author/eco/statistic/gettrenddata
  1392. 请求体:
  1393. {
  1394. "cookie": "...",
  1395. "nid": "文章/视频 nid 或 article_id"
  1396. }
  1397. """
  1398. try:
  1399. data = request.json or {}
  1400. cookie_str = data.get("cookie", "")
  1401. nid = data.get("nid", "")
  1402. if not cookie_str:
  1403. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1404. if not nid:
  1405. return jsonify({"success": False, "error": "缺少 nid 参数"}), 400
  1406. PublisherClass = get_publisher("baijiahao")
  1407. publisher = PublisherClass(headless=HEADLESS_MODE)
  1408. result = asyncio.run(
  1409. publisher.get_trend_data(
  1410. cookie_str,
  1411. nid=str(nid),
  1412. )
  1413. )
  1414. return jsonify(result)
  1415. except Exception as e:
  1416. traceback.print_exc()
  1417. return jsonify({"success": False, "error": str(e)}), 500
  1418. @app.route("/baijiahao/app_statistic_v3", methods=["POST"])
  1419. def baijiahao_app_statistic_v3():
  1420. """
  1421. 百家号用户每日数据:代理调用 appStatisticV3(账号近30天基础数据)。
  1422. 登录模式与打开后台一致:使用账号已存 Cookie。
  1423. 请求体: { "cookie": "...", "start_day": "YYYYMMDD", "end_day": "YYYYMMDD" }
  1424. """
  1425. try:
  1426. data = request.json or {}
  1427. cookie_str = data.get("cookie", "")
  1428. start_day = data.get("start_day", "")
  1429. end_day = data.get("end_day", "")
  1430. if not cookie_str:
  1431. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1432. if not start_day or not end_day:
  1433. return jsonify({"success": False, "error": "缺少 start_day 或 end_day 参数"}), 400
  1434. PublisherClass = get_publisher("baijiahao")
  1435. publisher = PublisherClass(headless=HEADLESS_MODE)
  1436. result = asyncio.run(
  1437. publisher.get_app_statistic_v3(cookie_str, start_day=start_day, end_day=end_day)
  1438. )
  1439. return jsonify(result)
  1440. except Exception as e:
  1441. traceback.print_exc()
  1442. return jsonify({"success": False, "error": str(e), "errno": -1}), 500
  1443. @app.route("/baijiahao/fans_basic_info", methods=["POST"])
  1444. def baijiahao_fans_basic_info():
  1445. """
  1446. 百家号用户每日数据:代理调用 getFansBasicInfo(近30天粉丝数据)。
  1447. 登录模式与打开后台一致:使用账号已存 Cookie。
  1448. 请求体: { "cookie": "...", "start": "YYYYMMDD", "end": "YYYYMMDD" }
  1449. """
  1450. try:
  1451. data = request.json or {}
  1452. cookie_str = data.get("cookie", "")
  1453. start_str = data.get("start", "")
  1454. end_str = data.get("end", "")
  1455. if not cookie_str:
  1456. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1457. if not start_str or not end_str:
  1458. return jsonify({"success": False, "error": "缺少 start 或 end 参数"}), 400
  1459. PublisherClass = get_publisher("baijiahao")
  1460. publisher = PublisherClass(headless=HEADLESS_MODE)
  1461. result = asyncio.run(
  1462. publisher.get_fans_basic_info(cookie_str, start=start_str, end=end_str)
  1463. )
  1464. return jsonify(result)
  1465. except Exception as e:
  1466. traceback.print_exc()
  1467. return jsonify({"success": False, "error": str(e), "errno": -1}), 500
  1468. @app.route("/xiaohongshu/account_base", methods=["POST"])
  1469. def xiaohongshu_account_base():
  1470. """
  1471. 小红书每日用户数据:代理调用创作者中心 account/base(账号概览近30日)。
  1472. 登录方式与打开后台一致:使用账号已存 Cookie。
  1473. 请求体: { "cookie": "..." }
  1474. """
  1475. try:
  1476. data = request.json or {}
  1477. cookie_str = data.get("cookie", "")
  1478. if not cookie_str:
  1479. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1480. PublisherClass = get_publisher("xiaohongshu")
  1481. publisher = PublisherClass(headless=HEADLESS_MODE)
  1482. result = asyncio.run(publisher.get_account_base(cookie_str))
  1483. return jsonify(result)
  1484. except Exception as e:
  1485. traceback.print_exc()
  1486. return jsonify({"data": None, "code": 500, "error": str(e)}), 500
  1487. @app.route("/xiaohongshu/fans_overall_new", methods=["POST"])
  1488. def xiaohongshu_fans_overall_new():
  1489. """
  1490. 小红书每日用户数据:代理调用创作者中心 fans/overall_new(粉丝趋势近30日)。
  1491. 登录方式与打开后台一致:使用账号已存 Cookie。
  1492. 请求体: { "cookie": "..." }
  1493. """
  1494. try:
  1495. data = request.json or {}
  1496. cookie_str = data.get("cookie", "")
  1497. if not cookie_str:
  1498. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1499. PublisherClass = get_publisher("xiaohongshu")
  1500. publisher = PublisherClass(headless=HEADLESS_MODE)
  1501. result = asyncio.run(publisher.get_fans_overall_new(cookie_str))
  1502. return jsonify(result)
  1503. except Exception as e:
  1504. traceback.print_exc()
  1505. return jsonify({"data": None, "code": 500, "error": str(e)}), 500
  1506. @app.route("/xiaohongshu/account_overview", methods=["POST"])
  1507. def xiaohongshu_account_overview():
  1508. """
  1509. 小红书每日用户数据:一次请求同时拉取 account/base 与 fans/overall_new(内部并行),减少耗时。
  1510. 请求体: { "cookie": "..." }
  1511. 返回: { "account_base": {...}, "fans_overall_new": {...} }
  1512. """
  1513. try:
  1514. data = request.json or {}
  1515. cookie_str = data.get("cookie", "")
  1516. if not cookie_str:
  1517. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1518. PublisherClass = get_publisher("xiaohongshu")
  1519. publisher = PublisherClass(headless=HEADLESS_MODE)
  1520. result = asyncio.run(publisher.get_account_overview(cookie_str))
  1521. return jsonify(result)
  1522. except Exception as e:
  1523. traceback.print_exc()
  1524. return jsonify({"account_base": None, "fans_overall_new": None, "code": 500, "error": str(e)}), 500
  1525. @app.route("/xiaohongshu/note_base", methods=["POST"])
  1526. def xiaohongshu_note_base():
  1527. """
  1528. 小红书每日作品数据:代理调用创作者中心 note/base(单条笔记数据)。
  1529. 登录方式与打开后台一致:使用账号已存 Cookie。
  1530. 请求体: { "cookie": "...", "note_id": "xxx" }
  1531. """
  1532. try:
  1533. data = request.json or {}
  1534. cookie_str = data.get("cookie", "")
  1535. note_id = (data.get("note_id") or "").strip()
  1536. if not cookie_str:
  1537. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1538. if not note_id:
  1539. return jsonify({"data": None, "code": 400, "error": "缺少 note_id 参数"}), 400
  1540. PublisherClass = get_publisher("xiaohongshu")
  1541. publisher = PublisherClass(headless=HEADLESS_MODE)
  1542. result = asyncio.run(publisher.get_note_base(cookie_str, note_id))
  1543. return jsonify(result)
  1544. except Exception as e:
  1545. traceback.print_exc()
  1546. return jsonify({"data": None, "code": 500, "error": str(e)}), 500
  1547. # ==================== 健康检查 ====================
  1548. @app.route("/health", methods=["GET"])
  1549. def health_check():
  1550. """健康检查"""
  1551. # 检查 xhs SDK 是否可用
  1552. xhs_available = False
  1553. try:
  1554. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1555. xhs_available = XHS_SDK_AVAILABLE
  1556. except:
  1557. pass
  1558. return jsonify({
  1559. "status": "ok",
  1560. "xhs_sdk": xhs_available,
  1561. "supported_platforms": list(PLATFORM_MAP.keys()),
  1562. "headless_mode": HEADLESS_MODE
  1563. })
  1564. @app.route("/", methods=["GET"])
  1565. def index():
  1566. """首页"""
  1567. return jsonify({
  1568. "name": "智媒通视频发布服务",
  1569. "version": "1.2.0",
  1570. "endpoints": {
  1571. "GET /": "服务信息",
  1572. "GET /health": "健康检查",
  1573. "POST /publish": "发布视频",
  1574. "POST /publish/batch": "批量发布",
  1575. "POST /works": "获取作品列表",
  1576. "POST /comments": "获取作品评论",
  1577. "POST /all_comments": "获取所有作品评论",
  1578. "POST /work_day_statistics": "保存作品每日统计数据",
  1579. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  1580. "POST /check_cookie": "检查 Cookie",
  1581. "POST /sign": "小红书签名"
  1582. },
  1583. "supported_platforms": list(PLATFORM_MAP.keys())
  1584. })
  1585. # ==================== 命令行启动 ====================
  1586. def main():
  1587. parser = argparse.ArgumentParser(description='智媒通视频发布服务')
  1588. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  1589. # 从环境变量读取 HOST,默认仅本地访问
  1590. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  1591. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  1592. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  1593. parser.add_argument('--debug', action='store_true', help='调试模式')
  1594. args = parser.parse_args()
  1595. global HEADLESS_MODE
  1596. HEADLESS_MODE = args.headless.lower() == 'true'
  1597. # 检查 xhs SDK
  1598. xhs_status = "未安装"
  1599. try:
  1600. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1601. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  1602. except:
  1603. pass
  1604. print("=" * 60)
  1605. print("智媒通视频发布服务")
  1606. print("=" * 60)
  1607. print(f"XHS SDK: {xhs_status}")
  1608. print(f"Headless 模式: {HEADLESS_MODE}")
  1609. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  1610. print("=" * 60)
  1611. print(f"启动服务: http://{args.host}:{args.port}")
  1612. print("=" * 60)
  1613. app.run(host=args.host, port=args.port, debug=bool(args.debug), threaded=True, use_reloader=False)
  1614. @app.route('/auto-reply', methods=['POST'])
  1615. def auto_reply():
  1616. """
  1617. 微信视频号自动回复私信
  1618. POST /auto-reply
  1619. Body: {
  1620. "platform": "weixin",
  1621. "cookie": "..."
  1622. }
  1623. """
  1624. try:
  1625. data = request.json
  1626. platform = data.get('platform', '').lower()
  1627. cookie = data.get('cookie', '')
  1628. if platform != 'weixin':
  1629. return jsonify({
  1630. 'success': False,
  1631. 'error': '只支持微信视频号平台'
  1632. }), 400
  1633. if not cookie:
  1634. return jsonify({
  1635. 'success': False,
  1636. 'error': '缺少 Cookie'
  1637. }), 400
  1638. print(f"[API] 接收自动回复请求: platform={platform}")
  1639. # 创建 Publisher 实例
  1640. publisher = WeixinPublisher(headless=HEADLESS_MODE)
  1641. # 执行自动回复
  1642. loop = asyncio.new_event_loop()
  1643. asyncio.set_event_loop(loop)
  1644. result = loop.run_until_complete(publisher.auto_reply_private_messages(cookie))
  1645. loop.close()
  1646. print(f"[API] 自动回复结果: {result}")
  1647. return jsonify(result)
  1648. except Exception as e:
  1649. print(f"[API] 自动回复异常: {e}")
  1650. traceback.print_exc()
  1651. return jsonify({
  1652. 'success': False,
  1653. 'error': str(e)
  1654. }), 500
  1655. if __name__ == '__main__':
  1656. main()