THIS IS REFACTOR MOTHER FUCKER

This commit is contained in:
def 2023-01-10 04:48:55 +04:00
parent 6f904df4ff
commit 84b42b4950
13 changed files with 128 additions and 51 deletions

2
config.yaml Normal file
View file

@ -0,0 +1,2 @@
matrix_owner_id: "@dettlaff:inex.rocks"
db_path: "data/database.sqlite3"

View file

@ -1,51 +1,25 @@
import asyncio import asyncio
import os import os
import sqlite3
import sys
import aiogram as telegram
import nio as matrix
from matrix import MatrixLoop from matrix import MatrixLoop
from telegram import TelegramLoop from mirrortea.abstract_source_platform.telegram import Telegram
from mirrortea.init_db import ( from config_dataclass import Config
MATRIX_ROOMS_SQL,
TELEGRAM_USER_MATRIX_CHATS_SQL, CONFIG_FILE_NAME = "config.yaml"
TELEGRAM_USERS_SQL,
)
def main(): def main():
config = Config( config = Config.from_yaml_config(CONFIG_FILE_NAME)
db_path=os.environ["DB_PATH"],
matrix_bot_id=os.environ["MATRIX_BOT_ID"],
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER_URL"],
matrix_owner_id=os.environ["MATRIX_OWNER_ID"],
matrix_password=os.environ["MATRIX_PASSWORD"],
telegram_bot_token=os.environ["TELEGRAM_BOT_TOKEN"],
)
asyncio.run(Application(config).run()) asyncio.run(Application(config).run())
class Config:
def __init__(self, **kwargs):
self.db_path = kwargs["db_path"]
self.matrix_bot_id = kwargs["matrix_bot_id"]
self.matrix_homeserver_url = kwargs["matrix_homeserver_url"]
self.matrix_owner_id = kwargs["matrix_owner_id"]
self.matrix_password = kwargs["matrix_password"]
self.telegram_bot_token = kwargs["telegram_bot_token"]
# выглядит ужасно :(
class Application: class Application:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
self.sqlite_adapter = SqliteAdapter(self, config.db_path)
self.matrix_loop = MatrixLoop(self) self.matrix_loop = MatrixLoop(self)
self.telegram_loop = TelegramLoop(self) self.telegram = Telegram(self)
async def run(self): async def run(self):
try: try:
@ -59,23 +33,5 @@ class Application:
await self.matrix_loop.finish() await self.matrix_loop.finish()
class SqliteAdapter:
def __init__(self, app, path):
self.app = app
self.path = path
self.conn = sqlite3.connect(path)
self._create_tables()
def _create_tables(self):
for table in [
TELEGRAM_USER_MATRIX_CHATS_SQL,
TELEGRAM_USERS_SQL,
MATRIX_ROOMS_SQL,
]:
self.conn.execute(table)
self.conn.commit()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -0,0 +1,3 @@
from mirrortea.abstract_source_platform.telegram import Telegram
platforms = [Telegram]

View file

@ -0,0 +1,9 @@
from abc import ABC, abstractmethod
from mirrortea.models.user import User
class AbstractSourcePlatform(ABC):
@abstractmethod
def get_user_information(self) -> User:
"""Init tables in database"""

View file

@ -1,4 +1,13 @@
class TelegramLoop: import sys
import aiogram as telegram
from mirrortea.abstract_source_platform.abstact_source_platform import (
AbstractSourcePlatform,
)
from mirrortea.models.user import User
class Telegram(AbstractSourcePlatform):
def __init__(self, app): def __init__(self, app):
self.app = app self.app = app
self.bot = telegram.Bot(token=app.config.telegram_bot_token) self.bot = telegram.Bot(token=app.config.telegram_bot_token)
@ -10,3 +19,6 @@ class TelegramLoop:
async def on_message(self, msg): async def on_message(self, msg):
print(msg, file=sys.stderr) print(msg, file=sys.stderr)
async def get_user_information(self) -> User:
pass

View file

@ -0,0 +1,32 @@
import os
import yaml
from pathlib import Path
from dataclasses import dataclass
from jinja2 import BaseLoader, Environment
def render_env_template(raw_config: str) -> dict:
template = Environment(loader=BaseLoader).from_string(raw_config)
conf = template.render(**os.environ)
return yaml.safe_load(conf)
@dataclass
class Config:
db_path: Path
matrix_bot_id: str
matrix_homeserver_url: str
matrix_password: str
matrix_owner_id: str
telegram_bot_token: str
@classmethod
def from_dict(config_class, dict):
return config_class(**dict)
@classmethod
def from_yaml_config(config_class, path: Path):
with open(path) as raw:
return config_class.from_dict(render_env_template(raw.read()))

View file

@ -1,3 +1,6 @@
import nio as matrix
class MatrixLoop: class MatrixLoop:
def __init__(self, app): def __init__(self, app):
self.app = app self.app = app

15
mirrortea/models/user.py Normal file
View file

@ -0,0 +1,15 @@
from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
"""
Bridge user from platform source
"""
first_name: str
last_named: Optional[str]
id: str
username: Optional[str]
avatar_hash: Optional[str]

View file

@ -0,0 +1,5 @@
from mirrortea.repository.sqlite_repository import (
SQLiteDatabaseRepository,
)
repository = SQLiteDatabaseRepository()

View file

@ -0,0 +1,7 @@
from abc import ABC, abstractmethod
class AbstractDatabaseRepository(ABC):
@abstractmethod
def create_tables(self) -> None:
"""Init tables in database"""

View file

@ -15,6 +15,7 @@ CREATE TABLE IF NOT EXISTS telegram_users
first_name TEXT NOT NULL (50), first_name TEXT NOT NULL (50),
last_name TEXT (50), last_name TEXT (50),
username TEXT (50), username TEXT (50),
avatar_hash BLOB,
); );
""" """

View file

@ -0,0 +1,31 @@
import sqlite3
from pathlib import Path
from typing import Optional
from mirrortea.repository.abstract_db_repository import AbstractDatabaseRepository
from mirrortea.repository.sqlite_init_tables import (
TELEGRAM_USER_MATRIX_CHATS_SQL,
TELEGRAM_USERS_SQL,
MATRIX_ROOMS_SQL,
)
TABLES_LIST = [
TELEGRAM_USER_MATRIX_CHATS_SQL,
TELEGRAM_USERS_SQL,
MATRIX_ROOMS_SQL,
]
class SQLiteDatabaseRepository(AbstractDatabaseRepository):
def __init__(self, app, path: Path):
self.path = path
self.conn = sqlite3.connect(path)
@staticmethod
def create_tables(self) -> None:
"""Init tables in database"""
for table in TABLES_LIST:
self.conn.execute(table)
self.conn.commit()

View file

@ -1,2 +1,3 @@
aiogram==2.24 aiogram==2.24
matrix-nio==0.20.1 matrix-nio==0.20.1
jinja2