Compare commits

..

12 Commits

13 changed files with 638 additions and 3 deletions

View File

@ -2,6 +2,41 @@
An approach to having kids use a Kodi media center instance: manage session use and keep track of time spent and available budget.
## Getting started
1. Set up a MySQL database by whatever means you prefer. This step is outside the scope of this *getting started* guide.
* In your MySQL daemon create one database and a user with all grants except for the `GRANT` grant on that database, here with account `kodi-timekeeper` as an example on a MySQL 5.7.22 daemon:
```
# Create account
CREATE USER 'kodi-timekeeper'@'localhost' IDENTIFIED WITH 'mysql_native_password' AS '*hash' REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK;
# Grants for kodi-timekeeper@localhost
GRANT USAGE ON *.* TO 'kodi-timekeeper'@'localhost';
GRANT ALL PRIVILEGES ON `kodi-timekeeper`.* TO 'kodi-timekeeper'@'localhost';
```
Here `hash` is the hashed account password. To compute it yourself head into your MySQL daemon and execute the query:
```
SELECT CONCAT('*', UPPER(SHA1(UNHEX(SHA1('topsecret')))));
```
The result of which will be something like:
```
*6C47D9CD3A183D230B04FE7F38D7D313E2B4B5AE
```
Which is the hash representation of password `topsecret`. This query-hash mechanism comes courtesy of René Cannaò formerly of Pythian Services Inc. in his 2011 [article "Hashing Algorithm in MySQL PASSWORD()" at blog.pythian.com](https://blog.pythian.com/hashing-algorithm-in-mysql-password-2/).
2. On your operating system make sure the `mysql_config` binary exists. On a Debian or a derivative distribution that typically involves `sudo apt-get install default-libmysqlclient-dev`.
3. `git clone` this repo
4. Install requirements via `pip install -r requirements.txt`
5. Export the following shell environment variables as needed. The next step will use these variables to connect to your database and create tables. Values below are defaults so if you want to stick to a default feel free to simply not export the variable.
```
export DB_DIALECTDRIVER='mysql'
export DB_USER='kodi-timekeeper'
export DB_PASSWORD='-kodi-timekeeper'
export DB_HOST='localhost'
export DB_NAME='kodi-timekeeper'
```
6. Navigate into the repository's `db` subdirectory
7. Initialize your database: `alembic upgrade head`
## Valid Conventional Commits scopes
* `meta`: Affects the Git project's structure such as for example a `pyproject.toml` change, adding a new directory or changing how a news fragment file is formatted
@ -11,4 +46,9 @@ An approach to having kids use a Kodi media center instance: manage session use
```
```
build(meta): Set custom towncrier news topics
```
* `db`: Affects database connectivity features, for example being able to migrate database versions or installing an empty database
* Examples:
```
feat(db): Add requirements for database work
```

1
db/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration.

102
db/alembic.ini Normal file
View File

@ -0,0 +1,102 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = .
# template used to generate migration files
# file_template = %%(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-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# 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 ./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:./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.
# 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
# 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

95
db/env.py Normal file
View File

@ -0,0 +1,95 @@
import os
from logging.config import fileConfig
# #3 Get connection string from env vars instead of a Git-committed env.py
# http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/
# from sqlalchemy import engine_from_config
from sqlalchemy import engine_from_config, create_engine
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
# 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
# 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 get_url():
# #3 Get connection string from env vars instead of a Git-committed env.py
# http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/
return "%s://%s:%s@%s/%s" % (
os.getenv("DB_DIALECTDRIVER", "mysql"),
os.getenv("DB_USER", "kodi-timekeeper"),
os.getenv("DB_PASSWORD", "kodi-timekeeper"),
os.getenv("DB_HOST", "localhost"),
os.getenv("DB_NAME", "kodi-timekeeper"),
)
def run_migrations_offline():
"""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.
"""
# #3 Get connection string from env vars instead of a Git-committed env.py
# http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/
# url = config.get_main_option("sqlalchemy.url")
url = get_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():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# #3 Get connection string from env vars instead of a Git-committed env.py
# http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/
connectable = create_engine(get_url())
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()

24
db/script.py.mako Normal file
View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,100 @@
"""Rename tables, columns to be more descriptive
Revision ID: 2da14bfaeaa1
Revises: 954ded90cc97
Create Date: 2022-05-05 02:36:43.563735
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2da14bfaeaa1'
down_revision = '954ded90cc97'
branch_labels = None
depends_on = None
def upgrade():
op.rename_table(u"time_budget", u"time_budgets")
op.drop_constraint(u"FK_time-budget_users", "time_budgets", type_="foreignkey")
op.alter_column(
u"users",
u"id",
new_column_name=u"user_id",
existing_type=sa.Integer,
existing_nullable=False)
op.create_foreign_key(
u"FK__time_budgets__users",
u"time_budgets",
u"users",
[u"user_id"],
[u"user_id"],
onupdate="CASCADE",
ondelete="RESTRICT")
op.alter_column(
u"time_budgets",
u"time_budget_s",
new_column_name=u"time_budget",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"0")
op.alter_column(
u"time_budgets",
u"id",
new_column_name=u"budget_id",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"0")
op.alter_column(
u"kodi_instances",
u"id",
new_column_name=u"instance_id",
existing_type=sa.Integer,
existing_nullable=False)
def downgrade():
op.alter_column(
u"kodi_instances",
u"instance_id",
new_column_name=u"id",
existing_type=sa.Integer,
existing_nullable=False)
op.alter_column(
u"time_budgets",
u"budget_id",
new_column_name=u"id",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"0")
op.alter_column(
u"time_budgets",
u"time_budget",
new_column_name=u"time_budget_s",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"0")
op.drop_constraint(u"FK__time_budgets__users", "time_budgets", type_="foreignkey")
op.alter_column(
u"users",
u"user_id",
new_column_name=u"id",
existing_type=sa.Integer,
existing_nullable=False)
op.create_foreign_key(
u"FK_time-budget_users",
u"time_budgets",
u"users",
[u"user_id"],
[u"id"],
onupdate="CASCADE",
ondelete="RESTRICT")
op.rename_table(u"time_budgets", u"time_budget")

View File

@ -0,0 +1,40 @@
"""Add time budgets table
Revision ID: 64bc9837edef
Revises: 7218e9517c00
Create Date: 2022-05-05 01:14:04.395901
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '64bc9837edef'
down_revision = '7218e9517c00'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
u"time-budget",
sa.Column(u"id", sa.Integer, primary_key=True),
sa.Column(u"user-id", sa.Integer, nullable=False),
sa.Column(u"time-budget-s", sa.Integer, nullable=False, server_default=u"0"),
mysql_charset="utf8",
mysql_collate="utf8_unicode_ci"
)
op.create_foreign_key(
u"FK_time-budget_users",
u"time-budget",
u"users",
[u"user-id"],
[u"id"],
onupdate="CASCADE",
ondelete="RESTRICT")
def downgrade():
op.drop_constraint(u"FK_time-budget_users", "time-budget", type_="foreignkey")
op.drop_table(u"time-budget")

View File

@ -0,0 +1,35 @@
"""Add Kodi instances table
Revision ID: 68d8f4d96043
Revises:
Create Date: 2022-05-04 01:35:12.791868
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '68d8f4d96043'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
u"kodi-instances",
sa.Column(u"id", sa.Integer, primary_key=True),
sa.Column(u"webserver-proto", sa.String(10), nullable=False, server_default=u"ws"),
sa.Column(u"webserver-addr", sa.String(40), nullable=False, server_default=u"localhost"),
sa.Column(u"webserver-port", sa.Integer, nullable=False, server_default=u"8080"),
sa.Column(u"webserver-jsonrpcpath", sa.String(10), nullable=False, server_default=u"/jsonrpc"),
sa.Column(u"webserver-username", sa.String(48)),
sa.Column(u"webserver-password", sa.String(48)),
mysql_charset="utf8",
mysql_collate="utf8_unicode_ci"
)
def downgrade():
op.drop_table(u"kodi-instances")

View File

@ -0,0 +1,30 @@
"""Add users table
Revision ID: 7218e9517c00
Revises: 68d8f4d96043
Create Date: 2022-05-04 22:49:36.690140
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7218e9517c00'
down_revision = '68d8f4d96043'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
u"users",
sa.Column(u"id", sa.Integer, primary_key=True),
sa.Column(u"username", sa.String(48), nullable=False),
mysql_charset="utf8",
mysql_collate="utf8_unicode_ci"
)
def downgrade():
op.drop_table(u"users")

View File

@ -0,0 +1,136 @@
"""Replace dashes in column, table names with underscores
Revision ID: 954ded90cc97
Revises: 64bc9837edef
Create Date: 2022-05-05 01:43:15.068725
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '954ded90cc97'
down_revision = '64bc9837edef'
branch_labels = None
depends_on = None
def upgrade():
op.rename_table(u"kodi-instances", u"kodi_instances")
op.rename_table(u"time-budget", u"time_budget")
op.alter_column(
u"kodi_instances",
u"webserver-proto",
new_column_name=u"webserver_proto",
existing_type=sa.String(10),
existing_nullable=False,
existing_server_default=u"ws")
op.alter_column(
u"kodi_instances",
u"webserver-addr",
new_column_name=u"webserver_addr",
existing_type=sa.String(40),
existing_nullable=False,
existing_server_default=u"localhost")
op.alter_column(
u"kodi_instances",
u"webserver-port",
new_column_name=u"webserver_port",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"8080")
op.alter_column(
u"kodi_instances",
u"webserver-jsonrpcpath",
new_column_name=u"webserver_jsonrpcpath",
existing_type=sa.String(10),
existing_nullable=False,
existing_server_default=u"/jsonrpc")
op.alter_column(
u"kodi_instances",
u"webserver-username",
new_column_name=u"webserver_username",
existing_type=sa.String(48),
existing_nullable=True)
op.alter_column(
u"kodi_instances",
u"webserver-password",
new_column_name=u"webserver_password",
existing_type=sa.String(48),
existing_nullable=True)
op.alter_column(
u"time_budget",
u"user-id",
new_column_name=u"user_id",
existing_type=sa.Integer,
existing_nullable=False)
op.alter_column(
u"time_budget",
u"time-budget-s",
new_column_name=u"time_budget_s",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"0")
def downgrade():
op.alter_column(
u"time_budget",
u"user_id",
new_column_name=u"user-id",
existing_type=sa.Integer,
existing_nullable=False)
op.alter_column(
u"time_budget",
u"time_budget_s",
new_column_name=u"time-budget-s",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"0")
op.alter_column(
u"kodi_instances",
u"webserver_proto",
new_column_name=u"webserver-proto",
existing_type=sa.String(10),
existing_nullable=False,
existing_server_default=u"ws")
op.alter_column(
u"kodi_instances",
u"webserver_addr",
new_column_name=u"webserver-addr",
existing_type=sa.String(40),
existing_nullable=False,
existing_server_default=u"localhost")
op.alter_column(
u"kodi_instances",
u"webserver_port",
new_column_name=u"webserver-port",
existing_type=sa.Integer,
existing_nullable=False,
existing_server_default=u"8080")
op.alter_column(
u"kodi_instances",
u"webserver_jsonrpcpath",
new_column_name=u"webserver-jsonrpcpath",
existing_type=sa.String(10),
existing_nullable=False,
existing_server_default=u"/jsonrpc")
op.alter_column(
u"kodi_instances",
u"webserver_username",
new_column_name=u"webserver-username",
existing_type=sa.String(48),
existing_nullable=True)
op.alter_column(
u"kodi_instances",
u"webserver_password",
new_column_name=u"webserver-password",
existing_type=sa.String(48),
existing_nullable=True)
op.rename_table(u"time_budget", u"time-budget")
op.rename_table(u"kodi_instances", u"kodi-instances")

View File

@ -14,8 +14,23 @@
# via requests
"requests==2.27.1",
# via -r requirements.in
"urllib3==1.26.9"
"urllib3==1.26.9",
# via requests
"alembic==1.7.7",
# via -r requirements.in
"greenlet==1.1.2",
# via sqlalchemy
"mako==1.2.0",
# via alembic
"markupsafe==2.1.1",
# via
# mako
"sqlalchemy==1.4.36",
# via
# -r requirements.in
# alembic
"mysqlclient==2.1.0"
# via -r requirements.in
]
[project.optional-dependencies]

View File

@ -1,4 +1,7 @@
requests
towncrier
semver
pytest
pytest
SQLAlchemy
alembic
mysqlclient

View File

@ -4,6 +4,8 @@
#
# pip-compile
#
alembic==1.7.7
# via -r requirements.in
attrs==21.4.0
# via pytest
certifi==2021.10.8
@ -16,6 +18,8 @@ click==8.1.3
# towncrier
click-default-group==1.2.2
# via towncrier
greenlet==1.1.2
# via sqlalchemy
idna==3.3
# via requests
incremental==21.3.0
@ -24,8 +28,14 @@ iniconfig==1.1.1
# via pytest
jinja2==3.1.2
# via towncrier
mako==1.2.0
# via alembic
markupsafe==2.1.1
# via jinja2
# via
# jinja2
# mako
mysqlclient==2.1.0
# via -r requirements.in
packaging==21.3
# via pytest
pluggy==1.0.0
@ -40,6 +50,10 @@ requests==2.27.1
# via -r requirements.in
semver==2.13.0
# via -r requirements.in
sqlalchemy==1.4.36
# via
# -r requirements.in
# alembic
tomli==2.0.1
# via
# pytest