You are here

class Soundcloud in Media entity Soundcloud 3.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/media/Source/Soundcloud.php \Drupal\media_entity_soundcloud\Plugin\media\Source\Soundcloud

Soundcloud entity media source.

Plugin annotation


@MediaSource(
  id = "soundcloud",
  label = @Translation("Soundcloud"),
  allowed_field_types = {"string", "string_long", "link"},
  default_thumbnail_filename = "soundcloud.png",
  description = @Translation("Provides business logic and metadata for Soundcloud."),
  forms = {
    "media_library_add" = "\Drupal\media_entity_soundcloud\Form\SoundcloudForm"
  }
)

Hierarchy

Expanded class hierarchy of Soundcloud

2 files declare their use of Soundcloud
SoundcloudEmbedFormatter.php in src/Plugin/Field/FieldFormatter/SoundcloudEmbedFormatter.php
SoundcloudForm.php in src/Form/SoundcloudForm.php
1 string reference to 'Soundcloud'
SoundcloudEmbedFormatterTest::testSoundcloudEmbedFormatter in tests/src/Functional/SoundcloudEmbedFormatterTest.php
Tests adding and editing a soundcloud embed formatter.

File

src/Plugin/media/Source/Soundcloud.php, line 31

Namespace

Drupal\media_entity_soundcloud\Plugin\media\Source
View source
class Soundcloud extends MediaSourceBase {

  /**
   * Soundcloud attributes.
   *
   * @var array
   */
  protected $soundcloud;

  /**
   * Config factory interface.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Http Client Interface.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_manager, ConfigFactoryInterface $config_factory, ClientInterface $httpClient) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $field_type_manager, $config_factory);
    $this->httpClient = $httpClient;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('plugin.manager.field.field_type'), $container
      ->get('config.factory'), $container
      ->get('http_client'));
  }

  /**
   * {@inheritdoc}
   */
  public function getMetadataAttributes() {
    $attributes = [
      'track_id' => $this
        ->t('The track id - not always available'),
      'playlist_id' => $this
        ->t('The playlist (set) id - not always available'),
      'source_id' => t('Compound of source type (track or playlist) and id so that it is unique among all SoundCloud media'),
      'html' => $this
        ->t('HTML embed code'),
      'thumbnail_uri' => t('URI of the thumbnail'),
    ];
    return $attributes;
  }

  /**
   * {@inheritdoc}
   */
  public function getMetadata(MediaInterface $media, $attribute_name) {
    $file_system = \Drupal::service('file_system');
    $content_url = $this
      ->getMediaUrl($media);
    if ($content_url === FALSE) {
      return FALSE;
    }
    $data = $this
      ->oEmbed($content_url);
    if ($data === FALSE) {
      return FALSE;
    }
    switch ($attribute_name) {
      case 'html':
        return $data['html'];
      case 'thumbnail_uri':
        if (isset($data['thumbnail_url'])) {
          $destination = $this->configFactory
            ->get('media_entity_soundcloud.settings')
            ->get('thumbnail_destination');
          $local_uri = $destination . '/' . pathinfo($data['thumbnail_url'], PATHINFO_BASENAME);

          // Save the file if it does not exist.
          if (!file_exists($local_uri)) {
            $file_system
              ->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
            $image = file_get_contents($data['thumbnail_url']);
            $file_system
              ->saveData($image, $local_uri, FileSystemInterface::EXISTS_REPLACE);
          }
          return $local_uri;
        }
        return parent::getMetadata($media, $attribute_name);
      case 'track_id':
      case 'playlist_id':
      case 'source_id':

        // Extract the src attribute from the html code.
        preg_match('/src="([^"]+)"/', $data['html'], $src_matches);
        if (!count($src_matches)) {
          return FALSE;
        }

        // Extract the id from the src.
        preg_match('#/(tracks|playlists)/(\\d+)#', urldecode($src_matches[1]), $matches);
        if (!count($matches)) {
          return FALSE;
        }
        if ($attribute_name == 'source_id') {
          return $matches[1] . '/' . $matches[2];
        }
        elseif ($attribute_name == 'track_id' && $matches[1] == 'tracks' || $attribute_name == 'playlist_id' && $matches[1] == 'playlists') {
          return $matches[2];
        }
        return FALSE;
      default:
        return parent::getMetadata($media, $attribute_name);
    }
  }

  /**
   * Returns the track id from the source_url_field.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The media entity.
   *
   * @return string|bool
   *   The track if from the source_url_field if found. False otherwise.
   */
  protected function getMediaUrl(MediaInterface $media) {
    $source_field = $this
      ->getSourceFieldDefinition($media->bundle->entity);
    $field_name = $source_field
      ->getName();
    if ($media
      ->hasField($field_name)) {
      $property_name = $source_field
        ->getFieldStorageDefinition()
        ->getMainPropertyName();
      return $media->{$field_name}->{$property_name};
    }
    return FALSE;
  }

  /**
   * Returns oembed data for a Soundcloud url.
   *
   * @param string $url
   *   The Soundcloud Url.
   *
   * @return array
   *   An array of oembed data.
   */
  protected function oEmbed($url) {
    $this->soundcloud =& drupal_static(__FUNCTION__ . hash('md5', $url));
    if (!isset($this->soundcloud)) {
      $url = 'https://soundcloud.com/oembed?format=json&url=' . $url;
      try {
        $response = $this->httpClient
          ->get($url);
        $this->soundcloud = Json::decode((string) $response
          ->getBody());
      } catch (ClientException $e) {
        $this->soundcloud = FALSE;
      }
    }
    return $this->soundcloud;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MediaSourceBase::$entityFieldManager protected property The entity field manager service.
MediaSourceBase::$entityTypeManager protected property The entity type manager service.
MediaSourceBase::$fieldTypeManager protected property The field type plugin manager service.
MediaSourceBase::$label protected property Plugin label.
MediaSourceBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 2
MediaSourceBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
MediaSourceBase::createSourceField public function Creates the source field definition for a type. Overrides MediaSourceInterface::createSourceField 2
MediaSourceBase::createSourceFieldStorage protected function Creates the source field storage definition.
MediaSourceBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 2
MediaSourceBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
MediaSourceBase::getSourceFieldDefinition public function Get the source field definition for a media type. Overrides MediaSourceInterface::getSourceFieldDefinition
MediaSourceBase::getSourceFieldName protected function Determine the name of the source field. 2
MediaSourceBase::getSourceFieldOptions protected function Get the source field options for the media type form.
MediaSourceBase::getSourceFieldStorage protected function Returns the source field storage definition.
MediaSourceBase::getSourceFieldValue public function Get the primary value stored in the source field. Overrides MediaSourceInterface::getSourceFieldValue
MediaSourceBase::prepareFormDisplay public function Prepares the media type fields for this source in the form display. Overrides MediaSourceInterface::prepareFormDisplay 3
MediaSourceBase::prepareViewDisplay public function Prepares the media type fields for this source in the view display. Overrides MediaSourceInterface::prepareViewDisplay 6
MediaSourceBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
MediaSourceBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 1
MediaSourceBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
MediaSourceInterface::METADATA_FIELD_EMPTY constant Default empty value for metadata fields.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
Soundcloud::$configFactory protected property Config factory interface. Overrides MediaSourceBase::$configFactory
Soundcloud::$httpClient protected property Http Client Interface.
Soundcloud::$soundcloud protected property Soundcloud attributes.
Soundcloud::create public static function Creates an instance of the plugin. Overrides MediaSourceBase::create
Soundcloud::getMediaUrl protected function Returns the track id from the source_url_field.
Soundcloud::getMetadata public function Gets the value for a metadata attribute for a given media item. Overrides MediaSourceBase::getMetadata
Soundcloud::getMetadataAttributes public function Gets a list of metadata attributes provided by this plugin. Overrides MediaSourceInterface::getMetadataAttributes
Soundcloud::oEmbed protected function Returns oembed data for a Soundcloud url.
Soundcloud::__construct public function Constructs a new class instance. Overrides MediaSourceBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.