Version 1
[yaffs-website] / web / modules / contrib / video / src / Plugin / video / Provider / YouTube.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\video\Plugin\video\Provider\YouTube.
6  */
7
8 namespace Drupal\video\Plugin\video\Provider;
9
10 use Drupal\video\ProviderPluginBase;
11 use GuzzleHttp\Exception\ClientException;
12
13 /**
14  * @VideoEmbeddableProvider(
15  *   id = "youtube",
16  *   label = @Translation("YouTube"),
17  *   description = @Translation("YouTube Video Provider"),
18  *   regular_expressions = {
19  *     "@(?:(?<protocol>http|https):)?//(?:www\.)?youtube(?<cookie>-nocookie)?\.com/embed/(?<id>[a-z0-9_-]+)@i",
20  *     "@(?:(?<protocol>http|https):)?//(?:www\.)?youtube(?<cookie>-nocookie)?\.com/v/(?<id>[a-z0-9_-]+)@i",
21  *     "@(?:(?<protocol>http|https):)?//(?:www\.)?youtube(?<cookie>-nocookie)?\.com/watch(\?|\?.*\&)v=(?<id>[a-z0-9_-]+)@i",
22  *     "@(?:(?<protocol>http|https):)?//youtu(?<cookie>-nocookie)?\.be/(?<id>[a-z0-9_-]+)@i"
23  *   },
24  *   mimetype = "video/youtube",
25  *   stream_wrapper = "youtube"
26  * )
27  */
28 class YouTube extends ProviderPluginBase {
29
30   /**
31    * {@inheritdoc}
32    */
33   public function renderEmbedCode($settings) {
34     $file = $this->getVideoFile();
35     $data = $this->getVideoMetadata();
36     return [
37       '#type' => 'html_tag',
38       '#tag' => 'iframe',
39       '#attributes' => [
40         'width' => $settings['width'],
41         'height' => $settings['height'],
42         'frameborder' => '0',
43         'allowfullscreen' => 'allowfullscreen',
44         'src' => sprintf('https://www.youtube.com/embed/%s?autoplay=%d&start=%d', $data['id'], $settings['autoplay'], NULL),
45       ],
46     ];
47   }
48   
49   /**
50    * {@inheritdoc}
51    */
52   public function getRemoteThumbnailUrl() {
53     $data = $this->getVideoMetadata();
54     $url = '';
55
56     // Sometimes the video has not every version of thumbnails. Guzzle throws
57     // exception at that time. Now catch it, and try download another size of
58     // thumbnail.
59     $img_urls = [
60       'http://img.youtube.com/vi/' . $data['id'] . "/maxresdefault.jpg",
61       'http://img.youtube.com/vi/' . $data['id'] . "/hqdefault.jpg",
62       'http://img.youtube.com/vi/' . $data['id'] . "/default.jpg",
63     ];
64
65     foreach ($img_urls as $url) {
66       try {
67         $this->httpClient->request('GET', $url);
68       }
69       catch (ClientException $e) {
70         $e->getResponse();
71         if ($e->getCode() != 404) {
72           throw $e;
73         }
74       }
75     }
76
77     return $url;
78   }
79 }