geminiClient = $client; $this->jwtProvider = $jwt_auth; $this->mediaSource = $media_source; $this->guzzle = $guzzle; $this->logger = $logger; } /** * Lookup this entity's URI in the Gemini db and return the other URI. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to look for. * * @return string|null * Return the URI or null */ public function lookup(EntityInterface $entity) { // Exit early if the entity hasn't been saved yet. if ($entity->id() == NULL) { return NULL; } $is_media = $entity->getEntityTypeId() == 'media'; // Use the entity's uuid unless it's a media, // use its file's uuid instead. if ($is_media) { try { $file = $this->mediaSource->getSourceFile($entity); $uuid = $file->uuid(); } // If the media has no source file, exit early. catch (NotFoundHttpException $e) { return NULL; } } else { $uuid = $entity->uuid(); } // Look it up in Gemini. $token = "Bearer " . $this->jwtProvider->generateToken(); $urls = $this->geminiClient->getUrls($uuid, $token); // Exit early if there's no results from Gemini. if (empty($urls)) { return NULL; } // If it's not a media, just return the url from Gemini;. if (!$is_media) { return $urls['fedora']; } // If it's a media, perform a HEAD request against // the file in Fedora and get its 'describedy' link header. try { $head = $this->guzzle->head( $urls['fedora'], ['allow_redirects' => FALSE, 'headers' => ['Authorization' => $token]] ); $links = Psr7\parse_header($head->getHeader("Link")); foreach ($links as $link) { if ($link['rel'] == 'describedby') { return trim($link[0], '<>'); } } } catch (RequestException $e) { $this->logger->warn( "Error performing Gemini lookup for media. Fedora HEAD to @url returned @status => @message", [ '@url' => $urls['fedora'], '@status' => $e->getCode(), '@message' => $e->getMessage, ] ); return NULL; } // Return null if no link header is found. return NULL; } }