final upload
This commit is contained in:
359
app.py
359
app.py
@@ -1,15 +1,36 @@
|
||||
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
|
||||
|
||||
# First import models
|
||||
from models import User, Player, Content, Group, ServerLog
|
||||
|
||||
# Then import utilities that use the models
|
||||
from flask_login import login_user, logout_user, login_required, current_user
|
||||
from pptx_to_images import convert_pptx_to_images # Assuming you have a module for PPTX conversion
|
||||
import os
|
||||
from utils.logger import get_recent_logs, log_action, log_upload, log_process
|
||||
from utils.group_player_management import (
|
||||
create_group as create_group_util,
|
||||
edit_group as edit_group_util,
|
||||
delete_group as delete_group_util,
|
||||
add_player as add_player_util,
|
||||
edit_player as edit_player_util,
|
||||
delete_player as delete_player_util,
|
||||
get_group_content
|
||||
)
|
||||
|
||||
# Finally, import modules that depend on both models and logger
|
||||
from utils.uploads import (
|
||||
add_image_to_playlist,
|
||||
convert_video_and_update_playlist,
|
||||
process_pdf,
|
||||
process_pptx,
|
||||
process_uploaded_files
|
||||
)
|
||||
|
||||
# Define global variables for server version and build date
|
||||
SERVER_VERSION = "1.0.0"
|
||||
BUILD_DATE = "2025-06-25"
|
||||
@@ -59,214 +80,14 @@ def admin_required(f):
|
||||
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.
|
||||
Increment the playlist version for the player or group.
|
||||
"""
|
||||
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)
|
||||
# Increment playlist version for each player in the group
|
||||
player.playlist_version += 1
|
||||
# Increment playlist version for the group
|
||||
group.playlist_version += 1
|
||||
elif target_type == 'player':
|
||||
player = Player.query.get_or_404(target_id)
|
||||
new_content = Content(file_name=filename, duration=duration, player_id=target_id)
|
||||
db.session.add(new_content)
|
||||
# Increment playlist version for the player
|
||||
player.playlist_version += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
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:1080", # 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}")
|
||||
|
||||
def convert_pdf_to_images_and_update_playlist(pdf_file, output_folder, duration, target_type, target_id, delete_pdf=True):
|
||||
"""
|
||||
Converts a PDF file to images and adds them to the playlist.
|
||||
Can be used by both direct PDF uploads and PPTX conversions.
|
||||
"""
|
||||
print(f"Converting PDF to images: {pdf_file}") # Debugging
|
||||
try:
|
||||
images = convert_from_path(pdf_file, dpi=300)
|
||||
print(f"Number of pages in PDF: {len(images)}") # Debugging
|
||||
base_name = os.path.splitext(os.path.basename(pdf_file))[0]
|
||||
image_filenames = []
|
||||
|
||||
for i, image in enumerate(images):
|
||||
image_filename = f"{base_name}_page_{i + 1}.jpg"
|
||||
image_path = os.path.join(output_folder, image_filename)
|
||||
image.save(image_path, 'JPEG')
|
||||
image_filenames.append(image_filename)
|
||||
print(f"Saved page {i + 1} as image: {image_path}") # Debugging
|
||||
|
||||
# Add images to playlist
|
||||
if target_type == 'group':
|
||||
group = Group.query.get_or_404(target_id)
|
||||
for player in group.players:
|
||||
for image_filename in image_filenames:
|
||||
new_content = Content(file_name=image_filename, duration=duration, player_id=player.id)
|
||||
db.session.add(new_content)
|
||||
player.playlist_version += 1
|
||||
group.playlist_version += 1
|
||||
elif target_type == 'player':
|
||||
player = Player.query.get_or_404(target_id)
|
||||
for image_filename in image_filenames:
|
||||
new_content = Content(file_name=image_filename, duration=duration, player_id=target_id)
|
||||
db.session.add(new_content)
|
||||
player.playlist_version += 1
|
||||
|
||||
db.session.commit()
|
||||
print(f"Added {len(image_filenames)} pages to playlist")
|
||||
|
||||
# Delete the PDF file if requested
|
||||
if delete_pdf and os.path.exists(pdf_file):
|
||||
os.remove(pdf_file)
|
||||
print(f"PDF file deleted: {pdf_file}")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error converting PDF to images: {e}")
|
||||
return False
|
||||
|
||||
def convert_pdf_to_images_and_upload(input_file, output_folder, duration, target_type, target_id):
|
||||
"""
|
||||
Converts a PDF file to images and adds them to the playlist.
|
||||
Each page is saved as a separate image in the output folder.
|
||||
"""
|
||||
print(f"Converting PDF file: {input_file}") # Debugging
|
||||
if not os.path.exists(output_folder):
|
||||
os.makedirs(output_folder)
|
||||
|
||||
# Convert PDF to images and update playlist
|
||||
return convert_pdf_to_images_and_update_playlist(input_file, output_folder, duration, target_type, target_id, True)
|
||||
|
||||
def convert_pptx_to_images_and_upload(input_file, output_folder, duration, target_type, target_id):
|
||||
"""
|
||||
Converts a PowerPoint file (.pptx) to individual slide images by first converting it to a PDF.
|
||||
Each slide is saved as a separate image in the output folder and added to the playlist.
|
||||
"""
|
||||
command = [
|
||||
"python", "pptx_to_images.py", input_file, output_folder
|
||||
]
|
||||
try:
|
||||
subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error converting PPTX: {e.stderr.decode()}")
|
||||
return False
|
||||
|
||||
# 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)
|
||||
server_logs = get_recent_logs(20) # Get the 20 most recent logs
|
||||
return render_template('dashboard.html', players=players, groups=groups, logo_exists=logo_exists, server_logs=server_logs)
|
||||
|
||||
@app.route('/register', methods=['GET', 'POST'])
|
||||
def register():
|
||||
@@ -313,46 +134,14 @@ def upload_content():
|
||||
return_url = request.form.get('return_url')
|
||||
media_type = request.form['media_type']
|
||||
|
||||
print(f"Target Type: {target_type}, Target ID: {target_id}, Media Type: {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)
|
||||
file_ext = os.path.splitext(filename)[1].lower()
|
||||
|
||||
if media_type == 'ppt':
|
||||
print(f"Processing PPT file: {file_path}")
|
||||
success = convert_pptx_to_images(file_path, app.config['UPLOAD_FOLDER'])
|
||||
|
||||
if success:
|
||||
base_name = os.path.splitext(filename)[0]
|
||||
# Find all PNGs generated for this PPTX
|
||||
slide_images = sorted([
|
||||
f for f in os.listdir(app.config['UPLOAD_FOLDER'])
|
||||
if (f.startswith(base_name) and f.endswith('.png'))
|
||||
])
|
||||
print("Slide images found:", slide_images)
|
||||
if target_type == 'group':
|
||||
group = Group.query.get_or_404(target_id)
|
||||
for player in group.players:
|
||||
for slide_image in slide_images:
|
||||
new_content = Content(file_name=slide_image, duration=duration, player_id=player.id)
|
||||
db.session.add(new_content)
|
||||
elif target_type == 'player':
|
||||
for slide_image in slide_images:
|
||||
new_content = Content(file_name=slide_image, duration=duration, player_id=target_id)
|
||||
db.session.add(new_content)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error processing file {file.filename}: {e}")
|
||||
flash(f"Error processing file {file.filename}: {e}", 'danger')
|
||||
|
||||
db.session.commit()
|
||||
# Process uploaded files and get results
|
||||
results = process_uploaded_files(app, files, media_type, duration, target_type, target_id)
|
||||
|
||||
return redirect(return_url)
|
||||
|
||||
@@ -364,7 +153,8 @@ def upload_content():
|
||||
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)
|
||||
return render_template('upload_content.html', target_type=target_type, target_id=target_id,
|
||||
players=players, groups=groups, return_url=return_url)
|
||||
|
||||
|
||||
|
||||
@@ -400,8 +190,11 @@ def change_role(user_id):
|
||||
@admin_required
|
||||
def delete_user(user_id):
|
||||
user = User.query.get_or_404(user_id)
|
||||
username = user.username # Store username before deletion for logging
|
||||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
# Add log entry for user deletion
|
||||
log_user_deleted(username)
|
||||
return redirect(url_for('admin'))
|
||||
|
||||
@app.route('/admin/create_user', methods=['POST'])
|
||||
@@ -415,6 +208,8 @@ def create_user():
|
||||
new_user = User(username=username, password=hashed_password, role=role)
|
||||
db.session.add(new_user)
|
||||
db.session.commit()
|
||||
# Add log entry for user creation
|
||||
log_user_created(username, role)
|
||||
return redirect(url_for('admin'))
|
||||
|
||||
@app.route('/player/<int:player_id>')
|
||||
@@ -504,6 +299,7 @@ def delete_player(player_id):
|
||||
|
||||
return redirect(url_for('dashboard'))
|
||||
|
||||
# Update the add_player function
|
||||
@app.route('/player/add', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
@@ -513,9 +309,8 @@ def add_player():
|
||||
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()
|
||||
add_player_util(username, hostname, password, quickconnect_password)
|
||||
flash(f'Player "{username}" added successfully.', 'success')
|
||||
return redirect(url_for('dashboard'))
|
||||
return render_template('add_player.html')
|
||||
|
||||
@@ -525,13 +320,12 @@ def add_player():
|
||||
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()
|
||||
username = request.form['username']
|
||||
hostname = request.form['hostname']
|
||||
password = request.form['password'] if request.form['password'] else None
|
||||
quickconnect_password = request.form['quickconnect_password'] if request.form['quickconnect_password'] else None
|
||||
edit_player_util(player_id, username, hostname, password, quickconnect_password)
|
||||
flash(f'Player "{username}" updated successfully.', 'success')
|
||||
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))
|
||||
@@ -631,8 +425,30 @@ def get_playlists():
|
||||
if not player or not bcrypt.check_password_hash(player.quickconnect_password, quickconnect_code):
|
||||
return jsonify({'error': 'Invalid hostname or quick connect code'}), 404
|
||||
|
||||
# Query the Content table for media files associated with the player
|
||||
content = Content.query.filter_by(player_id=player.id).all()
|
||||
# Check if player is locked to a group
|
||||
if player.locked_to_group_id:
|
||||
# Get content for all players in the group to ensure shared content
|
||||
group_players = player.locked_to_group.players
|
||||
player_ids = [p.id for p in group_players]
|
||||
|
||||
# Use the first occurrence of each file for the playlist
|
||||
content_query = (
|
||||
db.session.query(
|
||||
Content.file_name,
|
||||
db.func.min(Content.id).label('id'),
|
||||
db.func.min(Content.duration).label('duration')
|
||||
)
|
||||
.filter(Content.player_id.in_(player_ids))
|
||||
.group_by(Content.file_name)
|
||||
)
|
||||
|
||||
content = db.session.query(Content).filter(
|
||||
Content.id.in_([c.id for c in content_query])
|
||||
).all()
|
||||
else:
|
||||
# Get player's individual content
|
||||
content = Content.query.filter_by(player_id=player.id).all()
|
||||
|
||||
playlist = [
|
||||
{
|
||||
'file_name': media.file_name,
|
||||
@@ -668,13 +484,8 @@ 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()
|
||||
create_group_util(group_name, player_ids)
|
||||
flash(f'Group "{group_name}" created successfully.', 'success')
|
||||
return redirect(url_for('dashboard'))
|
||||
players = Player.query.all()
|
||||
return render_template('create_group.html', players=players)
|
||||
@@ -684,15 +495,7 @@ def create_group():
|
||||
@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()
|
||||
)
|
||||
|
||||
content = get_group_content(group_id)
|
||||
return render_template('manage_group.html', group=group, content=content)
|
||||
|
||||
@app.route('/group/<int:group_id>/edit', methods=['GET', 'POST'])
|
||||
@@ -701,10 +504,10 @@ def manage_group(group_id):
|
||||
def edit_group(group_id):
|
||||
group = Group.query.get_or_404(group_id)
|
||||
if request.method == 'POST':
|
||||
group.name = request.form['name']
|
||||
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()
|
||||
edit_group_util(group_id, name, player_ids)
|
||||
flash(f'Group "{name}" updated successfully.', 'success')
|
||||
return redirect(url_for('dashboard'))
|
||||
players = Player.query.all()
|
||||
return render_template('edit_group.html', group=group, players=players)
|
||||
@@ -714,8 +517,9 @@ def edit_group(group_id):
|
||||
@admin_required
|
||||
def delete_group(group_id):
|
||||
group = Group.query.get_or_404(group_id)
|
||||
db.session.delete(group)
|
||||
db.session.commit()
|
||||
group_name = group.name
|
||||
delete_group_util(group_id)
|
||||
flash(f'Group "{group_name}" deleted successfully.', 'success')
|
||||
return redirect(url_for('dashboard'))
|
||||
|
||||
@app.route('/group/<int:group_id>/fullscreen', methods=['GET'])
|
||||
@@ -777,6 +581,5 @@ def get_playlist_version():
|
||||
'hashed_quickconnect': player.quickconnect_password
|
||||
})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=5000, debug=True)
|
||||
app.run(debug=True, host='0.0.0.0')
|
||||
Reference in New Issue
Block a user