1
0

PreviewManager.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author John Molakvoæ <skjnldsv@protonmail.com>
  8. * @author Julius Härtl <jus@bitgrid.net>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Olivier Paroz <github@oparoz.com>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Sebastian Steinmetz <462714+steiny2k@users.noreply.github.com>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC;
  32. use OC\AppFramework\Bootstrap\Coordinator;
  33. use OC\Preview\Generator;
  34. use OC\Preview\GeneratorHelper;
  35. use OC\Preview\IMagickSupport;
  36. use OCP\AppFramework\QueryException;
  37. use OCP\EventDispatcher\IEventDispatcher;
  38. use OCP\Files\File;
  39. use OCP\Files\IAppData;
  40. use OCP\Files\IRootFolder;
  41. use OCP\Files\NotFoundException;
  42. use OCP\Files\SimpleFS\ISimpleFile;
  43. use OCP\IBinaryFinder;
  44. use OCP\IConfig;
  45. use OCP\IPreview;
  46. use OCP\IServerContainer;
  47. use OCP\Preview\IProviderV2;
  48. use function array_key_exists;
  49. class PreviewManager implements IPreview {
  50. protected IConfig $config;
  51. protected IRootFolder $rootFolder;
  52. protected IAppData $appData;
  53. protected IEventDispatcher $eventDispatcher;
  54. private ?Generator $generator = null;
  55. private GeneratorHelper $helper;
  56. protected bool $providerListDirty = false;
  57. protected bool $registeredCoreProviders = false;
  58. protected array $providers = [];
  59. /** @var array mime type => support status */
  60. protected array $mimeTypeSupportMap = [];
  61. protected ?array $defaultProviders = null;
  62. protected ?string $userId;
  63. private Coordinator $bootstrapCoordinator;
  64. /**
  65. * Hash map (without value) of loaded bootstrap providers
  66. * @psalm-var array<string, null>
  67. */
  68. private array $loadedBootstrapProviders = [];
  69. private IServerContainer $container;
  70. private IBinaryFinder $binaryFinder;
  71. private IMagickSupport $imagickSupport;
  72. private bool $enablePreviews;
  73. public function __construct(
  74. IConfig $config,
  75. IRootFolder $rootFolder,
  76. IAppData $appData,
  77. IEventDispatcher $eventDispatcher,
  78. GeneratorHelper $helper,
  79. ?string $userId,
  80. Coordinator $bootstrapCoordinator,
  81. IServerContainer $container,
  82. IBinaryFinder $binaryFinder,
  83. IMagickSupport $imagickSupport
  84. ) {
  85. $this->config = $config;
  86. $this->rootFolder = $rootFolder;
  87. $this->appData = $appData;
  88. $this->eventDispatcher = $eventDispatcher;
  89. $this->helper = $helper;
  90. $this->userId = $userId;
  91. $this->bootstrapCoordinator = $bootstrapCoordinator;
  92. $this->container = $container;
  93. $this->binaryFinder = $binaryFinder;
  94. $this->imagickSupport = $imagickSupport;
  95. $this->enablePreviews = $config->getSystemValueBool('enable_previews', true);
  96. }
  97. /**
  98. * In order to improve lazy loading a closure can be registered which will be
  99. * called in case preview providers are actually requested
  100. *
  101. * $callable has to return an instance of \OCP\Preview\IProvider or \OCP\Preview\IProviderV2
  102. *
  103. * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
  104. * @param \Closure $callable
  105. * @return void
  106. */
  107. public function registerProvider($mimeTypeRegex, \Closure $callable): void {
  108. if (!$this->enablePreviews) {
  109. return;
  110. }
  111. if (!isset($this->providers[$mimeTypeRegex])) {
  112. $this->providers[$mimeTypeRegex] = [];
  113. }
  114. $this->providers[$mimeTypeRegex][] = $callable;
  115. $this->providerListDirty = true;
  116. }
  117. /**
  118. * Get all providers
  119. */
  120. public function getProviders(): array {
  121. if (!$this->enablePreviews) {
  122. return [];
  123. }
  124. $this->registerCoreProviders();
  125. $this->registerBootstrapProviders();
  126. if ($this->providerListDirty) {
  127. $keys = array_map('strlen', array_keys($this->providers));
  128. array_multisort($keys, SORT_DESC, $this->providers);
  129. $this->providerListDirty = false;
  130. }
  131. return $this->providers;
  132. }
  133. /**
  134. * Does the manager have any providers
  135. */
  136. public function hasProviders(): bool {
  137. $this->registerCoreProviders();
  138. return !empty($this->providers);
  139. }
  140. private function getGenerator(): Generator {
  141. if ($this->generator === null) {
  142. $this->generator = new Generator(
  143. $this->config,
  144. $this,
  145. $this->appData,
  146. new GeneratorHelper(
  147. $this->rootFolder,
  148. $this->config
  149. ),
  150. $this->eventDispatcher
  151. );
  152. }
  153. return $this->generator;
  154. }
  155. /**
  156. * Returns a preview of a file
  157. *
  158. * The cache is searched first and if nothing usable was found then a preview is
  159. * generated by one of the providers
  160. *
  161. * @param File $file
  162. * @param int $width
  163. * @param int $height
  164. * @param bool $crop
  165. * @param string $mode
  166. * @param string $mimeType
  167. * @return ISimpleFile
  168. * @throws NotFoundException
  169. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  170. * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
  171. */
  172. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  173. $this->throwIfPreviewsDisabled();
  174. $previewConcurrency = $this->getGenerator()->getNumConcurrentPreviews('preview_concurrency_all');
  175. $sem = Generator::guardWithSemaphore(Generator::SEMAPHORE_ID_ALL, $previewConcurrency);
  176. try {
  177. $preview = $this->getGenerator()->getPreview($file, $width, $height, $crop, $mode, $mimeType);
  178. } finally {
  179. Generator::unguardWithSemaphore($sem);
  180. }
  181. return $preview;
  182. }
  183. /**
  184. * Generates previews of a file
  185. *
  186. * @param File $file
  187. * @param array $specifications
  188. * @param string $mimeType
  189. * @return ISimpleFile the last preview that was generated
  190. * @throws NotFoundException
  191. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  192. * @since 19.0.0
  193. */
  194. public function generatePreviews(File $file, array $specifications, $mimeType = null) {
  195. $this->throwIfPreviewsDisabled();
  196. return $this->getGenerator()->generatePreviews($file, $specifications, $mimeType);
  197. }
  198. /**
  199. * returns true if the passed mime type is supported
  200. *
  201. * @param string $mimeType
  202. * @return boolean
  203. */
  204. public function isMimeSupported($mimeType = '*') {
  205. if (!$this->enablePreviews) {
  206. return false;
  207. }
  208. if (isset($this->mimeTypeSupportMap[$mimeType])) {
  209. return $this->mimeTypeSupportMap[$mimeType];
  210. }
  211. $this->registerCoreProviders();
  212. $this->registerBootstrapProviders();
  213. $providerMimeTypes = array_keys($this->providers);
  214. foreach ($providerMimeTypes as $supportedMimeType) {
  215. if (preg_match($supportedMimeType, $mimeType)) {
  216. $this->mimeTypeSupportMap[$mimeType] = true;
  217. return true;
  218. }
  219. }
  220. $this->mimeTypeSupportMap[$mimeType] = false;
  221. return false;
  222. }
  223. /**
  224. * Check if a preview can be generated for a file
  225. */
  226. public function isAvailable(\OCP\Files\FileInfo $file): bool {
  227. if (!$this->enablePreviews) {
  228. return false;
  229. }
  230. $this->registerCoreProviders();
  231. if (!$this->isMimeSupported($file->getMimetype())) {
  232. return false;
  233. }
  234. $mount = $file->getMountPoint();
  235. if ($mount and !$mount->getOption('previews', true)) {
  236. return false;
  237. }
  238. foreach ($this->providers as $supportedMimeType => $providers) {
  239. if (preg_match($supportedMimeType, $file->getMimetype())) {
  240. foreach ($providers as $providerClosure) {
  241. $provider = $this->helper->getProvider($providerClosure);
  242. if (!($provider instanceof IProviderV2)) {
  243. continue;
  244. }
  245. if ($provider->isAvailable($file)) {
  246. return true;
  247. }
  248. }
  249. }
  250. }
  251. return false;
  252. }
  253. /**
  254. * List of enabled default providers
  255. *
  256. * The following providers are enabled by default:
  257. * - OC\Preview\PNG
  258. * - OC\Preview\JPEG
  259. * - OC\Preview\GIF
  260. * - OC\Preview\BMP
  261. * - OC\Preview\XBitmap
  262. * - OC\Preview\MarkDown
  263. * - OC\Preview\MP3
  264. * - OC\Preview\TXT
  265. *
  266. * The following providers are disabled by default due to performance or privacy concerns:
  267. * - OC\Preview\Font
  268. * - OC\Preview\HEIC
  269. * - OC\Preview\Illustrator
  270. * - OC\Preview\Movie
  271. * - OC\Preview\MSOfficeDoc
  272. * - OC\Preview\MSOffice2003
  273. * - OC\Preview\MSOffice2007
  274. * - OC\Preview\OpenDocument
  275. * - OC\Preview\PDF
  276. * - OC\Preview\Photoshop
  277. * - OC\Preview\Postscript
  278. * - OC\Preview\StarOffice
  279. * - OC\Preview\SVG
  280. * - OC\Preview\TIFF
  281. *
  282. * @return array
  283. */
  284. protected function getEnabledDefaultProvider() {
  285. if ($this->defaultProviders !== null) {
  286. return $this->defaultProviders;
  287. }
  288. $imageProviders = [
  289. Preview\PNG::class,
  290. Preview\JPEG::class,
  291. Preview\GIF::class,
  292. Preview\BMP::class,
  293. Preview\XBitmap::class,
  294. Preview\Krita::class,
  295. Preview\WebP::class,
  296. ];
  297. $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([
  298. Preview\MarkDown::class,
  299. Preview\MP3::class,
  300. Preview\TXT::class,
  301. Preview\OpenDocument::class,
  302. ], $imageProviders));
  303. if (in_array(Preview\Image::class, $this->defaultProviders)) {
  304. $this->defaultProviders = array_merge($this->defaultProviders, $imageProviders);
  305. }
  306. $this->defaultProviders = array_unique($this->defaultProviders);
  307. return $this->defaultProviders;
  308. }
  309. /**
  310. * Register the default providers (if enabled)
  311. *
  312. * @param string $class
  313. * @param string $mimeType
  314. */
  315. protected function registerCoreProvider($class, $mimeType, $options = []) {
  316. if (in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  317. $this->registerProvider($mimeType, function () use ($class, $options) {
  318. return new $class($options);
  319. });
  320. }
  321. }
  322. /**
  323. * Register the default providers (if enabled)
  324. */
  325. protected function registerCoreProviders() {
  326. if ($this->registeredCoreProviders) {
  327. return;
  328. }
  329. $this->registeredCoreProviders = true;
  330. $this->registerCoreProvider(Preview\TXT::class, '/text\/plain/');
  331. $this->registerCoreProvider(Preview\MarkDown::class, '/text\/(x-)?markdown/');
  332. $this->registerCoreProvider(Preview\PNG::class, '/image\/png/');
  333. $this->registerCoreProvider(Preview\JPEG::class, '/image\/jpeg/');
  334. $this->registerCoreProvider(Preview\GIF::class, '/image\/gif/');
  335. $this->registerCoreProvider(Preview\BMP::class, '/image\/bmp/');
  336. $this->registerCoreProvider(Preview\XBitmap::class, '/image\/x-xbitmap/');
  337. $this->registerCoreProvider(Preview\WebP::class, '/image\/webp/');
  338. $this->registerCoreProvider(Preview\Krita::class, '/application\/x-krita/');
  339. $this->registerCoreProvider(Preview\MP3::class, '/audio\/mpeg/');
  340. $this->registerCoreProvider(Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/');
  341. $this->registerCoreProvider(Preview\Imaginary::class, Preview\Imaginary::supportedMimeTypes());
  342. // SVG and Bitmap require imagick
  343. if ($this->imagickSupport->hasExtension()) {
  344. $imagickProviders = [
  345. 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => Preview\SVG::class],
  346. 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => Preview\TIFF::class],
  347. 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => Preview\PDF::class],
  348. 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Preview\Illustrator::class],
  349. 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Preview\Photoshop::class],
  350. 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Preview\Postscript::class],
  351. 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Preview\Font::class],
  352. 'HEIC' => ['mimetype' => '/image\/(x-)?hei(f|c)/', 'class' => Preview\HEIC::class],
  353. 'TGA' => ['mimetype' => '/image\/(x-)?t(ar)?ga/', 'class' => Preview\TGA::class],
  354. 'SGI' => ['mimetype' => '/image\/(x-)?sgi/', 'class' => Preview\SGI::class],
  355. ];
  356. foreach ($imagickProviders as $queryFormat => $provider) {
  357. $class = $provider['class'];
  358. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  359. continue;
  360. }
  361. if ($this->imagickSupport->supportsFormat($queryFormat)) {
  362. $this->registerCoreProvider($class, $provider['mimetype']);
  363. }
  364. }
  365. }
  366. $this->registerCoreProvidersOffice();
  367. // Video requires avconv or ffmpeg
  368. if (in_array(Preview\Movie::class, $this->getEnabledDefaultProvider())) {
  369. $movieBinary = $this->config->getSystemValue('preview_ffmpeg_path', null);
  370. if (!is_string($movieBinary)) {
  371. $movieBinary = $this->binaryFinder->findBinaryPath('avconv');
  372. if (!is_string($movieBinary)) {
  373. $movieBinary = $this->binaryFinder->findBinaryPath('ffmpeg');
  374. }
  375. }
  376. if (is_string($movieBinary)) {
  377. $this->registerCoreProvider(Preview\Movie::class, '/video\/.*/', ["movieBinary" => $movieBinary]);
  378. }
  379. }
  380. }
  381. private function registerCoreProvidersOffice(): void {
  382. $officeProviders = [
  383. ['mimetype' => '/application\/msword/', 'class' => Preview\MSOfficeDoc::class],
  384. ['mimetype' => '/application\/vnd.ms-.*/', 'class' => Preview\MSOffice2003::class],
  385. ['mimetype' => '/application\/vnd.openxmlformats-officedocument.*/', 'class' => Preview\MSOffice2007::class],
  386. ['mimetype' => '/application\/vnd.oasis.opendocument.*/', 'class' => Preview\OpenDocument::class],
  387. ['mimetype' => '/application\/vnd.sun.xml.*/', 'class' => Preview\StarOffice::class],
  388. ['mimetype' => '/image\/emf/', 'class' => Preview\EMF::class],
  389. ];
  390. $findBinary = true;
  391. $officeBinary = false;
  392. foreach ($officeProviders as $provider) {
  393. $class = $provider['class'];
  394. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  395. continue;
  396. }
  397. if ($findBinary) {
  398. // Office requires openoffice or libreoffice
  399. $officeBinary = $this->config->getSystemValue('preview_libreoffice_path', false);
  400. if ($officeBinary === false) {
  401. $officeBinary = $this->binaryFinder->findBinaryPath('libreoffice');
  402. }
  403. if ($officeBinary === false) {
  404. $officeBinary = $this->binaryFinder->findBinaryPath('openoffice');
  405. }
  406. $findBinary = false;
  407. }
  408. if ($officeBinary) {
  409. $this->registerCoreProvider($class, $provider['mimetype'], ['officeBinary' => $officeBinary]);
  410. }
  411. }
  412. }
  413. private function registerBootstrapProviders(): void {
  414. $context = $this->bootstrapCoordinator->getRegistrationContext();
  415. if ($context === null) {
  416. // Just ignore for now
  417. return;
  418. }
  419. $providers = $context->getPreviewProviders();
  420. foreach ($providers as $provider) {
  421. $key = $provider->getMimeTypeRegex() . '-' . $provider->getService();
  422. if (array_key_exists($key, $this->loadedBootstrapProviders)) {
  423. // Do not load the provider more than once
  424. continue;
  425. }
  426. $this->loadedBootstrapProviders[$key] = null;
  427. $this->registerProvider($provider->getMimeTypeRegex(), function () use ($provider) {
  428. try {
  429. return $this->container->get($provider->getService());
  430. } catch (QueryException $e) {
  431. return null;
  432. }
  433. });
  434. }
  435. }
  436. /**
  437. * @throws NotFoundException if preview generation is disabled
  438. */
  439. private function throwIfPreviewsDisabled(): void {
  440. if (!$this->enablePreviews) {
  441. throw new NotFoundException('Previews disabled');
  442. }
  443. }
  444. }