Added ability to set log level for bot
This commit is contained in:
@@ -39,7 +39,7 @@ class ClientAuth:
|
|||||||
"""
|
"""
|
||||||
if self._full_matrix_username is None:
|
if self._full_matrix_username is None:
|
||||||
raise RuntimeError("ClientAuth is not set up")
|
raise RuntimeError("ClientAuth is not set up")
|
||||||
self._logger.info("Trying to log in using session data from disk...")
|
self._logger.debug("Trying to log in using session data from disk...")
|
||||||
access_token = await self._db.prop_get("access_token")
|
access_token = await self._db.prop_get("access_token")
|
||||||
device_id = await self._db.prop_get("device_id")
|
device_id = await self._db.prop_get("device_id")
|
||||||
if not isinstance(access_token, str) or not isinstance(device_id, str):
|
if not isinstance(access_token, str) or not isinstance(device_id, str):
|
||||||
@@ -64,7 +64,7 @@ class ClientAuth:
|
|||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"Unknown response for whoami request"
|
"Unknown response for whoami request"
|
||||||
)
|
)
|
||||||
self._logger.info("Logged in using stored session data")
|
self._logger.debug("Logged in using stored session data")
|
||||||
|
|
||||||
async def _login_using_password(self, client: AsyncClient) -> None:
|
async def _login_using_password(self, client: AsyncClient) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -79,11 +79,11 @@ class ClientAuth:
|
|||||||
"""
|
"""
|
||||||
if self._full_matrix_username is None:
|
if self._full_matrix_username is None:
|
||||||
raise RuntimeError("ClientAuth is not set up")
|
raise RuntimeError("ClientAuth is not set up")
|
||||||
self._logger.info("Trying to log in using password")
|
self._logger.debug("Trying to log in using password")
|
||||||
password = await self._default_password_callback()
|
password = await self._default_password_callback()
|
||||||
result = await client.login(password=password)
|
result = await client.login(password=password)
|
||||||
if type(result) is LoginResponse:
|
if type(result) is LoginResponse:
|
||||||
self._logger.info("Logged in using password")
|
self._logger.debug("Logged in using password")
|
||||||
await self._db.prop_set("access_token", result.access_token)
|
await self._db.prop_set("access_token", result.access_token)
|
||||||
await self._db.prop_set("device_id", result.device_id)
|
await self._db.prop_set("device_id", result.device_id)
|
||||||
elif type(result) is LoginError:
|
elif type(result) is LoginError:
|
||||||
@@ -96,8 +96,9 @@ class ClientAuth:
|
|||||||
#
|
#
|
||||||
# PUBLIC
|
# PUBLIC
|
||||||
#
|
#
|
||||||
def __init__(self, db: _Database):
|
def __init__(self, db: _Database, *, log_level = logging.INFO):
|
||||||
self._logger = logging.getLogger("ClientAuth")
|
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
self._db = db
|
self._db = db
|
||||||
self._full_matrix_username: str | None = None
|
self._full_matrix_username: str | None = None
|
||||||
self._config: MatrixBotConfig | None = None
|
self._config: MatrixBotConfig | None = None
|
||||||
@@ -108,6 +109,7 @@ class ClientAuth:
|
|||||||
"""
|
"""
|
||||||
self._config = config
|
self._config = config
|
||||||
self._full_matrix_username = Utils.build_full_matrix_username(config)
|
self._full_matrix_username = Utils.build_full_matrix_username(config)
|
||||||
|
self._logger.debug(f"Using full matrix username `{self._full_matrix_username}`")
|
||||||
|
|
||||||
async def login(self, client: AsyncClient) -> None:
|
async def login(self, client: AsyncClient) -> None:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ class ClientManager:
|
|||||||
if self._client is None:
|
if self._client is None:
|
||||||
raise RuntimeError("Client does not exist")
|
raise RuntimeError("Client does not exist")
|
||||||
# try to login
|
# try to login
|
||||||
self._logger.info("Logging in...")
|
self._logger.debug("Logging in...")
|
||||||
try:
|
try:
|
||||||
await self._client_auth.login(self._client)
|
await self._client_auth.login(self._client)
|
||||||
self._logger.info(f"Logged in as {self._client.user_id}")
|
self._logger.info(f"Logged in as {self._client.user_id}")
|
||||||
@@ -70,7 +70,7 @@ class ClientManager:
|
|||||||
self._logger.error(traceback.format_exc())
|
self._logger.error(traceback.format_exc())
|
||||||
raise
|
raise
|
||||||
# sync forever
|
# sync forever
|
||||||
self._logger.info("Syncing forever...")
|
self._logger.debug("Syncing forever...")
|
||||||
await self._cancellable_sync_forever(
|
await self._cancellable_sync_forever(
|
||||||
timeout=self._config.client_sync_period_ms,
|
timeout=self._config.client_sync_period_ms,
|
||||||
since=(await self._db.prop_get("next_batch")),
|
since=(await self._db.prop_get("next_batch")),
|
||||||
@@ -107,8 +107,9 @@ class ClientManager:
|
|||||||
#
|
#
|
||||||
# PUBLIC
|
# PUBLIC
|
||||||
#
|
#
|
||||||
def __init__(self, client_auth: ClientAuth, db: _Database):
|
def __init__(self, client_auth: ClientAuth, db: _Database, *, log_level = logging.INFO):
|
||||||
self._logger = logging.getLogger("ClientManager")
|
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
self._client_auth = client_auth
|
self._client_auth = client_auth
|
||||||
self._db = db
|
self._db = db
|
||||||
|
|
||||||
@@ -174,7 +175,7 @@ class ClientManager:
|
|||||||
self._background_coroutine()
|
self._background_coroutine()
|
||||||
)
|
)
|
||||||
self._was_started_ever = True
|
self._was_started_ever = True
|
||||||
self._logger.info("Bot background is started")
|
self._logger.debug("Bot background is started")
|
||||||
|
|
||||||
async def stop(self) -> None:
|
async def stop(self) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -201,4 +202,4 @@ class ClientManager:
|
|||||||
except:
|
except:
|
||||||
self._logger.error(traceback.format_exc())
|
self._logger.error(traceback.format_exc())
|
||||||
self._background_task = None
|
self._background_task = None
|
||||||
self._logger.info("Bot background task is stopped")
|
self._logger.debug("Bot background task is stopped")
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
import aiosqlite
|
import aiosqlite
|
||||||
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -29,13 +30,17 @@ class _Database:
|
|||||||
")"
|
")"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
self._logger.debug(f"Creating the tables")
|
||||||
for statement in STATEMENTS:
|
for statement in STATEMENTS:
|
||||||
async with self._conn.execute(statement) as cursor:
|
async with self._conn.execute(statement) as cursor:
|
||||||
await cursor.fetchall()
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Tables are created")
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self, *, log_level = logging.INFO):
|
||||||
"""Create database object."""
|
"""Create database object."""
|
||||||
self._conn: aiosqlite.Connection | None = None
|
self._conn: aiosqlite.Connection | None = None
|
||||||
|
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
|
|
||||||
async def setup(self, config: MatrixBotConfig):
|
async def setup(self, config: MatrixBotConfig):
|
||||||
"""Setup the database connection."""
|
"""Setup the database connection."""
|
||||||
@@ -47,19 +52,24 @@ class _Database:
|
|||||||
if not isinstance(db_path, Path):
|
if not isinstance(db_path, Path):
|
||||||
db_path = Path(db_path)
|
db_path = Path(db_path)
|
||||||
db_path /= "database.sqlite"
|
db_path /= "database.sqlite"
|
||||||
|
self._logger.debug(f"Database path is `{db_path}`")
|
||||||
# connect to and setup database
|
# connect to and setup database
|
||||||
self._conn = await aiosqlite.connect(db_path, autocommit=True)
|
self._conn = await aiosqlite.connect(db_path, autocommit=True)
|
||||||
self._conn.row_factory = sqlite3.Row
|
self._conn.row_factory = sqlite3.Row
|
||||||
|
self._logger.debug(f"Connected to the database")
|
||||||
await self._create_tables()
|
await self._create_tables()
|
||||||
# get database schema version
|
# get database schema version
|
||||||
last_schema_version = await self.prop_get("schema_version") or self.SCHEMA_VERSION
|
last_schema_version = await self.prop_get("schema_version") or self.SCHEMA_VERSION
|
||||||
|
self._logger.debug(f"On-disk database schema version is `{last_schema_version}`")
|
||||||
if not isinstance(last_schema_version, int):
|
if not isinstance(last_schema_version, int):
|
||||||
raise RuntimeError("Invalid last_schema_version type")
|
raise RuntimeError("Invalid last_schema_version type")
|
||||||
# find version difference
|
# find version difference
|
||||||
if self.SCHEMA_VERSION < last_schema_version:
|
if self.SCHEMA_VERSION < last_schema_version:
|
||||||
|
self._logger.critical(f"Database schema downgrade is not supported")
|
||||||
raise RuntimeError("It is forbidden to downgrade `mab` database version")
|
raise RuntimeError("It is forbidden to downgrade `mab` database version")
|
||||||
elif self.SCHEMA_VERSION > last_schema_version:
|
elif self.SCHEMA_VERSION > last_schema_version:
|
||||||
pass # implement schema updating when needed
|
self._logger.info(f"Database schema will be updated to `{self.SCHEMA_VERSION}`")
|
||||||
|
# implement schema updating when needed
|
||||||
# save current schema version
|
# save current schema version
|
||||||
await self.prop_set("schema_version", self.SCHEMA_VERSION)
|
await self.prop_set("schema_version", self.SCHEMA_VERSION)
|
||||||
|
|
||||||
@@ -67,8 +77,10 @@ class _Database:
|
|||||||
"""Close the database connection."""
|
"""Close the database connection."""
|
||||||
if self._conn is None:
|
if self._conn is None:
|
||||||
raise RuntimeError("No connection exists")
|
raise RuntimeError("No connection exists")
|
||||||
|
self._logger.debug(f"Closing database connection")
|
||||||
await self._conn.close()
|
await self._conn.close()
|
||||||
self._conn = None
|
self._conn = None
|
||||||
|
self._logger.debug(f"Database connection is closed")
|
||||||
|
|
||||||
async def prop_get(self, name: str) -> Any | None:
|
async def prop_get(self, name: str) -> Any | None:
|
||||||
"""Gets the value of the property `name` and returns it."""
|
"""Gets the value of the property `name` and returns it."""
|
||||||
@@ -88,6 +100,7 @@ class _Database:
|
|||||||
async with self._conn.execute("REPLACE INTO props(name, value) VALUES(?, ?)",
|
async with self._conn.execute("REPLACE INTO props(name, value) VALUES(?, ?)",
|
||||||
(name, value)) as cursor:
|
(name, value)) as cursor:
|
||||||
await cursor.fetchall()
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Updated property `{name}`")
|
||||||
|
|
||||||
async def join_timestamp_get(self, room_id: str) -> int | None:
|
async def join_timestamp_get(self, room_id: str) -> int | None:
|
||||||
"""Returns the server timestamp when the room was joined (or None)."""
|
"""Returns the server timestamp when the room was joined (or None)."""
|
||||||
@@ -106,6 +119,7 @@ class _Database:
|
|||||||
async with self._conn.execute("REPLACE INTO join_timestamps(room_id, timestamp) VALUES(?, ?)",
|
async with self._conn.execute("REPLACE INTO join_timestamps(room_id, timestamp) VALUES(?, ?)",
|
||||||
(room_id, timestamp)) as cursor:
|
(room_id, timestamp)) as cursor:
|
||||||
await cursor.fetchall()
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Updated join timestamp for room `{room_id}`")
|
||||||
|
|
||||||
async def join_timestamp_remove(self, room_id: str) -> None:
|
async def join_timestamp_remove(self, room_id: str) -> None:
|
||||||
"""Removes the server timestamp when the room was joined."""
|
"""Removes the server timestamp when the room was joined."""
|
||||||
@@ -113,3 +127,4 @@ class _Database:
|
|||||||
raise RuntimeError("No connection exists")
|
raise RuntimeError("No connection exists")
|
||||||
async with self._conn.execute("DELETE FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor:
|
async with self._conn.execute("DELETE FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor:
|
||||||
await cursor.fetchall()
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Removed join timestamp for room `{room_id}`")
|
||||||
@@ -26,15 +26,16 @@ class MatrixBot:
|
|||||||
Asynchronous Matrix Bot Implementation.
|
Asynchronous Matrix Bot Implementation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, config: MatrixBotConfig) -> None:
|
def __init__(self, config: MatrixBotConfig, *, log_level = logging.INFO) -> None:
|
||||||
# create the logger
|
# create the logger
|
||||||
self._logger = logging.getLogger("MatrixBot")
|
self._logger = logging.getLogger(self.__class__.__name__)
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
self._was_started = False
|
self._was_started = False
|
||||||
# create classes that compose MatrixBot
|
# create classes that compose MatrixBot
|
||||||
self._validator = Validator()
|
self._validator = Validator()
|
||||||
self._database = _Database()
|
self._database = _Database(log_level=log_level)
|
||||||
self._client_auth = ClientAuth(self._database)
|
self._client_auth = ClientAuth(self._database, log_level=log_level)
|
||||||
self._client_manager = ClientManager(self._client_auth, self._database)
|
self._client_manager = ClientManager(self._client_auth, self._database, log_level=log_level)
|
||||||
self._client_uploader = ClientUploader(self._database)
|
self._client_uploader = ClientUploader(self._database)
|
||||||
self._client_downloader = ClientDownloader()
|
self._client_downloader = ClientDownloader()
|
||||||
self._client_room_operations = ClientRoomOperations()
|
self._client_room_operations = ClientRoomOperations()
|
||||||
|
|||||||
Reference in New Issue
Block a user