""" Settings routes for the Podcastrr application. """ from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app import os from app.models.settings import Settings from app.models.database import db settings_bp = Blueprint('settings', __name__) @settings_bp.route('/', methods=['GET', 'POST']) def index(): """ Display and update application settings. """ # Get current settings settings = Settings.query.first() # If no settings exist, create default settings if not settings: settings = Settings( download_path=current_app.config['DOWNLOAD_PATH'], naming_format="{podcast_title}/{episode_title}", auto_download=False, max_downloads=5, delete_after_days=30 ) db.session.add(settings) db.session.commit() if request.method == 'POST': # Update settings download_path = request.form.get('download_path') naming_format = request.form.get('naming_format') auto_download = 'auto_download' in request.form max_downloads = int(request.form.get('max_downloads', 5)) delete_after_days = int(request.form.get('delete_after_days', 30)) # Validate download path if not os.path.exists(download_path): try: os.makedirs(download_path, exist_ok=True) except Exception as e: flash(f'Error creating download directory: {str(e)}', 'error') return render_template('settings/index.html', title='Settings', settings=settings) # Update settings settings.download_path = download_path settings.naming_format = naming_format settings.auto_download = auto_download settings.max_downloads = max_downloads settings.delete_after_days = delete_after_days db.session.commit() # Update application config current_app.config['DOWNLOAD_PATH'] = download_path flash('Settings updated successfully!', 'success') return redirect(url_for('settings.index')) return render_template('settings/index.html', title='Settings', settings=settings) @settings_bp.route('/naming-preview', methods=['POST']) def naming_preview(): """ Preview the naming format. """ naming_format = request.form.get('naming_format', '') # Example data for preview example_data = { 'podcast_title': 'Example Podcast', 'episode_title': 'Episode 1: Introduction', 'published_date': '2023-01-01', 'episode_number': '1' } try: # Format the example data with the naming format preview = naming_format.format(**example_data) return {'preview': preview} except Exception as e: return {'error': str(e)}