-
Notifications
You must be signed in to change notification settings - Fork 31
Improve image handling #2041
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
Open
BentiGorlich
wants to merge
8
commits into
main
Choose a base branch
from
new/image-handling-improvements
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Improve image handling #2041
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1a2813a
Improve image handling
BentiGorlich 4038f0f
Fix tests
BentiGorlich 708c311
Fix tests II
BentiGorlich 7f8ef44
Use the highest compression, fix naming
BentiGorlich aa37fcb
Move docs to 09
BentiGorlich 40e818b
Improve command display, remove restriction to 65535 batch size
BentiGorlich a7914f5
Add command to refresh media metadata
BentiGorlich 34d6a19
Review changes
BentiGorlich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
docs/02-admin/03-optional-features/09-image-compression.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # Image compression | ||
|
|
||
| You can enable compression of images uploaded to mbin by users or downloaded from remote instances, | ||
| for increased compatibility, to save on size and for a better user experience. | ||
|
|
||
| To enable image compression set `MBIN_IMAGE_COMPRESSION_QUALITY` in your `.env` file to a value between 0.1 and 0.95. | ||
| This setting is used as a starting point to compress the image. It is gradually lowered (in 0.05 steps) until the maximum size is no longer exceeded. | ||
|
|
||
| > [!HINT] | ||
| > The maximum file size is determined by the `MBIN_MAX_IMAGE_BYTES` setting in your `.env` file | ||
|
|
||
| > [!NOTE] | ||
| > Enabling this setting can cause a higher memory usage | ||
|
|
||
| ## Better compatibility | ||
|
|
||
| If another instance shares a thread with an image attached that exceeds your maximum image size, it will not be downloaded, | ||
| but instead loaded directly from the other instance. This works most of the time, | ||
| but sometimes website settings will block it and thus your users will see an image that cannot be loaded. | ||
| This behavior also introduces web requests to other servers, which may unintentionally leak information to the remote instance. | ||
|
|
||
| If instead your server compresses the image and saves it locally this will never happen. | ||
|
|
||
| ## Saving space | ||
|
|
||
| When image compression is enabled you can reduce your maximum image size to, lets say 1MB. | ||
| Without the compression this might not be suitable, because too many images exceed that size, | ||
| and you don't want to risk compatibility problems, | ||
| but with it enabled the images will just be compressed, saving space. | ||
|
|
||
| ## A better user experience | ||
|
|
||
| Normally there is a maximum image size your users must adhere to, but if image compression is enabled, | ||
| instead of showing your user an error that the image exceeds that size, the upload goes through and the image is compressed. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace DoctrineMigrations; | ||
|
|
||
| use Doctrine\DBAL\Schema\Schema; | ||
| use Doctrine\Migrations\AbstractMigration; | ||
|
|
||
| final class Version20260303142852 extends AbstractMigration | ||
| { | ||
| public function getDescription(): string | ||
| { | ||
| return 'Add local_size, original_size, is_compressed and source_too_big image columns'; | ||
| } | ||
|
|
||
| public function up(Schema $schema): void | ||
| { | ||
| $this->addSql('ALTER TABLE image ADD is_compressed BOOLEAN DEFAULT false NOT NULL'); | ||
| $this->addSql('ALTER TABLE image ADD source_too_big BOOLEAN DEFAULT false NOT NULL'); | ||
| $this->addSql('ALTER TABLE image ADD downloaded_at TIMESTAMP(0) WITH TIME ZONE DEFAULT NULL'); | ||
| // init the column for all existing images, it gets overwritten in the big loop underneath | ||
| $this->addSql('ALTER TABLE image ADD created_at TIMESTAMP(0) WITH TIME ZONE NOT NULL DEFAULT current_timestamp'); | ||
| $this->addSql('ALTER TABLE image ALTER created_at DROP DEFAULT;'); | ||
| $this->addSql('ALTER TABLE image ADD original_size BIGINT DEFAULT 0 NOT NULL'); | ||
| $this->addSql('ALTER TABLE image ADD local_size BIGINT DEFAULT 0 NOT NULL'); | ||
|
|
||
| // set the downloaded at value to something realistically | ||
| $this->addSql('DO | ||
| $do$ | ||
| declare tempRow record; | ||
| BEGIN | ||
| FOR tempRow IN | ||
| SELECT i.id, e.created_at as ec, ec.created_at as ecc, p.created_at as pc, pc.created_at as pcc, u.created_at as uc, u2.created_at as u2c, m.created_at as mc, m2.created_at as m2c FROM image i | ||
| LEFT JOIN entry e ON i.id = e.image_id | ||
| LEFT JOIN entry_comment ec ON i.id = ec.image_id | ||
| LEFT JOIN post p ON i.id = p.image_id | ||
| LEFT JOIN post_comment pc ON i.id = pc.image_id | ||
| LEFT JOIN "user" u ON i.id = u.avatar_id | ||
| LEFT JOIN "user" u2 ON i.id = u2.cover_id | ||
| LEFT JOIN magazine m ON i.id = m.icon_id | ||
| LEFT JOIN magazine m2 ON i.id = m2.banner_id | ||
| LOOP | ||
| IF tempRow.ec IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.ec, created_at = tempRow.ec WHERE id = tempRow.id; | ||
| ELSIF tempRow.ecc IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.ecc, created_at = tempRow.ecc WHERE id = tempRow.id; | ||
| ELSIF tempRow.pc IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.pc, created_at = tempRow.pc WHERE id = tempRow.id; | ||
| ELSIF tempRow.pcc IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.pcc, created_at = tempRow.pcc WHERE id = tempRow.id; | ||
| ELSIF tempRow.uc IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.uc, created_at = tempRow.uc WHERE id = tempRow.id; | ||
| ELSIF tempRow.u2c IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.u2c, created_at = tempRow.u2c WHERE id = tempRow.id; | ||
| ELSIF tempRow.mc IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.mc, created_at = tempRow.mc WHERE id = tempRow.id; | ||
| ELSIF tempRow.m2c IS NOT NULL THEN | ||
| UPDATE image SET downloaded_at = tempRow.m2c, created_at = tempRow.m2c WHERE id = tempRow.id; | ||
| END IF; | ||
| END LOOP; | ||
| END | ||
| $do$;'); | ||
| } | ||
|
|
||
| public function down(Schema $schema): void | ||
| { | ||
| $this->addSql('ALTER TABLE image DROP is_compressed'); | ||
| $this->addSql('ALTER TABLE image DROP source_too_big'); | ||
| $this->addSql('ALTER TABLE image DROP downloaded_at'); | ||
| $this->addSql('ALTER TABLE image DROP created_at'); | ||
| $this->addSql('ALTER TABLE image DROP original_size'); | ||
| $this->addSql('ALTER TABLE image DROP local_size'); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Command; | ||
|
|
||
| use App\Repository\ImageRepository; | ||
| use App\Utils\GeneralUtil; | ||
| use Doctrine\ORM\EntityManagerInterface; | ||
| use League\Flysystem\FilesystemException; | ||
| use League\Flysystem\FilesystemOperator; | ||
| use Psr\Log\LoggerInterface; | ||
| use Symfony\Component\Console\Attribute\AsCommand; | ||
| use Symfony\Component\Console\Command\Command; | ||
| use Symfony\Component\Console\Input\InputInterface; | ||
| use Symfony\Component\Console\Input\InputOption; | ||
| use Symfony\Component\Console\Output\OutputInterface; | ||
| use Symfony\Component\Console\Style\SymfonyStyle; | ||
|
|
||
| #[AsCommand( | ||
| name: 'mbin:images:refresh-meta', | ||
| description: 'Refresh meta information about your media', | ||
| )] | ||
| class RefreshImageMetaDataCommand extends Command | ||
| { | ||
| public function __construct( | ||
| private readonly ImageRepository $imageRepository, | ||
| private readonly FilesystemOperator $publicUploadsFilesystem, | ||
| private readonly LoggerInterface $logger, | ||
| private readonly EntityManagerInterface $entityManager, | ||
| ) { | ||
| parent::__construct(); | ||
| } | ||
|
|
||
| protected function configure(): void | ||
| { | ||
| $this->addOption('batch-size', null, InputOption::VALUE_REQUIRED, 'The number of images to handle at once, the higher the number the faster the command, but it also takes more memory', '10000'); | ||
| $this->addOption('dry-run', null, InputOption::VALUE_NONE, 'Do a trial without removing any media'); | ||
| } | ||
|
|
||
| protected function execute(InputInterface $input, OutputInterface $output): int | ||
| { | ||
| $io = new SymfonyStyle($input, $output); | ||
| GeneralUtil::useProgressbarFormatsWithMessage(); | ||
|
|
||
| $dryRun = \boolval($input->getOption('dry-run')); | ||
| $batchSize = \intval($input->getOption('batch-size')); | ||
| $images = $this->imageRepository->findSavedImagesPaginated($batchSize); | ||
| $count = $images->count(); | ||
| $progressBar = $io->createProgressBar($count); | ||
| $progressBar->setMessage(''); | ||
| $progressBar->start(); | ||
| $totalCheckedFiles = 0; | ||
| $totalUpdateFiles = 0; | ||
|
|
||
| for ($i = 0; $i < $images->getNbPages(); ++$i) { | ||
| $progressBar->setMessage(\sprintf('Fetching images %s - %s', ($i * $batchSize) + 1, ($i + 1) * $batchSize)); | ||
| $progressBar->display(); | ||
| foreach ($images->getCurrentPageResults() as $image) { | ||
| $progressBar->advance(); | ||
| ++$totalCheckedFiles; | ||
|
|
||
| try { | ||
| if ($this->publicUploadsFilesystem->has($image->filePath)) { | ||
| ++$totalUpdateFiles; | ||
| $fileSize = $this->publicUploadsFilesystem->fileSize($image->filePath); | ||
| if (!$dryRun) { | ||
| $image->localSize = $fileSize; | ||
| $progressBar->setMessage(\sprintf('Refreshed meta data of "%s" (%s)', $image->filePath, $image->getId())); | ||
| $this->logger->debug('Refreshed meta data of "{path}" ({id})', ['path' => $image->filePath, 'id' => $image->getId()]); | ||
| } else { | ||
| $progressBar->setMessage(\sprintf('Would have refreshed meta data of "%s" (%s)', $image->filePath, $image->getId())); | ||
| } | ||
| $progressBar->display(); | ||
| } else { | ||
| $previousPath = $image->filePath; | ||
| // mark it as not present on the media storage | ||
| if (!$dryRun) { | ||
| $image->filePath = null; | ||
| $image->localSize = 0; | ||
| $image->downloadedAt = null; | ||
| $progressBar->setMessage(\sprintf('Marked "%s" (%s) as not present on the media storage', $previousPath, $image->getId())); | ||
| } else { | ||
| $progressBar->setMessage(\sprintf('Would have marked "%s" (%s) as not present on the media storage', $image->filePath, $image->getId())); | ||
| } | ||
| $progressBar->display(); | ||
| } | ||
| } catch (FilesystemException $e) { | ||
| $this->logger->error('There was an exception refreshing the meta data of "{path}" ({id}): {exClass} - {message}', [ | ||
| 'path' => $image->filePath, | ||
| 'id' => $image->getId(), | ||
| 'exClass' => \get_class($image), | ||
| 'message' => $e->getMessage(), | ||
| 'exception' => $e, | ||
| ]); | ||
| $progressBar->setMessage(\sprintf('Error checking meta data of "%s" (%s)', $image->filePath, $image->getId())); | ||
| $progressBar->display(); | ||
| } | ||
| } | ||
| if (!$dryRun) { | ||
| $this->entityManager->flush(); | ||
| } | ||
| if ($images->hasNextPage()) { | ||
| $images->setCurrentPage($images->getNextPage()); | ||
| } | ||
| } | ||
| $io->writeln(''); | ||
| if (!$dryRun) { | ||
| $io->success(\sprintf('Refreshed %s files', $totalUpdateFiles)); | ||
| } else { | ||
| $io->success(\sprintf('Would have refreshed %s files', $totalUpdateFiles)); | ||
| } | ||
|
|
||
| return Command::SUCCESS; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What happens if a user uploads a PNG which is over the size limit. As it can not be further compressed, will it be rejected or be stored despite being larger than allowed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it should then still get rejected imo
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Everything above the size limit will still be rejected