$refreshSecondMargin) { $minutes = floor($secondsLeft / 60); $seconds = $secondsLeft % 60; echo "⏳ Token expires in $minutes minutes and $seconds seconds.\n"; } else { echo "🔄 Access token expired or will expire in less than $refreshSecondMargin seconds. (Seconds Left: $secondsLeft). 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 === $checkUrl = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={$playlistId}&maxResults=50"; $found = false; do { $ch = curl_init($checkUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $token['access_token'], 'User-Agent: curl/7.64.1' ]); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); foreach ($data['items'] ?? [] as $item) { if (($item['snippet']['resourceId']['videoId'] ?? '') === $videoId) { echo "ℹ️ Video already in FediList: $videoId\n"; return false; } } $checkUrl = $data['nextPageToken'] ?? false ? $checkUrl . '&pageToken=' . $data['nextPageToken'] : false; } while ($checkUrl); // === Step 2: Add the video === $postData = [ 'snippet' => [ 'playlistId' => $playlistId, 'resourceId' => [ 'kind' => 'youtube#video', 'videoId' => $videoId ] ] ]; $ch = curl_init('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $token['access_token'], 'Content-Type: application/json', 'User-Agent: curl/7.64.1' ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); if (isset($result['id'])) { echo "✅ Added video to FediList: $videoId\n"; return true; } else { echo "‼️ Failed to add video:\n$response\n"; return false; } } ?>