Files
ds-play/app/static/functions.py
2025-05-11 16:25:56 +03:00

161 lines
6.8 KiB
Python
Executable File

import os
import json
import requests
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
Logger = logging.getLogger(__name__)
def load_playlist():
"""Load playlist from the server or local storage."""
try:
Logger.info("python_functions: Attempting to load playlist from server...")
# Load app configuration
app_config_path = os.path.join(os.path.dirname(__file__), '../../app_config.json')
if not os.path.exists(app_config_path):
Logger.error("python_functions: App configuration file not found.")
return []
with open(app_config_path, 'r') as config_file:
app_config = json.load(config_file)
server = app_config.get('server_address', '')
port = app_config.get('port', 1025)
host = app_config.get('player_name', '')
quick = app_config.get('quickconnect_code', '')
if not server or not host or not quick:
Logger.error("python_functions: Missing required configuration values.")
return []
# Construct the server IP and request URL
server_ip = f'{server}:{port}'
url = f'http://{server_ip}/api/playlists'
params = {
'hostname': host,
'quickconnect_code': quick
}
# Send the request
response = requests.get(url, params=params)
# Debugging logs
Logger.debug(f"python_functions: Status Code: {response.status_code}")
Logger.debug(f"python_functions: Response Content: {response.text}")
if response.status_code == 200:
try:
playlist = response.json().get('playlist', [])
Logger.info("python_functions: Playlist loaded successfully.")
Logger.debug(f"python_functions: Loaded playlist: {playlist}")
return playlist
except json.JSONDecodeError as e:
Logger.error(f"python_functions: Failed to parse JSON response: {e}")
else:
Logger.error(f"python_functions: Failed to retrieve playlist: {response.text}")
except requests.exceptions.RequestException as e:
Logger.error(f"python_functions: Failed to load playlist: {e}")
return []
def download_media_files(playlist):
"""Download media files from the playlist."""
Logger.info("python_functions: Starting media file download...")
base_dir = os.path.join(os.path.dirname(__file__), 'static', 'resurse') # Update this to the correct path
if not os.path.exists(base_dir):
os.makedirs(base_dir)
Logger.info(f"python_functions: Created directory {base_dir} for media files.")
for media in playlist:
file_name = media.get('file_name', '')
file_url = media.get('url', '')
file_path = os.path.join(base_dir, file_name)
try:
response = requests.get(file_url)
if response.status_code == 200:
with open(file_path, 'wb') as file:
file.write(response.content)
Logger.info(f"python_functions: Downloaded {file_name} to {file_path}")
else:
Logger.error(f"python_functions: Failed to download {file_name}: {response.status_code}")
except requests.exceptions.RequestException as e:
Logger.error(f"python_functions: Failed to download {file_name}: {e}")
def download_playlist_files_from_server():
"""Download playlist files using app configuration."""
Logger.info("python_functions: Starting playlist file download using app configuration...")
# Load app configuration
app_config_path = os.path.join(os.path.dirname(__file__), '../../app_config.json')
if not os.path.exists(app_config_path):
Logger.error("python_functions: App configuration file not found.")
return
try:
with open(app_config_path, 'r') as config_file:
app_config = json.load(config_file)
except json.JSONDecodeError as e:
Logger.error(f"python_functions: Failed to load app configuration: {e}")
return
# Extract configuration values
server_address = app_config.get('server_address', '')
port = app_config.get('port', 1025)
hostname = app_config.get('player_name', '')
quickconnect_code = app_config.get('quickconnect_code', '')
if not server_address or not hostname or not quickconnect_code:
Logger.error("python_functions: Missing required configuration values.")
return
# Construct the request URL and parameters
server_ip = f'{server_address}:{port}'
url = f'http://{server_ip}/api/playlists'
params = {
'hostname': hostname,
'quickconnect_code': quickconnect_code
}
try:
# Send request to fetch the playlist
response = requests.get(url, params=params)
Logger.debug(f"python_functions: Status Code: {response.status_code}")
Logger.debug(f"python_functions: Response Content: {response.text}")
if response.status_code == 200:
try:
playlist = response.json().get('playlist', [])
Logger.info("python_functions: Playlist retrieved successfully.")
Logger.debug(f"python_functions: Playlist: {playlist}")
# Download media files from the playlist
base_dir = os.path.join(os.path.dirname(__file__), 'static', 'resurse')
if not os.path.exists(base_dir):
os.makedirs(base_dir)
Logger.info(f"python_functions: Created directory {base_dir} for media files.")
for media in playlist:
file_name = media.get('file_name', '')
file_url = media.get('url', '')
file_path = os.path.join(base_dir, file_name)
try:
file_response = requests.get(file_url)
if file_response.status_code == 200:
with open(file_path, 'wb') as file:
file.write(file_response.content)
Logger.info(f"python_functions: Downloaded {file_name} to {file_path}")
else:
Logger.error(f"python_functions: Failed to download {file_name}: {file_response.status_code}")
except requests.exceptions.RequestException as e:
Logger.error(f"python_functions: Failed to download {file_name}: {e}")
except json.JSONDecodeError as e:
Logger.error(f"python_functions: Failed to parse playlist JSON: {e}")
else:
Logger.error(f"python_functions: Failed to retrieve playlist: {response.text}")
except requests.exceptions.RequestException as e:
Logger.error(f"python_functions: Failed to connect to server: {e}")
download_playlist_files_from_server()