0
votes

I'd like to store a string as a custom field within each YouTube video of a playlist.

(To be specific, my website retrieves this playlist and shows the thumbnail image of each of its videos, and I want to display a quotation under each image.)

I know from docs at https://developers.google.com/youtube/v3/docs/playlistItems/list that I can retrieve details of a YouTube playlist by doing something like this:

$service = new Google_Service_YouTube($client);
$queryParams = [
    'maxResults' => 50,
    'playlistId' => '{myID}'
];
$response = $service->playlistItems->listPlaylistItems('id,snippet,contentDetails,status', $queryParams);

But from those docs and https://developers.google.com/youtube/v3/docs/videos and others, I haven't seen how to save any custom fields.

I suppose I could use the "description" field, but that is not ideal since I'd rather the public-facing description be independent of this custom string field I'd like to save.

How would you recommend achieving my goal (ideally without creating my own database)?

1

1 Answers

0
votes

In case anyone is satisfied by using the "description" field, that's what I settled on since I haven't found anything better.

Hopefully this code helps someone, and I hope even more that someone provides an answer about a better approach.

<?php

namespace App\Helpers;

use Cache;
use \Google_Client as Google_Client;
use \Google_Service_YouTube as Google_Service_YouTube;

class YouTubeHelper {

    const CACHE_KEY_PREFIX = 'youtubePlayListCache_';
    const CACHE_TEMPLATE = self::CACHE_KEY_PREFIX . '{put playlist ID here}';

    /**
     * @param string $playlistId
     * @param int $maxResults
     * @return array
     */
    public static function getVideoIdsAndQuotations($playlistId, $maxResults = 50) {
        $result = [];
        /* @var $ytResponse \Google_Service_YouTube_PlaylistItemListResponse */
        $ytResponse = self::getPlaylistItemListResponse($playlistId, $maxResults);
        foreach ($ytResponse->getItems() as $item) {
            $videoId = $item->getContentDetails()->getVideoId();
            $desc = $item->getSnippet()->getDescription();
            $result[$videoId] = self::getQuotationFromDesc($desc);
        }
        return $result;
    }

    /**
     * 
     * @param string $desc
     * @return string
     */
    public static function getQuotationFromDesc($desc) {
        $lines = explode(PHP_EOL, $desc);
        $firstLine = $lines[0];
        $firstLineWithoutSurroundingQuotes = trim($firstLine, '"');
        return $firstLineWithoutSurroundingQuotes;
    }

    /**
     * @param string $playlistId
     * @param int $maxResults
     * @return \Google_Service_YouTube_PlaylistItemListResponse
     */
    public static function getPlaylistItemListResponse($playlistId, $maxResults = 50) {
        return Cache::rememberForever(self::CACHE_KEY_PREFIX . $playlistId, function()use ($playlistId, $maxResults) {
                    $client = self::getYouTubeClient();
                    $service = new Google_Service_YouTube($client); // Define service object for making API requests.
                    $queryParams = [
                        'maxResults' => $maxResults,
                        'playlistId' => $playlistId
                    ];
                    $response = $service->playlistItems->listPlaylistItems('id,snippet,contentDetails,status', $queryParams);
                    return $response;
                });
    }

    /**
     * @return Google_Client
     */
    public static function getYouTubeClient() {
        $client = new Google_Client();
        $client->setApplicationName('');
        $key = config('services.google.youtubeApiKey');
        $client->setDeveloperKey($key); //https://github.com/googleapis/google-api-php-client
        $client->setScopes(['https://www.googleapis.com/auth/youtube.readonly']);
        $headers = ['Referer' => config('app.url')];
        $guzzleClient = new \GuzzleHttp\Client(['headers' => $headers]);
        $client->setHttpClient($guzzleClient); //https://stackoverflow.com/a/44421003/470749
        return $client;
    }

}