1
0

Imaginary.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2020, Nextcloud, GmbH.
  4. *
  5. * @author Vincent Petry <vincent@nextcloud.com>
  6. * @author Carl Schwan <carl@carlschwan.eu>
  7. *
  8. * @license AGPL-3.0-or-later
  9. *
  10. * This code is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License, version 3,
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License, version 3,
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>
  21. *
  22. */
  23. namespace OC\Preview;
  24. use OCP\Files\File;
  25. use OCP\Http\Client\IClientService;
  26. use OCP\IConfig;
  27. use OCP\IImage;
  28. use OCP\Image;
  29. use OC\StreamImage;
  30. use Psr\Log\LoggerInterface;
  31. class Imaginary extends ProviderV2 {
  32. /** @var IConfig */
  33. private $config;
  34. /** @var IClientService */
  35. private $service;
  36. /** @var LoggerInterface */
  37. private $logger;
  38. public function __construct(array $config) {
  39. parent::__construct($config);
  40. $this->config = \OC::$server->get(IConfig::class);
  41. $this->service = \OC::$server->get(IClientService::class);
  42. $this->logger = \OC::$server->get(LoggerInterface::class);
  43. }
  44. /**
  45. * {@inheritDoc}
  46. */
  47. public function getMimeType(): string {
  48. return self::supportedMimeTypes();
  49. }
  50. public static function supportedMimeTypes(): string {
  51. return '/(image\/(bmp|x-bitmap|png|jpeg|gif|heic|heif|svg\+xml|tiff|webp)|application\/(pdf|illustrator))/';
  52. }
  53. public function getCroppedThumbnail(File $file, int $maxX, int $maxY, bool $crop): ?IImage {
  54. $maxSizeForImages = $this->config->getSystemValueInt('preview_max_filesize_image', 50);
  55. $size = $file->getSize();
  56. if ($maxSizeForImages !== -1 && $size > ($maxSizeForImages * 1024 * 1024)) {
  57. return null;
  58. }
  59. $imaginaryUrl = $this->config->getSystemValueString('preview_imaginary_url', 'invalid');
  60. if ($imaginaryUrl === 'invalid') {
  61. $this->logger->error('Imaginary preview provider is enabled, but no url is configured. Please provide the url of your imaginary server to the \'preview_imaginary_url\' config variable.');
  62. return null;
  63. }
  64. $imaginaryUrl = rtrim($imaginaryUrl, '/');
  65. // Object store
  66. $stream = $file->fopen('r');
  67. $httpClient = $this->service->newClient();
  68. $convert = false;
  69. $autorotate = true;
  70. switch ($file->getMimeType()) {
  71. case 'image/heic':
  72. // Autorotate seems to be broken for Heic so disable for that
  73. $autorotate = false;
  74. $mimeType = 'jpeg';
  75. break;
  76. case 'image/gif':
  77. case 'image/png':
  78. $mimeType = 'png';
  79. break;
  80. case 'image/svg+xml':
  81. case 'application/pdf':
  82. case 'application/illustrator':
  83. $convert = true;
  84. // Converted files do not need to be autorotated
  85. $autorotate = false;
  86. $mimeType = 'png';
  87. break;
  88. default:
  89. $mimeType = 'jpeg';
  90. }
  91. $preview_format = $this->config->getSystemValueString('preview_format', 'jpeg');
  92. switch ($preview_format) { // Change the format to the correct one
  93. case 'webp':
  94. $mimeType = 'webp';
  95. break;
  96. default:
  97. }
  98. $operations = [];
  99. if ($convert) {
  100. $operations[] = [
  101. 'operation' => 'convert',
  102. 'params' => [
  103. 'type' => $mimeType,
  104. ]
  105. ];
  106. } elseif ($autorotate) {
  107. $operations[] = [
  108. 'operation' => 'autorotate',
  109. ];
  110. }
  111. switch ($mimeType) {
  112. case 'jpeg':
  113. $quality = $this->config->getAppValue('preview', 'jpeg_quality', '80');
  114. break;
  115. case 'webp':
  116. $quality = $this->config->getAppValue('preview', 'webp_quality', '80');
  117. break;
  118. default:
  119. $quality = $this->config->getAppValue('preview', 'jpeg_quality', '80');
  120. }
  121. $operations[] = [
  122. 'operation' => ($crop ? 'smartcrop' : 'fit'),
  123. 'params' => [
  124. 'width' => $maxX,
  125. 'height' => $maxY,
  126. 'stripmeta' => 'true',
  127. 'type' => $mimeType,
  128. 'norotation' => 'true',
  129. 'quality' => $quality,
  130. ]
  131. ];
  132. try {
  133. $imaginaryKey = $this->config->getSystemValueString('preview_imaginary_key', '');
  134. $response = $httpClient->post(
  135. $imaginaryUrl . '/pipeline', [
  136. 'query' => ['operations' => json_encode($operations), 'key' => $imaginaryKey],
  137. 'stream' => true,
  138. 'content-type' => $file->getMimeType(),
  139. 'body' => $stream,
  140. 'nextcloud' => ['allow_local_address' => true],
  141. 'timeout' => 120,
  142. 'connect_timeout' => 3,
  143. ]);
  144. } catch (\Exception $e) {
  145. $this->logger->info('Imaginary preview generation failed: ' . $e->getMessage(), [
  146. 'exception' => $e,
  147. ]);
  148. return null;
  149. }
  150. if ($response->getStatusCode() !== 200) {
  151. $this->logger->info('Imaginary preview generation failed: ' . json_decode($response->getBody())['message']);
  152. return null;
  153. }
  154. // This is not optimal but previews are distorted if the wrong width and height values are
  155. // used. Both dimension headers are only sent when passing the option "-return-size" to
  156. // Imaginary.
  157. if ($response->getHeader('Image-Width') && $response->getHeader('Image-Height')) {
  158. $image = new StreamImage(
  159. $response->getBody(),
  160. $response->getHeader('Content-Type'),
  161. (int)$response->getHeader('Image-Width'),
  162. (int)$response->getHeader('Image-Height'),
  163. );
  164. } else {
  165. $image = new Image();
  166. $image->loadFromFileHandle($response->getBody());
  167. }
  168. return $image->valid() ? $image : null;
  169. }
  170. /**
  171. * {@inheritDoc}
  172. */
  173. public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
  174. return $this->getCroppedThumbnail($file, $maxX, $maxY, false);
  175. }
  176. }