vs_cloud_api.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 get_vas_task(self, task_id: str) -> dict:
  71. # 例如:请求 GET /api/v1/tasks/{task_id}
  72. # curl -X 'GET' \
  73. # 'http://45.137.220.138:8888/api/vas/task/get_by_order?order_id=ORD-20260306212306-7e604df8' \
  74. # -H 'accept: application/json' \
  75. # -H 'Authorization: Bearer tok_c9be86aa78274939a3c008db31ce9d22'
  76. url = f"{self.base_url}/api/vas/task/detail"
  77. params = {"task_id": task_id}
  78. headers = self._get_headers()
  79. resp = self._perform_request('GET', url, params=params, headers=headers)
  80. result = resp.json()
  81. if result.get("code") == 0:
  82. return result.get("data", {})
  83. else:
  84. raise BizLogicError(message=f"Get Task={task_id} error: {result.get('message')}")
  85. def update_vas_task(self,
  86. task_id: int,
  87. update_data: Dict[str, Any]) -> Optional[Dict]:
  88. """
  89. 更新任务
  90. API: POST /api/vas/task/update?id=1
  91. Body: update_data (json)
  92. """
  93. url = f"{self.base_url}/api/vas/task/update"
  94. params = {"id": task_id}
  95. headers = self._get_headers()
  96. resp = self._perform_request('POST', url, params=params, json_data=update_data, headers=headers)
  97. result = resp.json()
  98. if result.get("code") == 0:
  99. return result.get("data", {})
  100. else:
  101. raise BizLogicError(message=f"Update vas task biz error: {result.get('message')}")
  102. def return_vas_task_to_queue(self, task_id: int):
  103. """
  104. 重入队列
  105. API: POST /api/vas/task/return_to_queue?task_id=1
  106. """
  107. url = f"{self.base_url}/api/vas/task/return_to_queue"
  108. params = {"task_id": task_id}
  109. headers = self._get_headers()
  110. resp = self._perform_request('POST', url, params=params, headers=headers)
  111. result = resp.json()
  112. if result.get("code") == 0:
  113. return result.get("data", {})
  114. else:
  115. raise BizLogicError(message=f"Return vas task to queue biz error: {result.get('message')}")
  116. def create_task(self, command: str, args: Dict) -> str:
  117. """
  118. [核心] 创建任务
  119. :param command: 任务指令 (e.g., "AntiCloudflareTurnstileTask", "AntiCloudflareTask")
  120. :param args: 任务参数字典 (e.g., {"proxy": "...", "websiteUrl": "..."})
  121. :return: task_id (直接返回任务ID,方便调用方)
  122. """
  123. url = f"{self.base_url}/api/tasks"
  124. headers = self._get_headers()
  125. payload = {
  126. "command": command,
  127. "args": args,
  128. "status": 0
  129. }
  130. # 发送请求
  131. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  132. result = resp.json()
  133. # 校验业务状态码
  134. if result.get("code") == 0:
  135. data = result.get("data", {})
  136. task_id = data.get("id")
  137. if not task_id:
  138. raise BizLogicError(message=f"Task created but no ID returned. Resp: {data}")
  139. return str(task_id)
  140. else:
  141. raise BizLogicError(message=f"Create task failed ({command}): {result.get('message')}")
  142. def get_task_result(self, task_id: str, timeout: int = 120, interval: int = 3) -> Dict:
  143. """
  144. [核心] 轮询获取任务结果
  145. :param task_id: 任务ID
  146. :param timeout: 最大等待时间(秒)
  147. :param interval: 轮询间隔(秒)
  148. :return: 任务成功后的 data 字典 (包含 token/cookies 等)
  149. """
  150. url = f"{self.base_url}/api/tasks/{task_id}"
  151. headers = self._get_headers()
  152. start_time = time.time()
  153. while True:
  154. # 1. 检查是否超时
  155. if time.time() - start_time > timeout:
  156. raise BizLogicError(message=f"Wait for task result timeout ({timeout}s). TaskID: {task_id}")
  157. try:
  158. # 2. 发起查询
  159. resp = self._perform_request('GET', url, headers=headers)
  160. result = resp.json()
  161. # 3. 校验 API 层面错误
  162. if result.get("code") != 0:
  163. raise BizLogicError(message=f"API Error fetching task: {result.get('message')}")
  164. data = result.get("data", {})
  165. status = data.get("status")
  166. # 4. 判断任务状态
  167. if status == 2: # 成功
  168. return data
  169. elif status == 3: # 失败
  170. error_msg = data.get("result", "Unknown error")
  171. raise BizLogicError(message=f"Task execution failed: {error_msg}")
  172. # status 为 0 (Pending) 或 1 (Running),继续等待
  173. except Exception as e:
  174. # 如果是 BizLogicError 直接抛出,不重试
  175. if isinstance(e, BizLogicError):
  176. raise e
  177. # 网络波动等其他异常,记录日志并重试
  178. VSC_WARN("vs_cloud", f"Polling exception: {str(e)}")
  179. # 等待下次轮询
  180. time.sleep(interval)
  181. def create_http_session(
  182. self,
  183. session_id: str,
  184. cookies: str,
  185. local_storage: str,
  186. user_agent: str,
  187. proxy: str,
  188. page: str
  189. ) -> Optional[Dict]:
  190. """创建 http session"""
  191. url = f"{self.base_url}/api/http-session"
  192. headers = self._get_headers()
  193. payload = {
  194. "local_storage": local_storage,
  195. "cookies": cookies,
  196. "user_agent": user_agent,
  197. "proxy": proxy,
  198. "page": page,
  199. "session_id": session_id
  200. }
  201. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  202. result = resp.json()
  203. if result.get("code") == 0:
  204. return result.get("data", {})
  205. else:
  206. raise BizLogicError(message=f"Create http session biz error: {result.get('message')}")
  207. def slot_refresh_start(
  208. self,
  209. routing_key: str,
  210. country: str = "",
  211. city: str = "",
  212. visa_type: str = "Tourist",
  213. snapshot_source: str = "worker",
  214. ):
  215. url = f"https://visafly.top/api/slot_refresh/start"
  216. payload = {
  217. "routing_key": routing_key,
  218. "country": country,
  219. "city": city,
  220. "visa_type": visa_type,
  221. "snapshot_source": snapshot_source,
  222. }
  223. headers = self._get_headers()
  224. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  225. result = resp.json()
  226. if result.get("code") == 0:
  227. return result.get("data", {})
  228. else:
  229. raise BizLogicError(message=f"Slot refresh start biz error: {result.get('message')}")
  230. def slot_refresh_success(
  231. self,
  232. routing_key: str,
  233. snapshot_source: str = "worker",
  234. ):
  235. url = 'https://visafly.top/api/slot_refresh/success'
  236. payload = {
  237. "routing_key": routing_key,
  238. "snapshot_source": snapshot_source,
  239. }
  240. headers = self._get_headers()
  241. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  242. result = resp.json()
  243. if result.get("code") == 0:
  244. return result.get("data", {})
  245. else:
  246. raise BizLogicError(message=f"Slot refresh success biz error: {result.get('message')}")
  247. def slot_refresh_fail(
  248. self,
  249. routing_key: str,
  250. error: str,
  251. snapshot_source: str = "worker",
  252. ):
  253. url = 'https://visafly.top/api/slot_refresh/fail'
  254. payload = {
  255. "routing_key": routing_key,
  256. "snapshot_source": snapshot_source,
  257. "error": error,
  258. }
  259. headers = self._get_headers()
  260. resp = self._perform_request('POST', url, headers=headers, json_data=payload)
  261. result = resp.json()
  262. if result.get("code") == 0:
  263. return result.get("data", {})
  264. else:
  265. raise BizLogicError(message=f"Slot refresh fail biz error: {result.get('message')}")
  266. def get_next_account(
  267. self,
  268. pool_name: str,
  269. lock_duration: float = 60
  270. ):
  271. url = 'https://visafly.top/api/account/next'
  272. params = {
  273. "pool_name": pool_name,
  274. "lock_duration": lock_duration
  275. }
  276. headers = self._get_headers()
  277. resp = self._perform_request('GET', url, headers=headers, params=params)
  278. result = resp.json()
  279. if result.get("code") == 0:
  280. return result.get("data", {})
  281. else:
  282. raise BizLogicError(message=f"Get next account biz error: {result.get('message')}")
  283. def slot_snapshot_report(
  284. self,
  285. query_payload: Dict[str, Any] = {}
  286. ):
  287. url = "https://visafly.top/api/slots/report"
  288. headers = self._get_headers()
  289. resp = self._perform_request("POST", url, headers=headers, json_data=query_payload)
  290. result = resp.json()
  291. if result.get("code") == 0:
  292. return result.get("data", {})
  293. else:
  294. raise BizLogicError(message=f"Slot refresh fail biz error: {result.get('message')}")
  295. def fetch_mail_content(
  296. self,
  297. email: str,
  298. sender: str,
  299. recipient: str,
  300. subject_keywords: str,
  301. body_keywords: str,
  302. sent_date: str,
  303. expiry: int
  304. ) -> Optional[str]:
  305. """
  306. 获取邮件内容
  307. """
  308. params = {
  309. "email": email,
  310. "sender": sender,
  311. "recipient": recipient,
  312. "subjectKeywords": subject_keywords,
  313. "bodyKeywords": body_keywords,
  314. "sentDate": sent_date,
  315. "expiry": str(expiry)
  316. }
  317. url = f"{self.base_url}/api/email-authorizations/fetch"
  318. headers = self._get_headers()
  319. resp = self._perform_request('POST', url, headers=headers, params=params, data="")
  320. result = resp.json()
  321. if result.get('code') == 0:
  322. data = result.get('data', {})
  323. return data.get('body', '')
  324. else:
  325. raise BizLogicError(message=f"Fetch mail content biz error: {result.get('message')}")
  326. def fetch_mail_content_from_top(
  327. self,
  328. email: str,
  329. sender: str,
  330. recipient: str,
  331. subject_keywords: str,
  332. body_keywords: str,
  333. top: int
  334. ) -> Optional[str]:
  335. """从顶部获取邮件内容"""
  336. params = {
  337. "email": email,
  338. "sender": sender,
  339. "recipient": recipient,
  340. "subjectKeywords": subject_keywords,
  341. "bodyKeywords": body_keywords,
  342. "top": str(top)
  343. }
  344. url = f"{self.base_url}/api/email-authorizations/fetch-top"
  345. headers = self._get_headers()
  346. resp = self._perform_request('POST', url, headers=headers, params=params, data="")
  347. result = resp.json()
  348. if result.get('code') == 0:
  349. data = result.get('data', {})
  350. return data.get('body', "")
  351. else:
  352. raise BizLogicError(message=f"Fetch mail content from top biz error: {result.get('message')}")