spatie / laravel-medialibrary

Associate files with Eloquent models
https://spatie.be/docs/laravel-medialibrary
MIT License
5.78k stars 1.08k forks source link

Cant delete files after using a customer FileNamer #3702

Closed innoflash closed 1 week ago

innoflash commented 2 months ago

Hello @Spatie, great package you have here.

Its probably documented somewhere but I am having issues deleting obsolete files when I add new ones. I defined a collection to keep only 3 files.

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('cover')
            ->onlyKeepLatest(3)
            ->useDisk('s3')
            ->acceptsFile(function (File $file) {
                return Str::of($file->mimeType)->contains('image');
            });
    }

I then created a custom file namer, I do not want my image and its conversions to share a name. A user can reverse engineer and I am trying to avoid that.

class FileNamer extends SpatieFileNamer
{
    public function conversionFileName(string $fileName, Conversion $conversion): string {
        $strippedFileName = pathinfo($fileName, PATHINFO_FILENAME);

        return md5($strippedFileName)."-{$conversion->getName()}";
    }

    public function originalFileName(string $fileName): string
    {
        $extLength = strlen(pathinfo($fileName, PATHINFO_EXTENSION));

        $baseName = substr($fileName, 0, strlen($fileName) - ($extLength ? $extLength + 1 : 0));

        return md5($baseName);
    }
}

Basically I am md5ing the original file name and the resultant file name so they cant be similar. Examples are shown below. image image

The furthest I could go investigating was upto these lines below when deleting the conversions, still to inspect the other removers. https://github.com/spatie/laravel-medialibrary/blob/548626199039f41d561fb01674f49a3f4534244e/src/Support/FileRemover/DefaultFileRemover.php#L68-L79

According to L72, only deletable conversations are files with a naming pattern like filename-conversionname which is not whats not set on my new file namer.

One can write a new file_remover_class or wire an extra media delete observer but cant we have this natively in the package.

Thanks