Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement square and uncropped sizes config #524

Merged
merged 2 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 48 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,45 @@ are running on the time this takes can vary.

## Commands

### preview:generate-all [--path=PATH ...] [user_id ...]
#### `preview:generate-all [--path=PATH ...] [user_id ...]`

Loop over all files and try to generate previews for them. If one or multiple user ids are supplied
it will just loop over the files of those users. You can also limit the generation to one or more
paths using `--path="/[username]/files/[folder path]"`, e.g. `--path="/alice/files/Photos"`. Note that
all given user_ids are ignored if at least one path is specified.
paths using `--path="/[username]/files/[folder path]"`, e.g. `--path="/alice/files/Photos"`. Note
that all given user_ids are ignored if at least one path is specified.

### preview:pre-generate
#### `preview:pre-generate`

Do the actual pre-generation. This means only for new or modified files (since the app was enabled
or the last pre-generation was done).

Use `<command> -vv` to get a more verbose output if you are interested to see which files are being
processed.

## Available configuration options

The value of each option can either be a list of sizes separated by **spaces** or an empty string.
Setting an empty string will simply skip those kinds of previews.
Deleting or not setting a config will use a built-in default list of values for those previews.

* Preview sizes must be a power of 4! Other sizes are silently ignored.
* The smallest possible size is 64.
* The max size is determined by your `preview_max_x` and `preview_max_y` settings in `config.php`.

#### `occ config:app:set --value="64 256" previewgenerator squareSizes`
Cropped square previews which are mostly used in the list and tile views of the files app.

#### `occ config:app:set --value="256 4096" previewgenerator squareUncroppedSizes`
Will retain the aspect ratio and try to maximize **either** width **or** height.

#### `occ config:app:set --value="64 256 1024" previewgenerator widthSizes`
Will retain the aspect ratio and use the specified width. The height will be scaled according to
the aspect ratio.

#### `occ config:app:set --value="64 256 1024" previewgenerator heightSizes`
Will retain the aspect ratio and use the specified height. The width will be scaled according to
the aspect ratio.

Do the actual pregeneration. This means only for new or modified files (since
the app was enabled or the last pregeneration was done).

## FAQ

Expand All @@ -75,28 +103,25 @@ Follow [these instructions](https://github.com/nextcloud/all-in-one/discussions/

### I don't want to generate all the preview sizes

This is possible since version 1.0.8. Just set the correct values via the command line
The following options are recommended if you only want to generate a minimum set of required
previews.
This should include all previews requested by the files, photos and activity apps.

```
./occ config:app:set --value="64 256 1024" previewgenerator squareSizes
./occ config:app:set --value="64 256 1024" previewgenerator widthSizes
./occ config:app:set --value="64 256 1024" previewgenerator heightSizes
./occ config:app:set --value="64 256" previewgenerator squareSizes
./occ config:app:set --value="256 4096" previewgenerator squareUncroppedSizes
./occ config:app:set --value="" previewgenerator widthSizes
./occ config:app:set --value="" previewgenerator heightSizes
```

This will only generate:
* square previews of: 64x64, 256x256 and 1024x1024
* aspect ratio previews with a width of: 64, 256 and 1024
* aspect ratio previews with a height of: 64, 256 and 1024

Note:
* preview sizes are always a power of 4.
* The smallest size is 64
* The max size is determined by your preview settings in config.php

### I get "PHP Fatal error: Allowed memory size of X bytes exhausted"
You need to increase the memory allowance of PHP, by default it is 128 MB. You do that by changing the memory_limit in the php.ini file.

If you use [the docker container](https://github.com/nextcloud/docker) you need set the environment variable `PHP_MEMORY_LIMIT` instead.
* Cropped square previews of: 64x64 and 256x256
* Aspect ratio previews with a max width **or** max height of: 256 and 4096

### I get "PHP Fatal error: Allowed memory size of X bytes exhausted"
You need to increase the memory allowance of PHP, by default it is 128 MB. You do that by changing the memory_limit in the php.ini file.

If you use [the docker container](https://github.com/nextcloud/docker) you need set the environment variable `PHP_MEMORY_LIMIT` instead.

### I want to skip a folder and everything in/under it

Expand Down
28 changes: 12 additions & 16 deletions lib/Command/Generate.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,28 +50,33 @@
use Symfony\Component\Console\Output\OutputInterface;

class Generate extends Command {
protected ?GlobalStoragesService $globalService;
/* @return array{width: int, height: int, crop: bool} */
protected array $specifications;

protected ?GlobalStoragesService $globalService;
protected IUserManager $userManager;
protected IRootFolder $rootFolder;
protected IPreview $previewGenerator;
protected IConfig $config;
protected OutputInterface $output;
protected IManager $encryptionManager;
protected SizeHelper $sizeHelper;

public function __construct(IRootFolder $rootFolder,
IUserManager $userManager,
IPreview $previewGenerator,
IConfig $config,
IManager $encryptionManager,
ContainerInterface $container) {
ContainerInterface $container,
SizeHelper $sizeHelper) {
parent::__construct();

$this->userManager = $userManager;
$this->rootFolder = $rootFolder;
$this->previewGenerator = $previewGenerator;
$this->config = $config;
$this->encryptionManager = $encryptionManager;
$this->sizeHelper = $sizeHelper;

try {
$this->globalService = $container->get(GlobalStoragesService::class);
Expand Down Expand Up @@ -107,19 +112,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$output->setFormatter($formatter);
$this->output = $output;

// Generate preview specifications once
$sizes = SizeHelper::calculateSizes($this->config);
$this->specifications = array_merge(
array_map(static function ($squareSize) {
return ['width' => $squareSize, 'height' => $squareSize, 'crop' => true];
}, $sizes['square']),
array_map(static function ($heightSize) {
return ['width' => -1, 'height' => $heightSize, 'crop' => false];
}, $sizes['height']),
array_map(static function ($widthSize) {
return ['width' => $widthSize, 'height' => -1, 'crop' => false];
}, $sizes['width'])
);
$this->specifications = $this->sizeHelper->generateSpecifications();
if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_VERY_VERBOSE) {
$output->writeln('Specifications: ' . json_encode($this->specifications));
}

$inputPaths = $input->getOption('path');
if ($inputPaths) {
Expand Down Expand Up @@ -162,7 +158,7 @@ private function getNoPreviewMountPaths(IUser $user): array {
$mount->getMountOptions()['previews'] === false
) {
$userFolder = $this->rootFolder->getUserFolder($userId)->getPath();
array_push($mountPaths, $userFolder.$mount->getMountPoint());
array_push($mountPaths, $userFolder . $mount->getMountPoint());
}
}
return $mountPaths;
Expand Down
27 changes: 11 additions & 16 deletions lib/Command/PreGenerate.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
use Symfony\Component\Console\Output\OutputInterface;

class PreGenerate extends Command {
/** @var int[][] */
protected array $sizes;
/* @return array{width: int, height: int, crop: bool} */
protected array $specifications;

protected string $appName;
protected IUserManager $userManager;
Expand All @@ -57,6 +57,7 @@ class PreGenerate extends Command {
protected IManager $encryptionManager;
protected ITimeFactory $time;
protected NoMediaService $noMediaService;
protected SizeHelper $sizeHelper;

/**
* @param string $appName
Expand All @@ -76,7 +77,8 @@ public function __construct(string $appName,
IDBConnection $connection,
IManager $encryptionManager,
ITimeFactory $time,
NoMediaService $noMediaService) {
NoMediaService $noMediaService,
SizeHelper $sizeHelper) {
parent::__construct();

$this->appName = $appName;
Expand All @@ -88,6 +90,7 @@ public function __construct(string $appName,
$this->encryptionManager = $encryptionManager;
$this->time = $time;
$this->noMediaService = $noMediaService;
$this->sizeHelper = $sizeHelper;
}

protected function configure(): void {
Expand All @@ -114,7 +117,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$output->setFormatter($formatter);
$this->output = $output;

$this->sizes = SizeHelper::calculateSizes($this->config);
$this->specifications = $this->sizeHelper->generateSpecifications();
if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_VERY_VERBOSE) {
$output->writeln('Specifications: ' . json_encode($this->specifications));
}
$this->startProcessing();

$this->clearPID();
Expand Down Expand Up @@ -200,18 +206,7 @@ private function processFile(File $file): void {
}

try {
$specifications = array_merge(
array_map(static function ($squareSize) {
return ['width' => $squareSize, 'height' => $squareSize, 'crop' => true];
}, $this->sizes['square']),
array_map(static function ($heightSize) {
return ['width' => -1, 'height' => $heightSize, 'crop' => false];
}, $this->sizes['height']),
array_map(static function ($widthSize) {
return ['width' => $widthSize, 'height' => -1, 'crop' => false];
}, $this->sizes['width'])
);
$this->previewGenerator->generatePreviews($file, $specifications);
$this->previewGenerator->generatePreviews($file, $this->specifications);
} catch (NotFoundException $e) {
// Maybe log that previews could not be generated?
} catch (\InvalidArgumentException|GenericFileException $e) {
Expand Down
79 changes: 61 additions & 18 deletions lib/SizeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,30 +27,37 @@

namespace OCA\PreviewGenerator;

use OCA\PreviewGenerator\AppInfo\Application;
use OCP\IConfig;

class SizeHelper {
public function __construct(
private IConfig $config,
) {
}

/**
* @param IConfig $config
* @return int[][]
* @return array{width: int, height: int, crop: bool}
*/
public static function calculateSizes(IConfig $config): array {
public function generateSpecifications(): array {
/*
* First calculate the systems max sizes
*/

$sizes = [
'square' => [],
'squareUncropped' => [],
'height' => [],
'width' => [],
];

$maxW = (int)$config->getSystemValue('preview_max_x', 4096);
$maxH = (int)$config->getSystemValue('preview_max_y', 4096);
$maxW = (int)$this->config->getSystemValue('preview_max_x', 4096);
$maxH = (int)$this->config->getSystemValue('preview_max_y', 4096);

$s = 64;
while ($s <= $maxW || $s <= $maxH) {
$sizes['square'][] = $s;
$sizes['squareUncropped'][] = $s;
$s *= 4;
}

Expand All @@ -72,35 +79,71 @@ public static function calculateSizes(IConfig $config): array {
* stuff it is their own fault and we just ignore it
*/
$getCustomSizes = function (IConfig $config, $key) {
$TXT = $config->getAppValue('previewgenerator', $key, '');
$raw = $config->getAppValue(Application::APP_ID, $key, null);
if ($raw === null) {
return null;
}

// User wants to skip those sizes deliberately
if ($raw === '') {
return [];
}

$values = [];
if ($TXT !== '') {
foreach (explode(' ', $TXT) as $value) {
if (ctype_digit($value)) {
$values[] = (int)$value;
}
foreach (explode(' ', $raw) as $value) {
if (ctype_digit($value)) {
$values[] = (int)$value;
}
}

return $values;
};

$squares = $getCustomSizes($config, 'squareSizes');
$widths = $getCustomSizes($config, 'widthSizes');
$heights = $getCustomSizes($config, 'heightSizes');
$squares = $getCustomSizes($this->config, 'squareSizes');
$squaresUncropped = $getCustomSizes($this->config, 'squareUncroppedSizes');
$widths = $getCustomSizes($this->config, 'widthSizes');
$heights = $getCustomSizes($this->config, 'heightSizes');

if ($squares !== []) {
if ($squares !== null) {
$sizes['square'] = array_intersect($sizes['square'], $squares);
}

if ($widths !== []) {
if ($squaresUncropped !== null) {
$sizes['squareUncropped'] = array_intersect(
$sizes['squareUncropped'],
$squaresUncropped,
);
}

if ($widths !== null) {
$sizes['width'] = array_intersect($sizes['width'], $widths);
}

if ($heights !== []) {
if ($heights !== null) {
$sizes['height'] = array_intersect($sizes['height'], $heights);
}

return $sizes;
return $this->mergeSpecifications($sizes);
}

/**
* @param int[][] $sizes
* @return array{width: int, height: int, crop: bool}
*/
private function mergeSpecifications(array $sizes): array {
return array_merge(
array_map(static function ($squareSize) {
return ['width' => $squareSize, 'height' => $squareSize, 'crop' => true];
}, $sizes['square']),
array_map(static function ($squareSize) {
return ['width' => $squareSize, 'height' => $squareSize, 'crop' => false];
}, $sizes['squareUncropped']),
array_map(static function ($heightSize) {
return ['width' => -1, 'height' => $heightSize, 'crop' => false];
}, $sizes['height']),
array_map(static function ($widthSize) {
return ['width' => $widthSize, 'height' => -1, 'crop' => false];
}, $sizes['width'])
);
}
}
Loading