widen_media-1.0.x-dev/src/Service/Widen.php

src/Service/Widen.php
<?php

namespace Drupal\widen_media\Service;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\State\State;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\widen_media\Widen\WidenAsset;
use Drupal\widen_media\WidenAssetException;
use GuzzleHttp\Client;

/**
 * Widen API Class.
 *
 * Interacts with Widen Collective service to get asset information.
 */
class Widen {

  use StringTranslationTrait;

  /**
   * Logger Service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * State Service.
   *
   * @var \Drupal\Core\State\State
   */
  protected $state;

  /**
   * Cache Backend Service.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

  /**
   * Guzzle Client.
   *
   * @var \GuzzleHttp\Client
   */
  protected $client;

  /**
   * Pattern used for extracting asset id from URL.
   *
   * @var string
   */
  protected $assetPattern = '/asset:(\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12})/';

  /**
   * Constructor for Widen Service.
   *
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerChannelFactory
   *   The Logger Factory.
   * @param \Drupal\Core\State\State $state
   *   The State Service.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cacheBackend
   *   The Cache Service.
   */
  public function __construct(
    LoggerChannelFactoryInterface $loggerChannelFactory,
    State $state,
    CacheBackendInterface $cacheBackend
  ) {
    $this->logger = $loggerChannelFactory->get('widen_media');
    $this->state = $state;
    $this->cacheBackend = $cacheBackend;
  }

  /**
   * Return the thumbnail sizes.
   *
   * @return array
   *   The labels used for Thumbnail Sizes.
   */
  public static function getThumbnailSizes() {
    return [
      '125px' => t('125px'),
      '160px' => t('160px'),
      '300px' => t('300px'),
      '600px' => t('600px'),
      '2048px' => t('2048px'),
    ];
  }

  /**
   * Return the embed types.
   *
   * @param string $type
   *   The type of embed options to remove.
   *
   * @return array
   *   The labels for embed types.
   */
  public static function getEmbedTypes($type) {
    switch ($type) {
      case 'video':
        return [
          'VideoWithPlayerAndDownload' => t('Video with Player and Download'),
          'video_player' => t('Video Player'),
          'video_player_with_download' => t('Video Player with Download'),
          'video_poster' => t('Video Poster'),
          'original' => t('Original'),
        ];

      case 'document':
        return [
          'document_html5_viewer' => t('HTML5 Viewer'),
          'document_thumbnail' => t('Document Thumbnail'),
          'document_viewer' => t('Document Viewer'),
          'document_viewer_with_download' => t('Document Viewer with Download'),
          'original' => t('Original'),
        ];

      case 'image':
        return [
          '1080pxLandscape' => t('1080px Landscape'),
          '360pxportrait' => t('360px Portrait'),
          '640pxLandscape' => t('640px Landscape'),
          '720pxPortrait' => t('720px Portrait'),
          'Originalwidth&height' => t('Original Width & Height'),
          'original' => t('Original'),
        ];

      default:
        return [];
    }
  }

  /**
   * Get asset data from the Widen service.
   *
   * @param string $url
   *   The URL to get assets from.
   *
   * @return \Drupal\widen_media\Widen\WidenAsset
   *   Return the Asset associated with the URL.
   *
   * @throws \Drupal\widen_media\WidenAssetException
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function getAsset($url) {
    $id = $this->extractAssetId($url);

    if ($id === FALSE) {
      throw new WidenAssetException("Unable to extract Asset ID");
    }

    $cid = "widen_media:asset:" . $id;
    if ($cache = $this->cacheBackend->get($cid)) {
      return WidenAsset::create($cache->data);
    }

    $asset = $this->makeRequest('GET', 'assets/' . $id, [
      'query' => ['expand' => $this->getExpandItems()],
    ]);

    // Cache the asset.
    $this->cacheBackend->set($cid, $asset, CacheBackendInterface::CACHE_PERMANENT);

    return WidenAsset::create($asset);
  }

  /**
   * Search Widen for Particular Set of Assets.
   *
   * @param string $query
   *   Data to search for in Widen.
   * @param string $sort
   *   Sort data by specific field.
   * @param bool $included_deleted
   *   Include data that is deleted.
   * @param bool $included_archived
   *   Include data that is archived.
   * @param bool $search_document_text
   *   Search the Document Text.
   *
   * @return \Drupal\widen_media\Widen\WidenAsset[]
   *   The Assets returned from the search.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function search(
    string $query,
    string $sort = '-created_date',
    bool $included_deleted = FALSE,
    bool $included_archived = FALSE,
    bool $search_document_text = FALSE
  ) {
    $requestQuery = [
      'query' => $query,
      'sort' => $sort,
      'include_deleted' => $included_deleted ? 'true' : 'false',
      'include_archived' => $included_archived ? 'true' : 'false',
      'search_document_text' => $search_document_text ? 'true' : 'false',
      'expand' => $this->getExpandItems(),
    ];

    return $this->getAllData('GET', 'assets/search', [
      'query' => $requestQuery,
    ]);
  }

  /**
   * Return the current user's widen account details.
   *
   * @return array
   *   Return widen account data for overall site.
   */
  private function getWidenAccount() {
    return $this->state->get('widencollective_auth', FALSE);
  }

  /**
   * Create a new client.
   *
   * @return \GuzzleHttp\Client
   *   Create a new Guzzle Client.
   */
  private function createClient() {
    return new Client([
      'base_uri' => 'https://api.widencollective.com/v2/',
      'default' => [
        'headers' => [
          'Content-type' => 'application/json',
          'Accept' => 'application/json',
        ],
      ],
    ]);
  }

  /**
   * Return the Client used for making requests.
   *
   * @return \GuzzleHttp\Client
   *   Return Guzzle Client.
   */
  private function getClient() {
    if (is_null($this->client)) {
      $this->client = $this->createClient();
    }

    return $this->client;
  }

  /**
   * Create a new request widen api.
   *
   * @param string $method
   *   The method to make a request for. Get, Post, Put, etc.
   * @param string $url
   *   The Request URL to make requests.
   * @param array $options
   *   The options for the request.
   *
   * @return array
   *   Return the data from the request.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  private function makeRequest(string $method, string $url, array $options = []) {
    $accessToken = $this->getWidenAccount();
    if ($accessToken !== FALSE) {
      $options['headers']['Authorization'] = 'Bearer ' . $accessToken['widen_token'];
      $request = $this->getClient()->request($method, $url, $options);
      return Json::decode($request->getBody());
    }
    return [];
  }

  /**
   * Get all the data for the requested url. This handles pagination.
   *
   * @param string $method
   *   The method to make a request for. Get, Post, Put, etc.
   * @param string $url
   *   The Request URL to make requests.
   * @param array $options
   *   The options for the request.
   * @param array $data
   *   The items being collected.
   *
   * @return \Drupal\widen_media\Widen\WidenAsset[]
   *   Return the data from the request.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  private function getAllData(string $method, string $url, array $options = [], array &$data = []) {
    if (!isset($options['query']['offset'])) {
      $options['query']['offset'] = 0;
    }

    if (!isset($options['query']['limit'])) {
      $options['query']['limit'] = 100;
    }

    $request = $this->makeRequest($method, $url, $options,);

    $items = $request['items'] ?? [];
    foreach ($items as $item) {
      $data[$item['id']] = WidenAsset::create($item);
    }

    if (!isset($request['total_count']) || !isset($request['query']['offset']) || !isset($request['query']['limit'])) {
      $this->logger->error('No counts provided in the return.');
      return $data;
    }

    if (count($data) < $request['total_count']) {
      $options['query']['offset'] = ($options['query']['offset'] + $options['query']['limit']);
      $this->getAllData($method, $url, $options, $data);
    }

    return $data;
  }

  /**
   * Return a list of the elements to expand.
   *
   * @return string
   *   Return the list of expanded items for service.
   */
  private function getExpandItems() {
    return implode(',', [
      'asset_properties',
      'file_properties',
      'embeds',
      'thumbnails',
      'metadata',
      'metadata_info',
      'metadata_vocabulary',
      'security',
    ]);
  }

  /**
   * Get the asset id rom the url.
   *
   * @param string $url
   *   The URL to extract that asset ID.
   *
   * @return string
   *   Return the UUID from the Url.
   */
  protected function extractAssetId($url) {
    preg_match($this->assetPattern, $url, $matches);
    if (count($matches) > 0) {
      return $matches[1];
    }
    return FALSE;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc