A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
feat: image soft delete functionality
aminnausin9cb21d6c7661
diff --git a/app/Data/Images/ImageUpdateData.php b/app/Data/Images/ImageUpdateData.phpnew file mode 100644index 00000000..8f72b16d--- /dev/null+++ b/app/Data/Images/ImageUpdateData.php@@ -0,0 +1,35 @@+<?php++namespace App\Data\Images;++use App\Enums\ImageType;+use App\Http\Requests\Media\MediaImageUpdateRequest;+use App\Http\Requests\Series\SeriesImageUpdateRequest;+use App\Models\User;+use Illuminate\Http\UploadedFile;++class ImageUpdateData {+ public function __construct(+ public readonly string $mode,+ public readonly ImageType $imageType,+ public readonly User $user,+ public readonly bool $isAdmin = false,+ public readonly ?int $imageId = null,+ public readonly ?string $url = null,+ public readonly ?UploadedFile $file = null,+ public readonly array $deletedIds = [],+ ) {}++ public static function fromRequest(MediaImageUpdateRequest|SeriesImageUpdateRequest $request, User $user, bool $isAdmin = false): self {+ return new self(+ imageType: ImageType::from($request->validated('type')),+ mode: $request->validated('mode'),+ user: $user,+ isAdmin: $isAdmin,+ imageId: $request->validated('image_id'),+ url: $request->validated('url'),+ file: $request->file('image'),+ deletedIds: $request->validated('deleted_images') ?? [],+ );+ }+}diff --git a/app/Services/Images/ImageService.php b/app/Services/Images/ImageService.phpindex 8c6a7b91..7e4a42fd 100644--- a/app/Services/Images/ImageService.php+++ b/app/Services/Images/ImageService.php@@ -3,6 +3,7 @@namespace App\Services\Images;use App\Data\Images\ImageData;+use App\Data\Images\ImageUpdateData;use App\Enums\ImageSource;use App\Enums\ImageType;use App\Enums\ImageVariant;@@ -10,6 +11,7 @@ use App\Models\Image;use App\Models\Metadata;use App\Models\Series;use Bepsvpt\Blurhash\Facades\BlurHash;+use Illuminate\Auth\Access\AuthorizationException;use Illuminate\Contracts\Filesystem\FileNotFoundException;use Illuminate\Database\Eloquent\Model;use Illuminate\Http\UploadedFile;@@ -246,6 +248,65 @@ class ImageService {}}+ public function resolveUpdatedImage(Model $owner, ImageUpdateData $data): ?Image {+ $image = match ($data->mode) {+ 'existing' => $owner->images()->where('id', $data->imageId)->where('image_type', $data->imageType)->firstOrFail(),+ 'upload' => $this->uploadImage($data->file, $owner, $data->imageType, $data->user->id),+ 'url' => $this->downloadFromUrl($data->url, $owner, $data->imageType, $data->user->id),+ 'remove' => null,+ default => throw new \InvalidArgumentException("Unknown mode: {$data->mode}"),+ };++ return $image;+ }++ /**+ * Sets replaced_at to now on the given images by id.+ *+ * Only allows 'deleting' uploaded files and images downloaded from a url that are owned by the requesting user+ *+ * @param Model $owner model to delete images from+ * @param ImageUpdateData $data DTO that holds delete request information+ */+ public function softDeleteImages(Model $owner, ImageUpdateData $data): void {+ if (! $data->deletedIds) {+ return;+ }++ if (! $data->isAdmin && $owner->images()->whereIn('id', $data->deletedIds)->where('user_id', '!=', $data->user->id)->exists()) {+ throw new AuthorizationException('You do not own one or more of the images you are trying to delete.');+ }++ $affected = $owner->images()+ ->whereIn('id', $data->deletedIds)+ ->whereIn('image_source', [ImageSource::UPLOADED->value, ImageSource::DOWNLOADED->value])+ ->when(! $data->isAdmin, fn ($q) => $q->where('user_id', $data->user->id))+ ->whereNull('replaced_at')+ ->get(['id', 'path', 'image_type', 'image_source']);++ if ($affected->isEmpty()) {+ return;+ }++ $affected->each->update(['replaced_at' => now()]);++ $uuid = $owner->uuid ?? $owner->getKey();+ $username = $data->user->email ?? "user {$data->user->id}";++ Log::info("Images soft deleted by {$username} on " . class_basename($owner) . " {$uuid}", [+ 'owner_id' => $owner->getKey(),+ 'deleted_by' => $data->user->id,+ 'images' => $affected->map(fn ($i) => [+ 'id' => $i->id,+ 'path' => $i->path,+ 'type' => $i->image_type,+ 'source' => $i->image_source,+ ])->toArray(),+ 'requested_ids' => $data->deletedIds,+ 'skipped' => count($data->deletedIds) - $affected->count(),+ ]);+ }+// Untested// Dangerouspublic function migrateImage(string $filePath, Model $owner, ImageType $imageType, ?int $userId = null): ?Image {@@ -317,7 +378,7 @@ class ImageService {return [$relativePath, $absolutePath];}- public function persistImage(Model $owner, ImageData $data, bool $overwrite = false): Image {+ public function persistImage(Model $owner, ImageData $data, bool $overwrite = false, bool $forceReplace = false): Image {if (! file_exists($data->absolutePath) || filesize($data->absolutePath) === 0) {throw new FileNotFoundException("Image file does not exist: {$data->absolutePath}");}@@ -352,12 +413,18 @@ class ImageService {);}- Image::where([- 'imageable_id' => $uuid,- 'imageable_type' => $owner::class,- 'image_type' => $data->type,- 'replaced_at' => null,- ])->update(['replaced_at' => now()]);+ // Only replace generated / extracted / auto downloaded files+ // User uploaded / url downloaded images should not be replaced?+ $autoSources = [ImageSource::GENERATED, ImageSource::EMBEDDED, ImageSource::DOWNLOADED];++ if (in_array($data->source, $autoSources) || $forceReplace) {+ Image::where([+ 'imageable_id' => $uuid,+ 'imageable_type' => $owner::class,+ 'image_type' => $data->type,+ 'replaced_at' => null,+ ])->update(['replaced_at' => now()]);+ }return Image::create(['imageable_id' => $uuid,diff --git a/resources/js/components/cards/data/ImageCard.vue b/resources/js/components/cards/data/ImageCard.vueindex d7f44696..abdd718b 100644--- a/resources/js/components/cards/data/ImageCard.vue+++ b/resources/js/components/cards/data/ImageCard.vue@@ -4,25 +4,43 @@ import type { ImageResource } from '@/contracts/media';import { CedarDelete2 } from '@/components/cedar-ui/icons';import { ButtonIcon } from '@/components/cedar-ui/button';+import { toTimeSpan } from '@/service/util';import { computed } from 'vue';+import { useAuth } from '@/composables/auth/useAuth';import { cn } from '@aminnausin/cedar-ui';import VideoControlWrapper from '@/components/video/VideoControlWrapper.vue';-import LazyImage from '@/components/lazy/LazyImage.vue';import MediaTag from '@/components/labels/MediaTag.vue';import ProiconsDelete from '~icons/proicons/delete';import PrimeSave from '~icons/prime/save';-const props = withDefaults(defineProps<{ data: ImageResource; isPrimary?: boolean; isActive?: boolean; isAudio?: boolean }>(), {+const props = withDefaults(defineProps<{ data: ImageResource; isPrimary?: boolean; isAudio?: boolean; isPendingDelete?: boolean }>(), {isPrimary: false,- isActive: false,isAudio: false,+ isPendingDelete: false,+});++const { userData } = useAuth();++const deletionDate = computed(() => {+ if (!props.data.replaced_at) return null;+ const replacedAt = new Date(props.data.replaced_at);+ return new Date(replacedAt.getTime() + 30 * 24 * 60 * 60 * 1000);});+const isDisabled = computed(() => !!deletionDate.value);+const filename = computed(() => props.data.path.split('/').at(-1));-const tags = computed(() => [props.data.type, props.data.source]);+const tags = computed(() => {+ if (deletionDate.value) return [`deletes ${toTimeSpan(deletionDate.value)}`];++ const imageTags = [props.data.source];++ if (userData.value?.id == props.data.user_id) return [...imageTags, 'owned'];+ return imageTags;+});const generatePosterStyle = (url?: string): HTMLAttributes['style'] => {if (!url) return {};@@ -40,16 +58,17 @@ const emit = defineEmits({select: () => true,deselect: () => true,delete: () => true,+ restore: () => true,});</script><template><div- :class="[- 'relative flex flex-wrap items-center justify-between',- 'w-full rounded-lg text-sm shadow-sm transition',- 'data-card',- `ring-2 ${isPrimary ? 'ring-primary-active/60' : 'ring-transparent dark:ring-neutral-700/20'}`,- ]"+ :class="+ cn('relative flex w-full flex-wrap items-center justify-between rounded-lg text-xs shadow-sm transition sm:text-sm', 'data-card ring-2 ring-transparent', {+ 'pointer-events-none! opacity-50': isDisabled,+ 'ring-primary-active/60': isPrimary,+ })+ "><div :class="cn('relative flex max-h-48 w-full items-center overflow-clip rounded-t-lg text-xs select-none sm:max-h-80')"><div :class="cn({ 'aspect-[1.91/1]!': data.type === 'preview', 'aspect-square': isAudio, 'aspect-video': !isAudio }, 'size-full', $attrs.class)">@@ -66,49 +85,65 @@ const emit = defineEmits({</div><!-- Overlay -->- <div :class="cn('duration-input pointer-events-none absolute inset-0 z-3 flex items-start justify-between gap-1 p-2 transition-[translate,margin]')">- <div class="h-fit">- <VideoControlWrapper :class="cn('w-fit transition-opacity duration-150')" v-if="isPrimary">- <p :class="cn('font-figtree px-1 text-white tabular-nums text-shadow-lg')">Primary</p>- </VideoControlWrapper>- </div>- <div class="text-foreground-i dark:text-foreground-0 pointer-events-auto flex gap-1" v-if="data.type !== 'preview'">- <ButtonIcon- class="overlay-button hover:ring-1"- :type="'button'"- :variant="'ghost'"- :title="isPrimary ? 'Already Selected' : 'Select'"- :disabled="isPrimary"- v-if="!isPrimary"- @click="$emit('select')"- >- <template #icon>- <PrimeSave class="size-4" />- </template>- </ButtonIcon>- <ButtonIcon v-else class="overlay-button hover:ring-1" :type="'button'" title="Remove Selection" :variant="'ghost'" @click="$emit('deselect')">- <template #icon>- <CedarDelete2 class="size-4" />- </template>- </ButtonIcon>- <ButtonIcon- v-if="!data.blurHash || data.source !== 'generated'"- class="overlay-button hover:ring-1"- :type="'button'"- title="Delete"- :variant="'ghost'"- @click="$emit('delete')"- >+ <div :class="cn('duration-input absolute inset-0 z-3 flex items-start justify-between gap-1 p-2 transition-[translate,margin]')">+ <VideoControlWrapper :class="cn('w-fit opacity-0 transition-opacity duration-100', { 'opacity-100': isPrimary })">+ <p :class="cn('px-1 text-white text-shadow-lg')">Primary</p>+ </VideoControlWrapper>+ <div class="text-foreground-i dark:text-foreground-0 pointer-events-auto ms-auto flex gap-1" v-if="data.type !== 'preview'">+ <ButtonIcon v-if="isPendingDelete" class="overlay-button hover:ring-1" :type="'button'" title="Undo delete" :variant="'ghost'" @click="$emit('restore')"><template #icon>- <ProiconsDelete class="size-4" />+ <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" class="size-4">+ <path d="M0 0h24v24H0z" fill="none" />+ <path+ fill="none"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="1.5"+ d="M9.25 12L5.957 8.707A1 1 0 0 1 5.664 8M9.25 4L5.957 7.293A1 1 0 0 0 5.664 8M7.25 19.5h6.25a5.75 5.75 0 0 0 0-11.5H5.664"+ />+ </svg></template></ButtonIcon>+ <template v-else-if="!isDisabled">+ <ButtonIcon+ class="overlay-button hover:ring-1"+ :type="'button'"+ :variant="'ghost'"+ :title="isPrimary ? 'Already Selected' : 'Select as primary'"+ :disabled="isPrimary"+ v-if="!isPrimary"+ @click="$emit('select')"+ >+ <template #icon>+ <PrimeSave class="size-4" />+ </template>+ </ButtonIcon>+ <ButtonIcon v-else class="overlay-button hover:ring-1" :type="'button'" title="Remove Selection" :variant="'ghost'" @click="$emit('deselect')">+ <template #icon>+ <CedarDelete2 class="size-4" />+ </template>+ </ButtonIcon>+ <ButtonIcon+ v-if="data.source !== 'generated' && (!data.blur_hash || (data.blur_hash && data.user_id))"+ class="overlay-button hover:ring-1"+ :type="'button'"+ title="Delete image"+ :variant="'ghost'"+ @click="$emit('delete')"+ >+ <template #icon>+ <ProiconsDelete class="size-4" />+ </template>+ </ButtonIcon>+ </template></div></div></div><div class="text-foreground-1 flex w-full flex-col items-start justify-between gap-x-4 gap-y-2 p-3 dark:text-inherit"><p class="w-full truncate" :title="filename">{{ filename }}</p>- <span class="-ms-0.5 flex w-full flex-wrap gap-1 overflow-clip text-xs [overflow-clip-margin:4px]">+ {{ data.source }}+ <span class="-ms-0.5 flex w-full flex-wrap gap-1 overflow-clip [overflow-clip-margin:4px]"><MediaTagv-for="(tag, index) in tags":key="index"