From 958c1289b15f5bd877dd7ff3b7cf3540a0c5198a Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Thu, 4 Aug 2016 19:41:04 +0200 Subject: New preview generator Signed-off-by: Roeland Jago Douma --- lib/private/Preview.php | 2 +- lib/private/Preview2.php | 366 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 367 insertions(+), 1 deletion(-) create mode 100644 lib/private/Preview2.php (limited to 'lib/private') diff --git a/lib/private/Preview.php b/lib/private/Preview.php index ccaec738caf..caa1e89bacc 100644 --- a/lib/private/Preview.php +++ b/lib/private/Preview.php @@ -125,7 +125,7 @@ class Preview { $sysConfig = \OC::$server->getConfig(); $this->configMaxWidth = $sysConfig->getSystemValue('preview_max_x', 2048); $this->configMaxHeight = $sysConfig->getSystemValue('preview_max_y', 2048); - $this->maxScaleFactor = $sysConfig->getSystemValue('preview_max_scale_factor', 2); + $this->maxScaleFactor = $sysConfig->getSystemValue('preview_max_scale_factor', 1); //save parameters $this->setFile($file); diff --git a/lib/private/Preview2.php b/lib/private/Preview2.php new file mode 100644 index 00000000000..11e699a2e72 --- /dev/null +++ b/lib/private/Preview2.php @@ -0,0 +1,366 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OC; + +use OC\Files\View; +use OCP\Files\File; +use OCP\Files\Folder; +use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\IConfig; +use OCP\IImage; +use OCP\Image; +use OCP\IPreview; +use OCP\Preview\IProvider; + +class Preview2 { + //the thumbnail folder + const THUMBNAILS_FOLDER = 'thumbnails'; + + const MODE_FILL = 'fill'; + const MODE_COVER = 'cover'; + + /** @var IRootFolder*/ + private $rootFolder; + /** @var File */ + private $file; + /** @var IPreview */ + private $previewManager; + /** @var IConfig */ + private $config; + + public function __construct( + IRootFolder $rootFolder, + IConfig $config, + IPreview $previewManager, + File $file + ) { + $this->rootFolder = $rootFolder; + $this->config = $config; + $this->file = $file; + $this->previewManager = $previewManager; + } + + /** + * Returns a preview of a file + * + * The cache is searched first and if nothing usable was found then a preview is + * generated by one of the providers + * + * @param int $width + * @param int $height + * @param bool $crop + * @param string $mode + * @return File + * @throws NotFoundException + */ + public function getPreview($width = -1, $height = -1, $crop = false, $mode = Preview2::MODE_FILL) { + if (!$this->previewManager->isMimeSupported($this->file->getMimeType())) { + throw new NotFoundException(); + } + + /* + * Get the preview folder + * TODO: Separate preview creation from storing previews + */ + $previewFolder = $this->getPreviewFolder(); + + // Get the max preview and infer the max preview sizes from that + $maxPreview = $this->getMaxPreview($previewFolder); + list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview); + + // Calculate the preview size + list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight); + + // Try to get a cached preview. Else generate (and store) one + try { + $file = $this->getCachedPreview($previewFolder, $width, $height, $crop); + } catch (NotFoundException $e) { + $file = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight); + } + + return $file; + } + + /** + * @param Folder $previewFolder + * @return File + * @throws NotFoundException + */ + private function getMaxPreview(Folder $previewFolder) { + $nodes = $previewFolder->getDirectoryListing(); + + /** @var File $node */ + foreach ($nodes as $node) { + if (strpos($node->getName(), 'max')) { + return $node; + } + } + + $previewProviders = $this->previewManager->getProviders(); + foreach ($previewProviders as $supportedMimeType => $providers) { + if (!preg_match($supportedMimeType, $this->file->getMimeType())) { + continue; + } + + foreach ($providers as $provider) { + $provider = $provider(); + if (!($provider instanceof IProvider)) { + continue; + } + + list($view, $path) = $this->getViewAndPath($this->file); + + $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048); + $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048); + + $preview = $provider->getThumbnail($path, $maxWidth, $maxHeight, false, $view); + + if (!($preview instanceof IImage)) { + continue; + } + + $path = strval($preview->width()) . '-' . strval($preview->height()) . '-max.png'; + $file = $previewFolder->newFile($path); + $file->putContent($preview->data()); + + return $file; + } + } + + throw new NotFoundException(); + } + + /** + * @param File $file + * @return int[] + */ + private function getPreviewSize(File $file) { + $size = explode('-', $file->getName()); + return [(int)$size[0], (int)$size[1]]; + } + + /** + * @param int $width + * @param int $height + * @param bool $crop + * @return string + */ + private function generatePath($width, $height, $crop) { + $path = strval($width) . '-' . strval($height); + if ($crop) { + $path .= '-crop'; + } + $path .= '.png'; + return $path; + } + + /** + * @param File $file + * @return array + * This is required to create the old view and path + */ + private function getViewAndPath(File $file) { + $owner = $file->getOwner()->getUID(); + + $userFolder = $this->rootFolder->getUserFolder($owner)->getParent(); + $nodes = $userFolder->getById($file->getId()); + + $file = $nodes[0]; + + $view = new View($userFolder->getPath()); + $path = $userFolder->getRelativePath($file->getPath()); + + return [$view, $path]; + } + + /** + * @param int $width + * @param int $height + * @param bool $crop + * @param string $mode + * @param int $maxWidth + * @param int $maxHeight + * @return int[] + */ + private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) { + + /* + * If we are not cropping we have to make sure the requested image + * respects the aspect ratio of the original. + */ + if (!$crop) { + $ratio = $maxHeight / $maxWidth; + + if ($width === -1) { + $width = $height / $ratio; + } + if ($height === -1) { + $height = $width * $ratio; + } + + $ratioH = $height / $maxHeight; + $ratioW = $width / $maxWidth; + + /* + * Fill means that the $height and $width are the max + * Cover means min. + */ + if ($mode === self::MODE_FILL) { + if ($ratioH > $ratioW) { + $height = $width * $ratio; + } else { + $width = $height / $ratio; + } + } else if ($mode === self::MODE_COVER) { + if ($ratioH > $ratioW) { + $width = $height / $ratio; + } else { + $height = $width * $ratio; + } + } + } + + if ($height !== $maxHeight && $width !== $maxWidth) { + /* + * Scale to the nearest power of two + */ + $pow2height = pow(2, ceil(log($height) / log(2))); + $pow2width = pow(2, ceil(log($width) / log(2))); + + $ratioH = $height / $pow2height; + $ratioW = $width / $pow2width; + + if ($ratioH < $ratioW) { + $width = $pow2width; + $height = $height / $ratioW; + } else { + $height = $pow2height; + $width = $width / $ratioH; + } + } + + /* + * Make sure the requested height and width fall within the max + * of the preview. + */ + if ($height > $maxHeight) { + $ratio = $height / $maxHeight; + $height = $maxHeight; + $width = $width / $ratio; + } + if ($width > $maxWidth) { + $ratio = $width / $maxWidth; + $width = $maxWidth; + $height = $height / $ratio; + } + + return [(int)round($width), (int)round($height)]; + } + + /** + * @param Folder $previewFolder + * @param File $maxPreview + * @param int $width + * @param int $height + * @param bool $crop + * @param int $maxWidth, + * @param int $maxHeight + * @return File + * @throws NotFoundException + */ + private function generatePreview(Folder $previewFolder, File $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { + $preview = new Image($maxPreview->getContent()); + + if ($crop) { + if ($height !== $preview->height() && $width !== $preview->width()) { + //Resize + $widthR = $preview->width() / $width; + $heightR = $preview->height() / $height; + + if ($widthR > $heightR) { + $scaleH = $height; + $scaleW = $maxWidth / $heightR; + } else { + $scaleH = $maxHeight / $widthR; + $scaleW = $width; + } + $preview->preciseResize(round($scaleW), round($scaleH)); + } + $cropX = floor(abs($width - $preview->width()) * 0.5); + $cropY = 0; + $preview->crop($cropX, $cropY, $width, $height); + } else { + $preview->resize(max($width, $height)); + } + + $path = $this->generatePath($width, $height, $crop); + $file = $previewFolder->newFile($path); + $file->putContent($preview->data()); + + return $file; + } + + /** + * @param Folder $previewFolder + * @param int $width + * @param int $height + * @param bool $crop + * @return File + * + * @throws NotFoundException + */ + private function getCachedPreview(Folder $previewFolder, $width, $height, $crop) { + $path = $this->generatePath($width, $height, $crop); + + return $previewFolder->get($path); + } + + /** + * Get the specific preview folder for this file + * + * @return Folder + */ + private function getPreviewFolder() { + $user = $this->file->getOwner(); + $user = $user->getUID(); + + $previewRoot = $this->rootFolder->getUserFolder($user); + $previewRoot = $previewRoot->getParent(); + + try { + /** @var Folder $previewRoot */ + $previewRoot = $previewRoot->get(self::THUMBNAILS_FOLDER); + } catch (NotFoundException $e) { + $previewRoot = $previewRoot->newFolder(self::THUMBNAILS_FOLDER); + } + + try { + $previewFolder = $previewRoot->get($this->file->getId()); + } catch (NotFoundException $e) { + $previewFolder = $previewRoot->newFolder($this->file->getId()); + } + + return $previewFolder; + } +} -- cgit v1.2.3 From 743132650aa906d9468d633c2c5ca382e565df84 Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Fri, 7 Oct 2016 14:16:38 +0200 Subject: Move to AppData Signed-off-by: Roeland Jago Douma --- core/ajax/preview2.php | 8 +++++-- core/routes.php | 4 ++-- lib/private/Preview2.php | 60 +++++++++++++++++++++--------------------------- 3 files changed, 34 insertions(+), 38 deletions(-) (limited to 'lib/private') diff --git a/core/ajax/preview2.php b/core/ajax/preview2.php index b2bbf64c6d2..7ac50282190 100644 --- a/core/ajax/preview2.php +++ b/core/ajax/preview2.php @@ -30,7 +30,11 @@ $file = $userFolder->get($file); $p = new \OC\Preview2(\OC::$server->getRootFolder(), \OC::$server->getConfig(), \OC::$server->getPreviewManager(), - $file); + $file, + \OC::$server->getAppDataDir('preview')); -$p->getPreview($maxX, $maxY, !$keepAspect, $mode); +$image = $p->getPreview($maxX, $maxY, !$keepAspect, $mode); + +header('Content-Type: ' . $image->getMimeType()); +echo $image->getContent(); diff --git a/core/routes.php b/core/routes.php index 4b73a86042a..9ccf0e653eb 100644 --- a/core/routes.php +++ b/core/routes.php @@ -69,11 +69,11 @@ $this->create('search_ajax_search', '/core/search') ->actionInclude('core/search/ajax/search.php'); // Routing $this->create('core_ajax_preview', '/core/preview') - ->actionInclude('core/ajax/preview.php'); + ->actionInclude('core/ajax/preview2.php'); $this->create('core_ajax_preview2', '/core/preview2') ->actionInclude('core/ajax/preview2.php'); $this->create('core_ajax_preview', '/core/preview.png') - ->actionInclude('core/ajax/preview.php'); + ->actionInclude('core/ajax/preview2.php'); $this->create('core_ajax_update', '/core/ajax/update.php') ->actionInclude('core/ajax/update.php'); diff --git a/lib/private/Preview2.php b/lib/private/Preview2.php index 11e699a2e72..0a813dca638 100644 --- a/lib/private/Preview2.php +++ b/lib/private/Preview2.php @@ -24,9 +24,11 @@ namespace OC; use OC\Files\View; use OCP\Files\File; -use OCP\Files\Folder; +use OCP\Files\IAppData; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; use OCP\Image; @@ -48,17 +50,21 @@ class Preview2 { private $previewManager; /** @var IConfig */ private $config; + /** @var IAppData */ + private $appData; public function __construct( IRootFolder $rootFolder, IConfig $config, IPreview $previewManager, - File $file + File $file, + IAppData $appData ) { $this->rootFolder = $rootFolder; $this->config = $config; $this->file = $file; $this->previewManager = $previewManager; + $this->appData = $appData; } /** @@ -71,7 +77,7 @@ class Preview2 { * @param int $height * @param bool $crop * @param string $mode - * @return File + * @return ISimpleFile * @throws NotFoundException */ public function getPreview($width = -1, $height = -1, $crop = false, $mode = Preview2::MODE_FILL) { @@ -103,14 +109,13 @@ class Preview2 { } /** - * @param Folder $previewFolder - * @return File + * @param ISimpleFolder $previewFolder + * @return ISimpleFile * @throws NotFoundException */ - private function getMaxPreview(Folder $previewFolder) { + private function getMaxPreview(ISimpleFolder $previewFolder) { $nodes = $previewFolder->getDirectoryListing(); - /** @var File $node */ foreach ($nodes as $node) { if (strpos($node->getName(), 'max')) { return $node; @@ -152,10 +157,10 @@ class Preview2 { } /** - * @param File $file + * @param ISimpleFile $file * @return int[] */ - private function getPreviewSize(File $file) { + private function getPreviewSize(ISimpleFile $file) { $size = explode('-', $file->getName()); return [(int)$size[0], (int)$size[1]]; } @@ -279,17 +284,17 @@ class Preview2 { } /** - * @param Folder $previewFolder - * @param File $maxPreview + * @param ISimpleFolder $previewFolder + * @param ISimpleFile $maxPreview * @param int $width * @param int $height * @param bool $crop * @param int $maxWidth, * @param int $maxHeight - * @return File + * @return ISimpleFile * @throws NotFoundException */ - private function generatePreview(Folder $previewFolder, File $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { + private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { $preview = new Image($maxPreview->getContent()); if ($crop) { @@ -322,45 +327,32 @@ class Preview2 { } /** - * @param Folder $previewFolder + * @param ISimpleFolder $previewFolder * @param int $width * @param int $height * @param bool $crop - * @return File + * @return ISimpleFile * * @throws NotFoundException */ - private function getCachedPreview(Folder $previewFolder, $width, $height, $crop) { + private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop) { $path = $this->generatePath($width, $height, $crop); - return $previewFolder->get($path); + return $previewFolder->getFile($path); } /** * Get the specific preview folder for this file * - * @return Folder + * @return ISimpleFolder */ private function getPreviewFolder() { - $user = $this->file->getOwner(); - $user = $user->getUID(); - - $previewRoot = $this->rootFolder->getUserFolder($user); - $previewRoot = $previewRoot->getParent(); - - try { - /** @var Folder $previewRoot */ - $previewRoot = $previewRoot->get(self::THUMBNAILS_FOLDER); - } catch (NotFoundException $e) { - $previewRoot = $previewRoot->newFolder(self::THUMBNAILS_FOLDER); - } - try { - $previewFolder = $previewRoot->get($this->file->getId()); + $folder = $this->appData->getFolder($this->file->getId()); } catch (NotFoundException $e) { - $previewFolder = $previewRoot->newFolder($this->file->getId()); + $folder = $this->appData->newFolder($this->file->getId()); } - return $previewFolder; + return $folder; } } -- cgit v1.2.3 From c8ff9fb00e6ce65666bac00e0cc2a8c6f4da4b6c Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Fri, 14 Oct 2016 15:09:51 +0200 Subject: Watch for file modification/deletion * Only connect the watcher once the instance is properly setup else AppData fails hard. Signed-off-by: Roeland Jago Douma --- lib/private/Preview/Watcher.php | 98 ++++++++++++++++++++++++++++++++ lib/private/Preview/WatcherConnector.php | 72 +++++++++++++++++++++++ lib/private/Server.php | 10 ++++ 3 files changed, 180 insertions(+) create mode 100644 lib/private/Preview/Watcher.php create mode 100644 lib/private/Preview/WatcherConnector.php (limited to 'lib/private') diff --git a/lib/private/Preview/Watcher.php b/lib/private/Preview/Watcher.php new file mode 100644 index 00000000000..0b87bcda86e --- /dev/null +++ b/lib/private/Preview/Watcher.php @@ -0,0 +1,98 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OC\Preview; + +use OCP\Files\File; +use OCP\Files\Node; +use OCP\Files\Folder; +use OCP\Files\IAppData; +use OCP\Files\NotFoundException; + +/** + * Class Watcher + * + * @package OC\Preview + * + * Class that will watch filesystem activity and remove previews as needed. + */ +class Watcher { + /** @var IAppData */ + private $appData; + + /** @var int[] */ + private $toDelete = []; + + /** + * Watcher constructor. + * + * @param IAppData $appData + */ + public function __construct(IAppData $appData) { + $this->appData = $appData; + } + + public function postWrite(Node $node) { + // We only handle files + if ($node instanceof Folder) { + return; + } + + try { + $folder = $this->appData->getFolder($node->getId()); + $folder->delete(); + } catch (NotFoundException $e) { + //Nothing to do + } + } + + public function preDelete(Node $node) { + // To avoid cycles + if ($this->toDelete !== []) { + return; + } + + if ($node instanceof File) { + $this->toDelete[] = $node->getId(); + return; + } + + /** @var Folder $node */ + $nodes = $node->search(''); + foreach ($nodes as $node) { + if ($node instanceof File) { + $this->toDelete[] = $node->getId(); + } + } + } + + public function postDelete(Node $node) { + foreach ($this->toDelete as $fid) { + try { + $folder = $this->appData->getFolder($fid); + $folder->delete(); + } catch (NotFoundException $e) { + // continue + } + } + } +} diff --git a/lib/private/Preview/WatcherConnector.php b/lib/private/Preview/WatcherConnector.php new file mode 100644 index 00000000000..4e6e786cec7 --- /dev/null +++ b/lib/private/Preview/WatcherConnector.php @@ -0,0 +1,72 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OC\Preview; + +use OC\SystemConfig; +use OCP\Files\Node; +use OCP\Files\IRootFolder; + +class WatcherConnector { + + /** @var IRootFolder */ + private $root; + + /** @var SystemConfig */ + private $config; + + /** + * WatcherConnector constructor. + * + * @param IRootFolder $root + * @param SystemConfig $config + */ + public function __construct(IRootFolder $root, + SystemConfig $config) { + $this->root = $root; + $this->config = $config; + } + + /** + * @return Watcher + */ + private function getWatcher() { + return \OC::$server->query(Watcher::class); + } + + public function connectWatcher() { + // Do not connect if we are not setup yet! + if ($this->config->getValue('instanceid', null) !== null) { + $this->root->listen('\OC\Files', 'postWrite', function (Node $node) { + $this->getWatcher()->postWrite($node); + }); + + $this->root->listen('\OC\Files', 'preDelete', function (Node $node) { + $this->getWatcher()->preDelete($node); + }); + + $this->root->listen('\OC\Files', 'postDelete', function (Node $node) { + $this->getWatcher()->postDelete($node); + }); + } + } +} diff --git a/lib/private/Server.php b/lib/private/Server.php index 9f993ade7fe..eb6865c4f9b 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -120,6 +120,12 @@ class Server extends ServerContainer implements IServerContainer { return new PreviewManager($c->getConfig()); }); + $this->registerService(\OC\Preview\Watcher::class, function (Server $c) { + return new \OC\Preview\Watcher( + $c->getAppDataDir('preview') + ); + }); + $this->registerService('EncryptionManager', function (Server $c) { $view = new View(); $util = new Encryption\Util( @@ -192,6 +198,10 @@ class Server extends ServerContainer implements IServerContainer { ); $connector = new HookConnector($root, $view); $connector->viewToNode(); + + $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig()); + $previewConnector->connectWatcher(); + return $root; }); $this->registerService('LazyRootFolder', function(Server $c) { -- cgit v1.2.3 From 02525fd98bb3994199ebd877968574610f6898ee Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Fri, 14 Oct 2016 19:27:14 +0200 Subject: Move preview endpoint to controller Signed-off-by: Roeland Jago Douma --- core/Controller/PreviewController.php | 123 ++++++++++++++++++++++++++++++++++ core/ajax/preview.php | 75 --------------------- core/ajax/preview2.php | 40 ----------- core/routes.php | 8 +-- lib/private/Preview2.php | 7 ++ 5 files changed, 132 insertions(+), 121 deletions(-) create mode 100644 core/Controller/PreviewController.php delete mode 100644 core/ajax/preview.php delete mode 100644 core/ajax/preview2.php (limited to 'lib/private') diff --git a/core/Controller/PreviewController.php b/core/Controller/PreviewController.php new file mode 100644 index 00000000000..2dd62a2cecf --- /dev/null +++ b/core/Controller/PreviewController.php @@ -0,0 +1,123 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OC\Core\Controller; + +use OC\PreviewManager; +use OCP\AppFramework\Controller; +use OCP\Files\File; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\DataResponse; +use OCP\Files\IAppData; +use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\IConfig; +use OCP\IRequest; + +class PreviewController extends Controller { + + /** @var string */ + private $userId; + + /** @var IRootFolder */ + private $root; + + /** @var IConfig */ + private $config; + + /** @var PreviewManager */ + private $previewManager; + + /** @var IAppData */ + private $appData; + + public function __construct($appName, + IRequest $request, + IRootFolder $root, + IConfig $config, + PreviewManager $previewManager, + IAppData $appData, + $userId + ) { + parent::__construct($appName, $request); + + $this->previewManager = $previewManager; + $this->root = $root; + $this->config = $config; + $this->appData = $appData; + $this->userId = $userId; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + * @param string $file + * @param int $x + * @param int $y + * @param bool $a + * @param bool $forceIcon + * @param string $mode + * @return DataResponse|Http\FileDisplayResponse + */ + public function getPreview( + $file = '', + $x = 32, + $y = 32, + $a = false, + $forceIcon = true, + $mode = 'fill') { + + if ($file === '') { + return new DataResponse([], Http::STATUS_BAD_REQUEST); + } + + if ($x === 0 || $y === 0) { + return new DataResponse([], Http::STATUS_BAD_REQUEST); + } + + try { + $userFolder = $this->root->getUserFolder($this->userId); + $file = $userFolder->get($file); + } catch (NotFoundException $e) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } + + if (!($file instanceof File) || (!$forceIcon && !$this->previewManager->isAvailable($file))) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } else if (!$file->isReadable()) { + return new DataResponse([], Http::STATUS_FORBIDDEN); + } + + $preview = new \OC\Preview2( + $this->root, + $this->config, + $this->previewManager, + $file, + $this->appData + ); + + $f = $preview->getPreview($x, $y, !$a, $mode); + return new Http\FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]); + } +} diff --git a/core/ajax/preview.php b/core/ajax/preview.php deleted file mode 100644 index aac623b5ce6..00000000000 --- a/core/ajax/preview.php +++ /dev/null @@ -1,75 +0,0 @@ - - * @author Joas Schilling - * @author Lukas Reschke - * @author Morris Jobke - * @author Robin Appelman - * @author Thomas Müller - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -\OC_Util::checkLoggedIn(); -\OC::$server->getSession()->close(); - -$file = array_key_exists('file', $_GET) ? (string)$_GET['file'] : ''; -$maxX = array_key_exists('x', $_GET) ? (int)$_GET['x'] : '32'; -$maxY = array_key_exists('y', $_GET) ? (int)$_GET['y'] : '32'; -$scalingUp = array_key_exists('scalingup', $_GET) ? (bool)$_GET['scalingup'] : true; -$keepAspect = array_key_exists('a', $_GET) ? true : false; -$always = array_key_exists('forceIcon', $_GET) ? (bool)$_GET['forceIcon'] : true; -$mode = array_key_exists('mode', $_GET) ? $_GET['mode'] : 'fill'; - -if ($file === '') { - //400 Bad Request - \OC_Response::setStatus(400); - \OCP\Util::writeLog('core-preview', 'No file parameter was passed', \OCP\Util::DEBUG); - exit; -} - -if ($maxX === 0 || $maxY === 0) { - //400 Bad Request - \OC_Response::setStatus(400); - \OCP\Util::writeLog('core-preview', 'x and/or y set to 0', \OCP\Util::DEBUG); - exit; -} - -$folder = \OC::$server->getUserFolder(); - -try { - $file = $folder->get($file); -} catch (\OCP\Files\NotFoundException $e) { - return \OC_Response::setStatus(404); -} - -if (!$file instanceof OCP\Files\File || !$always && !\OC::$server->getPreviewManager()->isAvailable($file)) { - \OC_Response::setStatus(404); -} else if (!$info->isReadable()) { - \OC_Response::setStatus(403); -} else { - $preview = new \OC\Preview2( - \OC::$server->getRootFolder(), - \OC::$server->getConfig(), - \OC::$server->getPreviewManager(), - $file - ); - $image = $preview->getPreview($maxX, $maxY, !$keepAspect, $mode); - - header('Content-Type: ' . $image->getMimeType()); - echo $image->getContent(); -} diff --git a/core/ajax/preview2.php b/core/ajax/preview2.php deleted file mode 100644 index 7ac50282190..00000000000 --- a/core/ajax/preview2.php +++ /dev/null @@ -1,40 +0,0 @@ -getSession()->close(); - -$file = array_key_exists('file', $_GET) ? (string)$_GET['file'] : ''; -$maxX = array_key_exists('x', $_GET) ? (int)$_GET['x'] : '32'; -$maxY = array_key_exists('y', $_GET) ? (int)$_GET['y'] : '32'; -$keepAspect = array_key_exists('a', $_GET) ? true : false; -$always = array_key_exists('forceIcon', $_GET) ? (bool)$_GET['forceIcon'] : true; -$mode = array_key_exists('mode', $_GET) ? $_GET['mode'] : 'fill'; - -if ($file === '') { - //400 Bad Request - \OC_Response::setStatus(400); - \OCP\Util::writeLog('core-preview', 'No file parameter was passed', \OCP\Util::DEBUG); - exit; -} - -if ($maxX === 0 || $maxY === 0) { - //400 Bad Request - \OC_Response::setStatus(400); - \OCP\Util::writeLog('core-preview', 'x and/or y set to 0', \OCP\Util::DEBUG); - exit; -} - -$userFolder = \OC::$server->getUserFolder(); -$file = $userFolder->get($file); - -$p = new \OC\Preview2(\OC::$server->getRootFolder(), - \OC::$server->getConfig(), - \OC::$server->getPreviewManager(), - $file, - \OC::$server->getAppDataDir('preview')); - -$image = $p->getPreview($maxX, $maxY, !$keepAspect, $mode); - -header('Content-Type: ' . $image->getMimeType()); -echo $image->getContent(); - diff --git a/core/routes.php b/core/routes.php index 9ccf0e653eb..c890d232cfe 100644 --- a/core/routes.php +++ b/core/routes.php @@ -52,6 +52,8 @@ $application->registerRoutes($this, [ ['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'], ['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'], ['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'], + ['name' => 'Preview#getPreview', 'url' => '/core/preview', 'verb' => 'GET'], + ['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'], ], 'ocs' => [ ['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'], @@ -68,12 +70,6 @@ $application->registerRoutes($this, [ $this->create('search_ajax_search', '/core/search') ->actionInclude('core/search/ajax/search.php'); // Routing -$this->create('core_ajax_preview', '/core/preview') - ->actionInclude('core/ajax/preview2.php'); -$this->create('core_ajax_preview2', '/core/preview2') - ->actionInclude('core/ajax/preview2.php'); -$this->create('core_ajax_preview', '/core/preview.png') - ->actionInclude('core/ajax/preview2.php'); $this->create('core_ajax_update', '/core/ajax/update.php') ->actionInclude('core/ajax/update.php'); diff --git a/lib/private/Preview2.php b/lib/private/Preview2.php index 0a813dca638..e1f3af6ebdc 100644 --- a/lib/private/Preview2.php +++ b/lib/private/Preview2.php @@ -53,6 +53,13 @@ class Preview2 { /** @var IAppData */ private $appData; + /** + * @param IRootFolder $rootFolder + * @param IConfig $config + * @param IPreview $previewManager + * @param File $file + * @param IAppData $appData + */ public function __construct( IRootFolder $rootFolder, IConfig $config, -- cgit v1.2.3 From d6f1287ae6407a8f1ef0d018fe197e0f920ed192 Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Fri, 14 Oct 2016 21:21:37 +0200 Subject: Move file Signed-off-by: Roeland Jago Douma --- core/Controller/PreviewController.php | 2 +- lib/private/Preview/Generator.php | 366 ++++++++++++++++++++++++++++++++++ lib/private/Preview2.php | 365 --------------------------------- 3 files changed, 367 insertions(+), 366 deletions(-) create mode 100644 lib/private/Preview/Generator.php delete mode 100644 lib/private/Preview2.php (limited to 'lib/private') diff --git a/core/Controller/PreviewController.php b/core/Controller/PreviewController.php index 2dd62a2cecf..425617813fa 100644 --- a/core/Controller/PreviewController.php +++ b/core/Controller/PreviewController.php @@ -109,7 +109,7 @@ class PreviewController extends Controller { return new DataResponse([], Http::STATUS_FORBIDDEN); } - $preview = new \OC\Preview2( + $preview = new \OC\Preview\Generator( $this->root, $this->config, $this->previewManager, diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php new file mode 100644 index 00000000000..6a2e2a4717e --- /dev/null +++ b/lib/private/Preview/Generator.php @@ -0,0 +1,366 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OC\Preview; + +use OC\Files\View; +use OCP\Files\File; +use OCP\Files\IAppData; +use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\SimpleFS\ISimpleFolder; +use OCP\IConfig; +use OCP\IImage; +use OCP\Image; +use OCP\IPreview; +use OCP\Preview\IProvider; + +class Generator { + //the thumbnail folder + const THUMBNAILS_FOLDER = 'thumbnails'; + + const MODE_FILL = 'fill'; + const MODE_COVER = 'cover'; + + /** @var IRootFolder*/ + private $rootFolder; + /** @var File */ + private $file; + /** @var IPreview */ + private $previewManager; + /** @var IConfig */ + private $config; + /** @var IAppData */ + private $appData; + + /** + * @param IRootFolder $rootFolder + * @param IConfig $config + * @param IPreview $previewManager + * @param File $file + * @param IAppData $appData + */ + public function __construct( + IRootFolder $rootFolder, + IConfig $config, + IPreview $previewManager, + File $file, + IAppData $appData + ) { + $this->rootFolder = $rootFolder; + $this->config = $config; + $this->file = $file; + $this->previewManager = $previewManager; + $this->appData = $appData; + } + + /** + * Returns a preview of a file + * + * The cache is searched first and if nothing usable was found then a preview is + * generated by one of the providers + * + * @param int $width + * @param int $height + * @param bool $crop + * @param string $mode + * @return ISimpleFile + * @throws NotFoundException + */ + public function getPreview($width = -1, $height = -1, $crop = false, $mode = Generator::MODE_FILL) { + if (!$this->previewManager->isMimeSupported($this->file->getMimeType())) { + throw new NotFoundException(); + } + + /* + * Get the preview folder + * TODO: Separate preview creation from storing previews + */ + $previewFolder = $this->getPreviewFolder(); + + // Get the max preview and infer the max preview sizes from that + $maxPreview = $this->getMaxPreview($previewFolder); + list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview); + + // Calculate the preview size + list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight); + + // Try to get a cached preview. Else generate (and store) one + try { + $file = $this->getCachedPreview($previewFolder, $width, $height, $crop); + } catch (NotFoundException $e) { + $file = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight); + } + + return $file; + } + + /** + * @param ISimpleFolder $previewFolder + * @return ISimpleFile + * @throws NotFoundException + */ + private function getMaxPreview(ISimpleFolder $previewFolder) { + $nodes = $previewFolder->getDirectoryListing(); + + foreach ($nodes as $node) { + if (strpos($node->getName(), 'max')) { + return $node; + } + } + + $previewProviders = $this->previewManager->getProviders(); + foreach ($previewProviders as $supportedMimeType => $providers) { + if (!preg_match($supportedMimeType, $this->file->getMimeType())) { + continue; + } + + foreach ($providers as $provider) { + $provider = $provider(); + if (!($provider instanceof IProvider)) { + continue; + } + + list($view, $path) = $this->getViewAndPath($this->file); + + $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048); + $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048); + + $preview = $provider->getThumbnail($path, $maxWidth, $maxHeight, false, $view); + + if (!($preview instanceof IImage)) { + continue; + } + + $path = strval($preview->width()) . '-' . strval($preview->height()) . '-max.png'; + $file = $previewFolder->newFile($path); + $file->putContent($preview->data()); + + return $file; + } + } + + throw new NotFoundException(); + } + + /** + * @param ISimpleFile $file + * @return int[] + */ + private function getPreviewSize(ISimpleFile $file) { + $size = explode('-', $file->getName()); + return [(int)$size[0], (int)$size[1]]; + } + + /** + * @param int $width + * @param int $height + * @param bool $crop + * @return string + */ + private function generatePath($width, $height, $crop) { + $path = strval($width) . '-' . strval($height); + if ($crop) { + $path .= '-crop'; + } + $path .= '.png'; + return $path; + } + + /** + * @param File $file + * @return array + * This is required to create the old view and path + */ + private function getViewAndPath(File $file) { + $owner = $file->getOwner()->getUID(); + + $userFolder = $this->rootFolder->getUserFolder($owner)->getParent(); + $nodes = $userFolder->getById($file->getId()); + + $file = $nodes[0]; + + $view = new View($userFolder->getPath()); + $path = $userFolder->getRelativePath($file->getPath()); + + return [$view, $path]; + } + + /** + * @param int $width + * @param int $height + * @param bool $crop + * @param string $mode + * @param int $maxWidth + * @param int $maxHeight + * @return int[] + */ + private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) { + + /* + * If we are not cropping we have to make sure the requested image + * respects the aspect ratio of the original. + */ + if (!$crop) { + $ratio = $maxHeight / $maxWidth; + + if ($width === -1) { + $width = $height / $ratio; + } + if ($height === -1) { + $height = $width * $ratio; + } + + $ratioH = $height / $maxHeight; + $ratioW = $width / $maxWidth; + + /* + * Fill means that the $height and $width are the max + * Cover means min. + */ + if ($mode === self::MODE_FILL) { + if ($ratioH > $ratioW) { + $height = $width * $ratio; + } else { + $width = $height / $ratio; + } + } else if ($mode === self::MODE_COVER) { + if ($ratioH > $ratioW) { + $width = $height / $ratio; + } else { + $height = $width * $ratio; + } + } + } + + if ($height !== $maxHeight && $width !== $maxWidth) { + /* + * Scale to the nearest power of two + */ + $pow2height = pow(2, ceil(log($height) / log(2))); + $pow2width = pow(2, ceil(log($width) / log(2))); + + $ratioH = $height / $pow2height; + $ratioW = $width / $pow2width; + + if ($ratioH < $ratioW) { + $width = $pow2width; + $height = $height / $ratioW; + } else { + $height = $pow2height; + $width = $width / $ratioH; + } + } + + /* + * Make sure the requested height and width fall within the max + * of the preview. + */ + if ($height > $maxHeight) { + $ratio = $height / $maxHeight; + $height = $maxHeight; + $width = $width / $ratio; + } + if ($width > $maxWidth) { + $ratio = $width / $maxWidth; + $width = $maxWidth; + $height = $height / $ratio; + } + + return [(int)round($width), (int)round($height)]; + } + + /** + * @param ISimpleFolder $previewFolder + * @param ISimpleFile $maxPreview + * @param int $width + * @param int $height + * @param bool $crop + * @param int $maxWidth, + * @param int $maxHeight + * @return ISimpleFile + * @throws NotFoundException + */ + private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { + $preview = new Image($maxPreview->getContent()); + + if ($crop) { + if ($height !== $preview->height() && $width !== $preview->width()) { + //Resize + $widthR = $preview->width() / $width; + $heightR = $preview->height() / $height; + + if ($widthR > $heightR) { + $scaleH = $height; + $scaleW = $maxWidth / $heightR; + } else { + $scaleH = $maxHeight / $widthR; + $scaleW = $width; + } + $preview->preciseResize(round($scaleW), round($scaleH)); + } + $cropX = floor(abs($width - $preview->width()) * 0.5); + $cropY = 0; + $preview->crop($cropX, $cropY, $width, $height); + } else { + $preview->resize(max($width, $height)); + } + + $path = $this->generatePath($width, $height, $crop); + $file = $previewFolder->newFile($path); + $file->putContent($preview->data()); + + return $file; + } + + /** + * @param ISimpleFolder $previewFolder + * @param int $width + * @param int $height + * @param bool $crop + * @return ISimpleFile + * + * @throws NotFoundException + */ + private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop) { + $path = $this->generatePath($width, $height, $crop); + + return $previewFolder->getFile($path); + } + + /** + * Get the specific preview folder for this file + * + * @return ISimpleFolder + */ + private function getPreviewFolder() { + try { + $folder = $this->appData->getFolder($this->file->getId()); + } catch (NotFoundException $e) { + $folder = $this->appData->newFolder($this->file->getId()); + } + + return $folder; + } +} diff --git a/lib/private/Preview2.php b/lib/private/Preview2.php deleted file mode 100644 index e1f3af6ebdc..00000000000 --- a/lib/private/Preview2.php +++ /dev/null @@ -1,365 +0,0 @@ - - * - * @author Roeland Jago Douma - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - * - */ -namespace OC; - -use OC\Files\View; -use OCP\Files\File; -use OCP\Files\IAppData; -use OCP\Files\IRootFolder; -use OCP\Files\NotFoundException; -use OCP\Files\SimpleFS\ISimpleFile; -use OCP\Files\SimpleFS\ISimpleFolder; -use OCP\IConfig; -use OCP\IImage; -use OCP\Image; -use OCP\IPreview; -use OCP\Preview\IProvider; - -class Preview2 { - //the thumbnail folder - const THUMBNAILS_FOLDER = 'thumbnails'; - - const MODE_FILL = 'fill'; - const MODE_COVER = 'cover'; - - /** @var IRootFolder*/ - private $rootFolder; - /** @var File */ - private $file; - /** @var IPreview */ - private $previewManager; - /** @var IConfig */ - private $config; - /** @var IAppData */ - private $appData; - - /** - * @param IRootFolder $rootFolder - * @param IConfig $config - * @param IPreview $previewManager - * @param File $file - * @param IAppData $appData - */ - public function __construct( - IRootFolder $rootFolder, - IConfig $config, - IPreview $previewManager, - File $file, - IAppData $appData - ) { - $this->rootFolder = $rootFolder; - $this->config = $config; - $this->file = $file; - $this->previewManager = $previewManager; - $this->appData = $appData; - } - - /** - * Returns a preview of a file - * - * The cache is searched first and if nothing usable was found then a preview is - * generated by one of the providers - * - * @param int $width - * @param int $height - * @param bool $crop - * @param string $mode - * @return ISimpleFile - * @throws NotFoundException - */ - public function getPreview($width = -1, $height = -1, $crop = false, $mode = Preview2::MODE_FILL) { - if (!$this->previewManager->isMimeSupported($this->file->getMimeType())) { - throw new NotFoundException(); - } - - /* - * Get the preview folder - * TODO: Separate preview creation from storing previews - */ - $previewFolder = $this->getPreviewFolder(); - - // Get the max preview and infer the max preview sizes from that - $maxPreview = $this->getMaxPreview($previewFolder); - list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview); - - // Calculate the preview size - list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight); - - // Try to get a cached preview. Else generate (and store) one - try { - $file = $this->getCachedPreview($previewFolder, $width, $height, $crop); - } catch (NotFoundException $e) { - $file = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight); - } - - return $file; - } - - /** - * @param ISimpleFolder $previewFolder - * @return ISimpleFile - * @throws NotFoundException - */ - private function getMaxPreview(ISimpleFolder $previewFolder) { - $nodes = $previewFolder->getDirectoryListing(); - - foreach ($nodes as $node) { - if (strpos($node->getName(), 'max')) { - return $node; - } - } - - $previewProviders = $this->previewManager->getProviders(); - foreach ($previewProviders as $supportedMimeType => $providers) { - if (!preg_match($supportedMimeType, $this->file->getMimeType())) { - continue; - } - - foreach ($providers as $provider) { - $provider = $provider(); - if (!($provider instanceof IProvider)) { - continue; - } - - list($view, $path) = $this->getViewAndPath($this->file); - - $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048); - $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048); - - $preview = $provider->getThumbnail($path, $maxWidth, $maxHeight, false, $view); - - if (!($preview instanceof IImage)) { - continue; - } - - $path = strval($preview->width()) . '-' . strval($preview->height()) . '-max.png'; - $file = $previewFolder->newFile($path); - $file->putContent($preview->data()); - - return $file; - } - } - - throw new NotFoundException(); - } - - /** - * @param ISimpleFile $file - * @return int[] - */ - private function getPreviewSize(ISimpleFile $file) { - $size = explode('-', $file->getName()); - return [(int)$size[0], (int)$size[1]]; - } - - /** - * @param int $width - * @param int $height - * @param bool $crop - * @return string - */ - private function generatePath($width, $height, $crop) { - $path = strval($width) . '-' . strval($height); - if ($crop) { - $path .= '-crop'; - } - $path .= '.png'; - return $path; - } - - /** - * @param File $file - * @return array - * This is required to create the old view and path - */ - private function getViewAndPath(File $file) { - $owner = $file->getOwner()->getUID(); - - $userFolder = $this->rootFolder->getUserFolder($owner)->getParent(); - $nodes = $userFolder->getById($file->getId()); - - $file = $nodes[0]; - - $view = new View($userFolder->getPath()); - $path = $userFolder->getRelativePath($file->getPath()); - - return [$view, $path]; - } - - /** - * @param int $width - * @param int $height - * @param bool $crop - * @param string $mode - * @param int $maxWidth - * @param int $maxHeight - * @return int[] - */ - private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) { - - /* - * If we are not cropping we have to make sure the requested image - * respects the aspect ratio of the original. - */ - if (!$crop) { - $ratio = $maxHeight / $maxWidth; - - if ($width === -1) { - $width = $height / $ratio; - } - if ($height === -1) { - $height = $width * $ratio; - } - - $ratioH = $height / $maxHeight; - $ratioW = $width / $maxWidth; - - /* - * Fill means that the $height and $width are the max - * Cover means min. - */ - if ($mode === self::MODE_FILL) { - if ($ratioH > $ratioW) { - $height = $width * $ratio; - } else { - $width = $height / $ratio; - } - } else if ($mode === self::MODE_COVER) { - if ($ratioH > $ratioW) { - $width = $height / $ratio; - } else { - $height = $width * $ratio; - } - } - } - - if ($height !== $maxHeight && $width !== $maxWidth) { - /* - * Scale to the nearest power of two - */ - $pow2height = pow(2, ceil(log($height) / log(2))); - $pow2width = pow(2, ceil(log($width) / log(2))); - - $ratioH = $height / $pow2height; - $ratioW = $width / $pow2width; - - if ($ratioH < $ratioW) { - $width = $pow2width; - $height = $height / $ratioW; - } else { - $height = $pow2height; - $width = $width / $ratioH; - } - } - - /* - * Make sure the requested height and width fall within the max - * of the preview. - */ - if ($height > $maxHeight) { - $ratio = $height / $maxHeight; - $height = $maxHeight; - $width = $width / $ratio; - } - if ($width > $maxWidth) { - $ratio = $width / $maxWidth; - $width = $maxWidth; - $height = $height / $ratio; - } - - return [(int)round($width), (int)round($height)]; - } - - /** - * @param ISimpleFolder $previewFolder - * @param ISimpleFile $maxPreview - * @param int $width - * @param int $height - * @param bool $crop - * @param int $maxWidth, - * @param int $maxHeight - * @return ISimpleFile - * @throws NotFoundException - */ - private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { - $preview = new Image($maxPreview->getContent()); - - if ($crop) { - if ($height !== $preview->height() && $width !== $preview->width()) { - //Resize - $widthR = $preview->width() / $width; - $heightR = $preview->height() / $height; - - if ($widthR > $heightR) { - $scaleH = $height; - $scaleW = $maxWidth / $heightR; - } else { - $scaleH = $maxHeight / $widthR; - $scaleW = $width; - } - $preview->preciseResize(round($scaleW), round($scaleH)); - } - $cropX = floor(abs($width - $preview->width()) * 0.5); - $cropY = 0; - $preview->crop($cropX, $cropY, $width, $height); - } else { - $preview->resize(max($width, $height)); - } - - $path = $this->generatePath($width, $height, $crop); - $file = $previewFolder->newFile($path); - $file->putContent($preview->data()); - - return $file; - } - - /** - * @param ISimpleFolder $previewFolder - * @param int $width - * @param int $height - * @param bool $crop - * @return ISimpleFile - * - * @throws NotFoundException - */ - private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop) { - $path = $this->generatePath($width, $height, $crop); - - return $previewFolder->getFile($path); - } - - /** - * Get the specific preview folder for this file - * - * @return ISimpleFolder - */ - private function getPreviewFolder() { - try { - $folder = $this->appData->getFolder($this->file->getId()); - } catch (NotFoundException $e) { - $folder = $this->appData->newFolder($this->file->getId()); - } - - return $folder; - } -} -- cgit v1.2.3 From 8468212386fa577a60df238c10243b8297e962fc Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Sun, 16 Oct 2016 15:47:30 +0200 Subject: Fix name conflict Signed-off-by: Roeland Jago Douma --- lib/private/Preview/Generator.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php index 6a2e2a4717e..08ab37057aa 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -32,7 +32,7 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; -use OCP\Image; +use OCP\Image as img; use OCP\IPreview; use OCP\Preview\IProvider; @@ -297,13 +297,13 @@ class Generator { * @param int $width * @param int $height * @param bool $crop - * @param int $maxWidth, + * @param int $maxWidth * @param int $maxHeight * @return ISimpleFile * @throws NotFoundException */ private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { - $preview = new Image($maxPreview->getContent()); + $preview = new img($maxPreview->getContent()); if ($crop) { if ($height !== $preview->height() && $width !== $preview->width()) { -- cgit v1.2.3 From 5466fbf761bfb810a43b11789b03b2ec54c9ab6e Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Sun, 16 Oct 2016 16:48:11 +0200 Subject: Move Ipreview to more of DI thingy Signed-off-by: Roeland Jago Douma --- core/Controller/PreviewController.php | 48 ++++++++++++++------------------ lib/private/Preview/Generator.php | 37 ++++++++++--------------- lib/private/PreviewManager.php | 52 +++++++++++++++++++++++++++++++++-- lib/private/Server.php | 6 +++- lib/public/IPreview.php | 25 +++++++++++++++++ 5 files changed, 116 insertions(+), 52 deletions(-) (limited to 'lib/private') diff --git a/core/Controller/PreviewController.php b/core/Controller/PreviewController.php index 425617813fa..f54681a856b 100644 --- a/core/Controller/PreviewController.php +++ b/core/Controller/PreviewController.php @@ -23,15 +23,14 @@ namespace OC\Core\Controller; -use OC\PreviewManager; +use OC\DatabaseException; use OCP\AppFramework\Controller; use OCP\Files\File; use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; -use OCP\Files\IAppData; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; -use OCP\IConfig; +use OCP\IPreview; use OCP\IRequest; class PreviewController extends Controller { @@ -42,29 +41,28 @@ class PreviewController extends Controller { /** @var IRootFolder */ private $root; - /** @var IConfig */ - private $config; - - /** @var PreviewManager */ - private $previewManager; - - /** @var IAppData */ - private $appData; + /** @var IPreview */ + private $preview; + /** + * PreviewController constructor. + * + * @param string $appName + * @param IRequest $request + * @param IPreview $preview + * @param IRootFolder $root + * @param string $userId + */ public function __construct($appName, IRequest $request, + IPreview $preview, IRootFolder $root, - IConfig $config, - PreviewManager $previewManager, - IAppData $appData, $userId ) { parent::__construct($appName, $request); - $this->previewManager = $previewManager; + $this->preview = $preview; $this->root = $root; - $this->config = $config; - $this->appData = $appData; $this->userId = $userId; } @@ -103,21 +101,17 @@ class PreviewController extends Controller { return new DataResponse([], Http::STATUS_NOT_FOUND); } - if (!($file instanceof File) || (!$forceIcon && !$this->previewManager->isAvailable($file))) { + if (!($file instanceof File) || (!$forceIcon && !$this->preview->isAvailable($file))) { return new DataResponse([], Http::STATUS_NOT_FOUND); } else if (!$file->isReadable()) { return new DataResponse([], Http::STATUS_FORBIDDEN); } - $preview = new \OC\Preview\Generator( - $this->root, - $this->config, - $this->previewManager, - $file, - $this->appData - ); - - $f = $preview->getPreview($x, $y, !$a, $mode); + try { + $f = $this->preview->getPreview($file, $x, $y, !$a, $mode); + } catch (NotFoundException $e) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } return new Http\FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]); } } diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php index 08ab37057aa..ea162926afa 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -37,16 +37,9 @@ use OCP\IPreview; use OCP\Preview\IProvider; class Generator { - //the thumbnail folder - const THUMBNAILS_FOLDER = 'thumbnails'; - - const MODE_FILL = 'fill'; - const MODE_COVER = 'cover'; /** @var IRootFolder*/ private $rootFolder; - /** @var File */ - private $file; /** @var IPreview */ private $previewManager; /** @var IConfig */ @@ -58,19 +51,16 @@ class Generator { * @param IRootFolder $rootFolder * @param IConfig $config * @param IPreview $previewManager - * @param File $file * @param IAppData $appData */ public function __construct( IRootFolder $rootFolder, IConfig $config, IPreview $previewManager, - File $file, IAppData $appData ) { $this->rootFolder = $rootFolder; $this->config = $config; - $this->file = $file; $this->previewManager = $previewManager; $this->appData = $appData; } @@ -81,6 +71,7 @@ class Generator { * The cache is searched first and if nothing usable was found then a preview is * generated by one of the providers * + * @param File $file * @param int $width * @param int $height * @param bool $crop @@ -88,8 +79,8 @@ class Generator { * @return ISimpleFile * @throws NotFoundException */ - public function getPreview($width = -1, $height = -1, $crop = false, $mode = Generator::MODE_FILL) { - if (!$this->previewManager->isMimeSupported($this->file->getMimeType())) { + public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL) { + if (!$this->previewManager->isMimeSupported($file->getMimeType())) { throw new NotFoundException(); } @@ -97,10 +88,10 @@ class Generator { * Get the preview folder * TODO: Separate preview creation from storing previews */ - $previewFolder = $this->getPreviewFolder(); + $previewFolder = $this->getPreviewFolder($file); // Get the max preview and infer the max preview sizes from that - $maxPreview = $this->getMaxPreview($previewFolder); + $maxPreview = $this->getMaxPreview($previewFolder, $file); list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview); // Calculate the preview size @@ -118,10 +109,11 @@ class Generator { /** * @param ISimpleFolder $previewFolder + * @param File $file * @return ISimpleFile * @throws NotFoundException */ - private function getMaxPreview(ISimpleFolder $previewFolder) { + private function getMaxPreview(ISimpleFolder $previewFolder, File $file) { $nodes = $previewFolder->getDirectoryListing(); foreach ($nodes as $node) { @@ -132,7 +124,7 @@ class Generator { $previewProviders = $this->previewManager->getProviders(); foreach ($previewProviders as $supportedMimeType => $providers) { - if (!preg_match($supportedMimeType, $this->file->getMimeType())) { + if (!preg_match($supportedMimeType, $file->getMimeType())) { continue; } @@ -142,7 +134,7 @@ class Generator { continue; } - list($view, $path) = $this->getViewAndPath($this->file); + list($view, $path) = $this->getViewAndPath($file); $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048); $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048); @@ -239,13 +231,13 @@ class Generator { * Fill means that the $height and $width are the max * Cover means min. */ - if ($mode === self::MODE_FILL) { + if ($mode === IPreview::MODE_FILL) { if ($ratioH > $ratioW) { $height = $width * $ratio; } else { $width = $height / $ratio; } - } else if ($mode === self::MODE_COVER) { + } else if ($mode === IPreview::MODE_COVER) { if ($ratioH > $ratioW) { $width = $height / $ratio; } else { @@ -352,13 +344,14 @@ class Generator { /** * Get the specific preview folder for this file * + * @param File $file * @return ISimpleFolder */ - private function getPreviewFolder() { + private function getPreviewFolder(File $file) { try { - $folder = $this->appData->getFolder($this->file->getId()); + $folder = $this->appData->getFolder($file->getId()); } catch (NotFoundException $e) { - $folder = $this->appData->newFolder($this->file->getId()); + $folder = $this->appData->newFolder($file->getId()); } return $folder; diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index 109feb45864..0cda55751bf 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -25,13 +25,29 @@ */ namespace OC; +use OC\Preview\Generator; +use OCP\Files\File; +use OCP\Files\IAppData; +use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\IConfig; use OCP\IPreview; use OCP\Preview\IProvider; class PreviewManager implements IPreview { - /** @var \OCP\IConfig */ + /** @var IConfig */ protected $config; + /** @var IRootFolder */ + protected $rootFolder; + + /** @var IAppData */ + protected $appData; + + /** @var Generator */ + private $generator; + /** @var bool */ protected $providerListDirty = false; @@ -52,8 +68,12 @@ class PreviewManager implements IPreview { * * @param \OCP\IConfig $config */ - public function __construct(\OCP\IConfig $config) { + public function __construct(IConfig $config, + IRootFolder $rootFolder, + IAppData $appData) { $this->config = $config; + $this->rootFolder = $rootFolder; + $this->appData = $appData; } /** @@ -120,6 +140,34 @@ class PreviewManager implements IPreview { return $preview->getPreview(); } + /** + * Returns a preview of a file + * + * The cache is searched first and if nothing usable was found then a preview is + * generated by one of the providers + * + * @param File $file + * @param int $width + * @param int $height + * @param bool $crop + * @param string $mode + * @return ISimpleFile + * @throws NotFoundException + * @since 9.2.0 + */ + public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL) { + if ($this->generator === null) { + $this->generator = new Generator( + $this->rootFolder, + $this->config, + $this, + $this->appData + ); + } + + return $this->generator->getPreview($file, $width, $height, $crop, $mode); + } + /** * returns true if the passed mime type is supported * diff --git a/lib/private/Server.php b/lib/private/Server.php index eb6865c4f9b..8f4e7d9ca2d 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -117,7 +117,11 @@ class Server extends ServerContainer implements IServerContainer { }); $this->registerService('PreviewManager', function (Server $c) { - return new PreviewManager($c->getConfig()); + return new PreviewManager( + $c->getConfig(), + $c->getRootFolder(), + $c->getAppDataDir('preview') + ); }); $this->registerService(\OC\Preview\Watcher::class, function (Server $c) { diff --git a/lib/public/IPreview.php b/lib/public/IPreview.php index 071b5b8064c..0942db4784c 100644 --- a/lib/public/IPreview.php +++ b/lib/public/IPreview.php @@ -33,11 +33,19 @@ // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; +use OCP\Files\File; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\NotFoundException; + /** * This class provides functions to render and show thumbnails and previews of files * @since 6.0.0 */ interface IPreview { + + const MODE_FILL = 'fill'; + const MODE_COVER = 'cover'; + /** * In order to improve lazy loading a closure can be registered which will be * called in case preview providers are actually requested @@ -73,9 +81,26 @@ interface IPreview { * @param boolean $scaleUp Scale smaller images up to the thumbnail size or not. Might look ugly * @return \OCP\IImage * @since 6.0.0 + * @deprecated 9.2.0 Use getPreview */ public function createPreview($file, $maxX = 100, $maxY = 75, $scaleUp = false); + /** + * Returns a preview of a file + * + * The cache is searched first and if nothing usable was found then a preview is + * generated by one of the providers + * + * @param File $file + * @param int $width + * @param int $height + * @param bool $crop + * @param string $mode + * @return ISimpleFile + * @throws NotFoundException + * @since 9.2.0 + */ + public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL); /** * Returns true if the passed mime type is supported -- cgit v1.2.3 From d720a2fb5719122a0250d63c269380c6ba413755 Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Sun, 16 Oct 2016 20:42:35 +0200 Subject: Moved over files_versions Signed-off-by: Roeland Jago Douma --- apps/files_versions/ajax/preview.php | 66 ------------ apps/files_versions/appinfo/routes.php | 15 ++- .../lib/Controller/PreviewController.php | 111 +++++++++++++++++++++ apps/files_versions/lib/Storage.php | 2 +- lib/private/Preview/Generator.php | 15 ++- lib/private/PreviewManager.php | 5 +- lib/public/IPreview.php | 3 +- 7 files changed, 137 insertions(+), 80 deletions(-) delete mode 100644 apps/files_versions/ajax/preview.php create mode 100644 apps/files_versions/lib/Controller/PreviewController.php (limited to 'lib/private') diff --git a/apps/files_versions/ajax/preview.php b/apps/files_versions/ajax/preview.php deleted file mode 100644 index 78e830d7c8f..00000000000 --- a/apps/files_versions/ajax/preview.php +++ /dev/null @@ -1,66 +0,0 @@ - - * @author Morris Jobke - * @author Roeland Jago Douma - * @author Thomas Müller - * @author Vincent Petry - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -\OC_Util::checkLoggedIn(); - -if(!\OC_App::isEnabled('files_versions')){ - exit; -} - -$file = array_key_exists('file', $_GET) ? (string) urldecode($_GET['file']) : ''; -$maxX = array_key_exists('x', $_GET) ? (int) $_GET['x'] : 44; -$maxY = array_key_exists('y', $_GET) ? (int) $_GET['y'] : 44; -$version = array_key_exists('version', $_GET) ? $_GET['version'] : ''; -$scalingUp = array_key_exists('scalingup', $_GET) ? (bool) $_GET['scalingup'] : true; - -if($file === '' && $version === '') { - \OC_Response::setStatus(400); //400 Bad Request - \OCP\Util::writeLog('versions-preview', 'No file parameter was passed', \OCP\Util::DEBUG); - exit; -} - -if($maxX === 0 || $maxY === 0) { - \OC_Response::setStatus(400); //400 Bad Request - \OCP\Util::writeLog('versions-preview', 'x and/or y set to 0', \OCP\Util::DEBUG); - exit; -} - -try { - list($user, $file) = \OCA\Files_Versions\Storage::getUidAndFilename($file); - $preview = new \OC\Preview($user, 'files_versions', $file.'.v'.$version); - $mimetype = \OC::$server->getMimeTypeDetector()->detectPath($file); - $preview->setMimetype($mimetype); - $preview->setMaxX($maxX); - $preview->setMaxY($maxY); - $preview->setScalingUp($scalingUp); - - $preview->showPreview(); -} catch (\OCP\Files\NotFoundException $e) { - \OC_Response::setStatus(404); - \OCP\Util::writeLog('core', $e->getmessage(), \OCP\Util::DEBUG); -} catch (\Exception $e) { - \OC_Response::setStatus(500); - \OCP\Util::writeLog('core', $e->getmessage(), \OCP\Util::DEBUG); -} diff --git a/apps/files_versions/appinfo/routes.php b/apps/files_versions/appinfo/routes.php index c2b686c38f3..434ff9d26ac 100644 --- a/apps/files_versions/appinfo/routes.php +++ b/apps/files_versions/appinfo/routes.php @@ -1,6 +1,7 @@ * * @author Björn Schießle * @author Jörn Friedrich Dreyer @@ -29,13 +30,17 @@ namespace OCA\Files_Versions\AppInfo; $application = new Application(); +$application->registerRoutes($this, [ + 'routes' => [ + [ + 'name' => 'Preview#getPreview', + 'url' => '/preview', + 'verb' => 'GET', + ], + ], +]); /** @var $this \OCP\Route\IRouter */ -$this->create('core_ajax_versions_preview', '/preview')->action( -function() { - require_once __DIR__ . '/../ajax/preview.php'; -}); - $this->create('files_versions_download', 'download.php') ->actionInclude('files_versions/download.php'); $this->create('files_versions_ajax_getVersions', 'ajax/getVersions.php') diff --git a/apps/files_versions/lib/Controller/PreviewController.php b/apps/files_versions/lib/Controller/PreviewController.php new file mode 100644 index 00000000000..3225febfcff --- /dev/null +++ b/apps/files_versions/lib/Controller/PreviewController.php @@ -0,0 +1,111 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OCA\Files_Versions\Controller; + +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\Http\FileDisplayResponse; +use OCP\Files\File; +use OCP\Files\Folder; +use OCP\Files\IMimeTypeDetector; +use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\IPreview; +use OCP\IRequest; + +class PreviewController extends Controller { + + /** @var IRootFolder */ + private $rootFolder; + + /** @var string */ + private $userId; + + /** @var IMimeTypeDetector */ + private $mimeTypeDetector; + + /** @var IPreview */ + private $previewManager; + + public function __construct($appName, + IRequest $request, + IRootFolder $rootFolder, + $userId, + IMimeTypeDetector $mimeTypeDetector, + IPreview $previewManager) { + parent::__construct($appName, $request); + + $this->rootFolder = $rootFolder; + $this->userId = $userId; + $this->mimeTypeDetector = $mimeTypeDetector; + $this->previewManager = $previewManager; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + * @param string $file + * @param int $x + * @param int $y + * @param string $version + * @return DataResponse|FileDisplayResponse + */ + public function getPreview( + $file = '', + $x = 44, + $y = 44, + $version = '' + ) { + if($file === '' && $version === '') { + return new DataResponse([], Http::STATUS_BAD_REQUEST); + } + + if($x === 0 || $y === 0) { + return new DataResponse([], Http::STATUS_BAD_REQUEST); + } + + try { + $userFolder = $this->rootFolder->getUserFolder($this->userId); + /** @var Folder $versionFolder */ + $versionFolder = $userFolder->getParent()->get('files_versions'); + $mimeType = $this->mimeTypeDetector->detectPath($file); + $file = $versionFolder->get($file.'.v'.$version); + + if ($file instanceof Folder) { + return new DataResponse([], Http::STATUS_BAD_REQUEST); + } + + /** @var File $file */ + $f = $this->previewManager->getPreview($file, $x, $y, true, IPreview::MODE_FILL, $mimeType); + + return new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]); + } catch (NotFoundException $e) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } catch (\Exception $e) { + return new DataResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); + } + + } +} diff --git a/apps/files_versions/lib/Storage.php b/apps/files_versions/lib/Storage.php index cf0e09f64ca..e7c2c8b7593 100644 --- a/apps/files_versions/lib/Storage.php +++ b/apps/files_versions/lib/Storage.php @@ -462,7 +462,7 @@ class Storage { if (empty($userFullPath)) { $versions[$key]['preview'] = ''; } else { - $versions[$key]['preview'] = \OCP\Util::linkToRoute('core_ajax_versions_preview', array('file' => $userFullPath, 'version' => $timestamp)); + $versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]); } $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename); $versions[$key]['name'] = $versionedFile; diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php index ea162926afa..d4c38b1cb6a 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -76,11 +76,15 @@ class Generator { * @param int $height * @param bool $crop * @param string $mode + * @param string $mimeType * @return ISimpleFile * @throws NotFoundException */ - public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL) { - if (!$this->previewManager->isMimeSupported($file->getMimeType())) { + public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) { + if ($mimeType === null) { + $mimeType = $file->getMimeType(); + } + if (!$this->previewManager->isMimeSupported($mimeType)) { throw new NotFoundException(); } @@ -91,7 +95,7 @@ class Generator { $previewFolder = $this->getPreviewFolder($file); // Get the max preview and infer the max preview sizes from that - $maxPreview = $this->getMaxPreview($previewFolder, $file); + $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType); list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview); // Calculate the preview size @@ -110,10 +114,11 @@ class Generator { /** * @param ISimpleFolder $previewFolder * @param File $file + * @param string $mimeType * @return ISimpleFile * @throws NotFoundException */ - private function getMaxPreview(ISimpleFolder $previewFolder, File $file) { + private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) { $nodes = $previewFolder->getDirectoryListing(); foreach ($nodes as $node) { @@ -124,7 +129,7 @@ class Generator { $previewProviders = $this->previewManager->getProviders(); foreach ($previewProviders as $supportedMimeType => $providers) { - if (!preg_match($supportedMimeType, $file->getMimeType())) { + if (!preg_match($supportedMimeType, $mimeType)) { continue; } diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index 0cda55751bf..2c17a5f3c80 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -151,11 +151,12 @@ class PreviewManager implements IPreview { * @param int $height * @param bool $crop * @param string $mode + * @param string $mimeType * @return ISimpleFile * @throws NotFoundException * @since 9.2.0 */ - public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL) { + public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) { if ($this->generator === null) { $this->generator = new Generator( $this->rootFolder, @@ -165,7 +166,7 @@ class PreviewManager implements IPreview { ); } - return $this->generator->getPreview($file, $width, $height, $crop, $mode); + return $this->generator->getPreview($file, $width, $height, $crop, $mode, $mimeType); } /** diff --git a/lib/public/IPreview.php b/lib/public/IPreview.php index 0942db4784c..c6417b4d182 100644 --- a/lib/public/IPreview.php +++ b/lib/public/IPreview.php @@ -96,11 +96,12 @@ interface IPreview { * @param int $height * @param bool $crop * @param string $mode + * @param string $mimeType To force a given mimetype for the file (files_versions needs this) * @return ISimpleFile * @throws NotFoundException * @since 9.2.0 */ - public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL); + public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null); /** * Returns true if the passed mime type is supported -- cgit v1.2.3 From 87855aa97b0d90f8036ec40174ac1a3dcbd463e8 Mon Sep 17 00:00:00 2001 From: Roeland Jago Douma Date: Mon, 17 Oct 2016 21:53:23 +0200 Subject: Added genertor helper & tests Signed-off-by: Roeland Jago Douma --- apps/files/tests/Controller/ApiControllerTest.php | 45 ++- lib/composer/composer/autoload_classmap.php | 1 + lib/composer/composer/autoload_static.php | 1 + lib/private/Preview/Generator.php | 44 +-- lib/private/Preview/GeneratorHelper.php | 91 ++++++ lib/private/PreviewManager.php | 7 +- tests/lib/Preview/GeneratorTest.php | 338 ++++++++++++++++++++++ 7 files changed, 477 insertions(+), 50 deletions(-) create mode 100644 lib/private/Preview/GeneratorHelper.php create mode 100644 tests/lib/Preview/GeneratorTest.php (limited to 'lib/private') diff --git a/apps/files/tests/Controller/ApiControllerTest.php b/apps/files/tests/Controller/ApiControllerTest.php index 4b7bec065a0..56d0f6c8dee 100644 --- a/apps/files/tests/Controller/ApiControllerTest.php +++ b/apps/files/tests/Controller/ApiControllerTest.php @@ -28,11 +28,15 @@ namespace OCA\Files\Controller; use OC\Files\FileInfo; use OCP\AppFramework\Http; +use OCP\Files\File; +use OCP\Files\Folder; use OCP\Files\NotFoundException; +use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\StorageNotAvailableException; use OCP\IConfig; use OCP\IUser; use OCP\IUserSession; +use OCP\Share\IManager; use Test\TestCase; use OCP\IRequest; use OCA\Files\Service\TagService; @@ -54,7 +58,7 @@ class ApiControllerTest extends TestCase { private $request; /** @var TagService */ private $tagService; - /** @var IPreview */ + /** @var IPreview|\PHPUnit_Framework_MockObject_MockObject */ private $preview; /** @var ApiController */ private $apiController; @@ -62,11 +66,13 @@ class ApiControllerTest extends TestCase { private $shareManager; /** @var \OCP\IConfig */ private $config; - /** @var \OC\Files\Node\Folder */ + /** @var Folder|\PHPUnit_Framework_MockObject_MockObject */ private $userFolder; public function setUp() { - $this->request = $this->getMockBuilder('\OCP\IRequest') + parent::setUp(); + + $this->request = $this->getMockBuilder(IRequest::class) ->disableOriginalConstructor() ->getMock(); $this->user = $this->createMock(IUser::class); @@ -77,17 +83,17 @@ class ApiControllerTest extends TestCase { $userSession->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $this->tagService = $this->getMockBuilder('\OCA\Files\Service\TagService') + $this->tagService = $this->getMockBuilder(TagService::class) ->disableOriginalConstructor() ->getMock(); - $this->shareManager = $this->getMockBuilder('\OCP\Share\IManager') + $this->shareManager = $this->getMockBuilder(IManager::class) ->disableOriginalConstructor() ->getMock(); - $this->preview = $this->getMockBuilder('\OCP\IPreview') + $this->preview = $this->getMockBuilder(IPreview::class) ->disableOriginalConstructor() ->getMock(); $this->config = $this->createMock(IConfig::class); - $this->userFolder = $this->getMockBuilder('\OC\Files\Node\Folder') + $this->userFolder = $this->getMockBuilder(Folder::class) ->disableOriginalConstructor() ->getMock(); @@ -153,28 +159,41 @@ class ApiControllerTest extends TestCase { } public function testGetThumbnailInvalidSize() { + $this->userFolder->method('get') + ->with($this->equalTo('')) + ->willThrowException(new NotFoundException()); $expected = new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST); $this->assertEquals($expected, $this->apiController->getThumbnail(0, 0, '')); } public function testGetThumbnailInvaidImage() { + $file = $this->createMock(File::class); + $this->userFolder->method('get') + ->with($this->equalTo('unknown.jpg')) + ->willReturn($file); $this->preview->expects($this->once()) - ->method('createPreview') - ->with('files/unknown.jpg', 10, 10, true) - ->willReturn(new Image); + ->method('getPreview') + ->with($file, 10, 10, true) + ->willThrowException(new NotFoundException()); $expected = new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND); $this->assertEquals($expected, $this->apiController->getThumbnail(10, 10, 'unknown.jpg')); } public function testGetThumbnail() { + $file = $this->createMock(File::class); + $this->userFolder->method('get') + ->with($this->equalTo('known.jpg')) + ->willReturn($file); + $preview = $this->createMock(ISimpleFile::class); $this->preview->expects($this->once()) - ->method('createPreview') - ->with('files/known.jpg', 10, 10, true) - ->willReturn(new Image(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); + ->method('getPreview') + ->with($this->equalTo($file), 10, 10, true) + ->willReturn($preview); $ret = $this->apiController->getThumbnail(10, 10, 'known.jpg'); $this->assertEquals(Http::STATUS_OK, $ret->getStatus()); + $this->assertInstanceOf(Http\FileDisplayResponse::class, $ret); } public function testUpdateFileSorting() { diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 19905bdbe7b..42cfb8c45e1 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -622,6 +622,7 @@ return array( 'OC\\Preview\\Font' => $baseDir . '/lib/private/Preview/Font.php', 'OC\\Preview\\GIF' => $baseDir . '/lib/private/Preview/GIF.php', 'OC\\Preview\\Generator' => $baseDir . '/lib/private/Preview/Generator.php', + 'OC\\Preview\\GeneratorHelper' => $baseDir . '/lib/private/Preview/GeneratorHelper.php', 'OC\\Preview\\Illustrator' => $baseDir . '/lib/private/Preview/Illustrator.php', 'OC\\Preview\\Image' => $baseDir . '/lib/private/Preview/Image.php', 'OC\\Preview\\JPEG' => $baseDir . '/lib/private/Preview/JPEG.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index 82dba9c92f5..d7e937577f2 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -652,6 +652,7 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c 'OC\\Preview\\Font' => __DIR__ . '/../../..' . '/lib/private/Preview/Font.php', 'OC\\Preview\\GIF' => __DIR__ . '/../../..' . '/lib/private/Preview/GIF.php', 'OC\\Preview\\Generator' => __DIR__ . '/../../..' . '/lib/private/Preview/Generator.php', + 'OC\\Preview\\GeneratorHelper' => __DIR__ . '/../../..' . '/lib/private/Preview/GeneratorHelper.php', 'OC\\Preview\\Illustrator' => __DIR__ . '/../../..' . '/lib/private/Preview/Illustrator.php', 'OC\\Preview\\Image' => __DIR__ . '/../../..' . '/lib/private/Preview/Image.php', 'OC\\Preview\\JPEG' => __DIR__ . '/../../..' . '/lib/private/Preview/JPEG.php', diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php index d4c38b1cb6a..3d4e9bf3677 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -23,46 +23,43 @@ namespace OC\Preview; -use OC\Files\View; use OCP\Files\File; use OCP\Files\IAppData; -use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; -use OCP\Image as img; use OCP\IPreview; use OCP\Preview\IProvider; class Generator { - /** @var IRootFolder*/ - private $rootFolder; /** @var IPreview */ private $previewManager; /** @var IConfig */ private $config; /** @var IAppData */ private $appData; + /** @var GeneratorHelper */ + private $helper; /** - * @param IRootFolder $rootFolder * @param IConfig $config * @param IPreview $previewManager * @param IAppData $appData + * @param GeneratorHelper $helper */ public function __construct( - IRootFolder $rootFolder, IConfig $config, IPreview $previewManager, - IAppData $appData + IAppData $appData, + GeneratorHelper $helper ) { - $this->rootFolder = $rootFolder; $this->config = $config; $this->previewManager = $previewManager; $this->appData = $appData; + $this->helper = $helper; } /** @@ -88,10 +85,6 @@ class Generator { throw new NotFoundException(); } - /* - * Get the preview folder - * TODO: Separate preview creation from storing previews - */ $previewFolder = $this->getPreviewFolder($file); // Get the max preview and infer the max preview sizes from that @@ -134,17 +127,15 @@ class Generator { } foreach ($providers as $provider) { - $provider = $provider(); + $provider = $this->helper->getProvider($provider); if (!($provider instanceof IProvider)) { continue; } - list($view, $path) = $this->getViewAndPath($file); - $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048); $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048); - $preview = $provider->getThumbnail($path, $maxWidth, $maxHeight, false, $view); + $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight); if (!($preview instanceof IImage)) { continue; @@ -185,24 +176,7 @@ class Generator { return $path; } - /** - * @param File $file - * @return array - * This is required to create the old view and path - */ - private function getViewAndPath(File $file) { - $owner = $file->getOwner()->getUID(); - - $userFolder = $this->rootFolder->getUserFolder($owner)->getParent(); - $nodes = $userFolder->getById($file->getId()); - - $file = $nodes[0]; - $view = new View($userFolder->getPath()); - $path = $userFolder->getRelativePath($file->getPath()); - - return [$view, $path]; - } /** * @param int $width @@ -300,7 +274,7 @@ class Generator { * @throws NotFoundException */ private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) { - $preview = new img($maxPreview->getContent()); + $preview = $this->helper->getImage($maxPreview); if ($crop) { if ($height !== $preview->height() && $width !== $preview->width()) { diff --git a/lib/private/Preview/GeneratorHelper.php b/lib/private/Preview/GeneratorHelper.php new file mode 100644 index 00000000000..282c46a2a5d --- /dev/null +++ b/lib/private/Preview/GeneratorHelper.php @@ -0,0 +1,91 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OC\Preview; + +use OC\Files\View; +use OCP\Files\File; +use OCP\Files\IRootFolder; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\IImage; +use OCP\Image as img; +use OCP\Preview\IProvider; + +/** + * Very small wrapper class to make the generator fully unit testable + */ +class GeneratorHelper { + + /** @var IRootFolder */ + private $rootFolder; + + public function __construct(IRootFolder $rootFolder) { + $this->rootFolder = $rootFolder; + } + + /** + * @param IProvider $provider + * @param File $file + * @param int $maxWidth + * @param int $maxHeight + * @return bool|IImage + */ + public function getThumbnail(IProvider $provider, File $file, $maxWidth, $maxHeight) { + list($view, $path) = $this->getViewAndPath($file); + return $provider->getThumbnail($path, $maxWidth, $maxHeight, false, $view); + } + + /** + * @param File $file + * @return array + * This is required to create the old view and path + */ + private function getViewAndPath(File $file) { + $owner = $file->getOwner()->getUID(); + + $userFolder = $this->rootFolder->getUserFolder($owner)->getParent(); + + $nodes = $userFolder->getById($file->getId()); + $file = $nodes[0]; + + $view = new View($userFolder->getPath()); + $path = $userFolder->getRelativePath($file->getPath()); + + return [$view, $path]; + } + + /** + * @param ISimpleFile $maxPreview + * @return IImage + */ + public function getImage(ISimpleFile $maxPreview) { + return new img($maxPreview->getContent()); + } + + /** + * @param $provider + * @return IProvider + */ + public function getProvider($provider) { + return $provider(); + } +} diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index 2c17a5f3c80..a2ef9659b3b 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -26,6 +26,7 @@ namespace OC; use OC\Preview\Generator; +use OC\Preview\GeneratorHelper; use OCP\Files\File; use OCP\Files\IAppData; use OCP\Files\IRootFolder; @@ -159,10 +160,12 @@ class PreviewManager implements IPreview { public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) { if ($this->generator === null) { $this->generator = new Generator( - $this->rootFolder, $this->config, $this, - $this->appData + $this->appData, + new GeneratorHelper( + $this->rootFolder + ) ); } diff --git a/tests/lib/Preview/GeneratorTest.php b/tests/lib/Preview/GeneratorTest.php new file mode 100644 index 00000000000..d64a0b912e1 --- /dev/null +++ b/tests/lib/Preview/GeneratorTest.php @@ -0,0 +1,338 @@ + + * + * @author Roeland Jago Douma + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace Test\Preview; + +use OC\Preview\Generator; +use OC\Preview\GeneratorHelper; +use OCP\Files\File; +use OCP\Files\IAppData; +use OCP\Files\NotFoundException; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\SimpleFS\ISimpleFolder; +use OCP\IConfig; +use OCP\IImage; +use OCP\IPreview; +use OCP\Preview\IProvider; + +class GeneratorTest extends \Test\TestCase { + + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ + private $config; + + /** @var IPreview|\PHPUnit_Framework_MockObject_MockObject */ + private $previewManager; + + /** @var IAppData|\PHPUnit_Framework_MockObject_MockObject */ + private $appData; + + /** @var GeneratorHelper|\PHPUnit_Framework_MockObject_MockObject */ + private $helper; + + /** @var Generator */ + private $generator; + + public function setUp() { + parent::setUp(); + + $this->config = $this->createMock(IConfig::class); + $this->previewManager = $this->createMock(IPreview::class); + $this->appData = $this->createMock(IAppData::class); + $this->helper = $this->createMock(GeneratorHelper::class); + + $this->generator = new Generator( + $this->config, + $this->previewManager, + $this->appData, + $this->helper + ); + } + + public function testGetCachedPreview() { + $file = $this->createMock(File::class); + $file->method('getMimeType') + ->willReturn('myMimeType'); + $file->method('getId') + ->willReturn(42); + + $this->previewManager->method('isMimeSupported') + ->with($this->equalTo('myMimeType')) + ->willReturn(true); + + $previewFolder = $this->createMock(ISimpleFolder::class); + $this->appData->method('getFolder') + ->with($this->equalTo(42)) + ->willReturn($previewFolder); + + $maxPreview = $this->createMock(ISimpleFile::class); + $maxPreview->method('getName') + ->willReturn('1000-1000-max.png'); + + $previewFolder->method('getDirectoryListing') + ->willReturn([$maxPreview]); + + $previewFile = $this->createMock(ISimpleFile::class); + + $previewFolder->method('getFile') + ->with($this->equalTo('128-128.png')) + ->willReturn($previewFile); + + $result = $this->generator->getPreview($file, 100, 100); + $this->assertSame($previewFile, $result); + } + + public function testGetNewPreview() { + $file = $this->createMock(File::class); + $file->method('getMimeType') + ->willReturn('myMimeType'); + $file->method('getId') + ->willReturn(42); + + $this->previewManager->method('isMimeSupported') + ->with($this->equalTo('myMimeType')) + ->willReturn(true); + + $previewFolder = $this->createMock(ISimpleFolder::class); + $this->appData->method('getFolder') + ->with($this->equalTo(42)) + ->willThrowException(new NotFoundException()); + + $this->appData->method('newFolder') + ->with($this->equalTo(42)) + ->willReturn($previewFolder); + + $this->config->method('getSystemValue') + ->will($this->returnCallback(function($key, $defult) { + return $defult; + })); + + $invalidProvider = $this->createMock(IProvider::class); + $validProvider = $this->createMock(IProvider::class); + + $this->previewManager->method('getProviders') + ->willReturn([ + '/image\/png/' => ['wrongProvider'], + '/myMimeType/' => ['brokenProvider', 'invalidProvider', 'validProvider'], + ]); + + $this->helper->method('getProvider') + ->will($this->returnCallback(function($provider) use ($invalidProvider, $validProvider) { + if ($provider === 'wrongProvider') { + $this->fail('Wrongprovider should not be constructed!'); + } else if ($provider === 'brokenProvider') { + return false; + } else if ($provider === 'invalidProvider') { + return $invalidProvider; + } else if ($provider === 'validProvider') { + return $validProvider; + } + $this->fail('Unexpected provider requested'); + })); + + $image = $this->createMock(IImage::class); + $image->method('width')->willReturn(2048); + $image->method('height')->willReturn(2048); + + $this->helper->method('getThumbnail') + ->will($this->returnCallback(function ($provider, $file, $x, $y) use ($invalidProvider, $validProvider, $image) { + if ($provider === $validProvider) { + return $image; + } else { + return false; + } + })); + + $image->method('data') + ->willReturn('my data'); + + $maxPreview = $this->createMock(ISimpleFile::class); + $maxPreview->method('getName')->willReturn('2048-2048-max.png'); + + $previewFile = $this->createMock(ISimpleFile::class); + + $previewFolder->method('getDirectoryListing') + ->willReturn([]); + $previewFolder->method('newFile') + ->will($this->returnCallback(function($filename) use ($maxPreview, $previewFile) { + if ($filename === '2048-2048-max.png') { + return $maxPreview; + } else if ($filename === '128-128.png') { + return $previewFile; + } + $this->fail('Unexpected file'); + })); + + $maxPreview->expects($this->once()) + ->method('putContent') + ->with($this->equalTo('my data')); + + $previewFolder->method('getFile') + ->with($this->equalTo('128-128.png')) + ->willThrowException(new NotFoundException()); + + $image = $this->createMock(IImage::class); + $this->helper->method('getImage') + ->with($this->equalTo($maxPreview)) + ->willReturn($image); + + $image->expects($this->once()) + ->method('resize') + ->with(128); + $image->method('data') + ->willReturn('my resized data'); + + $previewFile->expects($this->once()) + ->method('putContent') + ->with('my resized data'); + + $result = $this->generator->getPreview($file, 100, 100); + $this->assertSame($previewFile, $result); + } + + public function testInvalidMimeType() { + $this->expectException(NotFoundException::class); + + $file = $this->createMock(File::class); + + $this->previewManager->method('isMimeSupported') + ->with('invalidType') + ->willReturn(false); + + $this->generator->getPreview($file, 0, 0, true, IPreview::MODE_COVER, 'invalidType'); + } + + public function testNoProvider() { + $file = $this->createMock(File::class); + $file->method('getMimeType') + ->willReturn('myMimeType'); + $file->method('getId') + ->willReturn(42); + + $this->previewManager->method('isMimeSupported') + ->with($this->equalTo('myMimeType')) + ->willReturn(true); + + $previewFolder = $this->createMock(ISimpleFolder::class); + $this->appData->method('getFolder') + ->with($this->equalTo(42)) + ->willReturn($previewFolder); + + $previewFolder->method('getDirectoryListing') + ->willReturn([]); + + $this->previewManager->method('getProviders') + ->willReturn([]); + + $this->expectException(NotFoundException::class); + $this->generator->getPreview($file, 100, 100); + } + + public function dataSize() { + return [ + [1024, 2048, 512, 512, false, IPreview::MODE_FILL, 256, 512], + [1024, 2048, 512, 512, false, IPreview::MODE_COVER, 512, 1024], + [1024, 2048, 512, 512, true, IPreview::MODE_FILL, 512, 512], + [1024, 2048, 512, 512, true, IPreview::MODE_COVER, 512, 512], + + [1024, 2048, -1, 512, false, IPreview::MODE_COVER, 256, 512], + [1024, 2048, 512, -1, false, IPreview::MODE_FILL, 512, 1024], + + [1024, 2048, 250, 1100, true, IPreview::MODE_COVER, 256, 1126], + [1024, 1100, 250, 1100, true, IPreview::MODE_COVER, 250, 1100], + + [1024, 2048, 4096, 2048, false, IPreview::MODE_FILL, 1024, 2048], + [1024, 2048, 4096, 2048, false, IPreview::MODE_COVER, 1024, 2048], + + + [2048, 1024, 512, 512, false, IPreview::MODE_FILL, 512, 256], + [2048, 1024, 512, 512, false, IPreview::MODE_COVER, 1024, 512], + [2048, 1024, 512, 512, true, IPreview::MODE_FILL, 512, 512], + [2048, 1024, 512, 512, true, IPreview::MODE_COVER, 512, 512], + + [2048, 1024, -1, 512, false, IPreview::MODE_FILL, 1024, 512], + [2048, 1024, 512, -1, false, IPreview::MODE_COVER, 512, 256], + + [2048, 1024, 4096, 1024, true, IPreview::MODE_FILL, 2048, 512], + [2048, 1024, 4096, 1024, true, IPreview::MODE_COVER, 2048, 512], + ]; + } + + /** + * @dataProvider dataSize + * + * @param int $maxX + * @param int $maxY + * @param int $reqX + * @param int $reqY + * @param bool $crop + * @param string $mode + * @param int $expectedX + * @param int $expectedY + */ + public function testCorrectSize($maxX, $maxY, $reqX, $reqY, $crop, $mode, $expectedX, $expectedY) { + $file = $this->createMock(File::class); + $file->method('getMimeType') + ->willReturn('myMimeType'); + $file->method('getId') + ->willReturn(42); + + $this->previewManager->method('isMimeSupported') + ->with($this->equalTo('myMimeType')) + ->willReturn(true); + + $previewFolder = $this->createMock(ISimpleFolder::class); + $this->appData->method('getFolder') + ->with($this->equalTo(42)) + ->willReturn($previewFolder); + + $maxPreview = $this->createMock(ISimpleFile::class); + $maxPreview->method('getName') + ->willReturn($maxX . '-' . $maxY . '-max.png'); + + $previewFolder->method('getDirectoryListing') + ->willReturn([$maxPreview]); + + $filename = $expectedX . '-' . $expectedY; + if ($crop) { + $filename .= '-crop'; + } + $filename .= '.png'; + $previewFolder->method('getFile') + ->with($this->equalTo($filename)) + ->willThrowException(new NotFoundException()); + + $image = $this->createMock(IImage::class); + $this->helper->method('getImage') + ->with($this->equalTo($maxPreview)) + ->willReturn($image); + $image->method('height')->willReturn($maxY); + $image->method('width')->willReturn($maxX); + + $preview = $this->createMock(ISimpleFile::class); + $previewFolder->method('newFile') + ->with($this->equalTo($filename)) + ->willReturn($preview); + + $result = $this->generator->getPreview($file, $reqX, $reqY, $crop, $mode); + $this->assertSame($preview, $result); + } +} -- cgit v1.2.3