final upload

This commit is contained in:
2025-06-27 16:50:35 +03:00
parent d154853c7d
commit 67c9083a6e
24 changed files with 760 additions and 322 deletions

0
utils/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,161 @@
from models import Player, Group, Content
from extensions import db
from utils.logger import log_group_created, log_group_edited, log_group_deleted
from utils.logger import log_player_created, log_player_edited, log_player_deleted
def create_group(name, player_ids):
"""
Create a new group with the given name and add selected players to it.
Clears individual playlists of players and locks them to the group.
"""
new_group = Group(name=name)
db.session.add(new_group)
db.session.flush() # Get the group ID
# Add players to the group and lock them
for player_id in player_ids:
player = Player.query.get(player_id)
if player:
# Add player to group
new_group.players.append(player)
# Delete player's individual playlist
Content.query.filter_by(player_id=player.id).delete()
# Lock player to this group
player.locked_to_group_id = new_group.id
db.session.commit()
log_group_created(name)
return new_group
def edit_group(group_id, name, player_ids):
"""
Edit an existing group, updating its name and players.
Handles locking/unlocking players appropriately.
"""
group = Group.query.get_or_404(group_id)
group.name = name
# Get current players in the group
current_player_ids = [player.id for player in group.players]
# Determine players to add and remove
players_to_add = [pid for pid in player_ids if pid not in current_player_ids]
players_to_remove = [pid for pid in current_player_ids if pid not in player_ids]
# Handle players to add
for player_id in players_to_add:
player = Player.query.get(player_id)
if player:
# Add to group
group.players.append(player)
# Delete individual playlist
Content.query.filter_by(player_id=player.id).delete()
# Lock to group
player.locked_to_group_id = group.id
# Handle players to remove
for player_id in players_to_remove:
player = Player.query.get(player_id)
if player:
# Remove from group
group.players.remove(player)
# Unlock from group
player.locked_to_group_id = None
db.session.commit()
log_group_edited(group.name)
return group
def delete_group(group_id):
"""
Delete a group and unlock all associated players.
"""
group = Group.query.get_or_404(group_id)
group_name = group.name
# Unlock all players in the group
for player in group.players:
player.locked_to_group_id = None
db.session.delete(group)
db.session.commit()
log_group_deleted(group_name)
def add_player(username, hostname, password, quickconnect_password):
"""
Add a new player with the given details.
"""
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt()
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
hashed_quickconnect = bcrypt.generate_password_hash(quickconnect_password).decode('utf-8')
new_player = Player(
username=username,
hostname=hostname,
password=hashed_password,
quickconnect_password=hashed_quickconnect
)
db.session.add(new_player)
db.session.commit()
log_player_created(username, hostname)
return new_player
def edit_player(player_id, username, hostname, password=None, quickconnect_password=None):
"""
Edit an existing player's details.
"""
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt()
player = Player.query.get_or_404(player_id)
player.username = username
player.hostname = hostname
if password:
player.password = bcrypt.generate_password_hash(password).decode('utf-8')
if quickconnect_password:
player.quickconnect_password = bcrypt.generate_password_hash(quickconnect_password).decode('utf-8')
db.session.commit()
log_player_edited(username)
return player
def delete_player(player_id):
"""
Delete a player and all its content.
"""
player = Player.query.get_or_404(player_id)
username = player.username
# Delete all media related to the player
Content.query.filter_by(player_id=player_id).delete()
# Delete the player
db.session.delete(player)
db.session.commit()
log_player_deleted(username)
def get_group_content(group_id):
"""
Get unique content for a group.
"""
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 content

65
utils/logger.py Normal file
View File

@@ -0,0 +1,65 @@
import datetime
from extensions import db
from models import ServerLog
def log_action(action):
"""
Log an action to the server log database
"""
try:
new_log = ServerLog(action=action)
db.session.add(new_log)
db.session.commit()
print(f"Logged action: {action}")
except Exception as e:
print(f"Error logging action: {e}")
db.session.rollback()
def get_recent_logs(limit=20):
"""
Get the most recent log entries
"""
return ServerLog.query.order_by(ServerLog.timestamp.desc()).limit(limit).all()
# Helper functions for common log actions
def log_upload(file_type, file_name, target_type, target_name):
log_action(f"{file_type.upper()} file '{file_name}' uploaded for {target_type} '{target_name}'")
def log_process(file_type, file_name, target_type, target_name):
log_action(f"{file_type.upper()} file '{file_name}' processed for {target_type} '{target_name}'")
def log_player_created(username, hostname):
log_action(f"Player '{username}' with hostname '{hostname}' was created")
def log_player_edited(username):
log_action(f"Player '{username}' was edited")
def log_player_deleted(username):
log_action(f"Player '{username}' was deleted")
def log_group_created(name):
log_action(f"Group '{name}' was created")
def log_group_edited(name):
log_action(f"Group '{name}' was edited")
def log_group_deleted(name):
log_action(f"Group '{name}' was deleted")
def log_user_created(username, role):
log_action(f"User '{username}' with role '{role}' was created")
def log_user_role_changed(username, new_role):
log_action(f"User '{username}' role changed to '{new_role}'")
def log_user_deleted(username):
log_action(f"User '{username}' was deleted")
def log_content_deleted(content_name, target_type, target_name):
log_action(f"Content '{content_name}' removed from {target_type} '{target_name}'")
def log_settings_changed(setting_name):
log_action(f"Setting '{setting_name}' was changed")
def log_files_cleaned(count):
log_action(f"{count} unused files were cleaned from storage")

355
utils/uploads.py Normal file
View File

@@ -0,0 +1,355 @@
import os
import subprocess
from flask import Flask
from werkzeug.utils import secure_filename
from pdf2image import convert_from_path
from extensions import db
from models import Content, Player, Group
from utils.logger import log_upload, log_process
# Function to add image to playlist
def add_image_to_playlist(app, 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
if not os.path.exists(file_path):
file.save(file_path)
print(f"Adding image to playlist: {filename}, Target Type: {target_type}, Target ID: {target_id}")
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)
player.playlist_version += 1
group.playlist_version += 1
# Log the action
log_upload('image', filename, 'group', group.name)
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)
player.playlist_version += 1
# Log the action
log_upload('image', filename, 'player', player.username)
db.session.commit()
# Video conversion functions
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 1080p (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(app, 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}")
# PDF conversion functions
def convert_pdf_to_images(pdf_file, output_folder, delete_pdf=True):
"""
Convert a PDF file to images.
Args:
pdf_file (str): Path to the PDF file
output_folder (str): Path to save the images
delete_pdf (bool): Whether to delete the PDF file after processing
Returns:
list: List of generated image filenames, or empty list if conversion failed
"""
print(f"Converting PDF to images: {pdf_file}")
try:
images = convert_from_path(pdf_file, dpi=300)
print(f"Number of pages in PDF: {len(images)}")
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}")
# 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 image_filenames
except Exception as e:
print(f"Error converting PDF to images: {e}")
return []
def update_playlist_with_files(image_filenames, duration, target_type, target_id):
"""
Add files to a player or group playlist and update version numbers.
Args:
image_filenames (list): List of filenames to add to playlist
duration (int): Duration in seconds for each file
target_type (str): 'player' or 'group'
target_id (int): ID of the player or group
Returns:
bool: True if successful, False otherwise
"""
try:
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
else:
print(f"Invalid target type: {target_type}")
return False
db.session.commit()
print(f"Added {len(image_filenames)} files to playlist")
return True
except Exception as e:
db.session.rollback()
print(f"Error updating playlist: {e}")
return False
def process_pdf(input_file, output_folder, duration, target_type, target_id):
"""
Process a PDF file: convert to images and update playlist.
Args:
input_file (str): Path to the PDF file
output_folder (str): Path to save the images
duration (int): Duration in seconds for each image
target_type (str): 'player' or 'group'
target_id (int): ID of the player or group
Returns:
bool: True if successful, False otherwise
"""
# Ensure output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Convert PDF to images
image_filenames = convert_pdf_to_images(input_file, output_folder)
# Update playlist with generated images
if image_filenames:
return update_playlist_with_files(image_filenames, duration, target_type, target_id)
return False
def process_pptx(input_file, output_folder, duration, target_type, target_id):
"""
Process a PPTX file: convert to PDF, then to images, and update playlist.
Args:
input_file (str): Path to the PPTX file
output_folder (str): Path to save the images
duration (int): Duration in seconds for each image
target_type (str): 'player' or 'group'
target_id (int): ID of the player or group
Returns:
bool: True if successful, False otherwise
"""
# Ensure output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Step 1: Convert PPTX to PDF using LibreOffice
pdf_file = os.path.join(output_folder, os.path.splitext(os.path.basename(input_file))[0] + ".pdf")
command = [
'libreoffice',
'--headless',
'--convert-to', 'pdf',
'--outdir', output_folder,
input_file
]
print(f"Running LibreOffice command: {' '.join(command)}")
try:
result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"PPTX file converted to PDF: {pdf_file}")
# Step 2: Convert PDF to images and update playlist
image_filenames = convert_pdf_to_images(pdf_file, output_folder, True)
# Step 3: Delete the original PPTX file
if image_filenames and os.path.exists(input_file):
os.remove(input_file)
print(f"Original PPTX file deleted: {input_file}")
# Step 4: Update playlist with generated images
if image_filenames:
return update_playlist_with_files(image_filenames, duration, target_type, target_id)
return False
except subprocess.CalledProcessError as e:
print(f"Error converting PPTX to PDF: {e.stderr.decode() if hasattr(e, 'stderr') else str(e)}")
return False
except Exception as e:
print(f"Error processing PPTX file: {e}")
return False
def process_uploaded_files(app, files, media_type, duration, target_type, target_id):
"""
Process uploaded files based on media type and add them to playlists.
Returns:
list: List of result dictionaries with success status and messages
"""
results = []
# Get target name for logging
target_name = ""
if target_type == 'group':
group = Group.query.get_or_404(target_id)
target_name = group.name
elif target_type == 'player':
player = Player.query.get_or_404(target_id)
target_name = player.username
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)
print(f"Processing file: {filename}, Media Type: {media_type}")
result = {'filename': filename, 'success': True, 'message': ''}
if media_type == 'image':
add_image_to_playlist(app, file, filename, duration, target_type, target_id)
result['message'] = f"Image {filename} added to playlist"
log_upload('image', filename, target_type, target_name)
elif media_type == 'video':
# For videos, add to playlist then start conversion in background
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)
player.playlist_version += 1
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)
player.playlist_version += 1
db.session.commit()
# Start background conversion
import threading
threading.Thread(target=convert_video_and_update_playlist,
args=(app, file_path, filename, target_type, target_id, duration)).start()
result['message'] = f"Video {filename} added to playlist and being processed"
log_upload('video', filename, target_type, target_name)
elif media_type == 'pdf':
# For PDFs, convert to images and update playlist
success = process_pdf(file_path, app.config['UPLOAD_FOLDER'],
duration, target_type, target_id)
if success:
result['message'] = f"PDF {filename} processed successfully"
log_process('pdf', filename, target_type, target_name)
else:
result['success'] = False
result['message'] = f"Error processing PDF file: {filename}"
elif media_type == 'ppt':
# For PPT/PPTX, convert to PDF, then to images, and update playlist
success = process_pptx(file_path, app.config['UPLOAD_FOLDER'],
duration, target_type, target_id)
if success:
result['message'] = f"PowerPoint {filename} processed successfully"
log_process('ppt', filename, target_type, target_name)
else:
result['success'] = False
result['message'] = f"Error processing PowerPoint file: {filename}"
results.append(result)
except Exception as e:
print(f"Error processing file {file.filename}: {e}")
results.append({
'filename': file.filename,
'success': False,
'message': f"Error processing file {file.filename}: {str(e)}"
})
return results