You are here

public function BlazyVideoTrait::getVideoThumbnail in Blazy 7

Returns video thumbnail based on video id, needed by BlazyFilter.

@todo remove if media youtube, etc. support hi-res thumbnails, some time ago the request was rejected, hence the custom solution. Yet this is still relevant for BlazyFilter UGC, though, till merged with media WYSIWYG.

1 call to BlazyVideoTrait::getVideoThumbnail()
BlazyFilter::buildImageItem in src/Plugin/Filter/BlazyFilter.php

File

src/Plugin/Field/FieldFormatter/BlazyVideoTrait.php, line 127

Class

BlazyVideoTrait
A Trait common for Media integration with field details.

Namespace

Drupal\blazy\Plugin\Field\FieldFormatter

Code

public function getVideoThumbnail($url) {
  $vid = $this
    ->getVideoId($url);
  if (!$vid) {
    return '';
  }

  // @todo use VEF or Media family functions instead if any.
  // @see file_uri_to_object($uri, $use_existing = TRUE)
  $dir = 'public://video_thumbnails';

  // @todo avoid hard-coded extension instead of using pathinfo().
  $destination = $dir . '/' . $vid . ".jpg";

  // Returns local file if already stored locally.
  if (is_file($destination)) {
    return file_create_url($destination);
  }

  // Download video thumbnail.
  $file_url = '';
  try {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    if (strpos($url, 'vimeo') !== FALSE) {

      // Supress useless warning for local environment without internet.
      $data = @file_get_contents("{$protocol}://vimeo.com/api/v2/video/{$vid}.json");
      $data = drupal_json_decode($data);
      $file_url = isset($data[0]) ? $data[0]->thumbnail_large : '';
    }
    elseif (strpos($url, 'youtu') !== FALSE) {
      $context_options = [
        "ssl" => [
          "verify_peer" => FALSE,
          "verify_peer_name" => FALSE,
        ],
      ];

      // Supress useless warning for local environment without internet.
      if (@file_get_contents("{$protocol}://img.youtube.com/vi/{$vid}/maxresdefault.jpg", 0, stream_context_create($context_options), 0, 1)) {
        $file_url = "{$protocol}://img.youtube.com/vi/{$vid}/maxresdefault.jpg";
      }
      elseif (@file_get_contents($protocol . "://img.youtube.com/vi/{$vid}/0.jpg", 0, stream_context_create($context_options), 0, 1)) {
        $file_url = "{$protocol}://img.youtube.com/vi/{$vid}/0.jpg";
      }
    }
  } catch (\Exception $e) {

    // Ignore.
  }

  // Cached remote thumbnail locally.
  if ($file_url) {
    if (!is_file($dir)) {
      file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
    }
    if ($file_uri = system_retrieve_file($file_url, $destination, FALSE, FILE_EXISTS_REPLACE)) {
      $file_url = file_create_url($file_uri);
    }
  }
  return $file_url;
}