Generator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, Roeland Jago Douma <roeland@famdouma.nl>
  4. *
  5. * @author Morris Jobke <hey@morrisjobke.de>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OC\Preview;
  26. use OCP\Files\File;
  27. use OCP\Files\IAppData;
  28. use OCP\Files\NotFoundException;
  29. use OCP\Files\NotPermittedException;
  30. use OCP\Files\SimpleFS\ISimpleFile;
  31. use OCP\Files\SimpleFS\ISimpleFolder;
  32. use OCP\IConfig;
  33. use OCP\IImage;
  34. use OCP\IPreview;
  35. use OCP\Preview\IProvider;
  36. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  37. use Symfony\Component\EventDispatcher\GenericEvent;
  38. class Generator {
  39. /** @var IPreview */
  40. private $previewManager;
  41. /** @var IConfig */
  42. private $config;
  43. /** @var IAppData */
  44. private $appData;
  45. /** @var GeneratorHelper */
  46. private $helper;
  47. /** @var EventDispatcherInterface */
  48. private $eventDispatcher;
  49. /**
  50. * @param IConfig $config
  51. * @param IPreview $previewManager
  52. * @param IAppData $appData
  53. * @param GeneratorHelper $helper
  54. * @param EventDispatcherInterface $eventDispatcher
  55. */
  56. public function __construct(
  57. IConfig $config,
  58. IPreview $previewManager,
  59. IAppData $appData,
  60. GeneratorHelper $helper,
  61. EventDispatcherInterface $eventDispatcher
  62. ) {
  63. $this->config = $config;
  64. $this->previewManager = $previewManager;
  65. $this->appData = $appData;
  66. $this->helper = $helper;
  67. $this->eventDispatcher = $eventDispatcher;
  68. }
  69. /**
  70. * Returns a preview of a file
  71. *
  72. * The cache is searched first and if nothing usable was found then a preview is
  73. * generated by one of the providers
  74. *
  75. * @param File $file
  76. * @param int $width
  77. * @param int $height
  78. * @param bool $crop
  79. * @param string $mode
  80. * @param string $mimeType
  81. * @return ISimpleFile
  82. * @throws NotFoundException
  83. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  84. */
  85. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  86. //Make sure that we can read the file
  87. if (!$file->isReadable()) {
  88. throw new NotFoundException('Cannot read file');
  89. }
  90. $this->eventDispatcher->dispatch(
  91. IPreview::EVENT,
  92. new GenericEvent($file,[
  93. 'width' => $width,
  94. 'height' => $height,
  95. 'crop' => $crop,
  96. 'mode' => $mode
  97. ])
  98. );
  99. if ($mimeType === null) {
  100. $mimeType = $file->getMimeType();
  101. }
  102. if (!$this->previewManager->isMimeSupported($mimeType)) {
  103. throw new NotFoundException();
  104. }
  105. $previewFolder = $this->getPreviewFolder($file);
  106. // Get the max preview and infer the max preview sizes from that
  107. $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType);
  108. if ($maxPreview->getSize() === 0) {
  109. $maxPreview->delete();
  110. throw new NotFoundException('Max preview size 0, invalid!');
  111. }
  112. list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview);
  113. // If both width and heigth are -1 we just want the max preview
  114. if ($width === -1 && $height === -1) {
  115. $width = $maxWidth;
  116. $height = $maxHeight;
  117. }
  118. // Calculate the preview size
  119. list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
  120. // No need to generate a preview that is just the max preview
  121. if ($width === $maxWidth && $height === $maxHeight) {
  122. return $maxPreview;
  123. }
  124. // Try to get a cached preview. Else generate (and store) one
  125. try {
  126. try {
  127. $preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType());
  128. } catch (NotFoundException $e) {
  129. $preview = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight);
  130. }
  131. } catch (\InvalidArgumentException $e) {
  132. throw new NotFoundException();
  133. }
  134. if ($preview->getSize() === 0) {
  135. $preview->delete();
  136. throw new NotFoundException('Cached preview size 0, invalid!');
  137. }
  138. return $preview;
  139. }
  140. /**
  141. * @param ISimpleFolder $previewFolder
  142. * @param File $file
  143. * @param string $mimeType
  144. * @return ISimpleFile
  145. * @throws NotFoundException
  146. */
  147. private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) {
  148. $nodes = $previewFolder->getDirectoryListing();
  149. foreach ($nodes as $node) {
  150. if (strpos($node->getName(), 'max')) {
  151. return $node;
  152. }
  153. }
  154. $previewProviders = $this->previewManager->getProviders();
  155. foreach ($previewProviders as $supportedMimeType => $providers) {
  156. if (!preg_match($supportedMimeType, $mimeType)) {
  157. continue;
  158. }
  159. foreach ($providers as $provider) {
  160. $provider = $this->helper->getProvider($provider);
  161. if (!($provider instanceof IProvider)) {
  162. continue;
  163. }
  164. if (!$provider->isAvailable($file)) {
  165. continue;
  166. }
  167. $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 4096);
  168. $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 4096);
  169. $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
  170. if (!($preview instanceof IImage)) {
  171. continue;
  172. }
  173. // Try to get the extention.
  174. try {
  175. $ext = $this->getExtention($preview->dataMimeType());
  176. } catch (\InvalidArgumentException $e) {
  177. // Just continue to the next iteration if this preview doesn't have a valid mimetype
  178. continue;
  179. }
  180. $path = (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
  181. try {
  182. $file = $previewFolder->newFile($path);
  183. $file->putContent($preview->data());
  184. } catch (NotPermittedException $e) {
  185. throw new NotFoundException();
  186. }
  187. return $file;
  188. }
  189. }
  190. throw new NotFoundException();
  191. }
  192. /**
  193. * @param ISimpleFile $file
  194. * @return int[]
  195. */
  196. private function getPreviewSize(ISimpleFile $file) {
  197. $size = explode('-', $file->getName());
  198. return [(int)$size[0], (int)$size[1]];
  199. }
  200. /**
  201. * @param int $width
  202. * @param int $height
  203. * @param bool $crop
  204. * @param string $mimeType
  205. * @return string
  206. */
  207. private function generatePath($width, $height, $crop, $mimeType) {
  208. $path = (string)$width . '-' . (string)$height;
  209. if ($crop) {
  210. $path .= '-crop';
  211. }
  212. $ext = $this->getExtention($mimeType);
  213. $path .= '.' . $ext;
  214. return $path;
  215. }
  216. /**
  217. * @param int $width
  218. * @param int $height
  219. * @param bool $crop
  220. * @param string $mode
  221. * @param int $maxWidth
  222. * @param int $maxHeight
  223. * @return int[]
  224. */
  225. private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
  226. /*
  227. * If we are not cropping we have to make sure the requested image
  228. * respects the aspect ratio of the original.
  229. */
  230. if (!$crop) {
  231. $ratio = $maxHeight / $maxWidth;
  232. if ($width === -1) {
  233. $width = $height / $ratio;
  234. }
  235. if ($height === -1) {
  236. $height = $width * $ratio;
  237. }
  238. $ratioH = $height / $maxHeight;
  239. $ratioW = $width / $maxWidth;
  240. /*
  241. * Fill means that the $height and $width are the max
  242. * Cover means min.
  243. */
  244. if ($mode === IPreview::MODE_FILL) {
  245. if ($ratioH > $ratioW) {
  246. $height = $width * $ratio;
  247. } else {
  248. $width = $height / $ratio;
  249. }
  250. } else if ($mode === IPreview::MODE_COVER) {
  251. if ($ratioH > $ratioW) {
  252. $width = $height / $ratio;
  253. } else {
  254. $height = $width * $ratio;
  255. }
  256. }
  257. }
  258. if ($height !== $maxHeight && $width !== $maxWidth) {
  259. /*
  260. * Scale to the nearest power of four
  261. */
  262. $pow4height = 4 ** ceil(log($height) / log(4));
  263. $pow4width = 4 ** ceil(log($width) / log(4));
  264. // Minimum size is 64
  265. $pow4height = max($pow4height, 64);
  266. $pow4width = max($pow4width, 64);
  267. $ratioH = $height / $pow4height;
  268. $ratioW = $width / $pow4width;
  269. if ($ratioH < $ratioW) {
  270. $width = $pow4width;
  271. $height /= $ratioW;
  272. } else {
  273. $height = $pow4height;
  274. $width /= $ratioH;
  275. }
  276. }
  277. /*
  278. * Make sure the requested height and width fall within the max
  279. * of the preview.
  280. */
  281. if ($height > $maxHeight) {
  282. $ratio = $height / $maxHeight;
  283. $height = $maxHeight;
  284. $width /= $ratio;
  285. }
  286. if ($width > $maxWidth) {
  287. $ratio = $width / $maxWidth;
  288. $width = $maxWidth;
  289. $height /= $ratio;
  290. }
  291. return [(int)round($width), (int)round($height)];
  292. }
  293. /**
  294. * @param ISimpleFolder $previewFolder
  295. * @param ISimpleFile $maxPreview
  296. * @param int $width
  297. * @param int $height
  298. * @param bool $crop
  299. * @param int $maxWidth
  300. * @param int $maxHeight
  301. * @return ISimpleFile
  302. * @throws NotFoundException
  303. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  304. */
  305. private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) {
  306. $preview = $this->helper->getImage($maxPreview);
  307. if (!$preview->valid()) {
  308. throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
  309. }
  310. if ($crop) {
  311. if ($height !== $preview->height() && $width !== $preview->width()) {
  312. //Resize
  313. $widthR = $preview->width() / $width;
  314. $heightR = $preview->height() / $height;
  315. if ($widthR > $heightR) {
  316. $scaleH = $height;
  317. $scaleW = $maxWidth / $heightR;
  318. } else {
  319. $scaleH = $maxHeight / $widthR;
  320. $scaleW = $width;
  321. }
  322. $preview->preciseResize((int)round($scaleW), (int)round($scaleH));
  323. }
  324. $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
  325. $cropY = 0;
  326. $preview->crop($cropX, $cropY, $width, $height);
  327. } else {
  328. $preview->resize(max($width, $height));
  329. }
  330. $path = $this->generatePath($width, $height, $crop, $preview->dataMimeType());
  331. try {
  332. $file = $previewFolder->newFile($path);
  333. $file->putContent($preview->data());
  334. } catch (NotPermittedException $e) {
  335. throw new NotFoundException();
  336. }
  337. return $file;
  338. }
  339. /**
  340. * @param ISimpleFolder $previewFolder
  341. * @param int $width
  342. * @param int $height
  343. * @param bool $crop
  344. * @param string $mimeType
  345. * @return ISimpleFile
  346. *
  347. * @throws NotFoundException
  348. */
  349. private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType) {
  350. $path = $this->generatePath($width, $height, $crop, $mimeType);
  351. return $previewFolder->getFile($path);
  352. }
  353. /**
  354. * Get the specific preview folder for this file
  355. *
  356. * @param File $file
  357. * @return ISimpleFolder
  358. */
  359. private function getPreviewFolder(File $file) {
  360. try {
  361. $folder = $this->appData->getFolder($file->getId());
  362. } catch (NotFoundException $e) {
  363. $folder = $this->appData->newFolder($file->getId());
  364. }
  365. return $folder;
  366. }
  367. /**
  368. * @param string $mimeType
  369. * @return null|string
  370. * @throws \InvalidArgumentException
  371. */
  372. private function getExtention($mimeType) {
  373. switch ($mimeType) {
  374. case 'image/png':
  375. return 'png';
  376. case 'image/jpeg':
  377. return 'jpg';
  378. case 'image/gif':
  379. return 'gif';
  380. default:
  381. throw new \InvalidArgumentException('Not a valid mimetype');
  382. }
  383. }
  384. }