Add download buttons to test page - downloads confirmed working!

This commit is contained in:
DJP 2025-10-17 16:35:16 -04:00
parent 8cfa971078
commit b8512bc8da
2 changed files with 381 additions and 18 deletions

View file

@ -21,6 +21,65 @@ $assetId = $_GET['asset_id'] ?? '7f2a881a7448794e4c21100c49a32ff0b87bf259';
$assetDetails = null;
$renditions = null;
$error = null;
$downloadResult = null;
// Handle download action
if ($_GET['action'] === 'download' && isset($_GET['endpoint'])) {
$endpoint = $_GET['endpoint'];
$downloadId = $_GET['download_id'] ?? $assetId;
try {
$apiClient = new ApiClient();
$apiClient->setBaseUrl($configV3->getBaseUrl());
$oauth2Handler = new ReflectionProperty($testRunner, 'oauth2Handler');
$oauth2Handler->setAccessible(true);
$oauth2HandlerInstance = $oauth2Handler->getValue($testRunner);
if ($oauth2HandlerInstance) {
$apiClient->setHeader('Authorization', $oauth2HandlerInstance->getAuthHeader());
}
$request = ['method' => 'GET', 'url' => $endpoint];
$response = $apiClient->executeRequest($request);
if ($response['success'] && !empty($response['body'])) {
$jsonCheck = json_decode($response['body'], true);
if (!$jsonCheck || !isset($jsonCheck['exception_body'])) {
// Success! Save file
if (!is_dir('downloads')) {
mkdir('downloads', 0755, true);
}
$filename = "asset_{$downloadId}.jpg";
$filepath = "downloads/{$filename}";
file_put_contents($filepath, $response['body']);
$downloadResult = [
'success' => true,
'filename' => $filename,
'filepath' => $filepath,
'size' => strlen($response['body']),
'endpoint' => $endpoint
];
} else {
$downloadResult = [
'success' => false,
'error' => $jsonCheck['exception_body']['message'] ?? 'Unknown error'
];
}
} else {
$downloadResult = [
'success' => false,
'error' => $response['error'] ?? 'Download failed'
];
}
} catch (Exception $e) {
$downloadResult = [
'success' => false,
'error' => $e->getMessage()
];
}
}
if ($_GET['action'] === 'get_asset') {
try {
@ -70,6 +129,7 @@ if ($_GET['action'] === 'get_asset') {
// Try different download endpoints
$downloadAttempts = [];
$successfulDownload = null;
// Attempt 1: /contents
$attempt1 = [
@ -77,12 +137,26 @@ if ($_GET['action'] === 'get_asset') {
'url' => "/v6/assets/{$assetId}/contents"
];
$result1 = $apiClient->executeRequest($attempt1);
$isError1 = false;
if ($result1['success'] && !empty($result1['body'])) {
$jsonCheck = json_decode($result1['body'], true);
$isError1 = $jsonCheck && isset($jsonCheck['exception_body']);
if (!$isError1 && strlen($result1['body']) > 1000) {
$successfulDownload = [
'endpoint' => 'contents',
'url' => $attempt1['url'],
'data' => $result1['body'],
'size' => strlen($result1['body'])
];
}
}
$downloadAttempts['contents'] = [
'url' => $attempt1['url'],
'http_code' => $result1['http_code'],
'success' => $result1['success'],
'success' => $result1['success'] && !$isError1,
'response_size' => strlen($result1['body'] ?? ''),
'is_json_error' => json_decode($result1['body'] ?? '', true) !== null
'is_json_error' => $isError1
];
// Attempt 2: /content (without 's')
@ -91,12 +165,26 @@ if ($_GET['action'] === 'get_asset') {
'url' => "/v6/assets/{$assetId}/content"
];
$result2 = $apiClient->executeRequest($attempt2);
$isError2 = false;
if ($result2['success'] && !empty($result2['body'])) {
$jsonCheck = json_decode($result2['body'], true);
$isError2 = $jsonCheck && isset($jsonCheck['exception_body']);
if (!$isError2 && strlen($result2['body']) > 1000 && !$successfulDownload) {
$successfulDownload = [
'endpoint' => 'content',
'url' => $attempt2['url'],
'data' => $result2['body'],
'size' => strlen($result2['body'])
];
}
}
$downloadAttempts['content'] = [
'url' => $attempt2['url'],
'http_code' => $result2['http_code'],
'success' => $result2['success'],
'success' => $result2['success'] && !$isError2,
'response_size' => strlen($result2['body'] ?? ''),
'is_json_error' => json_decode($result2['body'] ?? '', true) !== null
'is_json_error' => $isError2
];
// Attempt 3: /original rendition
@ -105,24 +193,27 @@ if ($_GET['action'] === 'get_asset') {
'url' => "/v6/assets/{$assetId}/renditions/ORIGINAL"
];
$result3 = $apiClient->executeRequest($attempt3);
$downloadAttempts['rendition_original'] = [
'url' => $attempt3['url'],
'http_code' => $result3['http_code'],
'success' => $result3['success'],
'response_size' => strlen($result3['body'] ?? ''),
'is_json_error' => json_decode($result3['body'] ?? '', true) !== null
];
$isError3 = false;
if ($result3['success'] && !empty($result3['body'])) {
$jsonCheck = json_decode($result3['body'], true);
$isError3 = $jsonCheck && isset($jsonCheck['exception_body']);
// Attempt 4: Direct file download if we have a URL
if (isset($assetDetails['asset']['content_elements']['content_element'][0])) {
$contentElement = $assetDetails['asset']['content_elements']['content_element'][0];
if (isset($contentElement['download_url'])) {
$downloadAttempts['direct_url'] = [
'url' => $contentElement['download_url'],
'note' => 'Found in content_element download_url'
if (!$isError3 && strlen($result3['body']) > 1000 && !$successfulDownload) {
$successfulDownload = [
'endpoint' => 'rendition_original',
'url' => $attempt3['url'],
'data' => $result3['body'],
'size' => strlen($result3['body'])
];
}
}
$downloadAttempts['rendition_original'] = [
'url' => $attempt3['url'],
'http_code' => $result3['http_code'],
'success' => $result3['success'] && !$isError3,
'response_size' => strlen($result3['body'] ?? ''),
'is_json_error' => $isError3
];
} catch (Exception $e) {
$error = $e->getMessage();
@ -225,7 +316,45 @@ $oauth2Status = $testRunner->getOAuth2Status();
<button type="submit" class="btn">Get Asset Details</button>
</form>
<?php if ($downloadResult): ?>
<div class="alert alert-<?= $downloadResult['success'] ? 'success' : 'error' ?>">
<?php if ($downloadResult['success']): ?>
<strong> Download Successful!</strong><br>
File: <?= htmlspecialchars($downloadResult['filename']) ?><br>
Size: <?= number_format($downloadResult['size']) ?> bytes<br>
Path: <?= htmlspecialchars($downloadResult['filepath']) ?><br>
Endpoint: <code><?= htmlspecialchars($downloadResult['endpoint']) ?></code>
<?php else: ?>
<strong> Download Failed:</strong> <?= htmlspecialchars($downloadResult['error']) ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if (isset($downloadAttempts)): ?>
<div class="section" style="background: #e8f4f8; border: 2px solid #17a2b8;">
<h2>📥 Quick Download</h2>
<p>Click a successful endpoint below to download the file:</p>
<div style="margin: 15px 0;">
<?php
$hasSuccess = false;
foreach ($downloadAttempts as $name => $attempt):
if ($attempt['success']):
$hasSuccess = true;
?>
<a href="?action=download&endpoint=<?= urlencode($attempt['url']) ?>&download_id=<?= urlencode($assetId) ?>&asset_id=<?= urlencode($assetId) ?>"
style="display: inline-block; padding: 12px 24px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; margin: 5px;">
📥 Download via "<?= htmlspecialchars($name) ?>" (<?= number_format($attempt['response_size']) ?> bytes)
</a>
<?php
endif;
endforeach;
?>
<?php if (!$hasSuccess): ?>
<p style="color: #dc3545; margin: 10px 0;">⚠️ No successful endpoints found. File may not exist in storage.</p>
<?php endif; ?>
</div>
</div>
<div class="section">
<h2>Download Endpoint Tests</h2>
<table>

234
test_direct_download.php Normal file
View file

@ -0,0 +1,234 @@
<?php
session_start();
require_once 'config_v3.php';
require_once 'src/TestRunner.php';
require_once 'src/ApiClient.php';
$configV3 = new ConfigV3();
$config = [
'baseUrl' => $configV3->getBaseUrl(),
'timeout' => $configV3->get('api.timeout'),
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
];
$collectionPath = __DIR__ . '/' . $configV3->get('postman_collection');
$testRunner = new TestRunner($collectionPath, $config);
$assetId = $_GET['asset_id'] ?? '001aca62191e54abd8e145d688ce962ee98326cb';
$renditionId = $_GET['rendition_id'] ?? '';
$results = [];
if ($_GET['action'] === 'test') {
$apiClient = new ApiClient();
$apiClient->setBaseUrl($configV3->getBaseUrl());
// Get OAuth2 token
$oauth2Handler = new ReflectionProperty($testRunner, 'oauth2Handler');
$oauth2Handler->setAccessible(true);
$oauth2HandlerInstance = $oauth2Handler->getValue($testRunner);
$authHeader = null;
if ($oauth2HandlerInstance) {
$authHeader = $oauth2HandlerInstance->getAuthHeader();
$apiClient->setHeader('Authorization', $authHeader);
}
// Show auth status
echo "<div style='background: #e9ecef; padding: 15px; margin: 20px 0; border-radius: 6px;'>";
echo "<strong>🔑 Authentication Status:</strong><br>";
echo "OAuth2 Handler: " . ($oauth2HandlerInstance ? 'Active' : 'Not found') . "<br>";
echo "Auth Header: " . ($authHeader ? substr($authHeader, 0, 20) . '...' : 'Not set') . "<br>";
echo "Token Info: " . ($oauth2HandlerInstance ? json_encode($oauth2HandlerInstance->getTokenInfo()) : 'N/A');
echo "</div>";
// Try multiple download endpoints
// Note: V3 Postman collection shows {{baseUrl}}/assets/{id}/contents
// where {{baseUrl}} = https://ppr.dam.ferrero.com/otmmapi
$endpoints = [
// Standard v6 API format (most likely correct based on errors)
'/v6/assets/' . $assetId . '/contents',
'/v6/assets/' . $assetId . '/content',
'/v6/renditions/' . $assetId,
];
// If rendition ID provided, try it
if ($renditionId) {
array_unshift($endpoints, '/v6/renditions/' . $renditionId);
array_unshift($endpoints, '/renditions/' . $renditionId);
}
foreach ($endpoints as $endpoint) {
$request = ['method' => 'GET', 'url' => $endpoint];
$response = $apiClient->executeRequest($request);
$isError = false;
$errorMsg = null;
if ($response['success'] && !empty($response['body'])) {
$jsonCheck = json_decode($response['body'], true);
if ($jsonCheck && isset($jsonCheck['exception_body'])) {
$isError = true;
$errorMsg = $jsonCheck['exception_body']['message'] ?? 'Error';
}
}
$results[] = [
'endpoint' => $endpoint,
'full_url' => $configV3->getBaseUrl() . $endpoint,
'http_code' => $response['http_code'],
'success' => $response['success'],
'body_size' => strlen($response['body'] ?? ''),
'is_error' => $isError,
'error_msg' => $errorMsg,
'is_binary' => !$isError && $response['success'] && strlen($response['body'] ?? '') > 1000
];
// If successful, try to save the file
if (!$isError && $response['success'] && strlen($response['body'] ?? '') > 1000) {
$filename = "test_download_" . basename($endpoint) . ".jpg";
$filepath = "downloads/" . $filename;
if (!is_dir('downloads')) {
mkdir('downloads', 0755, true);
}
file_put_contents($filepath, $response['body']);
$results[count($results) - 1]['saved_to'] = $filepath;
$results[count($results) - 1]['saved_size'] = filesize($filepath);
}
}
}
$oauth2Status = $testRunner->getOAuth2Status();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Direct Download Test</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
padding: 20px;
background: #f5f5f5;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
}
.alert {
padding: 15px;
border-radius: 6px;
margin: 15px 0;
}
.alert-success { background: #d4edda; color: #155724; }
.alert-error { background: #f8d7da; color: #721c24; }
.btn {
padding: 12px 24px;
background: #667eea;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
text-decoration: none;
display: inline-block;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background: #667eea;
color: white;
}
.success { color: #28a745; font-weight: bold; }
.failure { color: #dc3545; font-weight: bold; }
code {
background: #f8f9fa;
padding: 2px 6px;
border-radius: 3px;
font-size: 12px;
}
</style>
</head>
<body>
<div class="container">
<h1>🔍 Direct Download Test</h1>
<?php if ($oauth2Status && $oauth2Status['enabled']): ?>
<div class="alert alert-<?= ($oauth2Status['has_token'] ?? false) ? 'success' : 'error' ?>">
<?= ($oauth2Status['has_token'] ?? false) ? '✅ OAuth2 Token Active' : '❌ OAuth2 Token Issue' ?>
</div>
<?php endif; ?>
<form method="GET">
<label>Asset ID:</label><br>
<input type="text" name="asset_id" value="<?= htmlspecialchars($assetId) ?>"
style="width: 500px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; margin: 10px 0;">
<br>
<input type="hidden" name="action" value="test">
<button type="submit" class="btn">Test All Download Endpoints</button>
</form>
<?php if (!empty($results)): ?>
<h2>Download Endpoint Test Results</h2>
<table>
<thead>
<tr>
<th>Endpoint</th>
<th>Full URL</th>
<th>HTTP</th>
<th>Size</th>
<th>Status</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $result): ?>
<tr style="background: <?= $result['is_binary'] ? '#d4edda' : ($result['is_error'] ? '#f8d7da' : '#fff3cd') ?>">
<td><code><?= htmlspecialchars($result['endpoint']) ?></code></td>
<td style="font-size: 10px; word-break: break-all;"><?= htmlspecialchars($result['full_url']) ?></td>
<td><strong><?= $result['http_code'] ?></strong></td>
<td><?= number_format($result['body_size']) ?> bytes</td>
<td>
<?php if ($result['is_binary']): ?>
<span class="success"> BINARY FILE</span>
<?php elseif ($result['is_error']): ?>
<span class="failure"> ERROR</span>
<?php else: ?>
<span>⚠️ UNKNOWN</span>
<?php endif; ?>
</td>
<td>
<?php if (isset($result['saved_to'])): ?>
<strong style="color: #28a745;">Saved to: <?= htmlspecialchars($result['saved_to']) ?></strong>
<br><small>(<?= number_format($result['saved_size']) ?> bytes)</small>
<?php elseif ($result['error_msg']): ?>
<?= htmlspecialchars($result['error_msg']) ?>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="alert alert-success">
<strong> Look for green rows with "BINARY FILE" - those are successful downloads!</strong>
</div>
<?php endif; ?>
</div>
</body>
</html>