From 3ebe1a93de8d8b8bca1780d4a9b82214abfe417e Mon Sep 17 00:00:00 2001 From: Jordy Ubink Date: Sat, 20 Sep 2025 10:55:28 +0200 Subject: [PATCH] Get the image file type from the response content type When using the external lookup tool, the file extention in the URL is used for the name of the downloaded image. However, some API's do not use file types in the resource name. If that is the case, the Content-Type of the request will now be used to define the file extention. --- services/StockService.php | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/services/StockService.php b/services/StockService.php index aba6ef2b..db61459a 100644 --- a/services/StockService.php +++ b/services/StockService.php @@ -630,7 +630,36 @@ class StockService extends BaseService { $webClient = new Client(); $response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . $this->getApplicationService()->GetInstalledVersion()->Version . ' (https://grocy.info)']]); - $fileName = $pluginOutput['__barcode'] . '.' . pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); + + $fileType = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); + + // Some API's don't use the filetype in the URL. In this case, use the content type in the headers. + if ($fileType == '') { + + // If the Content-Type does not exist, do not save the image. + if (!$response->hasHeader('Content-Type')) { + throw new \Exception('Image lookup response for product "' . $pluginOutput['name'] . '" does not have a Content-Type.'); + } + + $contentType = $response->getHeader('Content-Type')[0]; // e.g. image/jpeg + $contentTypeSplit = explode('/', $contentType); + + // If the Content-Type is not an image, do not save the image. + if ($contentTypeSplit[0] != 'image') { + throw new \Exception('Image lookup response for product "' . $pluginOutput['name'] . '" does not have a Content-Type image/xxxx.'); + } + + if ($contentType == 'image/svg+xml') { + // SVG needs special handling + $fileType = 'svg'; + } else { + // Use the content type as file extension + $fileType = $contentTypeSplit[1]; // e.g. jpeg + } + + } + + $fileName = $pluginOutput['__barcode'] . '.' . $fileType; file_put_contents($this->getFilesService()->GetFilePath('productpictures', $fileName), $response->getBody()); $productData['picture_file_name'] = $fileName; } @@ -1794,4 +1823,4 @@ class StockService extends BaseService $shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch(); return $shoppingListRow !== null; } -} +} \ No newline at end of file