diff --git a/.env b/.env new file mode 100644 index 0000000..ffb20f0 --- /dev/null +++ b/.env @@ -0,0 +1,34 @@ +# Flask-Configuration +SECRET_KEY="e2460fd1be9778d6a17aaa7e98676b042936856d70c3f5b2" +REDEEM_SECRET="590ba02d77e340284e48075fee6ff692" +WTF_CSRF_SECRET_KEY="2377b17a84388b7c9ff2fce049dc1898" + +# locales +BABEL_DEFAULT_LOCALE="en" +BABEL_SUPPORTED_LOCALES="de,en" +BABEL_TRANSLATION_DIRECTORIES="translations" + +# Timezone +TZ=Europe/Berlin + +# Security +SESSION_COOKIE_SECURE="False" +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 + +# Pushover +PUSHOVER_APP_TOKEN="" +PUSHOVER_USER_KEY="" + +# Gotify +GOTIFY_URL="" +GOTIFY_TOKEN="" + +# Matrix +MATRIX_HOMESERVER="" +MATRIX_ACCESS_TOKEN="" +MATRIX_ROOM_ID="" diff --git a/GameManager.png b/GameManager.png index 80228ed..5790d74 100644 Binary files a/GameManager.png and b/GameManager.png differ diff --git a/README.md b/README.md index bb04c92..05cf4c4 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,50 @@ -# 🔑 Game Key Management System 🔑 +# 🔑 Game Key Manager 🔑 -![Screenshot](GameManager.png) - -## Welcome! 👋 +## 👋 Welcome! 👋 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) + +(the link will also remain in the edit area) + +![Screenshot](GameManager.png) + --- ## ✨ Features ✨ - **Key Management:** - Enter your game keys, the corresponding game, platform, and where you got the key. + Enter your game keys, the corresponding game, platform, and maybe where you got the key. - **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:** Each user manages their own keys. -- **Search & Filter:** +- **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. - **Responsive UI:** Works on desktop and mobile, with Dark Mode toggle. - **Multi-language:** - Switch between English and German instantly. + 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, JSON) - - Redeem site with unique sharing link + - ~~Import/Export (CSV)~~ + - ~~Redeem site with unique sharing link~~ --- @@ -37,13 +53,14 @@ No more confusion about whether a key is redeemed, gifted, or still unused – n ### 1. **Clone the Repository** ```bash -git clone https://git.nocci.it/nocci/GiftGamesDB +git clone https://git.nocci.it/nocci/GameKeyManager cd steam-gift-manager ``` ### 2. **Setup Docker** 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) ### 3. **Initial Setup** @@ -62,54 +79,90 @@ docker-compose build --no-cache docker-compose up -d ``` -### 5. **Initialize and Edit Translations (Optional)** +### 5. **Edit your .env file to your liking** + +It's in your root folder of the installation! + +```xml +# Sicherheit +SESSION_COOKIE_SECURE="True" (only works if you run this app via HTTPS) +CSRF_ENABLED="True" +``` + +**Important after any(!) change of the .env file!** + +```bash +cd steam-gift-manager/ +docker-compose down && docker-compose up -d --build +``` + +### 6. **Initialize and Edit Translations (Optional)** ```bash ./translate.sh ``` -Edit the .po files in steam-translations/de/LC_MESSAGES/messages.po and en/LC_MESSAGES/messages.po +Edit the .po files in translations/de_DE/LC_MESSAGES/messages.po and en_US/LC_MESSAGES/messages.po ```bash ./translate.sh cd steam-gift-manager/ -docker-compose restart steam-manager +docker-compose down && docker-compose up -d --build ``` -### 6. **Open the App** +### 7. **Open the App** Go to [http://localhost:5000](http://localhost:5000) in your browser. - Register your first user. -- Add your keys, shop URLs, and (optionally) Steam AppIDs. +- Add your keys, shop URLs etc. - Enjoy search, status, and automatic Steam cover images! --- ## 🛠️ Technology Stack 🛠️ -- **Frontend:** Bootstrap 5, Jinja2 Templates -- **Backend:** Python 3, Flask, Flask-Babel, Flask-Login, Flask-SQLAlchemy +- **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 `steam-translations/` +- **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 are translated. -- You can add more languages by editing the `.po` files and running `./translate.sh`. +- 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 + +--- + +## 🪙 Do you this project? 🪙 + +If you’d like to support itme, you can make a donation here: + +[![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! --- ## 🙌 Contribute! 🙌 -This project is open source and thrives on your help! +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 📜 @@ -124,4 +177,4 @@ A big thank you to everyone who supports and contributes to this project! --- -**Enjoy your organized Steam key collection!** 🚀 +**Enjoy your organized Game key collection!** 🚀 diff --git a/setup.sh b/setup.sh index 37c72f3..6641305 100644 --- a/setup.sh +++ b/setup.sh @@ -1,53 +1,249 @@ #!/bin/bash set -e +# Color definitions +RED='\033[1;31m' +GREEN='\033[1;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# 1. Docker check (including 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 + if [[ "$install_docker" =~ ^[YyJj]$ ]]; then + if [ -f /etc/arch-release ]; then + echo -e "${GREEN}▶️ Installing Docker for Arch Linux...${NC}" + sudo pacman -Sy --noconfirm docker + sudo systemctl enable --now docker.service + else + echo -e "${GREEN}▶️ Using generic Docker installation script...${NC}" + curl -fsSL https://get.docker.com -o get-docker.sh + sudo sh get-docker.sh + rm get-docker.sh + fi + + # Check Docker group membership + 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 + newgrp docker + fi + + echo -e "${GREEN}✔️ Docker has been installed.${NC}" + else + echo -e "${YELLOW}❌ Docker is required. Exiting script.${NC}" + exit 1 + fi +fi + +# 2. Docker Compose check (V1 and V2 plugin, with Arch support) +DOCKER_COMPOSE_CMD="" +if command -v docker-compose &>/dev/null; then + DOCKER_COMPOSE_CMD="docker-compose" +elif docker compose version &>/dev/null; then + DOCKER_COMPOSE_CMD="docker compose" +else + echo -e "${RED}❗ Neither docker-compose nor docker compose plugin is installed!${NC}" + read -p "Would you like to install Docker Compose automatically now? [y/N]: " install_compose + if [[ "$install_compose" =~ ^[YyJj]$ ]]; then + if [ -f /etc/arch-release ]; then + sudo pacman -Sy --noconfirm docker-compose + elif command -v apt-get &>/dev/null; then + sudo apt-get update + sudo apt-get install -y docker-compose-plugin + elif command -v dnf &>/dev/null; then + sudo dnf install -y docker-compose + elif command -v yum &>/dev/null; then + sudo yum install -y docker-compose-plugin + else + echo -e "${RED}❌ Unsupported package manager! Please install Docker Compose manually.${NC}" + exit 1 + fi + + # Final check + if ! command -v docker-compose &>/dev/null && ! docker compose version &>/dev/null; then + echo -e "${RED}❌ Docker Compose installation failed!${NC}" + exit 1 + fi + echo -e "${GREEN}✔️ Docker Compose has been installed successfully.${NC}" + else + echo -e "${YELLOW}❌ Docker Compose is required. Exiting script.${NC}" + exit 1 + fi +fi + + # Konfiguration PROJECT_DIR="steam-gift-manager" -TRANSLATIONS_DIR="$PWD/steam-translations" -DATA_DIR="$PWD/data" +TRANSLATIONS_DIR="../translations" +DATA_DIR="../data" # 1. Projektordner & Übersetzungsordner erstellen -mkdir -p $PROJECT_DIR/{templates,static} -mkdir -p $TRANSLATIONS_DIR -mkdir -p $DATA_DIR +mkdir -p "$PROJECT_DIR"/{templates,static} +mkdir -p "$TRANSLATIONS_DIR"/de/LC_MESSAGES +mkdir -p "$TRANSLATIONS_DIR"/en/LC_MESSAGES +mkdir -p "$DATA_DIR" + +chmod -R a+rwX "$TRANSLATIONS_DIR" "$DATA_DIR" + cd $PROJECT_DIR # 2. requirements.txt cat < requirements.txt flask flask-login +flask-wtf +flask-migrate werkzeug python-dotenv flask-sqlalchemy flask-babel jinja2<3.1.0 +itsdangerous +sqlalchemy +apscheduler +matrix-client +reportlab +requests +pillow EOL -# 3. app.py (inkl. Import/Export) +# 3. .env-Datei im übergeordneten Verzeichnis erstellen +cd .. +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))') + +cat < .env +# Flask-Configuration +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" + +# Timezone +TZ=Europe/Berlin + +# Security +SESSION_COOKIE_SECURE="False" +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 + +# Pushover +PUSHOVER_APP_TOKEN="" +PUSHOVER_USER_KEY="" + +# Gotify +GOTIFY_URL="" +GOTIFY_TOKEN="" + +# Matrix +MATRIX_HOMESERVER="" +MATRIX_ACCESS_TOKEN="" +MATRIX_ROOM_ID="" +EOL + +# Zurück ins Projektverzeichnis +cd $PROJECT_DIR + +# 4. app.py (vollständige korrigierte Version) cat <<'PYTHON_END' > app.py -from flask import Flask, render_template, request, redirect, url_for, flash, make_response, session, abort, send_file +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 -import os +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 +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 +from io import BytesIO +import reportlab.lib app = Flask(__name__) -app.config['SECRET_KEY'] = os.urandom(24) -app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////app/data/games.db' -app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False -app.config['BABEL_DEFAULT_LOCALE'] = 'de' -app.config['BABEL_SUPPORTED_LOCALES'] = ['de', 'en'] -app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations' +csrf = CSRFProtect(app) -db = SQLAlchemy(app) +convention = { + "ix": "ix_%(column_0_label)s", + "uq": "uq_%(table_name)s_%(column_0_name)s", + "ck": "ck_%(table_name)s_%(constraint_name)s", + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", + "pk": "pk_%(table_name)s" +} + +metadata = MetaData(naming_convention=convention) +load_dotenv(override=True) + +# Lade Umgebungsvariablen aus .env mit override +load_dotenv(override=True) + +# Konfiguration +app.config.update( + 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' +) + +interval_hours = int(os.getenv('CHECK_EXPIRING_KEYS_INTERVAL_HOURS', 12)) + +# Initialisierung +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) + @babel.localeselector def get_locale(): if 'lang' in session and session['lang'] in app.config['BABEL_SUPPORTED_LOCALES']: @@ -61,36 +257,63 @@ def inject_template_vars(): theme='dark' if request.cookies.get('dark_mode') == 'true' else 'light' ) -class User(UserMixin, db.Model): +# Datenbankmodelle +class User(db.Model, UserMixin): + __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) - username = db.Column(db.String(100), unique=True) - password = db.Column(db.String(100)) - games = db.relationship('Game', backref='owner', lazy=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) class Game(db.Model): 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) + 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) redeem_date = db.Column(db.DateTime) - user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) steam_appid = db.Column(db.String(20)) +class RedeemToken(db.Model): + 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) + total_hours = db.Column(db.Integer, nullable=False) + +with app.app_context(): + db.create_all() + @login_manager.user_loader def load_user(user_id): return db.session.get(User, int(user_id)) +def extract_steam_appid(url): + match = re.search(r'store\.steampowered\.com/app/(\d+)', url or '') + return match.group(1) if match else '' + +# 404 +def get_or_404(model, id): + instance = db.session.get(model, id) + if not instance: + abort(404) + return instance + @app.route('/') @login_required def index(): search_query = request.args.get('q', '') - query = db.session.query(Game).filter_by(user_id=current_user.id) + query = Game.query.filter_by(user_id=current_user.id) + if search_query: query = query.filter(Game.name.ilike(f'%{search_query}%')) + games = query.order_by(Game.created_at.desc()).all() return render_template('index.html', games=games, @@ -115,25 +338,34 @@ def login(): username = request.form['username'] password = request.form['password'] 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') 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')) + 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') return redirect(url_for('register')) + new_user = User(username=username, password=password) db.session.add(new_user) db.session.commit() login_user(new_user) return redirect(url_for('index')) + return render_template('register.html') @app.route('/logout') @@ -142,13 +374,28 @@ def logout(): logout_user() return redirect(url_for('login')) -import re +@app.route('/change-password', methods=['GET', 'POST']) +@login_required +def change_password(): + if request.method == 'POST': + current_password = request.form['current_password'] + new_password = request.form['new_password'] + confirm_password = request.form['confirm_password'] -def extract_steam_appid(url): - match = re.search(r'store\.steampowered\.com/app/(\d+)', url or '') - if match: - return match.group(1) - return '' + if not check_password_hash(current_user.password, current_password): + flash(_('Aktuelles Passwort ist falsch'), 'danger') + return redirect(url_for('change_password')) + + if new_password != confirm_password: + flash(_('Neue Passwörter stimmen nicht überein'), 'danger') + return redirect(url_for('change_password')) + + current_user.password = generate_password_hash(new_password) + db.session.commit() + flash(_('Passwort erfolgreich geändert'), 'success') + return redirect(url_for('index')) + + return render_template('change_password.html') @app.route('/add', methods=['GET', 'POST']) @login_required @@ -157,8 +404,10 @@ def add_game(): try: url = request.form.get('url', '') steam_appid = request.form.get('steam_appid', '').strip() + if not steam_appid: steam_appid = extract_steam_appid(url) + new_game = Game( name=request.form['name'], steam_key=request.form['steam_key'], @@ -170,13 +419,19 @@ def add_game(): 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') return redirect(url_for('index')) + + except IntegrityError: + db.session.rollback() + flash(_('Steam Key already exists!'), 'danger') except Exception as e: db.session.rollback() flash(_('Error: ') + str(e), 'danger') + return render_template('add_game.html') @app.route('/edit/', methods=['GET', 'POST']) @@ -184,14 +439,26 @@ def add_game(): def edit_game(game_id): game = db.session.get(Game, game_id) if not game or game.owner != current_user: - return _("Not allowed!"), 403 + 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 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) + game.name = request.form['name'] game.steam_key = request.form['steam_key'] game.status = request.form['status'] @@ -200,32 +467,40 @@ def edit_game(game_id): 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 + db.session.commit() flash(_('Changes saved!'), 'success') return redirect(url_for('index')) + except Exception as e: db.session.rollback() flash(_('Error: ') + str(e), 'danger') + return render_template('edit_game.html', - game=game, - redeem_date=game.redeem_date.strftime('%Y-%m-%d') if game.redeem_date else '') + 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.route('/delete/', methods=['POST']) @login_required def delete_game(game_id): - game = Game.query.get_or_404(game_id) + game = db.session.get(Game, game_id) + if not game or game.owner != current_user: + abort(404) + if game.owner != current_user: - return _("Not allowed!"), 403 + abort(403) + try: db.session.delete(game) db.session.commit() - flash(_('Game deleted!'), 'success') except Exception as e: db.session.rollback() - flash(_('Error deleting: ') + str(e), 'danger') + return redirect(url_for('index')) -# --- Import/Export Funktionen --- @app.route('/export', methods=['GET']) @login_required @@ -233,14 +508,22 @@ def export_games(): games = Game.query.filter_by(user_id=current_user.id).all() output = io.StringIO() writer = csv.writer(output) + writer.writerow(['Name', 'Steam Key', 'Status', 'Recipient', 'Notes', 'URL', 'Created', 'Redeem by', 'Steam AppID']) + for game in games: writer.writerow([ - game.name, game.steam_key, game.status, game.recipient, game.notes, - game.url, game.created_at.strftime('%Y-%m-%d %H:%M:%S') if game.created_at else '', + game.name, + game.steam_key, + game.status, + game.recipient, + game.notes, + game.url, + game.created_at.strftime('%Y-%m-%d %H:%M:%S') if game.created_at else '', game.redeem_date.strftime('%Y-%m-%d') if game.redeem_date else '', game.steam_appid ]) + output.seek(0) return send_file( io.BytesIO(output.getvalue().encode('utf-8')), @@ -249,44 +532,316 @@ def export_games(): download_name='games_export.csv' ) + +@app.route('/export_pdf') +@login_required +def export_pdf(): + excluded_statuses = ['eingelöst', 'verschenkt'] + + games = Game.query.filter( + Game.user_id == current_user.id, + Game.status.notin_(excluded_statuses) + ).order_by(Game.created_at.desc()).all() + + buffer = io.BytesIO() + doc = SimpleDocTemplate(buffer, + pagesize=landscape(A4), + leftMargin=40, + rightMargin=40, + topMargin=40, + bottomMargin=40 + ) + + styles = getSampleStyleSheet() + elements = [] + img_height = 2*cm + + # Titel + elements.append(Paragraph(_("Game List (without Keys)"), styles['Title'])) + elements.append(Spacer(1, 12)) + + # Tabellenkopf + col_widths = [ + 5*cm, 10*cm, 6*cm, 3*cm + ] + data = [[ + Paragraph('Cover', styles['Normal']), + Paragraph('Name', styles['Normal']), + Paragraph('Shop-Link', styles['Normal']), + Paragraph('Einlösen bis', styles['Normal']) + ]] + + for game in games: + img = None + if game.steam_appid: + try: + img_url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{game.steam_appid}/header.jpg" + img_data = io.BytesIO(requests.get(img_url, timeout=5).content) + img = Image(img_data, width=3*cm, height=img_height) + except Exception: + img = Paragraph('', styles['Normal']) + + data.append([ + img or '', + Paragraph(game.name, styles['Normal']), + Paragraph(game.url or '', styles['Normal']), + game.redeem_date.strftime('%d.%m.%y') if game.redeem_date else '' + ]) + + # Tabelle formatieren + table = Table(data, colWidths=col_widths, repeatRows=1) + table.setStyle(TableStyle([ + ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), + ('FONTSIZE', (0,0), (-1,0), 8), + ('FONTSIZE', (0,1), (-1,-1), 8), + ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), + ('ALIGN', (0,0), (-1,-1), 'LEFT'), + ('GRID', (0,0), (-1,-1), 0.5, colors.lightgrey), + ('WORDWRAP', (1,1), (1,-1), 'CJK'), + ])) + + elements.append(table) + doc.build(elements) + + buffer.seek(0) + 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(): if request.method == 'POST': file = request.files.get('file') + if file and file.filename.endswith('.csv'): - stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None) + stream = io.StringIO(file.stream.read().decode("UTF8")) reader = csv.DictReader(stream) - for row in reader: - new_game = Game( - name=row['Name'], - steam_key=row['Steam Key'], - status=row['Status'], - recipient=row.get('Recipient', ''), - notes=row.get('Notes', ''), - url=row.get('URL', ''), - created_at=datetime.strptime(row['Created'], '%Y-%m-%d %H:%M:%S') if row.get('Created') else datetime.utcnow(), - redeem_date=datetime.strptime(row['Redeem by'], '%Y-%m-%d') if row.get('Redeem by') else None, - steam_appid=row.get('Steam AppID', ''), - user_id=current_user.id - ) - db.session.add(new_game) - db.session.commit() - flash(_('Import erfolgreich!'), 'success') + new_games = 0 + duplicates = 0 + + try: + with db.session.begin_nested(): + for row in reader: + steam_key = row['Steam Key'].strip() + + if Game.query.filter_by(steam_key=steam_key).first(): + duplicates += 1 + continue + + game = Game( + name=row['Name'], + steam_key=steam_key, + status=row['Status'], + recipient=row.get('Recipient', ''), + notes=row.get('Notes', ''), + url=row.get('URL', ''), + created_at=datetime.strptime(row['Created'], '%Y-%m-%d %H:%M:%S') if row.get('Created') else datetime.utcnow(), + redeem_date=datetime.strptime(row['Redeem by'], '%Y-%m-%d') if row.get('Redeem by') else None, + steam_appid=row.get('Steam AppID', ''), + user_id=current_user.id + ) + + db.session.add(game) + new_games += 1 + + db.session.commit() + + flash(_('%(new)d neue Spiele importiert, %(dup)d Duplikate übersprungen', new=new_games, dup=duplicates), 'success') + + except Exception as e: + db.session.rollback() + flash(_('Importfehler: %(error)s', error=str(e)), 'danger') + return redirect(url_for('index')) + flash(_('Bitte eine gültige CSV-Datei hochladen.'), '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) + + 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() + + 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}) + + except Exception as e: + app.logger.error(f"Redeem error: {str(e)}") + return jsonify({'error': str(e)}), 500 + +@app.route('/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(): + 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') + +# 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 + } + + try: + response = requests.post( + 'https://api.pushover.net/1/messages.json', + data=payload + ) + return response.status_code == 200 + except Exception as e: + app.logger.error(f"Pushover error: {str(e)}") + 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 + +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 + +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 + +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) + + +# Optional: Cleanup-Funktion für regelmäßiges Löschen abgelaufener 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() + + +# 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() + +# Shutdown des Schedulers bei Beendigung der App +atexit.register(lambda: scheduler.shutdown()) + if __name__ == '__main__': with app.app_context(): db.create_all() app.run(host='0.0.0.0', port=5000) + PYTHON_END -# 4. babel.cfg +# Babel Konfiguration erstellen cat < babel.cfg [python: **.py] -[jinja2: templates/**.html] +[jinja2: **/templates/**.html] +extensions=jinja2.ext.autoescape,jinja2.ext.with_ EOL # 5. Dockerfile @@ -295,7 +850,19 @@ FROM python:3.10-slim SHELL ["/bin/bash", "-c"] -RUN mkdir -p /app/data && chmod -R a+rwX /app/data +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 . @@ -317,79 +884,108 @@ DOCKER_END # 6. docker-compose.yml cat < docker-compose.yml - services: steam-manager: build: . ports: - "5000:5000" - volumes: - - $DATA_DIR:/app/data - - $TRANSLATIONS_DIR:/app/translations environment: - - FLASK_DEBUG=0 + - 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 ../steam-translations -chmod -R a+rwX ../data ../steam-translations +mkdir -p ../data ../translations +chmod -R a+rwX ../data ../translations -# 8. Übersetzungs-Workflow-Script +# 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 . -for lang in de en; do - if [ ! -f "../steam-translations/$lang/LC_MESSAGES/messages.po" ]; then - docker-compose exec steam-manager pybabel init -i translations/messages.pot -d translations -l $lang - fi +# 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 extrahiert, aktualisiert und kompiliert!" +echo "✅ Übersetzungen aktualisiert!" SCRIPT_END chmod +x ../translate.sh -# 9. Templates (nur neue/erweiterte hier, Rest wie gehabt) +cat <<'SCRIPT_END' > ../upgrade.sh +#!/bin/bash +set -e -cat < templates/import.html -{% extends "base.html" %} -{% block content %} -
-

{{ _('Import Games') }}

-
-
- - -
- - {{ _('Abbrechen') }} -
-
-{% endblock %} -HTML_END +# 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 +mkdir -p templates static + +# Base Template cat < templates/base.html - {{ _('Steam Manager') }} + + {{ _('Game Key Manager') }}