base.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. # -*- coding: utf-8 -*-
  2. """
  3. 平台发布基类
  4. 提供通用的发布接口和工具方法
  5. """
  6. import asyncio
  7. import json
  8. import os
  9. import uuid
  10. from abc import ABC, abstractmethod
  11. from dataclasses import dataclass, field
  12. from datetime import datetime
  13. from typing import List, Optional, Callable, Dict, Any
  14. from playwright.async_api import async_playwright, Browser, BrowserContext, Page
  15. @dataclass
  16. class PublishParams:
  17. """发布参数"""
  18. title: str
  19. video_path: str
  20. description: str = ""
  21. cover_path: Optional[str] = None
  22. tags: List[str] = field(default_factory=list)
  23. publish_date: Optional[datetime] = None
  24. location: str = "重庆市"
  25. def __post_init__(self):
  26. if not self.description:
  27. self.description = self.title
  28. @dataclass
  29. class PublishResult:
  30. """发布结果"""
  31. success: bool
  32. platform: str
  33. video_id: str = ""
  34. video_url: str = ""
  35. message: str = ""
  36. error: str = ""
  37. need_captcha: bool = False # 是否需要验证码
  38. captcha_type: str = "" # 验证码类型: phone, slider, image
  39. screenshot_base64: str = "" # 页面截图(Base64)
  40. page_url: str = "" # 当前页面 URL
  41. status: str = "" # 状态: uploading, processing, success, failed, need_captcha, need_action
  42. @dataclass
  43. class WorkItem:
  44. """作品数据"""
  45. work_id: str
  46. title: str
  47. cover_url: str = ""
  48. video_url: str = ""
  49. duration: int = 0 # 秒
  50. status: str = "published" # published, reviewing, rejected, draft
  51. publish_time: str = ""
  52. play_count: int = 0
  53. like_count: int = 0
  54. comment_count: int = 0
  55. share_count: int = 0
  56. collect_count: int = 0
  57. def to_dict(self) -> Dict[str, Any]:
  58. return {
  59. "work_id": self.work_id,
  60. "title": self.title,
  61. "cover_url": self.cover_url,
  62. "video_url": self.video_url,
  63. "duration": self.duration,
  64. "status": self.status,
  65. "publish_time": self.publish_time,
  66. "play_count": self.play_count,
  67. "like_count": self.like_count,
  68. "comment_count": self.comment_count,
  69. "share_count": self.share_count,
  70. "collect_count": self.collect_count,
  71. }
  72. @dataclass
  73. class CommentItem:
  74. """评论数据"""
  75. comment_id: str
  76. work_id: str
  77. content: str
  78. author_id: str = ""
  79. author_name: str = ""
  80. author_avatar: str = ""
  81. like_count: int = 0
  82. reply_count: int = 0
  83. create_time: str = ""
  84. is_author: bool = False # 是否是作者的评论
  85. replies: List['CommentItem'] = field(default_factory=list)
  86. def to_dict(self) -> Dict[str, Any]:
  87. return {
  88. "comment_id": self.comment_id,
  89. "work_id": self.work_id,
  90. "content": self.content,
  91. "author_id": self.author_id,
  92. "author_name": self.author_name,
  93. "author_avatar": self.author_avatar,
  94. "like_count": self.like_count,
  95. "reply_count": self.reply_count,
  96. "create_time": self.create_time,
  97. "is_author": self.is_author,
  98. "replies": [r.to_dict() for r in self.replies],
  99. }
  100. @dataclass
  101. class WorksResult:
  102. """作品列表结果"""
  103. success: bool
  104. platform: str
  105. works: List[WorkItem] = field(default_factory=list)
  106. total: int = 0
  107. has_more: bool = False
  108. next_page: Any = ""
  109. error: str = ""
  110. debug_info: str = "" # 调试信息
  111. def to_dict(self) -> Dict[str, Any]:
  112. return {
  113. "success": self.success,
  114. "platform": self.platform,
  115. "works": [w.to_dict() for w in self.works],
  116. "total": self.total,
  117. "has_more": self.has_more,
  118. "next_page": self.next_page,
  119. "error": self.error,
  120. "debug_info": self.debug_info,
  121. }
  122. @dataclass
  123. class CommentsResult:
  124. """评论列表结果"""
  125. success: bool
  126. platform: str
  127. work_id: str
  128. comments: List[CommentItem] = field(default_factory=list)
  129. total: int = 0
  130. has_more: bool = False
  131. error: str = ""
  132. def to_dict(self) -> Dict[str, Any]:
  133. return {
  134. "success": self.success,
  135. "platform": self.platform,
  136. "work_id": self.work_id,
  137. "comments": [c.to_dict() for c in self.comments],
  138. "total": self.total,
  139. "has_more": self.has_more,
  140. "error": self.error,
  141. }
  142. class BasePublisher(ABC):
  143. """
  144. 平台发布基类
  145. 所有平台发布器都需要继承此类
  146. """
  147. platform_name: str = "base"
  148. login_url: str = ""
  149. publish_url: str = ""
  150. cookie_domain: str = ""
  151. def __init__(self, headless: bool = True):
  152. self.headless = headless
  153. self.browser: Optional[Browser] = None
  154. self.context: Optional[BrowserContext] = None
  155. self.page: Optional[Page] = None
  156. self.on_progress: Optional[Callable[[int, str], None]] = None
  157. self.user_id: Optional[int] = None
  158. self.publish_task_id: Optional[int] = None
  159. self.publish_account_id: Optional[int] = None
  160. self.proxy_config: Optional[Dict[str, Any]] = None
  161. def set_progress_callback(self, callback: Callable[[int, str], None]):
  162. """设置进度回调"""
  163. self.on_progress = callback
  164. def report_progress(self, progress: int, message: str):
  165. """报告进度"""
  166. print(f"[{self.platform_name}] [{progress}%] {message}")
  167. if self.on_progress:
  168. self.on_progress(progress, message)
  169. @staticmethod
  170. def parse_cookies(cookies_str: str) -> list:
  171. """解析 cookie 字符串为列表"""
  172. try:
  173. cookies = json.loads(cookies_str)
  174. if isinstance(cookies, list):
  175. return cookies
  176. except json.JSONDecodeError:
  177. pass
  178. # 字符串格式: name=value; name2=value2
  179. cookies = []
  180. for item in cookies_str.split(';'):
  181. item = item.strip()
  182. if '=' in item:
  183. name, value = item.split('=', 1)
  184. cookies.append({
  185. 'name': name.strip(),
  186. 'value': value.strip(),
  187. 'domain': '',
  188. 'path': '/'
  189. })
  190. return cookies
  191. @staticmethod
  192. def cookies_to_string(cookies: list) -> str:
  193. """将 cookie 列表转换为字符串"""
  194. return '; '.join([f"{c['name']}={c['value']}" for c in cookies])
  195. async def init_browser(self, storage_state: str = None, proxy_config: Dict[str, Any] = None):
  196. """初始化浏览器"""
  197. print(f"[{self.platform_name}] init_browser: headless={self.headless}", flush=True)
  198. playwright = await async_playwright().start()
  199. proxy = proxy_config or self.proxy_config
  200. if proxy and isinstance(proxy, dict) and proxy.get('server'):
  201. self.browser = await playwright.chromium.launch(headless=self.headless, proxy=proxy)
  202. else:
  203. self.browser = await playwright.chromium.launch(headless=self.headless)
  204. if storage_state and os.path.exists(storage_state):
  205. self.context = await self.browser.new_context(storage_state=storage_state)
  206. else:
  207. self.context = await self.browser.new_context()
  208. self.page = await self.context.new_page()
  209. return self.page
  210. async def set_cookies(self, cookies: list):
  211. """设置 cookies"""
  212. if not self.context:
  213. raise Exception("Browser context not initialized")
  214. # 设置默认域名
  215. for cookie in cookies:
  216. if 'domain' not in cookie or not cookie['domain']:
  217. cookie['domain'] = self.cookie_domain
  218. await self.context.add_cookies(cookies)
  219. async def close_browser(self):
  220. """关闭浏览器"""
  221. if self.context:
  222. await self.context.close()
  223. if self.browser:
  224. await self.browser.close()
  225. async def save_cookies(self, file_path: str):
  226. """保存 cookies 到文件"""
  227. if self.context:
  228. await self.context.storage_state(path=file_path)
  229. async def capture_screenshot(self) -> str:
  230. """截取当前页面截图,返回 Base64 编码"""
  231. import base64
  232. if not self.page:
  233. return ""
  234. try:
  235. screenshot_bytes = await self.page.screenshot(type="jpeg", quality=80)
  236. return base64.b64encode(screenshot_bytes).decode('utf-8')
  237. except Exception as e:
  238. print(f"[{self.platform_name}] 截图失败: {e}")
  239. return ""
  240. async def request_sms_code_from_frontend(self, phone: str = "", timeout_seconds: int = 120, message: str = "") -> str:
  241. node_api_url = os.environ.get('NODEJS_API_URL', 'http://localhost:3000').rstrip('/')
  242. internal_api_key = os.environ.get('INTERNAL_API_KEY', 'internal-api-key-default')
  243. if not self.user_id:
  244. raise Exception("缺少 user_id,无法请求前端输入验证码")
  245. captcha_task_id = f"py_{self.platform_name}_{uuid.uuid4().hex}"
  246. payload = {
  247. "user_id": self.user_id,
  248. "captcha_task_id": captcha_task_id,
  249. "type": "sms",
  250. "phone": phone or "",
  251. "message": message or "请输入短信验证码",
  252. "timeout_seconds": timeout_seconds,
  253. "publish_task_id": self.publish_task_id,
  254. "publish_account_id": self.publish_account_id,
  255. }
  256. import requests
  257. try:
  258. resp = requests.post(
  259. f"{node_api_url}/api/internal/captcha/request",
  260. headers={
  261. "Content-Type": "application/json",
  262. "X-Internal-API-Key": internal_api_key,
  263. },
  264. json=payload,
  265. timeout=timeout_seconds + 30,
  266. )
  267. except Exception as e:
  268. raise Exception(f"请求前端验证码失败: {e}")
  269. try:
  270. data = resp.json()
  271. except Exception:
  272. raise Exception(f"请求前端验证码失败: HTTP {resp.status_code}")
  273. if resp.status_code >= 400 or not data.get("success"):
  274. raise Exception(data.get("error") or data.get("message") or f"请求前端验证码失败: HTTP {resp.status_code}")
  275. code = data.get("code") or ""
  276. if not code:
  277. raise Exception("未收到验证码")
  278. return str(code)
  279. async def ai_analyze_sms_send_state(self, screenshot_base64: str = None) -> dict:
  280. import os
  281. import requests
  282. import json
  283. import re
  284. try:
  285. if not screenshot_base64:
  286. screenshot_base64 = await self.capture_screenshot()
  287. if not screenshot_base64:
  288. return {
  289. "has_sms_modal": False,
  290. "send_button_state": "unknown",
  291. "sent_likely": False,
  292. "block_reason": "unknown",
  293. "suggested_action": "manual_send",
  294. "confidence": 0,
  295. "notes": "无法获取截图",
  296. }
  297. ai_api_key = os.environ.get('DASHSCOPE_API_KEY', '')
  298. ai_base_url = os.environ.get('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1')
  299. ai_vision_model = os.environ.get('AI_VISION_MODEL', 'qwen-vl-plus')
  300. if not ai_api_key:
  301. return {
  302. "has_sms_modal": True,
  303. "send_button_state": "unknown",
  304. "sent_likely": False,
  305. "block_reason": "no_ai_key",
  306. "suggested_action": "manual_send",
  307. "confidence": 0,
  308. "notes": "未配置 AI API Key",
  309. }
  310. prompt = """请分析这张网页截图,判断是否处于“短信验证码”验证弹窗/页面,并判断“发送验证码/获取验证码”是否已经触发成功。
  311. 你需要重点识别:
  312. 1) 是否存在短信验证码弹窗(包含“请输入验证码/短信验证码/手机号验证/获取验证码/发送验证码”等)
  313. 2) 发送按钮状态:enabled / disabled / countdown(出现xx秒) / hidden / unknown
  314. 3) 是否已发送成功:例如出现倒计时、按钮禁用、出现“已发送/重新发送/xx秒后重试”等
  315. 4) 是否被阻塞:例如出现滑块/人机验证、频繁发送、风控提示、网络异常等
  316. 请以 JSON 返回:
  317. ```json
  318. {
  319. "has_sms_modal": true,
  320. "send_button_state": "enabled|disabled|countdown|hidden|unknown",
  321. "sent_likely": true,
  322. "block_reason": "none|need_click_send|slider|risk|rate_limit|network|unknown",
  323. "suggested_action": "wait|click_send|solve_slider|manual_send",
  324. "confidence": 0-100,
  325. "notes": "一句话说明你看到的证据"
  326. }
  327. ```"""
  328. headers = {
  329. 'Authorization': f'Bearer {ai_api_key}',
  330. 'Content-Type': 'application/json'
  331. }
  332. payload = {
  333. "model": ai_vision_model,
  334. "messages": [
  335. {
  336. "role": "user",
  337. "content": [
  338. {
  339. "type": "image_url",
  340. "image_url": {
  341. "url": f"data:image/jpeg;base64,{screenshot_base64}"
  342. }
  343. },
  344. {
  345. "type": "text",
  346. "text": prompt
  347. }
  348. ]
  349. }
  350. ],
  351. "max_tokens": 500
  352. }
  353. response = requests.post(
  354. f"{ai_base_url}/chat/completions",
  355. headers=headers,
  356. json=payload,
  357. timeout=30
  358. )
  359. if response.status_code != 200:
  360. return {
  361. "has_sms_modal": True,
  362. "send_button_state": "unknown",
  363. "sent_likely": False,
  364. "block_reason": "network",
  365. "suggested_action": "manual_send",
  366. "confidence": 0,
  367. "notes": f"AI API 返回错误 {response.status_code}",
  368. }
  369. result = response.json()
  370. ai_response = result.get('choices', [{}])[0].get('message', {}).get('content', '')
  371. json_match = re.search(r'```json\\s*([\\s\\S]*?)\\s*```', ai_response)
  372. if json_match:
  373. json_str = json_match.group(1)
  374. else:
  375. json_match = re.search(r'\\{[\\s\\S]*\\}', ai_response)
  376. json_str = json_match.group(0) if json_match else '{}'
  377. try:
  378. data = json.loads(json_str)
  379. except Exception:
  380. data = {}
  381. return {
  382. "has_sms_modal": bool(data.get("has_sms_modal", True)),
  383. "send_button_state": data.get("send_button_state", "unknown"),
  384. "sent_likely": bool(data.get("sent_likely", False)),
  385. "block_reason": data.get("block_reason", "unknown"),
  386. "suggested_action": data.get("suggested_action", "manual_send"),
  387. "confidence": int(data.get("confidence", 0) or 0),
  388. "notes": data.get("notes", ""),
  389. }
  390. except Exception as e:
  391. return {
  392. "has_sms_modal": True,
  393. "send_button_state": "unknown",
  394. "sent_likely": False,
  395. "block_reason": "unknown",
  396. "suggested_action": "manual_send",
  397. "confidence": 0,
  398. "notes": f"AI 分析异常: {e}",
  399. }
  400. async def sync_cookies_to_node(self, cookies: list) -> bool:
  401. import os
  402. import json
  403. import requests
  404. if not self.user_id or not self.publish_account_id:
  405. return False
  406. async def ai_suggest_playwright_selector(self, goal: str, screenshot_base64: str = None) -> dict:
  407. import os
  408. import requests
  409. import json
  410. import re
  411. try:
  412. if not screenshot_base64:
  413. screenshot_base64 = await self.capture_screenshot()
  414. if not screenshot_base64:
  415. return {"has_selector": False, "selector": "", "confidence": 0, "notes": "无法获取截图"}
  416. ai_api_key = os.environ.get('DASHSCOPE_API_KEY', '')
  417. ai_base_url = os.environ.get('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1')
  418. ai_vision_model = os.environ.get('AI_VISION_MODEL', 'qwen-vl-plus')
  419. if not ai_api_key:
  420. return {"has_selector": False, "selector": "", "confidence": 0, "notes": "未配置 AI API Key"}
  421. prompt = f"""请分析这张网页截图,给出一个 Playwright Python 可用的 selector(用于 page.locator(selector))来完成目标操作。
  422. 目标:{goal}
  423. 要求:
  424. 1) selector 尽量稳定(优先 role/text/aria,其次 class,避免过度依赖随机 class)
  425. 2) selector 必须是 Playwright 支持的选择器语法(如:text="发布"、button:has-text("发布")、[role="button"]:has-text("发布") 等)
  426. 3) 只返回一个最优 selector
  427. 以 JSON 返回:
  428. ```json
  429. {{
  430. "has_selector": true,
  431. "selector": "button:has-text(\\"发布\\")",
  432. "confidence": 0-100,
  433. "notes": "你依据的页面证据"
  434. }}
  435. ```"""
  436. headers = {
  437. 'Authorization': f'Bearer {ai_api_key}',
  438. 'Content-Type': 'application/json'
  439. }
  440. payload = {
  441. "model": ai_vision_model,
  442. "messages": [
  443. {
  444. "role": "user",
  445. "content": [
  446. {
  447. "type": "image_url",
  448. "image_url": {
  449. "url": f"data:image/jpeg;base64,{screenshot_base64}"
  450. }
  451. },
  452. {
  453. "type": "text",
  454. "text": prompt
  455. }
  456. ]
  457. }
  458. ],
  459. "max_tokens": 300
  460. }
  461. response = requests.post(
  462. f"{ai_base_url}/chat/completions",
  463. headers=headers,
  464. json=payload,
  465. timeout=30
  466. )
  467. if response.status_code != 200:
  468. return {"has_selector": False, "selector": "", "confidence": 0, "notes": f"AI API 错误 {response.status_code}"}
  469. result = response.json()
  470. ai_response = result.get('choices', [{}])[0].get('message', {}).get('content', '')
  471. json_match = re.search(r'```json\\s*([\\s\\S]*?)\\s*```', ai_response)
  472. if json_match:
  473. json_str = json_match.group(1)
  474. else:
  475. json_match = re.search(r'\\{[\\s\\S]*\\}', ai_response)
  476. json_str = json_match.group(0) if json_match else '{}'
  477. try:
  478. data = json.loads(json_str)
  479. except Exception:
  480. data = {}
  481. selector = str(data.get("selector", "") or "").strip()
  482. has_selector = bool(data.get("has_selector", False)) and bool(selector)
  483. confidence = int(data.get("confidence", 0) or 0)
  484. notes = str(data.get("notes", "") or "")
  485. if not has_selector:
  486. return {"has_selector": False, "selector": "", "confidence": confidence, "notes": notes or "未给出 selector"}
  487. return {"has_selector": True, "selector": selector, "confidence": confidence, "notes": notes}
  488. except Exception as e:
  489. return {"has_selector": False, "selector": "", "confidence": 0, "notes": f"AI selector 异常: {e}"}
  490. node_api_url = os.environ.get('NODEJS_API_URL', 'http://localhost:3000').rstrip('/')
  491. internal_api_key = os.environ.get('INTERNAL_API_KEY', 'internal-api-key-default')
  492. try:
  493. payload = {
  494. "user_id": int(self.user_id),
  495. "account_id": int(self.publish_account_id),
  496. "cookies": json.dumps(cookies, ensure_ascii=False),
  497. }
  498. resp = requests.post(
  499. f"{node_api_url}/api/internal/accounts/update-cookies",
  500. headers={
  501. "Content-Type": "application/json",
  502. "X-Internal-API-Key": internal_api_key,
  503. },
  504. json=payload,
  505. timeout=30,
  506. )
  507. if resp.status_code >= 400:
  508. return False
  509. data = resp.json() if resp.content else {}
  510. return bool(data.get("success", True))
  511. except Exception:
  512. return False
  513. async def ai_check_captcha(self, screenshot_base64: str = None) -> dict:
  514. """
  515. 使用 AI 分析截图检测验证码
  516. Args:
  517. screenshot_base64: 截图的 Base64 编码,如果为空则自动获取当前页面截图
  518. Returns:
  519. dict: {
  520. "has_captcha": bool, # 是否有验证码
  521. "captcha_type": str, # 验证码类型: slider, image, phone, rotate, puzzle
  522. "captcha_description": str, # 验证码描述
  523. "confidence": float, # 置信度 0-100
  524. "need_headful": bool # 是否需要切换到有头浏览器
  525. }
  526. """
  527. import os
  528. import requests
  529. try:
  530. # 获取截图
  531. if not screenshot_base64:
  532. screenshot_base64 = await self.capture_screenshot()
  533. if not screenshot_base64:
  534. print(f"[{self.platform_name}] AI验证码检测: 无法获取截图")
  535. return {
  536. "has_captcha": False,
  537. "captcha_type": "",
  538. "captcha_description": "",
  539. "confidence": 0,
  540. "need_headful": False
  541. }
  542. # 获取 AI 配置
  543. ai_api_key = os.environ.get('DASHSCOPE_API_KEY', '')
  544. ai_base_url = os.environ.get('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1')
  545. ai_vision_model = os.environ.get('AI_VISION_MODEL', 'qwen-vl-plus')
  546. if not ai_api_key:
  547. print(f"[{self.platform_name}] AI验证码检测: 未配置 AI API Key,使用传统方式检测")
  548. return await self._traditional_captcha_check()
  549. # 构建 AI 请求
  550. prompt = """请分析这张网页截图,判断页面上是否存在验证码。
  551. 请检查以下类型的验证码:
  552. 1. 滑块验证码(需要滑动滑块到指定位置)
  553. 2. 图片验证码(需要选择正确的图片、点击图片上的文字等)
  554. 3. 旋转验证码(需要旋转图片到正确角度)
  555. 4. 拼图验证码(需要拖动拼图块到正确位置)
  556. 5. 手机验证码(需要输入手机收到的验证码)
  557. 6. 计算验证码(需要输入计算结果)
  558. 请以 JSON 格式返回结果:
  559. ```json
  560. {
  561. "has_captcha": true/false,
  562. "captcha_type": "slider/image/phone/rotate/puzzle/calculate/none",
  563. "captcha_description": "验证码的具体描述",
  564. "confidence": 0-100
  565. }
  566. ```
  567. 注意:
  568. - 如果页面有明显的验证码弹窗或验证区域,has_captcha 为 true
  569. - 如果只是普通的登录页面或表单,没有特殊的验证步骤,has_captcha 为 false
  570. - confidence 表示你对判断结果的信心,100 表示非常确定"""
  571. headers = {
  572. 'Authorization': f'Bearer {ai_api_key}',
  573. 'Content-Type': 'application/json'
  574. }
  575. payload = {
  576. "model": ai_vision_model,
  577. "messages": [
  578. {
  579. "role": "user",
  580. "content": [
  581. {
  582. "type": "image_url",
  583. "image_url": {
  584. "url": f"data:image/jpeg;base64,{screenshot_base64}"
  585. }
  586. },
  587. {
  588. "type": "text",
  589. "text": prompt
  590. }
  591. ]
  592. }
  593. ],
  594. "max_tokens": 500
  595. }
  596. print(f"[{self.platform_name}] AI验证码检测: 正在分析截图...")
  597. response = requests.post(
  598. f"{ai_base_url}/chat/completions",
  599. headers=headers,
  600. json=payload,
  601. timeout=30
  602. )
  603. if response.status_code != 200:
  604. print(f"[{self.platform_name}] AI验证码检测: API 返回错误 {response.status_code}")
  605. return await self._traditional_captcha_check()
  606. result = response.json()
  607. ai_response = result.get('choices', [{}])[0].get('message', {}).get('content', '')
  608. print(f"[{self.platform_name}] AI验证码检测响应: {ai_response[:200]}...")
  609. # 解析 AI 响应
  610. import re
  611. json_match = re.search(r'```json\s*([\s\S]*?)\s*```', ai_response)
  612. if json_match:
  613. json_str = json_match.group(1)
  614. else:
  615. # 尝试直接解析
  616. json_match = re.search(r'\{[\s\S]*\}', ai_response)
  617. if json_match:
  618. json_str = json_match.group(0)
  619. else:
  620. json_str = '{}'
  621. try:
  622. ai_result = json.loads(json_str)
  623. except:
  624. ai_result = {}
  625. has_captcha = ai_result.get('has_captcha', False)
  626. captcha_type = ai_result.get('captcha_type', '')
  627. captcha_description = ai_result.get('captcha_description', '')
  628. confidence = ai_result.get('confidence', 0)
  629. # 如果检测到验证码,需要切换到有头浏览器
  630. need_headful = has_captcha and captcha_type not in ['none', '']
  631. print(f"[{self.platform_name}] AI验证码检测结果: has_captcha={has_captcha}, type={captcha_type}, confidence={confidence}")
  632. return {
  633. "has_captcha": has_captcha,
  634. "captcha_type": captcha_type if captcha_type != 'none' else '',
  635. "captcha_description": captcha_description,
  636. "confidence": confidence,
  637. "need_headful": need_headful
  638. }
  639. except Exception as e:
  640. print(f"[{self.platform_name}] AI验证码检测异常: {e}")
  641. import traceback
  642. traceback.print_exc()
  643. return await self._traditional_captcha_check()
  644. async def _traditional_captcha_check(self) -> dict:
  645. """传统方式检测验证码(基于 DOM 元素)"""
  646. if not self.page:
  647. return {
  648. "has_captcha": False,
  649. "captcha_type": "",
  650. "captcha_description": "",
  651. "confidence": 0,
  652. "need_headful": False
  653. }
  654. try:
  655. # 检查常见的验证码选择器
  656. captcha_selectors = [
  657. # 滑块验证码
  658. ('[class*="slider"]', 'slider', '滑块验证码'),
  659. ('[class*="slide-verify"]', 'slider', '滑块验证码'),
  660. ('text="滑动"', 'slider', '滑块验证码'),
  661. ('text="拖动"', 'slider', '滑块验证码'),
  662. # 图片验证码
  663. ('[class*="captcha"]', 'image', '图片验证码'),
  664. ('[class*="verify-img"]', 'image', '图片验证码'),
  665. ('text="点击"', 'image', '图片验证码'),
  666. ('text="选择"', 'image', '图片验证码'),
  667. # 手机验证码
  668. ('text="验证码"', 'phone', '手机验证码'),
  669. ('text="获取验证码"', 'phone', '手机验证码'),
  670. ('[class*="sms-code"]', 'phone', '手机验证码'),
  671. # 旋转验证码
  672. ('text="旋转"', 'rotate', '旋转验证码'),
  673. ('[class*="rotate"]', 'rotate', '旋转验证码'),
  674. ]
  675. for selector, captcha_type, description in captcha_selectors:
  676. try:
  677. count = await self.page.locator(selector).count()
  678. if count > 0:
  679. # 检查是否可见
  680. element = self.page.locator(selector).first
  681. if await element.is_visible():
  682. print(f"[{self.platform_name}] 传统检测: 发现验证码 - {selector}")
  683. return {
  684. "has_captcha": True,
  685. "captcha_type": captcha_type,
  686. "captcha_description": description,
  687. "confidence": 80,
  688. "need_headful": True
  689. }
  690. except:
  691. pass
  692. return {
  693. "has_captcha": False,
  694. "captcha_type": "",
  695. "captcha_description": "",
  696. "confidence": 80,
  697. "need_headful": False
  698. }
  699. except Exception as e:
  700. print(f"[{self.platform_name}] 传统验证码检测异常: {e}")
  701. return {
  702. "has_captcha": False,
  703. "captcha_type": "",
  704. "captcha_description": "",
  705. "confidence": 0,
  706. "need_headful": False
  707. }
  708. async def get_page_url(self) -> str:
  709. """获取当前页面 URL"""
  710. if not self.page:
  711. return ""
  712. try:
  713. return self.page.url
  714. except:
  715. return ""
  716. async def check_publish_status(self) -> dict:
  717. """
  718. 检查发布状态
  719. 返回: {status, screenshot_base64, page_url, message}
  720. """
  721. if not self.page:
  722. return {"status": "error", "message": "页面未初始化"}
  723. try:
  724. screenshot = await self.capture_screenshot()
  725. page_url = await self.get_page_url()
  726. # 检查常见的成功/失败标志
  727. page_content = await self.page.content()
  728. # 检查成功标志
  729. success_keywords = ['发布成功', '上传成功', '发表成功', '提交成功']
  730. for keyword in success_keywords:
  731. if keyword in page_content:
  732. return {
  733. "status": "success",
  734. "screenshot_base64": screenshot,
  735. "page_url": page_url,
  736. "message": "发布成功"
  737. }
  738. # 检查验证码标志
  739. captcha_keywords = ['验证码', '身份验证', '请完成验证', '滑动验证', '图形验证']
  740. for keyword in captcha_keywords:
  741. if keyword in page_content:
  742. return {
  743. "status": "need_captcha",
  744. "screenshot_base64": screenshot,
  745. "page_url": page_url,
  746. "message": f"检测到{keyword}"
  747. }
  748. # 检查失败标志
  749. fail_keywords = ['发布失败', '上传失败', '提交失败', '操作失败']
  750. for keyword in fail_keywords:
  751. if keyword in page_content:
  752. return {
  753. "status": "failed",
  754. "screenshot_base64": screenshot,
  755. "page_url": page_url,
  756. "message": keyword
  757. }
  758. # 默认返回处理中
  759. return {
  760. "status": "processing",
  761. "screenshot_base64": screenshot,
  762. "page_url": page_url,
  763. "message": "处理中"
  764. }
  765. except Exception as e:
  766. return {
  767. "status": "error",
  768. "screenshot_base64": "",
  769. "page_url": "",
  770. "message": str(e)
  771. }
  772. async def wait_for_upload_complete(self, success_selector: str, timeout: int = 300):
  773. """等待上传完成"""
  774. if not self.page:
  775. raise Exception("Page not initialized")
  776. for _ in range(timeout // 3):
  777. try:
  778. count = await self.page.locator(success_selector).count()
  779. if count > 0:
  780. return True
  781. except:
  782. pass
  783. await asyncio.sleep(3)
  784. self.report_progress(30, "正在上传视频...")
  785. return False
  786. @abstractmethod
  787. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  788. """
  789. 发布视频 - 子类必须实现
  790. Args:
  791. cookies: cookie 字符串或 JSON
  792. params: 发布参数
  793. Returns:
  794. PublishResult: 发布结果
  795. """
  796. pass
  797. async def get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  798. """
  799. 获取作品列表 - 子类可覆盖实现
  800. Args:
  801. cookies: cookie 字符串或 JSON
  802. page: 页码(从0开始)
  803. page_size: 每页数量
  804. Returns:
  805. WorksResult: 作品列表结果
  806. """
  807. return WorksResult(
  808. success=False,
  809. platform=self.platform_name,
  810. error="该平台暂不支持获取作品列表"
  811. )
  812. async def get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  813. """
  814. 获取作品评论 - 子类可覆盖实现
  815. Args:
  816. cookies: cookie 字符串或 JSON
  817. work_id: 作品ID
  818. cursor: 分页游标
  819. Returns:
  820. CommentsResult: 评论列表结果
  821. """
  822. return CommentsResult(
  823. success=False,
  824. platform=self.platform_name,
  825. work_id=work_id,
  826. error="该平台暂不支持获取评论"
  827. )
  828. async def run(self, cookies: str, params: PublishParams) -> PublishResult:
  829. """
  830. 运行发布任务
  831. 包装了 publish 方法,添加了异常处理和资源清理
  832. """
  833. try:
  834. return await self.publish(cookies, params)
  835. except Exception as e:
  836. import traceback
  837. traceback.print_exc()
  838. return PublishResult(
  839. success=False,
  840. platform=self.platform_name,
  841. error=str(e)
  842. )
  843. finally:
  844. await self.close_browser()
  845. async def run_get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  846. """
  847. 运行获取作品任务
  848. """
  849. try:
  850. return await self.get_works(cookies, page, page_size)
  851. except Exception as e:
  852. import traceback
  853. traceback.print_exc()
  854. return WorksResult(
  855. success=False,
  856. platform=self.platform_name,
  857. error=str(e)
  858. )
  859. finally:
  860. await self.close_browser()
  861. async def run_get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  862. """
  863. 运行获取评论任务
  864. """
  865. try:
  866. return await self.get_comments(cookies, work_id, cursor)
  867. except Exception as e:
  868. import traceback
  869. traceback.print_exc()
  870. return CommentsResult(
  871. success=False,
  872. platform=self.platform_name,
  873. work_id=work_id,
  874. error=str(e)
  875. )
  876. finally:
  877. await self.close_browser()
  878. async def check_login_status(self, cookies: str) -> dict:
  879. """
  880. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  881. Args:
  882. cookies: cookie 字符串或 JSON
  883. Returns:
  884. dict: {
  885. "success": True,
  886. "valid": True/False,
  887. "need_login": True/False,
  888. "message": "状态描述"
  889. }
  890. """
  891. try:
  892. await self.init_browser()
  893. cookie_list = self.parse_cookies(cookies)
  894. await self.set_cookies(cookie_list)
  895. if not self.page:
  896. raise Exception("Page not initialized")
  897. # 访问平台后台首页
  898. home_url = self.login_url
  899. print(f"[{self.platform_name}] 访问后台页面: {home_url}")
  900. await self.page.goto(home_url, wait_until='domcontentloaded', timeout=30000)
  901. await asyncio.sleep(3)
  902. # 检查当前 URL 是否被重定向到登录页
  903. current_url = self.page.url
  904. print(f"[{self.platform_name}] 当前 URL: {current_url}")
  905. # 登录页特征
  906. login_indicators = ['login', 'passport', 'signin', 'auth']
  907. is_login_page = any(indicator in current_url.lower() for indicator in login_indicators)
  908. # 检查页面是否有登录弹窗
  909. need_login = is_login_page
  910. # 风控/验证码特征
  911. risk_indicators = ['captcha', 'verify', 'challenge', 'risk', 'security', 'safe', 'protect', 'slider']
  912. need_verification = any(indicator in current_url.lower() for indicator in risk_indicators)
  913. if not need_login:
  914. # 检查页面内容是否有登录提示
  915. login_selectors = [
  916. 'text="请先登录"',
  917. 'text="登录后继续"',
  918. 'text="请登录"',
  919. '[class*="login-modal"]',
  920. '[class*="login-dialog"]',
  921. '[class*="login-popup"]',
  922. ]
  923. for selector in login_selectors:
  924. try:
  925. if await self.page.locator(selector).count() > 0:
  926. need_login = True
  927. print(f"[{self.platform_name}] 检测到登录弹窗: {selector}")
  928. break
  929. except:
  930. pass
  931. if not need_login and not need_verification:
  932. verification_selectors = [
  933. 'text="安全验证"',
  934. 'text="验证码"',
  935. 'text="人机验证"',
  936. 'text="滑块"',
  937. 'text="请完成验证"',
  938. 'text="系统检测到异常"',
  939. 'text="访问受限"',
  940. 'text="行为异常"',
  941. ]
  942. for selector in verification_selectors:
  943. try:
  944. if await self.page.locator(selector).count() > 0:
  945. need_verification = True
  946. print(f"[{self.platform_name}] 检测到风控/验证码提示: {selector}")
  947. break
  948. except:
  949. pass
  950. if need_login:
  951. return {
  952. "success": True,
  953. "valid": False,
  954. "need_login": True,
  955. "message": "Cookie 已过期,需要重新登录"
  956. }
  957. elif need_verification:
  958. return {
  959. "success": True,
  960. "valid": False,
  961. "need_login": True,
  962. "message": "触发风控/需要验证"
  963. }
  964. else:
  965. return {
  966. "success": True,
  967. "valid": True,
  968. "need_login": False,
  969. "message": "登录状态有效"
  970. }
  971. except Exception as e:
  972. import traceback
  973. traceback.print_exc()
  974. return {
  975. "success": False,
  976. "valid": False,
  977. "need_login": True,
  978. "error": str(e)
  979. }
  980. finally:
  981. await self.close_browser()