init_load_source.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import asyncio
  2. import json
  3. import time
  4. from settings import 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. class init_load_source:
  9. async def load_source(self):
  10. await self.down_resouce()
  11. async def down_resouce(self):
  12. response_data = await self.get_update_file()
  13. if response_data:
  14. for relative_file_path, value in response_data.items():
  15. file_path = f"{os.getcwd()}/{relative_file_path}"
  16. if os.path.exists(file_path):
  17. file_md5 = get_md5(file_path)
  18. if file_md5 != value["file_md5"]:
  19. print(f"md5 不同 开始下载:{file_path}")
  20. await self.async_download_file(value["url"], file_path)
  21. else:
  22. pass
  23. else:
  24. print(f"文件不存在 开始下载:{file_path}")
  25. await self.async_download_file(value["url"], file_path)
  26. else:
  27. print("获取更新文件内容失败")
  28. async def get_update_file(self, type="client_camera", plugins_name="plugins_A"):
  29. """异步获取指定类型的插件文件更新信息
  30. Args:
  31. type (str, optional): 设备类型标识,默认为"client_camera"
  32. plugins_name (str, optional): 需要查询的插件名称,默认为"plugins_A"
  33. Returns:
  34. dict or None: 成功时返回插件文件的JSON数据,失败或未找到时返回None
  35. """
  36. url = HLM_HOST + "/api/openai/query_client_addons"
  37. params = {"type": type}
  38. try:
  39. async with aiohttp.ClientSession() as session:
  40. # 发送初始请求获取插件列表数据
  41. async with session.get(url, params=params, timeout=10) as response:
  42. response.raise_for_status()
  43. raw_data = await response.json()
  44. if not raw_data or not raw_data.get("data"):
  45. return None
  46. # 从插件列表中查找匹配的插件项
  47. item = next(
  48. (item for item in raw_data["data"]["list"] if item["name"] == plugins_name),
  49. None
  50. )
  51. if item:
  52. # 根据插件项中的URL获取具体文件内容
  53. url = item["url"]
  54. async with session.get(url, timeout=10) as item_response:
  55. item_response.raise_for_status()
  56. return await item_response.json()
  57. return None
  58. except Exception as e:
  59. print(f"An error occurred: {e}")
  60. return None
  61. async def async_download_file(self, url: str, file_path: str):
  62. """异步下载文件"""
  63. async with aiohttp.ClientSession() as session:
  64. async with session.get(url) as response:
  65. root_path, file_name = os.path.split(file_path)
  66. check_path(root_path)
  67. with open(file_path, 'wb') as f:
  68. async for chunk in response.content.iter_chunked(1024):
  69. f.write(chunk)