diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..9575706 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,21 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Remote Attach", + "type": "debugpy", + "request": "attach", + "connect": { + "host": "192.168.10.31", + "port": 5678 + }, + "pathMappings": [ + { + "localRoot": "${workspaceFolder}", + "remoteRoot": "/app" + } + ], + "justMyCode": true + } + ] +} \ No newline at end of file diff --git a/GameManager.png b/GameManager.png deleted file mode 100644 index 5790d74..0000000 Binary files a/GameManager.png and /dev/null differ diff --git a/GameManager1_1.png b/GameManager1_1.png new file mode 100644 index 0000000..412b7a1 Binary files /dev/null and b/GameManager1_1.png differ diff --git a/README.md b/README.md index 7fb5b08..18fe811 100644 --- a/README.md +++ b/README.md @@ -5,72 +5,92 @@ This project helps you keep track of your collected game keys. No more confusion about whether a key is redeemed, gifted, or still unused – now you have everything in one place, with search, status, and even automatic Steam cover images! -It's even possible to gift your keys via a unique website. Just edit the game to "Gifted" and you'll get a option to copy the on your overview page. (maybe HTTPS only) +You can even gift your keys via a unique 24-hour website link – just mark a game as "Gifted" and copy the link from your overview. (HTTPS recommended) -(the link will also remain in the edit area) - -![Screenshot](GameManager.png) +![Screenshot](GameManager1_1.png) --- ## ✨ Features ✨ - **Key Management:** - Enter your game keys, the corresponding game, platform, and maybe where you got the key. + Enter your game keys, platform, source, and more. - **Status Tracking:** - Mark keys as "Redeemed", "Gifted" or "Available" – always know your status. -- **Shop URL & Steam Cover:** - Save the shop URL and (optionally) the Steam AppID. The app will automatically show the official Steam cover image if available. -- **Gift your Games:** - You can create a unique redeem/gift website, which will expire after 24h. -- **Multi-user:** + Mark keys as "Redeemed", "Gifted", or "Available". +- **Steam Cover & Shop Info:** + Provide the Steam AppID and get the official game cover. Add shop URLs too. +- **Game Descriptions & Prices:** + Automatically fetch game descriptions, current best prices, and historical lows from [IsThereAnyDeal](https://isthereanydeal.com/) (API key required). +- **Gifting:** + Create a one-time gift link for each game that expires after 24 hours. +- **Search Functionality:** + Quickly find games with an integrated search bar. +- **Multi-user Support:** Each user manages their own keys. -- **Enable/Disable Registrations:** - Perfect if you want to run the Server just on your own (via .env file) -- **Search:** - Find games quickly with the search function. +- **User Roles:** + The first registered user becomes an admin automatically. +- **Admin Area:** + Admins can reset passwords, delete users, and view audit logs. +- **Audit Logs:** + Track user logins, password resets, and deleted accounts. +- **Registration Toggle:** + Enable or disable user registration via the `.env` file. - **Responsive UI:** - Works on desktop and mobile, with Dark Mode toggle. + Fully functional on desktop and mobile with Dark Mode support. - **Multi-language:** - Switch between English and German instantly*. -- **Import/Export (CSV / PDF -only export-):** - Easy export and import of your keys. (e.g. in case you have to start over) -- **Change Password:** - Change your Password on the fly. -- **Website Security:** - You can turn on/off CSRF and Secure Cookie via .env file. -- **Notifications:** - If you have key that have to be redeemed before a specific date. You can set up sending messages via, Pushover, Matrix and Gotify -- **No key data leaves your server!** -- **(Planned):** - - ~~Import/Export (CSV)~~ - - ~~Redeem site with unique sharing link~~ + Switch between English and German on the fly. +- **Import/Export (CSV, PDF export):** + Import/export your game keys easily. +- **Password Management:** + Users can change their passwords directly. +- **Notifications:** + Get alerts for expiring keys via Gotify, Matrix, or Pushover. +- **Security Settings:** + Toggle CSRF protection and secure cookies in `.env`. +- **Self-hosted:** + No data leaves your server. + +--- + +## 📱 Installable PWA + +Game Key Manager now includes full Progressive Web App (PWA) support! + +- Install the app on your desktop or mobile device with one click. +- Enjoy a native-app-like experience with offline access to previously loaded content. +- Add it to your home screen or applications for quicker access. + +No setup required — just open the site in a modern browser (like Chrome, Edge, Firefox or Safari) and look for the install prompt or browser menu option to "Install App". --- -## 🚀 Get Started! 🚀 +## 🚀 Get Started -### 1. **Clone the Repository** +### 1. Clone the Repository ```bash -git clone https://git.nocci.it/nocci/GameKeyManager +git clone https://codeberg.org/nocci/GameKeyManager ``` -### 2. **Setup Docker** +Alternative: -Make sure you have [Docker](https://www.docker.com/) and [docker-compose](https://docs.docker.com/compose/) installed. -If not, the script will ask you what to do and can install Docker and docker-compose for you. (maybe not if you are running Arch) +```bash +git clone https://dev.skynet.li/nocci/GameKeyManager +``` -### 3. **Initial Setup** +### 2. Setup Docker + +Make sure Docker and docker-compose are installed. +If not, the setup script can guide you (Arch-based distros may vary). + +### 3. Initial Setup ```bash chmod +x setup.sh ./setup.sh ``` -This script prepares all directories, configuration, and translation files. - -### 4. **Build and Start the App** +### 4. Build and Start the App ```bash cd steam-gift-manager/ @@ -78,102 +98,87 @@ docker-compose build --no-cache docker-compose up -d ``` -### 5. **Edit your .env file to your liking** +### 5. Configure `.env` File -It's in your root folder of the installation! +Adjust your settings: -```xml -# Security -SESSION_COOKIE_SECURE="True" (only works if you run this app via HTTPS) +```env +SESSION_COOKIE_SECURE="True" # Only works with HTTPS CSRF_ENABLED="True" +ITAD_API_KEY="your_api_key" # Optional, for price data ``` -**Important after any(!) change of the .env file!** +Apply changes after editing: ```bash -cd steam-gift-manager/ docker-compose down && docker-compose up -d --build ``` -### 6. **Initialize and Edit Translations (Optional)** +### 6. Translate (optional) ```bash ./translate.sh ``` -Edit the .po files in translations/de_DE/LC_MESSAGES/messages.po and en_US/LC_MESSAGES/messages.po +Edit the `.json` files in `translations/`, then restart: ```bash -./translate.sh -cd steam-gift-manager/ docker-compose down && docker-compose up -d --build ``` -### 7. **Open the App** +### 7. Access the App -Go to [http://localhost:5000](http://localhost:5000) in your browser. - -- Register your first user. -- Add your keys, shop URLs etc. -- Enjoy search, status, and automatic Steam cover images! +Visit [http://localhost:5000](http://localhost:5000) +Register the first user – this account becomes the admin! --- -## 🛠️ Technology Stack 🛠️ +## 🔔 Notifications (optional) -- **Frontend:** Bootstrap 5, Jinja2 Templates ... -- **Backend:** Python 3, Flask, Flask-Babel, Flask-Login, Flask-SQLAlchemy ... -- **Database:** SQLite (persisted in `data/`) -- **Containerization:** Docker, docker-compose -- **Translations:** Flask-Babel, editable `.po` files in `translations/` - -## 🌍 Multi-language - -- Switch between English and German using the dropdown in the navigation bar. -- All game and menu texts can be translated or individualized. - -## 🔔 Notifications - -- Send notifications if a game has to be redeemed by a specific date -- Gotify, Matrix and Pushover are already available - have a look into the .env file -- 48 hours before you are running out of time the app will send you a notice +- Reminders for expiring keys (48h notice) +- Pushover, Matrix, Gotify and more are supported through AppRise +- Configurable via `.env` --- -## 🪙 Do you this project? 🪙 +## 🛠️ Tech Stack -If you’d like to support itme, you can make a donation here: +- **Frontend:** Bootstrap 5, Jinja2, ... +- **Backend:** Python 3, Flask, Flask-SQLAlchemy, ... +- **Database:** SQLite +- **Container:** Docker, docker-compose -[![Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/nocci) +--- +## 💬 Contribute + +Contributions are welcome: + +- Report bugs +- Suggest features +- Submit Pull Requests + +--- + +## 💬 Our Base + +You can find us here: [https://skynet.li](https://skynet.li) + +--- + +## 🪙 Support + +Like the project? You can support me: + +[![Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/nocci) [![Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/nocci/donate) -Thank you! +--- + +## 📜 License + +Licensed under [Apache License 2.0](LICENSE). --- -## 🙌 Contribute! 🙌 - -This project is open source! - -- **Bug Reports:** Please report bugs as Issues. -- **Feature Requests:** Suggest new features! -- **Pull Requests:** Submit your code changes! - -// **only possible after Forgejo opens for federation** \\\ - ---- - -## 📜 License 📜 - -This project is licensed under the [Apache License 2.0](LICENSE). - ---- - -## 💖 Acknowledgements 💖 - -A big thank you to everyone who supports and contributes to this project! - ---- - -**Enjoy your organized Game key collection!** 🚀 +**Enjoy managing your game collection!** \ No newline at end of file diff --git a/setup.sh b/setup.sh index 7a24685..5194fda 100644 --- a/setup.sh +++ b/setup.sh @@ -1,13 +1,13 @@ #!/bin/bash set -e -# Color definitions +# Colors RED='\033[1;31m' GREEN='\033[1;32m' YELLOW='\033[1;33m' NC='\033[0m' -# 1. Docker check (including Arch Linux) +# Docker check (incl. Arch Linux) if ! command -v docker &>/dev/null; then echo -e "${RED}❗ Docker is not installed.${NC}" read -p "Would you like to install Docker automatically now? [y/N]: " install_docker @@ -23,7 +23,7 @@ if ! command -v docker &>/dev/null; then rm get-docker.sh fi - # Check Docker group membership + # Docker group membership check if ! groups | grep -q '\bdocker\b'; then echo -e "${YELLOW}⚠️ Your user is not in the docker group. Adding now...${NC}" sudo usermod -aG docker $USER @@ -37,7 +37,7 @@ if ! command -v docker &>/dev/null; then fi fi -# 2. Docker Compose check (V1 and V2 plugin, with Arch support) +# Check Docker compose (V1 und V2 Plugin, incl. Arch Support) DOCKER_COMPOSE_CMD="" if command -v docker-compose &>/dev/null; then DOCKER_COMPOSE_CMD="docker-compose" @@ -52,6 +52,7 @@ else elif command -v apt-get &>/dev/null; then sudo apt-get update sudo apt-get install -y docker-compose-plugin + sudo apt-get install -y docker-compose elif command -v dnf &>/dev/null; then sudo dnf install -y docker-compose elif command -v yum &>/dev/null; then @@ -73,23 +74,36 @@ else fi fi - -# Konfiguration +# Configuration PROJECT_DIR="steam-gift-manager" -TRANSLATIONS_DIR="../translations" -DATA_DIR="../data" +TRANSLATIONS_DIR="$PWD/$PROJECT_DIR/translations" +DATA_DIR="$PWD/data" -# 1. Projektordner & Übersetzungsordner erstellen -mkdir -p "$PROJECT_DIR"/{templates,static} -mkdir -p "$TRANSLATIONS_DIR"/de/LC_MESSAGES -mkdir -p "$TRANSLATIONS_DIR"/en/LC_MESSAGES +# Create folders +mkdir -p "$PROJECT_DIR" +mkdir -p "$PROJECT_DIR"/{templates,static,translations} mkdir -p "$DATA_DIR" chmod -R a+rwX "$TRANSLATIONS_DIR" "$DATA_DIR" +echo -e "\n\033[1;32m✅ Downloading assets - Please wait!\033[0m" + +# Download Pictures from my server +cd "$PROJECT_DIR/static" +wget -O logo.webp "https://assets.skynet.li/logo.webp" > /dev/null 2>&1 +wget -O logo_small.webp "https://assets.skynet.li/logo_small.webp" > /dev/null 2>&1 +wget -O forgejo.webp "https://assets.skynet.li/forgejo.webp" > /dev/null 2>&1 +wget -O gog_logo.webp "https://assets.skynet.li/gog_logo.webp" > /dev/null 2>&1 +wget -O logo_small_maskable.webp "https://assets.skynet.li/logo_small_maskable.webp" > /dev/null 2>&1 +wget -O favicon.ico "https://assets.skynet.li/favicon.ico" > /dev/null 2>&1 +wget -O apple-touch-icon.png "https://assets.skynet.li/apple-touch-icon.png" > /dev/null 2>&1 +wget -O web-app-manifest-192x192.png "https://assets.skynet.li/web-app-manifest-192x192.png" > /dev/null 2>&1 +wget -O web-app-manifest-512x512.png "https://assets.skynet.li/web-app-manifest-512x512.png" > /dev/null 2>&1 +cd ../.. + cd $PROJECT_DIR -# 2. requirements.txt +# requirements.txt cat < requirements.txt flask flask-login @@ -98,19 +112,23 @@ flask-migrate werkzeug python-dotenv flask-sqlalchemy -flask-babel jinja2<3.1.0 itsdangerous sqlalchemy apscheduler -matrix-client reportlab requests pillow +gunicorn +apprise +debugpy +pytz +Flask-Session +redis EOL -# 3. .env-Datei im übergeordneten Verzeichnis erstellen -cd .. + +# create .env SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_hex(24))') REDEEM_SECRET=$(python3 -c 'import secrets; print(secrets.token_hex(16))') REDEEM_CSRF=$(python3 -c 'import secrets; print(secrets.token_hex(16))') @@ -121,87 +139,206 @@ SECRET_KEY="$SECRET_KEY" REDEEM_SECRET="$REDEEM_SECRET" WTF_CSRF_SECRET_KEY="$REDEEM_CSRF" -# locales -BABEL_DEFAULT_LOCALE="en" -BABEL_SUPPORTED_LOCALES="de,en" -BABEL_TRANSLATION_DIRECTORIES="translations" +# Language Settings +DEFAULT_LANGUAGE="en" +SUPPORTED_LANGUAGES="de,en" # Timezone -TZ=Europe/Berlin +TZ="Europe/Berlin" # Security -SESSION_COOKIE_SECURE="False" +FORCE_HTTPS="False" +SESSION_COOKIE_SECURE="auto" CSRF_ENABLED="True" + # Account registration REGISTRATION_ENABLED="True" # checking interval if keys have to be redeemed before a specific date -CHECK_EXPIRING_KEYS_INTERVAL_HOURS=6 +CHECK_EXPIRING_KEYS_INTERVAL_HOURS="6" -# Pushover -PUSHOVER_APP_TOKEN="" -PUSHOVER_USER_KEY="" +# Want to check prices? Here you are! +ITAD_API_KEY="your-secret-key-here" +ITAD_COUNTRY="DE" -# Gotify -GOTIFY_URL="" -GOTIFY_TOKEN="" +# Apprise URLs (separate several with a comma or space) +APPRISE_URLS="" -# Matrix -MATRIX_HOMESERVER="" -MATRIX_ACCESS_TOKEN="" -MATRIX_ROOM_ID="" +### example for multiple notifications +#APPRISE_URLS="pover://USER_KEY@APP_TOKEN +#gotify://gotify.example.com/TOKEN +#matrixs://TOKEN@matrix.org/!ROOM_ID" + +# Redis URL +REDIS_URL="redis://redis:6379/0" + +# Enable Debug (e.g. for VS Code) +FLASK_DEBUG=1 +DEBUGPY=0 EOL -# Zurück ins Projektverzeichnis -cd $PROJECT_DIR - -# 4. app.py (vollständige korrigierte Version) +# app.py (the main app) cat <<'PYTHON_END' > app.py -import os -import logging -import warnings -from sqlalchemy.exc import LegacyAPIWarning -warnings.simplefilter("ignore", category=LegacyAPIWarning) -from flask import Flask, render_template, request, redirect, url_for, flash, make_response, session, abort, send_file, jsonify -from flask_sqlalchemy import SQLAlchemy -from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user -from flask_babel import Babel, _ -from werkzeug.security import generate_password_hash, check_password_hash -from datetime import datetime, timedelta -from flask_wtf import CSRFProtect -from flask import abort -import io -import warnings -import re -import io -import csv -import secrets -import requests -from dotenv import load_dotenv -load_dotenv(override=True) -from sqlalchemy.exc import IntegrityError -from apscheduler.schedulers.background import BackgroundScheduler +# Standard library imports import atexit -from flask_migrate import Migrate -from sqlalchemy import MetaData -from reportlab.pdfgen import canvas -from reportlab.lib.pagesizes import A4, landscape, letter -from reportlab.platypus import ( - SimpleDocTemplate, - Table, - TableStyle, - Paragraph, - Image, - Spacer -) -from reportlab.lib import colors -from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle -from reportlab.lib.utils import ImageReader -from reportlab.lib.units import cm, inch, mm +import csv +import io +import locale +import logging +import os +import random +import re +import secrets +import sqlite3 +import time +import traceback +from datetime import datetime, timedelta +from functools import wraps from io import BytesIO -import reportlab.lib +from time import sleep +from urllib.parse import urlparse +from zoneinfo import ZoneInfo +import warnings +# 3rd-Provider-Modules +import pytz +import requests +from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore +from apscheduler.schedulers.background import BackgroundScheduler +from dotenv import load_dotenv +from flask import ( + Flask, + Markup, + abort, + flash, + g, + jsonify, + make_response, + redirect, + render_template, + request, + send_file, + session, + url_for +) +from flask_login import ( + LoginManager, + UserMixin, + current_user, + login_required, + login_user, + logout_user +) +from flask_migrate import Migrate +from flask_session import Session +from flask_sqlalchemy import SQLAlchemy +from flask_wtf import CSRFProtect, FlaskForm +from redis import Redis +from reportlab.lib import colors +from reportlab.lib.pagesizes import A4, landscape, letter +from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet +from reportlab.lib.units import cm, inch, mm +from reportlab.lib.utils import ImageReader +from reportlab.pdfgen import canvas +from reportlab.platypus import ( + Image, + Paragraph, + SimpleDocTemplate, + Spacer, + Table, + TableStyle +) +from sqlalchemy import MetaData, UniqueConstraint, event +from sqlalchemy.engine import Engine +from sqlalchemy.exc import IntegrityError, LegacyAPIWarning +from sqlalchemy.orm import joinedload +from werkzeug.security import check_password_hash, generate_password_hash +from werkzeug.middleware.proxy_fix import ProxyFix +from wtforms import SelectField, StringField, TextAreaField, validators + +# Config +load_dotenv(override=True) +warnings.simplefilter("ignore", category=LegacyAPIWarning) + +# Logging-Config +logging.basicConfig(level=logging.INFO) +logging.getLogger('apscheduler').setLevel(logging.WARNING) + + +@event.listens_for(Engine, "connect") +def enable_foreign_keys(dbapi_connection, connection_record): + if isinstance(dbapi_connection, sqlite3.Connection): + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON;") + cursor.close() + +ITAD_API_KEY_PLACEHOLDER = "your_api_key_here" +TZ = os.getenv('TZ', 'UTC') +os.environ['TZ'] = TZ app = Flask(__name__) +app.jinja_env.globals['getattr'] = getattr + +@app.errorhandler(404) +def not_found_error(error): + return render_template('404.html'), 404 + +app.wsgi_app = ProxyFix( + app.wsgi_app, + x_proto=1, # Trust X-Forwarded-Proto Header + x_host=1 # Trust X-Forwarded-Host Header +) + +# UNIX-Systems (Linux, Docker) +try: + time.tzset() +except AttributeError: + pass # tzset not availabe on Windows +local_tz = pytz.timezone(TZ) + +# Load Languages +import os +import json + + +TRANSLATION_DIR = os.path.join(os.getcwd(), 'translations') +SUPPORTED_LANGUAGES = ['de', 'en'] +TRANSLATIONS = {} + +for lang in SUPPORTED_LANGUAGES: + try: + with open(os.path.join(TRANSLATION_DIR, f'{lang}.json'), encoding='utf-8') as f: + TRANSLATIONS[lang] = json.load(f) + print(f"✅ Loaded {lang} translations") + except Exception: + print(f"❌ Failed loading {lang}.json: {str(e)}") + TRANSLATIONS[lang] = {} + +def translate(key, lang=None, **kwargs): + lang = lang or session.get('lang', 'en') + fallback_lang = app.config.get('DEFAULT_LANGUAGE', 'en') + + translations = TRANSLATIONS.get(lang, {}) + fallback_translations = TRANSLATIONS.get(fallback_lang, {}) + + value = translations.get(key) or fallback_translations.get(key) or key + return value.format(**kwargs) if isinstance(value, str) else value + +## DEBUG Translations +if app.debug: + print(f"Loaded translations for 'de': {TRANSLATIONS.get('de', {})}") + +### Admin decorator +def admin_required(f): + @wraps(f) + def decorated_function(*args, **kwargs): + if not current_user.is_authenticated: + abort(403) + if not current_user.is_admin: + abort(403) + return f(*args, **kwargs) + return decorated_function + + csrf = CSRFProtect(app) convention = { @@ -215,77 +352,231 @@ convention = { metadata = MetaData(naming_convention=convention) load_dotenv(override=True) -# Lade Umgebungsvariablen aus .env mit override +# load variables from .env with override load_dotenv(override=True) -# Konfiguration +# App-Configuration app.config.update( + # Most Important SECRET_KEY=os.getenv('SECRET_KEY'), - SQLALCHEMY_DATABASE_URI=('sqlite:////app/data/games.db'), - SQLALCHEMY_TRACK_MODIFICATIONS=False, - BABEL_DEFAULT_LOCALE=os.getenv('BABEL_DEFAULT_LOCALE'), - BABEL_SUPPORTED_LOCALES=os.getenv('BABEL_SUPPORTED_LOCALES').split(','), - BABEL_TRANSLATION_DIRECTORIES=os.getenv('BABEL_TRANSLATION_DIRECTORIES'), - SESSION_COOKIE_SECURE=os.getenv('SESSION_COOKIE_SECURE') == 'True', - WTF_CSRF_ENABLED=os.getenv('CSRF_ENABLED') == 'True', - REGISTRATION_ENABLED=os.getenv('REGISTRATION_ENABLED', 'True').lower() == 'true' + SQLALCHEMY_DATABASE_URI = 'sqlite:////app/data/games.db', + SQLALCHEMY_TRACK_MODIFICATIONS = False, + DEFAULT_LANGUAGE='en', + ITAD_COUNTRY = os.getenv("ITAD_COUNTRY", "DE"), + + # SESSION-HANDLING (In Production: Use Redis!) + SESSION_TYPE='redis', + SESSION_PERMANENT = False, + SESSION_USE_SIGNER = True, + SESSION_REDIS=Redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0")), + SESSION_FILE_DIR = '/app/data/flask-sessions', + SESSION_COOKIE_NAME = 'gamekeys_session', + SESSION_COOKIE_SECURE = os.getenv('SESSION_COOKIE_SECURE', 'False').lower() == 'true', + SESSION_COOKIE_HTTPONLY = True, + SESSION_COOKIE_SAMESITE = 'Lax', + PERMANENT_SESSION_LIFETIME = timedelta(days=30), + + + # LOGIN COOKIE STUFF + REMEMBER_COOKIE_DURATION=timedelta(days=30), + REMEMBER_COOKIE_HTTPONLY=True, + REMEMBER_COOKIE_SECURE=True if os.getenv('FORCE_HTTPS', 'False').lower() == 'true' else False, + REMEMBER_COOKIE_SAMESITE='Lax', + + # CSRF-PROTECTION + WTF_CSRF_ENABLED = True, + WTF_CSRF_SECRET_KEY = os.getenv('CSRF_SECRET_KEY', os.urandom(32).hex()), + WTF_CSRF_TIME_LIMIT = 3600, + + # SECURITYsa & PERFORMANCE + REGISTRATION_ENABLED = os.getenv('REGISTRATION_ENABLED', 'True').lower() == 'true', + SEND_FILE_MAX_AGE_DEFAULT = int(os.getenv('SEND_FILE_MAX_AGE_DEFAULT', 0)), + TEMPLATES_AUTO_RELOAD = os.getenv('TEMPLATES_AUTO_RELOAD', 'True').lower() == 'true', + PREFERRED_URL_SCHEME = 'https' if os.getenv('FORCE_HTTPS') else 'http' ) + +Session(app) + interval_hours = int(os.getenv('CHECK_EXPIRING_KEYS_INTERVAL_HOURS', 12)) -# Initialisierung +# Init db = SQLAlchemy(app, metadata=metadata) migrate = Migrate(app, db) login_manager = LoginManager(app) login_manager.login_view = 'login' -babel = Babel(app) # Logging app.logger.addHandler(logging.StreamHandler()) -app.logger.setLevel(logging.INFO) +app.logger.setLevel(logging.DEBUG) + +@app.errorhandler(403) +def forbidden_error(error): + return render_template('403.html'), 403 + + +@app.before_request +def set_language(): + if 'lang' not in session or not session['lang']: + session['lang'] = app.config.get('DEFAULT_LANGUAGE', 'en') + g.lang = session['lang'] + +def enforce_https(): + if os.getenv('FORCE_HTTPS', 'False').lower() == 'true' and not app.debug: + proto = request.headers.get('X-Forwarded-Proto', 'http') + if proto != 'https' and not request.is_secure: + url = request.url.replace('http://', 'https://', 1) + return redirect(url, code=301) + +def debug_translations(): + if app.debug: + app.logger.debug(f"Lang: {session.get('lang')}") + +app.before_request(enforce_https) + -@babel.localeselector -def get_locale(): - if 'lang' in session and session['lang'] in app.config['BABEL_SUPPORTED_LOCALES']: - return session['lang'] - return request.accept_languages.best_match(app.config['BABEL_SUPPORTED_LOCALES']) @app.context_processor -def inject_template_vars(): - return dict( - get_locale=get_locale, - theme='dark' if request.cookies.get('dark_mode') == 'true' else 'light' - ) +def inject_template_globals(): + return { + '_': lambda key, **kwargs: translate(key, lang=session.get('lang', 'en'), **kwargs), + 'now': datetime.now(local_tz), + 'app_version': os.getenv('APP_VERSION', '1.0.0'), + 'local_tz': local_tz + } -# Datenbankmodelle -class User(db.Model, UserMixin): +@app.template_filter('strftime') +def _jinja2_filter_datetime(date, fmt='%d.%m.%Y'): + if date is None: + return '' + return date.strftime(fmt) + +@app.errorhandler(403) +def forbidden(e): + return render_template('403.html'), 403 + + +# DB Models +class ActivityLog(db.Model): + __tablename__ = 'activity_logs' + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id')) + action = db.Column(db.String(100), nullable=False) + details = db.Column(db.Text) + timestamp = db.Column(db.DateTime, default=lambda: datetime.now(local_tz)) + + user = db.relationship('User', backref='activities') + + +class User(UserMixin, db.Model): __tablename__ = 'users' + id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(256), nullable=False) - games = db.relationship('Game', back_populates='owner', lazy=True) + is_admin = db.Column(db.Boolean, default=False) + games = db.relationship( + 'Game', + back_populates='owner', + cascade='all, delete-orphan', + passive_deletes=True + ) + class Game(db.Model): + __tablename__ = 'games' + __table_args__ = ( + UniqueConstraint('steam_key', 'user_id', name='uq_steam_key_user'), + ) + id = db.Column(db.Integer, primary_key=True) - owner = db.relationship('User', back_populates='games') name = db.Column(db.String(100), nullable=False) steam_key = db.Column(db.String(100), nullable=False, unique=True) status = db.Column(db.String(50), nullable=False) recipient = db.Column(db.String(100)) notes = db.Column(db.Text) url = db.Column(db.String(200)) - created_at = db.Column(db.DateTime, default=datetime.utcnow) + created_at = db.Column(db.DateTime, default=lambda: datetime.now(local_tz)) redeem_date = db.Column(db.DateTime) - user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) steam_appid = db.Column(db.String(20)) + platform = db.Column(db.String(50), default='pc') + current_price = db.Column(db.Float) + current_price_shop = db.Column(db.String(100)) + historical_low = db.Column(db.Float) + release_date = db.Column(db.DateTime) + release_date = db.Column(db.DateTime) + itad_slug = db.Column(db.String(200)) + steam_description_en = db.Column(db.Text) + steam_description_de = db.Column(db.Text) + + # with users.id + user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False) + + owner = db.relationship( + 'User', + back_populates='games' + ) + + redeem_tokens = db.relationship( + 'RedeemToken', + back_populates='game', + cascade='all, delete-orphan', + passive_deletes=True + ) class RedeemToken(db.Model): + __tablename__ = 'redeem_tokens' + id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(17), unique=True, nullable=False) - game_id = db.Column(db.Integer, db.ForeignKey('game.id'), nullable=False) - expires = db.Column(db.DateTime, nullable=False) - used = db.Column(db.Boolean, default=False) + expires = db.Column(db.DateTime(timezone=True), nullable=False) total_hours = db.Column(db.Integer, nullable=False) + + # ForeignKey with CASCADE + game_id = db.Column( + db.Integer, + db.ForeignKey('games.id', ondelete='CASCADE'), + nullable=False + ) + + game = db.relationship('Game', back_populates='redeem_tokens') + + def is_expired(self): + # use timeszone (from .env) + local_tz = pytz.timezone(os.getenv('TZ', 'UTC')) + now = datetime.now(local_tz) + return now > self.expires.astimezone(local_tz) + +class GameForm(FlaskForm): + name = StringField('Name', [validators.DataRequired()]) + steam_key = StringField('Steam Key') + status = SelectField('Status', choices=[ + ('nicht eingelöst', 'Nicht eingelöst'), + ('eingelöst', 'Eingelöst'), + ('geschenkt', 'Geschenkt') + ]) + recipient = StringField('Empfänger') + notes = TextAreaField('Notizen') + url = StringField('Store URL') + redeem_date = StringField('Einlösedatum') + steam_appid = StringField('Steam App ID') + +PLATFORM_CHOICES = [ + ('steam', 'Steam'), + ('gog', 'GOG'), + ('xbox', 'XBox'), + ('playstation', 'PlayStation'), + ('switch', 'Nintendo Switch'), + ('other', 'Other'), + ('pc', 'PC') +] + +STATUS_CHOICES = [ + ('nicht eingelöst', 'Nicht eingelöst'), + ('eingelöst', 'Eingelöst'), + ('geschenkt', 'Geschenkt') +] with app.app_context(): db.create_all() @@ -305,6 +596,131 @@ def get_or_404(model, id): abort(404) return instance +# Admin Audit Helper +def log_activity(user_id, action, details=None): + """ + Store an activity log entry for auditing purposes. + """ + log = ActivityLog( + user_id=user_id, + action=action, + details=details + ) + db.session.add(log) + db.session.commit() + +# Game Infos Helper +def fetch_steam_data(appid, lang='en'): + lang_map = { + 'en': 'english', + 'de': 'german' + } + steam_lang = lang_map.get(lang, 'english') + try: + response = requests.get( + "https://store.steampowered.com/api/appdetails", + params={"appids": appid, "l": steam_lang}, + timeout=15 + ) + data = response.json().get(str(appid), {}) + if data.get("success"): + return { + "name": data["data"].get("name"), + "detailed_description": data["data"].get("detailed_description"), + "release_date": data["data"].get("release_date", {}).get("date"), + } + except Exception as e: + app.logger.error(f"Steam API error: {str(e)}") + return None + +def parse_steam_release_date(date_str): + """Parsing Steam-Release-Date (the german us thingy, you know)""" + import locale + from datetime import datetime + + # try german format + try: + locale.setlocale(locale.LC_TIME, "de_DE.UTF-8") + return datetime.strptime(date_str, "%d. %b. %Y") + except Exception: + pass + # Fallback: okay lets try the english one + try: + locale.setlocale(locale.LC_TIME, "en_US.UTF-8") + return datetime.strptime(date_str, "%d %b, %Y") + except Exception: + pass + return None + +def fetch_itad_slug(steam_appid: int) -> str | None: + api_key = os.getenv("ITAD_API_KEY") + if not api_key or api_key.strip() == "your-secret-key-here": + app.logger.warning("ITAD-API-Key ist nicht gesetzt oder ist ein Platzhalter.") + return None + try: + response = requests.get( + "https://api.isthereanydeal.com/games/lookup/v1", + params={"key": api_key, "appid": steam_appid, "platform": "steam"}, + timeout=10 + ) + data = response.json() + return data.get("game", {}).get("slug") + except Exception as e: + app.logger.error(f"ITAD Error: {str(e)}") + return None + + +def fetch_itad_game_id(steam_appid: int) -> str | None: + api_key = os.getenv("ITAD_API_KEY") + if not api_key or api_key.strip() == "your-secret-key-here": + app.logger.warning("ITAD-API-Key ist nicht gesetzt oder ist ein Platzhalter.") + return None + + try: + response = requests.get( + "https://api.isthereanydeal.com/games/lookup/v1", + params={"key": api_key, "appid": steam_appid, "platform": "steam"}, + timeout=10 + ) + response.raise_for_status() + data = response.json() + if data.get("found") and data.get("game") and data["game"].get("id"): + return data["game"]["id"] + app.logger.error(f"ITAD Response Error: {data}") + return None + except Exception as e: + app.logger.error(f"ITAD Error: {str(e)}") + return None + +def fetch_itad_prices(game_id: str) -> dict | None: + api_key = os.getenv("ITAD_API_KEY") + country = os.getenv("ITAD_COUNTRY", "DE") + + if not api_key or api_key.strip() == "your-secret-key-here": + app.logger.warning("ITAD-API-Key ist nicht gesetzt oder ist ein Platzhalter.") + return None + + try: + response = requests.post( + "https://api.isthereanydeal.com/games/prices/v3", + params={ + "key": api_key, + "country": country, + "shops": "steam", + "vouchers": "false" + }, + json=[game_id], + headers={"Content-Type": "application/json"}, + timeout=15 + ) + response.raise_for_status() + return response.json()[0] + + except Exception as e: + app.logger.error(f"ITAD-Preisabfrage fehlgeschlagen: {str(e)}") + return None + + @app.route('/') @login_required def index(): @@ -322,50 +738,76 @@ def index(): @app.route('/set-lang/') def set_lang(lang): - if lang in app.config['BABEL_SUPPORTED_LOCALES']: + if lang in SUPPORTED_LANGUAGES: session['lang'] = lang + session.permanent = True return redirect(request.referrer or url_for('index')) - + @app.route('/set-theme/') def set_theme(theme): resp = make_response('', 204) - resp.set_cookie('dark_mode', 'true' if theme == 'dark' else 'false', max_age=60*60*24*365) + resp.set_cookie('theme', theme, max_age=60*60*24*365) return resp @app.route('/login', methods=['GET', 'POST']) def login(): + if current_user.is_authenticated: # Prevent already logged-in users from accessing login page + return redirect(url_for('index')) + if request.method == 'POST': - username = request.form['username'] - password = request.form['password'] + username = request.form.get('username') + password = request.form.get('password') + remember = request.form.get('remember_me') == 'true' + user = User.query.filter_by(username=username).first() - + if user and check_password_hash(user.password, password): - login_user(user) - return redirect(url_for('index')) - - flash(_('Invalid credentials'), 'danger') + # Pass remember=True to login_user and set duration + # The duration will be taken from app.config['REMEMBER_COOKIE_DURATION'] + login_user(user, remember=remember) + + # Log activity + log_activity(user.id, 'user_login', f"User '{user.username}' logged in.") + + next_page = request.args.get('next') + # Add security check for next_page to prevent open redirect + if not next_page or urlparse(next_page).netloc != '': + next_page = url_for('index') + flash(translate('Logged in successfully.'), 'success') + return redirect(next_page) + else: + flash(translate('Invalid username or password.'), 'danger') return render_template('login.html') @app.route('/register', methods=['GET', 'POST']) def register(): if not app.config['REGISTRATION_ENABLED']: - flash(_('Registrierungen sind deaktiviert'), 'danger') - return redirect(url_for('login')) - + abort(403) + if request.method == 'POST': username = request.form['username'] - password = generate_password_hash(request.form['password']) - - if User.query.filter_by(username=username).first(): - flash(_('Username already exists'), 'danger') + password = request.form['password'] + + existing_user = User.query.filter_by(username=username).first() + if existing_user: + flash(translate('Username already exists'), 'error') return redirect(url_for('register')) - - new_user = User(username=username, password=password) + + # make the first user admin + is_admin = User.query.count() == 0 + + new_user = User( + username=username, + password=generate_password_hash(password), + is_admin=is_admin + ) + db.session.add(new_user) db.session.commit() login_user(new_user) + flash(translate('Registration successful'), 'success') return redirect(url_for('index')) - + return render_template('register.html') @app.route('/logout') @@ -383,16 +825,16 @@ def change_password(): confirm_password = request.form['confirm_password'] if not check_password_hash(current_user.password, current_password): - flash(_('Aktuelles Passwort ist falsch'), 'danger') + flash(translate('Current passwort is wrong'), 'danger') return redirect(url_for('change_password')) if new_password != confirm_password: - flash(_('Neue Passwörter stimmen nicht überein'), 'danger') + flash(translate('New Passwords are not matching'), 'danger') return redirect(url_for('change_password')) current_user.password = generate_password_hash(new_password) db.session.commit() - flash(_('Passwort erfolgreich geändert'), 'success') + flash(translate('Password changed successfully', session.get('lang', 'en')), 'success') return redirect(url_for('index')) return render_template('change_password.html') @@ -407,98 +849,134 @@ def add_game(): if not steam_appid: steam_appid = extract_steam_appid(url) - + + steam_key = request.form['steam_key'] + if Game.query.filter_by(steam_key=steam_key).first(): + flash(translate('Steam Key already exists!'), 'error') + return redirect(url_for('add_game')) + new_game = Game( name=request.form['name'], - steam_key=request.form['steam_key'], + steam_key=steam_key, status=request.form['status'], recipient=request.form.get('recipient', ''), notes=request.form.get('notes', ''), url=url, steam_appid=steam_appid, + platform=request.form.get('platform', 'pc'), redeem_date=datetime.strptime(request.form['redeem_date'], '%Y-%m-%d') if request.form['redeem_date'] else None, user_id=current_user.id ) db.session.add(new_game) db.session.commit() - flash(_('Game added successfully!'), 'success') + flash(translate('Game added successfully!'), 'success') return redirect(url_for('index')) - except IntegrityError: + except IntegrityError as e: db.session.rollback() - flash(_('Steam Key already exists!'), 'danger') + if "UNIQUE constraint failed: game.steam_key" in str(e): + flash(translate('Steam Key already exists!'), 'error') + else: + flash(translate('Database error: %(error)s', error=str(e)), 'error') + except Exception as e: db.session.rollback() - flash(_('Error: ') + str(e), 'danger') + flash(translate('Error: %(error)s', error=str(e)), 'error') - return render_template('add_game.html') + return render_template( + 'add_game.html', + platforms=PLATFORM_CHOICES, + statuses=STATUS_CHOICES + ) + @app.route('/edit/', methods=['GET', 'POST']) @login_required def edit_game(game_id): - game = db.session.get(Game, game_id) - if not game or game.owner != current_user: - abort(404) - - if not game or game.owner != current_user: - abort(403) - - active_redeem = RedeemToken.query.filter( - RedeemToken.game_id == game_id, - RedeemToken.expires > datetime.utcnow() - ).first() - - redeem_url = url_for('redeem_page', token=active_redeem.token, _external=True) if active_redeem else None + # Eager Loading für Tokens + game = Game.query.options(joinedload(Game.redeem_tokens)).get_or_404(game_id) + + def safe_parse_date(date_str): + try: + naive = datetime.strptime(date_str, '%Y-%m-%d') if date_str else None + return local_tz.localize(naive) if naive else None + except ValueError: + return None if request.method == 'POST': try: - url = request.form.get('url', '') - steam_appid = request.form.get('steam_appid', '').strip() - - if not steam_appid: - steam_appid = extract_steam_appid(url) - + # Validation + if not request.form.get('name') or not request.form.get('steam_key'): + flash(translate('Name and Steam Key are required'), 'error') + return redirect(url_for('edit_game', game_id=game_id)) + + # Duplicate check + existing = Game.query.filter( + Game.steam_key == request.form['steam_key'], + Game.id != game.id, + Game.user_id == current_user.id + ).first() + if existing: + flash(translate('Steam Key already exists'), 'error') + return redirect(url_for('edit_game', game_id=game_id)) + + # Update fields game.name = request.form['name'] game.steam_key = request.form['steam_key'] game.status = request.form['status'] + game.platform = request.form.get('platform', 'pc') game.recipient = request.form.get('recipient', '') game.notes = request.form.get('notes', '') - game.url = url - game.steam_appid = steam_appid - game.redeem_date = datetime.strptime(request.form['redeem_date'], '%Y-%m-%d') if request.form['redeem_date'] else None + game.url = request.form.get('url', '') + game.steam_appid = request.form.get('steam_appid', '') + game.redeem_date = safe_parse_date(request.form.get('redeem_date', '')) + # Token-Logic + if game.status == 'geschenkt': + # Vorhandene Tokens löschen + RedeemToken.query.filter_by(game_id=game.id).delete() + + # Generate new Token + token = secrets.token_urlsafe(12)[:17] + expires = datetime.now(local_tz) + timedelta(hours=24) + new_token = RedeemToken( + token=token, + game_id=game.id, + expires=expires, + total_hours=24 + ) + db.session.add(new_token) + db.session.commit() - flash(_('Changes saved!'), 'success') + flash(translate('Changes saved successfully'), 'success') return redirect(url_for('index')) - + + except IntegrityError as e: + db.session.rollback() + app.logger.error(f"IntegrityError: {traceback.format_exc()}") + flash(translate('Database error: {error}', error=str(e.orig)), 'error') except Exception as e: db.session.rollback() - flash(_('Error: ') + str(e), 'danger') - - return render_template('edit_game.html', - game=game, - redeem_url=redeem_url, - active_redeem=active_redeem, - redeem_date=game.redeem_date.strftime('%Y-%m-%d') if game.redeem_date else '') + app.logger.error(f"Unexpected error: {traceback.format_exc()}") + flash(translate('Unexpected error: {error}', error=str(e)), 'error') + + return render_template( + 'edit_game.html', + game=game, + platforms=PLATFORM_CHOICES, + statuses=STATUS_CHOICES, + redeem_date=game.redeem_date.strftime('%Y-%m-%d') if game.redeem_date else '' + ) @app.route('/delete/', methods=['POST']) @login_required def delete_game(game_id): - game = db.session.get(Game, game_id) - if not game or game.owner != current_user: - abort(404) - - if game.owner != current_user: - abort(403) - - try: - db.session.delete(game) - db.session.commit() - except Exception as e: - db.session.rollback() - + game = Game.query.get_or_404(game_id) + db.session.delete(game) + db.session.commit() + flash(translate('Game deleted successfully'), 'success') return redirect(url_for('index')) @@ -556,11 +1034,14 @@ def export_pdf(): elements = [] img_height = 2*cm - # Titel - elements.append(Paragraph(_("Game List (without Keys)"), styles['Title'])) + # Title + elements.append(Paragraph( + translate("Game List (without Keys)", lang=session.get('lang', 'en')), + styles['Title'] + )) elements.append(Spacer(1, 12)) - # Tabellenkopf + # Table header col_widths = [ 5*cm, 10*cm, 6*cm, 3*cm ] @@ -580,6 +1061,12 @@ def export_pdf(): img = Image(img_data, width=3*cm, height=img_height) except Exception: img = Paragraph('', styles['Normal']) + elif game.url and 'gog.com' in game.url: + try: + img_path = os.path.join(app.root_path, 'static', 'gog_logo.webp') + img = Image(img_path, width=3*cm, height=img_height) + except Exception: + img = Paragraph('', styles['Normal']) data.append([ img or '', @@ -588,7 +1075,7 @@ def export_pdf(): game.redeem_date.strftime('%d.%m.%y') if game.redeem_date else '' ]) - # Tabelle formatieren + # Table format table = Table(data, colWidths=col_widths, repeatRows=1) table.setStyle(TableStyle([ ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), @@ -604,13 +1091,14 @@ def export_pdf(): doc.build(elements) buffer.seek(0) - return send_file( + return send_file( buffer, mimetype='application/pdf', as_attachment=True, download_name=f'game_export_{datetime.now().strftime("%Y%m%d")}.pdf' ) + @app.route('/import', methods=['GET', 'POST']) @login_required def import_games(): @@ -650,402 +1138,530 @@ def import_games(): db.session.commit() - flash(_('%(new)d neue Spiele importiert, %(dup)d Duplikate übersprungen', new=new_games, dup=duplicates), 'success') + flash(translate("new_games_imported", new=new_games, dup=duplicates), 'success') except Exception as e: db.session.rollback() - flash(_('Importfehler: %(error)s', error=str(e)), 'danger') + flash(translate('Import error: {error}', error=str(e)), 'danger') return redirect(url_for('index')) - flash(_('Bitte eine gültige CSV-Datei hochladen.'), 'danger') + flash(translate('Please upload a valid CSV file.'), 'danger') return render_template('import.html') @app.route('/generate_redeem/', methods=['POST']) @login_required def generate_redeem(game_id): - game = db.session.get(Game, game_id) - if not game or game.owner != current_user: - abort(403) - - if game.owner != current_user or game.status != 'verschenkt': - abort(403) - + game = Game.query.get_or_404(game_id) + if game.user_id != current_user.id or game.status != 'geschenkt': + return jsonify({'error': translate('Forbidden')}), 403 + try: - token = secrets.token_urlsafe(12)[:17] - expires = datetime.utcnow() + timedelta(hours=24) - total_hours = 24 - RedeemToken.query.filter_by(game_id=game_id).delete() - + token = secrets.token_urlsafe(12)[:17] + expires = datetime.now(local_tz) + timedelta(hours=24) new_token = RedeemToken( token=token, game_id=game_id, expires=expires, total_hours=24 ) - db.session.add(new_token) db.session.commit() - - redeem_url = url_for('redeem_page', token=token, _external=True) - return jsonify({'url': redeem_url}) - + redeem_url = url_for('redeem', token=token, _external=True, _scheme='https') + message = translate( + 'Redeem link generated: {url}', + url=redeem_url + ) + return jsonify({'url': redeem_url, 'message': message}) except Exception as e: - app.logger.error(f"Redeem error: {str(e)}") + db.session.rollback() return jsonify({'error': str(e)}), 500 -@app.route('/redeem/') +@app.route('/redeem/', endpoint='redeem') def redeem_page(token): redeem_token = RedeemToken.query.filter_by(token=token).first() - if not redeem_token: abort(404) - if redeem_token.expires < datetime.utcnow(): + expires_utc = redeem_token.expires.astimezone(pytz.UTC) + if datetime.now(pytz.UTC) > expires_utc: db.session.delete(redeem_token) db.session.commit() abort(404) - game = Game.query.get(redeem_token.game_id) redeem_token.used = True db.session.commit() - return render_template('redeem.html', - game=game, - redeem_token=redeem_token, - platform_link='https://store.steampowered.com/account/registerkey?key=' if game.steam_appid else 'https://www.gog.com/redeem') + if game.platform == 'steam': + platform_link = 'https://store.steampowered.com/account/registerkey?key=' + platform_name = 'Steam' + elif game.platform == 'gog': + platform_link = 'https://www.gog.com/redeem/' + platform_name = 'GOG' + elif game.platform == 'xbox': + platform_link = 'https://redeem.microsoft.com/' + platform_name = 'Xbox' + elif game.platform == 'playstation': + platform_link = 'https://redeem.playstation.com/' + platform_name = 'PlayStation' + elif game.platform == 'switch': + platform_link = 'https://ec.nintendo.com/redeem/' + platform_name = 'Nintendo Switch' + else: + # Fallback für benutzerdefinierte Keys + platform_link = '' + platform_name = 'Key' -# Benachrichtigungsfunktionen -def send_pushover_notification(user, game): - """Sendet Pushover-Benachrichtigung für ablaufenden Key""" - if not app.config['PUSHOVER_APP_TOKEN'] or not app.config['PUSHOVER_USER_KEY']: - return False - - payload = { - "token": os.getenv('PUSHOVER_APP_TOKEN'), - "user": os.getenv('PUSHOVER_USER_KEY'), - "title": "Steam-Key läuft ab!", - "message": f"Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!", - "url": url_for('edit_game', game_id=game.id, _external=True), - "url_title": "Zum Spiel", - "priority": 1 - } + return render_template( + 'redeem.html', + game=game, + redeem_token=redeem_token, + expires_timestamp=int(expires_utc.timestamp() * 1000), + platform_link=platform_link, + platform_name=platform_name + ) + + +@app.route('/admin/users') +@login_required +@admin_required +def admin_users(): + users = User.query.all() + return render_template('admin_users.html', users=users) + +@app.route('/admin/users/delete/', methods=['POST']) +@login_required +@admin_required +def admin_delete_user(user_id): + if current_user.id == user_id: + flash(translate('You cannot delete yourself'), 'error') + return redirect(url_for('admin_users')) + user = User.query.get_or_404(user_id) + db.session.delete(user) + db.session.commit() + + log_activity( + current_user.id, + 'user_deleted', + f"Deleted user: {user.username} (ID: {user.id})" + ) + + flash(translate('User deleted successfully'), 'success') + return redirect(url_for('admin_users')) + +@app.route('/admin/users/reset_password/', methods=['POST']) +@login_required +@admin_required +def admin_reset_password(user_id): + user = User.query.get_or_404(user_id) + new_password = secrets.token_urlsafe(8) + user.password = generate_password_hash(new_password) + db.session.commit() + + log_activity( + current_user.id, + 'user_newpassword', + f"New password for user: {user.username} (ID: {user.id})" + ) + + + flash( + translate('New password for {username}: {password}', + username=user.username, + password=new_password), + 'info' + ) + return redirect(url_for('admin_users')) + +@app.route('/admin/audit-logs') +@login_required +@admin_required +def admin_audit_logs(): + page = request.args.get('page', 1, type=int) + logs = ActivityLog.query.order_by(ActivityLog.timestamp.desc()).paginate(page=page, per_page=20) + return render_template('admin_audit_logs.html', logs=logs) + +@app.route('/game//update', methods=['POST']) +@login_required +def update_game_data(game_id): + game = Game.query.get_or_404(game_id) + + # 1. Getting Steam AppID + steam_appid = request.form.get('steam_appid', '').strip() + app.logger.info(f"🚀 Update gestartet für Game {game_id} mit AppID: {steam_appid}") + + # 2. Steam-Data (Multilingual) + if steam_appid: + try: + app.logger.debug(f"🔍 Fetching Steam data for AppID: {steam_appid}") + for lang in ['en', 'de']: + steam_data = fetch_steam_data(steam_appid, lang=lang) + if steam_data: + if lang == 'en' and steam_data.get("name"): + game.name = steam_data.get("name", game.name) + setattr(game, f'steam_description_{lang}', steam_data.get("detailed_description") or "No Infos available") + if lang == 'en': + date_str = steam_data.get("release_date", {}) + if date_str: + parsed_date = parse_steam_release_date(date_str) + if parsed_date: + game.release_date = local_tz.localize(parsed_date) + else: + app.logger.warning(f"Could not parse Steam release date: {date_str}") + app.logger.info("✅ Steam data successfully updated") + except Exception as e: + app.logger.error(f"💥 Kritischer Steam-Fehler: {str(e)}", exc_info=True) + flash(translate('Error during Steam query'), 'danger') + else: + app.logger.warning("⚠️ Keine Steam-AppID vorhanden, Steam-Daten werden nicht aktualisiert") + flash(translate('Steam-AppID missing, no Steam Data transferred'), 'warning') + + + # ITAD-Slug doings and such + itad_slug = fetch_itad_slug(steam_appid) + if itad_slug: + game.itad_slug = itad_slug + + # 4. ITAD-Prices + price_data = None + if steam_appid: + try: + app.logger.debug("🔄 Starte ITAD-Abfrage...") + game.itad_game_id = fetch_itad_game_id(steam_appid) + + if game.itad_game_id: + app.logger.info(f"🔑 ITAD Game ID: {game.itad_game_id}") + price_data = fetch_itad_prices(game.itad_game_id) + + if price_data: + # Best price right now + all_deals = price_data.get("deals", []) + if all_deals: + best_deal = min( + all_deals, + key=lambda deal: deal.get("price", {}).get("amount", float('inf')) + ) + game.current_price = best_deal.get("price", {}).get("amount") + game.current_price_shop = best_deal.get("shop", {}).get("name") + app.logger.info(f"💶 Current Best: {game.current_price}€ at {game.current_price_shop}") + else: + game.current_price = None + game.current_price_shop = None + + app.logger.info(f"💶 Current Best: {game.current_price}€") + + game.historical_low = price_data.get("historyLow", {}).get("all", {}).get("amount") + app.logger.info(f"📉 Historical Low: {game.historical_low}€") + else: + app.logger.warning("⚠️ Keine ITAD-Preisdaten erhalten") + else: + app.logger.warning("⚠️ Keine ITAD Game ID erhalten") + + except Exception as e: + app.logger.error(f"💥 ITAD-API-Fehler: {str(e)}", exc_info=True) + flash(translate('Fehler bei Preisabfrage'), 'danger') + try: - response = requests.post( - 'https://api.pushover.net/1/messages.json', - data=payload - ) - return response.status_code == 200 + db.session.commit() + flash(translate('Externe Daten erfolgreich aktualisiert!'), 'success') + app.logger.info("💾 Datenbank-Update erfolgreich") except Exception as e: - app.logger.error(f"Pushover error: {str(e)}") + db.session.rollback() + app.logger.error(f"💥 Datenbank-Fehler: {str(e)}", exc_info=True) + flash(translate('Fehler beim Speichern der Daten'), 'danger') + + return redirect(url_for('edit_game', game_id=game_id)) + + +@app.route('/game/') +@login_required +def game_details(game_id): + game = Game.query.get_or_404(game_id) + return render_template('game_details.html', game=game) + + +@app.route('/debug-session') +def debug_session(): + return jsonify(dict(session)) + +# Apprise Notifications +import apprise + +def send_apprise_notification(user, game): + apprise_urls = os.getenv('APPRISE_URLS', '').strip() + if not apprise_urls: + app.logger.error("No APPRISE_URLS configured") return False -def send_gotify_notification(user, game): - """Sendet Gotify-Benachrichtigung für ablaufenden Key""" - if not GOTIFY_URL or not GOTIFY_TOKEN: - return False - - payload = { - "title": "Steam-Key läuft ab!", - "message": f"Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!", - "priority": 5 - } - - try: - response = requests.post( - f"{GOTIFY_URL}/message?token={GOTIFY_TOKEN}", - json=payload - ) - return response.status_code == 200 - except Exception as e: - app.logger.error(f"Gotify error: {str(e)}") - return False + apobj = apprise.Apprise() + for url in apprise_urls.replace(',', '\n').splitlines(): + if url.strip(): + apobj.add(url.strip()) -def send_matrix_notification(user, game): - """Sendet Matrix-Benachrichtigung für ablaufenden Key""" - if not MATRIX_HOMESERVER or not MATRIX_ACCESS_TOKEN or not MATRIX_ROOM_ID: - return False - - try: - from matrix_client.client import MatrixClient - - client = MatrixClient(MATRIX_HOMESERVER, token=MATRIX_ACCESS_TOKEN) - room = client.join_room(MATRIX_ROOM_ID) - - message = f"🎮 Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!" - room.send_text(message) - - return True - except Exception as e: - app.logger.error(f"Matrix error: {str(e)}") - return False + edit_url = url_for('edit_game', game_id=game.id, _external=True) + result = apobj.notify( + title="Steam-Key läuft ab!", + body=f"Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!\n\nLink: {edit_url}", + ) + return result def send_notification(user, game): - """Sendet Benachrichtigung über den bevorzugten Dienst des Benutzers""" - if user.notification_service == 'pushover': - return send_pushover_notification(user, game) - elif user.notification_service == 'gotify': - return send_gotify_notification(user, game) - elif user.notification_service == 'matrix': - return send_matrix_notification(user, game) - return False + return send_apprise_notification(user, game) def check_expiring_keys(): - with app.app_context(): - now = datetime.utcnow() - expiry_threshold = now + timedelta(hours=48) - - # Moderner Select-Aufruf - stmt = select(Game).where( - Game.status != 'eingelöst', - Game.redeem_date <= expiry_threshold, - Game.redeem_date > now - ) - - expiring_games = db.session.execute(stmt).scalars().all() - - for game in expiring_games: - user = User.query.get(game.user_id) - if user.notification_service and user.notification_service != 'none': - send_notification(user, game) + now = datetime.now(local_tz) + expiry_threshold = now + timedelta(hours=48) + + stmt = select(Game).where( + Game.status != 'eingelöst', + Game.redeem_date <= expiry_threshold, + Game.redeem_date > now + ) + + expiring_games = db.session.execute(stmt).scalars().all() + + for game in expiring_games: + user = User.query.get(game.user_id) + if user.notification_service and user.notification_service != 'none': + send_notification(user, game) -# Optional: Cleanup-Funktion für regelmäßiges Löschen abgelaufener Tokens +# Optional: cleaning up old tokens def cleanup_expired_tokens(): - now = datetime.utcnow() - expired = RedeemToken.query.filter(RedeemToken.expires < now).all() - for token in expired: - db.session.delete(token) - db.session.commit() + with app.app_context(): + try: + now = datetime.now(local_tz) + expired = RedeemToken.query.filter(RedeemToken.expires < now).all() + for token in expired: + db.session.delete(token) + db.session.commit() + app.logger.info(f"Cleaned up {len(expired)} expired tokens.") + except Exception as e: + app.logger.error(f"Error during cleanup_expired_tokens: {e}") + db.session.rollback() -# Scheduler initialisieren und starten -scheduler = BackgroundScheduler() -scheduler.add_job(func=check_expiring_keys, trigger="interval", hours=interval_hours) -scheduler.add_job(func=cleanup_expired_tokens, trigger="interval", hours=1) +# Scheduler start +scheduler = BackgroundScheduler(timezone=str(local_tz)) + +def check_expiring_keys_job(): + with app.app_context(): + check_expiring_keys() + +def cleanup_expired_tokens_job(): + with app.app_context(): + cleanup_expired_tokens() + +# Add Jobs +scheduler.add_job( + check_expiring_keys_job, + 'interval', + hours=int(os.getenv('CHECK_EXPIRING_KEYS_INTERVAL_HOURS', 12)), + id='check_expiring_keys' +) +scheduler.add_job( + cleanup_expired_tokens_job, + 'interval', + hours=1, + id='cleanup_expired_tokens' +) +# price updates +def update_prices_job(): + with app.app_context(): + games = Game.query.filter(Game.steam_appid.isnot(None)).all() + for game in games: + # just update prices + itad_data = fetch_itad_data(f"app/{game.steam_appid}") + if itad_data: + game.current_price = itad_data.get('price_new') + game.historical_low = itad_data.get('price_low', {}).get('amount') + db.session.commit() + +scheduler.add_job( + update_prices_job, + 'interval', + hours=12, + id='update_prices' +) + + +def update_missing_steam_descriptions_job(): + with app.app_context(): + games = Game.query.filter( + (Game.steam_description_en == None) | (Game.steam_description_en == '') | + (Game.steam_description_de == None) | (Game.steam_description_de == '') + ).all() + for game in games: + for lang in ['en', 'de']: + if not getattr(game, f'steam_description_{lang}', None): + steam_data = fetch_steam_data(game.steam_appid, lang=lang) + if steam_data: + setattr(game, f'steam_description_{lang}', steam_data.get('detailed_description')) + db.session.commit() + +scheduler.add_job( + update_missing_steam_descriptions_job, + 'interval', + hours=24, + id='update_missing_steam_descriptions' +) + +# start Scheduler scheduler.start() - -# Shutdown des Schedulers bei Beendigung der App -atexit.register(lambda: scheduler.shutdown()) +atexit.register(lambda: scheduler.shutdown(wait=False)) if __name__ == '__main__': with app.app_context(): db.create_all() - app.run(host='0.0.0.0', port=5000) + app.run(debug=True, host='0.0.0.0', port=5000) PYTHON_END -# Babel Konfiguration erstellen -cat < babel.cfg -[python: **.py] -[jinja2: **/templates/**.html] -extensions=jinja2.ext.autoescape,jinja2.ext.with_ -EOL -# 5. Dockerfile -cat < Dockerfile -FROM python:3.10-slim - -SHELL ["/bin/bash", "-c"] - -RUN apt-get update && apt-get install -y --no-install-recommends wget \ - && mkdir -p /app/static \ - && wget -O /app/static/logo.png "https://git.nocci.it/nocci/GiftGamesDB/raw/branch/main/steam-gift-manager/static/logo.png" \ - && wget -O /app/static/logo_small.png "https://git.nocci.it/nocci/GiftGamesDB/raw/branch/main/steam-gift-manager/static/logo_small.png" \ - && wget -O /app/static/forgejo.svg "https://git.nocci.it/nocci/GiftGamesDB/raw/branch/main/steam-gift-manager/static/forgejo.svg" \ - && rm -rf /var/lib/apt/lists/* - -RUN mkdir -p /app/data && \ - chown -R 1000:1000 /app/data - -ENV TZ=${TZ} -RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone - - -WORKDIR /app -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt - -COPY . . - -ARG UID=1000 -ARG GID=1000 -RUN groupadd -g \$GID appuser && \ - useradd -u \$UID -g \$GID -m appuser && \ - chown -R appuser:appuser /app - -USER appuser - -EXPOSE 5000 -CMD ["python", "app.py"] -DOCKER_END - -# 6. docker-compose.yml -cat < docker-compose.yml -services: - steam-manager: - build: . - ports: - - "5000:5000" - environment: - - REGISTRATION_ENABLED=${REGISTRATION_ENABLED:-True} - - TZ=${TZ} - volumes: - - ../data:/app/data - - ../translations:/app/translations - - ../.env:/app/.env - user: "1000:1000" - restart: unless-stopped -COMPOSE_END - -# 7. Verzeichnisse und Berechtigungen -mkdir -p ../data ../translations -chmod -R a+rwX ../data ../translations - -# 8. Übersetzungs- und Upgrade-Scripte -cat <<'SCRIPT_END' > ../translate.sh -#!/bin/bash -set -e - -cd "$(dirname "$0")/steam-gift-manager" - -declare -A locales=( - ["de"]="de" - ["en"]="en" -) - -# POT-Datei erstellen -docker-compose exec steam-manager pybabel extract -F babel.cfg -o translations/messages.pot . - -# Für jede Sprache prüfen und ggf. initialisieren -for lang in "${!locales[@]}"; do - if [ ! -f "translations/${locales[$lang]}/LC_MESSAGES/messages.po" ]; then - docker-compose exec steam-manager pybabel init \ - -i translations/messages.pot \ - -d translations \ - -l "${locales[$lang]}" - fi -done - -# Übersetzungen aktualisieren und kompilieren -docker-compose exec steam-manager pybabel update -i translations/messages.pot -d translations -docker-compose exec steam-manager pybabel compile -d translations - -echo "✅ Übersetzungen aktualisiert!" -SCRIPT_END -chmod +x ../translate.sh - -cat <<'SCRIPT_END' > ../upgrade.sh -#!/bin/bash -set -e - -# Setze das Arbeitsverzeichnis auf das Projektverzeichnis -cd "$(dirname "$0")/steam-gift-manager" - -# Setze FLASK_APP, falls nötig -export FLASK_APP=app.py - -# Initialisiere migrations, falls noch nicht vorhanden -if [ ! -d migrations ]; then - echo "Starting Flask-Migrate..." - docker-compose exec steam-manager flask db init -fi - -# Erzeuge Migration (nur wenn sich Modelle geändert haben) -docker-compose exec steam-manager flask db migrate -m "Automatic Migration" - -# Wende Migration an -docker-compose exec steam-manager flask db upgrade - -echo "✅ Database-Migration abgeschlossen!" -SCRIPT_END -chmod +x ../upgrade.sh - - -# 9. Templates +# Templates - this was the "fun" part mkdir -p templates static # Base Template cat < templates/base.html - + + + + {{ _('Game Key Manager') }} - + + + + + + {% if games and games[0].steam_appid %} + + {% endif %} + -
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} - {% for category, message in messages %} -
- {{ message }} - +
+ {% for category, message in messages %} + + {% endfor %}
- {% endfor %} {% endif %} {% endwith %} {% block content %}{% endblock %}
{% include "footer.html" %} @@ -1053,19 +1669,15 @@ cat < templates/base.html HTML_END # Index Template -cat < templates/index.html +cat <<'HTML_END' > templates/index.html {% extends "base.html" %} {% block content %} -
-

{{ _('My Games') }}

- + + - {% if games %}
@@ -1073,11 +1685,12 @@ cat < templates/index.html - + + @@ -1085,26 +1698,40 @@ cat < templates/index.html {% for game in games %} - + - + +
{{ _('Cover') }} {{ _('Name') }}{{ _('Key') }}{{ _('Key') }} {{ _('Status') }} {{ _('Created') }} {{ _('Redeem by') }} {{ _('Shop') }}{{ _('Price') }} {{ _('Actions') }}
- {% if game.steam_appid %} - Steam Header - {% endif %} + + {% if game.steam_appid %} + Steam Header + {% elif game.url and 'gog.com' in game.url %} + GOG Logo + {% endif %} + {{ game.name }}{{ game.steam_key }}{{ game.steam_key }} {% if game.status == 'nicht eingelöst' %} {{ _('Not redeemed') }} - {% elif game.status == 'verschenkt' %} + {% elif game.status == 'geschenkt' %} {{ _('Gifted') }} {% elif game.status == 'eingelöst' %} {{ _('Redeemed') }} {% endif %} {{ format_date(game.created_at) }}{{ game.created_at|strftime('%d.%m.%Y') }} {% if game.redeem_date %} - {{ format_date(game.redeem_date) }} + {{ game.redeem_date|strftime('%d.%m.%Y') }} {% endif %} @@ -1112,9 +1739,37 @@ cat < templates/index.html 🔗 {{ _('Shop') }} {% endif %} + {% if game.current_price is not none %} +
+
+ {{ _('Current Deal') }} +
+
+ {{ "%.2f"|format(game.current_price) }} € + {% if game.current_price_shop %} + ({{ game.current_price_shop }}) + {% endif %} +
+
+ {% endif %} + + {# Historical Low #} + {% if game.historical_low is not none %} +
+
+ {{ _('Hist. Low') }} +
+
+ {{ "%.2f"|format(game.historical_low) }} € +
+
+ {% endif %} +
- {% if game.status == 'verschenkt' %} -
- + + {% else %}
{{ _('No games yet') }}
{% endif %} {% endblock %} + HTML_END # Login Template cat < templates/login.html {% extends "base.html" %} {% block content %} -
-
-
-
- Logo -

{{ _('Login') }}

-
- -
- - -
-
- - -
- -
- -
-
+
+
+

{{ _('Login') }}

+
+ +
+ + +
+
+ + +
+
+ + +
+ {# Flash messages are handled in base.html, so the specific error block here can be removed #} + {# {% if error %} + + {% endif %} #} + + +
+ + {% if config.REGISTRATION_ENABLED %} + + {% endif %} +
{% endblock %} @@ -1201,175 +1940,380 @@ HTML_END cat < templates/register.html {% extends "base.html" %} {% block content %} -
-
-
-
-

{{ _('Register') }}

-
- -
- - -
-
- - -
- -
-
-
+
+
+

{{ _('Register') }}

+
+ +
+ + +
+
+ + +
+
+ + +
+ {% if error %} + + {% endif %} + +
+ +
{% endblock %} + HTML_END # Change Password Template cat < templates/change_password.html {% extends "base.html" %} {% block content %} -
-

{{ _('Change Password') }}

-
+
+
+
+

{{ _('Change Password') }}

+
- - + +
- - + +
- - + +
- + {{ _('Cancel') }} + +
+
{% endblock %} -HTML_END +HTML_END # Edit Game Template cat < templates/edit_game.html {% extends "base.html" %} {% block content %}
-

{{ _('Edit Game') }}

-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- {% if redeem_url and active_redeem %} -
- - - - {{ _('Expires at') }}: {{ active_redeem.expires.strftime('%d.%m.%Y %H:%M') }} - -
- {% endif %} -
-
- - {{ _('Cancel') }} -
+

{{ _('Spiel bearbeiten') }}

+ + + {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
+ {% for category, message in messages %} +
+ {{ message|safe }} + +
+ {% endfor %} +
+ {% endif %} + {% endwith %} + + +
+ + + + + + + +
+ +
+ +
+ +
+ + +
+
+ + +
+
+ + +
+
+ +
+ +
- +
+
+ + + + {{ _('For GOG games: Enter the Steam AppID here to enable price tracking.') }} + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + + +
+
+
+ 🔄 {{ _('External Data') }} +
+
+ {% if game.release_date %} +
+ {{ _('Release Date:') }} + {{ game.release_date|strftime('%d.%m.%Y') }} +
+ {% endif %} + {% if game.current_price %} +
+ {{ _('Now') }} +
+ {{ "%.2f"|format(game.current_price) }} € +
+
+ {% endif %} + {% if game.historical_low %} +
+ {{ _('Hist. Low') }} +
+ {{ "%.2f"|format(game.historical_low) }} € +
+
+ {% endif %} + {% if game.itad_slug %} + + 🔗 {{ _('View on IsThereAnyDeal') }} + + {% endif %} +
+
+
+ + + {% if game.status == 'geschenkt' %} +
+
+
{{ _('Redeem-Link') }}
+
+ {% for token in game.redeem_tokens if not token.is_expired() %} +
+ + +
+ + {{ _('Expires at') }}: {{ token.expires.astimezone(local_tz).strftime('%d.%m.%Y %H:%M') }} + + {% else %} +

{{ _('No active redeem links') }}

+ {% endfor %} +
+
+
+ {% endif %} + + + +
+
+ + + + {% endblock %} + + HTML_END cat < templates/add_game.html {% extends "base.html" %} {% block content %}
-

{{ _('Add New Game') }}

-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - {{ _('Cancel') }} -
-
-
+

{{ _('Add Game') }}

+ {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
+ {% for category, message in messages %} +
+ {{ message|safe }} +
+ {% endfor %} +
+ {% endif %} + {% endwith %} +
+ +
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + {{ _('Cancel') }} +
+
+
{% endblock %} + HTML_END # Import/Export Templates @@ -1381,11 +2325,11 @@ cat < templates/import.html
- +
- - {{ _('Abbrechen') }} + + {{ _('Cancel') }}
{% endblock %} @@ -1411,11 +2355,17 @@ cat <<'HTML_END' > templates/redeem.html

{{ _('Your Key:') }}

{{ game.steam_key }}
+ {% if platform_link %} - {{ _('Redeem now on') }} {% if game.steam_appid %}Steam{% else %}GOG{% endif %} + {{ _('Redeem now on') }} {{ platform_name }} + {% else %} +
+ {{ _('Your key:') }} {{ game.steam_key }} +
+ {% endif %}
{{ _('This page will expire in') }} @@ -1423,9 +2373,9 @@ cat <<'HTML_END' > templates/redeem.html
+ class="progress-bar bg-danger" + role="progressbar" + style="width: 100%">
@@ -1436,9 +2386,10 @@ cat <<'HTML_END' > templates/redeem.html
{% endblock %} HTML_END +# Game Details Templates +cat < templates/game_details.html +{% extends "base.html" %} +{% block content %} +
+
+

{{ game.name }}

+ +
+ +
+ {% if game.steam_appid %} + {{ game.name }} Cover + {% endif %} +
+ + +
+
+
{{ _('Status') }}
+
+ {% if game.status == 'nicht eingelöst' %} + {{ _('Not redeemed') }} + {% elif game.status == 'geschenkt' %} + {{ _('Gifted') }} + {% elif game.status == 'eingelöst' %} + {{ _('Redeemed') }} + {% endif %} +
+ +
{{ _('Release Date') }}
+
{{ game.release_date|strftime('%d.%m.%Y') if game.release_date else 'N/A' }}
+ +
{{ _('Current Price') }}
+
{{ "%.2f €"|format(game.current_price) if game.current_price else 'N/A' }}
+ +
+ + + {{ _('Edit') }} + +
+
+ {% set lang = session.get('lang', 'en') %} + {% set desc = getattr(game, 'steam_description_' + lang) %} + {% if desc %} +
+
+
+
{{ _('Game Description') }}
+
+ {{ desc|safe }} +
+
+
+
+ {% endif %} +
+
+{% endblock %} + +HTML_END + # Footer Template cat < templates/footer.html
@@ -1494,10 +2511,18 @@ cat < templates/footer.html Game Key Manager — is done by nocci
feel free to donate - if you can affort it: @@ -1508,6 +2533,166 @@ cat < templates/footer.html HTML_END +# Admin interface +cat < templates/admin_users.html +{% extends "base.html" %} + +{% block content %} +
+

{{ _('User Management') }}

+ + + + + + + + + {% for user in users %} + + + + + {% endfor %} + +
{{ _('Username') }}{{ _('Actions') }}
+ {{ user.username }} + {% if user.is_admin %}Admin{% endif %} + + {% if user.id != current_user.id %} +
+ + +
+ +
+ + +
+ {% endif %} +
+
+{% endblock %} + +HTML_END + +# Admin Audits +cat < templates/admin_audit_logs.html +{% extends "base.html" %} + +{% block content %} +
+

{{ _('Audit Logs') }}

+ +
+ + + + + + + + + + + {% for log in logs.items %} + + + + + + + {% endfor %} + +
{{ _('Timestamp') }}{{ _('User') }}{{ _('Action') }}{{ _('Details') }}
{{ log.timestamp|strftime('%d.%m.%Y %H:%M') }}{{ log.user.username if log.user else 'System' }}{{ log.action }}{{ log.details|default('', true) }}
+
+ + {% if logs.pages > 1 %} + + {% endif %} +
+{% endblock %} + +HTML_END + +# Error Sites +# 403 Tempate +cat < templates/403.html +{% extends "base.html" %} +{% block content %} +
+
+ Forbidden +

403

+

{{ _('Access Forbidden') }}

+

+ {{ _('Sorry, you are not allowed to access this page.') }} + ({{ _('Registration is currently disabled.') }}) +

+ + 🏠 {{ _('Back to Home') }} + +
+ + Sorry, you haven't unlocked this area yet. Grind some more XP or check your DLC entitlements.
Maybe try again after the next patch?
+
+
+
+
+{% endblock %} +HTML_END + +# 404 Template +cat < templates/404.html +{% extends "base.html" %} +{% block content %} +
+
+ Forbidden +

404

+

{{ _('Access Forbidden') }}

+

+ {{ _('Sorry, you are not allowed to access this page.') }} + ({{ _('Registration is currently disabled.') }}) +

+ + 🏠 {{ _('Back to Home') }} + +
+ + Sorry, you haven't unlocked this area yet. Grind some more XP or check your DLC entitlements.
Maybe try again after the next patch?
+
+
+
+
+{% endblock %} +HTML_END # CSS cat < static/style.css @@ -1555,7 +2740,7 @@ body { color: #ff6b6b; } -/* Progressbar-Animationen */ +/* Progressbar-Animations */ #expiry-bar { transition: width 1s linear, background-color 0.5s ease; } @@ -1573,16 +2758,448 @@ body { .table-pdf td, .table-pdf th { padding: 4px 8px; } + +.badge.bg-warning { + background-color: #ffcc00 !important; + color: #222 !important; +} +.badge.bg-success { + background-color: #198754 !important; + color: #fff !important; +} + + +.game-cover { + width: 368px; + height: 172px; + max-width: 100%; + max-height: 35vw; + object-fit: contain; + background: #222; + border-radius: 8px; + display: block; + margin: 0 auto; + transition: width 0.2s, height 0.2s; +} + +/* Responsive Cover Images */ +.game-cover { + width: 368px; + height: 172px; + object-fit: contain; + background: #222; + border-radius: 6px; +} + +@media (max-width: 1200px) { + .game-cover { + width: 260px; + height: 122px; + } +} + +@media (max-width: 992px) { + .game-cover { + width: 180px; + height: 84px; + } +} + +@media (max-width: 768px) { + .game-cover { + width: 120px; + height: 56px; + } +} + +@media (max-width: 576px) { + .game-cover { + width: 90px; + height: 42px; + } +} + +/* Accessibility Improvements */ +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} + +.price-value { + font-size: 1.2em; + font-weight: 400; + margin-top: 2px; +} + +.navbar-nav .nav-link { + white-space: nowrap; +} + +@media (max-width: 991.98px) { + .navbar-nav { + flex-direction: column !important; + align-items: flex-start !important; + } +} + +.card-body img, +.steam-description img { + max-width: 100%; + height: auto; + display: block; + margin: 8px auto; +} + +td.font-monospace { + word-break: break-all; + /* or */ + overflow-wrap: break-word; +} + +.key-col.hidden { + display: none !important; +} + +@media (max-width: 768px) { + .key-col { + display: none; + } +} + +.navbar .btn, +.navbar .dropdown-toggle, +.navbar .nav-link { + min-height: 40px; + line-height: 1.5 !important; + padding-top: 6px; + padding-bottom: 6px; + display: flex; + align-items: center; + font-size: 0.95em; +} + +.alert-error { background-color: #f8d7da; border-color: #f5c6cb; color: #721c24; } +.alert-success { background-color: #d4edda; border-color: #c3e6cb; color: #155724; } +.alert-info { background: #d9edf7; color: #31708f; } + CSS_END + +# directories and permissions +mkdir -p ../data +chmod -R a+rwX ../data +find ../data -type d -exec chmod 775 {} \; +find ../data -type f -exec chmod 664 {} \; + +# entrypoint.sh script +cat < entrypoint.sh +#!/bin/bash + +# Debug-Output +echo "🔄 DEBUGPY-Value: '$DEBUGPY'" +echo "🔄 FLASK_DEBUG-Value: '$FLASK_DEBUG'" + +# Debug-Modus activate if .env told you so +if [[ "$DEBUGPY" == "1" || "$FLASK_DEBUG" == "1" ]]; then + echo "🔄 Starting in DEBUG mode (Port 5678)..." + exec python -m debugpy --listen 0.0.0.0:5678 -m flask run --host=0.0.0.0 --port=5000 +else + echo "🚀 Starting in PRODUCTION mode..." + exec gunicorn -b 0.0.0.0:5000 app:app +fi + + +SCRIPT_END + +chmod +x entrypoint.sh + + +# create translate.sh and run it +cat <<'SCRIPT_END' > ../translate.sh +#!/bin/bash +set -e + +APP_DIR="steam-gift-manager" +TRANSLATION_DIR="$APP_DIR/translations" +LANGS=("de" "en") + +# check jq +if ! command -v jq &>/dev/null; then + echo "❌ jq is required. Install with: sudo apt-get install jq" + exit 1 +fi + +echo -e "\n\033[1;32m✅ Extracting translations...\033[0m" + +# 1. create json files +mkdir -p "$TRANSLATION_DIR" +for lang in "${LANGS[@]}"; do + file="$TRANSLATION_DIR/$lang.json" + [ -f "$file" ] || echo "{}" > "$file" +done + +# 2. extract all strings +STRINGS=$(grep -rhoP "_\(\s*['\"]((?:[^']|'[^'])*?)['\"]\s*[,)]" \ + "$APP_DIR/templates" "$APP_DIR/app.py" | \ + sed -E "s/_\(\s*['\"](.+?)['\"]\s*[,)]/\1/" | sort | uniq) + +# 3. put da keys in da json +for lang in "${LANGS[@]}"; do + file="$TRANSLATION_DIR/$lang.json" + tmp="$file.tmp" + jq --argjson keys "$(echo "$STRINGS" | jq -R . | jq -s .)" \ + 'reduce $keys[] as $k (.; .[$k] = (.[$k] // ""))' "$file" > "$tmp" + mv "$tmp" "$file" +done + +echo -e "\n\033[1;32m✅ Done! Translation keys added.\033[0m" + +SCRIPT_END + +chmod +x ../translate.sh + + +# EXECUTE IMMEDIATELY to create basic JSONs +cd .. +./translate.sh +cd $PROJECT_DIR + +# Dockerfile +cat <<'DOCKER_END' > Dockerfile +FROM python:3.10-slim + +SHELL ["/bin/bash", "-c"] + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + wget \ + && rm -rf /var/lib/apt/lists/* + +RUN apt-get update && apt-get install -y locales && \ + sed -i '/de_DE.UTF-8/s/^# //' /etc/locale.gen && \ + locale-gen +ENV LC_ALL=de_DE.UTF-8 LANG=de_DE.UTF-8 + + +RUN mkdir -p /app/data && \ + chown -R 1000:1000 /app/data + +ENV TZ=${TZ} +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +COPY entrypoint.sh /app/entrypoint.sh +RUN chmod +x /app/entrypoint.sh + +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +ARG UID=1000 +ARG GID=1000 + +RUN groupadd -g ${GID} appuser && \ + useradd -l -o -u ${UID} -g appuser -m appuser && \ + mkdir -p /app && \ + chown -R appuser:appuser /app + +USER appuser + +EXPOSE 5000 5678 +ENTRYPOINT ["/app/entrypoint.sh"] + +DOCKER_END + +# create docker-compose.yml +cat < docker-compose.yml +services: + redis: + image: redis:alpine + ports: + - "6379:6379" + volumes: + - redis_data:/data + networks: + - app-network + + steam-manager: + build: + context: . + args: + - UID=${UID:-1000} + - GID=${GID:-1000} + ports: + - "5000:5000" + - "5678:5678" + env_file: + - .env + environment: + - REDIS_URL=redis://redis:6379/0 + volumes: + - ../data:/app/data + - ./translations:/app/translations:rw + - ./static:/app/static:rw + user: "${UID:-1000}:${GID:-1000}" + restart: unless-stopped + command: ["/app/entrypoint.sh"] + networks: + - app-network + depends_on: + - redis + +volumes: + redis_data: + +networks: + app-network: + driver: bridge + + + +COMPOSE_END + + + +cat <<'SCRIPT_END' > ../upgrade.sh +#!/bin/bash +set -e + +# Set the working directory to the project directory +cd "$(dirname "$0")/steam-gift-manager" + +# set FLASK_APP, if needed +export FLASK_APP=app.py + +# Initialize migrations, if not yet available +if [ ! -d migrations ]; then + echo "Starting Flask-Migrate..." + docker-compose exec steam-manager flask db init +fi + +# Create migration (only if models have changed) +docker-compose exec steam-manager flask db migrate -m "Automatic Migration" + +# Apply migration +docker-compose exec steam-manager flask db upgrade + +echo "✅ Database migration completed!" +SCRIPT_END +chmod +x ../upgrade.sh + +# Manifest for PWA +cat < static/manifest.json +{ + "id": "/", + "name": "Game Key Manager", + "short_name": "GameKeys", + "start_url": "/", + "display": "standalone", + "background_color": "#212529", + "theme_color": "#212529", + "description": "Manage Steam/GOG keys easily!", + "orientation": "any", + "launch_handler": { + "client_mode": "navigate-existing" + }, + "icons": [ + { + "src": "/static/web-app-manifest-192x192.png", + "sizes": "192x192", + "type": "image/webp", + "purpose": "any" + }, + { + "src": "/static/web-app-manifest-192x192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "/static/web-app-manifest-512x512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ], + "theme_color": "#ffffff", + "background_color": "#3f3a3a", + "display": "standalone" +} +MANIFEST_END + +# Service Worker +cat < static/serviceworker.js +const CACHE_NAME = 'game-key-manager-v2'; +const ASSETS = [ + '/', + '/static/style.css', + '/static/logo.webp', + '/static/web-app-manifest-512x512.png', + '/static/web-app-manifest-192x192.png', + '/static/logo_small.webp', + '/static/gog_logo.webp', + '/static/forgejo.webp' +]; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME) + .then(cache => cache.addAll(ASSETS)) + ); +}); + +self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request) + .then(cachedResponse => cachedResponse || fetch(event.request)) + ); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then(keys => Promise.all( + keys.filter(key => key !== CACHE_NAME) + .map(key => caches.delete(key)) + )) + ); +}); +SW_END + +# Download German Translation from my server +cd "$TRANSLATIONS_DIR" + +read -p "Do you want to download German translations from the dev-server (could cause trouble, but normally it is safe)? [y/N]: " download_de +if [[ "$download_de" =~ ^[YyJj]$ ]]; then + wget -O de.json "https://assets.skynet.li/de.json" > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "✅ German translations downloaded successfully." + else + echo "❌ Download failed. Keeping existing de.json." + fi +else + echo "⏩ Skipped downloading German translations." +fi + + echo -e "\n\033[1;32m✅ Setup done! Seems to be okay!\033[0m" echo -e "Have a look in your .env" echo -e "nano .env" -echo -e "\n\033[1;32m✔️ After you are done start the system with:\033[0m" +echo -e "\n\033[1;32m✅ After you are done start the system with:\033[0m" echo -e "cd steam-gift-manager" echo -e "docker-compose build --no-cache && docker-compose up -d" -echo -e "\nGenerate translations: ./translate.sh" -echo -e "You can edit them in translations/en/LC_MESSAGES/messages.po" +echo -e "\n${GREEN}✅ JSON-based translations!${NC}" +echo -e "you can edit them here:" +echo -e " - translations/de.json" +echo -e " - translations/en.json" +echo -e "Enter your Apprise URLs in .env at APPRISE_URLS (e.g. for Pushover, Gotify, Matrix etc.)" +echo -e "You can put your IsThereAnyDeal API Key in there, too" echo -e "\nAfter any change in you configuration, .env or even translations:" echo -e "cd steam-gift-manager" echo -e "docker-compose down && docker-compose up -d --build" diff --git a/steam-gift-manager/.env b/steam-gift-manager/.env new file mode 100644 index 0000000..d1955a1 --- /dev/null +++ b/steam-gift-manager/.env @@ -0,0 +1,41 @@ +# Flask-Configuration +SECRET_KEY="1dc3d95006f7466670ac2d705ce43dc4a5ad8e2189dbe539" +REDEEM_SECRET="a50a961667ded234b1e59532ab7e27e1" +WTF_CSRF_SECRET_KEY="845ae46bd1bea30311e98df232d78b4e" + +# Language Settings +DEFAULT_LANGUAGE="en" +SUPPORTED_LANGUAGES="de,en" + +# Timezone +TZ="Europe/Berlin" + +# Security +FORCE_HTTPS="False" +SESSION_COOKIE_SECURE="auto" +CSRF_ENABLED="True" + +# Account registration +REGISTRATION_ENABLED="True" + +# checking interval if keys have to be redeemed before a specific date +CHECK_EXPIRING_KEYS_INTERVAL_HOURS="6" + +# Want to check prices? Here you are! +ITAD_API_KEY="your-secret-key-here" +ITAD_COUNTRY="DE" + +# Apprise URLs (separate several with a comma or space) +APPRISE_URLS="" + +### example for multiple notifications +#APPRISE_URLS="pover://USER_KEY@APP_TOKEN +#gotify://gotify.example.com/TOKEN +#matrixs://TOKEN@matrix.org/!ROOM_ID" + +# Redis URL +REDIS_URL="redis://redis:6379/0" + +# Enable Debug (e.g. for VS Code) +FLASK_DEBUG=1 +DEBUGPY=0 diff --git a/steam-gift-manager/Dockerfile b/steam-gift-manager/Dockerfile index 9d34b87..496be18 100644 --- a/steam-gift-manager/Dockerfile +++ b/steam-gift-manager/Dockerfile @@ -2,13 +2,25 @@ FROM python:3.10-slim SHELL ["/bin/bash", "-c"] -RUN apt-get update && apt-get install -y --no-install-recommends wget && mkdir -p /app/static && wget -O /app/static/logo.png "https://git.nocci.it/nocci/GiftGamesDB/raw/branch/main/steam-gift-manager/static/logo.png" && wget -O /app/static/logo_small.png "https://git.nocci.it/nocci/GiftGamesDB/raw/branch/main/steam-gift-manager/static/logo_small.png" && wget -O /app/static/forgejo.svg "https://git.nocci.it/nocci/GiftGamesDB/raw/branch/main/steam-gift-manager/static/forgejo.svg" && rm -rf /var/lib/apt/lists/* +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + wget \ + && rm -rf /var/lib/apt/lists/* -RUN mkdir -p /app/data && chown -R 1000:1000 /app/data +RUN apt-get update && apt-get install -y locales && \ + sed -i '/de_DE.UTF-8/s/^# //' /etc/locale.gen && \ + locale-gen +ENV LC_ALL=de_DE.UTF-8 LANG=de_DE.UTF-8 -ENV TZ= -RUN ln -snf /usr/share/zoneinfo/ /etc/localtime && echo > /etc/timezone +RUN mkdir -p /app/data && \ + chown -R 1000:1000 /app/data + +ENV TZ=${TZ} +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +COPY entrypoint.sh /app/entrypoint.sh +RUN chmod +x /app/entrypoint.sh WORKDIR /app COPY requirements.txt . @@ -18,9 +30,14 @@ COPY . . ARG UID=1000 ARG GID=1000 -RUN groupadd -g $GID appuser && useradd -u $UID -g $GID -m appuser && chown -R appuser:appuser /app + +RUN groupadd -g ${GID} appuser && \ + useradd -l -o -u ${UID} -g appuser -m appuser && \ + mkdir -p /app && \ + chown -R appuser:appuser /app USER appuser -EXPOSE 5000 -CMD ["python", "app.py"] +EXPOSE 5000 5678 +ENTRYPOINT ["/app/entrypoint.sh"] + diff --git a/steam-gift-manager/app.py b/steam-gift-manager/app.py index bd7f182..18614b0 100644 --- a/steam-gift-manager/app.py +++ b/steam-gift-manager/app.py @@ -1,48 +1,163 @@ -import os -import logging -import warnings -from sqlalchemy.exc import LegacyAPIWarning -warnings.simplefilter("ignore", category=LegacyAPIWarning) -from flask import Flask, render_template, request, redirect, url_for, flash, make_response, session, abort, send_file, jsonify -from flask_sqlalchemy import SQLAlchemy -from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user -from flask_babel import Babel, _ -from werkzeug.security import generate_password_hash, check_password_hash -from datetime import datetime, timedelta -from flask_wtf import CSRFProtect -from flask import abort -import io -import warnings -import re -import io -import csv -import secrets -import requests -from dotenv import load_dotenv -load_dotenv(override=True) -from sqlalchemy.exc import IntegrityError -from apscheduler.schedulers.background import BackgroundScheduler +# Standard library imports import atexit -from flask_migrate import Migrate -from sqlalchemy import MetaData -from reportlab.pdfgen import canvas -from reportlab.lib.pagesizes import A4, landscape, letter -from reportlab.platypus import ( - SimpleDocTemplate, - Table, - TableStyle, - Paragraph, - Image, - Spacer -) -from reportlab.lib import colors -from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle -from reportlab.lib.utils import ImageReader -from reportlab.lib.units import cm, inch, mm +import csv +import io +import locale +import logging +import os +import random +import re +import secrets +import sqlite3 +import time +import traceback +from datetime import datetime, timedelta +from functools import wraps from io import BytesIO -import reportlab.lib +from time import sleep +from urllib.parse import urlparse +from zoneinfo import ZoneInfo +import warnings +# 3rd-Provider-Modules +import pytz +import requests +from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore +from apscheduler.schedulers.background import BackgroundScheduler +from dotenv import load_dotenv +from flask import ( + Flask, + Markup, + abort, + flash, + g, + jsonify, + make_response, + redirect, + render_template, + request, + send_file, + session, + url_for +) +from flask_login import ( + LoginManager, + UserMixin, + current_user, + login_required, + login_user, + logout_user +) +from flask_migrate import Migrate +from flask_session import Session +from flask_sqlalchemy import SQLAlchemy +from flask_wtf import CSRFProtect, FlaskForm +from redis import Redis +from reportlab.lib import colors +from reportlab.lib.pagesizes import A4, landscape, letter +from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet +from reportlab.lib.units import cm, inch, mm +from reportlab.lib.utils import ImageReader +from reportlab.pdfgen import canvas +from reportlab.platypus import ( + Image, + Paragraph, + SimpleDocTemplate, + Spacer, + Table, + TableStyle +) +from sqlalchemy import MetaData, UniqueConstraint, event +from sqlalchemy.engine import Engine +from sqlalchemy.exc import IntegrityError, LegacyAPIWarning +from sqlalchemy.orm import joinedload +from werkzeug.security import check_password_hash, generate_password_hash +from werkzeug.middleware.proxy_fix import ProxyFix +from wtforms import SelectField, StringField, TextAreaField, validators + +# Config +load_dotenv(override=True) +warnings.simplefilter("ignore", category=LegacyAPIWarning) + +# Logging-Config +logging.basicConfig(level=logging.INFO) +logging.getLogger('apscheduler').setLevel(logging.WARNING) + + +@event.listens_for(Engine, "connect") +def enable_foreign_keys(dbapi_connection, connection_record): + if isinstance(dbapi_connection, sqlite3.Connection): + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON;") + cursor.close() + +ITAD_API_KEY_PLACEHOLDER = "your_api_key_here" +TZ = os.getenv('TZ', 'UTC') +os.environ['TZ'] = TZ app = Flask(__name__) +app.jinja_env.globals['getattr'] = getattr + +@app.errorhandler(404) +def not_found_error(error): + return render_template('404.html'), 404 + +app.wsgi_app = ProxyFix( + app.wsgi_app, + x_proto=1, # Trust X-Forwarded-Proto Header + x_host=1 # Trust X-Forwarded-Host Header +) + +# UNIX-Systems (Linux, Docker) +try: + time.tzset() +except AttributeError: + pass # tzset not availabe on Windows +local_tz = pytz.timezone(TZ) + +# Load Languages +import os +import json + + +TRANSLATION_DIR = os.path.join(os.getcwd(), 'translations') +SUPPORTED_LANGUAGES = ['de', 'en'] +TRANSLATIONS = {} + +for lang in SUPPORTED_LANGUAGES: + try: + with open(os.path.join(TRANSLATION_DIR, f'{lang}.json'), encoding='utf-8') as f: + TRANSLATIONS[lang] = json.load(f) + print(f"✅ Loaded {lang} translations") + except Exception: + print(f"❌ Failed loading {lang}.json: {str(e)}") + TRANSLATIONS[lang] = {} + +def translate(key, lang=None, **kwargs): + lang = lang or session.get('lang', 'en') + fallback_lang = app.config.get('DEFAULT_LANGUAGE', 'en') + + translations = TRANSLATIONS.get(lang, {}) + fallback_translations = TRANSLATIONS.get(fallback_lang, {}) + + value = translations.get(key) or fallback_translations.get(key) or key + return value.format(**kwargs) if isinstance(value, str) else value + +## DEBUG Translations +if app.debug: + print(f"Loaded translations for 'de': {TRANSLATIONS.get('de', {})}") + +### Admin decorator +def admin_required(f): + @wraps(f) + def decorated_function(*args, **kwargs): + if not current_user.is_authenticated: + abort(403) + if not current_user.is_admin: + abort(403) + return f(*args, **kwargs) + return decorated_function + + csrf = CSRFProtect(app) convention = { @@ -56,77 +171,231 @@ convention = { metadata = MetaData(naming_convention=convention) load_dotenv(override=True) -# Lade Umgebungsvariablen aus .env mit override +# load variables from .env with override load_dotenv(override=True) -# Konfiguration +# App-Configuration app.config.update( + # Most Important SECRET_KEY=os.getenv('SECRET_KEY'), - SQLALCHEMY_DATABASE_URI=('sqlite:////app/data/games.db'), - SQLALCHEMY_TRACK_MODIFICATIONS=False, - BABEL_DEFAULT_LOCALE=os.getenv('BABEL_DEFAULT_LOCALE'), - BABEL_SUPPORTED_LOCALES=os.getenv('BABEL_SUPPORTED_LOCALES').split(','), - BABEL_TRANSLATION_DIRECTORIES=os.getenv('BABEL_TRANSLATION_DIRECTORIES'), - SESSION_COOKIE_SECURE=os.getenv('SESSION_COOKIE_SECURE') == 'True', - WTF_CSRF_ENABLED=os.getenv('CSRF_ENABLED') == 'True', - REGISTRATION_ENABLED=os.getenv('REGISTRATION_ENABLED', 'True').lower() == 'true' + SQLALCHEMY_DATABASE_URI = 'sqlite:////app/data/games.db', + SQLALCHEMY_TRACK_MODIFICATIONS = False, + DEFAULT_LANGUAGE='en', + ITAD_COUNTRY = os.getenv("ITAD_COUNTRY", "DE"), + + # SESSION-HANDLING (In Production: Use Redis!) + SESSION_TYPE='redis', + SESSION_PERMANENT = False, + SESSION_USE_SIGNER = True, + SESSION_REDIS=Redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0")), + SESSION_FILE_DIR = '/app/data/flask-sessions', + SESSION_COOKIE_NAME = 'gamekeys_session', + SESSION_COOKIE_SECURE = os.getenv('SESSION_COOKIE_SECURE', 'False').lower() == 'true', + SESSION_COOKIE_HTTPONLY = True, + SESSION_COOKIE_SAMESITE = 'Lax', + PERMANENT_SESSION_LIFETIME = timedelta(days=30), + + + # LOGIN COOKIE STUFF + REMEMBER_COOKIE_DURATION=timedelta(days=30), + REMEMBER_COOKIE_HTTPONLY=True, + REMEMBER_COOKIE_SECURE=True if os.getenv('FORCE_HTTPS', 'False').lower() == 'true' else False, + REMEMBER_COOKIE_SAMESITE='Lax', + + # CSRF-PROTECTION + WTF_CSRF_ENABLED = True, + WTF_CSRF_SECRET_KEY = os.getenv('CSRF_SECRET_KEY', os.urandom(32).hex()), + WTF_CSRF_TIME_LIMIT = 3600, + + # SECURITYsa & PERFORMANCE + REGISTRATION_ENABLED = os.getenv('REGISTRATION_ENABLED', 'True').lower() == 'true', + SEND_FILE_MAX_AGE_DEFAULT = int(os.getenv('SEND_FILE_MAX_AGE_DEFAULT', 0)), + TEMPLATES_AUTO_RELOAD = os.getenv('TEMPLATES_AUTO_RELOAD', 'True').lower() == 'true', + PREFERRED_URL_SCHEME = 'https' if os.getenv('FORCE_HTTPS') else 'http' ) + +Session(app) + interval_hours = int(os.getenv('CHECK_EXPIRING_KEYS_INTERVAL_HOURS', 12)) -# Initialisierung +# Init db = SQLAlchemy(app, metadata=metadata) migrate = Migrate(app, db) login_manager = LoginManager(app) login_manager.login_view = 'login' -babel = Babel(app) # Logging app.logger.addHandler(logging.StreamHandler()) -app.logger.setLevel(logging.INFO) +app.logger.setLevel(logging.DEBUG) + +@app.errorhandler(403) +def forbidden_error(error): + return render_template('403.html'), 403 + + +@app.before_request +def set_language(): + if 'lang' not in session or not session['lang']: + session['lang'] = app.config.get('DEFAULT_LANGUAGE', 'en') + g.lang = session['lang'] + +def enforce_https(): + if os.getenv('FORCE_HTTPS', 'False').lower() == 'true' and not app.debug: + proto = request.headers.get('X-Forwarded-Proto', 'http') + if proto != 'https' and not request.is_secure: + url = request.url.replace('http://', 'https://', 1) + return redirect(url, code=301) + +def debug_translations(): + if app.debug: + app.logger.debug(f"Lang: {session.get('lang')}") + +app.before_request(enforce_https) + -@babel.localeselector -def get_locale(): - if 'lang' in session and session['lang'] in app.config['BABEL_SUPPORTED_LOCALES']: - return session['lang'] - return request.accept_languages.best_match(app.config['BABEL_SUPPORTED_LOCALES']) @app.context_processor -def inject_template_vars(): - return dict( - get_locale=get_locale, - theme='dark' if request.cookies.get('dark_mode') == 'true' else 'light' - ) +def inject_template_globals(): + return { + '_': lambda key, **kwargs: translate(key, lang=session.get('lang', 'en'), **kwargs), + 'now': datetime.now(local_tz), + 'app_version': os.getenv('APP_VERSION', '1.0.0'), + 'local_tz': local_tz + } -# Datenbankmodelle -class User(db.Model, UserMixin): +@app.template_filter('strftime') +def _jinja2_filter_datetime(date, fmt='%d.%m.%Y'): + if date is None: + return '' + return date.strftime(fmt) + +@app.errorhandler(403) +def forbidden(e): + return render_template('403.html'), 403 + + +# DB Models +class ActivityLog(db.Model): + __tablename__ = 'activity_logs' + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id')) + action = db.Column(db.String(100), nullable=False) + details = db.Column(db.Text) + timestamp = db.Column(db.DateTime, default=lambda: datetime.now(local_tz)) + + user = db.relationship('User', backref='activities') + + +class User(UserMixin, db.Model): __tablename__ = 'users' + id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(256), nullable=False) - games = db.relationship('Game', back_populates='owner', lazy=True) + is_admin = db.Column(db.Boolean, default=False) + games = db.relationship( + 'Game', + back_populates='owner', + cascade='all, delete-orphan', + passive_deletes=True + ) + class Game(db.Model): + __tablename__ = 'games' + __table_args__ = ( + UniqueConstraint('steam_key', 'user_id', name='uq_steam_key_user'), + ) + id = db.Column(db.Integer, primary_key=True) - owner = db.relationship('User', back_populates='games') name = db.Column(db.String(100), nullable=False) steam_key = db.Column(db.String(100), nullable=False, unique=True) status = db.Column(db.String(50), nullable=False) recipient = db.Column(db.String(100)) notes = db.Column(db.Text) url = db.Column(db.String(200)) - created_at = db.Column(db.DateTime, default=datetime.utcnow) + created_at = db.Column(db.DateTime, default=lambda: datetime.now(local_tz)) redeem_date = db.Column(db.DateTime) - user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) steam_appid = db.Column(db.String(20)) + platform = db.Column(db.String(50), default='pc') + current_price = db.Column(db.Float) + current_price_shop = db.Column(db.String(100)) + historical_low = db.Column(db.Float) + release_date = db.Column(db.DateTime) + release_date = db.Column(db.DateTime) + itad_slug = db.Column(db.String(200)) + steam_description_en = db.Column(db.Text) + steam_description_de = db.Column(db.Text) + + # with users.id + user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False) + + owner = db.relationship( + 'User', + back_populates='games' + ) + + redeem_tokens = db.relationship( + 'RedeemToken', + back_populates='game', + cascade='all, delete-orphan', + passive_deletes=True + ) class RedeemToken(db.Model): + __tablename__ = 'redeem_tokens' + id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(17), unique=True, nullable=False) - game_id = db.Column(db.Integer, db.ForeignKey('game.id'), nullable=False) - expires = db.Column(db.DateTime, nullable=False) - used = db.Column(db.Boolean, default=False) + expires = db.Column(db.DateTime(timezone=True), nullable=False) total_hours = db.Column(db.Integer, nullable=False) + + # ForeignKey with CASCADE + game_id = db.Column( + db.Integer, + db.ForeignKey('games.id', ondelete='CASCADE'), + nullable=False + ) + + game = db.relationship('Game', back_populates='redeem_tokens') + + def is_expired(self): + # use timeszone (from .env) + local_tz = pytz.timezone(os.getenv('TZ', 'UTC')) + now = datetime.now(local_tz) + return now > self.expires.astimezone(local_tz) + +class GameForm(FlaskForm): + name = StringField('Name', [validators.DataRequired()]) + steam_key = StringField('Steam Key') + status = SelectField('Status', choices=[ + ('nicht eingelöst', 'Nicht eingelöst'), + ('eingelöst', 'Eingelöst'), + ('geschenkt', 'Geschenkt') + ]) + recipient = StringField('Empfänger') + notes = TextAreaField('Notizen') + url = StringField('Store URL') + redeem_date = StringField('Einlösedatum') + steam_appid = StringField('Steam App ID') + +PLATFORM_CHOICES = [ + ('steam', 'Steam'), + ('gog', 'GOG'), + ('xbox', 'XBox'), + ('playstation', 'PlayStation'), + ('switch', 'Nintendo Switch'), + ('other', 'Other'), + ('pc', 'PC') +] + +STATUS_CHOICES = [ + ('nicht eingelöst', 'Nicht eingelöst'), + ('eingelöst', 'Eingelöst'), + ('geschenkt', 'Geschenkt') +] with app.app_context(): db.create_all() @@ -146,6 +415,131 @@ def get_or_404(model, id): abort(404) return instance +# Admin Audit Helper +def log_activity(user_id, action, details=None): + """ + Store an activity log entry for auditing purposes. + """ + log = ActivityLog( + user_id=user_id, + action=action, + details=details + ) + db.session.add(log) + db.session.commit() + +# Game Infos Helper +def fetch_steam_data(appid, lang='en'): + lang_map = { + 'en': 'english', + 'de': 'german' + } + steam_lang = lang_map.get(lang, 'english') + try: + response = requests.get( + "https://store.steampowered.com/api/appdetails", + params={"appids": appid, "l": steam_lang}, + timeout=15 + ) + data = response.json().get(str(appid), {}) + if data.get("success"): + return { + "name": data["data"].get("name"), + "detailed_description": data["data"].get("detailed_description"), + "release_date": data["data"].get("release_date", {}).get("date"), + } + except Exception as e: + app.logger.error(f"Steam API error: {str(e)}") + return None + +def parse_steam_release_date(date_str): + """Parsing Steam-Release-Date (the german us thingy, you know)""" + import locale + from datetime import datetime + + # try german format + try: + locale.setlocale(locale.LC_TIME, "de_DE.UTF-8") + return datetime.strptime(date_str, "%d. %b. %Y") + except Exception: + pass + # Fallback: okay lets try the english one + try: + locale.setlocale(locale.LC_TIME, "en_US.UTF-8") + return datetime.strptime(date_str, "%d %b, %Y") + except Exception: + pass + return None + +def fetch_itad_slug(steam_appid: int) -> str | None: + api_key = os.getenv("ITAD_API_KEY") + if not api_key or api_key.strip() == "your-secret-key-here": + app.logger.warning("ITAD-API-Key ist nicht gesetzt oder ist ein Platzhalter.") + return None + try: + response = requests.get( + "https://api.isthereanydeal.com/games/lookup/v1", + params={"key": api_key, "appid": steam_appid, "platform": "steam"}, + timeout=10 + ) + data = response.json() + return data.get("game", {}).get("slug") + except Exception as e: + app.logger.error(f"ITAD Error: {str(e)}") + return None + + +def fetch_itad_game_id(steam_appid: int) -> str | None: + api_key = os.getenv("ITAD_API_KEY") + if not api_key or api_key.strip() == "your-secret-key-here": + app.logger.warning("ITAD-API-Key ist nicht gesetzt oder ist ein Platzhalter.") + return None + + try: + response = requests.get( + "https://api.isthereanydeal.com/games/lookup/v1", + params={"key": api_key, "appid": steam_appid, "platform": "steam"}, + timeout=10 + ) + response.raise_for_status() + data = response.json() + if data.get("found") and data.get("game") and data["game"].get("id"): + return data["game"]["id"] + app.logger.error(f"ITAD Response Error: {data}") + return None + except Exception as e: + app.logger.error(f"ITAD Error: {str(e)}") + return None + +def fetch_itad_prices(game_id: str) -> dict | None: + api_key = os.getenv("ITAD_API_KEY") + country = os.getenv("ITAD_COUNTRY", "DE") + + if not api_key or api_key.strip() == "your-secret-key-here": + app.logger.warning("ITAD-API-Key ist nicht gesetzt oder ist ein Platzhalter.") + return None + + try: + response = requests.post( + "https://api.isthereanydeal.com/games/prices/v3", + params={ + "key": api_key, + "country": country, + "shops": "steam", + "vouchers": "false" + }, + json=[game_id], + headers={"Content-Type": "application/json"}, + timeout=15 + ) + response.raise_for_status() + return response.json()[0] + + except Exception as e: + app.logger.error(f"ITAD-Preisabfrage fehlgeschlagen: {str(e)}") + return None + + @app.route('/') @login_required def index(): @@ -163,50 +557,76 @@ def index(): @app.route('/set-lang/') def set_lang(lang): - if lang in app.config['BABEL_SUPPORTED_LOCALES']: + if lang in SUPPORTED_LANGUAGES: session['lang'] = lang + session.permanent = True return redirect(request.referrer or url_for('index')) - + @app.route('/set-theme/') def set_theme(theme): resp = make_response('', 204) - resp.set_cookie('dark_mode', 'true' if theme == 'dark' else 'false', max_age=60*60*24*365) + resp.set_cookie('theme', theme, max_age=60*60*24*365) return resp @app.route('/login', methods=['GET', 'POST']) def login(): + if current_user.is_authenticated: # Prevent already logged-in users from accessing login page + return redirect(url_for('index')) + if request.method == 'POST': - username = request.form['username'] - password = request.form['password'] + username = request.form.get('username') + password = request.form.get('password') + remember = request.form.get('remember_me') == 'true' + user = User.query.filter_by(username=username).first() - + if user and check_password_hash(user.password, password): - login_user(user) - return redirect(url_for('index')) - - flash(_('Invalid credentials'), 'danger') + # Pass remember=True to login_user and set duration + # The duration will be taken from app.config['REMEMBER_COOKIE_DURATION'] + login_user(user, remember=remember) + + # Log activity + log_activity(user.id, 'user_login', f"User '{user.username}' logged in.") + + next_page = request.args.get('next') + # Add security check for next_page to prevent open redirect + if not next_page or urlparse(next_page).netloc != '': + next_page = url_for('index') + flash(translate('Logged in successfully.'), 'success') + return redirect(next_page) + else: + flash(translate('Invalid username or password.'), 'danger') return render_template('login.html') @app.route('/register', methods=['GET', 'POST']) def register(): if not app.config['REGISTRATION_ENABLED']: - flash(_('Registrierungen sind deaktiviert'), 'danger') - return redirect(url_for('login')) - + abort(403) + if request.method == 'POST': username = request.form['username'] - password = generate_password_hash(request.form['password']) - - if User.query.filter_by(username=username).first(): - flash(_('Username already exists'), 'danger') + password = request.form['password'] + + existing_user = User.query.filter_by(username=username).first() + if existing_user: + flash(translate('Username already exists'), 'error') return redirect(url_for('register')) - - new_user = User(username=username, password=password) + + # make the first user admin + is_admin = User.query.count() == 0 + + new_user = User( + username=username, + password=generate_password_hash(password), + is_admin=is_admin + ) + db.session.add(new_user) db.session.commit() login_user(new_user) + flash(translate('Registration successful'), 'success') return redirect(url_for('index')) - + return render_template('register.html') @app.route('/logout') @@ -224,16 +644,16 @@ def change_password(): confirm_password = request.form['confirm_password'] if not check_password_hash(current_user.password, current_password): - flash(_('Aktuelles Passwort ist falsch'), 'danger') + flash(translate('Current passwort is wrong'), 'danger') return redirect(url_for('change_password')) if new_password != confirm_password: - flash(_('Neue Passwörter stimmen nicht überein'), 'danger') + flash(translate('New Passwords are not matching'), 'danger') return redirect(url_for('change_password')) current_user.password = generate_password_hash(new_password) db.session.commit() - flash(_('Passwort erfolgreich geändert'), 'success') + flash(translate('Password changed successfully', session.get('lang', 'en')), 'success') return redirect(url_for('index')) return render_template('change_password.html') @@ -248,98 +668,134 @@ def add_game(): if not steam_appid: steam_appid = extract_steam_appid(url) - + + steam_key = request.form['steam_key'] + if Game.query.filter_by(steam_key=steam_key).first(): + flash(translate('Steam Key already exists!'), 'error') + return redirect(url_for('add_game')) + new_game = Game( name=request.form['name'], - steam_key=request.form['steam_key'], + steam_key=steam_key, status=request.form['status'], recipient=request.form.get('recipient', ''), notes=request.form.get('notes', ''), url=url, steam_appid=steam_appid, + platform=request.form.get('platform', 'pc'), redeem_date=datetime.strptime(request.form['redeem_date'], '%Y-%m-%d') if request.form['redeem_date'] else None, user_id=current_user.id ) db.session.add(new_game) db.session.commit() - flash(_('Game added successfully!'), 'success') + flash(translate('Game added successfully!'), 'success') return redirect(url_for('index')) - except IntegrityError: + except IntegrityError as e: db.session.rollback() - flash(_('Steam Key already exists!'), 'danger') + if "UNIQUE constraint failed: game.steam_key" in str(e): + flash(translate('Steam Key already exists!'), 'error') + else: + flash(translate('Database error: %(error)s', error=str(e)), 'error') + except Exception as e: db.session.rollback() - flash(_('Error: ') + str(e), 'danger') + flash(translate('Error: %(error)s', error=str(e)), 'error') - return render_template('add_game.html') + return render_template( + 'add_game.html', + platforms=PLATFORM_CHOICES, + statuses=STATUS_CHOICES + ) + @app.route('/edit/', methods=['GET', 'POST']) @login_required def edit_game(game_id): - game = db.session.get(Game, game_id) - if not game or game.owner != current_user: - abort(404) - - if not game or game.owner != current_user: - abort(403) - - active_redeem = RedeemToken.query.filter( - RedeemToken.game_id == game_id, - RedeemToken.expires > datetime.utcnow() - ).first() - - redeem_url = url_for('redeem_page', token=active_redeem.token, _external=True) if active_redeem else None + # Eager Loading für Tokens + game = Game.query.options(joinedload(Game.redeem_tokens)).get_or_404(game_id) + + def safe_parse_date(date_str): + try: + naive = datetime.strptime(date_str, '%Y-%m-%d') if date_str else None + return local_tz.localize(naive) if naive else None + except ValueError: + return None if request.method == 'POST': try: - url = request.form.get('url', '') - steam_appid = request.form.get('steam_appid', '').strip() - - if not steam_appid: - steam_appid = extract_steam_appid(url) - + # Validation + if not request.form.get('name') or not request.form.get('steam_key'): + flash(translate('Name and Steam Key are required'), 'error') + return redirect(url_for('edit_game', game_id=game_id)) + + # Duplicate check + existing = Game.query.filter( + Game.steam_key == request.form['steam_key'], + Game.id != game.id, + Game.user_id == current_user.id + ).first() + if existing: + flash(translate('Steam Key already exists'), 'error') + return redirect(url_for('edit_game', game_id=game_id)) + + # Update fields game.name = request.form['name'] game.steam_key = request.form['steam_key'] game.status = request.form['status'] + game.platform = request.form.get('platform', 'pc') game.recipient = request.form.get('recipient', '') game.notes = request.form.get('notes', '') - game.url = url - game.steam_appid = steam_appid - game.redeem_date = datetime.strptime(request.form['redeem_date'], '%Y-%m-%d') if request.form['redeem_date'] else None + game.url = request.form.get('url', '') + game.steam_appid = request.form.get('steam_appid', '') + game.redeem_date = safe_parse_date(request.form.get('redeem_date', '')) + # Token-Logic + if game.status == 'geschenkt': + # Vorhandene Tokens löschen + RedeemToken.query.filter_by(game_id=game.id).delete() + + # Generate new Token + token = secrets.token_urlsafe(12)[:17] + expires = datetime.now(local_tz) + timedelta(hours=24) + new_token = RedeemToken( + token=token, + game_id=game.id, + expires=expires, + total_hours=24 + ) + db.session.add(new_token) + db.session.commit() - flash(_('Changes saved!'), 'success') + flash(translate('Changes saved successfully'), 'success') return redirect(url_for('index')) - + + except IntegrityError as e: + db.session.rollback() + app.logger.error(f"IntegrityError: {traceback.format_exc()}") + flash(translate('Database error: {error}', error=str(e.orig)), 'error') except Exception as e: db.session.rollback() - flash(_('Error: ') + str(e), 'danger') - - return render_template('edit_game.html', - game=game, - redeem_url=redeem_url, - active_redeem=active_redeem, - redeem_date=game.redeem_date.strftime('%Y-%m-%d') if game.redeem_date else '') + app.logger.error(f"Unexpected error: {traceback.format_exc()}") + flash(translate('Unexpected error: {error}', error=str(e)), 'error') + + return render_template( + 'edit_game.html', + game=game, + platforms=PLATFORM_CHOICES, + statuses=STATUS_CHOICES, + redeem_date=game.redeem_date.strftime('%Y-%m-%d') if game.redeem_date else '' + ) @app.route('/delete/', methods=['POST']) @login_required def delete_game(game_id): - game = db.session.get(Game, game_id) - if not game or game.owner != current_user: - abort(404) - - if game.owner != current_user: - abort(403) - - try: - db.session.delete(game) - db.session.commit() - except Exception as e: - db.session.rollback() - + game = Game.query.get_or_404(game_id) + db.session.delete(game) + db.session.commit() + flash(translate('Game deleted successfully'), 'success') return redirect(url_for('index')) @@ -397,11 +853,14 @@ def export_pdf(): elements = [] img_height = 2*cm - # Titel - elements.append(Paragraph(_("Game List (without Keys)"), styles['Title'])) + # Title + elements.append(Paragraph( + translate("Game List (without Keys)", lang=session.get('lang', 'en')), + styles['Title'] + )) elements.append(Spacer(1, 12)) - # Tabellenkopf + # Table header col_widths = [ 5*cm, 10*cm, 6*cm, 3*cm ] @@ -421,6 +880,12 @@ def export_pdf(): img = Image(img_data, width=3*cm, height=img_height) except Exception: img = Paragraph('', styles['Normal']) + elif game.url and 'gog.com' in game.url: + try: + img_path = os.path.join(app.root_path, 'static', 'gog_logo.webp') + img = Image(img_path, width=3*cm, height=img_height) + except Exception: + img = Paragraph('', styles['Normal']) data.append([ img or '', @@ -429,7 +894,7 @@ def export_pdf(): game.redeem_date.strftime('%d.%m.%y') if game.redeem_date else '' ]) - # Tabelle formatieren + # Table format table = Table(data, colWidths=col_widths, repeatRows=1) table.setStyle(TableStyle([ ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), @@ -445,13 +910,14 @@ def export_pdf(): doc.build(elements) buffer.seek(0) - return send_file( + return send_file( buffer, mimetype='application/pdf', as_attachment=True, download_name=f'game_export_{datetime.now().strftime("%Y%m%d")}.pdf' ) + @app.route('/import', methods=['GET', 'POST']) @login_required def import_games(): @@ -491,188 +957,382 @@ def import_games(): db.session.commit() - flash(_('%(new)d neue Spiele importiert, %(dup)d Duplikate übersprungen', new=new_games, dup=duplicates), 'success') + flash(translate("new_games_imported", new=new_games, dup=duplicates), 'success') except Exception as e: db.session.rollback() - flash(_('Importfehler: %(error)s', error=str(e)), 'danger') + flash(translate('Import error: {error}', error=str(e)), 'danger') return redirect(url_for('index')) - flash(_('Bitte eine gültige CSV-Datei hochladen.'), 'danger') + flash(translate('Please upload a valid CSV file.'), 'danger') return render_template('import.html') @app.route('/generate_redeem/', methods=['POST']) @login_required def generate_redeem(game_id): - game = db.session.get(Game, game_id) - if not game or game.owner != current_user: - abort(403) - - if game.owner != current_user or game.status != 'verschenkt': - abort(403) - + game = Game.query.get_or_404(game_id) + if game.user_id != current_user.id or game.status != 'geschenkt': + return jsonify({'error': translate('Forbidden')}), 403 + try: - token = secrets.token_urlsafe(12)[:17] - expires = datetime.utcnow() + timedelta(hours=24) - total_hours = 24 - RedeemToken.query.filter_by(game_id=game_id).delete() - + token = secrets.token_urlsafe(12)[:17] + expires = datetime.now(local_tz) + timedelta(hours=24) new_token = RedeemToken( token=token, game_id=game_id, expires=expires, total_hours=24 ) - db.session.add(new_token) db.session.commit() - - redeem_url = url_for('redeem_page', token=token, _external=True) - return jsonify({'url': redeem_url}) - + redeem_url = url_for('redeem', token=token, _external=True, _scheme='https') + message = translate( + 'Redeem link generated: {url}', + url=redeem_url + ) + return jsonify({'url': redeem_url, 'message': message}) except Exception as e: - app.logger.error(f"Redeem error: {str(e)}") + db.session.rollback() return jsonify({'error': str(e)}), 500 -@app.route('/redeem/') +@app.route('/redeem/', endpoint='redeem') def redeem_page(token): redeem_token = RedeemToken.query.filter_by(token=token).first() - if not redeem_token: abort(404) - if redeem_token.expires < datetime.utcnow(): + expires_utc = redeem_token.expires.astimezone(pytz.UTC) + if datetime.now(pytz.UTC) > expires_utc: db.session.delete(redeem_token) db.session.commit() abort(404) - game = Game.query.get(redeem_token.game_id) redeem_token.used = True db.session.commit() - return render_template('redeem.html', - game=game, - redeem_token=redeem_token, - platform_link='https://store.steampowered.com/account/registerkey?key=' if game.steam_appid else 'https://www.gog.com/redeem') + if game.platform == 'steam': + platform_link = 'https://store.steampowered.com/account/registerkey?key=' + platform_name = 'Steam' + elif game.platform == 'gog': + platform_link = 'https://www.gog.com/redeem/' + platform_name = 'GOG' + elif game.platform == 'xbox': + platform_link = 'https://redeem.microsoft.com/' + platform_name = 'Xbox' + elif game.platform == 'playstation': + platform_link = 'https://redeem.playstation.com/' + platform_name = 'PlayStation' + elif game.platform == 'switch': + platform_link = 'https://ec.nintendo.com/redeem/' + platform_name = 'Nintendo Switch' + else: + # Fallback für benutzerdefinierte Keys + platform_link = '' + platform_name = 'Key' -# Benachrichtigungsfunktionen -def send_pushover_notification(user, game): - """Sendet Pushover-Benachrichtigung für ablaufenden Key""" - if not app.config['PUSHOVER_APP_TOKEN'] or not app.config['PUSHOVER_USER_KEY']: - return False - - payload = { - "token": os.getenv('PUSHOVER_APP_TOKEN'), - "user": os.getenv('PUSHOVER_USER_KEY'), - "title": "Steam-Key läuft ab!", - "message": f"Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!", - "url": url_for('edit_game', game_id=game.id, _external=True), - "url_title": "Zum Spiel", - "priority": 1 - } + return render_template( + 'redeem.html', + game=game, + redeem_token=redeem_token, + expires_timestamp=int(expires_utc.timestamp() * 1000), + platform_link=platform_link, + platform_name=platform_name + ) + + +@app.route('/admin/users') +@login_required +@admin_required +def admin_users(): + users = User.query.all() + return render_template('admin_users.html', users=users) + +@app.route('/admin/users/delete/', methods=['POST']) +@login_required +@admin_required +def admin_delete_user(user_id): + if current_user.id == user_id: + flash(translate('You cannot delete yourself'), 'error') + return redirect(url_for('admin_users')) + user = User.query.get_or_404(user_id) + db.session.delete(user) + db.session.commit() + + log_activity( + current_user.id, + 'user_deleted', + f"Deleted user: {user.username} (ID: {user.id})" + ) + + flash(translate('User deleted successfully'), 'success') + return redirect(url_for('admin_users')) + +@app.route('/admin/users/reset_password/', methods=['POST']) +@login_required +@admin_required +def admin_reset_password(user_id): + user = User.query.get_or_404(user_id) + new_password = secrets.token_urlsafe(8) + user.password = generate_password_hash(new_password) + db.session.commit() + + log_activity( + current_user.id, + 'user_newpassword', + f"New password for user: {user.username} (ID: {user.id})" + ) + + + flash( + translate('New password for {username}: {password}', + username=user.username, + password=new_password), + 'info' + ) + return redirect(url_for('admin_users')) + +@app.route('/admin/audit-logs') +@login_required +@admin_required +def admin_audit_logs(): + page = request.args.get('page', 1, type=int) + logs = ActivityLog.query.order_by(ActivityLog.timestamp.desc()).paginate(page=page, per_page=20) + return render_template('admin_audit_logs.html', logs=logs) + +@app.route('/game//update', methods=['POST']) +@login_required +def update_game_data(game_id): + game = Game.query.get_or_404(game_id) + + # 1. Getting Steam AppID + steam_appid = request.form.get('steam_appid', '').strip() + app.logger.info(f"🚀 Update gestartet für Game {game_id} mit AppID: {steam_appid}") + + # 2. Steam-Data (Multilingual) + if steam_appid: + try: + app.logger.debug(f"🔍 Fetching Steam data for AppID: {steam_appid}") + for lang in ['en', 'de']: + steam_data = fetch_steam_data(steam_appid, lang=lang) + if steam_data: + if lang == 'en' and steam_data.get("name"): + game.name = steam_data.get("name", game.name) + setattr(game, f'steam_description_{lang}', steam_data.get("detailed_description") or "No Infos available") + if lang == 'en': + date_str = steam_data.get("release_date", {}) + if date_str: + parsed_date = parse_steam_release_date(date_str) + if parsed_date: + game.release_date = local_tz.localize(parsed_date) + else: + app.logger.warning(f"Could not parse Steam release date: {date_str}") + app.logger.info("✅ Steam data successfully updated") + except Exception as e: + app.logger.error(f"💥 Kritischer Steam-Fehler: {str(e)}", exc_info=True) + flash(translate('Error during Steam query'), 'danger') + else: + app.logger.warning("⚠️ Keine Steam-AppID vorhanden, Steam-Daten werden nicht aktualisiert") + flash(translate('Steam-AppID missing, no Steam Data transferred'), 'warning') + + + # ITAD-Slug doings and such + itad_slug = fetch_itad_slug(steam_appid) + if itad_slug: + game.itad_slug = itad_slug + + # 4. ITAD-Prices + price_data = None + if steam_appid: + try: + app.logger.debug("🔄 Starte ITAD-Abfrage...") + game.itad_game_id = fetch_itad_game_id(steam_appid) + + if game.itad_game_id: + app.logger.info(f"🔑 ITAD Game ID: {game.itad_game_id}") + price_data = fetch_itad_prices(game.itad_game_id) + + if price_data: + # Best price right now + all_deals = price_data.get("deals", []) + if all_deals: + best_deal = min( + all_deals, + key=lambda deal: deal.get("price", {}).get("amount", float('inf')) + ) + game.current_price = best_deal.get("price", {}).get("amount") + game.current_price_shop = best_deal.get("shop", {}).get("name") + app.logger.info(f"💶 Current Best: {game.current_price}€ at {game.current_price_shop}") + else: + game.current_price = None + game.current_price_shop = None + + app.logger.info(f"💶 Current Best: {game.current_price}€") + + game.historical_low = price_data.get("historyLow", {}).get("all", {}).get("amount") + app.logger.info(f"📉 Historical Low: {game.historical_low}€") + else: + app.logger.warning("⚠️ Keine ITAD-Preisdaten erhalten") + else: + app.logger.warning("⚠️ Keine ITAD Game ID erhalten") + + except Exception as e: + app.logger.error(f"💥 ITAD-API-Fehler: {str(e)}", exc_info=True) + flash(translate('Fehler bei Preisabfrage'), 'danger') + try: - response = requests.post( - 'https://api.pushover.net/1/messages.json', - data=payload - ) - return response.status_code == 200 + db.session.commit() + flash(translate('Externe Daten erfolgreich aktualisiert!'), 'success') + app.logger.info("💾 Datenbank-Update erfolgreich") except Exception as e: - app.logger.error(f"Pushover error: {str(e)}") + db.session.rollback() + app.logger.error(f"💥 Datenbank-Fehler: {str(e)}", exc_info=True) + flash(translate('Fehler beim Speichern der Daten'), 'danger') + + return redirect(url_for('edit_game', game_id=game_id)) + + +@app.route('/game/') +@login_required +def game_details(game_id): + game = Game.query.get_or_404(game_id) + return render_template('game_details.html', game=game) + + +@app.route('/debug-session') +def debug_session(): + return jsonify(dict(session)) + +# Apprise Notifications +import apprise + +def send_apprise_notification(user, game): + apprise_urls = os.getenv('APPRISE_URLS', '').strip() + if not apprise_urls: + app.logger.error("No APPRISE_URLS configured") return False -def send_gotify_notification(user, game): - """Sendet Gotify-Benachrichtigung für ablaufenden Key""" - if not GOTIFY_URL or not GOTIFY_TOKEN: - return False - - payload = { - "title": "Steam-Key läuft ab!", - "message": f"Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!", - "priority": 5 - } - - try: - response = requests.post( - f"{GOTIFY_URL}/message?token={GOTIFY_TOKEN}", - json=payload - ) - return response.status_code == 200 - except Exception as e: - app.logger.error(f"Gotify error: {str(e)}") - return False + apobj = apprise.Apprise() + for url in apprise_urls.replace(',', '\n').splitlines(): + if url.strip(): + apobj.add(url.strip()) -def send_matrix_notification(user, game): - """Sendet Matrix-Benachrichtigung für ablaufenden Key""" - if not MATRIX_HOMESERVER or not MATRIX_ACCESS_TOKEN or not MATRIX_ROOM_ID: - return False - - try: - from matrix_client.client import MatrixClient - - client = MatrixClient(MATRIX_HOMESERVER, token=MATRIX_ACCESS_TOKEN) - room = client.join_room(MATRIX_ROOM_ID) - - message = f"🎮 Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!" - room.send_text(message) - - return True - except Exception as e: - app.logger.error(f"Matrix error: {str(e)}") - return False + edit_url = url_for('edit_game', game_id=game.id, _external=True) + result = apobj.notify( + title="Steam-Key läuft ab!", + body=f"Dein Key für '{game.name}' läuft in weniger als 48 Stunden ab!\n\nLink: {edit_url}", + ) + return result def send_notification(user, game): - """Sendet Benachrichtigung über den bevorzugten Dienst des Benutzers""" - if user.notification_service == 'pushover': - return send_pushover_notification(user, game) - elif user.notification_service == 'gotify': - return send_gotify_notification(user, game) - elif user.notification_service == 'matrix': - return send_matrix_notification(user, game) - return False + return send_apprise_notification(user, game) def check_expiring_keys(): - with app.app_context(): - now = datetime.utcnow() - expiry_threshold = now + timedelta(hours=48) - - # Moderner Select-Aufruf - stmt = select(Game).where( - Game.status != 'eingelöst', - Game.redeem_date <= expiry_threshold, - Game.redeem_date > now - ) - - expiring_games = db.session.execute(stmt).scalars().all() - - for game in expiring_games: - user = User.query.get(game.user_id) - if user.notification_service and user.notification_service != 'none': - send_notification(user, game) + now = datetime.now(local_tz) + expiry_threshold = now + timedelta(hours=48) + + stmt = select(Game).where( + Game.status != 'eingelöst', + Game.redeem_date <= expiry_threshold, + Game.redeem_date > now + ) + + expiring_games = db.session.execute(stmt).scalars().all() + + for game in expiring_games: + user = User.query.get(game.user_id) + if user.notification_service and user.notification_service != 'none': + send_notification(user, game) -# Optional: Cleanup-Funktion für regelmäßiges Löschen abgelaufener Tokens +# Optional: cleaning up old tokens def cleanup_expired_tokens(): - now = datetime.utcnow() - expired = RedeemToken.query.filter(RedeemToken.expires < now).all() - for token in expired: - db.session.delete(token) - db.session.commit() + with app.app_context(): + try: + now = datetime.now(local_tz) + expired = RedeemToken.query.filter(RedeemToken.expires < now).all() + for token in expired: + db.session.delete(token) + db.session.commit() + app.logger.info(f"Cleaned up {len(expired)} expired tokens.") + except Exception as e: + app.logger.error(f"Error during cleanup_expired_tokens: {e}") + db.session.rollback() -# Scheduler initialisieren und starten -scheduler = BackgroundScheduler() -scheduler.add_job(func=check_expiring_keys, trigger="interval", hours=interval_hours) -scheduler.add_job(func=cleanup_expired_tokens, trigger="interval", hours=1) +# Scheduler start +scheduler = BackgroundScheduler(timezone=str(local_tz)) + +def check_expiring_keys_job(): + with app.app_context(): + check_expiring_keys() + +def cleanup_expired_tokens_job(): + with app.app_context(): + cleanup_expired_tokens() + +# Add Jobs +scheduler.add_job( + check_expiring_keys_job, + 'interval', + hours=int(os.getenv('CHECK_EXPIRING_KEYS_INTERVAL_HOURS', 12)), + id='check_expiring_keys' +) +scheduler.add_job( + cleanup_expired_tokens_job, + 'interval', + hours=1, + id='cleanup_expired_tokens' +) +# price updates +def update_prices_job(): + with app.app_context(): + games = Game.query.filter(Game.steam_appid.isnot(None)).all() + for game in games: + # just update prices + itad_data = fetch_itad_data(f"app/{game.steam_appid}") + if itad_data: + game.current_price = itad_data.get('price_new') + game.historical_low = itad_data.get('price_low', {}).get('amount') + db.session.commit() + +scheduler.add_job( + update_prices_job, + 'interval', + hours=12, + id='update_prices' +) + + +def update_missing_steam_descriptions_job(): + with app.app_context(): + games = Game.query.filter( + (Game.steam_description_en == None) | (Game.steam_description_en == '') | + (Game.steam_description_de == None) | (Game.steam_description_de == '') + ).all() + for game in games: + for lang in ['en', 'de']: + if not getattr(game, f'steam_description_{lang}', None): + steam_data = fetch_steam_data(game.steam_appid, lang=lang) + if steam_data: + setattr(game, f'steam_description_{lang}', steam_data.get('detailed_description')) + db.session.commit() + +scheduler.add_job( + update_missing_steam_descriptions_job, + 'interval', + hours=24, + id='update_missing_steam_descriptions' +) + +# start Scheduler scheduler.start() - -# Shutdown des Schedulers bei Beendigung der App -atexit.register(lambda: scheduler.shutdown()) +atexit.register(lambda: scheduler.shutdown(wait=False)) if __name__ == '__main__': with app.app_context(): db.create_all() - app.run(host='0.0.0.0', port=5000) + app.run(debug=True, host='0.0.0.0', port=5000) diff --git a/steam-gift-manager/babel.cfg b/steam-gift-manager/babel.cfg deleted file mode 100644 index f0234b3..0000000 --- a/steam-gift-manager/babel.cfg +++ /dev/null @@ -1,3 +0,0 @@ -[python: **.py] -[jinja2: **/templates/**.html] -extensions=jinja2.ext.autoescape,jinja2.ext.with_ diff --git a/steam-gift-manager/docker-compose.yml b/steam-gift-manager/docker-compose.yml index d4ad381..a9886bd 100644 --- a/steam-gift-manager/docker-compose.yml +++ b/steam-gift-manager/docker-compose.yml @@ -1,14 +1,44 @@ services: + redis: + image: redis:alpine + ports: + - "6379:6379" + volumes: + - redis_data:/data + networks: + - app-network + steam-manager: - build: . + build: + context: . + args: + - UID=0 + - GID=1000 ports: - "5000:5000" + - "5678:5678" + env_file: + - .env environment: - - REGISTRATION_ENABLED=True - - TZ= + - REDIS_URL=redis://redis:6379/0 volumes: - - ../data:/app/data - - ../translations:/app/translations - - ../.env:/app/.env - user: "1000:1000" + - ../data:/app/data + - ./translations:/app/translations:rw + - ./static:/app/static:rw + user: "0:1000" restart: unless-stopped + command: ["/app/entrypoint.sh"] + networks: + - app-network + depends_on: + - redis + +volumes: + redis_data: + +networks: + app-network: + driver: bridge + + + diff --git a/steam-gift-manager/entrypoint.sh b/steam-gift-manager/entrypoint.sh new file mode 100644 index 0000000..877de46 --- /dev/null +++ b/steam-gift-manager/entrypoint.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Debug-Output +echo "🔄 DEBUGPY-Value: ''" +echo "🔄 FLASK_DEBUG-Value: ''" + +# Debug-Modus activate if .env told you so +if [[ "" == "1" || "" == "1" ]]; then + echo "🔄 Starting in DEBUG mode (Port 5678)..." + exec python -m debugpy --listen 0.0.0.0:5678 -m flask run --host=0.0.0.0 --port=5000 +else + echo "🚀 Starting in PRODUCTION mode..." + exec gunicorn -b 0.0.0.0:5000 app:app +fi + + diff --git a/steam-gift-manager/requirements.txt b/steam-gift-manager/requirements.txt index 8c31714..2a2c066 100644 --- a/steam-gift-manager/requirements.txt +++ b/steam-gift-manager/requirements.txt @@ -5,12 +5,16 @@ flask-migrate werkzeug python-dotenv flask-sqlalchemy -flask-babel jinja2<3.1.0 itsdangerous sqlalchemy apscheduler -matrix-client reportlab requests pillow +gunicorn +apprise +debugpy +pytz +Flask-Session +redis diff --git a/steam-gift-manager/static/apple-touch-icon.png b/steam-gift-manager/static/apple-touch-icon.png new file mode 100644 index 0000000..14e6c59 Binary files /dev/null and b/steam-gift-manager/static/apple-touch-icon.png differ diff --git a/steam-gift-manager/static/favicon.ico b/steam-gift-manager/static/favicon.ico new file mode 100644 index 0000000..b3433b0 Binary files /dev/null and b/steam-gift-manager/static/favicon.ico differ diff --git a/steam-gift-manager/static/forgejo.svg b/steam-gift-manager/static/forgejo.svg deleted file mode 100644 index 804b05e..0000000 --- a/steam-gift-manager/static/forgejo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/steam-gift-manager/static/forgejo.webp b/steam-gift-manager/static/forgejo.webp new file mode 100644 index 0000000..34d45aa Binary files /dev/null and b/steam-gift-manager/static/forgejo.webp differ diff --git a/steam-gift-manager/static/gog_logo.webp b/steam-gift-manager/static/gog_logo.webp new file mode 100644 index 0000000..ce9a8a9 Binary files /dev/null and b/steam-gift-manager/static/gog_logo.webp differ diff --git a/steam-gift-manager/static/logo.png b/steam-gift-manager/static/logo.png deleted file mode 100644 index 1e09159..0000000 Binary files a/steam-gift-manager/static/logo.png and /dev/null differ diff --git a/steam-gift-manager/static/logo.webp b/steam-gift-manager/static/logo.webp new file mode 100644 index 0000000..7196e01 Binary files /dev/null and b/steam-gift-manager/static/logo.webp differ diff --git a/steam-gift-manager/static/logo_small.png b/steam-gift-manager/static/logo_small.png deleted file mode 100644 index 5db0156..0000000 Binary files a/steam-gift-manager/static/logo_small.png and /dev/null differ diff --git a/steam-gift-manager/static/logo_small.webp b/steam-gift-manager/static/logo_small.webp new file mode 100644 index 0000000..424e4bb Binary files /dev/null and b/steam-gift-manager/static/logo_small.webp differ diff --git a/steam-gift-manager/static/logo_small_maskable.webp b/steam-gift-manager/static/logo_small_maskable.webp new file mode 100644 index 0000000..8ac87ad Binary files /dev/null and b/steam-gift-manager/static/logo_small_maskable.webp differ diff --git a/steam-gift-manager/static/manifest.json b/steam-gift-manager/static/manifest.json new file mode 100644 index 0000000..05ba690 --- /dev/null +++ b/steam-gift-manager/static/manifest.json @@ -0,0 +1,37 @@ +{ + "id": "/", + "name": "Game Key Manager", + "short_name": "GameKeys", + "start_url": "/", + "display": "standalone", + "background_color": "#212529", + "theme_color": "#212529", + "description": "Manage Steam/GOG keys easily!", + "orientation": "any", + "launch_handler": { + "client_mode": "navigate-existing" + }, + "icons": [ + { + "src": "/static/web-app-manifest-192x192.png", + "sizes": "192x192", + "type": "image/webp", + "purpose": "any" + }, + { + "src": "/static/web-app-manifest-192x192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "/static/web-app-manifest-512x512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ], + "theme_color": "#ffffff", + "background_color": "#3f3a3a", + "display": "standalone" +} diff --git a/steam-gift-manager/static/serviceworker.js b/steam-gift-manager/static/serviceworker.js new file mode 100644 index 0000000..db9ab63 --- /dev/null +++ b/steam-gift-manager/static/serviceworker.js @@ -0,0 +1,34 @@ +const CACHE_NAME = 'game-key-manager-v2'; +const ASSETS = [ + '/', + '/static/style.css', + '/static/logo.webp', + '/static/web-app-manifest-512x512.png', + '/static/web-app-manifest-192x192.png', + '/static/logo_small.webp', + '/static/gog_logo.webp', + '/static/forgejo.webp' +]; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME) + .then(cache => cache.addAll(ASSETS)) + ); +}); + +self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request) + .then(cachedResponse => cachedResponse || fetch(event.request)) + ); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then(keys => Promise.all( + keys.filter(key => key !== CACHE_NAME) + .map(key => caches.delete(key)) + )) + ); +}); diff --git a/steam-gift-manager/static/style.css b/steam-gift-manager/static/style.css index 5ed653c..6511a14 100644 --- a/steam-gift-manager/static/style.css +++ b/steam-gift-manager/static/style.css @@ -42,7 +42,7 @@ body { color: #ff6b6b; } -/* Progressbar-Animationen */ +/* Progressbar-Animations */ #expiry-bar { transition: width 1s linear, background-color 0.5s ease; } @@ -60,3 +60,133 @@ body { .table-pdf td, .table-pdf th { padding: 4px 8px; } + +.badge.bg-warning { + background-color: #ffcc00 !important; + color: #222 !important; +} +.badge.bg-success { + background-color: #198754 !important; + color: #fff !important; +} + + +.game-cover { + width: 368px; + height: 172px; + max-width: 100%; + max-height: 35vw; + object-fit: contain; + background: #222; + border-radius: 8px; + display: block; + margin: 0 auto; + transition: width 0.2s, height 0.2s; +} + +/* Responsive Cover Images */ +.game-cover { + width: 368px; + height: 172px; + object-fit: contain; + background: #222; + border-radius: 6px; +} + +@media (max-width: 1200px) { + .game-cover { + width: 260px; + height: 122px; + } +} + +@media (max-width: 992px) { + .game-cover { + width: 180px; + height: 84px; + } +} + +@media (max-width: 768px) { + .game-cover { + width: 120px; + height: 56px; + } +} + +@media (max-width: 576px) { + .game-cover { + width: 90px; + height: 42px; + } +} + +/* Accessibility Improvements */ +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} + +.price-value { + font-size: 1.2em; + font-weight: 400; + margin-top: 2px; +} + +.navbar-nav .nav-link { + white-space: nowrap; +} + +@media (max-width: 991.98px) { + .navbar-nav { + flex-direction: column !important; + align-items: flex-start !important; + } +} + +.card-body img, +.steam-description img { + max-width: 100%; + height: auto; + display: block; + margin: 8px auto; +} + +td.font-monospace { + word-break: break-all; + /* or */ + overflow-wrap: break-word; +} + +.key-col.hidden { + display: none !important; +} + +@media (max-width: 768px) { + .key-col { + display: none; + } +} + +.navbar .btn, +.navbar .dropdown-toggle, +.navbar .nav-link { + min-height: 40px; + line-height: 1.5 !important; + padding-top: 6px; + padding-bottom: 6px; + display: flex; + align-items: center; + font-size: 0.95em; +} + +.alert-error { background-color: #f8d7da; border-color: #f5c6cb; color: #721c24; } +.alert-success { background-color: #d4edda; border-color: #c3e6cb; color: #155724; } +.alert-info { background: #d9edf7; color: #31708f; } + diff --git a/steam-gift-manager/static/web-app-manifest-192x192.png b/steam-gift-manager/static/web-app-manifest-192x192.png new file mode 100644 index 0000000..92a5881 Binary files /dev/null and b/steam-gift-manager/static/web-app-manifest-192x192.png differ diff --git a/steam-gift-manager/static/web-app-manifest-512x512.png b/steam-gift-manager/static/web-app-manifest-512x512.png new file mode 100644 index 0000000..a55a741 Binary files /dev/null and b/steam-gift-manager/static/web-app-manifest-512x512.png differ diff --git a/steam-gift-manager/templates/403.html b/steam-gift-manager/templates/403.html new file mode 100644 index 0000000..2aa4783 --- /dev/null +++ b/steam-gift-manager/templates/403.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block content %} +
+
+ Forbidden +

403

+

{{ _('Access Forbidden') }}

+

+ {{ _('Sorry, you are not allowed to access this page.') }} + ({{ _('Registration is currently disabled.') }}) +

+ + 🏠 {{ _('Back to Home') }} + +
+ + Sorry, you haven't unlocked this area yet. Grind some more XP or check your DLC entitlements.
Maybe try again after the next patch?
+
+
+
+
+{% endblock %} diff --git a/steam-gift-manager/templates/404.html b/steam-gift-manager/templates/404.html new file mode 100644 index 0000000..e7145be --- /dev/null +++ b/steam-gift-manager/templates/404.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block content %} +
+
+ Forbidden +

404

+

{{ _('Access Forbidden') }}

+

+ {{ _('Sorry, you are not allowed to access this page.') }} + ({{ _('Registration is currently disabled.') }}) +

+ + 🏠 {{ _('Back to Home') }} + +
+ + Sorry, you haven't unlocked this area yet. Grind some more XP or check your DLC entitlements.
Maybe try again after the next patch?
+
+
+
+
+{% endblock %} diff --git a/steam-gift-manager/templates/add_game.html b/steam-gift-manager/templates/add_game.html index 081aeaa..88f6d24 100644 --- a/steam-gift-manager/templates/add_game.html +++ b/steam-gift-manager/templates/add_game.html @@ -1,47 +1,94 @@ {% extends "base.html" %} {% block content %}
-

{{ _('Add New Game') }}

-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - {{ _('Cancel') }} -
-
-
+

{{ _('Add Game') }}

+ {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
+ {% for category, message in messages %} +
+ {{ message|safe }} +
+ {% endfor %} +
+ {% endif %} + {% endwith %} +
+ +
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + {{ _('Cancel') }} +
+
+
{% endblock %} + diff --git a/steam-gift-manager/templates/admin_audit_logs.html b/steam-gift-manager/templates/admin_audit_logs.html new file mode 100644 index 0000000..5c8b935 --- /dev/null +++ b/steam-gift-manager/templates/admin_audit_logs.html @@ -0,0 +1,55 @@ +{% extends "base.html" %} + +{% block content %} +
+

{{ _('Audit Logs') }}

+ +
+ + + + + + + + + + + {% for log in logs.items %} + + + + + + + {% endfor %} + +
{{ _('Timestamp') }}{{ _('User') }}{{ _('Action') }}{{ _('Details') }}
{{ log.timestamp|strftime('%d.%m.%Y %H:%M') }}{{ log.user.username if log.user else 'System' }}{{ log.action }}{{ log.details|default('', true) }}
+
+ + {% if logs.pages > 1 %} + + {% endif %} +
+{% endblock %} + diff --git a/steam-gift-manager/templates/admin_users.html b/steam-gift-manager/templates/admin_users.html new file mode 100644 index 0000000..e2f1398 --- /dev/null +++ b/steam-gift-manager/templates/admin_users.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} + +{% block content %} +
+

{{ _('User Management') }}

+ + + + + + + + + {% for user in users %} + + + + + {% endfor %} + +
{{ _('Username') }}{{ _('Actions') }}
+ {{ user.username }} + {% if user.is_admin %}Admin{% endif %} + + {% if user.id != current_user.id %} +
+ + +
+ +
+ + +
+ {% endif %} +
+
+{% endblock %} + diff --git a/steam-gift-manager/templates/base.html b/steam-gift-manager/templates/base.html index ec5b8c4..cc78a87 100644 --- a/steam-gift-manager/templates/base.html +++ b/steam-gift-manager/templates/base.html @@ -1,80 +1,140 @@ - + + + + {{ _('Game Key Manager') }} - + + + + + + {% if games and games[0].steam_appid %} + + {% endif %} + -
+
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} - {% for category, message in messages %} -
- {{ message }} - +
+ {% for category, message in messages %} + + {% endfor %}
- {% endfor %} {% endif %} {% endwith %} {% block content %}{% endblock %}
{% include "footer.html" %} diff --git a/steam-gift-manager/templates/change_password.html b/steam-gift-manager/templates/change_password.html index 7d6943c..ca3f406 100644 --- a/steam-gift-manager/templates/change_password.html +++ b/steam-gift-manager/templates/change_password.html @@ -1,22 +1,28 @@ {% extends "base.html" %} {% block content %} -
-

{{ _('Change Password') }}

-
+
+
+
+

{{ _('Change Password') }}

+
- - + +
- - + +
- - + +
- + {{ _('Cancel') }} + +
+
{% endblock %} + diff --git a/steam-gift-manager/templates/edit_game.html b/steam-gift-manager/templates/edit_game.html index 63e5384..8e28040 100644 --- a/steam-gift-manager/templates/edit_game.html +++ b/steam-gift-manager/templates/edit_game.html @@ -1,66 +1,190 @@ {% extends "base.html" %} {% block content %}
-

{{ _('Edit Game') }}

-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- {% if redeem_url and active_redeem %} -
- - - - {{ _('Expires at') }}: {{ active_redeem.expires.strftime('%d.%m.%Y %H:%M') }} - -
- {% endif %} -
-
- - {{ _('Cancel') }} -
+

{{ _('Spiel bearbeiten') }}

+ + + {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
+ {% for category, message in messages %} +
+ {{ message|safe }} + +
+ {% endfor %} +
+ {% endif %} + {% endwith %} + + +
+ + + + + + + +
+ +
+ +
+ +
+ + +
+
+ + +
+
+ + +
+
+ +
+ +
- +
+
+ + + + {{ _('For GOG games: Enter the Steam AppID here to enable price tracking.') }} + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + + +
+
+
+ 🔄 {{ _('External Data') }} +
+
+ {% if game.release_date %} +
+ {{ _('Release Date:') }} + {{ game.release_date|strftime('%d.%m.%Y') }} +
+ {% endif %} + {% if game.current_price %} +
+ {{ _('Now') }} +
+ {{ "%.2f"|format(game.current_price) }} € +
+
+ {% endif %} + {% if game.historical_low %} +
+ {{ _('Hist. Low') }} +
+ {{ "%.2f"|format(game.historical_low) }} € +
+
+ {% endif %} + {% if game.itad_slug %} + + 🔗 {{ _('View on IsThereAnyDeal') }} + + {% endif %} +
+
+
+ + + {% if game.status == 'geschenkt' %} +
+
+
{{ _('Redeem-Link') }}
+
+ {% for token in game.redeem_tokens if not token.is_expired() %} +
+ + +
+ + {{ _('Expires at') }}: {{ token.expires.astimezone(local_tz).strftime('%d.%m.%Y %H:%M') }} + + {% else %} +

{{ _('No active redeem links') }}

+ {% endfor %} +
+
+
+ {% endif %} + + + +
+
+ + + + {% endblock %} diff --git a/steam-gift-manager/templates/footer.html b/steam-gift-manager/templates/footer.html index 4f0d5fa..4397594 100644 --- a/steam-gift-manager/templates/footer.html +++ b/steam-gift-manager/templates/footer.html @@ -4,10 +4,18 @@ Game Key Manager — is done by nocci
feel free to donate - if you can affort it: diff --git a/steam-gift-manager/templates/game_details.html b/steam-gift-manager/templates/game_details.html new file mode 100644 index 0000000..b4ed10e --- /dev/null +++ b/steam-gift-manager/templates/game_details.html @@ -0,0 +1,62 @@ +{% extends "base.html" %} +{% block content %} +
+
+

{{ game.name }}

+ +
+ +
+ {% if game.steam_appid %} + {{ game.name }} Cover + {% endif %} +
+ + +
+
+
{{ _('Status') }}
+
+ {% if game.status == 'nicht eingelöst' %} + {{ _('Not redeemed') }} + {% elif game.status == 'geschenkt' %} + {{ _('Gifted') }} + {% elif game.status == 'eingelöst' %} + {{ _('Redeemed') }} + {% endif %} +
+ +
{{ _('Release Date') }}
+
{{ game.release_date|strftime('%d.%m.%Y') if game.release_date else 'N/A' }}
+ +
{{ _('Current Price') }}
+
{{ "%.2f €"|format(game.current_price) if game.current_price else 'N/A' }}
+ +
+ + + {{ _('Edit') }} + +
+
+ {% set lang = session.get('lang', 'en') %} + {% set desc = getattr(game, 'steam_description_' + lang) %} + {% if desc %} +
+
+
+
{{ _('Game Description') }}
+
+ {{ desc|safe }} +
+
+
+
+ {% endif %} +
+
+{% endblock %} + diff --git a/steam-gift-manager/templates/import.html b/steam-gift-manager/templates/import.html index 9abcc22..79dc283 100644 --- a/steam-gift-manager/templates/import.html +++ b/steam-gift-manager/templates/import.html @@ -5,11 +5,11 @@
- +
- - {{ _('Abbrechen') }} + + {{ _('Cancel') }}
{% endblock %} diff --git a/steam-gift-manager/templates/index.html b/steam-gift-manager/templates/index.html index ff6b87b..2b0c2e9 100644 --- a/steam-gift-manager/templates/index.html +++ b/steam-gift-manager/templates/index.html @@ -1,15 +1,11 @@ {% extends "base.html" %} {% block content %} -
-

{{ _('My Games') }}

- + + - {% if games %}
@@ -17,11 +13,12 @@ - + + @@ -29,26 +26,40 @@ {% for game in games %} - + - + +
{{ _('Cover') }} {{ _('Name') }}{{ _('Key') }}{{ _('Key') }} {{ _('Status') }} {{ _('Created') }} {{ _('Redeem by') }} {{ _('Shop') }}{{ _('Price') }} {{ _('Actions') }}
- {% if game.steam_appid %} - Steam Header - {% endif %} + + {% if game.steam_appid %} + Steam Header + {% elif game.url and 'gog.com' in game.url %} + GOG Logo + {% endif %} + {{ game.name }}{{ game.steam_key }}{{ game.steam_key }} {% if game.status == 'nicht eingelöst' %} {{ _('Not redeemed') }} - {% elif game.status == 'verschenkt' %} + {% elif game.status == 'geschenkt' %} {{ _('Gifted') }} {% elif game.status == 'eingelöst' %} {{ _('Redeemed') }} {% endif %} {{ format_date(game.created_at) }}{{ game.created_at|strftime('%d.%m.%Y') }} {% if game.redeem_date %} - {{ format_date(game.redeem_date) }} + {{ game.redeem_date|strftime('%d.%m.%Y') }} {% endif %} @@ -56,9 +67,37 @@ 🔗 {{ _('Shop') }} {% endif %} + {% if game.current_price is not none %} +
+
+ {{ _('Current Deal') }} +
+
+ {{ "%.2f"|format(game.current_price) }} € + {% if game.current_price_shop %} + ({{ game.current_price_shop }}) + {% endif %} +
+
+ {% endif %} + + {# Historical Low #} + {% if game.historical_low is not none %} +
+
+ {{ _('Hist. Low') }} +
+
+ {{ "%.2f"|format(game.historical_low) }} € +
+
+ {% endif %} +
- {% if game.status == 'verschenkt' %} -
- + {% else %}
{{ _('No games yet') }}
{% endif %} diff --git a/steam-gift-manager/templates/login.html b/steam-gift-manager/templates/login.html index 37f3eb0..98e1882 100644 --- a/steam-gift-manager/templates/login.html +++ b/steam-gift-manager/templates/login.html @@ -1,29 +1,51 @@ {% extends "base.html" %} {% block content %} -
-
-
-
- Logo -

{{ _('Login') }}

-
- -
- - -
-
- - -
- -
- -
-
+
+
+

{{ _('Login') }}

+
+ +
+ + +
+
+ + +
+
+ + +
+ {# Flash messages are handled in base.html, so the specific error block here can be removed #} + {# {% if error %} + + {% endif %} #} + + +
+ + {% if config.REGISTRATION_ENABLED %} + + {% endif %} +
{% endblock %} diff --git a/steam-gift-manager/templates/redeem.html b/steam-gift-manager/templates/redeem.html index a41f4da..c169167 100644 --- a/steam-gift-manager/templates/redeem.html +++ b/steam-gift-manager/templates/redeem.html @@ -16,11 +16,17 @@

{{ _('Your Key:') }}

{{ game.steam_key }}
+ {% if platform_link %} - {{ _('Redeem now on') }} {% if game.steam_appid %}Steam{% else %}GOG{% endif %} + {{ _('Redeem now on') }} {{ platform_name }} + {% else %} +
+ {{ _('Your key:') }} {{ game.steam_key }} +
+ {% endif %}
{{ _('This page will expire in') }} @@ -28,9 +34,9 @@
+ class="progress-bar bg-danger" + role="progressbar" + style="width: 100%">
@@ -41,9 +47,10 @@
diff --git a/steam-gift-manager/templates/register.html b/steam-gift-manager/templates/register.html index 40d6d62..b9b7ee0 100644 --- a/steam-gift-manager/templates/register.html +++ b/steam-gift-manager/templates/register.html @@ -1,24 +1,51 @@ {% extends "base.html" %} {% block content %} -
-
-
-
-

{{ _('Register') }}

-
- -
- - -
-
- - -
- -
-
-
+
+
+

{{ _('Register') }}

+
+ +
+ + +
+
+ + +
+
+ + +
+ {% if error %} + + {% endif %} + +
+ +
{% endblock %} + diff --git a/steam-gift-manager/translations/de.json b/steam-gift-manager/translations/de.json new file mode 100644 index 0000000..752d7e3 --- /dev/null +++ b/steam-gift-manager/translations/de.json @@ -0,0 +1,99 @@ +{ + "Access Forbidden": "Zugriff verweigert", + "Action": "Aktion", + "Actions": "Aktionen", + "Add Game": "Spiel hinzufügen", + "Add New Game": "Neues Spiel hinzufügen", + "Admin": "Admin", + "Already have an account? Login!": "Du hast schon ein Konto? Jetzt anmelden!", + "Audit Logs": "Prüfprotokolle", + "Back to Home": "Zurück zur Startseite", + "Cancel": "Abbrechen", + "Change Password": "Passwort ändern", + "Change password form": "Passwort ändern Formular", + "Clipboard error": "Ablagefehler", + "Confirm New Password": "Neues Passwort bestätigen", + "Confirm Password": "Passwort bestätigen", + "Copied!": "Kopiert!", + "Copy": "Kopieren", + "Cover": "Cover", + "Created": "Erstellt", + "Current Deal": "Aktuelles Angebot", + "Current Password": "Aktuelles Passwort", + "Current Price": "Aktueller Preis", + "Delete": "Löschen", + "Details": "Details", + "Edit": "Bearbeiten", + "Redeem-Link": "Einlöse-Link", + "Error": "Fehler", + "Expires at": "Läuft ab am", + "Export CSV": "CSV exportieren", + "Externe Daten": "Externe Daten", + "External Data": "Externe Daten", + "For GOG games: Enter the Steam AppID here to enable price tracking.": "Für GOG-Spiele: Gib hier die Steam AppID ein, um die Preisüberwachung zu aktivieren.", + "Game Description": "Spielbeschreibung", + "Game Key": "Spielschlüssel", + "Game Key Manager": "Game Key Manager", + "Generate redeem link": "Einlöse-Link generieren", + "Gifted": "Verschenkt", + "Hist. Low": "Historischer Tiefstpreis", + "Import": "Importieren", + "Import/Export": "Import/Export", + "Import CSV": "CSV importieren", + "Import Games": "Spiele importieren", + "Key": "Schlüssel", + "Link copied": "Link kopiert", + "Login": "Anmelden", + "Login form": "Anmeldeformular", + "Logout": "Abmelden", + "My Games": "Meine Spiele", + "Name": "Name", + "New Password": "Neues Passwort", + "Next": "Weiter", + "No account? Register here!": "Noch kein Konto? Hier registrieren!", + "No active redeem links": "Keine aktiven Einlöse-Links", + "No games yet": "Der Kornspeicher ist leer, Sire!", + "Notes": "Notizen", + "Not redeemed": "Nicht eingelöst", + "Now": "Jetzt", + "Password": "Passwort", + "Platform": "Plattform", + "Previous": "Zurück", + "Price": "Preis", + "Really delete?": "Wirklich löschen?", + "Recipient": "Empfänger", + "Redeem by": "Einlösen bis", + "Redeemed": "Eingelöst", + "Redeem now on": "Jetzt einlösen bei", + "Register": "Registrieren", + "Registration form": "Registrierungsformular", + "Registration is currently disabled.": "Registrierung ist derzeit deaktiviert.", + "Release Date": "Veröffentlichungsdatum", + "Remember me": "Angemeldet bleiben", + "Reset Password": "Passwort zurücksetzen", + "Save": "Speichern", + "Search": "Suchen", + "Search games": "Spiele suchen", + "Select CSV file": "CSV-Datei auswählen", + "Shop": "Shop", + "Shop URL": "Shop-URL", + "Show/Hide Keys": "Zeige/Verstecke Keys", + "Sorry, you are not allowed to access this page.": "Du bist nicht berechtigt, diese Seite zu betreten.", + "Spiel bearbeiten": "Spiel bearbeiten", + "Status": "Status", + "Steam AppID": "Steam AppID", + "Steam AppID (optional)": "Steam AppID (optional)", + "Steam Key": "Steam-Schlüssel", + "This page will expire in": "Diese Seite läuft ab in", + "Timestamp": "Zeitstempel", + "Unknown error": "Unbekannter Fehler", + "Update Data": "Daten aktualisieren", + "User": "Benutzer", + "User Management": "Benutzerverwaltung", + "Username": "Benutzername", + "Release Date:": "Veröffentlichung:", + "View Details": "Details anzeigen", + "View on IsThereAnyDeal": "Auf IsThereAnyDeal ansehen", + "Your Key:": "Dein Key:", + "Your key:": "Dein Key" +} \ No newline at end of file diff --git a/steam-gift-manager/translations/en.json b/steam-gift-manager/translations/en.json new file mode 100644 index 0000000..6facd36 --- /dev/null +++ b/steam-gift-manager/translations/en.json @@ -0,0 +1,96 @@ +{ + "Access Forbidden": "", + "Action": "", + "Actions": "", + "Add Game": "", + "Admin": "", + "Already have an account? Login!": "", + "Audit Logs": "", + "Back to Home": "", + "Cancel": "", + "Change Password": "", + "Change password form": "", + "Clipboard error": "", + "Confirm New Password": "", + "Confirm Password": "", + "Copied!": "", + "Copy": "", + "Cover": "", + "Created": "", + "Current Deal": "", + "Current Password": "", + "Current Price": "", + "Delete": "", + "Details": "", + "Edit": "", + "Error": "", + "Expires at": "", + "Export CSV": "", + "External Data": "", + "For GOG games: Enter the Steam AppID here to enable price tracking.": "", + "Game Description": "", + "Game Key": "", + "Game Key Manager": "", + "Generate redeem link": "", + "Gifted": "", + "Hist. Low": "", + "Import": "", + "Import CSV": "", + "Import/Export": "", + "Import Games": "", + "Key": "", + "Link copied": "", + "Login": "", + "Login form": "", + "Logout": "", + "Name": "", + "New Password": "", + "Next": "", + "No account? Register here!": "", + "No active redeem links": "", + "No games yet": "", + "Notes": "", + "Not redeemed": "", + "Now": "", + "Password": "", + "Platform": "", + "Previous": "", + "Price": "", + "Really delete?": "", + "Recipient": "", + "Redeem by": "", + "Redeemed": "", + "Redeem-Link": "", + "Redeem now on": "", + "Register": "", + "Registration form": "", + "Registration is currently disabled.": "", + "Release Date": "", + "Release Date:": "", + "Remember me": "", + "Reset Password": "", + "Save": "", + "Search": "", + "Search games": "", + "Select CSV file": "", + "Shop": "", + "Shop URL": "", + "Show/Hide Keys": "", + "Sorry, you are not allowed to access this page.": "", + "Spiel bearbeiten": "", + "Status": "", + "Steam AppID": "", + "Steam AppID (optional)": "", + "Steam Key": "", + "This page will expire in": "", + "Timestamp": "", + "Unknown error": "", + "Update Data": "", + "User": "", + "User Management": "", + "Username": "", + "View Details": "", + "View on IsThereAnyDeal": "", + "Your key:": "", + "Your Key:": "" +} diff --git a/translate.sh b/translate.sh index e78327d..16c782e 100755 --- a/translate.sh +++ b/translate.sh @@ -1,28 +1,38 @@ #!/bin/bash set -e -cd "$(dirname "$0")/steam-gift-manager" +APP_DIR="steam-gift-manager" +TRANSLATION_DIR="$APP_DIR/translations" +LANGS=("de" "en") -declare -A locales=( - ["de"]="de" - ["en"]="en" -) +# check jq +if ! command -v jq &>/dev/null; then + echo "❌ jq is required. Install with: sudo apt-get install jq" + exit 1 +fi -# POT-Datei erstellen -docker-compose exec steam-manager pybabel extract -F babel.cfg -o translations/messages.pot . +echo -e "\n\033[1;32m✅ Extracting translations...\033[0m" -# Für jede Sprache prüfen und ggf. initialisieren -for lang in "${!locales[@]}"; do - if [ ! -f "translations/${locales[$lang]}/LC_MESSAGES/messages.po" ]; then - docker-compose exec steam-manager pybabel init \ - -i translations/messages.pot \ - -d translations \ - -l "${locales[$lang]}" - fi +# 1. create json files +mkdir -p "$TRANSLATION_DIR" +for lang in "${LANGS[@]}"; do + file="$TRANSLATION_DIR/$lang.json" + [ -f "$file" ] || echo "{}" > "$file" done -# Übersetzungen aktualisieren und kompilieren -docker-compose exec steam-manager pybabel update -i translations/messages.pot -d translations -docker-compose exec steam-manager pybabel compile -d translations +# 2. extract all strings +STRINGS=$(grep -rhoP "_\(\s*['\"]((?:[^']|'[^'])*?)['\"]\s*[,)]" \ + "$APP_DIR/templates" "$APP_DIR/app.py" | \ + sed -E "s/_\(\s*['\"](.+?)['\"]\s*[,)]/\1/" | sort | uniq) + +# 3. put da keys in da json +for lang in "${LANGS[@]}"; do + file="$TRANSLATION_DIR/$lang.json" + tmp="$file.tmp" + jq --argjson keys "$(echo "$STRINGS" | jq -R . | jq -s .)" \ + 'reduce $keys[] as $k (.; .[$k] = (.[$k] // ""))' "$file" > "$tmp" + mv "$tmp" "$file" +done + +echo -e "\n\033[1;32m✅ Done! Translation keys added.\033[0m" -echo "✅ Übersetzungen aktualisiert!" diff --git a/translations/de/LC_MESSAGES/messages.mo b/translations/de/LC_MESSAGES/messages.mo deleted file mode 100644 index a1fd0f7..0000000 Binary files a/translations/de/LC_MESSAGES/messages.mo and /dev/null differ diff --git a/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po deleted file mode 100644 index 8f07c17..0000000 --- a/translations/de/LC_MESSAGES/messages.po +++ /dev/null @@ -1,287 +0,0 @@ -# German translations for PROJECT. -# Copyright (C) 2025 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR , 2025. -# -msgid "" -msgstr "" -"Project-Id-Version: PROJECT VERSION\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2025-04-26 11:13+0000\n" -"PO-Revision-Date: 2025-04-26 11:13+0000\n" -"Last-Translator: FULL NAME \n" -"Language: de\n" -"Language-Team: de \n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.17.0\n" - -#: app.py:187 -msgid "Invalid credentials" -msgstr "" - -#: app.py:193 -msgid "Registrierungen sind deaktiviert" -msgstr "" - -#: app.py:201 -msgid "Username already exists" -msgstr "" - -#: app.py:227 -msgid "Aktuelles Passwort ist falsch" -msgstr "" - -#: app.py:231 -msgid "Neue Passwörter stimmen nicht überein" -msgstr "" - -#: app.py:236 -msgid "Passwort erfolgreich geändert" -msgstr "" - -#: app.py:266 -msgid "Game added successfully!" -msgstr "" - -#: app.py:271 -msgid "Steam Key already exists!" -msgstr "" - -#: app.py:274 app.py:318 -msgid "Error: " -msgstr "" - -#: app.py:313 -msgid "Changes saved!" -msgstr "" - -#: app.py:401 -msgid "Game List (without Keys)" -msgstr "" - -#: app.py:494 -#, python-format -msgid "%(new)d neue Spiele importiert, %(dup)d Duplikate übersprungen" -msgstr "" - -#: app.py:498 -#, python-format -msgid "Importfehler: %(error)s" -msgstr "" - -#: app.py:502 -msgid "Bitte eine gültige CSV-Datei hochladen." -msgstr "" - -#: templates/add_game.html:4 templates/index.html:9 -msgid "Add New Game" -msgstr "" - -#: templates/add_game.html:9 templates/edit_game.html:9 templates/index.html:19 -msgid "Name" -msgstr "" - -#: templates/add_game.html:13 templates/edit_game.html:13 -msgid "Game Key" -msgstr "" - -#: templates/add_game.html:17 templates/edit_game.html:21 -#: templates/index.html:21 -msgid "Status" -msgstr "" - -#: templates/add_game.html:19 templates/edit_game.html:23 -#: templates/index.html:41 -msgid "Not redeemed" -msgstr "" - -#: templates/add_game.html:20 templates/edit_game.html:24 -#: templates/index.html:43 -msgid "Gifted" -msgstr "" - -#: templates/add_game.html:21 templates/edit_game.html:25 -#: templates/index.html:45 -msgid "Redeemed" -msgstr "" - -#: templates/add_game.html:25 templates/edit_game.html:29 -#: templates/index.html:23 -msgid "Redeem by" -msgstr "" - -#: templates/add_game.html:29 templates/edit_game.html:33 -msgid "Recipient" -msgstr "" - -#: templates/add_game.html:33 templates/edit_game.html:37 -msgid "Shop URL" -msgstr "" - -#: templates/add_game.html:37 templates/edit_game.html:41 -msgid "Notes" -msgstr "" - -#: templates/add_game.html:41 templates/edit_game.html:60 -msgid "Save" -msgstr "" - -#: templates/add_game.html:42 templates/edit_game.html:61 -msgid "Cancel" -msgstr "" - -#: templates/base.html:7 -msgid "Game Key Manager" -msgstr "" - -#: templates/base.html:23 -msgid "Search" -msgstr "" - -#: templates/base.html:31 -msgid "Dark Mode" -msgstr "" - -#: templates/base.html:44 -msgid "Passwort" -msgstr "" - -#: templates/base.html:47 -msgid "Logout" -msgstr "" - -#: templates/change_password.html:4 templates/change_password.html:19 -msgid "Change Password" -msgstr "" - -#: templates/change_password.html:8 -msgid "Current Password" -msgstr "" - -#: templates/change_password.html:12 -msgid "New Password" -msgstr "" - -#: templates/change_password.html:16 -msgid "Confirm New Password" -msgstr "" - -#: templates/edit_game.html:4 -msgid "Edit Game" -msgstr "" - -#: templates/edit_game.html:17 -msgid "Steam AppID (optional)" -msgstr "" - -#: templates/edit_game.html:47 -msgid "Active Redeem Link" -msgstr "" - -#: templates/edit_game.html:54 -msgid "Expires at" -msgstr "" - -#: templates/import.html:4 -msgid "Import Games" -msgstr "" - -#: templates/import.html:8 -msgid "CSV-Datei auswählen" -msgstr "" - -#: templates/import.html:11 -msgid "Importieren" -msgstr "" - -#: templates/import.html:12 -msgid "Abbrechen" -msgstr "" - -#: templates/index.html:4 -msgid "My Games" -msgstr "" - -#: templates/index.html:6 -msgid "Export CSV" -msgstr "" - -#: templates/index.html:8 -msgid "Import CSV" -msgstr "" - -#: templates/index.html:18 -msgid "Cover" -msgstr "" - -#: templates/index.html:20 -msgid "Key" -msgstr "" - -#: templates/index.html:22 -msgid "Created" -msgstr "" - -#: templates/index.html:24 templates/index.html:56 -msgid "Shop" -msgstr "" - -#: templates/index.html:25 -msgid "Actions" -msgstr "" - -#: templates/index.html:63 -msgid "Generate redeem link" -msgstr "" - -#: templates/index.html:70 -msgid "Really delete?" -msgstr "" - -#: templates/index.html:96 -msgid "Redeem link copied to clipboard!" -msgstr "" - -#: templates/index.html:100 -msgid "Error generating link" -msgstr "" - -#: templates/index.html:106 -msgid "No games yet" -msgstr "" - -#: templates/login.html:8 templates/login.html:19 -msgid "Login" -msgstr "" - -#: templates/login.html:12 templates/register.html:11 -msgid "Username" -msgstr "" - -#: templates/login.html:16 templates/register.html:15 -msgid "Password" -msgstr "" - -#: templates/login.html:22 -msgid "No account yet? Register" -msgstr "" - -#: templates/redeem.html:16 -msgid "Your Key:" -msgstr "" - -#: templates/redeem.html:22 -msgid "Redeem now on" -msgstr "" - -#: templates/redeem.html:26 -msgid "This page will expire in" -msgstr "" - -#: templates/register.html:7 templates/register.html:18 -msgid "Register" -msgstr "" - diff --git a/translations/en/LC_MESSAGES/messages.mo b/translations/en/LC_MESSAGES/messages.mo deleted file mode 100644 index 63cc42b..0000000 Binary files a/translations/en/LC_MESSAGES/messages.mo and /dev/null differ diff --git a/translations/en/LC_MESSAGES/messages.po b/translations/en/LC_MESSAGES/messages.po deleted file mode 100644 index 52e7e24..0000000 --- a/translations/en/LC_MESSAGES/messages.po +++ /dev/null @@ -1,287 +0,0 @@ -# English translations for PROJECT. -# Copyright (C) 2025 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR , 2025. -# -msgid "" -msgstr "" -"Project-Id-Version: PROJECT VERSION\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2025-04-26 11:13+0000\n" -"PO-Revision-Date: 2025-04-26 11:13+0000\n" -"Last-Translator: FULL NAME \n" -"Language: en\n" -"Language-Team: en \n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.17.0\n" - -#: app.py:187 -msgid "Invalid credentials" -msgstr "" - -#: app.py:193 -msgid "Registrierungen sind deaktiviert" -msgstr "" - -#: app.py:201 -msgid "Username already exists" -msgstr "" - -#: app.py:227 -msgid "Aktuelles Passwort ist falsch" -msgstr "" - -#: app.py:231 -msgid "Neue Passwörter stimmen nicht überein" -msgstr "" - -#: app.py:236 -msgid "Passwort erfolgreich geändert" -msgstr "" - -#: app.py:266 -msgid "Game added successfully!" -msgstr "" - -#: app.py:271 -msgid "Steam Key already exists!" -msgstr "" - -#: app.py:274 app.py:318 -msgid "Error: " -msgstr "" - -#: app.py:313 -msgid "Changes saved!" -msgstr "" - -#: app.py:401 -msgid "Game List (without Keys)" -msgstr "" - -#: app.py:494 -#, python-format -msgid "%(new)d neue Spiele importiert, %(dup)d Duplikate übersprungen" -msgstr "" - -#: app.py:498 -#, python-format -msgid "Importfehler: %(error)s" -msgstr "" - -#: app.py:502 -msgid "Bitte eine gültige CSV-Datei hochladen." -msgstr "" - -#: templates/add_game.html:4 templates/index.html:9 -msgid "Add New Game" -msgstr "" - -#: templates/add_game.html:9 templates/edit_game.html:9 templates/index.html:19 -msgid "Name" -msgstr "" - -#: templates/add_game.html:13 templates/edit_game.html:13 -msgid "Game Key" -msgstr "" - -#: templates/add_game.html:17 templates/edit_game.html:21 -#: templates/index.html:21 -msgid "Status" -msgstr "" - -#: templates/add_game.html:19 templates/edit_game.html:23 -#: templates/index.html:41 -msgid "Not redeemed" -msgstr "" - -#: templates/add_game.html:20 templates/edit_game.html:24 -#: templates/index.html:43 -msgid "Gifted" -msgstr "" - -#: templates/add_game.html:21 templates/edit_game.html:25 -#: templates/index.html:45 -msgid "Redeemed" -msgstr "" - -#: templates/add_game.html:25 templates/edit_game.html:29 -#: templates/index.html:23 -msgid "Redeem by" -msgstr "" - -#: templates/add_game.html:29 templates/edit_game.html:33 -msgid "Recipient" -msgstr "" - -#: templates/add_game.html:33 templates/edit_game.html:37 -msgid "Shop URL" -msgstr "" - -#: templates/add_game.html:37 templates/edit_game.html:41 -msgid "Notes" -msgstr "" - -#: templates/add_game.html:41 templates/edit_game.html:60 -msgid "Save" -msgstr "" - -#: templates/add_game.html:42 templates/edit_game.html:61 -msgid "Cancel" -msgstr "" - -#: templates/base.html:7 -msgid "Game Key Manager" -msgstr "" - -#: templates/base.html:23 -msgid "Search" -msgstr "" - -#: templates/base.html:31 -msgid "Dark Mode" -msgstr "" - -#: templates/base.html:44 -msgid "Passwort" -msgstr "" - -#: templates/base.html:47 -msgid "Logout" -msgstr "" - -#: templates/change_password.html:4 templates/change_password.html:19 -msgid "Change Password" -msgstr "" - -#: templates/change_password.html:8 -msgid "Current Password" -msgstr "" - -#: templates/change_password.html:12 -msgid "New Password" -msgstr "" - -#: templates/change_password.html:16 -msgid "Confirm New Password" -msgstr "" - -#: templates/edit_game.html:4 -msgid "Edit Game" -msgstr "" - -#: templates/edit_game.html:17 -msgid "Steam AppID (optional)" -msgstr "" - -#: templates/edit_game.html:47 -msgid "Active Redeem Link" -msgstr "" - -#: templates/edit_game.html:54 -msgid "Expires at" -msgstr "" - -#: templates/import.html:4 -msgid "Import Games" -msgstr "" - -#: templates/import.html:8 -msgid "CSV-Datei auswählen" -msgstr "" - -#: templates/import.html:11 -msgid "Importieren" -msgstr "" - -#: templates/import.html:12 -msgid "Abbrechen" -msgstr "" - -#: templates/index.html:4 -msgid "My Games" -msgstr "" - -#: templates/index.html:6 -msgid "Export CSV" -msgstr "" - -#: templates/index.html:8 -msgid "Import CSV" -msgstr "" - -#: templates/index.html:18 -msgid "Cover" -msgstr "" - -#: templates/index.html:20 -msgid "Key" -msgstr "" - -#: templates/index.html:22 -msgid "Created" -msgstr "" - -#: templates/index.html:24 templates/index.html:56 -msgid "Shop" -msgstr "" - -#: templates/index.html:25 -msgid "Actions" -msgstr "" - -#: templates/index.html:63 -msgid "Generate redeem link" -msgstr "" - -#: templates/index.html:70 -msgid "Really delete?" -msgstr "" - -#: templates/index.html:96 -msgid "Redeem link copied to clipboard!" -msgstr "" - -#: templates/index.html:100 -msgid "Error generating link" -msgstr "" - -#: templates/index.html:106 -msgid "No games yet" -msgstr "" - -#: templates/login.html:8 templates/login.html:19 -msgid "Login" -msgstr "" - -#: templates/login.html:12 templates/register.html:11 -msgid "Username" -msgstr "" - -#: templates/login.html:16 templates/register.html:15 -msgid "Password" -msgstr "" - -#: templates/login.html:22 -msgid "No account yet? Register" -msgstr "" - -#: templates/redeem.html:16 -msgid "Your Key:" -msgstr "" - -#: templates/redeem.html:22 -msgid "Redeem now on" -msgstr "" - -#: templates/redeem.html:26 -msgid "This page will expire in" -msgstr "" - -#: templates/register.html:7 templates/register.html:18 -msgid "Register" -msgstr "" - diff --git a/translations/messages.pot b/translations/messages.pot deleted file mode 100644 index 2322064..0000000 --- a/translations/messages.pot +++ /dev/null @@ -1,286 +0,0 @@ -# Translations template for PROJECT. -# Copyright (C) 2025 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR , 2025. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: PROJECT VERSION\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2025-04-26 11:13+0000\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.17.0\n" - -#: app.py:187 -msgid "Invalid credentials" -msgstr "" - -#: app.py:193 -msgid "Registrierungen sind deaktiviert" -msgstr "" - -#: app.py:201 -msgid "Username already exists" -msgstr "" - -#: app.py:227 -msgid "Aktuelles Passwort ist falsch" -msgstr "" - -#: app.py:231 -msgid "Neue Passwörter stimmen nicht überein" -msgstr "" - -#: app.py:236 -msgid "Passwort erfolgreich geändert" -msgstr "" - -#: app.py:266 -msgid "Game added successfully!" -msgstr "" - -#: app.py:271 -msgid "Steam Key already exists!" -msgstr "" - -#: app.py:274 app.py:318 -msgid "Error: " -msgstr "" - -#: app.py:313 -msgid "Changes saved!" -msgstr "" - -#: app.py:401 -msgid "Game List (without Keys)" -msgstr "" - -#: app.py:494 -#, python-format -msgid "%(new)d neue Spiele importiert, %(dup)d Duplikate übersprungen" -msgstr "" - -#: app.py:498 -#, python-format -msgid "Importfehler: %(error)s" -msgstr "" - -#: app.py:502 -msgid "Bitte eine gültige CSV-Datei hochladen." -msgstr "" - -#: templates/add_game.html:4 templates/index.html:9 -msgid "Add New Game" -msgstr "" - -#: templates/add_game.html:9 templates/edit_game.html:9 templates/index.html:19 -msgid "Name" -msgstr "" - -#: templates/add_game.html:13 templates/edit_game.html:13 -msgid "Game Key" -msgstr "" - -#: templates/add_game.html:17 templates/edit_game.html:21 -#: templates/index.html:21 -msgid "Status" -msgstr "" - -#: templates/add_game.html:19 templates/edit_game.html:23 -#: templates/index.html:41 -msgid "Not redeemed" -msgstr "" - -#: templates/add_game.html:20 templates/edit_game.html:24 -#: templates/index.html:43 -msgid "Gifted" -msgstr "" - -#: templates/add_game.html:21 templates/edit_game.html:25 -#: templates/index.html:45 -msgid "Redeemed" -msgstr "" - -#: templates/add_game.html:25 templates/edit_game.html:29 -#: templates/index.html:23 -msgid "Redeem by" -msgstr "" - -#: templates/add_game.html:29 templates/edit_game.html:33 -msgid "Recipient" -msgstr "" - -#: templates/add_game.html:33 templates/edit_game.html:37 -msgid "Shop URL" -msgstr "" - -#: templates/add_game.html:37 templates/edit_game.html:41 -msgid "Notes" -msgstr "" - -#: templates/add_game.html:41 templates/edit_game.html:60 -msgid "Save" -msgstr "" - -#: templates/add_game.html:42 templates/edit_game.html:61 -msgid "Cancel" -msgstr "" - -#: templates/base.html:7 -msgid "Game Key Manager" -msgstr "" - -#: templates/base.html:23 -msgid "Search" -msgstr "" - -#: templates/base.html:31 -msgid "Dark Mode" -msgstr "" - -#: templates/base.html:44 -msgid "Passwort" -msgstr "" - -#: templates/base.html:47 -msgid "Logout" -msgstr "" - -#: templates/change_password.html:4 templates/change_password.html:19 -msgid "Change Password" -msgstr "" - -#: templates/change_password.html:8 -msgid "Current Password" -msgstr "" - -#: templates/change_password.html:12 -msgid "New Password" -msgstr "" - -#: templates/change_password.html:16 -msgid "Confirm New Password" -msgstr "" - -#: templates/edit_game.html:4 -msgid "Edit Game" -msgstr "" - -#: templates/edit_game.html:17 -msgid "Steam AppID (optional)" -msgstr "" - -#: templates/edit_game.html:47 -msgid "Active Redeem Link" -msgstr "" - -#: templates/edit_game.html:54 -msgid "Expires at" -msgstr "" - -#: templates/import.html:4 -msgid "Import Games" -msgstr "" - -#: templates/import.html:8 -msgid "CSV-Datei auswählen" -msgstr "" - -#: templates/import.html:11 -msgid "Importieren" -msgstr "" - -#: templates/import.html:12 -msgid "Abbrechen" -msgstr "" - -#: templates/index.html:4 -msgid "My Games" -msgstr "" - -#: templates/index.html:6 -msgid "Export CSV" -msgstr "" - -#: templates/index.html:8 -msgid "Import CSV" -msgstr "" - -#: templates/index.html:18 -msgid "Cover" -msgstr "" - -#: templates/index.html:20 -msgid "Key" -msgstr "" - -#: templates/index.html:22 -msgid "Created" -msgstr "" - -#: templates/index.html:24 templates/index.html:56 -msgid "Shop" -msgstr "" - -#: templates/index.html:25 -msgid "Actions" -msgstr "" - -#: templates/index.html:63 -msgid "Generate redeem link" -msgstr "" - -#: templates/index.html:70 -msgid "Really delete?" -msgstr "" - -#: templates/index.html:96 -msgid "Redeem link copied to clipboard!" -msgstr "" - -#: templates/index.html:100 -msgid "Error generating link" -msgstr "" - -#: templates/index.html:106 -msgid "No games yet" -msgstr "" - -#: templates/login.html:8 templates/login.html:19 -msgid "Login" -msgstr "" - -#: templates/login.html:12 templates/register.html:11 -msgid "Username" -msgstr "" - -#: templates/login.html:16 templates/register.html:15 -msgid "Password" -msgstr "" - -#: templates/login.html:22 -msgid "No account yet? Register" -msgstr "" - -#: templates/redeem.html:16 -msgid "Your Key:" -msgstr "" - -#: templates/redeem.html:22 -msgid "Redeem now on" -msgstr "" - -#: templates/redeem.html:26 -msgid "This page will expire in" -msgstr "" - -#: templates/register.html:7 templates/register.html:18 -msgid "Register" -msgstr "" - diff --git a/upgrade.sh b/upgrade.sh index f5dff45..3e5ccb9 100644 --- a/upgrade.sh +++ b/upgrade.sh @@ -1,22 +1,22 @@ #!/bin/bash set -e -# Setze das Arbeitsverzeichnis auf das Projektverzeichnis +# Set the working directory to the project directory cd "$(dirname "$0")/steam-gift-manager" -# Setze FLASK_APP, falls nötig +# set FLASK_APP, if needed export FLASK_APP=app.py -# Initialisiere migrations, falls noch nicht vorhanden +# Initialize migrations, if not yet available if [ ! -d migrations ]; then echo "Starting Flask-Migrate..." docker-compose exec steam-manager flask db init fi -# Erzeuge Migration (nur wenn sich Modelle geändert haben) +# Create migration (only if models have changed) docker-compose exec steam-manager flask db migrate -m "Automatic Migration" -# Wende Migration an +# Apply migration docker-compose exec steam-manager flask db upgrade -echo "✅ Database-Migration abgeschlossen!" +echo "✅ Database migration completed!"