You are here

public function Brightcove::getRemoteThumbnailUrl in Video Embed Brightcove 8

File

src/Plugin/video_embed_field/Provider/Brightcove.php, line 91

Class

Brightcove
A Brightcove provider plugin.

Namespace

Drupal\video_embed_brightcove\Plugin\video_embed_field\Provider

Code

public function getRemoteThumbnailUrl() {

  // Get configured credentials.
  $config = $this->configFactory
    ->get('video_embed_brightcove.settings');
  $client_id = $config
    ->get('client_id');
  $client_secret = $config
    ->get('client_secret');

  // Skip if credentials are not configured.
  if (empty($client_id) || empty($client_secret)) {
    throw new \Exception('Brightcove API credentials are not set.');
  }

  // Process authentication to get access token.
  $auth_uri = 'https://oauth.brightcove.com/v4/access_token';
  $auth_string = base64_encode($client_id . ':' . $client_secret);
  $auth_options = [
    'headers' => [
      'Authorization' => 'Basic ' . $auth_string,
      'Content-Type' => 'application/x-www-form-urlencoded',
    ],
    'body' => 'grant_type=client_credentials',
  ];
  $auth = $this->httpClient
    ->request('POST', $auth_uri, $auth_options);

  // Skip if authentication was not successful.
  if ($auth
    ->getStatusCode() !== 200) {
    throw new \Exception('Brightcove API authentication failed.');
  }
  $auth_json = json_decode($auth
    ->getBody()
    ->getContents());

  // Process request to get video images.
  if (!empty($auth_json->access_token)) {
    $video_uri = 'https://cms.api.brightcove.com/v1/accounts/' . $this
      ->getPlayerId() . '/videos/' . $this
      ->getVideoId() . '/images';
    $video_options = [
      'headers' => [
        'Authorization' => 'Bearer ' . $auth_json->access_token,
        'Content-Type' => 'application/json',
      ],
    ];
    $video = $this->httpClient
      ->request('GET', $video_uri, $video_options);

    // Skip if request was not successful.
    if ($video
      ->getStatusCode() !== 200) {
      throw new \Exception('Brightcove API video request failed.');
    }
    $video_json = json_decode($video
      ->getBody()
      ->getContents());

    // Get poster image URL if available.
    if (!empty($video_json->poster->src)) {
      return $video_json->poster->src;
    }
  }

  // Throw exception if something went wrong.
  throw new \Exception('Brightcove API video thumbnail unavailable.');
}