app.py 82 KB

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