From 9a2a18172c42c866d3cc8d35ea5ed95f5cd9f87a Mon Sep 17 00:00:00 2001 From: Finn Christiansen Date: Sun, 16 Jun 2024 20:57:18 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20=20Add=20basic=20databa?= =?UTF-8?q?se=20support=20using=20SQLAlchemy=20and=20Alembic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 1 + .gitignore | 1 + alembic.ini | 116 ++++++++++++++++++ alembic/README | 1 + alembic/env.py | 83 +++++++++++++ alembic/script.py.mako | 26 ++++ .../12669d9a145b_initial_migration.py | 37 ++++++ matrix_bot_praying_times/__init__.py | 1 + matrix_bot_praying_times/__main__.py | 45 +++++-- matrix_bot_praying_times/db.py | 7 ++ matrix_bot_praying_times/models/__init__.py | 0 matrix_bot_praying_times/models/user.py | 13 ++ requirements.txt | 7 ++ 13 files changed, 325 insertions(+), 13 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/README create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/12669d9a145b_initial_migration.py create mode 100644 matrix_bot_praying_times/db.py create mode 100644 matrix_bot_praying_times/models/__init__.py create mode 100644 matrix_bot_praying_times/models/user.py diff --git a/.env.example b/.env.example index 9060eea..a4969bd 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ HOMESERVER="https://example.org" USERNAME="PrayingTimesBotUsername" PASSWORD="supersecret" +DB_URI="sqlite:///data/database.db" diff --git a/.gitignore b/.gitignore index df4e783..2e12995 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # created by virtualenv automatically bin/ lib/ +include/ __pycache__ pyvenv.cfg .env diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..42c1090 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,116 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..0d79cb1 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,83 @@ +import os +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config +config.set_main_option("sqlalchemy.url", os.getenv("DB_URI")) + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +#target_metadata = None +from matrix_bot_praying_times.db import Base +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..fbc4b07 --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/alembic/versions/12669d9a145b_initial_migration.py b/alembic/versions/12669d9a145b_initial_migration.py new file mode 100644 index 0000000..e3c2f3b --- /dev/null +++ b/alembic/versions/12669d9a145b_initial_migration.py @@ -0,0 +1,37 @@ +"""Initial migration + +Revision ID: 12669d9a145b +Revises: +Create Date: 2024-06-16 20:53:32.463819 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '12669d9a145b' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('user', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('username', sa.String(), nullable=True), + sa.Column('location', sa.String(), nullable=True), + sa.Column('room_id', sa.String(), nullable=True), + sa.Column('reminder_time_in_minutes', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('user') + # ### end Alembic commands ### diff --git a/matrix_bot_praying_times/__init__.py b/matrix_bot_praying_times/__init__.py index e69de29..b829229 100644 --- a/matrix_bot_praying_times/__init__.py +++ b/matrix_bot_praying_times/__init__.py @@ -0,0 +1 @@ +from .models.user import User diff --git a/matrix_bot_praying_times/__main__.py b/matrix_bot_praying_times/__main__.py index c39d3ef..361253d 100644 --- a/matrix_bot_praying_times/__main__.py +++ b/matrix_bot_praying_times/__main__.py @@ -6,6 +6,11 @@ import pytz from typing import Dict import os from dotenv import load_dotenv +from .models.user import User + +from sqlalchemy import create_engine +from sqlalchemy.sql import select +from sqlalchemy.orm import sessionmaker load_dotenv() @@ -20,9 +25,10 @@ bot = botlib.Bot(creds) PREFIX = '!' utc = pytz.UTC -user_locations: dict = {} -user_reminders: dict = {} -user_room_ids: dict = {} +engine = create_engine(os.getenv("DB_URI")) +Session = sessionmaker(bind=engine) +session = Session() + @bot.listener.on_message_event @@ -42,13 +48,15 @@ async def times(room, message) -> None: username = str(message).split(': ')[0] response = "" + user = session.query(User).filter(User.username == username, User.location != "").one_or_none() + if match.is_not_from_this_bot() and match.prefix() and match.command("times"): - if username not in user_locations: + if not user: response = "Please set your location first using *!set-location City, Country*" else: times = get_praying_times(datetime.datetime.today(), username) - response = "Today's praying times for {}:\n\n".format(user_locations[username]) + response = "Today's praying times for {}:\n\n".format(user.location) response += "\n".join("{}: {}".format(key, value) for key, value in times.items()) await bot.api.send_markdown_message(room.room_id, response) @@ -77,7 +85,15 @@ async def set_location(room, message) -> None: if match.is_not_from_this_bot() and match.prefix() and match.command("set-location"): location = " ".join(arg for arg in match.args()) username = str(message).split(': ')[0] - user_locations[username] = location + + user = session.query(User).filter_by(username=username).one_or_none() + if not user: + # create new user + user = User(username=username, location=location) + session.add(user) + user.location = location + session.commit() + response = "Your location was set to: {}".format(location) await bot.api.send_markdown_message(room.room_id, response) @@ -91,13 +107,14 @@ async def set_reminder(room, message) -> None: if match.is_not_from_this_bot() and match.prefix() and match.command("set-reminder"): minutes = int(match.args()[0]) username = str(message).split(': ')[0] + user = session.query(User).filter(User.username == username, User.location != "").one_or_none() - if username not in user_locations: + if not user: response = "You did not set your location yet." await bot.api.send_markdown_message(room.room_id, response) else: - user_reminders[username] = minutes - user_room_ids[username] = room.room_id + user.reminder_time_in_minues = minutes + user.room_id = room.room_id response = "Your reminder was set to {} minutes before praying.".format(minutes) schedule_reminder(username) await bot.api.send_markdown_message(room.room_id, response) @@ -107,15 +124,16 @@ def get_praying_times(date: datetime.date, username) -> Dict[str, str]: day = date.day month = date.month year = date.year - times_api_url = 'http://api.aladhan.com/v1/timingsByAddress/{}-{}-{}?address={}&method=7&iso8601=true'.format(day, month, year, user_locations[username]) + user = session.query(User).filter_by(username=username).one_or_none() + times_api_url = 'http://api.aladhan.com/v1/timingsByAddress/{}-{}-{}?address={}&method=7&iso8601=true'.format(day, month, year, user.location) times = requests.get(times_api_url) times = times.json()['data']['timings'] return times def schedule_reminder(username) -> None: - # TODO: add peristence for reminders now = datetime.datetime.now(datetime.UTC) + user = session.query(User).filter_by(username=username).one_or_none() # as a workaround until it's finished schedule the next 7 days for i in range(7): times = get_praying_times(datetime.date.today() + datetime.timedelta(days=i), username) @@ -124,12 +142,13 @@ def schedule_reminder(username) -> None: if praying_time > now: seconds = int((praying_time - now).total_seconds()) message = "{} is at {}".format(prayer, praying_time.strftime("%H:%M")) - asyncio.ensure_future(remind(username, message, seconds - user_reminders[username] * 60)) + asyncio.ensure_future(remind(username, message, seconds - user.reminder_time_in_minues * 60)) async def remind(username, message, seconds) -> None: await asyncio.sleep(seconds) - await bot.api.send_markdown_message(user_room_ids[username], message) + user = session.query(User).filter_by(username=username).one_or_none() + await bot.api.send_markdown_message(user.room_id, message) bot.run() diff --git a/matrix_bot_praying_times/db.py b/matrix_bot_praying_times/db.py new file mode 100644 index 0000000..ea6f67d --- /dev/null +++ b/matrix_bot_praying_times/db.py @@ -0,0 +1,7 @@ +import os +from sqlalchemy import create_engine +from sqlalchemy.orm import declarative_base +from sqlalchemy.orm import sessionmaker + + +Base = declarative_base() diff --git a/matrix_bot_praying_times/models/__init__.py b/matrix_bot_praying_times/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/matrix_bot_praying_times/models/user.py b/matrix_bot_praying_times/models/user.py new file mode 100644 index 0000000..a7acfdd --- /dev/null +++ b/matrix_bot_praying_times/models/user.py @@ -0,0 +1,13 @@ +from sqlalchemy import Column, String, Integer + +from ..db import Base + + +class User(Base): + __tablename__ = "user" + + id = Column(Integer, primary_key=True) + username = Column(String) + location = Column(String) + room_id = Column(String) + reminder_time_in_minutes = Column(Integer) diff --git a/requirements.txt b/requirements.txt index 59a0a62..23308ca 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,9 @@ +adhanpy==1.0.5 aiofiles==23.2.1 aiohttp==3.9.5 aiohttp-socks==0.8.4 aiosignal==1.3.1 +alembic==1.13.1 async-timeout==4.0.3 attrs==23.2.0 certifi==2024.6.2 @@ -9,6 +11,7 @@ cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.8 frozenlist==1.4.1 +greenlet==3.0.3 h11==0.14.0 h2==4.1.0 hpack==4.0.0 @@ -16,7 +19,9 @@ hyperframe==6.0.1 idna==3.7 jsonschema==4.22.0 jsonschema-specifications==2023.12.1 +Mako==1.3.5 Markdown==3.6 +MarkupSafe==2.1.5 matrix-nio==0.24.0 multidict==6.0.5 pillow==10.3.0 @@ -30,7 +35,9 @@ referencing==0.35.1 requests==2.32.3 rpds-py==0.18.1 simplematrixbotlib==2.11.0 +SQLAlchemy==2.0.30 toml==0.10.2 +typing_extensions==4.12.2 unpaddedbase64==2.1.0 urllib3==2.2.1 yarl==1.9.4