1
0

Imaginary.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. $operations = [];
  92. if ($convert) {
  93. $operations[] = [
  94. 'operation' => 'convert',
  95. 'params' => [
  96. 'type' => $mimeType,
  97. ]
  98. ];
  99. } elseif ($autorotate) {
  100. $operations[] = [
  101. 'operation' => 'autorotate',
  102. ];
  103. }
  104. $quality = $this->config->getAppValue('preview', 'jpeg_quality', '80');
  105. $operations[] = [
  106. 'operation' => ($crop ? 'smartcrop' : 'fit'),
  107. 'params' => [
  108. 'width' => $maxX,
  109. 'height' => $maxY,
  110. 'stripmeta' => 'true',
  111. 'type' => $mimeType,
  112. 'norotation' => 'true',
  113. 'quality' => $quality,
  114. ]
  115. ];
  116. try {
  117. $imaginaryKey = $this->config->getSystemValueString('preview_imaginary_key', '');
  118. $response = $httpClient->post(
  119. $imaginaryUrl . '/pipeline', [
  120. 'query' => ['operations' => json_encode($operations), 'key' => $imaginaryKey],
  121. 'stream' => true,
  122. 'content-type' => $file->getMimeType(),
  123. 'body' => $stream,
  124. 'nextcloud' => ['allow_local_address' => true],
  125. 'timeout' => 120,
  126. 'connect_timeout' => 3,
  127. ]);
  128. } catch (\Exception $e) {
  129. $this->logger->error('Imaginary preview generation failed: ' . $e->getMessage(), [
  130. 'exception' => $e,
  131. ]);
  132. return null;
  133. }
  134. if ($response->getStatusCode() !== 200) {
  135. $this->logger->error('Imaginary preview generation failed: ' . json_decode($response->getBody())['message']);
  136. return null;
  137. }
  138. // This is not optimal but previews are distorted if the wrong width and height values are
  139. // used. Both dimension headers are only sent when passing the option "-return-size" to
  140. // Imaginary.
  141. if ($response->getHeader('Image-Width') && $response->getHeader('Image-Height')) {
  142. $image = new StreamImage(
  143. $response->getBody(),
  144. $response->getHeader('Content-Type'),
  145. (int)$response->getHeader('Image-Width'),
  146. (int)$response->getHeader('Image-Height'),
  147. );
  148. } else {
  149. $image = new Image();
  150. $image->loadFromFileHandle($response->getBody());
  151. }
  152. return $image->valid() ? $image : null;
  153. }
  154. /**
  155. * {@inheritDoc}
  156. */
  157. public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
  158. return $this->getCroppedThumbnail($file, $maxX, $maxY, false);
  159. }
  160. }