Add autostart functionality and power management for Raspberry Pi
- Enhanced install.sh with comprehensive autostart workflow: * XDG autostart entry (desktop environment) * systemd user service (most reliable) * LXDE autostart support (Raspberry Pi OS) * Cron fallback (@reboot) * Terminal mode enabled for debugging - Added Raspberry Pi power management features: * Disable HDMI screen blanking * Prevent CPU power saving (performance mode) * Disable system sleep/suspend * X11 screensaver disabled * Display power management (DPMS) disabled - Fixed sudo compatibility: * Properly detects actual user when run with sudo * Correct file ownership for user configs * systemctl --user works correctly - Player launches in terminal for error visibility - Autostart configured to use start.sh (watchdog with auto-restart)
This commit is contained in:
+113
-19
@@ -1,12 +1,14 @@
|
||||
"""
|
||||
Updated get_playlists.py for Kiwy-Signage with DigiServer v2 authentication
|
||||
Uses secure auth flow: hostname → password/quickconnect → auth_code → API calls
|
||||
Now with HTTPS support and SSL certificate management
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import requests
|
||||
import logging
|
||||
from player_auth import PlayerAuth
|
||||
from ssl_utils import SSLManager
|
||||
|
||||
# Set up logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
@@ -16,11 +18,17 @@ logger = logging.getLogger(__name__)
|
||||
_auth_instance = None
|
||||
|
||||
|
||||
def get_auth_instance(config_file='player_auth.json'):
|
||||
"""Get or create global auth instance."""
|
||||
def get_auth_instance(config_file='player_auth.json', use_https=True, verify_ssl=True):
|
||||
"""Get or create global auth instance.
|
||||
|
||||
Args:
|
||||
config_file: Authentication config file path
|
||||
use_https: Whether to use HTTPS
|
||||
verify_ssl: Whether to verify SSL certificates
|
||||
"""
|
||||
global _auth_instance
|
||||
if _auth_instance is None:
|
||||
_auth_instance = PlayerAuth(config_file)
|
||||
_auth_instance = PlayerAuth(config_file, use_https=use_https, verify_ssl=verify_ssl)
|
||||
return _auth_instance
|
||||
|
||||
|
||||
@@ -33,7 +41,10 @@ def ensure_authenticated(config):
|
||||
Returns:
|
||||
PlayerAuth instance if authenticated, None otherwise
|
||||
"""
|
||||
auth = get_auth_instance()
|
||||
auth = get_auth_instance(
|
||||
use_https=config.get('use_https', True),
|
||||
verify_ssl=config.get('verify_ssl', True)
|
||||
)
|
||||
|
||||
# If already authenticated and valid, return auth instance
|
||||
if auth.is_authenticated():
|
||||
@@ -49,6 +60,7 @@ def ensure_authenticated(config):
|
||||
hostname = config.get("screen_name", "")
|
||||
quickconnect_key = config.get("quickconnect_key", "")
|
||||
port = config.get("port", "")
|
||||
use_https = config.get("use_https", True)
|
||||
|
||||
if not all([server_ip, hostname, quickconnect_key]):
|
||||
logger.error("❌ Missing configuration: server_ip, screen_name, or quickconnect_key")
|
||||
@@ -58,12 +70,20 @@ def ensure_authenticated(config):
|
||||
import re
|
||||
ip_pattern = r'^\d+\.\d+\.\d+\.\d+$'
|
||||
if re.match(ip_pattern, server_ip):
|
||||
server_url = f'http://{server_ip}:{port}'
|
||||
if use_https:
|
||||
# Use HTTPS for IP addresses
|
||||
server_url = f'https://{server_ip}:{port}' if port else f'https://{server_ip}'
|
||||
else:
|
||||
server_url = f'http://{server_ip}:{port}'
|
||||
else:
|
||||
server_url = f'http://{server_ip}'
|
||||
# For domain names, use HTTPS by default
|
||||
if use_https:
|
||||
server_url = f'https://{server_ip}'
|
||||
else:
|
||||
server_url = f'http://{server_ip}'
|
||||
|
||||
# Authenticate using quickconnect code
|
||||
logger.info(f"🔐 Authenticating player: {hostname}")
|
||||
logger.info(f"🔐 Authenticating player: {hostname} at {server_url}")
|
||||
success, error = auth.authenticate(
|
||||
server_url=server_url,
|
||||
hostname=hostname,
|
||||
@@ -202,12 +222,22 @@ def save_playlist(playlist_data, playlist_dir):
|
||||
return playlist_file
|
||||
|
||||
|
||||
def download_media_files(playlist, media_dir):
|
||||
"""Download media files from the server and save them to media_dir."""
|
||||
def download_media_files(playlist, media_dir, ssl_manager=None, server_url=None):
|
||||
"""Download media files from the server and save them to media_dir.
|
||||
|
||||
Args:
|
||||
playlist: List of media items
|
||||
media_dir: Directory to save media files
|
||||
ssl_manager: Optional SSLManager for HTTPS downloads
|
||||
server_url: Server base URL for constructing full file URLs
|
||||
"""
|
||||
if not os.path.exists(media_dir):
|
||||
os.makedirs(media_dir)
|
||||
logger.info(f"📁 Created directory {media_dir} for media files")
|
||||
|
||||
# Use SSL manager if provided, otherwise use requests directly
|
||||
session = ssl_manager.get_session() if ssl_manager else requests.Session()
|
||||
|
||||
updated_playlist = []
|
||||
for media in playlist:
|
||||
file_name = media.get('file_name', '')
|
||||
@@ -224,18 +254,57 @@ def download_media_files(playlist, media_dir):
|
||||
# Create parent directories if they don't exist (for nested paths like edited_media/5/)
|
||||
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
||||
|
||||
response = requests.get(file_url, timeout=30)
|
||||
# Construct full URL
|
||||
download_url = file_url
|
||||
|
||||
# Handle localhost URLs - replace with actual server IP
|
||||
if 'localhost' in file_url or 'localhost' in (server_url or ''):
|
||||
if server_url:
|
||||
# Extract the path from localhost URL
|
||||
if 'localhost' in file_url:
|
||||
# URL like: https://localhost/static/uploads/file.jpg
|
||||
# Extract path: /static/uploads/file.jpg
|
||||
parts = file_url.split('localhost')
|
||||
if len(parts) > 1:
|
||||
path = parts[1]
|
||||
download_url = f"{server_url}{path}"
|
||||
logger.info(f"🔄 Replacing localhost with {server_url}")
|
||||
else:
|
||||
download_url = file_url
|
||||
else:
|
||||
download_url = file_url
|
||||
else:
|
||||
logger.warning(f"⚠️ localhost URL provided but no server_url available: {file_url}")
|
||||
download_url = file_url
|
||||
|
||||
# Construct full URL if relative path is provided
|
||||
elif not file_url.startswith('http'):
|
||||
if server_url:
|
||||
download_url = f"{server_url}/{file_url}".replace('//', '/')
|
||||
# Fix the protocol part that might have been double-slashed
|
||||
download_url = download_url.replace('https:/', 'https://').replace('http:/', 'http://')
|
||||
else:
|
||||
logger.warning(f"⚠️ Relative URL provided but no server_url available: {file_url}")
|
||||
download_url = file_url
|
||||
|
||||
logger.info(f"📥 Downloading from: {download_url}")
|
||||
response = session.get(download_url, timeout=30, verify=False)
|
||||
if response.status_code == 200:
|
||||
with open(local_path, 'wb') as file:
|
||||
file.write(response.content)
|
||||
logger.info(f"✅ Successfully downloaded {file_name}")
|
||||
logger.info(f"✅ Successfully downloaded {file_name} ({len(response.content)} bytes)")
|
||||
else:
|
||||
logger.error(f"❌ Failed to download {file_name}. Status: {response.status_code}")
|
||||
continue
|
||||
# Still add to playlist even if download failed - might be cached or available later
|
||||
except requests.exceptions.SSLError as e:
|
||||
logger.error(f"❌ SSL Error downloading {file_name}: {e}")
|
||||
# Don't skip - may still add to playlist
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"❌ Error downloading {file_name}: {e}")
|
||||
continue
|
||||
# Don't skip - may still add to playlist
|
||||
|
||||
# Always add the media item to the playlist, even if download failed
|
||||
# (it might already exist or be available later)
|
||||
updated_media = {
|
||||
'file_name': file_name,
|
||||
'url': os.path.relpath(local_path, os.path.dirname(media_dir)),
|
||||
@@ -247,6 +316,7 @@ def download_media_files(playlist, media_dir):
|
||||
return updated_playlist
|
||||
|
||||
|
||||
|
||||
def delete_unused_media(playlist_data, media_dir):
|
||||
"""Delete media files not referenced in the current playlist."""
|
||||
try:
|
||||
@@ -303,14 +373,31 @@ def delete_unused_media(playlist_data, media_dir):
|
||||
|
||||
|
||||
def update_playlist_if_needed(config, playlist_dir, media_dir):
|
||||
"""Check for and download updated playlist if available."""
|
||||
"""Check for and download updated playlist if available.
|
||||
|
||||
Args:
|
||||
config: Configuration dict with server settings
|
||||
playlist_dir: Directory to save playlist
|
||||
media_dir: Directory to save media files
|
||||
"""
|
||||
try:
|
||||
# Initialize auth with SSL settings from config
|
||||
auth = ensure_authenticated(config)
|
||||
if not auth:
|
||||
logger.error("❌ Cannot update playlist - authentication failed")
|
||||
return None
|
||||
|
||||
# Fetch latest playlist from server
|
||||
server_data = fetch_server_playlist(config)
|
||||
server_version = server_data.get('version', 0)
|
||||
server_data = auth.get_playlist()
|
||||
|
||||
if not server_data:
|
||||
logger.warning("⚠️ No valid playlist received from server")
|
||||
return None
|
||||
|
||||
server_version = server_data.get('playlist_version', 0)
|
||||
|
||||
if server_version == 0:
|
||||
logger.warning("⚠️ No valid playlist received from server")
|
||||
logger.warning("⚠️ No valid playlist version received from server")
|
||||
return None
|
||||
|
||||
# Check local version from single playlist file
|
||||
@@ -321,7 +408,8 @@ def update_playlist_if_needed(config, playlist_dir, media_dir):
|
||||
try:
|
||||
with open(playlist_file, 'r') as f:
|
||||
local_data = json.load(f)
|
||||
local_version = local_data.get('version', 0)
|
||||
# Check for both 'version' and 'playlist_version' keys (for backward compatibility)
|
||||
local_version = local_data.get('version', local_data.get('playlist_version', 0))
|
||||
except Exception as e:
|
||||
logger.warning(f"⚠️ Could not read local playlist: {e}")
|
||||
|
||||
@@ -331,8 +419,14 @@ def update_playlist_if_needed(config, playlist_dir, media_dir):
|
||||
if server_version > local_version:
|
||||
logger.info(f"🔄 Updating playlist from v{local_version} to v{server_version}")
|
||||
|
||||
# Get SSL manager for downloads if using HTTPS
|
||||
ssl_manager = auth.ssl_manager if config.get('use_https', True) else None
|
||||
|
||||
# Get server URL from auth
|
||||
server_url = auth.auth_data.get('server_url', '')
|
||||
|
||||
# Download media files
|
||||
updated_playlist = download_media_files(server_data['playlist'], media_dir)
|
||||
updated_playlist = download_media_files(server_data.get('playlist', []), media_dir, ssl_manager, server_url)
|
||||
server_data['playlist'] = updated_playlist
|
||||
|
||||
# Save new playlist (single file, no versioning)
|
||||
|
||||
+13
-8
@@ -685,6 +685,8 @@ class SettingsPopup(Popup):
|
||||
screen_name = self.ids.screen_input.text.strip()
|
||||
quickconnect = self.ids.quickconnect_input.text.strip()
|
||||
port = self.player.config.get('port', '443')
|
||||
use_https = self.player.config.get('use_https', True)
|
||||
verify_ssl = self.player.config.get('verify_ssl', True)
|
||||
|
||||
if not all([server_ip, screen_name, quickconnect]):
|
||||
Clock.schedule_once(lambda dt: self.update_connection_status(
|
||||
@@ -699,13 +701,13 @@ class SettingsPopup(Popup):
|
||||
if port and port != '443' and port != '80':
|
||||
server_url = f"{server_ip}:{port}"
|
||||
else:
|
||||
protocol = "https" if port == "443" else "http"
|
||||
protocol = "https" if use_https else "http"
|
||||
server_url = f"{protocol}://{server_ip}:{port}"
|
||||
|
||||
Logger.info(f"SettingsPopup: Testing connection to {server_url}")
|
||||
Logger.info(f"SettingsPopup: Testing connection to {server_url} (HTTPS: {use_https}, Verify SSL: {verify_ssl})")
|
||||
|
||||
# Create temporary auth instance (don't save)
|
||||
auth = PlayerAuth('/tmp/temp_auth_test.json')
|
||||
auth = PlayerAuth('/tmp/temp_auth_test.json', use_https=use_https, verify_ssl=verify_ssl)
|
||||
|
||||
# Try to authenticate
|
||||
success, error = auth.authenticate(
|
||||
@@ -951,16 +953,18 @@ class SignagePlayer(Widget):
|
||||
self.config = json.load(f)
|
||||
Logger.info(f"SignagePlayer: Configuration loaded from {self.config_file}")
|
||||
else:
|
||||
# Create default configuration
|
||||
# Create default configuration with HTTPS support
|
||||
self.config = {
|
||||
"server_ip": "localhost",
|
||||
"port": "5000",
|
||||
"port": "443",
|
||||
"screen_name": "kivy-player",
|
||||
"quickconnect_key": "1234567",
|
||||
"max_resolution": "auto"
|
||||
"max_resolution": "auto",
|
||||
"use_https": True,
|
||||
"verify_ssl": True
|
||||
}
|
||||
self.save_config()
|
||||
Logger.info("SignagePlayer: Created default configuration")
|
||||
Logger.info("SignagePlayer: Created default configuration with HTTPS enabled")
|
||||
except Exception as e:
|
||||
Logger.error(f"SignagePlayer: Error loading config: {e}")
|
||||
self.show_error(f"Failed to load configuration: {e}")
|
||||
@@ -1053,7 +1057,8 @@ class SignagePlayer(Widget):
|
||||
data = json.load(f)
|
||||
|
||||
self.playlist = data.get('playlist', [])
|
||||
self.playlist_version = data.get('version', 0)
|
||||
# Check for both 'version' and 'playlist_version' keys (for backward compatibility)
|
||||
self.playlist_version = data.get('version', data.get('playlist_version', 0))
|
||||
|
||||
Logger.info(f"SignagePlayer: Loaded playlist v{self.playlist_version} with {len(self.playlist)} items")
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"hostname": "tv-terasa",
|
||||
"auth_code": "vkrxEO6eOTxkzXJBtoN4OuXc8eaX2mC3AB9ZePrnick",
|
||||
"hostname": "rpi-tvcanba1",
|
||||
"auth_code": "LhfERILw4cFxejhbIUuQ72QddisRgHMAm7kUSty64LA",
|
||||
"player_id": 1,
|
||||
"player_name": "TV-acasa",
|
||||
"player_name": "TVacasa",
|
||||
"playlist_id": 1,
|
||||
"orientation": "Landscape",
|
||||
"authenticated": true,
|
||||
"server_url": "http://digi-signage.moto-adv.com"
|
||||
"server_url": "https://192.168.0.121:443"
|
||||
}
|
||||
+66
-9
@@ -2,12 +2,14 @@
|
||||
Player Authentication Module for Kiwy-Signage
|
||||
Handles secure authentication with DigiServer v2
|
||||
Uses: hostname → password/quickconnect → get auth_code → use auth_code for API calls
|
||||
Now with HTTPS support and SSL certificate management
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import requests
|
||||
import logging
|
||||
from typing import Optional, Dict, Tuple
|
||||
from ssl_utils import SSLManager, setup_ssl_for_requests
|
||||
|
||||
# Set up logging
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -16,13 +18,19 @@ logger = logging.getLogger(__name__)
|
||||
class PlayerAuth:
|
||||
"""Handle player authentication with DigiServer v2."""
|
||||
|
||||
def __init__(self, config_file: str = 'player_auth.json'):
|
||||
def __init__(self, config_file: str = 'player_auth.json',
|
||||
use_https: bool = True, verify_ssl: bool = True):
|
||||
"""Initialize player authentication.
|
||||
|
||||
Args:
|
||||
config_file: Path to authentication config file
|
||||
use_https: Whether to use HTTPS for connections
|
||||
verify_ssl: Whether to verify SSL certificates
|
||||
"""
|
||||
self.config_file = config_file
|
||||
self.use_https = use_https
|
||||
self.verify_ssl = verify_ssl
|
||||
self.ssl_manager = SSLManager(verify_ssl=verify_ssl)
|
||||
self.auth_data = self._load_auth_data()
|
||||
|
||||
def _load_auth_data(self) -> Dict:
|
||||
@@ -65,7 +73,7 @@ class PlayerAuth:
|
||||
"""Authenticate with DigiServer v2.
|
||||
|
||||
Args:
|
||||
server_url: Server URL (e.g., 'http://server:5000')
|
||||
server_url: Server URL (e.g., 'http://server:5000' or 'https://server')
|
||||
hostname: Player hostname/identifier
|
||||
password: Player password (optional if using quickconnect)
|
||||
quickconnect_code: Quick connect code (optional if using password)
|
||||
@@ -77,6 +85,20 @@ class PlayerAuth:
|
||||
if not password and not quickconnect_code:
|
||||
return False, "Password or quick connect code required"
|
||||
|
||||
# Normalize server URL to HTTPS if needed
|
||||
if self.use_https:
|
||||
server_url = self.ssl_manager.validate_url_scheme(server_url)
|
||||
|
||||
# Try to download certificate if not present
|
||||
if not self.ssl_manager.has_certificate():
|
||||
logger.info("Downloading server certificate for HTTPS verification...")
|
||||
success, error = self.ssl_manager.download_server_certificate(server_url, timeout=timeout)
|
||||
if not success:
|
||||
logger.warning(f"⚠️ Certificate download failed: {error}")
|
||||
if self.verify_ssl:
|
||||
return False, error
|
||||
# Continue with unverified connection for testing
|
||||
|
||||
# Prepare authentication request
|
||||
auth_url = f"{server_url}/api/auth/player"
|
||||
payload = {
|
||||
@@ -87,7 +109,10 @@ class PlayerAuth:
|
||||
|
||||
try:
|
||||
logger.info(f"Authenticating with server: {auth_url}")
|
||||
response = requests.post(auth_url, json=payload, timeout=timeout)
|
||||
|
||||
# Use SSL-configured session
|
||||
session = self.ssl_manager.get_session()
|
||||
response = session.post(auth_url, json=payload, timeout=timeout)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
@@ -119,8 +144,16 @@ class PlayerAuth:
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = "Cannot connect to server"
|
||||
except requests.exceptions.SSLError as e:
|
||||
error_msg = f"SSL Certificate Error: {e}"
|
||||
logger.error(error_msg)
|
||||
if self.verify_ssl:
|
||||
logger.error(" This usually means the server certificate is not trusted.")
|
||||
logger.error(" Try downloading the server certificate or disabling SSL verification.")
|
||||
return False, error_msg
|
||||
|
||||
except requests.exceptions.ConnectionError as e:
|
||||
error_msg = f"Connection Error: {e}"
|
||||
logger.error(error_msg)
|
||||
return False, error_msg
|
||||
|
||||
@@ -154,7 +187,9 @@ class PlayerAuth:
|
||||
payload = {'auth_code': self.auth_data.get('auth_code')}
|
||||
|
||||
try:
|
||||
response = requests.post(verify_url, json=payload, timeout=timeout)
|
||||
# Use SSL-configured session
|
||||
session = self.ssl_manager.get_session()
|
||||
response = session.post(verify_url, json=payload, timeout=timeout)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
@@ -165,6 +200,10 @@ class PlayerAuth:
|
||||
logger.warning("❌ Auth code invalid or expired")
|
||||
return False, None
|
||||
|
||||
except requests.exceptions.SSLError as e:
|
||||
logger.error(f"SSL Error during verification: {e}")
|
||||
return False, None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to verify auth: {e}")
|
||||
return False, None
|
||||
@@ -195,7 +234,9 @@ class PlayerAuth:
|
||||
|
||||
try:
|
||||
logger.info(f"Fetching playlist from: {playlist_url}")
|
||||
response = requests.get(playlist_url, headers=headers, timeout=timeout)
|
||||
# Use SSL-configured session
|
||||
session = self.ssl_manager.get_session()
|
||||
response = session.get(playlist_url, headers=headers, timeout=timeout)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
@@ -211,6 +252,10 @@ class PlayerAuth:
|
||||
logger.error(f"Failed to get playlist: {response.status_code}")
|
||||
return None
|
||||
|
||||
except requests.exceptions.SSLError as e:
|
||||
logger.error(f"SSL Error fetching playlist: {e}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching playlist: {e}")
|
||||
return None
|
||||
@@ -240,10 +285,16 @@ class PlayerAuth:
|
||||
payload = {'status': status}
|
||||
|
||||
try:
|
||||
response = requests.post(heartbeat_url, headers=headers,
|
||||
# Use SSL-configured session
|
||||
session = self.ssl_manager.get_session()
|
||||
response = session.post(heartbeat_url, headers=headers,
|
||||
json=payload, timeout=timeout)
|
||||
return response.status_code == 200
|
||||
|
||||
except requests.exceptions.SSLError as e:
|
||||
logger.debug(f"SSL Error in heartbeat: {e}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"Heartbeat failed: {e}")
|
||||
return False
|
||||
@@ -284,10 +335,16 @@ class PlayerAuth:
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(feedback_url, headers=headers,
|
||||
# Use SSL-configured session
|
||||
session = self.ssl_manager.get_session()
|
||||
response = session.post(feedback_url, headers=headers,
|
||||
json=payload, timeout=timeout)
|
||||
return response.status_code == 200
|
||||
|
||||
except requests.exceptions.SSLError as e:
|
||||
logger.debug(f"SSL Error sending feedback: {e}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"Feedback failed: {e}")
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user