Skip to content

Instantly share code, notes, and snippets.

@adlerweb
Created April 26, 2015 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adlerweb/e0336c7369f416b2bfdc to your computer and use it in GitHub Desktop.
Save adlerweb/e0336c7369f416b2bfdc to your computer and use it in GitHub Desktop.
Youtube WatchLater to Playlist Script
<?php
/**
* Youtube Watch Later List To Playlist Script
*
* This script fetches your watch later list and outputs it as an M3U playlist
*
* Requirements:
* PHP enabled webserver
* Google PHP API (https://github.com/google/google-api-php-client)
* A YouTube API key (Oauth2, can be registered at https://console.developers.google.com/)
* Some kittens to sacrifice
*
* Initialization
* First ensure your webserver can write a file called "key.php" to the directory
* you put this file in. E.g. "touch key.php ; chmod ugo+w key.php"
* Next open the appropriate URL in your browser. You will be asked to pair
* this script with your YouTube-Account. If you configured everything correctly
* it will output the playlist and save your access codes in the key.php mentioned
* above. Successive requests do not require additional authentication. You may now
* put the URL in your YT-enabled media player like VLC.
*
* Based on examples by DomSammut (https://www.domsammut.com/code/php-server-side-youtube-v3-oauth-api-video-upload-guide)
* 2015 Florian Knodt <yt@adlerweb.info>
*/
// Set this to the directory of google api php client
set_include_path('./google-api-php-client/src/');
$OAUTH2_CLIENT_ID = 'YOURID.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'YOURSECRET';
$REDIRECT = 'http://localhost/yt/ytwll2m3u.php';
$APPNAME = 'YouTube WLL Import Test';
require_once 'Google/autoload.php';
session_start();
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setApplicationName($APPNAME);
$client->setAccessType('offline');
if(file_exists('key.php')) {
require_once 'key.php';
}
if(isset($key)) {
$client->setAccessToken($key);
$_SESSION['token'] = $key;
}else{
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri($REDIRECT);
}
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
$keydata = '<?php $key=\''.$_SESSION['token'].'\'; ?>';
//echo '<code>' . $_SESSION['token'] . '</code>';
if(!is_writable('key.php')) {
die('key.php can not be written - please put this code into key.php: '.$keydata);
}
file_put_contents('key.php', $keydata);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Call the channels.list method to retrieve information about the
// currently authenticated user's channel.
$channelsResponse = $youtube->channels->listChannels('contentDetails', array(
'mine' => 'true',
));
$playlist = '#EXTM3U'."\n";
foreach ($channelsResponse['items'] as $channel) {
// Extract the unique playlist ID that identifies the list of videos
// uploaded to the channel, and then call the playlistItems.list method
// to retrieve that list.
$uploadsListId = $channel['contentDetails']['relatedPlaylists']['watchLater'];
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $uploadsListId,
'maxResults' => 50
));
foreach ($playlistItemsResponse['items'] as $playlistItem) {
$playlist .= '#EXTINF:-1,'.$playlistItem['snippet']['title']."\n".'https://www.youtube.com/watch?v='.$playlistItem['snippet']['resourceId']['videoId']."\n";
}
while(isset($playlistItemsResponse['nextPageToken'])) {
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $uploadsListId,
'maxResults' => 50,
'nextPageToken' => $playlistItemsResponse['nextPageToken'],
));
foreach ($playlistItemsResponse['items'] as $playlistItem) {
//$htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'],
//$playlistItem['snippet']['resourceId']['videoId']);
$playlist .= '#EXTINF:-1,'.$playlistItem['snippet']['title']."\n".'https://www.youtube.com/watch?v='.$playlistItem['snippet']['resourceId']['videoId']."\n";
}
}
}
} catch (Google_ServiceException $e) {
echo sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
echo sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to <a href="$authUrl">authorise access</a> before proceeding.<p>
END;
}
if(isset($playlist)) die($playlist);
?>
<!doctype html>
<html>
<head>
<title>My Uploads</title>
</head>
<body>
<?php echo $htmlBody?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment