1
0

PreviewManager.php 15 KB

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