![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/soundstudiopro.com/private_html/ |
<?php
// Enhanced API.Box Track Synchronization - Pulls ALL Available Data
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config/database.php';
$api_key = '63edba40620216c5aa2c04240ac41dbd';
// Handle sync requests
if (isset($_POST['action']) && $_POST['action'] === 'sync_track' && !empty($_POST['sync_track_id']) && !empty($_POST['sync_task_id'])) {
$track_id = (int)$_POST['sync_track_id'];
$task_id = $_POST['sync_task_id'];
echo "<h1>🔄 Syncing Track $track_id</h1>";
echo "<p><strong>Task ID: $task_id</strong></p>";
// Perform the sync
$result = syncTrackWithFullData($track_id, $task_id, $api_key);
if ($result['success']) {
echo "<div style='background: #d4edda; border: 1px solid #c3e6cb; color: #155724; padding: 15px; border-radius: 8px; margin: 20px 0;'>";
echo "<h3>✅ Sync Completed Successfully!</h3>";
echo "<p>Track $track_id has been updated with all available data from API.Box.</p>";
echo "<p><a href='track.php?id=$track_id' style='color: #155724; text-decoration: underline;'>View Updated Track</a></p>";
echo "<p><a href='enhanced_api_box_sync.php' style='color: #155724; text-decoration: underline;'>← Back to Track List</a></p>";
echo "</div>";
} else {
echo "<div style='background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 15px; border-radius: 8px; margin: 20px 0;'>";
echo "<h3>❌ Sync Failed</h3>";
echo "<p>Error: " . htmlspecialchars($result['error']) . "</p>";
echo "<p><a href='enhanced_api_box_sync.php' style='color: #155724; text-decoration: underline;'>← Back to Track List</a></p>";
echo "</div>";
}
echo "<hr>";
}
echo "<h1>🚀 Enhanced API.Box Track Synchronization</h1>";
echo "<p><strong>This script pulls ALL available data from API.Box including lyrics, metadata, variations, waveform data, and more!</strong></p>";
$pdo = getDBConnection();
if (!$pdo) {
echo "<p style='color: red;'>❌ Database connection failed</p>";
exit;
}
// Enhanced function to get FULL track data from API.Box
function getFullTrackData($task_id, $api_key) {
$api_url = "https://api.api.box/api/v1/status/$task_id";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $api_key,
'Content-Type: application/json',
'User-Agent: SoundStudioPro-Enhanced-Sync/2.0'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // Increased timeout for full data
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_error) {
return ['error' => 'cURL Error: ' . $curl_error];
}
if ($http_code !== 200) {
return ['error' => 'HTTP Error: ' . $http_code, 'response' => $response];
}
$data = json_decode($response, true);
// Extract ALL available data from API.Box response
return [
'task_id' => $task_id,
'status' => $data['status'] ?? 'unknown',
'audio_url' => $data['audio_url'] ?? $data['audioUrl'] ?? null,
'lyrics' => $data['lyrics'] ?? $data['lyrics_text'] ?? $data['data']['lyrics'] ?? $data['data']['data'][0]['lyrics'] ?? null,
'metadata' => $data['metadata'] ?? null,
'variations' => $data['variations'] ?? $data['variation_urls'] ?? [],
'prompt' => $data['prompt'] ?? $data['description'] ?? null,
'duration' => $data['duration'] ?? $data['length'] ?? null,
'genre' => $data['genre'] ?? $data['style'] ?? null,
'bpm' => $data['bpm'] ?? $data['tempo'] ?? null,
'key' => $data['key'] ?? $data['musical_key'] ?? null,
'time_signature' => $data['time_signature'] ?? $data['timeSignature'] ?? null,
'instruments' => $data['instruments'] ?? $data['instrumentation'] ?? null,
'mood' => $data['mood'] ?? $data['emotion'] ?? null,
'energy' => $data['energy'] ?? $data['intensity'] ?? null,
'created_at' => $data['createdAt'] ?? $data['created_at'] ?? null,
'completed_at' => $data['completedAt'] ?? $data['completed_at'] ?? null,
'error_message' => $data['error'] ?? $data['error_message'] ?? null,
'processing_time' => $data['processingTime'] ?? $data['processing_time'] ?? null,
'file_size' => $data['fileSize'] ?? $data['file_size'] ?? null,
'quality_score' => $data['qualityScore'] ?? $data['quality_score'] ?? null,
'tags' => $data['tags'] ?? $data['keywords'] ?? [],
'waveform_data' => $data['waveform'] ?? $data['waveform_data'] ?? null,
'spectrum_analysis' => $data['spectrum'] ?? $data['spectrum_analysis'] ?? null,
'audio_segments' => $data['segments'] ?? $data['audio_segments'] ?? null,
'cost_info' => $data['cost'] ?? $data['cost_info'] ?? null,
'generation_parameters' => $data['parameters'] ?? $data['generation_parameters'] ?? null,
'model_version' => $data['model'] ?? $data['model_version'] ?? null,
'sample_rate' => $data['sampleRate'] ?? $data['sample_rate'] ?? null,
'bit_depth' => $data['bitDepth'] ?? $data['bit_depth'] ?? null,
'channels' => $data['channels'] ?? $data['audio_channels'] ?? null,
'raw_response' => $data // Keep the full response for debugging
];
}
// Enhanced function to sync track with ALL data
function syncTrackWithFullData($track_id, $task_id, $api_key) {
global $pdo;
echo "<p>🔄 Syncing track ID $track_id with task ID $task_id...</p>";
// Get full data from API.Box
$full_data = getFullTrackData($task_id, $api_key);
if (isset($full_data['error'])) {
echo "<p style='color: red;'>❌ Error getting data: {$full_data['error']}</p>";
return ['success' => false, 'error' => $full_data['error']];
}
echo "<p>✅ Retrieved data from API.Box:</p>";
echo "<ul>";
echo "<li>Status: {$full_data['status']}</li>";
echo "<li>Audio URL: " . ($full_data['audio_url'] ? '✅' : '❌') . "</li>";
echo "<li>Lyrics: " . ($full_data['lyrics'] ? '✅' : '❌') . "</li>";
echo "<li>Duration: " . ($full_data['duration'] ? $full_data['duration'] . 's' : '❌') . "</li>";
echo "<li>Genre: " . ($full_data['genre'] ?: '❌') . "</li>";
echo "<li>BPM: " . ($full_data['bpm'] ?: '❌') . "</li>";
echo "<li>Key: " . ($full_data['key'] ?: '❌') . "</li>";
echo "<li>Variations: " . count($full_data['variations']) . "</li>";
echo "</ul>";
// Prepare comprehensive metadata
$metadata = [
'genre' => $full_data['genre'],
'style' => $full_data['genre'], // Alternative field
'bpm' => $full_data['bpm'],
'key' => $full_data['key'],
'time_signature' => $full_data['time_signature'],
'instruments' => $full_data['instruments'],
'mood' => $full_data['mood'],
'energy' => $full_data['energy'],
'tags' => $full_data['tags'],
'waveform_data' => $full_data['waveform_data'],
'spectrum_analysis' => $full_data['spectrum_analysis'],
'audio_segments' => $full_data['audio_segments'],
'cost_info' => $full_data['cost_info'],
'generation_parameters' => $full_data['generation_parameters'],
'processing_time' => $full_data['processing_time'],
'quality_score' => $full_data['quality_score'],
'model_version' => $full_data['model_version'],
'sample_rate' => $full_data['sample_rate'],
'bit_depth' => $full_data['bit_depth'],
'channels' => $full_data['channels'],
'api_box_raw_data' => $full_data['raw_response'] // Store the full API response
];
// Remove null values
$metadata = array_filter($metadata, function($value) {
return $value !== null && $value !== '';
});
// Update database with ALL the data
$stmt = $pdo->prepare("
UPDATE music_tracks SET
audio_url = ?,
lyrics = ?,
metadata = ?,
duration = ?,
status = ?,
model_version = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
");
$result = $stmt->execute([
$full_data['audio_url'],
$full_data['lyrics'],
json_encode($metadata),
$full_data['duration'],
$full_data['status'] === 'success' ? 'complete' : 'failed',
$full_data['model_version'] ?? 'v3',
$track_id
]);
if ($result) {
echo "<p style='color: green;'>✅ Track synced successfully with full data!</p>";
// If there are variations, create separate tracks for them
if (!empty($full_data['variations'])) {
echo "<p>🔄 Processing variations...</p>";
foreach ($full_data['variations'] as $index => $variation_url) {
if ($variation_url && $variation_url !== $full_data['audio_url']) {
// Check if variation track already exists
$stmt = $pdo->prepare("SELECT id FROM music_tracks WHERE audio_url = ?");
$stmt->execute([$variation_url]);
$existing = $stmt->fetch();
if (!$existing) {
// Create variation track
$stmt = $pdo->prepare("
INSERT INTO music_tracks (
user_id, task_id, title, prompt, audio_url,
status, duration, metadata, created_at
) VALUES (
(SELECT user_id FROM music_tracks WHERE id = ?),
?,
?,
?,
?,
'complete',
?,
?,
CURRENT_TIMESTAMP
)
");
$variation_title = "Variation " . ($index + 1);
$variation_metadata = array_merge($metadata, ['variation_index' => $index]);
$stmt->execute([
$track_id,
$task_id . '_variation_' . $index,
$variation_title,
$full_data['prompt'],
$variation_url,
$full_data['duration'],
json_encode($variation_metadata)
]);
echo "<p style='color: blue;'>📝 Created variation track: $variation_title</p>";
}
}
}
}
return ['success' => true, 'data' => $full_data];
} else {
echo "<p style='color: red;'>❌ Failed to sync track</p>";
return ['success' => false, 'error' => 'Database update failed'];
}
}
// Skip API.Box logs - focus on direct track syncing
echo "<h2>🚀 Direct Track Synchronization</h2>";
echo "<p>Syncing tracks directly from API.Box using their task IDs...</p>";
// Get all local tracks
$stmt = $pdo->prepare("
SELECT mt.*, u.name as user_name, u.email as user_email
FROM music_tracks mt
JOIN users u ON mt.user_id = u.id
ORDER BY mt.created_at DESC
");
$stmt->execute();
$local_tracks = $stmt->fetchAll();
echo "<h2>🔍 Enhanced Track Analysis</h2>";
// Find tracks that need syncing - focus on tracks with task_ids
$tracks_to_sync = [];
foreach ($local_tracks as $track) {
if (!empty($track['task_id'])) {
// Always try to sync tracks with task_ids to get lyrics and other data
$tracks_to_sync[] = [
'track_id' => $track['id'],
'task_id' => $track['task_id'],
'title' => $track['title'],
'user_name' => $track['user_name'],
'current_status' => $track['status'],
'api_status' => 'unknown' // We'll check this when we sync
];
}
}
echo "<h3>📋 Tracks Ready for Enhanced Sync</h3>";
if (empty($tracks_to_sync)) {
echo "<p>✅ All tracks are already synced!</p>";
} else {
echo "<table border='1' style='border-collapse: collapse; margin: 20px 0; width: 100%;'>";
echo "<tr style='background: #f0f0f0;'>";
echo "<th>Track ID</th><th>Title</th><th>User</th><th>Current Status</th><th>Actions</th>";
echo "</tr>";
foreach ($tracks_to_sync as $sync_item) {
echo "<tr>";
echo "<td>{$sync_item['track_id']}</td>";
echo "<td>{$sync_item['title']}</td>";
echo "<td>{$sync_item['user_name']}</td>";
echo "<td style='color: orange;'>{$sync_item['current_status']}</td>";
echo "<td>";
echo "<button onclick='syncTrackDirectly({$sync_item['track_id']}, \"{$sync_item['task_id']}\")' style='background: #48bb78; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer;'>🚀 Enhanced Sync</button>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "<p><button onclick='syncAllTracks()' style='background: #667eea; color: white; border: none; padding: 12px 24px; border-radius: 8px; cursor: pointer; font-size: 16px;'>🔄 Sync All Tracks with Full Data</button></p>";
}
// Skip API-only tracks section for now - focus on syncing existing tracks
echo "<h2>🎯 Focus: Syncing Existing Tracks</h2>";
echo "<p>We're focusing on getting lyrics and enhanced data for your existing tracks.</p>";
echo "<h3>🔗 Quick Actions</h3>";
echo "<p>";
echo "<button onclick='syncErikTrack()' style='background: #ed8936; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; margin-right: 10px;'>🎵 Sync Erik's Track</button>";
echo "<button onclick='checkAllStatuses()' style='background: #667eea; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; margin-right: 10px;'>🔍 Check All Statuses</button>";
echo "<button onclick='exportFullData()' style='background: #48bb78; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer;'>📊 Export Full Data</button>";
echo "</p>";
?>
<script>
// Direct sync function that works with the current script
async function syncTrackDirectly(trackId, taskId) {
if (confirm('Perform enhanced sync with ALL available data from API.Box?')) {
try {
// Create a form and submit it to the same script
const form = document.createElement('form');
form.method = 'POST';
form.action = window.location.href;
const trackIdInput = document.createElement('input');
trackIdInput.type = 'hidden';
trackIdInput.name = 'sync_track_id';
trackIdInput.value = trackId;
const taskIdInput = document.createElement('input');
taskIdInput.type = 'hidden';
taskIdInput.name = 'sync_task_id';
taskIdInput.value = taskId;
const actionInput = document.createElement('input');
actionInput.type = 'hidden';
actionInput.name = 'action';
actionInput.value = 'sync_track';
form.appendChild(trackIdInput);
form.appendChild(taskIdInput);
form.appendChild(actionInput);
document.body.appendChild(form);
form.submit();
} catch (error) {
alert('Error starting sync: ' + error.message);
}
}
}
// Check full status of a track
async function checkFullStatus(taskId) {
try {
const response = await fetch(`/check_full_status.php?task_id=${taskId}`);
const data = await response.json();
if (data.success) {
// Display full data in a formatted way
let message = `Full API.Box Data for ${taskId}:\n\n`;
message += `Status: ${data.data.status}\n`;
message += `Audio URL: ${data.data.audio_url || 'N/A'}\n`;
message += `Lyrics: ${data.data.lyrics ? 'Available' : 'N/A'}\n`;
message += `Duration: ${data.data.duration || 'N/A'}s\n`;
message += `Genre: ${data.data.genre || 'N/A'}\n`;
message += `BPM: ${data.data.bpm || 'N/A'}\n`;
message += `Key: ${data.data.key || 'N/A'}\n`;
message += `Variations: ${data.data.variations ? data.data.variations.length : 0}\n`;
message += `Quality Score: ${data.data.quality_score || 'N/A'}\n`;
alert(message);
} else {
alert('Failed to get full status: ' + data.error);
}
} catch (error) {
alert('Error checking full status: ' + error.message);
}
}
// Import full track with all data
async function importFullTrack(taskId) {
if (confirm('Import this track with ALL available data from API.Box?')) {
try {
const response = await fetch('/import_full_track.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
task_id: taskId
})
});
const data = await response.json();
if (data.success) {
alert('Full track imported successfully!');
location.reload();
} else {
alert('Import failed: ' + data.error);
}
} catch (error) {
alert('Error importing track: ' + error.message);
}
}
}
// Sync all tracks with full data
async function syncAllTracks() {
if (confirm('Sync ALL tracks with full data from API.Box? This may take a while.')) {
try {
const response = await fetch('/sync_all_tracks_full.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (data.success) {
alert(`Sync completed! ${data.synced_count} tracks updated with full data.`);
location.reload();
} else {
alert('Sync failed: ' + data.error);
}
} catch (error) {
alert('Error syncing all tracks: ' + error.message);
}
}
}
// Special function to sync Erik's track
async function syncErikTrack() {
if (confirm('Sync Erik\'s track with full data from API.Box?')) {
try {
const response = await fetch('/sync_erik_track_full.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (data.success) {
alert('Erik\'s track synced with full data!');
location.reload();
} else {
alert('Sync failed: ' + data.error);
}
} catch (error) {
alert('Error syncing Erik\'s track: ' + error.message);
}
}
}
// Check all statuses
async function checkAllStatuses() {
if (confirm('Check status of all tracks in API.Box? This will show what data is available.')) {
try {
const response = await fetch('/check_all_statuses.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (data.success) {
alert(`Status check completed! Found ${data.total_tracks} tracks with various data availability.`);
location.reload();
} else {
alert('Status check failed: ' + data.error);
}
} catch (error) {
alert('Error checking statuses: ' + error.message);
}
}
}
// Export full data
async function exportFullData() {
if (confirm('Export full data for all tracks? This will create a comprehensive report.')) {
try {
const response = await fetch('/export_full_data.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (data.success) {
alert('Full data export completed! Check the downloads folder.');
} else {
alert('Export failed: ' + data.error);
}
} catch (error) {
alert('Error exporting data: ' + error.message);
}
}
}
</script>