You are here

function youtube_get_remote_image in YouTube Field 8

Same name and namespace in other branches
  1. 7 youtube.inc \youtube_get_remote_image()

Retrieves the thumbnail image for a given video from YouTube.

Parameters

int $video_id: The video ID of the particular YouTube video.

bool $force_small: (optional) When TRUE, this function should return the standard size image regardless of what the youtube_thumb_hires variable is set to. This is used should the high resolution image be found to not exist for a particular video.

Return value

bool|object Either the Drupal $file object of saved image, or FALSE if the save failed.

2 calls to youtube_get_remote_image()
template_preprocess_youtube_thumbnail in ./youtube.module
Prepares variables for the YouTube Thumbnail template.
youtube_tokens in ./youtube.module
Implements hook_tokens().

File

./youtube.module, line 312
Youtube field module adds a field for YouTube videos.

Code

function youtube_get_remote_image($video_id = NULL, $force_small = FALSE) {

  // This value is TRUE when higher resolution thumbnails should be saved.
  // This resolution is not guaranteed to exist and if it doesn't, the smaller
  // resolution image will be saved in its place.
  $youtube_thumb_hires = \Drupal::config('youtube.settings')
    ->get('youtube_thumb_hires');

  // This boolean is TRUE if we're obtaining a hi-res thumbnail.
  $get_hires = $youtube_thumb_hires && !$force_small;

  // Build the image url.
  if ($get_hires) {
    $src = youtube_build_remote_image_path($video_id, 'maxresdefault');
  }
  else {
    $src = youtube_build_remote_image_path($video_id);
  }

  // Make the request for the file.
  try {
    $image_request = Drupal::httpClient()
      ->get($src);
  } catch (RequestException $e) {

    // The high resolution image didn't exist and the request was a 404. Force
    // it to try again, but look for the smaller resolution image.
    if ($get_hires) {
      return youtube_get_remote_image($video_id, TRUE);
    }
    watchdog_exception('youtube', $e);
    return FALSE;
  }
  $youtube_thumb_uri = youtube_build_thumbnail_uri();
  if (!\Drupal::service('file_system')
    ->prepareDirectory($youtube_thumb_uri, FileSystemInterface::CREATE_DIRECTORY) && !mkdir($youtube_thumb_uri, 0775, TRUE)) {
    \Drupal::service('logger.factory')
      ->get('youtube')
      ->error('Failed to create YouTube thumbnail directory: %dir', [
      '%dir' => $youtube_thumb_uri,
    ]);
    return FALSE;
  }
  $data = $image_request
    ->getBody(TRUE);
  $destination = youtube_build_thumbnail_uri($video_id);

  // Save the thumbnail and add to Drupal managed files.
  $file = file_save_data($data, $destination, FileSystemInterface::EXISTS_REPLACE);
  if (!$file) {
    \Drupal::service('logger.factory')
      ->get('youtube')
      ->error('Unable to save youtube thumbnail to filesystem for video %id', [
      '%id' => $video_id,
    ]);
    return FALSE;
  }
  return $file;
}