webdam-1.0.x-dev/src/WebdamConnector.php

src/WebdamConnector.php
<?php

namespace Drupal\webdam;

use Bynder\webdam\Client;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Extension\ModuleExtensionList;
use GuzzleHttp\Client as HttpClient;

/**
 * Webdam api connector.
 */
class WebdamConnector {

  /**
   * The base URL of the webdam API.
   */
  const BASE_URL = "https://apiv2.webdamdb.com";

  /**
   * The http client.
   *
   * @var \GuzzleHttp\Client
   */
  protected HttpClient $httpClient;

  /**
   * Webdam settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected ImmutableConfig $webdamSettings;

  /**
   * The list of modules.
   *
   * @var \Drupal\Core\Extension\ModuleExtensionList
   */
  protected ModuleExtensionList $extensionList;

  /**
   * Constructs WebdamConnector.
   *
   * @param \GuzzleHttp\Client $http_client
   *   The http client.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory.
   * @param \Drupal\Core\Extension\ModuleExtensionList $extension_list
   *   The extension list.
   */
  public function __construct(HttpClient $http_client, ConfigFactoryInterface $config_factory, ModuleExtensionList $extension_list) {
    $this->httpClient = $http_client;
    $this->webdamSettings = $config_factory->get('webdam.settings');
    $this->extensionList = $extension_list;
  }

  /**
   * Prepares the WebDam client using values stored in config.
   *
   * @return \Bynder\webdam\Client
   *   The configured webdam client.
   */
  public function getClient(): Client {
    return $this->doGetClient(
      $this->webdamSettings->get('username'),
      $this->webdamSettings->get('password'),
      $this->webdamSettings->get('client_id'),
      $this->webdamSettings->get('client_secret')
    );
  }

  /**
   * Prepares the WebDam client.
   *
   * @param string $username
   *   The username.
   * @param string $password
   *   The password.
   * @param string $client_id
   *   Thc client id.
   * @param string $client_secret
   *   The client secret.
   *
   * @return \Bynder\webdam\Client
   *   The configured webdam client.
   */
  public function doGetClient(string $username, string $password, string $client_id, string $client_secret): Client {
    return new Client($this->httpClient, $username, $password, $client_id, $client_secret);
  }

  /**
   * Get the auth token.
   *
   * Copied from \Bynder\webdam\Client::checkAuth.
   *
   * @return string
   *   The auth token.
   *
   * @throws \Bynder\webdam\Exception\InvalidCredentialsException
   * @throws \Exception
   */
  public function getToken() {
    $client = $this->getClient();

    $client->checkAuth();
    $auth_state = $client->getAuthState();

    if ($auth_state['valid_token'] && !empty($auth_state['access_token'])) {
      return $auth_state['access_token'];
    }
    else {
      throw new \Exception('Invalid or missing token');
    }
  }

  /**
   * Get metadata via graphQL.
   *
   * This mimics the call made by UCV.
   *
   * @param int $id
   *   The UUID of the item.
   *
   * @return array
   *   Item data.
   */
  public function getMetadataGraphQL(string $id): array {
    global $base_url;
    $webdam_info = $this->extensionList->getExtensionInfo('webdam');
    $webdam_version = !empty($webdam_info['version']) ? $webdam_info['version'] : 'n/a';

    $headers = [
      'Accept' => 'application/json',
      'Authorization' => 'Bearer ' . $this->getToken(),
      'Content-Type' => 'application/json',
      'X-Webdam-Integration' => "Drupal/webdam: $webdam_version; $base_url",
    ];

    // We derive the id from the databaseId by base64 encoding it.
    $post = '{
    "query": "\n        fragment AddMediaAsset on Asset {\n            \n    id\n    name\n    description\n    databaseId\n    createdAt\n    originalUrl\n    publishedAt\n    tags\n    width\n    height\n    type\n    updatedAt\n    url\n    metaproperties {\n      nodes {\n        name\n        type\n        options {\n          name\n          displayLabel\n        }\n      }\n    }\n    textMetaproperties {\n      name\n      value\n    }\n    derivatives {\n      thumbnail\n      webImage\n    }\n    ... on Video {\n      previewUrls\n    }\n\n        }\n\n        query getAssetById($id: ID!) {\n            node(id: $id) {\n                __typename\n                id\n                ...on Asset {\n                    ...AddMediaAsset\n                    files\n                }\n            }\n        }",
    "variables": {
        "id": "' . base64_encode('(Asset_id ' . $id . ')') . '"
      }
    }';

    $response = $this->httpClient->post($this->webdamSettings->get('account_domain') . '/graphql', [
      'headers' => $headers,
      'body' => $post,
    ]);

    if ($response->getStatusCode() == 200) {
      $decoded_data = json_decode((string) $response->getBody(), TRUE);
      if (!isset($decoded_data['data']['node'])) {
        return [];
      }

      return $decoded_data['data']['node'];
    }
    else {
      return [];
    }
  }

}

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

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