|
<?php |
|
// Set headers for JSON response |
|
header('Content-Type: application/json'); |
|
|
|
// Configuration |
|
$apiUrl = 'https://api.pepy.tech/api/v2/projects/'; |
|
$projects = ['mkdoxy', 'pyspacemouse']; |
|
$apiKey = 'API'; |
|
$cacheFile = 'cache.json'; |
|
$cacheDuration = 12 * 60 * 60; // 12 hours in seconds |
|
|
|
// Check if force revalidation is requested |
|
$forceRevalidate = isset($_GET['force']) && $_GET['force'] === 'true'; |
|
|
|
// Function to fetch project data from API |
|
function fetchProjectData($apiUrl, $project, $apiKey) { |
|
$url = $apiUrl . $project; |
|
|
|
// Create context with headers |
|
$context = stream_context_create([ |
|
'http' => [ |
|
'method' => 'GET', |
|
'header' => "X-API-Key: $apiKey\r\n" |
|
] |
|
]); |
|
|
|
$response = file_get_contents($url, false, $context); |
|
|
|
if ($response === FALSE) { |
|
return ['error' => 'Error fetching data']; |
|
} |
|
|
|
return json_decode($response, true); |
|
} |
|
|
|
// Function to format numbers |
|
function formatNumber($number) { |
|
if ($number >= 1000000) { |
|
return round($number / 1000000, 1) . 'M'; |
|
} elseif ($number >= 1000) { |
|
return round($number / 1000, 1) . 'k'; |
|
} |
|
return $number; |
|
} |
|
|
|
// Determine if cache needs to be updated |
|
$cacheValid = file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheDuration; |
|
|
|
if (!$cacheValid || $forceRevalidate) { |
|
// Initialize result array |
|
$totalDownloads = 0; |
|
$result = [ |
|
'total_downloads' => 0, |
|
'total_downloads_formatted' => '', |
|
'projects' => [], |
|
'last_fetch_time' => date('Y-m-d H:i:s') |
|
]; |
|
|
|
// Fetch data for each project |
|
foreach ($projects as $project) { |
|
$data = fetchProjectData($apiUrl, $project, $apiKey); |
|
|
|
if (isset($data['total_downloads'])) { |
|
$projectDownloads = $data['total_downloads']; |
|
$totalDownloads += $projectDownloads; |
|
$result['projects'][$project] = [ |
|
'total_downloads' => $projectDownloads, |
|
'total_downloads_formatted' => formatNumber($projectDownloads) |
|
]; |
|
} else { |
|
$result['projects'][$project] = [ |
|
'error' => $data['error'] ?? 'No data found' |
|
]; |
|
} |
|
} |
|
|
|
// Set total downloads in the result |
|
$result['total_downloads'] = $totalDownloads; |
|
$result['total_downloads_formatted'] = formatNumber($totalDownloads); |
|
|
|
// Save result to cache |
|
file_put_contents($cacheFile, json_encode($result, JSON_PRETTY_PRINT)); |
|
} else { |
|
// Load cached data |
|
$result = json_decode(file_get_contents($cacheFile), true); |
|
} |
|
|
|
// Return JSON response |
|
echo json_encode($result, JSON_PRETTY_PRINT); |