2af04e1db3
- Content model: add url column + is_weblink() for web page content items - Player model: add deployment tracking fields (status, timestamps, message) - Content blueprint: add add_weblink and add_weblink_to_playlist routes; weblinks auto-deleted when removed from playlist - Players blueprint: add SSH deploy mode in add_player; weblink-aware playlist - API blueprint: weblink URL served directly in playlist response; add /api/deploy/test-ssh and /api/deploy/player endpoints - Admin blueprint: add build-player page (clone from Gitea, write base config); replace nginx status card with Caddy status on HTTPS config page - caddy_manager: rewritten to generate proper HTTPS/internal-CA Caddyfiles and reload Caddy via admin API (/load) for live config updates - ssh_deploy, background_tasks, player_build: new utils for SSH deployment - background_tasks: push Flask app context into background thread so DB updates after deployment complete correctly - ssh_deploy: robust install script detection with passwordless sudo injection (uses SSH credentials, cleaned up after install) - Dockerfile: add git, sshpass, openssh-client, rsync - docker-compose: switch nginx to Caddy on ports 80/443; add port 5000 for dev - Templates: add_player deploy mode UI, weblink form in playlist/upload pages, build_player admin page, Caddy status on HTTPS config page - Migrations: add_url_to_content, add_deployment_fields_to_player - app.py: call db.create_all() on startup for schema bootstrap - config.py: add PLAYER_CODE_DIR and PLAYER_REPO_URL settings
102 lines
3.8 KiB
Python
102 lines
3.8 KiB
Python
"""Background task execution for long-running operations."""
|
|
import threading
|
|
import logging
|
|
from typing import Callable, Any, Dict
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def run_background_task(task_func: Callable, *args, **kwargs) -> threading.Thread:
|
|
"""Run a function in a background thread, with a Flask app context pushed."""
|
|
from flask import current_app
|
|
# Capture the app instance now (in the request context) so the thread can use it
|
|
app = current_app._get_current_object()
|
|
|
|
def wrapper():
|
|
with app.app_context():
|
|
try:
|
|
logger.info(f"Starting background task: {task_func.__name__}")
|
|
task_func(*args, **kwargs)
|
|
logger.info(f"Completed background task: {task_func.__name__}")
|
|
except Exception as e:
|
|
logger.error(f"Background task failed ({task_func.__name__}): {str(e)}", exc_info=True)
|
|
|
|
thread = threading.Thread(target=wrapper, daemon=True)
|
|
thread.start()
|
|
return thread
|
|
|
|
|
|
def background_player_deployment(
|
|
hostname: str,
|
|
username: str,
|
|
password: str,
|
|
player_name: str,
|
|
player_id: int,
|
|
port: int = 22,
|
|
server_url: str = None,
|
|
server_api_key: str = None,
|
|
player_hostname: str = None,
|
|
quickconnect_code: str = None,
|
|
orientation: str = 'Landscape',
|
|
verify_ssl: bool = False
|
|
) -> None:
|
|
"""
|
|
Deploy player code to host in background.
|
|
|
|
Args:
|
|
hostname: SSH hostname/IP
|
|
username: SSH username
|
|
password: SSH password
|
|
player_name: Player name
|
|
player_id: Player database ID
|
|
port: SSH port
|
|
server_url: DigiServer URL for player
|
|
server_api_key: API key for player
|
|
player_hostname: Player screen identity used for auth (Player.hostname)
|
|
quickconnect_code: Quick connect code used for auth
|
|
orientation: Player orientation (Landscape/Portrait)
|
|
verify_ssl: Whether the player should verify the server TLS certificate
|
|
"""
|
|
from app.utils.ssh_deploy import deploy_player_to_host
|
|
from app.models import Player
|
|
from app.extensions import db
|
|
from app.utils.logger import log_action
|
|
|
|
try:
|
|
# Execute deployment
|
|
result = deploy_player_to_host(
|
|
hostname=hostname,
|
|
username=username,
|
|
password=password,
|
|
player_name=player_name,
|
|
port=port,
|
|
server_url=server_url,
|
|
server_api_key=server_api_key,
|
|
player_hostname=player_hostname,
|
|
quickconnect_code=quickconnect_code,
|
|
orientation=orientation,
|
|
verify_ssl=verify_ssl
|
|
)
|
|
|
|
# Update player with deployment status
|
|
from datetime import datetime
|
|
player = Player.query.get(player_id)
|
|
if player:
|
|
player.last_deployment_at = datetime.utcnow()
|
|
if result.get('success'):
|
|
player.deployment_status = 'deployed'
|
|
player.last_deployment_status = 'success'
|
|
player.last_deployment_message = result.get('message', 'Deployment successful')
|
|
log_action('info', f'Background deployment completed for player "{player_name}": {result["message"]}')
|
|
else:
|
|
player.deployment_status = 'failed'
|
|
player.last_deployment_status = 'failed'
|
|
player.last_deployment_message = result.get('error', result.get('message', 'Deployment failed'))
|
|
log_action('error', f'Background deployment failed for player "{player_name}": {result.get("error", result.get("message"))}')
|
|
|
|
db.session.commit()
|
|
|
|
except Exception as e:
|
|
logger.error(f"Background deployment error for player '{player_name}': {str(e)}", exc_info=True)
|
|
log_action('error', f'Background deployment error for player "{player_name}": {str(e)}')
|