standalone.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import os
  2. import time
  3. import random
  4. import threading
  5. from datetime import datetime
  6. from typing import Dict, Callable, Optional
  7. from vs_types import BookerStandaloneConfig, QueryWaitMode, VSPlgConfig, VSQueryResult, VSBookResult, GroupStatus, PluginStatus, utc_now_str
  8. from vs_plg_factory import VSPlgFactory
  9. from utils.safe_redis_cli import SafeRedisClient
  10. from toolkit.vs_cloud_api import VSCloudApi
  11. from toolkit.thread_pool import ThreadPool
  12. class StandaloneGCO:
  13. """
  14. Standalone GCO 实例管理器。
  15. 遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。
  16. """
  17. TAG = "STANDALONE"
  18. def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
  19. self.m_cfg = cfg
  20. self.m_logger = logger
  21. self.m_factory = VSPlgFactory()
  22. self.m_instance = None
  23. self.m_lock = threading.RLock()
  24. self.m_stop_event = threading.Event()
  25. self.m_last_login_time = 0
  26. self.m_next_query_time = 0
  27. self.m_current_dates = {}
  28. self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
  29. def _log(self, message: str):
  30. prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
  31. if self.m_logger:
  32. self.m_logger(f"{prefix} {message}")
  33. else:
  34. print(f"{prefix} {message}")
  35. def _get_wait_interval(self) -> float:
  36. """根据配置计算下一次查询的等待时间"""
  37. mode = self.m_cfg.query_wait.mode
  38. if mode == QueryWaitMode.Loop:
  39. return 1.0
  40. elif mode == QueryWaitMode.Fixed:
  41. return float(self.m_cfg.query_wait.fixed_wait)
  42. elif mode == QueryWaitMode.Random:
  43. return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
  44. return 30.0
  45. def _is_within_active_hours(self) -> bool:
  46. """判断当前是否在允许创建实例和查询的时间段内"""
  47. start_str = self.m_cfg.active_time_start
  48. end_str = self.m_cfg.active_time_end
  49. current_bj_time = datetime.utcnow().time()
  50. start_time = datetime.strptime(start_str, "%H:%M").time()
  51. end_time = datetime.strptime(end_str, "%H:%M").time()
  52. return start_time <= current_bj_time <= end_time
  53. def update_config(self, new_cfg: BookerStandaloneConfig):
  54. """动态更新配置"""
  55. with self.m_lock:
  56. if self.m_cfg.enable and not new_cfg.enable:
  57. self._log("Config dynamically updated: Group DISABLED.")
  58. elif not self.m_cfg.enable and new_cfg.enable:
  59. self._log("Config dynamically updated: Group ENABLED.")
  60. else:
  61. self._log("Config dynamically updated: Parameters refreshed.")
  62. self.m_cfg = new_cfg
  63. def get_status(self) -> GroupStatus:
  64. with self.m_lock:
  65. instance = self.m_instance
  66. gid = self.m_cfg.identifier
  67. enable = self.m_cfg.enable
  68. plugin_name = self.m_cfg.plugin_config.plugin_name
  69. plugins_status = []
  70. healthy_count = 0
  71. if instance:
  72. st = instance.get_plugin_status()
  73. if st.is_healthy:
  74. healthy_count += 1
  75. plugins_status.append(st)
  76. return GroupStatus(
  77. group_id=gid,
  78. enable=enable,
  79. plugin_name=plugin_name,
  80. total_tasks=1 if instance else 0,
  81. healthy_tasks=healthy_count,
  82. plugins=plugins_status,
  83. updated_at=utc_now_str(),
  84. )
  85. def start(self):
  86. """非阻塞启动,注册插件并开启后台工作线程"""
  87. if not self.m_cfg.enable:
  88. return
  89. self._log("Starting Standalone GCO...")
  90. plugin_name = self.m_cfg.plugin_config.plugin_name
  91. class_name = "".join(part.title() for part in plugin_name.split('_'))
  92. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  93. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  94. worker_name = f"Standalone-{self.m_cfg.identifier}"
  95. threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
  96. def stop(self):
  97. """优雅停止"""
  98. self._log("Stopping Standalone GCO...")
  99. self.m_stop_event.set()
  100. self._cleanup_instance("standalone stopped")
  101. def _cleanup_instance(self, reason: str = ""):
  102. with self.m_lock:
  103. if self.m_instance is not None:
  104. try:
  105. self._log(f"🧹 Cleaned up instance. Reason: {reason}")
  106. self.m_instance.cleanup()
  107. except Exception as e:
  108. self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
  109. finally:
  110. self.m_instance = None
  111. def _notify_date_changes(self, query_result: VSQueryResult):
  112. current_earliest_date = query_result.earliest_date
  113. apt_type = query_result.apt_type
  114. if current_earliest_date:
  115. last_date = self.m_current_dates.get(apt_type.routing_key)
  116. if last_date != current_earliest_date:
  117. self.m_current_dates[apt_type.routing_key] = current_earliest_date
  118. def _push_to_wx():
  119. try:
  120. push_content = (
  121. f"📢【档期变化通知】\n"
  122. f"最早日期: {query_result.earliest_date}\n"
  123. f"目标国家: {apt_type.country}\n"
  124. f"递交城市: {apt_type.city}\n"
  125. f"签证类型: {apt_type.visa_type}\n"
  126. f"Routing: {apt_type.routing_key}"
  127. )
  128. VSCloudApi.Instance().push_weixin_text(push_content)
  129. except Exception as e:
  130. self._log(f"Failed to notify to cloud: {e}")
  131. ThreadPool.getInstance().enqueue(_push_to_wx)
  132. def _notify_book_result(self, book_result: VSBookResult):
  133. if book_result.success:
  134. def _update_cloud_success():
  135. try:
  136. push_content = (
  137. f"🎉 【预定成功通知】\n"
  138. f"━━━━━━━━━━━━━━━\n"
  139. f"预约账号: {book_result.account}\n"
  140. f"预约日期: {book_result.book_date}\n"
  141. f"预约时间: {book_result.book_time}\n"
  142. f"预约编号: {book_result.urn}\n"
  143. f"支付链接: {book_result.payment_link if book_result.payment_link else '无需支付/暂无'}\n"
  144. f"━━━━━━━━━━━━━━━\n"
  145. )
  146. VSCloudApi.Instance().push_weixin_text(push_content)
  147. except Exception as e:
  148. self._log(f"Failed to update success state to cloud: {e}")
  149. ThreadPool.getInstance().enqueue(_update_cloud_success)
  150. def _init_instance(self):
  151. """初始化单实例并进行登录创建会话"""
  152. self._cleanup_instance("recreating new session")
  153. now = time.time()
  154. if now < self.m_last_login_time + self.m_cfg.login_interval:
  155. wait_time = self.m_last_login_time + self.m_cfg.login_interval - now
  156. self._log(f"Waiting {int(wait_time)}s for login interval cooldown...")
  157. if self.m_stop_event.wait(wait_time):
  158. return
  159. plugin_name = self.m_cfg.plugin_config.plugin_name
  160. plg_cfg = VSPlgConfig()
  161. plg_cfg.debug = self.m_cfg.debug
  162. plg_cfg.account = self.m_cfg.account
  163. proxy = VSCloudApi.Instance().get_next_proxy(self.m_cfg.proxy_pool, proxy_cd=600)
  164. plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
  165. plg_cfg.free_config = self.m_cfg.free_config
  166. plg_cfg.session_max_life = self.m_cfg.session_max_life
  167. instance = self.m_factory.create(self.m_cfg.identifier, plugin_name)
  168. instance.set_log(self.m_logger)
  169. instance.set_config(plg_cfg)
  170. with self.m_lock:
  171. self.m_instance = instance
  172. self._log("Creating session...")
  173. try:
  174. instance.create_session()
  175. self.m_last_login_time = time.time()
  176. self.m_next_query_time = time.time() + self._get_wait_interval()
  177. self._log("Session created successfully.")
  178. except Exception:
  179. self._cleanup_instance("session creation failed")
  180. raise
  181. def _worker_loop(self):
  182. """
  183. 后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定
  184. """
  185. self._log("Standalone worker loop started.")
  186. while not self.m_stop_event.is_set():
  187. try:
  188. if not self.m_cfg.enable:
  189. self.m_stop_event.wait(1.0)
  190. continue
  191. if not self._is_within_active_hours():
  192. self.m_stop_event.wait(5.0)
  193. continue
  194. # 1. 会话初始化
  195. if self.m_instance is None:
  196. try:
  197. self._init_instance()
  198. except Exception as e:
  199. self._log(f"Failed to create session: {e}. Retrying in 30s...")
  200. self.m_stop_event.wait(30.0)
  201. continue
  202. # 2. 健康检查
  203. if self.m_instance and not self.m_instance.health_check():
  204. self._log("Health check failed. Session dead. Recreating session...")
  205. self._cleanup_instance("session health check failed")
  206. continue
  207. # 3. 查询等待
  208. now = time.time()
  209. if now < self.m_next_query_time:
  210. wait_sec = min(self.m_next_query_time - now, 1.0)
  211. self.m_stop_event.wait(wait_sec)
  212. continue
  213. # 4. 随机选取 routing_key 进行查询
  214. apt_types = self.m_cfg.appointment_types
  215. if not apt_types:
  216. self.m_stop_event.wait(2.0)
  217. continue
  218. weights = [float(t.weight) for t in apt_types]
  219. apt_type = random.choices(apt_types, weights=weights, k=1)[0]
  220. self._log(f"Querying slots for {apt_type.routing_key}...")
  221. query_result = self.m_instance.query(apt_type)
  222. query_result.apt_type = apt_type
  223. self.m_next_query_time = time.time() + self._get_wait_interval()
  224. self._notify_date_changes(query_result)
  225. # 5. 发现档期,执行自动预定
  226. if query_result.success:
  227. self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
  228. book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
  229. self._notify_book_result(book_result)
  230. if book_result.success:
  231. self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
  232. # 预定成功后可继续或等待后续任务
  233. self.m_stop_event.wait(5.0)
  234. except Exception as e:
  235. self._log(f"Standalone loop exception: {e}")
  236. self.m_stop_event.wait(2.0)