diff --git a/add_to_fedilist.php b/add_to_fedilist.php index 74a2b7d5..df246b0d 100644 --- a/add_to_fedilist.php +++ b/add_to_fedilist.php @@ -8,24 +8,62 @@ 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; - } + } $videoId = $matches[1]; // === Step 1: Check if video is already in playlist ===