_local_storage.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. logger = logging.getLogger(__name__)
  17. MAX_FILESIZE = 1024 * 1024 * 5 # 5 MB
  18. MAX_TOTALSIZE = 1024 * 1024 * 100 # 100 MB
  19. class LocalStorage:
  20. """Saves modules to disk and fetches them if remote storage is not available."""
  21. def __init__(self):
  22. self._path = os.path.join(os.path.expanduser("~"), ".hikka", "modules_cache")
  23. self._ensure_dirs()
  24. @property
  25. def _total_size(self) -> int:
  26. return sum(os.path.getsize(f.path) for f in os.scandir(self._path))
  27. def _ensure_dirs(self):
  28. """Ensures that the local storage directory exists."""
  29. if not os.path.isdir(self._path):
  30. os.makedirs(self._path)
  31. def _get_path(self, repo: str, module_name: str) -> str:
  32. return os.path.join(
  33. self._path,
  34. hashlib.sha256(f"{repo}_{module_name}".encode()).hexdigest() + ".py",
  35. )
  36. def save(self, repo: str, module_name: str, module_code: str):
  37. """
  38. Saves module to disk.
  39. :param repo: Repository name.
  40. :param module_name: Module name.
  41. :param module_code: Module source code.
  42. """
  43. size = len(module_code)
  44. if size > MAX_FILESIZE:
  45. logger.warning(
  46. "Module %s from %s is too large (%s bytes) to save to local cache.",
  47. module_name,
  48. repo,
  49. size,
  50. )
  51. return
  52. if self._total_size + size > MAX_TOTALSIZE:
  53. logger.warning(
  54. "Local storage is full, cannot save module %s from %s.",
  55. module_name,
  56. repo,
  57. )
  58. return
  59. with open(self._get_path(repo, module_name), "w") as f:
  60. f.write(module_code)
  61. logger.debug("Saved module %s from %s to local cache.", module_name, repo)
  62. def fetch(self, repo: str, module_name: str) -> typing.Optional[str]:
  63. """
  64. Fetches module from disk.
  65. :param repo: Repository name.
  66. :param module_name: Module name.
  67. :return: Module source code or None.
  68. """
  69. path = self._get_path(repo, module_name)
  70. if os.path.isfile(path):
  71. with open(path, "r") as f:
  72. return f.read()
  73. return None
  74. class RemoteStorage:
  75. def __init__(self, client: CustomTelegramClient):
  76. self._local_storage = LocalStorage()
  77. self._client = client
  78. async def preload(self, urls: typing.List[str]):
  79. """Preloads modules from remote storage."""
  80. logger.debug("Preloading modules from remote storage.")
  81. for url in urls:
  82. logger.debug("Preloading module %s", url)
  83. with contextlib.suppress(Exception):
  84. await self.fetch(url)
  85. await asyncio.sleep(5)
  86. @staticmethod
  87. def _parse_url(url: str) -> typing.Tuple[str, str, str]:
  88. """
  89. Parses a URL into a repository and module name.
  90. :param url: URL to parse.
  91. :return: Tuple of (url, repo, module_name).
  92. """
  93. domain_name = url.split("/")[2]
  94. if domain_name == "raw.githubusercontent.com":
  95. owner, repo, branch = url.split("/")[3:6]
  96. module_name = url.split("/")[-1].split(".")[0]
  97. repo = f"git+{owner}/{repo}:{branch}"
  98. elif domain_name == "github.com":
  99. owner, repo, _, branch = url.split("/")[3:7]
  100. module_name = url.split("/")[-1].split(".")[0]
  101. repo = f"git+{owner}/{repo}:{branch}"
  102. else:
  103. repo, module_name = url.rsplit("/", maxsplit=1)
  104. repo = repo.strip("/")
  105. return url, repo, module_name
  106. async def fetch(self, url: str, auth: typing.Optional[str] = None) -> str:
  107. """
  108. Fetches the module from the remote storage.
  109. :param url: URL to the module.
  110. :param auth: Optional authentication string in the format "username:password".
  111. :return: Module source code.
  112. """
  113. url, repo, module_name = self._parse_url(url)
  114. try:
  115. r = await utils.run_sync(
  116. requests.get,
  117. url,
  118. auth=(tuple(auth.split(":", 1)) if auth else None),
  119. )
  120. r.raise_for_status()
  121. except Exception:
  122. logger.debug(
  123. "Can't load module from remote storage. Trying local storage.",
  124. exc_info=True,
  125. )
  126. if module := self._local_storage.fetch(repo, module_name):
  127. logger.debug("Module source loaded from local storage.")
  128. return module
  129. raise
  130. self._local_storage.save(repo, module_name, r.text)
  131. return r.text