update.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import os
  2. import queue
  3. import shutil
  4. import threading
  5. import time
  6. import requests
  7. from model.custom_struct import GameConfig, UpdateInfo
  8. from net.task_api import task_api
  9. from tools.file_downloader import FileDownloader
  10. from tools.ini_operate import ConfigIni
  11. from tools.log import logger
  12. class Updater:
  13. def __init__(self, script_path, image_path):
  14. self.url = task_api.log_url
  15. self.update_config = self._initialize_update_config()
  16. self.script_path = script_path
  17. self.image_path = image_path
  18. self.lock = threading.Lock()
  19. self.updating_games = {}
  20. self.download_queue = queue.Queue()
  21. def set_updating_status(self, game_id, _type, status):
  22. """设置更新状态。"""
  23. with self.lock:
  24. # 使用 setdefault 初始化 game_id 和 _type
  25. self.updating_games.setdefault(game_id, {}).setdefault(_type, None)
  26. # 更新状态
  27. self.updating_games[game_id][_type] = status
  28. def get_is_updating(self, game_id):
  29. with self.lock:
  30. tmp_dict = self.updating_games.get(game_id, {})
  31. return tmp_dict.get('script') == 1 or tmp_dict.get('image') == 1
  32. @staticmethod
  33. def _initialize_update_config():
  34. """初始化并返回配置文件对象。"""
  35. config_dir = 'config'
  36. os.makedirs(config_dir, exist_ok=True)
  37. return ConfigIni(os.path.join(os.getcwd(), config_dir, 'update.ini'))
  38. def check_updates(self, device_info, game_list):
  39. for game in game_list:
  40. game_info = GameConfig.dict_to_GameConfig(game)
  41. if self.get_is_updating(game_info.task_id): # 检查是否正在更新
  42. return
  43. if device_info.check_script_update == '1':
  44. self._check_script_update(game_info)
  45. if device_info.check_image_update == '1':
  46. self._check_image_update(game_info)
  47. def _check_script_update(self, game_info):
  48. local_script_md5 = self.update_config.get(game_info.task_id, 'script_md5')
  49. url = f'{self.url}/gameTask/downloadFile?taskId={game_info.task_id}&md5String={local_script_md5}'
  50. try:
  51. result = requests.get(url, timeout=10)
  52. if result.status_code == 200:
  53. json_obj = result.json()
  54. if json_obj['code'] == 0 and json_obj['data']['flag']:
  55. remote_md5 = json_obj['data']['md5_string']
  56. download_url = json_obj['data']['url']
  57. update_info = UpdateInfo(
  58. game_id=game_info.task_id,
  59. md5=remote_md5,
  60. download_url=download_url,
  61. file_type='script',
  62. save_path=os.path.join(self.script_path, game_info.script)
  63. )
  64. self.download_queue.put(update_info)
  65. self.set_updating_status(game_info.task_id, 'script', 1) # 标记为正在更新
  66. return True
  67. return False
  68. except Exception as e:
  69. return False
  70. def _check_image_update(self, game_info):
  71. local_image_md5 = self.update_config.get(game_info.task_id, 'image_md5')
  72. url = f'{self.url}/fileManager/getMirrorDownloadByTaskId?task_id={game_info.task_id}'
  73. try:
  74. result = requests.get(url, timeout=10)
  75. if result.status_code == 200:
  76. json_obj = result.json()
  77. if json_obj['code'] == 0:
  78. remote_md5 = json_obj['data']['md5']
  79. if remote_md5 != local_image_md5:
  80. download_url = json_obj['data']['qiniu_address']
  81. update_info = UpdateInfo(
  82. game_id=game_info.task_id,
  83. md5=remote_md5,
  84. download_url=download_url,
  85. file_type='image',
  86. save_path=os.path.join(self.image_path, game_info.image)
  87. )
  88. logger.info(f'检测到 game_id:{update_info.game_id}-{game_info.image}有更新,准备下载')
  89. self.download_queue.put(update_info)
  90. self.set_updating_status(game_info.task_id, 'image', 1) # 标记为正在更新
  91. return True
  92. return False
  93. except Exception as e:
  94. return False
  95. def run(self):
  96. error_count = 0
  97. update_info = None
  98. while True:
  99. try:
  100. if not self.download_queue.empty():
  101. update_info = self.download_queue.get()
  102. if update_info:
  103. downloader = FileDownloader(update_info.download_url, f'{update_info.save_path}.tmp')
  104. if update_info.file_type == 'script':
  105. downloader.download(resume=False)
  106. # 获取当前时间戳(10位整数)
  107. current_timestamp = int(time.time())
  108. # 构建带有时间戳的文件名模式
  109. timestamped_file_name = f"{os.path.splitext(update_info.save_path)[0]}#{current_timestamp}{os.path.splitext(update_info.save_path)[1]}"
  110. shutil.move(f'{update_info.save_path}.tmp', timestamped_file_name)
  111. self.update_config.set(update_info.game_id, 'script_md5', update_info.md5)
  112. self.set_updating_status(update_info.game_id, update_info.file_type, 0)
  113. elif update_info.file_type == 'image':
  114. downloader.download()
  115. shutil.move(f'{update_info.save_path}.tmp', update_info.save_path)
  116. self.update_config.set(update_info.game_id, 'image_md5', update_info.md5)
  117. self.set_updating_status(update_info.game_id, update_info.file_type, 0)
  118. error_count = 0
  119. time.sleep(5)
  120. except Exception as e:
  121. error_count += 1
  122. if error_count == 5:
  123. task_api.notify(f'下载更新连续错误5次,请检查')
  124. logger.exception(f'更新线程异常,错误信息:{e}')
  125. time.sleep(5)
  126. finally:
  127. if update_info:
  128. self.set_updating_status(update_info.game_id, update_info.file_type, 0) # 标记为更新完成