diff --git a/app/app.py b/app/app.py index c3ba1f2..47dd839 100755 --- a/app/app.py +++ b/app/app.py @@ -1,25 +1,10 @@ +# ...existing code... + # Player feedback API from models.player_feedback import PlayerFeedback -# --- API route to receive player feedback --- -@app.route('/api/player-feedback', methods=['POST']) -def api_player_feedback(): - data = request.get_json() - required_fields = ['player_name', 'quickconnect_code', 'message', 'status', 'timestamp'] - if not all(field in data for field in required_fields): - return jsonify({'error': 'Missing required fields'}), 400 - feedback = PlayerFeedback( - player_name=data['player_name'], - quickconnect_code=data['quickconnect_code'], - message=data['message'], - status=data['status'], - timestamp=data['timestamp'], - playlist_version=data.get('playlist_version'), - error_details=data.get('error_details') - ) - db.session.add(feedback) - db.session.commit() - return jsonify({'success': True, 'feedback_id': feedback.id}), 200 +# --- API route to receive player feedback --- + import os import click import psutil @@ -121,6 +106,38 @@ login_manager.login_view = 'login' migrate = Migrate(app, db) +@app.route('/api/player-feedback', methods=['POST']) +def api_player_feedback(): + from datetime import datetime + import dateutil.parser + + data = request.get_json() + required_fields = ['player_name', 'quickconnect_code', 'message', 'status', 'timestamp'] + if not all(field in data for field in required_fields): + return jsonify({'error': 'Missing required fields'}), 400 + + # Convert timestamp string to datetime object + try: + if isinstance(data['timestamp'], str): + timestamp = dateutil.parser.parse(data['timestamp']) + else: + timestamp = data['timestamp'] + except (ValueError, TypeError): + return jsonify({'error': 'Invalid timestamp format'}), 400 + + feedback = PlayerFeedback( + player_name=data['player_name'], + quickconnect_code=data['quickconnect_code'], + message=data['message'], + status=data['status'], + timestamp=timestamp, + playlist_version=data.get('playlist_version'), + error_details=data.get('error_details') + ) + db.session.add(feedback) + db.session.commit() + return jsonify({'success': True, 'feedback_id': feedback.id}), 200 + # Add error handlers for better user experience @app.errorhandler(413) def request_entity_too_large(error): @@ -352,7 +369,13 @@ def create_user(): def player_page(player_id): player = db.session.get(Player, player_id) content = get_player_content(player_id) - return render_template('player_page.html', player=player, content=content) + + # Get last 5 feedback entries for this player + player_feedback = PlayerFeedback.query.filter_by( + player_name=player.username + ).order_by(PlayerFeedback.timestamp.desc()).limit(5).all() + + return render_template('player_page.html', player=player, content=content, player_feedback=player_feedback) @app.route('/player//upload', methods=['POST']) @login_required diff --git a/app/migrations/README b/app/migrations/README new file mode 100644 index 0000000..0e04844 --- /dev/null +++ b/app/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/app/migrations/alembic.ini b/app/migrations/alembic.ini new file mode 100644 index 0000000..ec9d45c --- /dev/null +++ b/app/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[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 + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[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/app/migrations/env.py b/app/migrations/env.py new file mode 100644 index 0000000..4c97092 --- /dev/null +++ b/app/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +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. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# 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_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +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. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + 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. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/app/migrations/script.py.mako b/app/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/app/migrations/script.py.mako @@ -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"} diff --git a/app/migrations/versions/217eab16e4e4_add_playerfeedback_table.py b/app/migrations/versions/217eab16e4e4_add_playerfeedback_table.py new file mode 100644 index 0000000..8ec7371 --- /dev/null +++ b/app/migrations/versions/217eab16e4e4_add_playerfeedback_table.py @@ -0,0 +1,38 @@ +"""Add PlayerFeedback table + +Revision ID: 217eab16e4e4 +Revises: +Create Date: 2025-09-08 11:30:26.742813 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '217eab16e4e4' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('player_feedback', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('player_name', sa.String(length=255), nullable=False), + sa.Column('quickconnect_code', sa.String(length=255), nullable=False), + sa.Column('message', sa.Text(), nullable=False), + sa.Column('status', sa.String(length=50), nullable=False), + sa.Column('timestamp', sa.DateTime(), nullable=False), + sa.Column('playlist_version', sa.Integer(), nullable=True), + sa.Column('error_details', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('player_feedback') + # ### end Alembic commands ### diff --git a/app/requirements.txt b/app/requirements.txt index c236af1..a10f438 100755 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -18,6 +18,9 @@ alembic==1.14.1 Mako==1.3.8 greenlet==3.1.1 +# Date parsing +python-dateutil==2.9.0 + # File Processing pdf2image==1.17.0 PyPDF2==3.0.1 diff --git a/app/templates/player_page.html b/app/templates/player_page.html index 5bbee16..8ba73bb 100644 --- a/app/templates/player_page.html +++ b/app/templates/player_page.html @@ -54,20 +54,77 @@

Player Schedule for {{ player.username }}

- -
-
-

Player Info

+
+ +
+
+
+

Player Info

+
+
+

Player Name: {{ player.username }}

+

Hostname: {{ player.hostname }}

+ {% if current_user.role == 'admin' %} + Update +
+ +
+ {% endif %} +
+
-
-

Player Name: {{ player.username }}

-

Hostname: {{ player.hostname }}

- {% if current_user.role == 'admin' %} - Update -
- -
- {% endif %} + + +
+
+
+

Player Status

+
+
+ {% if player_feedback %} +
+ Current Status: + + {{ player_feedback[0].status|title }} + +
+
+ Last Activity: {{ player_feedback[0].timestamp.strftime('%Y-%m-%d %H:%M:%S') }} +
+
+ Latest Message: {{ player_feedback[0].message }} +
+ + +
+ Recent Activity (Last 5) +
+ {% for feedback in player_feedback %} +
+
+ + {{ feedback.status|title }} + + {{ feedback.timestamp.strftime('%m-%d %H:%M') }} +
+
+ {{ feedback.message }} + {% if feedback.playlist_version %} +
Playlist v{{ feedback.playlist_version }} + {% endif %} +
+
+ {% endfor %} +
+
+ {% else %} +
+

No status information available

+ Player hasn't sent any feedback yet +
+ {% endif %} +
+
diff --git a/app/utils/uploads.py b/app/utils/uploads.py index 15a96ae..a025b48 100644 --- a/app/utils/uploads.py +++ b/app/utils/uploads.py @@ -1,4 +1,4 @@ - import os +import os import subprocess from flask import Flask from werkzeug.utils import secure_filename