Handles token refrsh for oAUTH API

This commit is contained in:
Santiago Lema 2025-05-21 02:24:15 +00:00
parent 8dc8688d2e
commit b5adf7dbd0

View file

@ -9,19 +9,57 @@ function isYouTubeLink($url) {
function addVideoToFediList($videoUrl) {
$playlistId = @file_get_contents(__DIR__ .'/_credentials/fedilist_id.txt');
$credentialsDir = __DIR__ . '/_credentials';
$tokenPath = "$credentialsDir/token.json";
$playlistId = @file_get_contents("$credentialsDir/fedilist_id.txt");
if (!$playlistId) {
echo "‼️ Error: FediList ID not found. Make sure fedilist_id.txt exists.\n";
return false;
}
$token = @json_decode(file_get_contents(__DIR__ .'/_credentials/token.json'), true);
// === Load client credentials ===
$secrets = json_decode(file_get_contents("$credentialsDir/client_secret.json"), true);
$client = $secrets['installed'] ?? $secrets['web'] ?? null;
if (!$client || !isset($client['client_id'], $client['client_secret'])) {
die("Error: Invalid client_secret.json format.\n");
}
$clientId = $client['client_id'];
$clientSecret = $client['client_secret'];
// === Load token ===
$token = @json_decode(file_get_contents($tokenPath), true);
if (!$token || !isset($token['access_token'])) {
echo "‼️ Error: token.json missing or invalid. Authenticate first.\n";
return false;
}
// Extract video ID from URL
// === Refresh token if expired ===
if (isset($token['expires_at']) && time() >= $token['expires_at']) {
echo "🔄 Access token expired. Refreshing...\n";
$refreshResponse = curlPost('https://oauth2.googleapis.com/token', [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'refresh_token' => $token['refresh_token'],
'grant_type' => 'refresh_token'
]);
if (isset($refreshResponse['access_token'])) {
$token['access_token'] = $refreshResponse['access_token'];
$token['expires_in'] = $refreshResponse['expires_in'];
$token['expires_at'] = time() + $refreshResponse['expires_in'];
file_put_contents($tokenPath, json_encode($token));
echo "✅ Token refreshed.\n";
} else {
echo "‼️ Failed to refresh token: " . ($refreshResponse['error'] ?? 'unknown') . "\n";
return false;
}
}
// === Extract video ID ===
if (!preg_match('/(?:v=|\/)([a-zA-Z0-9_-]{11})/', $videoUrl, $matches)) {
echo "⁉️ Invalid YouTube URL: $videoUrl\n";
return false;