lock_util.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """
  2. """
  3. import logging
  4. import os
  5. import threading
  6. import time
  7. import api
  8. class LockManager:
  9. """
  10. 全局锁管理,每个手机号只能打开一个上下文相同的浏览器
  11. """
  12. def __init__(self):
  13. self.locks = {}
  14. def acquire_lock(self, key):
  15. if key not in self.locks:
  16. self.locks[key] = threading.Lock()
  17. acquire = self.locks[key].acquire(timeout=300)
  18. if acquire:
  19. logging.info(f"{key} 获取锁成功")
  20. def release_lock(self, key):
  21. if key in self.locks:
  22. self.locks[key].release()
  23. logging.info(f"{key} 释放锁成功")
  24. def is_locked(self, key):
  25. """
  26. 检查给定的键是否处于锁定状态
  27. """
  28. if key in self.locks:
  29. return self.locks[key].locked()
  30. else:
  31. return False
  32. def add_phone(lock_key: str, phones: set):
  33. directory = f"./.data/{lock_key}"
  34. if not os.path.exists(directory):
  35. os.makedirs(directory)
  36. for entry in os.listdir(directory):
  37. # 构建完整的路径
  38. full_path = os.path.join(directory, entry)
  39. # 检查是否是文件夹
  40. if os.path.isdir(full_path):
  41. # 如果是文件夹,将文件夹名称添加到集合中
  42. phones.add(entry)
  43. print(f"已存在的{lock_key}账号:", phones)
  44. lock_manager_dict = {
  45. "huitun": LockManager(),
  46. "xhs": LockManager()
  47. }
  48. lock_phone_dict = {
  49. "huitun": set(),
  50. "xhs": set()
  51. }
  52. for key in lock_phone_dict.keys():
  53. add_phone(key, lock_phone_dict[key])
  54. def get_idle_phone(key: str):
  55. lock_manager = lock_manager_dict[key]
  56. api.assert_not_none(lock_manager, "lock_manager is None")
  57. while True:
  58. for phone in lock_phone_dict[key]:
  59. if not lock_manager.is_locked(phone):
  60. return phone
  61. time.sleep(1)