![]() 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/public_html/ |
<?php
// Sync All Tracks with Full Data from API.Box
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config/database.php';
$api_key = '63edba40620216c5aa2c04240ac41dbd';
echo "<h1>🚀 Full Track Sync - Loading Missing Info on Cards</h1>";
echo "<p><strong>This script syncs ALL tracks with their complete data from API.Box and displays missing info on the cards.</strong></p>";
$pdo = getDBConnection();
if (!$pdo) {
echo "<p style='color: red;'>❌ Database connection failed</p>";
exit;
}
// Function to get FULL track data from API.Box using individual status endpoint
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-Full-Sync/2.0'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
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
];
}
// Function to sync track with ALL data and update database
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'];
}
}
// Get all local tracks that have task_ids
echo "<h2>🔍 Finding Tracks to Sync</h2>";
$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
WHERE mt.task_id IS NOT NULL AND mt.task_id != ''
ORDER BY mt.created_at DESC
");
$stmt->execute();
$local_tracks = $stmt->fetchAll();
echo "<p>Found " . count($local_tracks) . " tracks with task IDs</p>";
if (empty($local_tracks)) {
echo "<p>❌ No tracks found with task IDs. Cannot sync without API.Box task IDs.</p>";
exit;
}
// Display tracks and sync them
echo "<h2>📋 Syncing All Tracks with Full Data</h2>";
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>Task ID</th><th>Current Status</th><th>Actions</th>";
echo "</tr>";
$synced_count = 0;
$failed_count = 0;
foreach ($local_tracks as $track) {
echo "<tr>";
echo "<td>{$track['id']}</td>";
echo "<td>" . htmlspecialchars($track['title'] ?: 'Untitled') . "</td>";
echo "<td>{$track['user_name']}</td>";
echo "<td style='font-family: monospace;'>{$track['task_id']}</td>";
echo "<td style='color: " . ($track['status'] === 'complete' ? 'green' : 'orange') . "'>{$track['status']}</td>";
echo "<td>";
if ($track['status'] !== 'complete') {
echo "<button onclick='syncTrack({$track['id']}, \"{$track['task_id']}\")' style='background: #48bb78; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer;'>🚀 Sync Full Data</button>";
} else {
echo "<button onclick='checkTrackData({$track['id']})' style='background: #667eea; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer;'>🔍 Check Data</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>";
// Show current data status
echo "<h2>📊 Current Data Status</h2>";
$stmt = $pdo->prepare("
SELECT
COUNT(*) as total_tracks,
SUM(CASE WHEN lyrics IS NOT NULL AND lyrics != '' THEN 1 ELSE 0 END) as tracks_with_lyrics,
SUM(CASE WHEN metadata IS NOT NULL AND metadata != '' THEN 1 ELSE 0 END) as tracks_with_metadata,
SUM(CASE WHEN duration IS NOT NULL THEN 1 ELSE 0 END) as tracks_with_duration,
SUM(CASE WHEN status = 'complete' THEN 1 ELSE 0 END) as completed_tracks
FROM music_tracks
");
$stmt->execute();
$stats = $stmt->fetch();
echo "<div style='display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;'>";
echo "<div style='background: #f7fafc; padding: 20px; border-radius: 8px; text-align: center;'>";
echo "<h3>📊 Total Tracks</h3>";
echo "<p style='font-size: 24px; font-weight: bold; color: #2d3748;'>{$stats['total_tracks']}</p>";
echo "</div>";
echo "<div style='background: #f0fff4; padding: 20px; border-radius: 8px; text-align: center;'>";
echo "<h3>🎵 With Lyrics</h3>";
echo "<p style='font-size: 24px; font-weight: bold; color: #38a169;'>{$stats['tracks_with_lyrics']}</p>";
echo "</div>";
echo "<div style='background: #fffaf0; padding: 20px; border-radius: 8px; text-align: center;'>";
echo "<h3>📋 With Metadata</h3>";
echo "<p style='font-size: 24px; font-weight: bold; color: #d69e2e;'>{$stats['tracks_with_metadata']}</p>";
echo "</div>";
echo "<div style='background: #f0f9ff; padding: 20px; border-radius: 8px; text-align: center;'>";
echo "<h3>⏱️ With Duration</h3>";
echo "<p style='font-size: 24px; font-weight: bold; color: #3182ce;'>{$stats['tracks_with_duration']}</p>";
echo "</div>";
echo "<div style='background: #f0fff4; padding: 20px; border-radius: 8px; text-align: center;'>";
echo "<h3>✅ Completed</h3>";
echo "<p style='font-size: 24px; font-weight: bold; color: #38a169;'>{$stats['completed_tracks']}</p>";
echo "</div>";
echo "</div>";
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='exportFullData()' style='background: #48bb78; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer;'>📊 Export Full Data</button>";
echo "</p>";
?>
<script>
// Sync individual track with full data
async function syncTrack(trackId, taskId) {
if (confirm('Sync this track with ALL available data from API.Box?')) {
try {
const response = await fetch('/sync_single_track.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
track_id: trackId,
task_id: taskId
})
});
const data = await response.json();
if (data.success) {
alert('Track synced successfully with full data!');
location.reload();
} else {
alert('Sync failed: ' + data.error);
}
} catch (error) {
alert('Error during sync: ' + error.message);
}
}
}
// Check track data
async function checkTrackData(trackId) {
try {
const response = await fetch(`/check_track_data.php?track_id=${trackId}`);
const data = await response.json();
if (data.success) {
let message = `Track Data for ID ${trackId}:\n\n`;
message += `Title: ${data.track.title || 'N/A'}\n`;
message += `Audio URL: ${data.track.audio_url || 'N/A'}\n`;
message += `Lyrics: ${data.track.lyrics ? 'Available' : 'N/A'}\n`;
message += `Duration: ${data.track.duration || 'N/A'}s\n`;
message += `Metadata: ${data.track.metadata ? 'Available' : 'N/A'}\n`;
message += `Status: ${data.track.status}\n`;
alert(message);
} else {
alert('Failed to get track data: ' + data.error);
}
} catch (error) {
alert('Error checking track data: ' + 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_batch.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);
}
}
}
// 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);
alert('Export failed: ' + data.error);
}
} catch (error) {
alert('Error exporting data: ' + error.message);
}
}
}
</script>