database.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  2. # █▀█ █ █ █ █▀█ █▀▄ █
  3. # © Copyright 2022
  4. # https://t.me/hikariatama
  5. #
  6. # 🔒 Licensed under the GNU AGPLv3
  7. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  8. import contextlib
  9. import json
  10. import logging
  11. import os
  12. import time
  13. import asyncio
  14. import collections
  15. try:
  16. import psycopg2
  17. except ImportError as e:
  18. if "DYNO" in os.environ:
  19. raise e
  20. try:
  21. import redis
  22. except ImportError as e:
  23. if "DYNO" in os.environ:
  24. raise e
  25. from typing import Any, Union
  26. from telethon.tl.types import Message
  27. from telethon.errors.rpcerrorlist import ChannelsTooMuchError
  28. from . import utils, main
  29. from .pointers import (
  30. PointerList,
  31. PointerDict,
  32. )
  33. DATA_DIR = (
  34. os.path.normpath(os.path.join(utils.get_base_dir(), ".."))
  35. if "OKTETO" not in os.environ and "DOCKER" not in os.environ
  36. else "/data"
  37. )
  38. logger = logging.getLogger(__name__)
  39. class NoAssetsChannel(Exception):
  40. """Raised when trying to read/store asset with no asset channel present"""
  41. class Database(dict):
  42. _next_revision_call = 0
  43. _revisions = []
  44. _assets = None
  45. _me = None
  46. _postgre = None
  47. _redis = None
  48. _saving_task = None
  49. def __init__(self, client):
  50. super().__init__()
  51. self._client = client
  52. def __repr__(self):
  53. return object.__repr__(self)
  54. def _postgre_save_sync(self):
  55. with self._postgre, self._postgre.cursor() as cur:
  56. cur.execute(
  57. "UPDATE hikka SET data = %s WHERE id = %s;",
  58. (json.dumps(self), self._client.tg_id),
  59. )
  60. def _redis_save_sync(self):
  61. with self._redis.pipeline() as pipe:
  62. pipe.set(
  63. str(self._client.tg_id),
  64. json.dumps(self, ensure_ascii=True),
  65. )
  66. pipe.execute()
  67. async def remote_force_save(self) -> bool:
  68. """Force save database to remote endpoint without waiting"""
  69. if not self._postgre and not self._redis:
  70. return False
  71. if self._redis:
  72. await utils.run_sync(self._redis_save_sync)
  73. logger.debug("Published db to Redis")
  74. else:
  75. await utils.run_sync(self._postgre_save_sync)
  76. logger.debug("Published db to PostgreSQL")
  77. return True
  78. async def _postgre_save(self) -> bool:
  79. """Save database to postgresql"""
  80. if not self._postgre:
  81. return False
  82. await asyncio.sleep(5)
  83. await utils.run_sync(self._postgre_save_sync)
  84. logger.debug("Published db to PostgreSQL")
  85. self._saving_task = None
  86. return True
  87. async def _redis_save(self) -> bool:
  88. """Save database to redis"""
  89. if not self._redis:
  90. return False
  91. await asyncio.sleep(5)
  92. await utils.run_sync(self._redis_save_sync)
  93. logger.debug("Published db to Redis")
  94. self._saving_task = None
  95. return True
  96. async def postgre_init(self) -> bool:
  97. """Init postgresql database"""
  98. POSTGRE_URI = os.environ.get("DATABASE_URL") or main.get_config_key(
  99. "postgre_uri"
  100. )
  101. if not POSTGRE_URI:
  102. return False
  103. conn = psycopg2.connect(POSTGRE_URI, sslmode="require")
  104. with conn, conn.cursor() as cur:
  105. cur.execute("CREATE TABLE IF NOT EXISTS hikka (id bigint, data text);")
  106. with contextlib.suppress(Exception):
  107. cur.execute(
  108. "SELECT EXISTS(SELECT 1 FROM hikka WHERE id=%s);",
  109. (self._client.tg_id,),
  110. )
  111. if not cur.fetchone()[0]:
  112. cur.execute(
  113. "INSERT INTO hikka (id, data) VALUES (%s, %s);",
  114. (self._client.tg_id, json.dumps(self)),
  115. )
  116. with contextlib.suppress(Exception):
  117. cur.execute(
  118. "SELECT (column_name, data_type) "
  119. "FROM information_schema.columns "
  120. "WHERE table_name = 'hikka' AND column_name = 'id';"
  121. )
  122. if "integer" in cur.fetchone()[0].lower():
  123. logger.warning(
  124. "Made legacy migration from integer to bigint "
  125. "in postgresql database"
  126. )
  127. cur.execute("ALTER TABLE hikka ALTER COLUMN id TYPE bigint;")
  128. self._postgre = conn
  129. async def redis_init(self) -> bool:
  130. """Init redis database"""
  131. if REDIS_URI := os.environ.get("REDIS_URL") or main.get_config_key("redis_uri"):
  132. self._redis = redis.Redis.from_url(REDIS_URI)
  133. else:
  134. return False
  135. async def init(self):
  136. """Asynchronous initialization unit"""
  137. if os.environ.get("REDIS_URL") or main.get_config_key("redis_uri"):
  138. await self.redis_init()
  139. elif os.environ.get("DATABASE_URL") or main.get_config_key("postgre_uri"):
  140. await self.postgre_init()
  141. self._db_path = os.path.join(DATA_DIR, f"config-{self._client.tg_id}.json")
  142. self.read()
  143. try:
  144. self._assets, _ = await utils.asset_channel(
  145. self._client,
  146. "hikka-assets",
  147. "🌆 Your Hikka assets will be stored here",
  148. archive=True,
  149. avatar="https://raw.githubusercontent.com/hikariatama/assets/master/hikka-assets.png",
  150. )
  151. except ChannelsTooMuchError:
  152. self._assets = None
  153. logger.error(
  154. "Can't find and/or create assets folder\n"
  155. "This may cause several consequences, such as:\n"
  156. "- Non working assets feature (e.g. notes)\n"
  157. "- This error will occur every restart\n\n"
  158. "You can solve this by leaving some channels/groups"
  159. )
  160. def read(self):
  161. """Read database and stores it in self"""
  162. if self._redis:
  163. try:
  164. self.update(
  165. **json.loads(
  166. self._redis.get(
  167. str(self._client.tg_id),
  168. ).decode(),
  169. )
  170. )
  171. except Exception:
  172. logger.exception("Error reading redis database")
  173. return
  174. if self._postgre:
  175. try:
  176. with self._postgre, self._postgre.cursor() as cur:
  177. cur.execute(
  178. "SELECT data FROM hikka WHERE id=%s;",
  179. (self._client.tg_id,),
  180. )
  181. self.update(
  182. **json.loads(
  183. cur.fetchall()[0][0],
  184. ),
  185. )
  186. except Exception:
  187. logger.exception("Error reading postgresql database")
  188. return
  189. try:
  190. with open(self._db_path, "r", encoding="utf-8") as f:
  191. self.update(**json.load(f))
  192. except (FileNotFoundError, json.decoder.JSONDecodeError):
  193. logger.warning("Database read failed! Creating new one...")
  194. def process_db_autofix(self, db: dict) -> bool:
  195. if not utils.is_serializable(db):
  196. return False
  197. for key, value in db.copy().items():
  198. if not isinstance(key, (str, int)):
  199. logger.warning(
  200. f"DbAutoFix: Dropped {key=} , because it is not string or int"
  201. )
  202. continue
  203. if not isinstance(value, dict):
  204. # If value is not a dict (module values), drop it,
  205. # otherwise it may cause problems
  206. del db[key]
  207. logger.warning(
  208. f"DbAutoFix: Dropped {key=}, because it is non-dict {type(value)=}"
  209. )
  210. continue
  211. for subkey in value:
  212. if not isinstance(subkey, (str, int)):
  213. del db[key][subkey]
  214. logger.warning(
  215. f"DbAutoFix: Dropped {subkey=} of db[{key}], because it is not"
  216. " string or int"
  217. )
  218. continue
  219. return True
  220. def save(self) -> bool:
  221. """Save database"""
  222. if not self.process_db_autofix(self):
  223. try:
  224. rev = self._revisions.pop()
  225. while not self.process_db_autofix(rev):
  226. rev = self._revisions.pop()
  227. except IndexError:
  228. raise RuntimeError(
  229. "Can't find revision to restore broken database from "
  230. "database is most likely broken and will lead to problems, "
  231. "so its save is forbidden."
  232. )
  233. self.clear()
  234. self.update(**rev)
  235. raise RuntimeError(
  236. "Rewriting database to the last revision because new one destructed it"
  237. )
  238. if self._next_revision_call < time.time():
  239. self._revisions += [dict(self)]
  240. self._next_revision_call = time.time() + 3
  241. while len(self._revisions) > 15:
  242. self._revisions.pop()
  243. if self._redis:
  244. if not self._saving_task:
  245. self._saving_task = asyncio.ensure_future(self._redis_save())
  246. return True
  247. if self._postgre:
  248. if not self._saving_task:
  249. self._saving_task = asyncio.ensure_future(self._postgre_save())
  250. return True
  251. try:
  252. with open(self._db_path, "w", encoding="utf-8") as f:
  253. json.dump(self, f, indent=4)
  254. except Exception:
  255. logger.exception("Database save failed!")
  256. return False
  257. return True
  258. async def store_asset(self, message: Message) -> int:
  259. """
  260. Save assets
  261. returns asset_id as integer
  262. """
  263. if not self._assets:
  264. raise NoAssetsChannel("Tried to save asset to non-existing asset channel")
  265. return (
  266. (await self._client.send_message(self._assets, message)).id
  267. if isinstance(message, Message)
  268. else (
  269. await self._client.send_message(
  270. self._assets,
  271. file=message,
  272. force_document=True,
  273. )
  274. ).id
  275. )
  276. async def fetch_asset(self, asset_id: int) -> Union[None, Message]:
  277. """Fetch previously saved asset by its asset_id"""
  278. if not self._assets:
  279. raise NoAssetsChannel(
  280. "Tried to fetch asset from non-existing asset channel"
  281. )
  282. asset = await self._client.get_messages(self._assets, ids=[asset_id])
  283. return asset[0] if asset else None
  284. def get(self, owner: str, key: str, default: Any = None) -> Any:
  285. """Get database key"""
  286. try:
  287. return self[owner][key]
  288. except KeyError:
  289. return default
  290. def set(self, owner: str, key: str, value: Any) -> bool:
  291. """Set database key"""
  292. if not utils.is_serializable(owner):
  293. raise RuntimeError(
  294. "Attempted to write object to "
  295. f"{owner=} ({type(owner)=}) of database. It is not "
  296. "JSON-serializable key which will cause errors"
  297. )
  298. if not utils.is_serializable(key):
  299. raise RuntimeError(
  300. "Attempted to write object to "
  301. f"{key=} ({type(key)=}) of database. It is not "
  302. "JSON-serializable key which will cause errors"
  303. )
  304. if not utils.is_serializable(value):
  305. raise RuntimeError(
  306. "Attempted to write object of "
  307. f"{key=} ({type(value)=}) to database. It is not "
  308. "JSON-serializable value which will cause errors"
  309. )
  310. super().setdefault(owner, {})[key] = value
  311. return self.save()
  312. def pointer(self, owner: str, key: str, default: Any = None) -> Any:
  313. """Get a pointer to database key"""
  314. value = self.get(owner, key, default)
  315. mapping = {
  316. list: PointerList,
  317. dict: PointerDict,
  318. collections.abc.Hashable: lambda v: v,
  319. }
  320. pointer_constructor = next(
  321. (pointer for type_, pointer in mapping.items() if isinstance(value, type_)),
  322. None,
  323. )
  324. if pointer_constructor is None:
  325. raise ValueError(
  326. f"Pointer for type {type(value).__name__} is not implemented"
  327. )
  328. return pointer_constructor(self, owner, key, default)