video_embed_spotify-8.x-1.5/src/Plugin/video_embed_field/Provider/Spotify.php
src/Plugin/video_embed_field/Provider/Spotify.php
<?php
namespace Drupal\video_embed_spotify\Plugin\video_embed_field\Provider;
use Drupal\video_embed_field\ProviderPluginBase;
/**
* Provides Spotify plugin.
*
* @VideoEmbedProvider(
* id = "spotify",
* title = @Translation("Spotify")
* )
*/
class Spotify extends ProviderPluginBase {
const URLREGEXP = "/^https:\/\/(open\.spotify\.com\/)(embed-podcast\/|embed\/)?(?<type>album|artist|episode|playlist|show|track|user)\/(?<id>[0-9A-Za-z_-]*)(\?.*)?$/i";
/**
* {@inheritdoc}
*/
public function renderEmbedCode($width, $height, $autoplay, $title_format = NULL, $use_title_fallback = TRUE) {
$embed_code = [
'#type' => 'video_embed_iframe',
'#provider' => 'spotify',
'#url' => $this->buildEmbedUrl(),
'#attributes' => [
'width' => $width,
'height' => $height,
'frameborder' => '0',
'allowfullscreen' => 'allowfullscreen',
'allowtransparency' => 'true',
'allow' => 'encrypted-media',
],
];
$title = $this->getName($title_format, $use_title_fallback);
if (isset($title)) {
$embed_code['#attributes']['title'] = $title;
}
return $embed_code;
}
/**
* Get the Spotify oembed data.
*
* @return mixed
* An array of data from the oembed endpoint.
*/
protected function oEmbedData() {
// Adding headers to the request.
$opts = [
'http' => [
'header' => "User-Agent:MyAgent/1.0\r\n",
],
];
$context = stream_context_create($opts);
return json_decode(file_get_contents('https://open.spotify.com/oembed?url=' . $this->getInput(), FALSE, $context));
}
/**
* {@inheritdoc}
*/
public function getRemoteThumbnailUrl() {
try {
return $this->oEmbedData()->thumbnail_url;
}
catch (\Exception $e) {
}
return "";
}
/**
* {@inheritdoc}
*/
public function getLocalThumbnailUri() {
return $this->thumbsDirectory . '/' . str_replace('/', '', $this->getVideoId()) . '.jpg';
}
/**
* {@inheritdoc}
*/
public static function getIdFromInput($input) {
preg_match(static::URLREGEXP, $input, $matches);
return $matches['id'] ?? FALSE;
}
/**
* {@inheritdoc}
*/
protected function buildEmbedUrl() {
preg_match(static::URLREGEXP, $this->getInput(), $matches);
if (isset($matches['id']) && isset($matches['type'])) {
$path = 'https://open.spotify.com/embed';
$path .= ((in_array($matches['type'], ['episode', 'show'])) ? ('-podcast') : (''));
$path .= '/' . $matches['type'] . '/' . $matches['id'];
return $path;
}
return "";
}
}
