diff --git a/src/mab/bot/_callbacks.py b/src/mab/bot/_callbacks.py index a49f311..255a410 100644 --- a/src/mab/bot/_callbacks.py +++ b/src/mab/bot/_callbacks.py @@ -9,7 +9,7 @@ from nio import MatrixRoom from nio import MatrixInvitedRoom, InviteMemberEvent, JoinResponse from nio.events.room_events import Event as RoomEvent -from ._storage import Storage +from ._database import _Database from ..types import MatrixBotConfig from ..context import EventContext from ..context.vars import ContextVars, ContextVarsPopulator @@ -142,9 +142,9 @@ class Callbacks: # # PUBLIC # - def __init__(self, storage: Storage, matrix_bot: "MatrixBot"): + def __init__(self, db: _Database, matrix_bot: "MatrixBot"): self._logger = logging.getLogger("Callbacks") - self._storage = storage + self._db = db self._matrix_bot = matrix_bot self._context_vars_populator = ContextVarsPopulator() diff --git a/src/mab/bot/_client_auth.py b/src/mab/bot/_client_auth.py index d424531..7895ba2 100644 --- a/src/mab/bot/_client_auth.py +++ b/src/mab/bot/_client_auth.py @@ -2,7 +2,7 @@ import asyncio import aioconsole import logging import os -from ._storage import Storage +from ._database import _Database from ..utils import Utils from ..types import MatrixBotConfig @@ -28,7 +28,7 @@ class ClientAuth: async def _login_using_session_data(self, client: AsyncClient) -> None: """ - Login using session data from `Storage`. + Login using session data from database. Args: - client - client that needs to get logged in @@ -40,14 +40,15 @@ class ClientAuth: if self._full_matrix_username is None: raise RuntimeError("ClientAuth is not set up") self._logger.info("Trying to log in using session data from disk...") - session_data = await self._storage.read_session_data() - if session_data is None: - self._logger.error("Can't read session data from disk") - raise RuntimeError("Can't read session data from disk") + access_token = await self._db.prop_get("access_token") + device_id = await self._db.prop_get("device_id") + if not isinstance(access_token, str) or not isinstance(device_id, str): + self._logger.error("Can't read session data from database") + raise RuntimeError("Can't read session data from database") client.restore_login( user_id=self._full_matrix_username, - access_token=session_data["access_token"], - device_id=session_data["device_id"] + access_token=access_token, + device_id=device_id ) client.load_store() result = await client.whoami() @@ -83,10 +84,8 @@ class ClientAuth: result = await client.login(password=password) if type(result) is LoginResponse: self._logger.info("Logged in using password") - await self._storage.write_session_data( - access_token=result.access_token, - device_id=result.device_id - ) + await self._db.prop_set("access_token", result.access_token) + await self._db.prop_set("device_id", result.device_id) elif type(result) is LoginError: self._logger.error(f"Can't log in using password: '{result.message}'") raise RuntimeError(result.message) @@ -97,9 +96,9 @@ class ClientAuth: # # PUBLIC # - def __init__(self, storage: Storage): + def __init__(self, db: _Database): self._logger = logging.getLogger("ClientAuth") - self._storage = storage + self._db = db self._full_matrix_username: str | None = None self._config: MatrixBotConfig | None = None diff --git a/src/mab/bot/_client_manager.py b/src/mab/bot/_client_manager.py index eabb28e..b6897f3 100644 --- a/src/mab/bot/_client_manager.py +++ b/src/mab/bot/_client_manager.py @@ -7,7 +7,7 @@ from typing import Any from nio import AsyncClient, AsyncClientConfig, SyncResponse from ..types import MatrixBotConfig -from ._storage import Storage +from ._database import _Database from ._client_auth import ClientAuth class ClientManager: @@ -26,7 +26,7 @@ class ClientManager: await self._client.close() self._logger.debug("Dumping 'next_batch' value...") if self._last_next_batch is not None: - await self._storage.write_next_batch(self._last_next_batch) + await self._db.prop_set("next_batch", self._last_next_batch) async def _cancellable_sync_forever(self, *args, **kwargs) -> Any: """ @@ -73,7 +73,7 @@ class ClientManager: self._logger.info("Syncing forever...") await self._cancellable_sync_forever( timeout=self._config.client_sync_period_ms, - since=(await self._storage.read_next_batch()), + since=(await self._db.prop_get("next_batch")), full_state=True ) @@ -90,7 +90,7 @@ class ClientManager: delta_time = current_time - self._last_next_batch_write_time if delta_time >= self._config.client_next_batch_dump_period_s: try: - await self._storage.write_next_batch(self._last_next_batch) + await self._db.prop_set("next_batch", self._last_next_batch) self._last_next_batch_write_time = current_time except: self._logger.error(traceback.format_exc()) @@ -107,10 +107,10 @@ class ClientManager: # # PUBLIC # - def __init__(self, client_auth: ClientAuth, storage: Storage): + def __init__(self, client_auth: ClientAuth, db: _Database): self._logger = logging.getLogger("ClientManager") self._client_auth = client_auth - self._storage = storage + self._db = db self._config: MatrixBotConfig | None = None self._client: AsyncClient | None = None diff --git a/src/mab/bot/_client_uploader.py b/src/mab/bot/_client_uploader.py index 7bded2b..91136e6 100644 --- a/src/mab/bot/_client_uploader.py +++ b/src/mab/bot/_client_uploader.py @@ -11,13 +11,13 @@ from PIL import Image from nio import AsyncClient from nio import UploadError -from ._storage import Storage +from ._database import _Database from ..types import MatrixBotConfig, UploadResult class ClientUploader: """This class uploads files""" - def __init__(self, storage: Storage): - self._storage = storage + def __init__(self, db: _Database): + self._db = db self._config: MatrixBotConfig | None = None self._client: AsyncClient | None = None diff --git a/src/mab/bot/_database.py b/src/mab/bot/_database.py new file mode 100644 index 0000000..19cf68d --- /dev/null +++ b/src/mab/bot/_database.py @@ -0,0 +1,84 @@ +import sqlite3 +import aiosqlite +from typing import Any +from pathlib import Path + +from ..types import MatrixBotConfig + +class _Database: + """Database interface""" + + SCHEMA_VERSION = 1 + """Version of the database schema""" + + async def _create_tables(self) -> None: + """Create tables required for bot operation.""" + if self._conn is None: + raise RuntimeError("No connection exists") + STATEMENTS = ( + ( + "CREATE TABLE IF NOT EXISTS props(" + "name TEXT UNIQUE ON CONFLICT REPLACE," + "value" + ")" + ), + ) + for statement in STATEMENTS: + async with self._conn.execute(statement) as cursor: + await cursor.fetchall() + + def __init__(self): + """Create database object.""" + self._conn: aiosqlite.Connection | None = None + + async def setup(self, config: MatrixBotConfig): + """Setup the database connection.""" + if self._conn is not None: + raise RuntimeError("The connection already exists") + # save config and create path to the database + self._config = config + db_path = self._config.storage_directory + if not isinstance(db_path, Path): + db_path = Path(db_path) + db_path /= "database.sqlite" + # connect to and setup database + self._conn = await aiosqlite.connect(db_path, autocommit=True) + self._conn.row_factory = sqlite3.Row + await self._create_tables() + # get database schema version + last_schema_version = await self.prop_get("schema_version") or self.SCHEMA_VERSION + if not isinstance(last_schema_version, int): + raise RuntimeError("Invalid last_schema_version type") + # find version difference + if self.SCHEMA_VERSION < last_schema_version: + raise RuntimeError("It is forbidden to downgrade `mab` database version") + elif self.SCHEMA_VERSION > last_schema_version: + pass # implement schema updating when needed + # save current schema version + await self.prop_set("schema_version", self.SCHEMA_VERSION) + + async def close(self) -> None: + """Close the database connection.""" + if self._conn is None: + raise RuntimeError("No connection exists") + await self._conn.close() + self._conn = None + + async def prop_get(self, name: str) -> Any | None: + """Gets the value of the property `name` and returns it.""" + if self._conn is None: + raise RuntimeError("No connection exists") + async with self._conn.execute("SELECT value FROM props WHERE name=?", + (name,)) as cursor: + row = await cursor.fetchone() + if row is None: + return None + return row["value"] + + async def prop_set(self, name: str, value: Any) -> None: + """Sets the value of the property `name` to `value`.""" + if self._conn is None: + raise RuntimeError("No connection exists") + async with self._conn.execute("REPLACE INTO props(name, value) VALUES(?, ?)", + (name, value)) as cursor: + await cursor.fetchall() \ No newline at end of file diff --git a/src/mab/bot/_storage.py b/src/mab/bot/_storage.py deleted file mode 100644 index 1d2618a..0000000 --- a/src/mab/bot/_storage.py +++ /dev/null @@ -1,103 +0,0 @@ -from pathlib import Path -import aiofiles -import logging -import json -from typing import Any - -from ..types import MatrixBotConfig - -class Storage: - """This class manages internal storage of the MatrixBot""" - - def __init__(self): - self._logger = logging.getLogger("Storage") - self._config: MatrixBotConfig | None = None - - async def setup(self, config: MatrixBotConfig) -> None: - """ - Setup the internal storage of the MatrixBot. - - Args: - - config - the config to use - - Returns: - - Does not return anything - - Raises an exception on error - """ - self._config = config - - async def write_next_batch(self, next_batch: str) -> None: - """ - Write `next_batch` value to the disk. - - Args: - - next_batch - value to save - - Returns: - - Does not return anything - - Raises an exception on error - """ - if self._config is None: - raise RuntimeError("Storage is not set up") - path = Path(self._config.storage_directory) / "next_batch" - async with aiofiles.open(path, "w") as f: - await f.write(next_batch) - self._logger.debug("next_batch value is written to the disk") - - async def read_next_batch(self) -> str | None: - """ - Read `next_batch` value from the disk. - - Returns: - - Returns `str` if there is `next_batch` value saved on disk - - Returns `None` if `next_batch` was never saved yet - - Raises an exception on error - """ - if self._config is None: - raise RuntimeError("Storage is not set up") - path = Path(self._config.storage_directory) / "next_batch" - if not path.is_file(): - return None - async with aiofiles.open(path, "r") as f: - return (await f.read()).strip() - - async def write_session_data(self, *, access_token: str, device_id: str) -> None: - """ - Write session data to disk. - - Args: - - access_token - access_token to write to the disk - - device_id - device_id to write to disk - - Returns: - - Does not return anything - - Raises an exception on error - """ - if self._config is None: - raise RuntimeError("Storage is not set up") - path = Path(self._config.storage_directory) / "session_data.json" - data = { - "access_token": access_token, - "device_id": device_id - } - async with aiofiles.open(path, "w") as f: - await f.write(json.dumps(data, indent=4)) - self._logger.debug("Session data is writter to the disk") - - async def read_session_data(self) -> dict[str, Any] | None: - """ - Read session data from disk. - - Returns: - - Dictionary with `access_token` and `device_id` keys if these - values were saved using `write_session_data` - - `None` if session data was never saved yet - """ - if self._config is None: - raise RuntimeError("Storage is not set up") - path = Path(self._config.storage_directory) / "session_data.json" - if not path.is_file(): - return None - async with aiofiles.open(path, "r") as f: - j = json.loads(await f.read()) - return j \ No newline at end of file diff --git a/src/mab/bot/bot.py b/src/mab/bot/bot.py index 30cd46d..41e2a8f 100644 --- a/src/mab/bot/bot.py +++ b/src/mab/bot/bot.py @@ -11,7 +11,7 @@ from ..context import EventContext from ..context.vars import ContextVars from ._validation import Validator -from ._storage import Storage +from ._database import _Database from ._client_auth import ClientAuth from ._client_room_operations import ClientRoomOperations from ._client_downloader import ClientDownloader @@ -32,14 +32,14 @@ class MatrixBot: self._was_started = False # create classes that compose MatrixBot self._validator = Validator() - self._storage = Storage() - self._client_auth = ClientAuth(self._storage) - self._client_manager = ClientManager(self._client_auth, self._storage) - self._client_uploader = ClientUploader(self._storage) + self._database = _Database() + self._client_auth = ClientAuth(self._database) + self._client_manager = ClientManager(self._client_auth, self._database) + self._client_uploader = ClientUploader(self._database) self._client_downloader = ClientDownloader() self._client_room_operations = ClientRoomOperations() self._client_sender = ClientSender() - self._callbacks = Callbacks(self._storage, self) + self._callbacks = Callbacks(self._database, self) # validate the config and save it try: self._validator.validate_bot_config(config) @@ -79,7 +79,7 @@ class MatrixBot: raise RuntimeError("The bot was already started") self._was_started = True await self._client_manager.setup(self._config) - await self._storage.setup(self._config) + await self._database.setup(self._config) await self._client_auth.setup(self._config) await self._client_uploader.setup( self._config, @@ -111,6 +111,7 @@ class MatrixBot: bot to completely stop. """ await self._client_manager.stop() + await self._database.close() async def run(self) -> None: """