diff --git a/.changelog/current/2323-use-curl-for-downloads.md b/.changelog/current/2323-use-curl-for-downloads.md new file mode 100644 index 000000000..1e5eb8c4b --- /dev/null +++ b/.changelog/current/2323-use-curl-for-downloads.md @@ -0,0 +1,3 @@ +# Maintenance + +- Use cURL for import of recipe images as well diff --git a/lib/Service/RecipeService.php b/lib/Service/RecipeService.php index 1d2e43954..442947e25 100755 --- a/lib/Service/RecipeService.php +++ b/lib/Service/RecipeService.php @@ -9,6 +9,7 @@ use OCA\Cookbook\Exception\NoRecipeNameGivenException; use OCA\Cookbook\Exception\RecipeExistsException; use OCA\Cookbook\Exception\UserFolderNotWritableException; +use OCA\Cookbook\Helper\DownloadHelper; use OCA\Cookbook\Helper\FileSystem\RecipeNameHelper; use OCA\Cookbook\Helper\Filter\JSON\JSONFilter; use OCA\Cookbook\Helper\ImageService\ImageSize; @@ -65,6 +66,9 @@ class RecipeService { /** @var JSONFilter */ private $jsonFilter; + /** @var DownloadHelper */ + private $downloadHelper; + public function __construct( ?string $UserId, IRootFolder $root, @@ -77,7 +81,8 @@ public function __construct( LoggerInterface $logger, HtmlDownloadService $downloadService, RecipeExtractionService $extractionService, - JSONFilter $jsonFilter + JSONFilter $jsonFilter, + DownloadHelper $downloadHelper, ) { $this->user_id = $UserId; $this->root = $root; @@ -91,6 +96,7 @@ public function __construct( $this->htmlDownloadService = $downloadService; $this->recipeExtractionService = $extractionService; $this->jsonFilter = $jsonFilter; + $this->downloadHelper = $downloadHelper; } /** @@ -275,7 +281,12 @@ public function addRecipe($json, $importedHtml = null) { if (strpos($json['image'], 'http') === 0) { // The image is a URL $json['image'] = str_replace(' ', '%20', $json['image']); - $full_image_data = file_get_contents($json['image']); + try { + $full_image_data = $this->downloadImage($json['image']); + } catch (Exception $ex) { + $this->logger->warning('Failed to download an image using curl. Falling back to PHP default behavior.'); + $full_image_data = file_get_contents($json['image']); + } } else { // The image is a local path @@ -309,6 +320,15 @@ public function addRecipe($json, $importedHtml = null) { return $recipe_file; } + private function downloadImage(string $url) { + $this->downloadHelper->downloadFile($url); + $status = $this->downloadHelper->getStatus(); + if($status >= 400) { + throw new Exception($this->il10n->t('Cannot download image using curl')); + } + return $this->downloadHelper->getContent(); + } + /** * Download a recipe from a url and store it in the files *