3 namespace Drupal\video_embed_field;
5 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
6 use Drupal\Core\Plugin\PluginBase;
7 use GuzzleHttp\ClientInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
11 * A base for the provider plugins.
13 abstract class ProviderPluginBase extends PluginBase implements ProviderPluginInterface, ContainerFactoryPluginInterface {
16 * The directory where thumbnails are stored.
20 protected $thumbsDirectory = 'public://video_thumbnails';
23 * The ID of the video.
30 * The input that caused the embed provider to be selected.
39 * @var \GuzzleHttp\ClientInterface
41 protected $httpClient;
44 * Create a plugin with the given input.
46 * @param string $configuration
47 * The configuration of the plugin.
48 * @param string $plugin_id
50 * @param array $plugin_definition
51 * The plugin definition.
52 * @param \GuzzleHttp\ClientInterface $http_client
57 public function __construct($configuration, $plugin_id, $plugin_definition, ClientInterface $http_client) {
58 parent::__construct($configuration, $plugin_id, $plugin_definition);
59 if (!static::isApplicable($configuration['input'])) {
60 throw new \Exception('Tried to create a video provider plugin with invalid input.');
62 $this->input = $configuration['input'];
63 $this->videoId = $this->getIdFromInput($configuration['input']);
64 $this->httpClient = $http_client;
68 * Get the ID of the video.
73 protected function getVideoId() {
74 return $this->videoId;
78 * Get the input which caused this plugin to be selected.
81 * The raw input from the user.
83 protected function getInput() {
90 public static function isApplicable($input) {
91 $id = static::getIdFromInput($input);
98 public function renderThumbnail($image_style, $link_url) {
101 '#uri' => $this->getLocalThumbnailUri(),
104 if (!empty($image_style)) {
105 $output['#theme'] = 'image_style';
106 $output['#style_name'] = $image_style;
122 public function downloadThumbnail() {
123 $local_uri = $this->getLocalThumbnailUri();
124 if (!file_exists($local_uri)) {
125 file_prepare_directory($this->thumbsDirectory, FILE_CREATE_DIRECTORY);
127 $thumbnail = $this->httpClient->request('GET', $this->getRemoteThumbnailUrl());
128 file_unmanaged_save_data((string) $thumbnail->getBody(), $local_uri);
130 catch (\Exception $e) {
138 public function getLocalThumbnailUri() {
139 return $this->thumbsDirectory . '/' . $this->getVideoId() . '.jpg';
145 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
146 return new static($configuration, $plugin_id, $plugin_definition, $container->get('http_client'));
152 public function getName() {
153 return $this->t('@provider Video (@id)', ['@provider' => $this->getPluginDefinition()['title'], '@id' => $this->getVideoId()]);