Problem/Motivation

It is difficult to understand how to retrieve external urls to files which are stored in the DAM in a programmatic way, either via Twig or PHP.

Some use cases:

  1. when using Linkit and Linkit Media Library in CKEditor5 - how can we get the full URL to the remote image?
  2. when trying to set a variable for use in twig, i.e. background_image or something

Steps to reproduce

  1. Install and configure the DAM
  2. Import some media items into Drupal
  3. Try to get a URL to the source file programmatically

Proposed resolution

TBD

Remaining tasks

TBD

Current Workaround

My current approach to handling this is to create a new service in Drupal that connects to the API. The method looks like this:

  public function getAssetDamUrl(string $asset_id, string $format = 'original'): string {
    $search_url = $this->getAssetLookupUrl($asset_id);
    $access_token = $this->settings->get('dam_access_key');
    $headers = [
      'Authorization' => "Bearer " . $access_token,
    ];
    try {
      $request = $this->httpClient->request('GET', $search_url, ['headers' => $headers]);
      $item_data = json_decode($request->getBody()->getContents(), TRUE);
      return $item_data['embeds'][$format]['url'] ?? "";
    }
    catch (RequestException $e) {
      return "";
    }
  }

But I wonder if:

  1. Is it worthwhile to add a new service into Acquia Dam for this purpose?
  2. Is there a better/more efficient way?

Issue fork acquia_dam-3530888

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

dan612 created an issue. See original summary.

rajeshreeputra’s picture

Try using getAsset($asset_id) method.

$asset_data = \Drupal::service('acquia_dam.client.factory')->getSiteClient()->getAsset($asset_id);
if ($asset_data) {
  $asset_url = $asset_data['embeds']['original'];
}
rajeshreeputra’s picture

You can also try

    /** @var \Drupal\acquia_dam\Plugin\media\Source\Asset $source */
    $source = $media->getSource();
    $embed_codes = $source->getMetadata($media, 'embeds');
    $url = $embed_codes['original']['url'];
dan612’s picture

Thank you! these are working for me. Much more streamlined 😁.

Would it be worth adding these to the README in a ## DEVELOPER USAGE section?

rajeshreeputra’s picture

You can also use a stream wrapper if both asset_id and version_id are available.
\Drupal::service('stream_wrapper.acquia_dam')->getViaUri('acquia-dam://<asset_id>/<version_id>')->getExternalUrl();

rajeshreeputra’s picture

Status: Active » Needs work

Adding this to README sound good, let's make it.

dan612’s picture

Status: Needs work » Needs review

Added some info to the README!