#!/usr/bin/env python3 """ Simplified diagnostic script using Flask's built-in test client. This script tests the player edit media API endpoint. """ import sys import json from datetime import datetime from pathlib import Path # Add the app directory to the path sys.path.insert(0, '/app') from app import create_app from app.extensions import db from app.models import Player, Content def test_edit_media_endpoint(): """Test the edit media endpoint using Flask test client""" print("\n" + "="*60) print("DIGISERVER EDIT MEDIA API - DIAGNOSTIC TEST") print("="*60 + "\n") # Create app context app = create_app() with app.app_context(): # Get a test client client = app.test_client() # Test 1: Check server health print("[1/6] Testing server health...") response = client.get('/api/health') if response.status_code == 200: print(f" ✓ Server is healthy (Status: {response.status_code})") data = response.json print(f" Version: {data.get('version')}") else: print(f" ✗ Server health check failed (Status: {response.status_code})") return # Test 2: Check endpoint without auth print("\n[2/6] Testing endpoint availability (without auth)...") response = client.post('/api/player-edit-media') if response.status_code == 401: print(f" ✓ Endpoint exists and requires auth (Status: 401)") print(f" Response: {response.json}") elif response.status_code == 404: print(f" ✗ ENDPOINT NOT FOUND! (Status: 404)") print(f" The /api/player-edit-media route is not registered!") return else: print(f" ⚠ Unexpected status: {response.status_code}") print(f" Response: {response.json}") # Test 3: Get player and auth code print("\n[3/6] Retrieving player credentials...") player = Player.query.first() if not player: print(" ✗ No players found in database!") return print(f" ✓ Found player: {player.name}") print(f" Player ID: {player.id}") print(f" Auth Code: {player.auth_code[:10]}...{player.auth_code[-5:]}") print(f" Has assigned playlist: {player.playlist_id is not None}") # Test 4: Test authentication print("\n[4/6] Testing authentication...") headers = { 'Authorization': f'Bearer {player.auth_code}' } response = client.post('/api/player-edit-media', headers=headers) if response.status_code == 401: print(f" ✗ Authentication FAILED!") print(f" Response: {response.json}") return elif response.status_code == 400: print(f" ✓ Authentication successful!") print(f" Got 400 (missing data) which means auth passed") else: print(f" ⚠ Unexpected response: {response.status_code}") # Test 5: Get sample content print("\n[5/6] Finding sample content...") content = Content.query.first() if not content: print(" ✗ No content found in database!") return print(f" ✓ Found content: {content.filename}") print(f" Content ID: {content.id}") print(f" Type: {content.content_type}") print(f" Duration: {content.duration}s") # Check if file exists on disk file_path = Path(f'/app/app/static/uploads/{content.filename}') file_exists = file_path.exists() print(f" File exists on disk: {file_exists}") # Test 6: Simulate upload print("\n[6/6] Simulating media upload...") metadata = { "time_of_modification": datetime.utcnow().isoformat() + "Z", "original_name": content.filename, "new_name": f"{content.filename.split('.')[0]}_v1.{content.filename.split('.')[-1]}", "version": 1, "user_card_data": "test_user_123" } print(f" Metadata prepared:") print(f" Original: {metadata['original_name']}") print(f" New name: {metadata['new_name']}") print(f" Version: {metadata['version']}") # Create a dummy file dummy_file_data = b"fake image data for testing" # Send request with multipart data data = { 'metadata': json.dumps(metadata) } # Use Flask test client's multipart support response = client.post( '/api/player-edit-media', headers=headers, data=data, content_type='multipart/form-data' ) print(f"\n Response Status: {response.status_code}") if response.status_code == 200: print(f" ✓ UPLOAD SUCCESSFUL!") resp_data = response.json print(f" Response: {json.dumps(resp_data, indent=6)}") elif response.status_code == 400: resp = response.json error_msg = resp.get('error', 'Unknown error') print(f" ⚠ Bad Request (400): {error_msg}") print(f" Full response: {resp}") elif response.status_code == 404: resp = response.json error_msg = resp.get('error', 'Unknown error') print(f" ✗ Not Found (404): {error_msg}") print(f" Make sure content filename matches exactly") else: print(f" ✗ Upload failed with status {response.status_code}") print(f" Response: {response.data.decode('utf-8')}") # Summary print("\n" + "="*60) print("DIAGNOSTICS SUMMARY") print("="*60) print(f""" Endpoint Status: - Route exists: YES - Authentication: Working - Test content available: YES - Database accessible: YES Recommendations: 1. The endpoint IS working and accessible 2. Check player application logs for upload errors 3. Verify player is sending correct request format 4. Make sure player has valid authorization code 5. Check network connectivity between player and server """) if __name__ == "__main__": try: test_edit_media_endpoint() except Exception as e: print(f"\n✗ ERROR: {str(e)}") import traceback traceback.print_exc()