6 use Procrastinator\Result;
7 use FileFetcher\FileFetcher;
8 use Dkan\Datastore\Resource as R;
9 use Drupal\Core\Entity\EntityRepository;
10 use Drupal\Core\File\FileSystem;
11 use Drupal\node\NodeInterface;
20 private $entityRepository;
22 private $jobStoreFactory;
29 EntityRepository $entityRepository,
30 FileSystem $fileSystem,
34 $this->entityRepository = $entityRepository;
35 $this->fileSystem = $fileSystem;
36 $this->jobStoreFactory = $jobStoreFactory;
50 public function get($useFileFetcher = FALSE, $runFileFetcher = TRUE): ?R {
51 $node = $this->entityRepository->loadEntityByUuid(
'node', $this->uuid);
56 if ($useFileFetcher == TRUE) {
57 return $this->getResourceFromFileFetcher($node, $runFileFetcher);
60 return new R($node->id(), $this->getResourceFilePathFromNode($node), $this->getMimeType($node));
72 public function remove() {
74 $filePath = $fileFetcher->getStateProperty(
'destination');
75 if (file_exists($filePath)) {
78 $this->jobStoreFactory->getInstance(FileFetcher::class)->remove($this->uuid);
86 return isset($fileFetcher) ? $fileFetcher->getResult() :
new Result();
95 $fileFetcher = FileFetcher::get($this->uuid, $this->jobStoreFactory->getInstance(FileFetcher::class), [
96 'filePath' => $filePath,
97 'temporaryDirectory' => $tmpDirectory,
99 $fileFetcher->setTimeLimit(self::DEFAULT_TIMELIMIT);
108 $node = $this->entityRepository->loadEntityByUuid(
'node', $this->uuid);
111 throw new \Exception(
"No node found for uuid {$this->uuid}");
114 $filePath = $this->getResourceFilePathFromNode($node);
116 $tmpDirectory = $this->fileSystem->realpath(
"public://") .
"/dkan-tmp";
117 $this->fileSystem->prepareDirectory($tmpDirectory, FileSystem::CREATE_DIRECTORY | FileSystem::MODIFY_PERMISSIONS);
134 private function getResourceFilePathFromNode(NodeInterface $node): string {
136 $meta = $node->get(
'field_json_metadata')->getString();
139 throw new \Exception(
"Entity for {$node->uuid()} does not have required field `field_json_metadata`.");
142 $metadata = json_decode($meta);
144 if (!($metadata instanceof \stdClass)) {
145 throw new \Exception(
"Invalid metadata information or missing file information.");
148 if (isset($metadata->data->downloadURL)) {
149 return $metadata->data->downloadURL;
152 throw new \Exception(
"Invalid metadata information or missing file information.");
158 private function getResourceFromFileFetcher($node, $runFileFetcher) {
161 if ($runFileFetcher) {
165 if ($fileFetcher->getResult()->getStatus() != Result::DONE) {
169 $json = $fileFetcher->getResult()->getData();
170 $fileData = json_decode($json);
171 return new R($node->id(), $fileData->destination, $this->getMimeType($node));
183 private function getMimeType(NodeInterface $node) : ?string {
184 $metadata = json_decode($node->get(
'field_json_metadata')->getString());
185 return $metadata->data->mediaType ?? NULL;