PreviewManager.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 OCP\AppFramework\QueryException;
  36. use OCP\EventDispatcher\IEventDispatcher;
  37. use OCP\Files\File;
  38. use OCP\Files\IAppData;
  39. use OCP\Files\IRootFolder;
  40. use OCP\Files\NotFoundException;
  41. use OCP\Files\SimpleFS\ISimpleFile;
  42. use OCP\IBinaryFinder;
  43. use OCP\IConfig;
  44. use OCP\IPreview;
  45. use OCP\IServerContainer;
  46. use OCP\Preview\IProviderV2;
  47. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  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. protected EventDispatcherInterface $legacyEventDispatcher;
  55. private ?Generator $generator = null;
  56. private GeneratorHelper $helper;
  57. protected bool $providerListDirty = false;
  58. protected bool $registeredCoreProviders = false;
  59. protected array $providers = [];
  60. /** @var array mime type => support status */
  61. protected array $mimeTypeSupportMap = [];
  62. protected ?array $defaultProviders = null;
  63. protected ?string $userId;
  64. private Coordinator $bootstrapCoordinator;
  65. /**
  66. * Hash map (without value) of loaded bootstrap providers
  67. * @psalm-var array<string, null>
  68. */
  69. private array $loadedBootstrapProviders = [];
  70. private IServerContainer $container;
  71. private IBinaryFinder $binaryFinder;
  72. public function __construct(
  73. IConfig $config,
  74. IRootFolder $rootFolder,
  75. IAppData $appData,
  76. IEventDispatcher $eventDispatcher,
  77. EventDispatcherInterface $legacyEventDispatcher,
  78. GeneratorHelper $helper,
  79. ?string $userId,
  80. Coordinator $bootstrapCoordinator,
  81. IServerContainer $container,
  82. IBinaryFinder $binaryFinder
  83. ) {
  84. $this->config = $config;
  85. $this->rootFolder = $rootFolder;
  86. $this->appData = $appData;
  87. $this->eventDispatcher = $eventDispatcher;
  88. $this->legacyEventDispatcher = $legacyEventDispatcher;
  89. $this->helper = $helper;
  90. $this->userId = $userId;
  91. $this->bootstrapCoordinator = $bootstrapCoordinator;
  92. $this->container = $container;
  93. $this->binaryFinder = $binaryFinder;
  94. }
  95. /**
  96. * In order to improve lazy loading a closure can be registered which will be
  97. * called in case preview providers are actually requested
  98. *
  99. * $callable has to return an instance of \OCP\Preview\IProvider or \OCP\Preview\IProviderV2
  100. *
  101. * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
  102. * @param \Closure $callable
  103. * @return void
  104. */
  105. public function registerProvider($mimeTypeRegex, \Closure $callable): void {
  106. if (!$this->config->getSystemValue('enable_previews', true)) {
  107. return;
  108. }
  109. if (!isset($this->providers[$mimeTypeRegex])) {
  110. $this->providers[$mimeTypeRegex] = [];
  111. }
  112. $this->providers[$mimeTypeRegex][] = $callable;
  113. $this->providerListDirty = true;
  114. }
  115. /**
  116. * Get all providers
  117. */
  118. public function getProviders(): array {
  119. if (!$this->config->getSystemValue('enable_previews', true)) {
  120. return [];
  121. }
  122. $this->registerCoreProviders();
  123. $this->registerBootstrapProviders();
  124. if ($this->providerListDirty) {
  125. $keys = array_map('strlen', array_keys($this->providers));
  126. array_multisort($keys, SORT_DESC, $this->providers);
  127. $this->providerListDirty = false;
  128. }
  129. return $this->providers;
  130. }
  131. /**
  132. * Does the manager have any providers
  133. */
  134. public function hasProviders(): bool {
  135. $this->registerCoreProviders();
  136. return !empty($this->providers);
  137. }
  138. private function getGenerator(): Generator {
  139. if ($this->generator === null) {
  140. $this->generator = new Generator(
  141. $this->config,
  142. $this,
  143. $this->appData,
  144. new GeneratorHelper(
  145. $this->rootFolder,
  146. $this->config
  147. ),
  148. $this->legacyEventDispatcher,
  149. $this->eventDispatcher
  150. );
  151. }
  152. return $this->generator;
  153. }
  154. /**
  155. * Returns a preview of a file
  156. *
  157. * The cache is searched first and if nothing usable was found then a preview is
  158. * generated by one of the providers
  159. *
  160. * @param File $file
  161. * @param int $width
  162. * @param int $height
  163. * @param bool $crop
  164. * @param string $mode
  165. * @param string $mimeType
  166. * @return ISimpleFile
  167. * @throws NotFoundException
  168. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  169. * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
  170. */
  171. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  172. $previewConcurrency = $this->getGenerator()->getNumConcurrentPreviews('preview_concurrency_all');
  173. $sem = Generator::guardWithSemaphore(Generator::SEMAPHORE_ID_ALL, $previewConcurrency);
  174. try {
  175. $preview = $this->getGenerator()->getPreview($file, $width, $height, $crop, $mode, $mimeType);
  176. } finally {
  177. Generator::unguardWithSemaphore($sem);
  178. }
  179. return $preview;
  180. }
  181. /**
  182. * Generates previews of a file
  183. *
  184. * @param File $file
  185. * @param array $specifications
  186. * @param string $mimeType
  187. * @return ISimpleFile the last preview that was generated
  188. * @throws NotFoundException
  189. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  190. * @since 19.0.0
  191. */
  192. public function generatePreviews(File $file, array $specifications, $mimeType = null) {
  193. return $this->getGenerator()->generatePreviews($file, $specifications, $mimeType);
  194. }
  195. /**
  196. * returns true if the passed mime type is supported
  197. *
  198. * @param string $mimeType
  199. * @return boolean
  200. */
  201. public function isMimeSupported($mimeType = '*') {
  202. if (!$this->config->getSystemValue('enable_previews', true)) {
  203. return false;
  204. }
  205. if (isset($this->mimeTypeSupportMap[$mimeType])) {
  206. return $this->mimeTypeSupportMap[$mimeType];
  207. }
  208. $this->registerCoreProviders();
  209. $this->registerBootstrapProviders();
  210. $providerMimeTypes = array_keys($this->providers);
  211. foreach ($providerMimeTypes as $supportedMimeType) {
  212. if (preg_match($supportedMimeType, $mimeType)) {
  213. $this->mimeTypeSupportMap[$mimeType] = true;
  214. return true;
  215. }
  216. }
  217. $this->mimeTypeSupportMap[$mimeType] = false;
  218. return false;
  219. }
  220. /**
  221. * Check if a preview can be generated for a file
  222. */
  223. public function isAvailable(\OCP\Files\FileInfo $file): bool {
  224. if (!$this->config->getSystemValue('enable_previews', true)) {
  225. return false;
  226. }
  227. $this->registerCoreProviders();
  228. if (!$this->isMimeSupported($file->getMimetype())) {
  229. return false;
  230. }
  231. $mount = $file->getMountPoint();
  232. if ($mount and !$mount->getOption('previews', true)) {
  233. return false;
  234. }
  235. foreach ($this->providers as $supportedMimeType => $providers) {
  236. if (preg_match($supportedMimeType, $file->getMimetype())) {
  237. foreach ($providers as $providerClosure) {
  238. $provider = $this->helper->getProvider($providerClosure);
  239. if (!($provider instanceof IProviderV2)) {
  240. continue;
  241. }
  242. if ($provider->isAvailable($file)) {
  243. return true;
  244. }
  245. }
  246. }
  247. }
  248. return false;
  249. }
  250. /**
  251. * List of enabled default providers
  252. *
  253. * The following providers are enabled by default:
  254. * - OC\Preview\PNG
  255. * - OC\Preview\JPEG
  256. * - OC\Preview\GIF
  257. * - OC\Preview\BMP
  258. * - OC\Preview\XBitmap
  259. * - OC\Preview\MarkDown
  260. * - OC\Preview\MP3
  261. * - OC\Preview\TXT
  262. *
  263. * The following providers are disabled by default due to performance or privacy concerns:
  264. * - OC\Preview\Font
  265. * - OC\Preview\HEIC
  266. * - OC\Preview\Illustrator
  267. * - OC\Preview\Movie
  268. * - OC\Preview\MSOfficeDoc
  269. * - OC\Preview\MSOffice2003
  270. * - OC\Preview\MSOffice2007
  271. * - OC\Preview\OpenDocument
  272. * - OC\Preview\PDF
  273. * - OC\Preview\Photoshop
  274. * - OC\Preview\Postscript
  275. * - OC\Preview\StarOffice
  276. * - OC\Preview\SVG
  277. * - OC\Preview\TIFF
  278. *
  279. * @return array
  280. */
  281. protected function getEnabledDefaultProvider() {
  282. if ($this->defaultProviders !== null) {
  283. return $this->defaultProviders;
  284. }
  285. $imageProviders = [
  286. Preview\PNG::class,
  287. Preview\JPEG::class,
  288. Preview\GIF::class,
  289. Preview\BMP::class,
  290. Preview\XBitmap::class,
  291. Preview\Krita::class,
  292. Preview\WebP::class,
  293. ];
  294. $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([
  295. Preview\MarkDown::class,
  296. Preview\MP3::class,
  297. Preview\TXT::class,
  298. Preview\OpenDocument::class,
  299. ], $imageProviders));
  300. if (in_array(Preview\Image::class, $this->defaultProviders)) {
  301. $this->defaultProviders = array_merge($this->defaultProviders, $imageProviders);
  302. }
  303. $this->defaultProviders = array_unique($this->defaultProviders);
  304. return $this->defaultProviders;
  305. }
  306. /**
  307. * Register the default providers (if enabled)
  308. *
  309. * @param string $class
  310. * @param string $mimeType
  311. */
  312. protected function registerCoreProvider($class, $mimeType, $options = []) {
  313. if (in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  314. $this->registerProvider($mimeType, function () use ($class, $options) {
  315. return new $class($options);
  316. });
  317. }
  318. }
  319. /**
  320. * Register the default providers (if enabled)
  321. */
  322. protected function registerCoreProviders() {
  323. if ($this->registeredCoreProviders) {
  324. return;
  325. }
  326. $this->registeredCoreProviders = true;
  327. $this->registerCoreProvider(Preview\TXT::class, '/text\/plain/');
  328. $this->registerCoreProvider(Preview\MarkDown::class, '/text\/(x-)?markdown/');
  329. $this->registerCoreProvider(Preview\PNG::class, '/image\/png/');
  330. $this->registerCoreProvider(Preview\JPEG::class, '/image\/jpeg/');
  331. $this->registerCoreProvider(Preview\GIF::class, '/image\/gif/');
  332. $this->registerCoreProvider(Preview\BMP::class, '/image\/bmp/');
  333. $this->registerCoreProvider(Preview\XBitmap::class, '/image\/x-xbitmap/');
  334. $this->registerCoreProvider(Preview\WebP::class, '/image\/webp/');
  335. $this->registerCoreProvider(Preview\Krita::class, '/application\/x-krita/');
  336. $this->registerCoreProvider(Preview\MP3::class, '/audio\/mpeg/');
  337. $this->registerCoreProvider(Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/');
  338. $this->registerCoreProvider(Preview\Imaginary::class, Preview\Imaginary::supportedMimeTypes());
  339. // SVG, Office and Bitmap require imagick
  340. if (extension_loaded('imagick')) {
  341. $checkImagick = new \Imagick();
  342. $imagickProviders = [
  343. 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => Preview\SVG::class],
  344. 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => Preview\TIFF::class],
  345. 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => Preview\PDF::class],
  346. 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Preview\Illustrator::class],
  347. 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Preview\Photoshop::class],
  348. 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Preview\Postscript::class],
  349. 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Preview\Font::class],
  350. 'HEIC' => ['mimetype' => '/image\/hei(f|c)/', 'class' => Preview\HEIC::class],
  351. 'TGA' => ['mimetype' => '/image\/t(ar)?ga/', 'class' => Preview\TGA::class],
  352. 'SGI' => ['mimetype' => '/image\/sgi/', 'class' => Preview\SGI::class],
  353. ];
  354. foreach ($imagickProviders as $queryFormat => $provider) {
  355. $class = $provider['class'];
  356. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  357. continue;
  358. }
  359. if (count($checkImagick->queryFormats($queryFormat)) === 1) {
  360. $this->registerCoreProvider($class, $provider['mimetype']);
  361. }
  362. }
  363. if (count($checkImagick->queryFormats('PDF')) === 1) {
  364. // Office requires openoffice or libreoffice
  365. $officeBinary = $this->config->getSystemValue('preview_libreoffice_path', null);
  366. if (!is_string($officeBinary)) {
  367. $officeBinary = $this->binaryFinder->findBinaryPath('libreoffice');
  368. }
  369. if (!is_string($officeBinary)) {
  370. $officeBinary = $this->binaryFinder->findBinaryPath('openoffice');
  371. }
  372. if (is_string($officeBinary)) {
  373. $this->registerCoreProvider(Preview\MSOfficeDoc::class, '/application\/msword/', ["officeBinary" => $officeBinary]);
  374. $this->registerCoreProvider(Preview\MSOffice2003::class, '/application\/vnd.ms-.*/', ["officeBinary" => $officeBinary]);
  375. $this->registerCoreProvider(Preview\MSOffice2007::class, '/application\/vnd.openxmlformats-officedocument.*/', ["officeBinary" => $officeBinary]);
  376. $this->registerCoreProvider(Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/', ["officeBinary" => $officeBinary]);
  377. $this->registerCoreProvider(Preview\StarOffice::class, '/application\/vnd.sun.xml.*/', ["officeBinary" => $officeBinary]);
  378. }
  379. }
  380. }
  381. // Video requires avconv or ffmpeg
  382. if (in_array(Preview\Movie::class, $this->getEnabledDefaultProvider())) {
  383. $movieBinary = $this->config->getSystemValue('preview_ffmpeg_path', null);
  384. if (!is_string($movieBinary)) {
  385. $movieBinary = $this->binaryFinder->findBinaryPath('avconv');
  386. if (!is_string($movieBinary)) {
  387. $movieBinary = $this->binaryFinder->findBinaryPath('ffmpeg');
  388. }
  389. }
  390. if (is_string($movieBinary)) {
  391. $this->registerCoreProvider(Preview\Movie::class, '/video\/.*/', ["movieBinary" => $movieBinary]);
  392. }
  393. }
  394. }
  395. private function registerBootstrapProviders(): void {
  396. $context = $this->bootstrapCoordinator->getRegistrationContext();
  397. if ($context === null) {
  398. // Just ignore for now
  399. return;
  400. }
  401. $providers = $context->getPreviewProviders();
  402. foreach ($providers as $provider) {
  403. $key = $provider->getMimeTypeRegex() . '-' . $provider->getService();
  404. if (array_key_exists($key, $this->loadedBootstrapProviders)) {
  405. // Do not load the provider more than once
  406. continue;
  407. }
  408. $this->loadedBootstrapProviders[$key] = null;
  409. $this->registerProvider($provider->getMimeTypeRegex(), function () use ($provider) {
  410. try {
  411. return $this->container->get($provider->getService());
  412. } catch (QueryException $e) {
  413. return null;
  414. }
  415. });
  416. }
  417. }
  418. }