Files
Kiwy-Signage/dev/tests/test_edited_media_upload.py
T
SKE087 31807f37bf Cleanup repo + harden offline install and watchdog
Repo hygiene:
- Remove dead scripts (.wait-for-display, .display-keepalive, .keep-screen-alive)
- Remove stale backup/scratch (install.sh.bak, New.txt, stale .pyc)
- Stop tracking machine-specific/generated state (config/app_config.json,
  playlists/server_playlist.json, src/player_auth.json, generated launchers)
- Prune duplicate wheel versions (one per package)
- Reorganize working_files -> dev/, dev/tests/, documentation/dev-notes/, scripts/
- Extend .gitignore; fix no-op rules in repo/.gitignore

Offline install (install.sh):
- Non-fatal system-dep step; per-package apt retry; .deb bundle install
- Skip pip self-upgrade offline; guard online fallbacks behind connectivity probe
- Dependency-free fetch_url (curl/wget/urllib); --no-reboot flag
- Fix corrupted literal backslash-bang escapes (shebangs, test -f, banner)
- Idempotent cron install (no more stacked @reboot lines)

Autostart / watchdog:
- start.sh: single-instance flock lock (.player_watchdog.lock) acquired only
  after a display is confirmed, preventing parallel watchdogs
- Set XDG_RUNTIME_DIR when missing; exit early if headless
- run_player.sh: activate .venv; stop_player.sh: clear lock file
2026-10-14 23:29:14 +03:00

166 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""
Test script to diagnose edited media upload issues
Run this to test if the server endpoint exists and works correctly
"""
import json
import os
import sys
import requests
from pathlib import Path
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
def test_upload():
"""Test the edited media upload functionality"""
print("\n" + "="*60)
print("EDITED MEDIA UPLOAD DIAGNOSTICS")
print("="*60)
# Get authentication
try:
from get_playlists_v2 import get_auth_instance
auth = get_auth_instance()
if not auth or not auth.is_authenticated():
print("❌ ERROR: Not authenticated!")
print(" Please ensure player_auth.json exists and is valid")
return False
server_url = auth.auth_data.get('server_url')
auth_code = auth.auth_data.get('auth_code')
print(f"\n✓ Authentication successful")
print(f" Server URL: {server_url}")
print(f" Auth Code: {auth_code[:20]}..." if auth_code else " Auth Code: None")
except Exception as e:
print(f"❌ Authentication error: {e}")
return False
# Check for edited media files
edited_media_dir = os.path.join(os.path.dirname(__file__), 'media', 'edited_media')
edited_files = list(Path(edited_media_dir).glob('*_e_v*.jpg'))
metadata_files = list(Path(edited_media_dir).glob('*_metadata.json'))
print(f"\n✓ Edited Media Directory: {edited_media_dir}")
print(f" Edited images: {len(edited_files)}")
print(f" Metadata files: {len(metadata_files)}")
if not edited_files:
print("\n⚠️ No edited images found!")
print(" Create an edit first, then run this test")
return False
# Test with the first edited image
image_path = str(edited_files[0])
metadata_file = str(edited_files[0]).replace('.jpg', '_metadata.json')
if not os.path.exists(metadata_file):
print(f"\n❌ Metadata file not found: {metadata_file}")
return False
print(f"\nTesting upload with:")
print(f" Image: {os.path.basename(image_path)}")
print(f" Size: {os.path.getsize(image_path):,} bytes")
print(f" Metadata: {os.path.basename(metadata_file)}")
# Load and display metadata
with open(metadata_file, 'r') as f:
metadata = json.load(f)
print(f"\nMetadata content:")
for key, value in metadata.items():
print(f" {key}: {value}")
# Add original_filename if not present
metadata['original_filename'] = os.path.basename(metadata['original_path'])
# Prepare upload request
upload_url = f"{server_url}/api/player-edit-media"
headers = {'Authorization': f'Bearer {auth_code}'}
print(f"\n{'='*60}")
print("TESTING UPLOAD...")
print(f"{'='*60}")
print(f"Endpoint: {upload_url}")
print(f"Headers: Authorization: Bearer {auth_code[:20]}...")
try:
with open(image_path, 'rb') as img_file:
files = {
'image_file': (metadata['original_filename'], img_file, 'image/jpeg')
}
data = {
'metadata': json.dumps(metadata),
'original_file': metadata['original_filename']
}
print(f"\nSending request (30s timeout, SSL verify=False)...")
response = requests.post(
upload_url,
headers=headers,
files=files,
data=data,
timeout=30,
verify=False
)
print(f"\n✓ Response received!")
print(f" Status Code: {response.status_code}")
print(f" Headers: {dict(response.headers)}")
if response.status_code == 200:
print(f"\n✅ SUCCESS! Server accepted the upload")
print(f" Response: {response.json()}")
return True
elif response.status_code == 404:
print(f"\n❌ ENDPOINT NOT FOUND (404)")
print(f" The server does NOT have /api/player-edit-media endpoint")
print(f" Server may need to implement this feature")
elif response.status_code == 401:
print(f"\n❌ AUTHENTICATION FAILED (401)")
print(f" Check your auth_code in player_auth.json")
else:
print(f"\n❌ REQUEST FAILED (Status: {response.status_code})")
print(f" Response: {response.text}")
return False
except requests.exceptions.ConnectionError as e:
print(f"\n❌ CONNECTION ERROR")
print(f" Cannot reach server at {server_url}")
print(f" Error: {e}")
return False
except requests.exceptions.Timeout as e:
print(f"\n❌ TIMEOUT")
print(f" Server did not respond within 30 seconds")
print(f" Error: {e}")
return False
except requests.exceptions.SSLError as e:
print(f"\n❌ SSL ERROR")
print(f" Error: {e}")
print(f" Tip: Try adding verify=False to requests")
return False
except Exception as e:
print(f"\n❌ UNEXPECTED ERROR")
print(f" Error: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == '__main__':
success = test_upload()
print(f"\n{'='*60}")
if success:
print("✅ UPLOAD TEST PASSED - Server accepts edited media!")
else:
print("❌ UPLOAD TEST FAILED - See details above")
print(f"{'='*60}\n")
sys.exit(0 if success else 1)