app.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313
  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. def _test_proxy_for_platform(host: str, port: int, platform: str, timeout: int = 15) -> dict:
  130. """
  131. 测试代理IP对特定平台的可用性
  132. Returns:
  133. dict: {"ok": bool, "blocked": bool, "cost_ms": int, "error": str}
  134. """
  135. # 不同平台的测试URL
  136. platform_test_urls = {
  137. "douyin": "https://creator.douyin.com/",
  138. "xiaohongshu": "https://creator.xiaohongshu.com/",
  139. "kuaishou": "https://cp.kuaishou.com/",
  140. "weixin": "https://channels.weixin.qq.com/",
  141. }
  142. test_url = platform_test_urls.get(platform, "https://www.baidu.com/")
  143. proxy_meta = _build_requests_proxy_meta(host, port)
  144. proxies = {"http": proxy_meta, "https": proxy_meta}
  145. start = int(round(time.time() * 1000))
  146. try:
  147. session = requests.Session()
  148. session.trust_env = False
  149. session.headers.update({
  150. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  151. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
  152. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  153. })
  154. resp = session.get(test_url, proxies=proxies, timeout=timeout, allow_redirects=True)
  155. cost_ms = int(round(time.time() * 1000)) - start
  156. # 检查是否被重定向到验证页面
  157. final_url = resp.url.lower()
  158. blocked_indicators = ["captcha", "verify", "challenge", "blocked", "forbidden", "error", "login"]
  159. is_blocked = any(indicator in final_url for indicator in blocked_indicators)
  160. # 检查响应状态码
  161. if resp.status_code == 403 or resp.status_code == 429:
  162. is_blocked = True
  163. result = {
  164. "ok": not is_blocked and resp.status_code < 400,
  165. "blocked": is_blocked,
  166. "cost_ms": cost_ms,
  167. "status_code": resp.status_code,
  168. "final_url": resp.url,
  169. }
  170. if is_blocked:
  171. print(f"[Proxy] platform {platform} blocked: {_mask_ip_port(host + ':' + str(port))} status={resp.status_code}", flush=True)
  172. else:
  173. print(f"[Proxy] platform {platform} ok: {_mask_ip_port(host + ':' + str(port))} cost={cost_ms}ms", flush=True)
  174. return result
  175. except Exception as e:
  176. cost_ms = int(round(time.time() * 1000)) - start
  177. print(f"[Proxy] platform {platform} test failed: {_mask_ip_port(host + ':' + str(port))} err={type(e).__name__}", flush=True)
  178. return {
  179. "ok": False,
  180. "blocked": False,
  181. "cost_ms": cost_ms,
  182. "error": str(e),
  183. }
  184. def _query_ip_location(ip: str, timeout: int = 5) -> dict:
  185. """
  186. 查询IP的实际地理位置
  187. Args:
  188. ip: IP地址
  189. timeout: 超时时间(秒)
  190. Returns:
  191. dict: {
  192. "country": "国家",
  193. "region": "地区",
  194. "city": "城市",
  195. "isp": "运营商",
  196. "success": bool
  197. }
  198. """
  199. try:
  200. # 使用 ip-api.com 查询IP位置(免费,支持中文)
  201. resp = requests.get(
  202. f"http://ip-api.com/json/{ip}?lang=zh-CN",
  203. timeout=timeout
  204. )
  205. data = resp.json()
  206. if data.get("status") == "success":
  207. return {
  208. "success": True,
  209. "country": data.get("country", ""),
  210. "region": data.get("regionName", ""),
  211. "city": data.get("city", ""),
  212. "isp": data.get("isp", ""),
  213. "lat": data.get("lat", 0),
  214. "lon": data.get("lon", 0),
  215. }
  216. else:
  217. return {"success": False, "error": data.get("message", "Unknown error")}
  218. except Exception as e:
  219. return {"success": False, "error": str(e)}
  220. def _verify_proxy_location(host: str, port: int, expected_city: str = "", expected_region: str = "") -> dict:
  221. """
  222. 验证代理IP的实际地理位置是否符合预期
  223. Args:
  224. host: 代理IP
  225. port: 代理端口
  226. expected_city: 预期城市
  227. expected_region: 预期地区
  228. Returns:
  229. dict: {
  230. "match": bool,
  231. "actual_city": str,
  232. "expected_city": str,
  233. "location": dict
  234. }
  235. """
  236. print(f"[Proxy] 验证IP地理位置: {host}:{port}", flush=True)
  237. # 查询IP位置
  238. location = _query_ip_location(host)
  239. if not location.get("success"):
  240. print(f"[Proxy] ⚠️ IP位置查询失败: {location.get('error')}", flush=True)
  241. return {
  242. "match": False,
  243. "error": location.get("error"),
  244. "location": location
  245. }
  246. actual_city = location.get("city", "")
  247. actual_region = location.get("region", "")
  248. print(f"[Proxy] IP实际位置: {actual_city}, {actual_region}, {location.get('country')}", flush=True)
  249. print(f"[Proxy] IP运营商: {location.get('isp')}", flush=True)
  250. # 检查是否匹配
  251. match = True
  252. if expected_city:
  253. # 标准化城市名(去掉"市"等后缀)
  254. actual_normalized = actual_city.replace("市", "").strip()
  255. expected_normalized = expected_city.replace("市", "").strip()
  256. if actual_normalized != expected_normalized:
  257. match = False
  258. print(f"[Proxy] ⚠️ 位置不匹配!预期: {expected_city}, 实际: {actual_city}", flush=True)
  259. else:
  260. print(f"[Proxy] ✓ 位置匹配: {actual_city}", flush=True)
  261. return {
  262. "match": match,
  263. "actual_city": actual_city,
  264. "actual_region": actual_region,
  265. "expected_city": expected_city,
  266. "expected_region": expected_region,
  267. "location": location
  268. }
  269. _PROXY_CACHE_TTL_SECONDS = 20 * 60
  270. _resolved_proxy_cache = {}
  271. def _resolve_shenlong_proxy(proxy_payload: dict, platform: str = None) -> dict:
  272. test_url = 'http://myip.ipip.net'
  273. city = str(proxy_payload.get('city') or '').strip()
  274. region_code = str(proxy_payload.get('regionCode') or '').strip()
  275. api_url = str(proxy_payload.get('apiUrl') or '').strip()
  276. product_key = str(proxy_payload.get('productKey') or '').strip()
  277. signature = str(proxy_payload.get('signature') or '').strip()
  278. isp = str(proxy_payload.get('isp') or '').strip()
  279. publish_task_id = str(proxy_payload.get('publish_task_id') or '').strip()
  280. # 获取平台信息用于测试
  281. target_platform = str(platform or proxy_payload.get('platform') or '').lower().strip()
  282. if not product_key:
  283. raise Exception('缺少神龙产品Key')
  284. if not signature:
  285. raise Exception('缺少神龙签名')
  286. if region_code and region_code.isdigit() and len(region_code) == 6:
  287. if region_code.endswith('0000'):
  288. region_code = ''
  289. elif not region_code.endswith('00'):
  290. region_code = region_code[:4] + '00'
  291. cache_key = ''
  292. if publish_task_id:
  293. cache_key = f"publish_task:{publish_task_id}:area:{region_code or '-'}:isp:{isp or '-'}"
  294. now = int(time.time())
  295. cached = _resolved_proxy_cache.get(cache_key)
  296. if isinstance(cached, dict) and cached.get('expire_at', 0) > now and cached.get('server'):
  297. server = str(cached.get('server') or '').strip()
  298. if server:
  299. print(f"[Proxy] cache hit: task={publish_task_id} area={region_code or '-'} isp={isp or '-'}", flush=True)
  300. return {'server': server}
  301. request_url = api_url or 'http://api.shenlongip.com/ip'
  302. params = {
  303. 'key': product_key,
  304. 'sign': signature,
  305. 'count': 1,
  306. 'pattern': 'json',
  307. 'mr': 1,
  308. }
  309. if region_code:
  310. params['area'] = region_code
  311. if isp:
  312. params['isp'] = isp
  313. payload = None
  314. session = requests.Session()
  315. session.trust_env = False
  316. resp = session.get(
  317. request_url,
  318. params=params,
  319. headers={
  320. 'User-Agent': 'Mozilla/5.0',
  321. 'Accept': 'application/json',
  322. },
  323. timeout=15,
  324. )
  325. content_type = (resp.headers.get('content-type') or '').lower()
  326. raw_text = resp.text or ''
  327. try:
  328. if 'application/json' in content_type or raw_text.strip().startswith('{') or raw_text.strip().startswith('['):
  329. payload = resp.json()
  330. except Exception:
  331. payload = None
  332. if isinstance(payload, dict) and payload.get('code') is not None:
  333. try:
  334. api_code = int(payload.get('code'))
  335. except Exception:
  336. api_code = -1
  337. if api_code != 200:
  338. raise Exception(f"代理提取失败: code={api_code} msg={str(payload.get('msg') or '').strip() or 'unknown'}")
  339. elif resp.status_code >= 400:
  340. raise Exception(f"代理提取失败: HTTP {resp.status_code}")
  341. def collect_ip_ports(data_list, city_filter: str):
  342. ips = []
  343. for item in data_list:
  344. if isinstance(item, str):
  345. for ip_port in _extract_ip_ports(item):
  346. ips.append(ip_port)
  347. continue
  348. if not isinstance(item, dict):
  349. continue
  350. item_city = str(item.get('city') or item.get('area') or '').strip()
  351. if city_filter and item_city and item_city != city_filter:
  352. continue
  353. ip = str(item.get('ip') or item.get('host') or item.get('proxy_ip') or '').strip()
  354. port = str(item.get('port') or item.get('proxy_port') or '').strip()
  355. if ip and port:
  356. ips.append(f"{ip}:{port}")
  357. proxy = str(item.get('proxy') or item.get('ip_port') or '').strip()
  358. if proxy:
  359. for ip_port in _extract_ip_ports(proxy):
  360. ips.append(ip_port)
  361. return ips
  362. ip_ports = []
  363. if payload is not None:
  364. if isinstance(payload, dict):
  365. if isinstance(payload.get('data'), list):
  366. ip_ports = collect_ip_ports(payload.get('data'), '')
  367. elif isinstance(payload.get('list'), list):
  368. ip_ports = collect_ip_ports(payload.get('list'), '')
  369. elif payload.get('ip') and payload.get('port'):
  370. ip_ports = collect_ip_ports([payload], '')
  371. elif isinstance(payload, list):
  372. ip_ports = collect_ip_ports(payload, '')
  373. else:
  374. ip_ports = _extract_ip_ports(raw_text)
  375. if not ip_ports:
  376. raise Exception('代理提取结果为空')
  377. random.shuffle(ip_ports)
  378. candidates = ip_ports[: min(10, len(ip_ports))]
  379. print(f"[Proxy] shenlong resolved: city={city or '-'} area={region_code or '-'} candidates={len(candidates)}/{len(ip_ports)}", flush=True)
  380. for ip_port in candidates:
  381. try:
  382. host, port_str = ip_port.split(':', 1)
  383. port = int(port_str)
  384. except Exception:
  385. continue
  386. # 首先测试基础连接
  387. if not _test_proxy_connectivity(test_url, host, port, timeout=10):
  388. continue
  389. # 如果指定了平台,测试平台可用性
  390. if target_platform:
  391. platform_result = _test_proxy_for_platform(host, port, target_platform, timeout=15)
  392. if platform_result.get('blocked'):
  393. print(f"[Proxy] platform {target_platform} blocked, trying next...", flush=True)
  394. continue
  395. if not platform_result.get('ok') and platform_result.get('cost_ms', 0) > 10000:
  396. print(f"[Proxy] platform {target_platform} too slow ({platform_result.get('cost_ms')}ms), trying next...", flush=True)
  397. continue
  398. # 🔧 验证IP地理位置
  399. expected_city = city or ""
  400. location_result = _verify_proxy_location(host, port, expected_city)
  401. # 如果位置不匹配,给出警告但继续使用
  402. if not location_result.get("match") and expected_city:
  403. actual_city = location_result.get("actual_city", "未知")
  404. print(f"[Proxy] ⚠️ 位置不匹配警告:预期 {expected_city}, 实际 {actual_city}", flush=True)
  405. print(f"[Proxy] 💡 这可能导致微信显示的位置不正确", flush=True)
  406. # 不阻止使用,只是警告
  407. server = f"http://{host}:{port}"
  408. if cache_key:
  409. _resolved_proxy_cache[cache_key] = {
  410. 'server': server,
  411. 'expire_at': int(time.time()) + _PROXY_CACHE_TTL_SECONDS,
  412. }
  413. print(f"[Proxy] cache set: task={publish_task_id} ttl={_PROXY_CACHE_TTL_SECONDS}s", flush=True)
  414. return {'server': server}
  415. raise Exception('未找到可用代理IP')
  416. def validate_video_file(video_path: str) -> bool:
  417. """验证视频文件是否有效"""
  418. if not video_path:
  419. return False
  420. if not os.path.exists(video_path):
  421. return False
  422. if not os.path.isfile(video_path):
  423. return False
  424. valid_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv', '.webm']
  425. ext = os.path.splitext(video_path)[1].lower()
  426. if ext not in valid_extensions:
  427. return False
  428. if os.path.getsize(video_path) < 1024:
  429. return False
  430. return True
  431. # 创建 Flask 应用
  432. app = Flask(__name__)
  433. CORS(app)
  434. # 配置日志以显示所有 HTTP 请求
  435. import logging
  436. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  437. # 让 werkzeug 日志显示
  438. werkzeug_logger = logging.getLogger('werkzeug')
  439. werkzeug_logger.setLevel(logging.INFO)
  440. # 添加 StreamHandler 确保输出到控制台
  441. handler = logging.StreamHandler(sys.stdout)
  442. handler.setLevel(logging.INFO)
  443. werkzeug_logger.addHandler(handler)
  444. logging.getLogger('urllib3').setLevel(logging.WARNING)
  445. # 添加请求钩子,打印所有收到的请求
  446. @app.before_request
  447. def log_request_info():
  448. """在处理每个请求前打印详细信息"""
  449. print(f"\n{'='*60}", flush=True)
  450. print(f"[HTTP Request] {request.method} {request.path}", flush=True)
  451. print(f"[HTTP Request] From: {request.remote_addr}", flush=True)
  452. if request.content_type and 'json' in request.content_type:
  453. try:
  454. data = request.get_json(silent=True)
  455. if data:
  456. # 打印部分参数,避免太长
  457. keys = list(data.keys()) if data else []
  458. print(f"[HTTP Request] JSON keys: {keys}", flush=True)
  459. except:
  460. pass
  461. print(f"{'='*60}\n", flush=True)
  462. # 全局配置
  463. HEADLESS_MODE = os.environ.get('HEADLESS', 'true').lower() == 'true'
  464. print(f"[Config] HEADLESS env value: '{os.environ.get('HEADLESS', 'NOT SET')}'", flush=True)
  465. print(f"[Config] HEADLESS_MODE: {HEADLESS_MODE}", flush=True)
  466. # Node.js API 配置
  467. NODEJS_API_BASE_URL = os.environ.get('NODEJS_API_URL', 'http://localhost:3000')
  468. INTERNAL_API_KEY = os.environ.get('INTERNAL_API_KEY', 'internal-api-key-default')
  469. print(f"[API Config] Node.js API: {NODEJS_API_BASE_URL}", flush=True)
  470. class NodeApiError(Exception):
  471. """用于把 Node 内部接口的错误状态码/内容透传给调用方。"""
  472. def __init__(self, status_code: int, payload: dict):
  473. super().__init__(payload.get("error") or payload.get("message") or "Node API error")
  474. self.status_code = status_code
  475. self.payload = payload
  476. def call_nodejs_api(method: str, endpoint: str, data: dict = None, params: dict = None) -> dict:
  477. """调用 Node.js 内部 API"""
  478. url = f"{NODEJS_API_BASE_URL}/api/internal{endpoint}"
  479. headers = {
  480. 'Content-Type': 'application/json',
  481. 'X-Internal-API-Key': INTERNAL_API_KEY,
  482. }
  483. try:
  484. if method.upper() == 'GET':
  485. response = requests.get(url, headers=headers, params=params, timeout=30)
  486. elif method.upper() == 'POST':
  487. response = requests.post(url, headers=headers, json=data, timeout=30)
  488. else:
  489. raise ValueError(f"Unsupported HTTP method: {method}")
  490. # 兼容 Node 可能返回非 JSON 的情况
  491. try:
  492. payload = response.json()
  493. except Exception:
  494. payload = {
  495. "success": False,
  496. "error": "Node.js API 返回非 JSON 响应",
  497. "status": response.status_code,
  498. "text": (response.text or "")[:2000],
  499. "url": url,
  500. "endpoint": endpoint,
  501. }
  502. if response.status_code >= 400:
  503. # 把真实状态码/返回体抛出去,由路由决定如何返回给前端
  504. if isinstance(payload, dict):
  505. payload.setdefault("success", False)
  506. payload.setdefault("status", response.status_code)
  507. payload.setdefault("url", url)
  508. payload.setdefault("endpoint", endpoint)
  509. raise NodeApiError(response.status_code, payload if isinstance(payload, dict) else {
  510. "success": False,
  511. "error": "Node.js API 调用失败",
  512. "status": response.status_code,
  513. "data": payload,
  514. "url": url,
  515. "endpoint": endpoint,
  516. })
  517. return payload
  518. except requests.exceptions.RequestException as e:
  519. # 连接失败/超时等(此时通常拿不到 response)
  520. print(f"[API Error] 调用 Node.js API 失败: {e}", flush=True)
  521. raise NodeApiError(502, {
  522. "success": False,
  523. "error": f"无法连接 Node.js API: {str(e)}",
  524. "status": 502,
  525. "url": url,
  526. "endpoint": endpoint,
  527. })
  528. # ==================== 签名相关(小红书专用) ====================
  529. @app.route("/sign", methods=["POST"])
  530. def sign_endpoint():
  531. """小红书签名接口"""
  532. try:
  533. from platforms.xiaohongshu import XiaohongshuPublisher
  534. data = request.json
  535. publisher = XiaohongshuPublisher(headless=True)
  536. result = asyncio.run(publisher.get_sign(
  537. data.get("uri", ""),
  538. data.get("data"),
  539. data.get("a1", ""),
  540. data.get("web_session", "")
  541. ))
  542. return jsonify(result)
  543. except Exception as e:
  544. traceback.print_exc()
  545. return jsonify({"error": str(e)}), 500
  546. # ==================== 代理测试接口 ====================
  547. @app.route("/proxy/test", methods=["POST"])
  548. def test_proxy():
  549. """
  550. 测试代理配置
  551. 请求体:
  552. {
  553. "provider": "shenlong", # 代理提供商
  554. "productKey": "xxx", # 神龙产品Key
  555. "signature": "xxx", # 神龙签名
  556. "apiUrl": "http://...", # API地址(可选)
  557. "city": "城市", # 城市(可选)
  558. "regionCode": "区域代码", # 区域代码(可选)
  559. "isp": "运营商", # 运营商(可选)
  560. "platform": "douyin" # 目标平台(可选,用于测试平台可用性)
  561. }
  562. 响应:
  563. {
  564. "success": true,
  565. "proxy": "http://x.x.x.x:port",
  566. "platform_test": {
  567. "ok": true,
  568. "blocked": false,
  569. "cost_ms": 1234
  570. }
  571. }
  572. """
  573. try:
  574. data = request.json
  575. provider = str(data.get('provider') or 'shenlong').strip().lower()
  576. platform = str(data.get('platform') or '').strip().lower()
  577. print(f"[Proxy Test] 测试代理: provider={provider}, platform={platform or 'default'}")
  578. if provider == 'shenlong':
  579. # 使用神龙代理解析
  580. proxy_config = _resolve_shenlong_proxy(data, platform=platform)
  581. server = proxy_config.get('server', '')
  582. result = {
  583. "success": True,
  584. "proxy": server,
  585. "provider": provider,
  586. }
  587. # 如果指定了平台,测试平台可用性
  588. if platform and server:
  589. # 从 server 中提取 host 和 port
  590. try:
  591. server_clean = server.replace('http://', '').replace('https://', '')
  592. host, port_str = server_clean.split(':')
  593. port = int(port_str)
  594. platform_result = _test_proxy_for_platform(host, port, platform)
  595. result["platform_test"] = platform_result
  596. except Exception as e:
  597. result["platform_test"] = {
  598. "ok": False,
  599. "error": str(e)
  600. }
  601. # 🔧 添加IP地理位置信息
  602. if server:
  603. try:
  604. server_clean = server.replace('http://', '').replace('https://', '')
  605. host = server_clean.split(':')[0]
  606. # 查询IP位置
  607. location = _query_ip_location(host)
  608. if location.get("success"):
  609. result["ip_location"] = {
  610. "country": location.get("country"),
  611. "region": location.get("region"),
  612. "city": location.get("city"),
  613. "isp": location.get("isp"),
  614. }
  615. # 检查是否匹配预期城市
  616. expected_city = data.get('city', '').strip()
  617. if expected_city:
  618. actual_city = location.get("city", "")
  619. actual_normalized = actual_city.replace("市", "").strip()
  620. expected_normalized = expected_city.replace("市", "").strip()
  621. if actual_normalized != expected_normalized:
  622. result["location_match"] = False
  623. result["location_warning"] = f"IP实际位置({actual_city})与预期({expected_city})不符"
  624. else:
  625. result["location_match"] = True
  626. except Exception as e:
  627. result["ip_location_error"] = str(e)
  628. return jsonify(result)
  629. else:
  630. return jsonify({
  631. "success": False,
  632. "error": f"不支持的代理提供商: {provider}"
  633. }), 400
  634. except Exception as e:
  635. traceback.print_exc()
  636. return jsonify({
  637. "success": False,
  638. "error": str(e)
  639. }), 500
  640. @app.route("/proxy/platforms", methods=["GET"])
  641. def get_supported_platforms():
  642. """获取支持的平台列表"""
  643. return jsonify({
  644. "platforms": [
  645. {"id": "douyin", "name": "抖音", "test_url": "https://creator.douyin.com/"},
  646. {"id": "xiaohongshu", "name": "小红书", "test_url": "https://creator.xiaohongshu.com/"},
  647. {"id": "kuaishou", "name": "快手", "test_url": "https://cp.kuaishou.com/"},
  648. {"id": "weixin", "name": "视频号", "test_url": "https://channels.weixin.qq.com/"},
  649. ]
  650. })
  651. # ==================== 统一发布接口 ====================
  652. @app.route("/publish", methods=["POST"])
  653. def publish_video():
  654. """
  655. 统一发布接口
  656. 请求体:
  657. {
  658. "platform": "douyin", # douyin | xiaohongshu | weixin | kuaishou
  659. "cookie": "cookie字符串或JSON",
  660. "title": "视频标题",
  661. "description": "视频描述(可选)",
  662. "video_path": "视频文件绝对路径",
  663. "cover_path": "封面图片绝对路径(可选)",
  664. "tags": ["话题1", "话题2"],
  665. "post_time": "定时发布时间(可选,格式:2024-01-20 12:00:00)",
  666. "location": "位置(可选,默认:重庆市)"
  667. }
  668. 响应:
  669. {
  670. "success": true,
  671. "platform": "douyin",
  672. "video_id": "xxx",
  673. "video_url": "xxx",
  674. "message": "发布成功"
  675. }
  676. """
  677. try:
  678. data = request.json
  679. # 获取参数
  680. platform = data.get("platform", "").lower()
  681. cookie_str = data.get("cookie", "")
  682. title = data.get("title", "")
  683. description = data.get("description", "")
  684. video_path = data.get("video_path", "")
  685. cover_path = data.get("cover_path")
  686. tags = data.get("tags", [])
  687. post_time = data.get("post_time")
  688. location = data.get("location", "重庆市")
  689. # 🔧 如果启用了代理,自动使用代理所在地区作为发布位置
  690. proxy_payload = data.get('proxy')
  691. if isinstance(proxy_payload, dict) and proxy_payload.get('enabled'):
  692. # 优先级:city > regionName > 保持原值
  693. proxy_city = proxy_payload.get('city', '').strip()
  694. proxy_region = proxy_payload.get('regionName', '').strip()
  695. if proxy_city:
  696. location = proxy_city
  697. print(f"[Publish] 💡 使用代理地区作为发布位置: {location}", flush=True)
  698. elif proxy_region:
  699. location = proxy_region
  700. print(f"[Publish] 💡 使用代理区域作为发布位置: {location}", flush=True)
  701. # 调试日志
  702. print(f"[Publish] 收到请求: platform={platform}, title={title}, video_path={video_path}")
  703. # 参数验证
  704. if not platform:
  705. print("[Publish] 错误: 缺少 platform 参数")
  706. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  707. if platform not in PLATFORM_MAP:
  708. print(f"[Publish] 错误: 不支持的平台 {platform}")
  709. return jsonify({
  710. "success": False,
  711. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  712. }), 400
  713. if not cookie_str:
  714. print("[Publish] 错误: 缺少 cookie 参数")
  715. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  716. if not title:
  717. print("[Publish] 错误: 缺少 title 参数")
  718. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  719. if not video_path:
  720. print("[Publish] 错误: 缺少 video_path 参数")
  721. return jsonify({"success": False, "error": "缺少 video_path 参数"}), 400
  722. # 视频文件验证(增加详细信息)
  723. if not os.path.exists(video_path):
  724. print(f"[Publish] 错误: 视频文件不存在: {video_path}")
  725. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  726. if not os.path.isfile(video_path):
  727. print(f"[Publish] 错误: 路径不是文件: {video_path}")
  728. return jsonify({"success": False, "error": f"路径不是文件: {video_path}"}), 400
  729. # 解析发布时间
  730. publish_date = parse_datetime(post_time) if post_time else None
  731. # 创建发布参数
  732. params = PublishParams(
  733. title=title,
  734. video_path=video_path,
  735. description=description,
  736. cover_path=cover_path,
  737. tags=tags,
  738. publish_date=publish_date,
  739. location=location
  740. )
  741. print("=" * 60)
  742. print(f"[Publish] 平台: {platform}")
  743. print(f"[Publish] 标题: {title}")
  744. print(f"[Publish] 视频: {video_path}")
  745. print(f"[Publish] 封面: {cover_path}")
  746. print(f"[Publish] 话题: {tags}")
  747. print(f"[Publish] 定时: {publish_date}")
  748. print("=" * 60)
  749. # 获取对应平台的发布器
  750. PublisherClass = get_publisher(platform)
  751. publisher = PublisherClass(headless=HEADLESS_MODE)
  752. proxy_payload = data.get('proxy')
  753. if isinstance(proxy_payload, dict) and proxy_payload.get('enabled'):
  754. provider = str(proxy_payload.get('provider') or 'shenlong').strip().lower()
  755. if provider == 'shenlong':
  756. proxy_payload_with_task = dict(proxy_payload)
  757. if data.get('publish_task_id') is not None:
  758. proxy_payload_with_task['publish_task_id'] = data.get('publish_task_id')
  759. # 传递平台参数,用于测试代理对特定平台的可用性
  760. publisher.proxy_config = _resolve_shenlong_proxy(proxy_payload_with_task, platform=platform)
  761. # 执行发布
  762. result = asyncio.run(publisher.run(cookie_str, params))
  763. response_data = {
  764. "success": result.success,
  765. "platform": result.platform,
  766. "video_id": result.video_id,
  767. "video_url": result.video_url,
  768. "message": result.message,
  769. "error": result.error,
  770. "need_captcha": result.need_captcha,
  771. "captcha_type": result.captcha_type,
  772. "screenshot_base64": result.screenshot_base64,
  773. "page_url": result.page_url,
  774. "status": result.status,
  775. "screenshot_path": getattr(result, 'screenshot_path', '') or ''
  776. }
  777. # 如果需要验证码,打印明确的日志
  778. if result.need_captcha:
  779. print(f"[Publish] 需要验证码: type={result.captcha_type}")
  780. return jsonify(response_data)
  781. except Exception as e:
  782. traceback.print_exc()
  783. return jsonify({"success": False, "error": str(e)}), 500
  784. # ==================== AI 辅助发布接口 ====================
  785. # 存储活跃的发布会话
  786. active_publish_sessions = {}
  787. @app.route("/publish/ai-assisted", methods=["POST"])
  788. def publish_ai_assisted():
  789. """
  790. AI 辅助发布接口
  791. 与普通发布接口的区别:
  792. 1. 发布过程中会返回截图供 AI 分析
  793. 2. 如果检测到需要验证码,返回截图和状态,等待外部处理
  794. 3. 支持继续发布(输入验证码后)
  795. 请求体:
  796. {
  797. "platform": "douyin",
  798. "cookie": "cookie字符串",
  799. "title": "视频标题",
  800. "video_path": "视频文件路径",
  801. ...
  802. "return_screenshot": true // 是否返回截图
  803. }
  804. 响应:
  805. {
  806. "success": true/false,
  807. "status": "success|failed|need_captcha|processing",
  808. "screenshot_base64": "...", // 当前页面截图
  809. "page_url": "...",
  810. ...
  811. }
  812. """
  813. # 立即打印请求日志,确保能看到
  814. print("\n" + "!" * 60, flush=True)
  815. print("!!! [AI-Assisted Publish] 收到请求 !!!", flush=True)
  816. print("!" * 60 + "\n", flush=True)
  817. try:
  818. data = request.json
  819. print(f"[AI-Assisted Publish] 请求数据: platform={data.get('platform')}, title={data.get('title')}", flush=True)
  820. # 获取参数
  821. platform = data.get("platform", "").lower()
  822. cookie_str = data.get("cookie", "")
  823. title = data.get("title", "")
  824. description = data.get("description", "")
  825. video_path = data.get("video_path", "")
  826. cover_path = data.get("cover_path")
  827. tags = data.get("tags", [])
  828. post_time = data.get("post_time")
  829. location = data.get("location", "重庆市")
  830. # 🔧 如果启用了代理,自动使用代理所在地区作为发布位置
  831. proxy_payload = data.get('proxy')
  832. if isinstance(proxy_payload, dict) and proxy_payload.get('enabled'):
  833. # 优先级:city > regionName > 保持原值
  834. proxy_city = proxy_payload.get('city', '').strip()
  835. proxy_region = proxy_payload.get('regionName', '').strip()
  836. if proxy_city:
  837. location = proxy_city
  838. print(f"[AI-Assisted Publish] 💡 使用代理地区作为发布位置: {location}", flush=True)
  839. elif proxy_region:
  840. location = proxy_region
  841. print(f"[AI-Assisted Publish] 💡 使用代理区域作为发布位置: {location}", flush=True)
  842. return_screenshot = data.get("return_screenshot", True)
  843. # 支持请求级别的 headless 参数,用于验证码场景下的有头浏览器模式
  844. headless = data.get("headless", HEADLESS_MODE)
  845. if isinstance(headless, str):
  846. headless = headless.lower() == 'true'
  847. # 参数验证
  848. if not platform:
  849. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  850. if platform not in PLATFORM_MAP:
  851. return jsonify({"success": False, "error": f"不支持的平台: {platform}"}), 400
  852. if not cookie_str:
  853. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  854. if not title:
  855. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  856. if not video_path or not os.path.exists(video_path):
  857. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  858. # 解析发布时间
  859. publish_date = parse_datetime(post_time) if post_time else None
  860. # 创建发布参数
  861. params = PublishParams(
  862. title=title,
  863. video_path=video_path,
  864. description=description,
  865. cover_path=cover_path,
  866. tags=tags,
  867. publish_date=publish_date,
  868. location=location
  869. )
  870. print("=" * 60)
  871. print(f"[AI Publish] 平台: {platform}")
  872. print(f"[AI Publish] 标题: {title}")
  873. print(f"[AI Publish] 视频: {video_path}")
  874. print(f"[AI Publish] Headless: {headless}")
  875. print("=" * 60)
  876. # 获取对应平台的发布器
  877. PublisherClass = get_publisher(platform)
  878. publisher = PublisherClass(headless=headless) # 使用请求参数中的 headless 值
  879. proxy_payload = data.get('proxy')
  880. if isinstance(proxy_payload, dict) and proxy_payload.get('enabled'):
  881. provider = str(proxy_payload.get('provider') or 'shenlong').strip().lower()
  882. if provider == 'shenlong':
  883. proxy_payload_with_task = dict(proxy_payload)
  884. if data.get('publish_task_id') is not None:
  885. proxy_payload_with_task['publish_task_id'] = data.get('publish_task_id')
  886. # 传递平台参数,用于测试代理对特定平台的可用性
  887. publisher.proxy_config = _resolve_shenlong_proxy(proxy_payload_with_task, platform=platform)
  888. try:
  889. publisher.user_id = int(data.get("user_id")) if data.get("user_id") is not None else None
  890. except Exception:
  891. publisher.user_id = None
  892. try:
  893. publisher.publish_task_id = int(data.get("publish_task_id")) if data.get("publish_task_id") is not None else None
  894. except Exception:
  895. publisher.publish_task_id = None
  896. try:
  897. publisher.publish_account_id = int(data.get("publish_account_id")) if data.get("publish_account_id") is not None else None
  898. except Exception:
  899. publisher.publish_account_id = None
  900. # 执行发布
  901. result = asyncio.run(publisher.run(cookie_str, params))
  902. response_data = {
  903. "success": result.success,
  904. "platform": result.platform,
  905. "video_id": result.video_id,
  906. "video_url": result.video_url,
  907. "message": result.message,
  908. "error": result.error,
  909. "need_captcha": result.need_captcha,
  910. "captcha_type": result.captcha_type,
  911. "status": result.status or ("success" if result.success else "failed"),
  912. "page_url": result.page_url,
  913. "screenshot_path": getattr(result, 'screenshot_path', '') or ''
  914. }
  915. # 如果请求返回截图
  916. if return_screenshot and result.screenshot_base64:
  917. response_data["screenshot_base64"] = result.screenshot_base64
  918. return jsonify(response_data)
  919. except Exception as e:
  920. traceback.print_exc()
  921. return jsonify({"success": False, "error": str(e), "status": "error"}), 500
  922. # ==================== 批量发布接口 ====================
  923. @app.route("/publish/batch", methods=["POST"])
  924. def publish_batch():
  925. """
  926. 批量发布接口 - 发布到多个平台
  927. 请求体:
  928. {
  929. "platforms": ["douyin", "xiaohongshu"],
  930. "cookies": {
  931. "douyin": "cookie字符串",
  932. "xiaohongshu": "cookie字符串"
  933. },
  934. "title": "视频标题",
  935. "video_path": "视频文件绝对路径",
  936. ...
  937. }
  938. """
  939. try:
  940. data = request.json
  941. platforms = data.get("platforms", [])
  942. cookies = data.get("cookies", {})
  943. if not platforms:
  944. return jsonify({"success": False, "error": "缺少 platforms 参数"}), 400
  945. results = []
  946. for platform in platforms:
  947. platform = platform.lower()
  948. cookie_str = cookies.get(platform, "")
  949. if not cookie_str:
  950. results.append({
  951. "platform": platform,
  952. "success": False,
  953. "error": f"缺少 {platform} 的 cookie"
  954. })
  955. continue
  956. try:
  957. # 创建参数
  958. params = PublishParams(
  959. title=data.get("title", ""),
  960. video_path=data.get("video_path", ""),
  961. description=data.get("description", ""),
  962. cover_path=data.get("cover_path"),
  963. tags=data.get("tags", []),
  964. publish_date=parse_datetime(data.get("post_time")),
  965. location=data.get("location", "重庆市")
  966. )
  967. # 发布
  968. PublisherClass = get_publisher(platform)
  969. publisher = PublisherClass(headless=HEADLESS_MODE)
  970. result = asyncio.run(publisher.run(cookie_str, params))
  971. results.append({
  972. "platform": result.platform,
  973. "success": result.success,
  974. "video_id": result.video_id,
  975. "message": result.message,
  976. "error": result.error
  977. })
  978. except Exception as e:
  979. results.append({
  980. "platform": platform,
  981. "success": False,
  982. "error": str(e)
  983. })
  984. # 统计成功/失败数量
  985. success_count = sum(1 for r in results if r.get("success"))
  986. return jsonify({
  987. "success": success_count > 0,
  988. "total": len(platforms),
  989. "success_count": success_count,
  990. "fail_count": len(platforms) - success_count,
  991. "results": results
  992. })
  993. except Exception as e:
  994. traceback.print_exc()
  995. return jsonify({"success": False, "error": str(e)}), 500
  996. # ==================== Cookie 验证接口 ====================
  997. @app.route("/check_cookie", methods=["POST"])
  998. def check_cookie():
  999. """检查 cookie 是否有效"""
  1000. try:
  1001. data = request.json
  1002. platform = data.get("platform", "").lower()
  1003. cookie_str = data.get("cookie", "")
  1004. if not cookie_str:
  1005. return jsonify({"valid": False, "error": "缺少 cookie 参数"}), 400
  1006. # 目前只支持小红书的 cookie 验证
  1007. if platform == "xiaohongshu":
  1008. try:
  1009. from platforms.xiaohongshu import XiaohongshuPublisher, XHS_SDK_AVAILABLE
  1010. if XHS_SDK_AVAILABLE:
  1011. from xhs import XhsClient
  1012. publisher = XiaohongshuPublisher()
  1013. xhs_client = XhsClient(cookie_str, sign=publisher.sign_sync)
  1014. info = xhs_client.get_self_info()
  1015. if info:
  1016. return jsonify({
  1017. "valid": True,
  1018. "user_info": {
  1019. "user_id": info.get("user_id"),
  1020. "nickname": info.get("nickname"),
  1021. "avatar": info.get("images")
  1022. }
  1023. })
  1024. except Exception as e:
  1025. return jsonify({"valid": False, "error": str(e)})
  1026. # 其他平台返回格式正确但未验证
  1027. return jsonify({
  1028. "valid": True,
  1029. "message": "Cookie 格式正确,但未进行在线验证"
  1030. })
  1031. except Exception as e:
  1032. traceback.print_exc()
  1033. return jsonify({"valid": False, "error": str(e)})
  1034. # ==================== 获取作品列表接口 ====================
  1035. @app.route("/works", methods=["POST"])
  1036. def get_works():
  1037. """
  1038. 获取作品列表
  1039. 请求体:
  1040. {
  1041. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  1042. "cookie": "cookie字符串或JSON",
  1043. "page": 0, # 页码(从0开始,可选,默认0)
  1044. "page_size": 20 # 每页数量(可选,默认20)
  1045. }
  1046. 响应:
  1047. {
  1048. "success": true,
  1049. "platform": "douyin",
  1050. "works": [...],
  1051. "total": 100,
  1052. "has_more": true
  1053. }
  1054. """
  1055. try:
  1056. data = request.json
  1057. platform = data.get("platform", "").lower()
  1058. cookie_str = data.get("cookie", "")
  1059. page = data.get("page", 0)
  1060. page_size = data.get("page_size", 20)
  1061. auto_paging = bool(data.get("auto_paging", False))
  1062. print(f"[Works] 收到请求: platform={platform}, page={page}, page_size={page_size}, auto_paging={auto_paging}", flush=True)
  1063. if not platform:
  1064. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1065. if platform not in PLATFORM_MAP:
  1066. return jsonify({
  1067. "success": False,
  1068. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1069. }), 400
  1070. if not cookie_str:
  1071. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1072. # 获取对应平台的发布器
  1073. PublisherClass = get_publisher(platform)
  1074. publisher = PublisherClass(headless=HEADLESS_MODE)
  1075. # 执行获取作品
  1076. if platform == "xiaohongshu" and auto_paging and hasattr(publisher, "get_all_works"):
  1077. result = asyncio.run(publisher.get_all_works(cookie_str))
  1078. else:
  1079. result = asyncio.run(publisher.run_get_works(cookie_str, page, page_size))
  1080. return jsonify(result.to_dict())
  1081. except Exception as e:
  1082. traceback.print_exc()
  1083. return jsonify({"success": False, "error": str(e)}), 500
  1084. # ==================== 视频号同步作品每日数据(浏览器自动化) ====================
  1085. @app.route("/sync_weixin_account_works_daily_stats", methods=["POST"])
  1086. def sync_weixin_account_works_daily_stats():
  1087. """
  1088. 纯浏览器批量同步视频号账号下所有(在库)作品的每日数据到 work_day_statistics。
  1089. 流程:打开 statistic/post → 单篇视频 → 近30天 → 遍历列表,按 exportId 匹配作品,
  1090. 匹配则点击查看 → 详情页近30天 → 下载表格 → 解析 CSV 存入 work_day_statistics。
  1091. 请求体: {
  1092. "works": [{"work_id": 906, "platform_video_id": "export/xxx"}, ...],
  1093. "cookie": "...",
  1094. "show_browser": false
  1095. }
  1096. """
  1097. try:
  1098. data = request.json or {}
  1099. works = data.get("works", [])
  1100. cookie_str = data.get("cookie", "")
  1101. if not works or not cookie_str:
  1102. return jsonify({
  1103. "success": False,
  1104. "error": "缺少 works 或 cookie 参数",
  1105. }), 400
  1106. show_browser = data.get("show_browser", False)
  1107. if isinstance(show_browser, str):
  1108. show_browser = show_browser.lower() in ("true", "1", "yes")
  1109. headless = not show_browser
  1110. def save_fn(stats_list):
  1111. if not stats_list:
  1112. return {"inserted": 0, "updated": 0}
  1113. return call_nodejs_api("POST", "/work-day-statistics/batch-dates", {"statistics": stats_list})
  1114. def update_works_fn(updates):
  1115. if not updates:
  1116. return {"updated": 0}
  1117. return call_nodejs_api("POST", "/works/batch-update-from-csv", {"updates": updates})
  1118. publisher = WeixinPublisher(headless=headless)
  1119. result = asyncio.run(publisher.sync_account_works_daily_stats_via_browser(
  1120. cookie_str, works, save_fn=save_fn, update_works_fn=update_works_fn, headless=headless
  1121. ))
  1122. if not result.get("success"):
  1123. return jsonify({
  1124. "success": False,
  1125. "error": result.get("error", "同步失败"),
  1126. }), 200
  1127. works_updated = result.get("works_updated", 0)
  1128. msg = f"批量同步完成: 处理 {result.get('total_processed', 0)} 个作品, 跳过 {result.get('total_skipped', 0)} 个, 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条"
  1129. if works_updated > 0:
  1130. msg += f", works 表更新 {works_updated} 条"
  1131. return jsonify({
  1132. "success": True,
  1133. "message": msg,
  1134. "total_processed": result.get("total_processed", 0),
  1135. "total_skipped": result.get("total_skipped", 0),
  1136. "inserted": result.get("inserted", 0),
  1137. "updated": result.get("updated", 0),
  1138. "works_updated": works_updated,
  1139. })
  1140. except Exception as e:
  1141. traceback.print_exc()
  1142. return jsonify({"success": False, "error": str(e)}), 500
  1143. @app.route("/sync_weixin_work_daily_stats", methods=["POST"])
  1144. def sync_weixin_work_daily_stats():
  1145. """
  1146. 通过浏览器自动化同步单个视频号作品的每日数据到 work_day_statistics。
  1147. 请求体: { "work_id": 906, "platform_video_id": "export/xxx", "cookie": "..." }
  1148. """
  1149. try:
  1150. data = request.json or {}
  1151. work_id = data.get("work_id")
  1152. platform_video_id = (data.get("platform_video_id") or "").strip()
  1153. cookie_str = data.get("cookie", "")
  1154. if not work_id or not platform_video_id or not cookie_str:
  1155. return jsonify({
  1156. "success": False,
  1157. "error": "缺少 work_id、platform_video_id 或 cookie 参数",
  1158. }), 400
  1159. work_id = int(work_id)
  1160. # show_browser=True 时显示浏览器窗口,便于观察点击操作
  1161. show_browser = data.get("show_browser", True)
  1162. if isinstance(show_browser, str):
  1163. show_browser = show_browser.lower() in ("true", "1", "yes")
  1164. headless = not show_browser
  1165. print(f"[SyncWXDailyStats] headless={headless} (show_browser={show_browser})", flush=True)
  1166. publisher = WeixinPublisher(headless=headless)
  1167. result = asyncio.run(publisher.sync_work_daily_stats_via_browser(
  1168. cookie_str, work_id, platform_video_id
  1169. ))
  1170. if not result.get("success"):
  1171. return jsonify({
  1172. "success": False,
  1173. "error": result.get("error", "同步失败"),
  1174. }), 200
  1175. stats = result.get("statistics") or []
  1176. if not stats:
  1177. return jsonify({
  1178. "success": True,
  1179. "message": "无新数据需要保存",
  1180. "inserted": 0,
  1181. "updated": 0,
  1182. })
  1183. save_result = call_nodejs_api("POST", "/work-day-statistics/batch-dates", {
  1184. "statistics": stats,
  1185. })
  1186. return jsonify({
  1187. "success": True,
  1188. "message": f"同步成功: 新增 {save_result.get('inserted', 0)} 条, 更新 {save_result.get('updated', 0)} 条",
  1189. "inserted": save_result.get("inserted", 0),
  1190. "updated": save_result.get("updated", 0),
  1191. })
  1192. except Exception as e:
  1193. traceback.print_exc()
  1194. return jsonify({"success": False, "error": str(e)}), 500
  1195. # ==================== 保存作品日统计数据接口 ====================
  1196. @app.route("/work_day_statistics", methods=["POST"])
  1197. def save_work_day_statistics():
  1198. """
  1199. 保存作品每日统计数据
  1200. 当天的数据走更新流,日期变化走新增流
  1201. 请求体:
  1202. {
  1203. "statistics": [
  1204. {
  1205. "work_id": 1,
  1206. "fans_count": 1000,
  1207. "play_count": 5000,
  1208. "like_count": 200,
  1209. "comment_count": 50,
  1210. "share_count": 30,
  1211. "collect_count": 100
  1212. },
  1213. ...
  1214. ]
  1215. }
  1216. 响应:
  1217. {
  1218. "success": true,
  1219. "inserted": 5,
  1220. "updated": 3,
  1221. "message": "保存成功"
  1222. }
  1223. """
  1224. print("=" * 60, flush=True)
  1225. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  1226. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  1227. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  1228. print("=" * 60, flush=True)
  1229. try:
  1230. data = request.json
  1231. statistics_list = data.get("statistics", [])
  1232. if not statistics_list:
  1233. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  1234. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  1235. # 调用 Node.js API 保存数据
  1236. result = call_nodejs_api('POST', '/work-day-statistics', {
  1237. 'statistics': statistics_list
  1238. })
  1239. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  1240. return jsonify(result)
  1241. except Exception as e:
  1242. traceback.print_exc()
  1243. return jsonify({"success": False, "error": str(e)}), 500
  1244. @app.route("/work_day_statistics/trend", methods=["GET"])
  1245. def get_statistics_trend():
  1246. """
  1247. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  1248. 查询参数:
  1249. user_id: 用户ID (必填)
  1250. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  1251. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  1252. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  1253. account_id: 账号ID (可选,不填则查询所有账号)
  1254. 响应:
  1255. {
  1256. "success": true,
  1257. "data": {
  1258. "dates": ["01-16", "01-17", "01-18", ...],
  1259. "fans": [100, 120, 130, ...],
  1260. "views": [1000, 1200, 1500, ...],
  1261. "likes": [50, 60, 70, ...],
  1262. "comments": [10, 12, 15, ...],
  1263. "shares": [5, 6, 8, ...],
  1264. "collects": [20, 25, 30, ...]
  1265. }
  1266. }
  1267. """
  1268. try:
  1269. user_id = request.args.get("user_id")
  1270. days = request.args.get("days")
  1271. start_date = request.args.get("start_date")
  1272. end_date = request.args.get("end_date")
  1273. account_id = request.args.get("account_id")
  1274. if not user_id:
  1275. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1276. # 调用 Node.js API 获取数据
  1277. params = {"user_id": user_id}
  1278. if days:
  1279. params["days"] = days
  1280. if start_date:
  1281. params["start_date"] = start_date
  1282. if end_date:
  1283. params["end_date"] = end_date
  1284. if account_id:
  1285. params["account_id"] = account_id
  1286. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  1287. return jsonify(result)
  1288. except Exception as e:
  1289. traceback.print_exc()
  1290. return jsonify({"success": False, "error": str(e)}), 500
  1291. @app.route("/work_day_statistics/platforms", methods=["GET"])
  1292. def get_statistics_by_platform():
  1293. """
  1294. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  1295. 数据来源:
  1296. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  1297. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  1298. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  1299. 查询参数:
  1300. user_id: 用户ID (必填)
  1301. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  1302. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  1303. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  1304. 响应:
  1305. {
  1306. "success": true,
  1307. "data": [
  1308. {
  1309. "platform": "douyin",
  1310. "fansCount": 1000,
  1311. "fansIncrease": 50,
  1312. "viewsCount": 5000,
  1313. "likesCount": 200,
  1314. "commentsCount": 30,
  1315. "collectsCount": 100
  1316. },
  1317. ...
  1318. ]
  1319. }
  1320. """
  1321. try:
  1322. user_id = request.args.get("user_id")
  1323. days = request.args.get("days")
  1324. start_date = request.args.get("start_date")
  1325. end_date = request.args.get("end_date")
  1326. if not user_id:
  1327. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1328. # 调用 Node.js API 获取数据
  1329. params = {"user_id": user_id}
  1330. if days:
  1331. params["days"] = days
  1332. if start_date:
  1333. params["start_date"] = start_date
  1334. if end_date:
  1335. params["end_date"] = end_date
  1336. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  1337. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  1338. return jsonify(result)
  1339. except Exception as e:
  1340. traceback.print_exc()
  1341. return jsonify({"success": False, "error": str(e)}), 500
  1342. @app.route("/work_day_statistics/batch", methods=["POST"])
  1343. def get_work_statistics_history():
  1344. """
  1345. 批量获取作品的历史统计数据
  1346. 请求体:
  1347. {
  1348. "work_ids": [1, 2, 3],
  1349. "start_date": "2025-01-01", # 可选
  1350. "end_date": "2025-01-21" # 可选
  1351. }
  1352. 响应:
  1353. {
  1354. "success": true,
  1355. "data": {
  1356. "1": [
  1357. {"record_date": "2025-01-20", "play_count": 100, ...},
  1358. {"record_date": "2025-01-21", "play_count": 150, ...}
  1359. ],
  1360. ...
  1361. }
  1362. }
  1363. """
  1364. try:
  1365. data = request.json
  1366. work_ids = data.get("work_ids", [])
  1367. start_date = data.get("start_date")
  1368. end_date = data.get("end_date")
  1369. if not work_ids:
  1370. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  1371. # 调用 Node.js API 获取数据
  1372. request_data = {"work_ids": work_ids}
  1373. if start_date:
  1374. request_data["start_date"] = start_date
  1375. if end_date:
  1376. request_data["end_date"] = end_date
  1377. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  1378. return jsonify(result)
  1379. except Exception as e:
  1380. traceback.print_exc()
  1381. return jsonify({"success": False, "error": str(e)}), 500
  1382. @app.route("/work_day_statistics/overview", methods=["GET"])
  1383. def get_overview():
  1384. """
  1385. 获取数据总览(账号列表和汇总统计)
  1386. 查询参数:
  1387. user_id: 用户ID (必填)
  1388. 响应:
  1389. {
  1390. "success": true,
  1391. "data": {
  1392. "accounts": [
  1393. {
  1394. "id": 1,
  1395. "nickname": "账号名称",
  1396. "username": "账号ID",
  1397. "avatarUrl": "头像URL",
  1398. "platform": "douyin",
  1399. "groupId": 1,
  1400. "fansCount": 1000,
  1401. "totalIncome": null,
  1402. "yesterdayIncome": null,
  1403. "totalViews": 5000,
  1404. "yesterdayViews": 100,
  1405. "yesterdayComments": 10,
  1406. "yesterdayLikes": 50,
  1407. "yesterdayFansIncrease": 5,
  1408. "updateTime": "2025-01-26T10:00:00Z",
  1409. "status": "active"
  1410. },
  1411. ...
  1412. ],
  1413. "summary": {
  1414. "totalAccounts": 5,
  1415. "totalIncome": 0,
  1416. "yesterdayIncome": 0,
  1417. "totalViews": 10000,
  1418. "yesterdayViews": 200,
  1419. "totalFans": 5000,
  1420. "yesterdayComments": 20,
  1421. "yesterdayLikes": 100,
  1422. "yesterdayFansIncrease": 10
  1423. }
  1424. }
  1425. }
  1426. """
  1427. try:
  1428. user_id = request.args.get("user_id")
  1429. if not user_id:
  1430. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  1431. # 调用 Node.js API 获取数据
  1432. params = {"user_id": user_id}
  1433. result = call_nodejs_api('GET', '/work-day-statistics/overview', params=params)
  1434. return jsonify(result)
  1435. except NodeApiError as e:
  1436. # 透传 Node 的真实状态码/错误内容,避免所有错误都变成 500
  1437. return jsonify(e.payload), e.status_code
  1438. except Exception as e:
  1439. traceback.print_exc()
  1440. return jsonify({"success": False, "error": str(e)}), 500
  1441. # ==================== 获取评论列表接口 ====================
  1442. @app.route("/comments", methods=["POST"])
  1443. def get_comments():
  1444. """
  1445. 获取作品评论
  1446. 请求体:
  1447. {
  1448. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  1449. "cookie": "cookie字符串或JSON",
  1450. "work_id": "作品ID",
  1451. "cursor": "" # 分页游标(可选)
  1452. }
  1453. 响应:
  1454. {
  1455. "success": true,
  1456. "platform": "douyin",
  1457. "work_id": "xxx",
  1458. "comments": [...],
  1459. "total": 50,
  1460. "has_more": true,
  1461. "cursor": "xxx"
  1462. }
  1463. """
  1464. try:
  1465. data = request.json
  1466. platform = data.get("platform", "").lower()
  1467. cookie_str = data.get("cookie", "")
  1468. work_id = data.get("work_id", "")
  1469. cursor = data.get("cursor", "")
  1470. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  1471. if not platform:
  1472. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1473. if platform not in PLATFORM_MAP:
  1474. return jsonify({
  1475. "success": False,
  1476. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1477. }), 400
  1478. if not cookie_str:
  1479. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1480. if not work_id:
  1481. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  1482. # 获取对应平台的发布器
  1483. PublisherClass = get_publisher(platform)
  1484. publisher = PublisherClass(headless=HEADLESS_MODE)
  1485. # 执行获取评论
  1486. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  1487. result_dict = result.to_dict()
  1488. # 添加 cursor 到响应
  1489. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  1490. result_dict['cursor'] = result.__dict__['cursor']
  1491. return jsonify(result_dict)
  1492. except Exception as e:
  1493. traceback.print_exc()
  1494. return jsonify({"success": False, "error": str(e)}), 500
  1495. # ==================== 获取所有作品评论接口 ====================
  1496. @app.route("/all_comments", methods=["POST"])
  1497. def get_all_comments():
  1498. """
  1499. 获取所有作品的评论(一次性获取)
  1500. 请求体:
  1501. {
  1502. "platform": "douyin", # douyin | xiaohongshu
  1503. "cookie": "cookie字符串或JSON"
  1504. }
  1505. 响应:
  1506. {
  1507. "success": true,
  1508. "platform": "douyin",
  1509. "work_comments": [
  1510. {
  1511. "work_id": "xxx",
  1512. "title": "作品标题",
  1513. "cover_url": "封面URL",
  1514. "comments": [...]
  1515. }
  1516. ],
  1517. "total": 5
  1518. }
  1519. """
  1520. try:
  1521. data = request.json
  1522. platform = data.get("platform", "").lower()
  1523. cookie_str = data.get("cookie", "")
  1524. print(f"[AllComments] 收到请求: platform={platform}")
  1525. if not platform:
  1526. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1527. if platform not in ['douyin', 'xiaohongshu']:
  1528. return jsonify({
  1529. "success": False,
  1530. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  1531. }), 400
  1532. if not cookie_str:
  1533. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1534. # 获取对应平台的发布器
  1535. PublisherClass = get_publisher(platform)
  1536. publisher = PublisherClass(headless=HEADLESS_MODE)
  1537. # 执行获取所有评论
  1538. result = asyncio.run(publisher.get_all_comments(cookie_str))
  1539. return jsonify(result)
  1540. except Exception as e:
  1541. traceback.print_exc()
  1542. return jsonify({"success": False, "error": str(e)}), 500
  1543. # ==================== 登录状态检查接口 ====================
  1544. @app.route("/check_login", methods=["POST"])
  1545. def check_login():
  1546. """
  1547. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  1548. 请求体:
  1549. {
  1550. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  1551. "cookie": "cookie字符串或JSON"
  1552. }
  1553. 响应:
  1554. {
  1555. "success": true,
  1556. "valid": true, # Cookie 是否有效
  1557. "need_login": false, # 是否需要重新登录
  1558. "message": "登录状态有效"
  1559. }
  1560. """
  1561. try:
  1562. data = request.json
  1563. platform = data.get("platform", "").lower()
  1564. cookie_str = data.get("cookie", "")
  1565. print(f"[CheckLogin] 收到请求: platform={platform}")
  1566. if not platform:
  1567. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1568. if platform not in PLATFORM_MAP:
  1569. return jsonify({
  1570. "success": False,
  1571. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1572. }), 400
  1573. if not cookie_str:
  1574. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1575. # 获取对应平台的发布器
  1576. PublisherClass = get_publisher(platform)
  1577. publisher = PublisherClass(headless=HEADLESS_MODE)
  1578. # 执行登录检查
  1579. result = asyncio.run(publisher.check_login_status(cookie_str))
  1580. return jsonify(result)
  1581. except Exception as e:
  1582. traceback.print_exc()
  1583. return jsonify({
  1584. "success": False,
  1585. "valid": False,
  1586. "need_login": True,
  1587. "error": str(e)
  1588. }), 500
  1589. # ==================== 获取账号信息接口 ====================
  1590. @app.route("/account_info", methods=["POST"])
  1591. def get_account_info():
  1592. """
  1593. 获取账号信息
  1594. 请求体:
  1595. {
  1596. "platform": "baijiahao", # 平台
  1597. "cookie": "cookie字符串或JSON"
  1598. }
  1599. 响应:
  1600. {
  1601. "success": true,
  1602. "account_id": "xxx",
  1603. "account_name": "用户名",
  1604. "avatar_url": "头像URL",
  1605. "fans_count": 0,
  1606. "works_count": 0
  1607. }
  1608. """
  1609. try:
  1610. data = request.json
  1611. platform = data.get("platform", "").lower()
  1612. cookie_str = data.get("cookie", "")
  1613. print(f"[AccountInfo] 收到请求: platform={platform}")
  1614. if not platform:
  1615. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1616. if platform not in PLATFORM_MAP:
  1617. return jsonify({
  1618. "success": False,
  1619. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1620. }), 400
  1621. if not cookie_str:
  1622. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1623. # 获取对应平台的发布器
  1624. PublisherClass = get_publisher(platform)
  1625. publisher = PublisherClass(headless=HEADLESS_MODE)
  1626. # 检查是否有 get_account_info 方法
  1627. if hasattr(publisher, 'get_account_info'):
  1628. result = asyncio.run(publisher.get_account_info(cookie_str))
  1629. return jsonify(result)
  1630. else:
  1631. return jsonify({
  1632. "success": False,
  1633. "error": f"平台 {platform} 不支持获取账号信息"
  1634. }), 400
  1635. except Exception as e:
  1636. traceback.print_exc()
  1637. return jsonify({"success": False, "error": str(e)}), 500
  1638. # ==================== 百家号作品每日数据辅助接口 ====================
  1639. @app.route("/baijiahao/article_stats", methods=["POST"])
  1640. def baijiahao_article_stats():
  1641. """
  1642. 百家号:代理调用 /author/eco/statistics/articleListStatistic
  1643. 请求体:
  1644. {
  1645. "cookie": "...",
  1646. "start_day": "YYYYMMDD",
  1647. "end_day": "YYYYMMDD",
  1648. "type": "small_video_v2|video|news",
  1649. "num": 1,
  1650. "count": 10
  1651. }
  1652. """
  1653. try:
  1654. data = request.json or {}
  1655. cookie_str = data.get("cookie", "")
  1656. start_day = data.get("start_day", "")
  1657. end_day = data.get("end_day", "")
  1658. stat_type = data.get("type", "video")
  1659. num = int(data.get("num", 1) or 1)
  1660. count = int(data.get("count", 10) or 10)
  1661. if not cookie_str:
  1662. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1663. if not start_day or not end_day:
  1664. return jsonify({"success": False, "error": "缺少 start_day 或 end_day 参数"}), 400
  1665. PublisherClass = get_publisher("baijiahao")
  1666. publisher = PublisherClass(headless=HEADLESS_MODE)
  1667. result = asyncio.run(
  1668. publisher.get_article_stats(
  1669. cookie_str,
  1670. start_day=start_day,
  1671. end_day=end_day,
  1672. stat_type=stat_type,
  1673. num=num,
  1674. count=count,
  1675. )
  1676. )
  1677. return jsonify(result)
  1678. except Exception as e:
  1679. traceback.print_exc()
  1680. return jsonify({"success": False, "error": str(e)}), 500
  1681. @app.route("/baijiahao/trend_data", methods=["POST"])
  1682. def baijiahao_trend_data():
  1683. """
  1684. 百家号:代理调用 /author/eco/statistic/gettrenddata
  1685. 请求体:
  1686. {
  1687. "cookie": "...",
  1688. "nid": "文章/视频 nid 或 article_id"
  1689. }
  1690. """
  1691. try:
  1692. data = request.json or {}
  1693. cookie_str = data.get("cookie", "")
  1694. nid = data.get("nid", "")
  1695. if not cookie_str:
  1696. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1697. if not nid:
  1698. return jsonify({"success": False, "error": "缺少 nid 参数"}), 400
  1699. PublisherClass = get_publisher("baijiahao")
  1700. publisher = PublisherClass(headless=HEADLESS_MODE)
  1701. result = asyncio.run(
  1702. publisher.get_trend_data(
  1703. cookie_str,
  1704. nid=str(nid),
  1705. )
  1706. )
  1707. return jsonify(result)
  1708. except Exception as e:
  1709. traceback.print_exc()
  1710. return jsonify({"success": False, "error": str(e)}), 500
  1711. @app.route("/baijiahao/app_statistic_v3", methods=["POST"])
  1712. def baijiahao_app_statistic_v3():
  1713. """
  1714. 百家号用户每日数据:代理调用 appStatisticV3(账号近30天基础数据)。
  1715. 登录模式与打开后台一致:使用账号已存 Cookie。
  1716. 请求体: { "cookie": "...", "start_day": "YYYYMMDD", "end_day": "YYYYMMDD" }
  1717. """
  1718. try:
  1719. data = request.json or {}
  1720. cookie_str = data.get("cookie", "")
  1721. start_day = data.get("start_day", "")
  1722. end_day = data.get("end_day", "")
  1723. if not cookie_str:
  1724. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1725. if not start_day or not end_day:
  1726. return jsonify({"success": False, "error": "缺少 start_day 或 end_day 参数"}), 400
  1727. PublisherClass = get_publisher("baijiahao")
  1728. publisher = PublisherClass(headless=HEADLESS_MODE)
  1729. result = asyncio.run(
  1730. publisher.get_app_statistic_v3(cookie_str, start_day=start_day, end_day=end_day)
  1731. )
  1732. return jsonify(result)
  1733. except Exception as e:
  1734. traceback.print_exc()
  1735. return jsonify({"success": False, "error": str(e), "errno": -1}), 500
  1736. @app.route("/baijiahao/fans_basic_info", methods=["POST"])
  1737. def baijiahao_fans_basic_info():
  1738. """
  1739. 百家号用户每日数据:代理调用 getFansBasicInfo(近30天粉丝数据)。
  1740. 登录模式与打开后台一致:使用账号已存 Cookie。
  1741. 请求体: { "cookie": "...", "start": "YYYYMMDD", "end": "YYYYMMDD" }
  1742. """
  1743. try:
  1744. data = request.json or {}
  1745. cookie_str = data.get("cookie", "")
  1746. start_str = data.get("start", "")
  1747. end_str = data.get("end", "")
  1748. if not cookie_str:
  1749. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1750. if not start_str or not end_str:
  1751. return jsonify({"success": False, "error": "缺少 start 或 end 参数"}), 400
  1752. PublisherClass = get_publisher("baijiahao")
  1753. publisher = PublisherClass(headless=HEADLESS_MODE)
  1754. result = asyncio.run(
  1755. publisher.get_fans_basic_info(cookie_str, start=start_str, end=end_str)
  1756. )
  1757. return jsonify(result)
  1758. except Exception as e:
  1759. traceback.print_exc()
  1760. return jsonify({"success": False, "error": str(e), "errno": -1}), 500
  1761. @app.route("/xiaohongshu/account_base", methods=["POST"])
  1762. def xiaohongshu_account_base():
  1763. """
  1764. 小红书每日用户数据:代理调用创作者中心 account/base(账号概览近30日)。
  1765. 登录方式与打开后台一致:使用账号已存 Cookie。
  1766. 请求体: { "cookie": "..." }
  1767. """
  1768. try:
  1769. data = request.json or {}
  1770. cookie_str = data.get("cookie", "")
  1771. if not cookie_str:
  1772. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1773. PublisherClass = get_publisher("xiaohongshu")
  1774. publisher = PublisherClass(headless=HEADLESS_MODE)
  1775. result = asyncio.run(publisher.get_account_base(cookie_str))
  1776. return jsonify(result)
  1777. except Exception as e:
  1778. traceback.print_exc()
  1779. return jsonify({"data": None, "code": 500, "error": str(e)}), 500
  1780. @app.route("/xiaohongshu/fans_overall_new", methods=["POST"])
  1781. def xiaohongshu_fans_overall_new():
  1782. """
  1783. 小红书每日用户数据:代理调用创作者中心 fans/overall_new(粉丝趋势近30日)。
  1784. 登录方式与打开后台一致:使用账号已存 Cookie。
  1785. 请求体: { "cookie": "..." }
  1786. """
  1787. try:
  1788. data = request.json or {}
  1789. cookie_str = data.get("cookie", "")
  1790. if not cookie_str:
  1791. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1792. PublisherClass = get_publisher("xiaohongshu")
  1793. publisher = PublisherClass(headless=HEADLESS_MODE)
  1794. result = asyncio.run(publisher.get_fans_overall_new(cookie_str))
  1795. return jsonify(result)
  1796. except Exception as e:
  1797. traceback.print_exc()
  1798. return jsonify({"data": None, "code": 500, "error": str(e)}), 500
  1799. @app.route("/xiaohongshu/account_overview", methods=["POST"])
  1800. def xiaohongshu_account_overview():
  1801. """
  1802. 小红书每日用户数据:一次请求同时拉取 account/base 与 fans/overall_new(内部并行),减少耗时。
  1803. 请求体: { "cookie": "..." }
  1804. 返回: { "account_base": {...}, "fans_overall_new": {...} }
  1805. """
  1806. try:
  1807. data = request.json or {}
  1808. cookie_str = data.get("cookie", "")
  1809. if not cookie_str:
  1810. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1811. PublisherClass = get_publisher("xiaohongshu")
  1812. publisher = PublisherClass(headless=HEADLESS_MODE)
  1813. result = asyncio.run(publisher.get_account_overview(cookie_str))
  1814. return jsonify(result)
  1815. except Exception as e:
  1816. traceback.print_exc()
  1817. return jsonify({"account_base": None, "fans_overall_new": None, "code": 500, "error": str(e)}), 500
  1818. @app.route("/xiaohongshu/note_base", methods=["POST"])
  1819. def xiaohongshu_note_base():
  1820. """
  1821. 小红书每日作品数据:代理调用创作者中心 note/base(单条笔记数据)。
  1822. 登录方式与打开后台一致:使用账号已存 Cookie。
  1823. 请求体: { "cookie": "...", "note_id": "xxx" }
  1824. """
  1825. try:
  1826. data = request.json or {}
  1827. cookie_str = data.get("cookie", "")
  1828. note_id = (data.get("note_id") or "").strip()
  1829. if not cookie_str:
  1830. return jsonify({"data": None, "code": 400, "error": "缺少 cookie 参数"}), 400
  1831. if not note_id:
  1832. return jsonify({"data": None, "code": 400, "error": "缺少 note_id 参数"}), 400
  1833. PublisherClass = get_publisher("xiaohongshu")
  1834. publisher = PublisherClass(headless=HEADLESS_MODE)
  1835. result = asyncio.run(publisher.get_note_base(cookie_str, note_id))
  1836. return jsonify(result)
  1837. except Exception as e:
  1838. traceback.print_exc()
  1839. return jsonify({"data": None, "code": 500, "error": str(e)}), 500
  1840. # ==================== 健康检查 ====================
  1841. @app.route("/health", methods=["GET"])
  1842. def health_check():
  1843. """健康检查"""
  1844. # 检查 xhs SDK 是否可用
  1845. xhs_available = False
  1846. try:
  1847. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1848. xhs_available = XHS_SDK_AVAILABLE
  1849. except:
  1850. pass
  1851. return jsonify({
  1852. "status": "ok",
  1853. "xhs_sdk": xhs_available,
  1854. "supported_platforms": list(PLATFORM_MAP.keys()),
  1855. "headless_mode": HEADLESS_MODE
  1856. })
  1857. @app.route("/", methods=["GET"])
  1858. def index():
  1859. """首页"""
  1860. return jsonify({
  1861. "name": "智媒通视频发布服务",
  1862. "version": "1.2.0",
  1863. "endpoints": {
  1864. "GET /": "服务信息",
  1865. "GET /health": "健康检查",
  1866. "POST /publish": "发布视频",
  1867. "POST /publish/batch": "批量发布",
  1868. "POST /works": "获取作品列表",
  1869. "POST /comments": "获取作品评论",
  1870. "POST /all_comments": "获取所有作品评论",
  1871. "POST /work_day_statistics": "保存作品每日统计数据",
  1872. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  1873. "POST /check_cookie": "检查 Cookie",
  1874. "POST /sign": "小红书签名"
  1875. },
  1876. "supported_platforms": list(PLATFORM_MAP.keys())
  1877. })
  1878. # ==================== 命令行启动 ====================
  1879. def main():
  1880. parser = argparse.ArgumentParser(description='智媒通视频发布服务')
  1881. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  1882. # 从环境变量读取 HOST,默认仅本地访问
  1883. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  1884. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  1885. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  1886. parser.add_argument('--debug', action='store_true', help='调试模式')
  1887. args = parser.parse_args()
  1888. global HEADLESS_MODE
  1889. HEADLESS_MODE = args.headless.lower() == 'true'
  1890. # 检查 xhs SDK
  1891. xhs_status = "未安装"
  1892. try:
  1893. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1894. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  1895. except:
  1896. pass
  1897. print("=" * 60)
  1898. print("智媒通视频发布服务")
  1899. print("=" * 60)
  1900. print(f"XHS SDK: {xhs_status}")
  1901. print(f"Headless 模式: {HEADLESS_MODE}")
  1902. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  1903. print("=" * 60)
  1904. print(f"启动服务: http://{args.host}:{args.port}")
  1905. print("=" * 60)
  1906. app.run(host=args.host, port=args.port, debug=bool(args.debug), threaded=True, use_reloader=False)
  1907. @app.route('/auto-reply', methods=['POST'])
  1908. def auto_reply():
  1909. """
  1910. 微信视频号自动回复私信
  1911. POST /auto-reply
  1912. Body: {
  1913. "platform": "weixin",
  1914. "cookie": "..."
  1915. }
  1916. """
  1917. try:
  1918. data = request.json
  1919. platform = data.get('platform', '').lower()
  1920. cookie = data.get('cookie', '')
  1921. if platform != 'weixin':
  1922. return jsonify({
  1923. 'success': False,
  1924. 'error': '只支持微信视频号平台'
  1925. }), 400
  1926. if not cookie:
  1927. return jsonify({
  1928. 'success': False,
  1929. 'error': '缺少 Cookie'
  1930. }), 400
  1931. print(f"[API] 接收自动回复请求: platform={platform}")
  1932. # 创建 Publisher 实例
  1933. publisher = WeixinPublisher(headless=HEADLESS_MODE)
  1934. # 执行自动回复
  1935. loop = asyncio.new_event_loop()
  1936. asyncio.set_event_loop(loop)
  1937. result = loop.run_until_complete(publisher.auto_reply_private_messages(cookie))
  1938. loop.close()
  1939. print(f"[API] 自动回复结果: {result}")
  1940. return jsonify(result)
  1941. except Exception as e:
  1942. print(f"[API] 自动回复异常: {e}")
  1943. traceback.print_exc()
  1944. return jsonify({
  1945. 'success': False,
  1946. 'error': str(e)
  1947. }), 500
  1948. if __name__ == '__main__':
  1949. main()