import os from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify, send_from_directory from flask_migrate import Migrate from pdf2image import convert_from_path import subprocess from werkzeug.utils import secure_filename from functools import wraps from extensions import db, bcrypt, login_manager from models import User, Player, Content, Group # Add Group to the imports from flask_login import login_user, logout_user, login_required, current_user from pptx import Presentation from pptx.util import Inches from PIL import Image import io import threading app = Flask(__name__, instance_relative_config=True) # Set the secret key from environment variable or use a default value app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'Ana_Are_Multe_Mere-Si_Nu_Are_Pere') # Configure the database location to be in the instance folder app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'dashboard.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Set maximum content length to 1GB app.config['MAX_CONTENT_LENGTH'] = 2048 * 2048 * 2048 # 2GB, adjust as needed # Ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True) db.init_app(app) bcrypt.init_app(app) login_manager.init_app(app) UPLOAD_FOLDER = 'static/uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER UPLOAD_FOLDERLOGO = 'static/resurse' app.config['UPLOAD_FOLDERLOGO'] = UPLOAD_FOLDERLOGO # Ensure the upload folder exists if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) os.makedirs(UPLOAD_FOLDERLOGO) login_manager.login_view = 'login' migrate = Migrate(app, db) @login_manager.user_loader def load_user(user_id): return db.session.get(User, int(user_id)) def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if current_user.role != 'admin': return redirect(url_for('dashboard')) return f(*args, **kwargs) return decorated_function def add_image_to_playlist(file, filename, duration, target_type, target_id): """ Save the image file and add it to the playlist database. """ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) # Only save if file does not already exist (prevents double-saving) if not os.path.exists(file_path): file.save(file_path) if target_type == 'group': group = Group.query.get_or_404(target_id) for player in group.players: new_content = Content(file_name=filename, duration=duration, player_id=player.id) db.session.add(new_content) elif target_type == 'player': new_content = Content(file_name=filename, duration=duration, player_id=target_id) db.session.add(new_content) def convert_ppt_to_images(input_file, output_folder): """ Converts a PowerPoint file (.ppt or .pptx) to images using LibreOffice. Each slide is saved as a separate image in the output folder. """ if not os.path.exists(output_folder): os.makedirs(output_folder) # Convert the PowerPoint file to images using LibreOffice command = [ 'libreoffice', '--headless', '--convert-to', 'png', '--outdir', output_folder, input_file ] try: subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(f"PPT file converted to images: {input_file}") except subprocess.CalledProcessError as e: print(f"Error converting PPT to images: {e.stderr.decode()}") return False # Rename the generated images to follow the naming convention base_name = os.path.splitext(os.path.basename(input_file))[0] for i, file_name in enumerate(sorted(os.listdir(output_folder))): if file_name.endswith('.png'): new_name = f"{base_name}_{i + 1}.png" os.rename(os.path.join(output_folder, file_name), os.path.join(output_folder, new_name)) return True def convert_pdf_to_images(input_file, output_folder): """ Converts a PDF file to images using pdf2image. Each page is saved as a separate image in the output folder. """ if not os.path.exists(output_folder): os.makedirs(output_folder) # Convert the PDF file to images images = convert_from_path(input_file, dpi=300) base_name = os.path.splitext(os.path.basename(input_file))[0] for i, image in enumerate(images): image_filename = f"{base_name}_{i + 1}.jpg" image_path = os.path.join(output_folder, image_filename) image.save(image_path, 'JPEG') # Delete the original PDF file after conversion if os.path.exists(input_file): os.remove(input_file) print(f"Original PDF file deleted: {input_file}") def convert_video(input_file, output_folder): """ Converts a video file to MP4 format with H.264 codec, 720p resolution, and 30 FPS. Args: input_file (str): Path to the input video file. output_folder (str): Path to the folder where the converted video will be saved. Returns: str: Path to the converted video file, or None if conversion fails. """ if not os.path.exists(output_folder): os.makedirs(output_folder) # Generate the output file path base_name = os.path.splitext(os.path.basename(input_file))[0] output_file = os.path.join(output_folder, f"{base_name}.mp4") # FFmpeg command to convert the video command = [ "ffmpeg", "-i", input_file, # Input file "-c:v", "libx264", # Video codec: H.264 "-preset", "fast", # Encoding speed/quality tradeoff "-crf", "23", # Constant Rate Factor (quality, lower is better) "-vf", "scale=-1:720", # Scale video to 720p (preserve aspect ratio) "-r", "30", # Frame rate: 30 FPS "-c:a", "aac", # Audio codec: AAC "-b:a", "128k", # Audio bitrate output_file # Output file ] try: # Run the FFmpeg command subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(f"Video converted successfully: {output_file}") return output_file except subprocess.CalledProcessError as e: print(f"Error converting video: {e.stderr.decode()}") return None def convert_video_and_update_playlist(file_path, original_filename, target_type, target_id, duration): print(f"Starting video conversion for: {file_path}") converted_file = convert_video(file_path, app.config['UPLOAD_FOLDER']) if converted_file: converted_filename = os.path.basename(converted_file) print(f"Video converted successfully: {converted_filename}") # Use the application context to interact with the database with app.app_context(): # Update the database with the converted filename if target_type == 'group': group = Group.query.get_or_404(target_id) for player in group.players: content = Content.query.filter_by(player_id=player.id, file_name=original_filename).first() if content: content.file_name = converted_filename elif target_type == 'player': content = Content.query.filter_by(player_id=target_id, file_name=original_filename).first() if content: content.file_name = converted_filename db.session.commit() print(f"Database updated with converted video: {converted_filename}") # Delete the original file only if it exists if os.path.exists(file_path): os.remove(file_path) print(f"Original file deleted: {file_path}") else: print(f"Video conversion failed for: {file_path}") # Convert EMU to pixels def emu_to_pixels(emu): return int(emu / 914400 * 96) @app.route('/') @login_required def dashboard(): players = Player.query.all() groups = Group.query.all() logo_exists = os.path.exists(os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'logo.png')) return render_template('dashboard.html', players=players, groups=groups, logo_exists=logo_exists) @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') new_user = User(username=username, password=hashed_password, role='user') db.session.add(new_user) db.session.commit() return redirect(url_for('login')) return render_template('register.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username).first() if user and bcrypt.check_password_hash(user.password, password): login_user(user) return redirect(url_for('dashboard')) else: flash('Login Unsuccessful. Please check username and password', 'danger') login_picture_exists = os.path.exists(os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'login_picture.png')) return render_template('login.html', login_picture_exists=login_picture_exists) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('login')) @app.route('/upload_content', methods=['GET', 'POST']) @login_required @admin_required def upload_content(): if request.method == 'POST': target_type = request.form.get('target_type') target_id = request.form.get('target_id') files = request.files.getlist('files') duration = int(request.form['duration']) return_url = request.form.get('return_url') media_type = request.form['media_type'] if not target_type or not target_id: flash('Please select a target type and target ID.', 'danger') return redirect(url_for('upload_content')) for file in files: try: # Generate a secure filename and save the file filename = secure_filename(file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) filename = secure_filename(file.filename) file_ext = os.path.splitext(filename)[1].lower() # Handle PDF files if media_type == 'pdf': print(f"Processing PDF file: {file_path}") convert_pdf_to_images(file_path, app.config['UPLOAD_FOLDER']) # Add the converted images to the playlist if target_type == 'group': group = Group.query.get_or_404(target_id) for player in group.players: for image_file in os.listdir(app.config['UPLOAD_FOLDER']): if image_file.startswith(os.path.splitext(filename)[0]) and image_file.endswith('.jpg'): new_content = Content(file_name=image_file, duration=duration, player_id=player.id) db.session.add(new_content) elif target_type == 'player': for image_file in os.listdir(app.config['UPLOAD_FOLDER']): if image_file.startswith(os.path.splitext(filename)[0]) and image_file.endswith('.jpg'): new_content = Content(file_name=image_file, duration=duration, player_id=target_id) db.session.add(new_content) # --- Add this block for images --- elif media_type in ['jpg', 'jpeg', 'png'] or (media_type == 'image' and file_ext in ['.jpg', '.jpeg', '.png']): add_image_to_playlist(file, filename, duration, target_type, target_id) # Handle video files elif media_type == 'video': # Add the video file to the playlist if target_type == 'group': group = Group.query.get_or_404(target_id) for player in group.players: new_content = Content(file_name=filename, duration=duration, player_id=player.id) db.session.add(new_content) elif target_type == 'player': new_content = Content(file_name=filename, duration=duration, player_id=target_id) db.session.add(new_content) # Launch the video conversion function in a thread thread = threading.Thread(target=convert_video_and_update_playlist, args=(file_path, filename, target_type, target_id, duration)) thread.start() # Handle PPT files elif media_type == 'ppt': print(f"Processing PPT file: {file_path}") success = convert_ppt_to_images(file_path, app.config['UPLOAD_FOLDER']) if success: # Add each slide image to the playlist base_name = os.path.splitext(filename)[0] for slide_image in sorted(os.listdir(app.config['UPLOAD_FOLDER'])): if slide_image.startswith(base_name) and slide_image.endswith('.png'): if target_type == 'group': group = Group.query.get_or_404(target_id) for player in group.players: new_content = Content(file_name=slide_image, duration=duration, player_id=player.id) db.session.add(new_content) elif target_type == 'player': new_content = Content(file_name=slide_image, duration=duration, player_id=target_id) db.session.add(new_content) # Commit the changes to the database db.session.commit() # Remove the original PPT file after processing if os.path.exists(file_path): os.remove(file_path) print(f"Original PPT file deleted: {file_path}") else: print(f"Failed to process PPT file: {file_path}") flash(f"Failed to process PPT file: {file_path}", 'danger') except Exception as e: print(f"Error processing file {filename}: {e}") flash(f"Error processing file {filename}: {e}", 'danger') db.session.commit() return redirect(return_url) # Handle GET request target_type = request.args.get('target_type') target_id = request.args.get('target_id') return_url = request.args.get('return_url', url_for('dashboard')) players = [{'id': player.id, 'username': player.username} for player in Player.query.all()] groups = [{'id': group.id, 'name': group.name} for group in Group.query.all()] return render_template('upload_content.html', target_type=target_type, target_id=target_id, players=players, groups=groups, return_url=return_url) @app.route('/admin') @login_required @admin_required def admin(): logo_exists = os.path.exists(os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'logo.png')) login_picture_exists = os.path.exists(os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'login_picture.png')) users = User.query.all() return render_template('admin.html', users=users, logo_exists=logo_exists, login_picture_exists=login_picture_exists) @app.route('/admin/change_role/', methods=['POST']) @login_required @admin_required def change_role(user_id): user = User.query.get_or_404(user_id) new_role = request.form['role'] user.role = new_role db.session.commit() return redirect(url_for('admin')) @app.route('/admin/delete_user/', methods=['POST']) @login_required @admin_required def delete_user(user_id): user = User.query.get_or_404(user_id) db.session.delete(user) db.session.commit() return redirect(url_for('admin')) @app.route('/admin/create_user', methods=['POST']) @login_required @admin_required def create_user(): username = request.form['username'] password = request.form['password'] role = request.form['role'] hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') new_user = User(username=username, password=hashed_password, role=role) db.session.add(new_user) db.session.commit() return redirect(url_for('admin')) @app.route('/player/') @login_required def player_page(player_id): player = db.session.get(Player, player_id) content = Content.query.filter_by(player_id=player_id).all() return render_template('player_page.html', player=player, content=content) @app.route('/player//upload', methods=['POST']) @login_required def upload_content_to_player(player_id): player = Player.query.get_or_404(player_id) files = request.files.getlist('files') duration = int(request.form['duration']) for file in files: filename = secure_filename(file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) new_content = Content(file_name=filename, duration=duration, player_id=player_id) db.session.add(new_content) db.session.commit() return redirect(url_for('player_page', player_id=player_id)) @app.route('/content//edit', methods=['POST']) @login_required def edit_content(content_id): content = Content.query.get_or_404(content_id) new_duration = int(request.form['duration']) content.duration = new_duration db.session.commit() return redirect(url_for('player_page', player_id=content.player_id)) @app.route('/content//delete', methods=['POST']) @login_required def delete_content(content_id): content = Content.query.get_or_404(content_id) player_id = content.player_id db.session.delete(content) db.session.commit() return redirect(url_for('player_page', player_id=player_id)) @app.route('/player//fullscreen', methods=['GET', 'POST']) def player_fullscreen(player_id): player = Player.query.get_or_404(player_id) if request.method == 'POST': hostname = request.form['hostname'] password = request.form['password'] quickconnect_password = request.form.get('quickconnect_password') if quickconnect_password: if player.hostname == hostname and bcrypt.check_password_hash(player.quickconnect_password, quickconnect_password): authenticated = True else: authenticated = False else: if player.hostname == hostname and bcrypt.check_password_hash(player.password, password): authenticated = True else: authenticated = False else: authenticated = False if authenticated or current_user.is_authenticated: content = Content.query.filter_by(player_id=player_id).all() return render_template('player_fullscreen.html', player=player, content=content) else: return render_template('player_auth.html', player_id=player_id) @app.route('/player//delete', methods=['POST']) @login_required @admin_required def delete_player(player_id): player = Player.query.get_or_404(player_id) # Delete all media related to the player media_items = Content.query.filter_by(player_id=player_id).all() for media in media_items: db.session.delete(media) # Delete the player db.session.delete(player) db.session.commit() return redirect(url_for('dashboard')) @app.route('/player/add', methods=['GET', 'POST']) @login_required @admin_required def add_player(): if request.method == 'POST': username = request.form['username'] hostname = request.form['hostname'] password = bcrypt.generate_password_hash(request.form['password']).decode('utf-8') quickconnect_password = bcrypt.generate_password_hash(request.form['quickconnect_password']).decode('utf-8') new_player = Player(username=username, hostname=hostname, password=password, quickconnect_password=quickconnect_password) db.session.add(new_player) db.session.commit() return redirect(url_for('dashboard')) return render_template('add_player.html') @app.route('/player//edit', methods=['GET', 'POST']) @login_required @admin_required def edit_player(player_id): player = Player.query.get_or_404(player_id) if request.method == 'POST': player.username = request.form['username'] player.hostname = request.form['hostname'] if request.form['password']: player.password = bcrypt.generate_password_hash(request.form['password']).decode('utf-8') if request.form['quickconnect_password']: player.quickconnect_password = bcrypt.generate_password_hash(request.form['quickconnect_password']).decode('utf-8') db.session.commit() return redirect(url_for('player_page', player_id=player.id)) return_url = request.args.get('return_url', url_for('player_page', player_id=player.id)) return render_template('edit_player.html', player=player, return_url=return_url) @app.route('/change_theme', methods=['POST']) @login_required @admin_required def change_theme(): theme = request.form['theme'] current_user.theme = theme db.session.commit() return redirect(url_for('admin')) @app.route('/upload_logo', methods=['POST']) @login_required @admin_required def upload_logo(): if 'logo' not in request.files: return redirect(url_for('admin')) file = request.files['logo'] if file.filename == '': return redirect(url_for('admin')) if file: filename = secure_filename(file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'logo.png') file.save(file_path) return redirect(url_for('admin')) @app.route('/upload_personalization_pictures', methods=['POST']) @login_required @admin_required def upload_personalization_pictures(): logo_file = request.files.get('logo') login_picture_file = request.files.get('login_picture') if logo_file and logo_file.filename != '': logo_filename = secure_filename(logo_file.filename) logo_file_path = os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'logo.png') logo_file.save(logo_file_path) if login_picture_file and login_picture_file.filename != '': login_picture_filename = secure_filename(login_picture_file.filename) login_picture_file_path = os.path.join(app.config['UPLOAD_FOLDERLOGO'], 'login_picture.png') login_picture_file.save(login_picture_file_path) return redirect(url_for('admin')) @app.route('/clean_unused_files', methods=['POST']) @login_required @admin_required def clean_unused_files(): # Get all file names from the database content_files = {content.file_name for content in Content.query.all()} logo_file = 'resurse/logo.png' login_picture_file = 'resurse/login_picture.png' # Debugging: Print the content files from the database print("Content files from database:", content_files) # Get all files in the upload folder all_files = set(os.listdir(app.config['UPLOAD_FOLDER'])) # Determine unused files used_files = content_files | {logo_file, login_picture_file} unused_files = all_files - used_files # Debugging: Print the lists of files print("All files:", all_files) print("Used files:", used_files) print("Unused files:", unused_files) # Delete unused files for file_name in unused_files: file_path = os.path.join(app.config['UPLOAD_FOLDER'], file_name) if os.path.isfile(file_path): print(f"Deleting file: {file_path}") # Debugging: Print the file being deleted os.remove(file_path) flash('Unused files have been cleaned.', 'success') return redirect(url_for('admin')) @app.route('/api/playlists', methods=['GET']) def get_playlist(): hostname = request.args.get('hostname') quickconnect_code = request.args.get('quickconnect_code') if not hostname or not quickconnect_code: return jsonify({'error': 'Hostname and quick connect code are required'}), 400 player = Player.query.filter_by(hostname=hostname).first() if not player or not player.verify_quickconnect_code(quickconnect_code): return jsonify({'error': 'Invalid hostname or quick connect code'}), 404 content = Content.query.filter_by(player_id=player.id).all() playlist = [{'file_name': item.file_name, 'duration': item.duration, 'url': url_for('media', filename=item.file_name, _external=True)} for item in content] return jsonify({'playlist': playlist}) @app.route('/media/') def media(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) @app.context_processor def inject_theme(): if current_user.is_authenticated: theme = current_user.theme else: theme = 'light' return dict(theme=theme) @app.route('/group/create', methods=['GET', 'POST']) @login_required @admin_required def create_group(): if request.method == 'POST': group_name = request.form['name'] player_ids = request.form.getlist('players') new_group = Group(name=group_name) for player_id in player_ids: player = Player.query.get(player_id) if player: new_group.players.append(player) db.session.add(new_group) db.session.commit() return redirect(url_for('dashboard')) players = Player.query.all() return render_template('create_group.html', players=players) @app.route('/group//manage') @login_required @admin_required def manage_group(group_id): group = Group.query.get_or_404(group_id) # Get unique media files for the group content = ( db.session.query(Content.id, Content.file_name, db.func.min(Content.duration).label('duration')) .filter(Content.player_id.in_([player.id for player in group.players])) .group_by(Content.file_name) .all() ) return render_template('manage_group.html', group=group, content=content) @app.route('/group//edit', methods=['GET', 'POST']) @login_required @admin_required def edit_group(group_id): group = Group.query.get_or_404(group_id) if request.method == 'POST': group.name = request.form['name'] player_ids = request.form.getlist('players') group.players = [Player.query.get(player_id) for player_id in player_ids if Player.query.get(player_id)] db.session.commit() return redirect(url_for('dashboard')) players = Player.query.all() return render_template('edit_group.html', group=group, players=players) @app.route('/group//delete', methods=['POST']) @login_required @admin_required def delete_group(group_id): group = Group.query.get_or_404(group_id) db.session.delete(group) db.session.commit() return redirect(url_for('dashboard')) @app.route('/group//fullscreen', methods=['GET']) @login_required def group_fullscreen(group_id): group = Group.query.get_or_404(group_id) content = Content.query.filter(Content.player_id.in_([player.id for player in group.players])).all() return render_template('group_fullscreen.html', group=group, content=content) @app.route('/group//media//edit', methods=['POST']) @login_required @admin_required def edit_group_media(group_id, content_id): group = Group.query.get_or_404(group_id) new_duration = int(request.form['duration']) # Update the duration for all players in the group for player in group.players: content = Content.query.filter_by(player_id=player.id, file_name=Content.query.get(content_id).file_name).first() if content: content.duration = new_duration db.session.commit() return redirect(url_for('manage_group', group_id=group_id)) @app.route('/group//media//delete', methods=['POST']) @login_required @admin_required def delete_group_media(group_id, content_id): group = Group.query.get_or_404(group_id) file_name = Content.query.get(content_id).file_name # Delete the media for all players in the group for player in group.players: content = Content.query.filter_by(player_id=player.id, file_name=file_name).first() if content: db.session.delete(content) db.session.commit() return redirect(url_for('manage_group', group_id=group_id)) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)