vs_cloud_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. # toolkit/vs_cloud_api.py
  2. import requests
  3. import json
  4. import time
  5. import urllib.parse
  6. from datetime import datetime
  7. from typing import Dict, Any, Optional
  8. from vs_types import NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  9. from vs_log_macros import VSC_ERROR, VSC_INFO, VSC_WARN, VSC_DEBUG
  10. class VSCloudApi:
  11. """
  12. @brief VSCloudApi 的 Python 实现
  13. 用于对接云端服务 (打码、邮件、Session存储、任务调度)
  14. """
  15. _instance = None
  16. def __new__(cls, *args, **kwargs):
  17. if cls._instance is None:
  18. cls._instance = super(VSCloudApi, cls).__new__(cls)
  19. # 初始化默认配置
  20. cls._instance.base_url = "https://visafly.top"
  21. cls._instance.api_token = "Bearer tok_e946329a60ff45ba807f3f41b0e8b7fc"
  22. cls._instance.session = requests.Session()
  23. return cls._instance
  24. @staticmethod
  25. def Instance():
  26. return VSCloudApi()
  27. def _get_headers(self, content_type: str = "application/json") -> Dict[str, str]:
  28. return {
  29. "Authorization": self.api_token,
  30. "Content-Type": content_type,
  31. "Accept": "application/json, text/plain, */*"
  32. }
  33. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None):
  34. """
  35. 统一 HTTP 请求封装,严格复刻 C++ 逻辑:
  36. 1. 发送 OPTIONS 请求
  37. 2. 发送实际请求
  38. """
  39. resp = self.session.request(method, url, headers=headers, data=data, json=json_data, params=params)
  40. VSC_DEBUG('vs_cloud', f'[perform request] {method} {url} {data} {json_data} {params} {resp.text}')
  41. if resp.status_code == 200:
  42. return resp
  43. elif resp.status_code == 401:
  44. raise SessionExpiredOrInvalidError()
  45. elif resp.status_code == 403:
  46. raise PermissionDeniedError()
  47. elif resp.status_code == 429:
  48. raise RateLimiteddError()
  49. else:
  50. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  51. # =========================================================================
  52. # VAS Task Management (新增 API)
  53. # =========================================================================
  54. def get_vas_task_pop(self, routing_key: str) -> Optional[Dict]:
  55. """
  56. 获取任务信息
  57. API: GET /api/vas/task/pop
  58. """
  59. url = f"{self.base_url}/api/vas/task/pop"
  60. params = {
  61. "queue_name": routing_key,
  62. }
  63. headers = self._get_headers()
  64. resp = self._perform_request('GET', url, params=params, headers=headers)
  65. result = resp.json()
  66. if result.get("code") == 0:
  67. return result.get("data", {})
  68. else:
  69. raise BizLogicError(message=f"Get vas task pop biz error: {result.get('message')}")
  70. def update_vas_task(self,
  71. task_id: int,
  72. update_data: Dict[str, Any]) -> Optional[Dict]:
  73. """
  74. 更新任务
  75. API: POST /api/vas/task/update?id=1
  76. Body: update_data (json)
  77. """
  78. url = f"{self.base_url}/api/vas/task/update"
  79. params = {"id": task_id}
  80. headers = self._get_headers()
  81. resp = self._perform_request('POST', url, params=params, json_data=update_data, headers=headers)
  82. result = resp.json()
  83. if result.get("code") == 0:
  84. return result.get("data", {})
  85. else:
  86. raise BizLogicError(message=f"Update vas task biz error: {result.get('message')}")
  87. def return_vas_task_to_queue(self, task_id: int):
  88. """
  89. 重入队列
  90. API: POST /api/vas/task/return_to_queue?task_id=1
  91. """
  92. url = f"{self.base_url}/api/vas/task/return_to_queue"
  93. params = {"task_id": task_id}
  94. headers = self._get_headers()
  95. resp = self._perform_request('POST', url, params=params, headers=headers)
  96. result = resp.json()
  97. if result.get("code") == 0:
  98. return result.get("data", {})
  99. else:
  100. raise BizLogicError(message=f"Return vas task to queue biz error: {result.get('message')}")
  101. def create_task(self, command: str, args: Dict) -> str:
  102. """
  103. [核心] 创建任务
  104. :param command: 任务指令 (e.g., "AntiCloudflareTurnstileTask", "AntiCloudflareTask")
  105. :param args: 任务参数字典 (e.g., {"proxy": "...", "websiteUrl": "..."})
  106. :return: task_id (直接返回任务ID,方便调用方)
  107. """
  108. url = f"{self.base_url}/api/tasks"
  109. headers = self._get_headers()
  110. payload = {
  111. "command": command,
  112. "args": args,
  113. "status": 0
  114. }
  115. # 发送请求
  116. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  117. result = resp.json()
  118. # 校验业务状态码
  119. if result.get("code") == 0:
  120. data = result.get("data", {})
  121. task_id = data.get("id")
  122. if not task_id:
  123. raise BizLogicError(message=f"Task created but no ID returned. Resp: {data}")
  124. return str(task_id)
  125. else:
  126. raise BizLogicError(message=f"Create task failed ({command}): {result.get('message')}")
  127. def get_task_result(self, task_id: str, timeout: int = 120, interval: int = 3) -> Dict:
  128. """
  129. [核心] 轮询获取任务结果
  130. :param task_id: 任务ID
  131. :param timeout: 最大等待时间(秒)
  132. :param interval: 轮询间隔(秒)
  133. :return: 任务成功后的 data 字典 (包含 token/cookies 等)
  134. """
  135. url = f"{self.base_url}/api/tasks/{task_id}"
  136. headers = self._get_headers()
  137. start_time = time.time()
  138. while True:
  139. # 1. 检查是否超时
  140. if time.time() - start_time > timeout:
  141. raise BizLogicError(message=f"Wait for task result timeout ({timeout}s). TaskID: {task_id}")
  142. try:
  143. # 2. 发起查询
  144. resp = self._perform_request('GET', url, headers=headers)
  145. result = resp.json()
  146. # 3. 校验 API 层面错误
  147. if result.get("code") != 0:
  148. raise BizLogicError(message=f"API Error fetching task: {result.get('message')}")
  149. data = result.get("data", {})
  150. status = data.get("status")
  151. # 4. 判断任务状态
  152. if status == 2: # 成功
  153. return data
  154. elif status == 3: # 失败
  155. error_msg = data.get("result", "Unknown error")
  156. raise BizLogicError(message=f"Task execution failed: {error_msg}")
  157. # status 为 0 (Pending) 或 1 (Running),继续等待
  158. except Exception as e:
  159. # 如果是 BizLogicError 直接抛出,不重试
  160. if isinstance(e, BizLogicError):
  161. raise e
  162. # 网络波动等其他异常,记录日志并重试
  163. VSC_WARN("vs_cloud", f"Polling exception: {str(e)}")
  164. # 等待下次轮询
  165. time.sleep(interval)
  166. def create_http_session(
  167. self,
  168. session_id: str,
  169. cookies: str,
  170. local_storage: str,
  171. user_agent: str,
  172. proxy: str,
  173. page: str
  174. ) -> Optional[Dict]:
  175. """创建 http session"""
  176. url = f"{self.base_url}/api/http-session"
  177. headers = self._get_headers()
  178. payload = {
  179. "local_storage": local_storage,
  180. "cookies": cookies,
  181. "user_agent": user_agent,
  182. "proxy": proxy,
  183. "page": page,
  184. "session_id": session_id
  185. }
  186. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  187. result = resp.json()
  188. if result.get("code") == 0:
  189. return result.get("data", {})
  190. else:
  191. raise BizLogicError(message=f"Create http session biz error: {result.get('message')}")
  192. def slot_refresh_start(
  193. self,
  194. routing_key: str,
  195. country: str = "",
  196. city: str = "",
  197. visa_type: str = "Tourist",
  198. snapshot_source: str = "worker",
  199. ):
  200. url = f"https://visafly.top/api/slot_refresh/start"
  201. payload = {
  202. "routing_key": routing_key,
  203. "country": country,
  204. "city": city,
  205. "visa_type": visa_type,
  206. "snapshot_source": snapshot_source,
  207. }
  208. headers = self._get_headers()
  209. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  210. result = resp.json()
  211. if result.get("code") == 0:
  212. return result.get("data", {})
  213. else:
  214. raise BizLogicError(message=f"Slot refresh start biz error: {result.get('message')}")
  215. def slot_refresh_success(
  216. self,
  217. routing_key: str,
  218. snapshot_source: str = "worker",
  219. ):
  220. url = 'https://visafly.top/api/slot_refresh/success'
  221. payload = {
  222. "routing_key": routing_key,
  223. "snapshot_source": snapshot_source,
  224. }
  225. headers = self._get_headers()
  226. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  227. result = resp.json()
  228. if result.get("code") == 0:
  229. return result.get("data", {})
  230. else:
  231. raise BizLogicError(message=f"Slot refresh success biz error: {result.get('message')}")
  232. def slot_refresh_fail(
  233. self,
  234. routing_key: str,
  235. error: str,
  236. snapshot_source: str = "worker",
  237. ):
  238. url = 'https://visafly.top/api/slot_refresh/fail'
  239. payload = {
  240. "routing_key": routing_key,
  241. "snapshot_source": snapshot_source,
  242. "error": error,
  243. }
  244. headers = self._get_headers()
  245. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  246. result = resp.json()
  247. if result.get("code") == 0:
  248. return result.get("data", {})
  249. else:
  250. raise BizLogicError(message=f"Slot refresh fail biz error: {result.get('message')}")
  251. def get_next_account(
  252. self,
  253. pool_name: str,
  254. lock_duration: float = 60
  255. ):
  256. url = 'https://visafly.top/api/account/next'
  257. params = {
  258. "pool_name": pool_name,
  259. "lock_duration": lock_duration
  260. }
  261. headers = self._get_headers()
  262. resp = self._perform_request('GET', url, headers=headers, params=params)
  263. result = resp.json()
  264. if result.get("code") == 0:
  265. return result.get("data", {})
  266. else:
  267. raise BizLogicError(message=f"Get next account biz error: {result.get('message')}")
  268. def slot_snapshot_report(
  269. self,
  270. query_payload: Dict[str, Any] = {}
  271. ):
  272. url = "https://visafly.top/api/slots/report"
  273. headers = self._get_headers()
  274. resp = self._perform_request("POST", url, headers=headers, json_data=query_payload)
  275. result = resp.json()
  276. if result.get("code") == 0:
  277. return result.get("data", {})
  278. else:
  279. raise BizLogicError(message=f"Slot refresh fail biz error: {result.get('message')}")
  280. def fetch_mail_content(
  281. self,
  282. email: str,
  283. sender: str,
  284. recipient: str,
  285. subject_keywords: str,
  286. body_keywords: str,
  287. sent_date: str,
  288. expiry: int
  289. ) -> Optional[str]:
  290. """
  291. 获取邮件内容
  292. """
  293. params = {
  294. "email": email,
  295. "sender": sender,
  296. "recipient": recipient,
  297. "subjectKeywords": subject_keywords,
  298. "bodyKeywords": body_keywords,
  299. "sentDate": sent_date,
  300. "expiry": str(expiry)
  301. }
  302. url = f"{self.base_url}/api/email-authorizations/fetch"
  303. headers = self._get_headers()
  304. resp = self._perform_request('POST', url, headers=headers, params=params, data="")
  305. result = resp.json()
  306. if result.get('code') == 0:
  307. data = result.get('data', {})
  308. return data.get('body', '')
  309. else:
  310. raise BizLogicError(message=f"Fetch mail content biz error: {result.get('message')}")
  311. def fetch_mail_content_from_top(
  312. self,
  313. email: str,
  314. sender: str,
  315. recipient: str,
  316. subject_keywords: str,
  317. body_keywords: str,
  318. top: int
  319. ) -> Optional[str]:
  320. """从顶部获取邮件内容"""
  321. params = {
  322. "email": email,
  323. "sender": sender,
  324. "recipient": recipient,
  325. "subjectKeywords": subject_keywords,
  326. "bodyKeywords": body_keywords,
  327. "top": str(top)
  328. }
  329. url = f"{self.base_url}/api/email-authorizations/fetch-top"
  330. headers = self._get_headers()
  331. resp = self._perform_request('POST', url, headers=headers, params=params, data="")
  332. result = resp.json()
  333. if result.get('code') == 0:
  334. data = result.get('data', {})
  335. return data.get('body', "")
  336. else:
  337. raise BizLogicError(message=f"Fetch mail content from top biz error: {result.get('message')}")