feat: Modifica mopdulo di estrazione immagini

Modifica modulo di estrazione immagine per evitare i temp
This commit is contained in:
luca 2025-11-07 17:09:20 +01:00
parent 31f89c3713
commit b2d9bbbf75
4 changed files with 70 additions and 25 deletions

View File

@ -39,7 +39,7 @@ services:
# volume (which is what we're creating here) will be initialized with the
# existing content of the image at the same location
- /app/public/sites
- ./web/sites/default/files:/app/public/sites/default/files
- d4science_files:/app/public/sites/default/files
restart: unless-stopped
db:
@ -55,3 +55,5 @@ services:
MYSQL_PASSWORD: "NDyJ4.pixFnuF"
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
restart: unless-stopped
volumes:
d4science_files:

View File

@ -4,6 +4,7 @@ use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\file\Entity\File;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\File\FileSystemInterface;
/**
@ -153,36 +154,78 @@ function create_vre_node(array $vre, Node $gateway_node) {
* @return \Drupal\file\Entity\File|null
* L'entità File creata, o NULL se il download fallisce.
*/
function download_and_save_image($url) {
/**
* Ritorna SEMPRE la stessa File entity per uno stesso img_id.
* Se $refreshContents = TRUE, riscarica e sovrascrive il file su disco.
*/
function download_and_save_image(string $url, bool $refreshContents = FALSE): ?File {
try {
$client = \Drupal::httpClient();
$response = $client->get($url, ['stream' => TRUE]);
// 1) Estrai img_id (chiave stabile)
parse_str(parse_url($url, PHP_URL_QUERY) ?: '', $q);
$img_id = $q['img_id'] ?? NULL;
if (!$img_id) {
\Drupal::logger('d4s_custom')->warning('img_id assente: @url', ['@url' => $url]);
return NULL;
}
if ($response->getStatusCode() === 200) {
parse_str(parse_url($url, PHP_URL_QUERY), $query_params);
// 2) Dir e destinazione con NOME STABILE
$dir = 'public://vre_images';
$fs = \Drupal::service('file_system');
$fs->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY);
$img_id = $query_params['img_id'] ?? 'unknown';
$t = $query_params['t'] ?? 'unknown';
// NB: scegli un'estensione e tienila costante (png di default)
$destination = "$dir/vre_{$img_id}.png";
// Genera il nome unico del file
$file_name = 'vre_' . $img_id . '_' . $t;
// 3) Se ESISTE già una File entity con quell'URI -> RIUSA
$storage = \Drupal::entityTypeManager()->getStorage('file');
$existing = $storage->loadByProperties(['uri' => $destination]);
if ($existing) {
/** @var \Drupal\file\Entity\File $file */
$file = reset($existing);
// Percorso temporaneo
$temp_file_path = 'public://temp_' . $file_name . '.png';
$file_contents = $response->getBody()->getContents();
file_put_contents($temp_file_path, $file_contents);
$file = File::create([
'uri' => $temp_file_path,
]);
$file->setPermanent();
$file->save();
if ($refreshContents) {
// Sovrascrivi i bytes su disco, mantenendo la STESSA entity.
$client = \Drupal::httpClient();
$resp = $client->get($url, ['timeout' => 10, 'connect_timeout' => 5]);
if ($resp->getStatusCode() === 200) {
$data = (string) $resp->getBody();
// Sovrascrive a disco (nessuna nuova entity):
$fs->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE);
}
}
// Assicurati permanente e salvato
if ($file->isTemporary()) {
$file->setPermanent()->save();
}
return $file;
}
} catch (\Exception $e) {
\Drupal::logger('d4s_custom')->error('Errore nel download dell\'immagine: @message', ['@message' => $e->getMessage()]);
// 4) NON esiste: scarica e CREA una nuova File entity UNA SOLA VOLTA
$client = \Drupal::httpClient();
$response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 5]);
if ($response->getStatusCode() !== 200) {
\Drupal::logger('d4s_custom')->warning('HTTP @code per @url', ['@code' => $response->getStatusCode(), '@url' => $url]);
return NULL;
}
$data = (string) $response->getBody();
/** @var \Drupal\file\FileRepositoryInterface $repo */
$repo = \Drupal::service('file.repository');
// Qui CREA lentity (solo la prima volta) e scrive su disco:
$file = $repo->writeData($data, $destination, FileSystemInterface::EXISTS_REPLACE);
if (!$file instanceof File) {
\Drupal::logger('d4s_custom')->error('Impossibile creare File entity per @dest', ['@dest' => $destination]);
return NULL;
}
$file->setPermanent();
$file->save();
return $file;
} catch (\Throwable $e) {
\Drupal::logger('d4s_custom')->error('Errore download immagine: @m', ['@m' => $e->getMessage()]);
return NULL;
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long