93 lines
2.9 KiB
PHP
93 lines
2.9 KiB
PHP
<?php
|
||
|
||
// === Example use ===
|
||
#addVideoToFediList('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||
|
||
function isYouTubeLink($url) {
|
||
return preg_match('#^(https?://)?(www\.)?(youtube\.com/watch\?v=|youtu\.be/)[a-zA-Z0-9_-]{11}#', $url);
|
||
}
|
||
|
||
function addVideoToFediList($videoUrl) {
|
||
|
||
$playlistId = @file_get_contents(__DIR__ .'/_credentials/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);
|
||
if (!$token || !isset($token['access_token'])) {
|
||
echo "‼️ Error: token.json missing or invalid. Authenticate first.\n";
|
||
return false;
|
||
}
|
||
|
||
// Extract video ID from URL
|
||
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;
|
||
}
|
||
}
|
||
|
||
?>
|