init_load_source.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import asyncio
  2. import json
  3. import time
  4. from settings import DOMAIN as HLM_HOST
  5. import aiohttp
  6. import os
  7. from utils.utils_func import get_md5, get_modified_time, compare_two_times, check_path
  8. from utils.common import message_queue
  9. class init_load_source:
  10. async def load_source(self):
  11. await self.down_resouce()
  12. async def down_resouce(self):
  13. response_data = await self.get_update_file(plugins_name="new_custom_plugins")
  14. if response_data:
  15. for relative_file_path, value in response_data['data'].items():
  16. if "new_custom_plugins" in relative_file_path and os.path.exists("lib") == False:
  17. # print("主目录不存在,不下载")
  18. continue
  19. if (
  20. "new_custom_plugins" in relative_file_path
  21. and os.path.exists("lib")
  22. ):
  23. relative_file_path = relative_file_path.replace(
  24. "new_custom_plugins", "lib/custom_plugins"
  25. )
  26. file_path = f"{os.getcwd()}/{relative_file_path}"
  27. if os.path.exists(file_path):
  28. file_md5 = get_md5(file_path)
  29. if file_md5 != value["file_md5"]:
  30. file_modified_time = get_modified_time(file_path)
  31. if compare_two_times(file_modified_time, response_data["update_time"]) == "left_new":
  32. continue
  33. else:
  34. print(f"md5 不同 开始下载:{file_path}")
  35. await self.async_download_file(value["url"], file_path)
  36. else:
  37. pass
  38. else:
  39. print(f"文件不存在 开始下载:{file_path}")
  40. await self.send_message(f"开始下载:{file_path}")
  41. await self.async_download_file(value["url"], file_path)
  42. else:
  43. print("获取更新文件内容失败")
  44. async def send_message(self, msg):
  45. message = {
  46. 'code': 0,
  47. 'msg_code': 'down_source',
  48. 'message': msg
  49. }
  50. await message_queue.put(json.dumps(message))
  51. async def get_update_file(self, type="client_camera", plugins_name="plugins_A"):
  52. """异步获取指定类型的插件文件更新信息
  53. Args:
  54. type (str, optional): 设备类型标识,默认为"client_camera"
  55. plugins_name (str, optional): 需要查询的插件名称,默认为"plugins_A"
  56. Returns:
  57. dict or None: 成功时返回插件文件的JSON数据,失败或未找到时返回None
  58. """
  59. url = HLM_HOST + "/api/openai/query_client_addons"
  60. params = {"type": type}
  61. try:
  62. async with aiohttp.ClientSession() as session:
  63. # 发送初始请求获取插件列表数据
  64. async with session.get(url, params=params, timeout=10) as response:
  65. response.raise_for_status()
  66. raw_data = await response.json()
  67. if not raw_data or not raw_data.get("data"):
  68. return None
  69. # 从插件列表中查找匹配的插件项
  70. item = next(
  71. (item for item in raw_data["data"]["list"] if item["name"] == plugins_name),
  72. None
  73. )
  74. if item:
  75. # 根据插件项中的URL获取具体文件内容
  76. url = item["url"]
  77. async with session.get(url, timeout=10) as item_response:
  78. item_response.raise_for_status()
  79. return await item_response.json()
  80. return None
  81. except Exception as e:
  82. print(f"An error occurred: {e}")
  83. return None
  84. async def async_download_file(self, url: str, file_path: str):
  85. """异步下载文件"""
  86. async with aiohttp.ClientSession() as session:
  87. async with session.get(url) as response:
  88. root_path, file_name = os.path.split(file_path)
  89. check_path(root_path)
  90. with open(file_path, 'wb') as f:
  91. async for chunk in response.content.iter_chunked(1024):
  92. f.write(chunk)