_local_storage.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Saves modules to disk and fetches them if remote storage is not available."""
  2. # ©️ Dan Gazizullin, 2021-2023
  3. # This file is a part of Hikka Userbot
  4. # 🌐 https://github.com/hikariatama/Hikka
  5. # You can redistribute it and/or modify it under the terms of the GNU AGPLv3
  6. # 🔑 https://www.gnu.org/licenses/agpl-3.0.html
  7. import asyncio
  8. import contextlib
  9. import hashlib
  10. import logging
  11. import os
  12. import typing
  13. import requests
  14. from . import utils
  15. from .tl_cache import CustomTelegramClient
  16. from .version import __version__
  17. logger = logging.getLogger(__name__)
  18. MAX_FILESIZE = 1024 * 1024 * 5 # 5 MB
  19. MAX_TOTALSIZE = 1024 * 1024 * 100 # 100 MB
  20. class LocalStorage:
  21. """Saves modules to disk and fetches them if remote storage is not available."""
  22. def __init__(self):
  23. self._path = os.path.join(os.path.expanduser("~"), ".hikka", "modules_cache")
  24. self._ensure_dirs()
  25. @property
  26. def _total_size(self) -> int:
  27. return sum(os.path.getsize(f.path) for f in os.scandir(self._path))
  28. def _ensure_dirs(self):
  29. """Ensures that the local storage directory exists."""
  30. if not os.path.isdir(self._path):
  31. os.makedirs(self._path)
  32. def _get_path(self, repo: str, module_name: str) -> str:
  33. return os.path.join(
  34. self._path,
  35. hashlib.sha256(f"{repo}_{module_name}".encode()).hexdigest() + ".py",
  36. )
  37. def save(self, repo: str, module_name: str, module_code: str):
  38. """
  39. Saves module to disk.
  40. :param repo: Repository name.
  41. :param module_name: Module name.
  42. :param module_code: Module source code.
  43. """
  44. size = len(module_code)
  45. if size > MAX_FILESIZE:
  46. logger.warning(
  47. "Module %s from %s is too large (%s bytes) to save to local cache.",
  48. module_name,
  49. repo,
  50. size,
  51. )
  52. return
  53. if self._total_size + size > MAX_TOTALSIZE:
  54. logger.warning(
  55. "Local storage is full, cannot save module %s from %s.",
  56. module_name,
  57. repo,
  58. )
  59. return
  60. with open(self._get_path(repo, module_name), "w") as f:
  61. f.write(module_code)
  62. logger.debug("Saved module %s from %s to local cache.", module_name, repo)
  63. def fetch(self, repo: str, module_name: str) -> typing.Optional[str]:
  64. """
  65. Fetches module from disk.
  66. :param repo: Repository name.
  67. :param module_name: Module name.
  68. :return: Module source code or None.
  69. """
  70. path = self._get_path(repo, module_name)
  71. if os.path.isfile(path):
  72. with open(path, "r") as f:
  73. return f.read()
  74. return None
  75. class RemoteStorage:
  76. def __init__(self, client: CustomTelegramClient):
  77. self._local_storage = LocalStorage()
  78. self._client = client
  79. async def preload(self, urls: typing.List[str]):
  80. """Preloads modules from remote storage."""
  81. logger.debug("Preloading modules from remote storage.")
  82. for url in urls:
  83. logger.debug("Preloading module %s", url)
  84. with contextlib.suppress(Exception):
  85. await self.fetch(url)
  86. await asyncio.sleep(5)
  87. async def preload_main_repo(self):
  88. """Preloads modules from the main repo."""
  89. mods_info = (
  90. await utils.run_sync(requests.get, "https://mods.hikariatama.ru/mods.json")
  91. ).json()
  92. for name, info in mods_info.items():
  93. _, repo, module_name = self._parse_url(info["link"])
  94. code = self._local_storage.fetch(repo, module_name)
  95. if code:
  96. sha = hashlib.sha256(code.encode()).hexdigest()
  97. if sha != info["sha"]:
  98. logger.debug("Module %s from main repo is outdated.", name)
  99. code = None
  100. else:
  101. logger.debug("Module %s from main repo is up to date.", name)
  102. if not code:
  103. logger.debug("Preloading module %s from main repo.", name)
  104. with contextlib.suppress(Exception):
  105. await self.fetch(info["link"])
  106. await asyncio.sleep(5)
  107. continue
  108. @staticmethod
  109. def _parse_url(url: str) -> typing.Tuple[str, str, str]:
  110. """
  111. Parses a URL into a repository and module name.
  112. :param url: URL to parse.
  113. :return: Tuple of (url, repo, module_name).
  114. """
  115. domain_name = url.split("/")[2]
  116. if domain_name == "raw.githubusercontent.com":
  117. owner, repo, branch = url.split("/")[3:6]
  118. module_name = url.split("/")[-1].split(".")[0]
  119. repo = f"git+{owner}/{repo}:{branch}"
  120. elif domain_name == "github.com":
  121. owner, repo, _, branch = url.split("/")[3:7]
  122. module_name = url.split("/")[-1].split(".")[0]
  123. repo = f"git+{owner}/{repo}:{branch}"
  124. else:
  125. repo, module_name = url.rsplit("/", maxsplit=1)
  126. repo = repo.strip("/")
  127. return url, repo, module_name
  128. async def fetch(self, url: str, auth: typing.Optional[str] = None) -> str:
  129. """
  130. Fetches the module from the remote storage.
  131. :param url: URL to the module.
  132. :param auth: Optional authentication string in the format "username:password".
  133. :return: Module source code.
  134. """
  135. url, repo, module_name = self._parse_url(url)
  136. try:
  137. r = await utils.run_sync(
  138. requests.get,
  139. url,
  140. auth=(tuple(auth.split(":", 1)) if auth else None),
  141. headers={
  142. "User-Agent": "Hikka Userbot",
  143. "X-Hikka-Version": ".".join(map(str, __version__)),
  144. "X-Hikka-Commit-SHA": utils.get_git_hash(),
  145. "X-Hikka-User": str(self._client.tg_id),
  146. },
  147. )
  148. r.raise_for_status()
  149. except Exception:
  150. logger.debug(
  151. "Can't load module from remote storage. Trying local storage.",
  152. exc_info=True,
  153. )
  154. if module := self._local_storage.fetch(repo, module_name):
  155. logger.debug("Module source loaded from local storage.")
  156. return module
  157. raise
  158. self._local_storage.save(repo, module_name, r.text)
  159. return r.text