account_manager.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import threading
  2. import time
  3. import json
  4. import os
  5. import random
  6. from typing import Optional, Dict, Any, List
  7. from vs_log_macros import VSC_DEBUG, VSC_WARN, VSC_INFO, VSC_ERROR
  8. class AccountManager:
  9. """
  10. 账户管理器 (仅本地配置文件模式)
  11. 读取 config/accounts.json
  12. """
  13. _instance = None
  14. _lock = threading.RLock()
  15. def __new__(cls):
  16. with cls._lock:
  17. if cls._instance is None:
  18. cls._instance = super().__new__(cls)
  19. cls._instance._init_data()
  20. return cls._instance
  21. @staticmethod
  22. def Instance():
  23. return AccountManager()
  24. def _init_data(self):
  25. self._accounts: Dict[str, List[Dict]] = {} # pool_name -> [account_dict]
  26. self._account_lock = threading.RLock()
  27. self._config_path = "config/accounts.json"
  28. # 初始化时加载
  29. self.reload_config()
  30. def reload_config(self):
  31. """(重新)加载本地配置文件"""
  32. if not os.path.exists(self._config_path):
  33. VSC_WARN("acc_mgr", f"Config file not found: {self._config_path}. Account pools are empty.")
  34. return
  35. try:
  36. with open(self._config_path, 'r', encoding='utf-8') as f:
  37. data = json.load(f)
  38. count = 0
  39. with self._account_lock:
  40. self._accounts.clear()
  41. for pool_name, acc_list in data.items():
  42. processed_list = []
  43. for acc in acc_list:
  44. # 确保必要字段存在,并初始化状态
  45. if "id" not in acc or "username" not in acc:
  46. continue
  47. acc.setdefault('lock_until', 0)
  48. # bound_data 用于存储绑定的预约人信息,配置文件里可以是 null
  49. acc.setdefault('bound_data', None)
  50. processed_list.append(acc)
  51. count += 1
  52. self._accounts[pool_name] = processed_list
  53. VSC_INFO("acc_mgr", f"Loaded {count} accounts from {self._config_path}")
  54. except json.JSONDecodeError:
  55. VSC_ERROR("acc_mgr", f"Invalid JSON format in {self._config_path}")
  56. except Exception as e:
  57. VSC_ERROR("acc_mgr", f"Failed to load config: {e}")
  58. def next(self, pool_name: str, lock_duration: float = 60.0) -> Optional[Dict[str, Any]]:
  59. """
  60. 获取下一个可用账号 (随机策略),并自动锁定指定时长。
  61. @param pool_name: 账号池名称
  62. @param lock_duration: 锁定时间(秒),默认60秒
  63. @return: 账号信息字典 或 None
  64. """
  65. with self._account_lock:
  66. accounts = self._accounts.get(pool_name, [])
  67. if not accounts:
  68. VSC_WARN("acc_mgr", "No accounts found for pool '%s'", pool_name)
  69. return None
  70. now = time.time()
  71. # 筛选未锁定的账号 (lock_until 必须小于等于当前时间)
  72. available = [acc for acc in accounts if acc.get("lock_until", 0) <= now]
  73. if not available:
  74. VSC_DEBUG("acc_mgr", "Pool '%s' has %d accounts but all are locked.", pool_name, len(accounts))
  75. return None
  76. # 随机选择
  77. selected = random.choice(available)
  78. # === 关键修改:立即更新锁定时间 ===
  79. # 直接修改引用的对象,确保其他线程或其他逻辑能感知到该账号已被占用
  80. selected["lock_until"] = now + lock_duration
  81. VSC_DEBUG("acc_mgr", "Selected account %s (id=%s) from pool %s, locked for %.1fs",
  82. selected.get("username"), selected.get("id"), pool_name, lock_duration)
  83. # 返回账号数据的浅拷贝,防止调用者无意修改 Manager 内部的其他字段
  84. # (虽然 Python dict 是引用传递,但 copy 一下是个好习惯,除非你需要引用修改)
  85. return selected.copy()
  86. def lock(self, pool_name: str, account_id: int, duration_seconds: int):
  87. """
  88. 锁定账号一段时间
  89. """
  90. with self._account_lock:
  91. accounts = self._accounts.get(pool_name, [])
  92. for acc in accounts:
  93. if acc["id"] == account_id:
  94. acc["lock_until"] = time.time() + duration_seconds
  95. VSC_INFO("acc_mgr", "Locked account %s (id=%d) for %ds",
  96. acc.get("username"), account_id, duration_seconds)
  97. return
  98. VSC_WARN("acc_mgr", "Account %d not found in pool %s to lock", account_id, pool_name)
  99. def remove(self, pool_name: str, account_id: int, reason: str = "success", extra_data: dict = None):
  100. """
  101. 从内存中移除账号 (预订成功后不再使用)
  102. 注意:这不会修改磁盘上的 accounts.json 文件,重启程序后账号会恢复
  103. """
  104. with self._account_lock:
  105. accounts = self._accounts.get(pool_name, [])
  106. target_acc = None
  107. for acc in accounts:
  108. if acc["id"] == account_id:
  109. target_acc = acc
  110. break
  111. if target_acc:
  112. accounts.remove(target_acc)
  113. VSC_INFO("acc_mgr", "Removed account %s (id=%d) from memory pool %s. Reason: %s",
  114. target_acc.get("username"), account_id, pool_name, reason)
  115. else:
  116. VSC_WARN("acc_mgr", "Attempt to remove non-existent account %d from pool %s", account_id, pool_name)