1
0

PreviewManager.php 15 KB

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