vs_cloud_api.py 13 KB

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