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

Entity Assets now use Gallery #935

Merged
merged 9 commits into from
Aug 4, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions app/Http/Controllers/Entity/AssetController.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function index(Campaign $campaign, Entity $entity)
);
}

$assets = $entity->assets;
$assets = $entity->assets()->with('image')->get();

return view('entities.pages.assets.index', compact(
'campaign',
Expand Down Expand Up @@ -102,7 +102,7 @@ protected function storeFile(StoreEntityAsset $request, Campaign $campaign, Enti
$file = $service
->entity($entity)
->campaign($campaign)
->upload($request, 'file', 'w/' . $campaign->id . '/entity-assets');
->upload($request, 'file');

return redirect()
->route('entities.entity_assets.index', [$campaign, $entity])
Expand Down
1 change: 0 additions & 1 deletion app/Models/CommunityEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use App\User;
use App\Facades\Img;
use App\Models\Concerns\Uuid;
use App\Models\Scopes\CommunityEventScopes;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
Expand Down
20 changes: 20 additions & 0 deletions app/Models/EntityAsset.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
* @property int $id
* @property int $type_id
* @property int $entity_id
* @property string|null $image_uuid
* @property string $name
* @property array $metadata
* @property Carbon $created_at
Expand Down Expand Up @@ -49,6 +51,7 @@ class EntityAsset extends Model
'metadata',
'visibility_id',
'is_pinned',
'image_uuid',
];

public $casts = [
Expand Down Expand Up @@ -104,6 +107,10 @@ public function isImage(): bool
*/
public function imageUrl(): string
{
if ($this->image) {
return $this->image->getUrl(120, 80);
}

return Img::crop(120, 80)->url($this->metadata['path']);
}

Expand All @@ -126,6 +133,7 @@ public function getIconAttribute(): mixed
/**
* A virtual getter for the image path for the image observer delete loop
*/
//check this
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
public function getImagePathAttribute(): string
{
return (string) $this->metadata['path'];
Expand Down Expand Up @@ -157,11 +165,23 @@ public function urlDomain(): string

public function url(): string
{
if ($this->image_uuid) {
return $this->image->getUrl();
}

$path = $this->metadata['path'];
$cloudfront = config('filesystems.disks.cloudfront.url');
if ($cloudfront) {
return Storage::disk('cloudfront')->url($path);
}
return Storage::url($path);
}

/**
* Image stored in the gallery
*/
public function image(): HasOne
{
return $this->hasOne('App\Models\Image', 'id', 'image_uuid');
}
}
5 changes: 5 additions & 0 deletions app/Models/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,11 @@ public function isFont(): bool
return in_array($this->ext, ['woff', 'woff2']);
}

public function isFile(): bool
{
return in_array($this->ext, ['pdf', 'gif', 'webp', 'pdf', 'xls', 'xlsx', 'csv', 'mp3', 'ogg', 'json']);
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
}

public function getUrl(?int $sizeX = null, ?int $sizeY = null): string
{
if ($this->isSvg()) {
Expand Down
1 change: 1 addition & 0 deletions app/Models/Relations/EntityRelations.php
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ public function pinnedFiles(): HasMany
{
return $this->files()
->where('is_pinned', 1)
->with('image')
;
}

Expand Down
5 changes: 5 additions & 0 deletions app/Observers/EntityAssetObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Observers;

use App\Facades\CampaignCache;
use App\Models\EntityAsset;
use App\Facades\Images;

Expand All @@ -12,6 +13,10 @@ class EntityAssetObserver
*/
public function saved(EntityAsset $entityAsset)
{
if ($entityAsset->isFile()) {
CampaignCache::clear();
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
}

// When adding or changing an asset to an entity, we want to update the
// last updated date to reflect changes in the dashboard.
$entityAsset->entity->child->touchQuietly();
Expand Down
9 changes: 6 additions & 3 deletions app/Services/Caches/CharacterCacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ public function genderSuggestion(): array
*/
public function clearSuggestion(): self
{
$this->forget(
$this->genderSuggestionKey()
);
if (isset($this->campaign)) {
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
$this->forget(
$this->genderSuggestionKey()
);
}

return $this;
}

Expand Down
1 change: 0 additions & 1 deletion app/Services/Campaign/DefaultImageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use App\Traits\CampaignAware;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class DefaultImageService
{
Expand Down
3 changes: 3 additions & 0 deletions app/Services/Campaign/ExportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,9 @@ protected function process(string $entity, $model): self

/** @var EntityAsset $file */
foreach ($model->entity->files as $file) {
if (!isset($file->metadata['path'])) {
continue;
}
$path = $file->metadata['path'];
if (!Storage::exists($path)) {
continue;
Expand Down
1 change: 0 additions & 1 deletion app/Services/Campaign/GalleryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ public function storageInfo(): array
];
}


/**
* Total size in mb
*/
Expand Down
37 changes: 24 additions & 13 deletions app/Services/Campaign/Import/Mappers/EntityMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,26 @@ protected function migrateToGallery(string $old): self
return $this;
}

$image = $this->migrateImage($img);

if ($old == 'image_path') {
$this->entity->image_uuid = ImportIdMapper::getGallery($image->id);
} else {
$this->entity->header_uuid = ImportIdMapper::getGallery($image->id);
}

return $this;
}

protected function migrateImage(string $img): Image
{
$imageExt = Str::after($img, '.');

//We need to create a new Image to migrate to the new system.
$image = new Image();
$image->campaign_id = $this->campaign->id;
$image->ext = $imageExt;
$image->created_by = $this->user->id;
$image->name = $this->entity->name;
$image->visibility_id = 1;
$size = Storage::disk('local')->size($this->path . $img);
Expand All @@ -170,13 +184,7 @@ protected function migrateToGallery(string $old): self
Storage::writeStream($image->path, Storage::disk('local')->readStream($this->path . $img));
ImportIdMapper::putGallery($image->id, $image->id);

if ($old == 'image_path') {
$this->entity->image_uuid = ImportIdMapper::getGallery($image->id);
} else {
$this->entity->header_uuid = ImportIdMapper::getGallery($image->id);
}

return $this;
return $image;
}

protected function gallery(): self
Expand Down Expand Up @@ -213,7 +221,7 @@ protected function posts(): self
foreach ($import as $field) {
$post->$field = $data[$field];
}
if (!empty($data['location_id'])) {
if (!empty($data['location_id']) && ImportIdMapper::has('locations', $data['location_id'])) {
$locationID = ImportIdMapper::get('locations', $data['location_id']);
if (!empty($locationID)) {
$post->location_id = $locationID;
Expand Down Expand Up @@ -257,20 +265,23 @@ protected function assets(): self
if (!empty($data['metadata'])) {
if (!empty($data['metadata']['path'])) {
$img = $data['metadata']['path'];
$ext = Str::afterLast($img, '.');
$destination = 'w/' . $this->campaign->id . '/entity-assets/' . uniqid() . '.' . $ext;

if (!Storage::disk('local')->exists($this->path . $img)) {
//dd('image ' . $this->path . $img . ' doesnt exist');
continue;
}
Storage::writeStream($destination, Storage::disk('local')->readStream($this->path . $img));
$data['metadata']['path'] = $destination;

$image = $this->migrateImage($img);
$asset->image_uuid = $image->id;
unset($data['metadata']['path']);
$asset->metadata = $data['metadata'];

} else {
$asset->metadata = $data['metadata'];
}
}
if (isset($data['image_uuid'])) {
$asset->image_uuid = ImportIdMapper::getGallery($data['image_uuid']);
}
$asset->created_by = $this->user->id;
$asset->save();
}
Expand Down
2 changes: 2 additions & 0 deletions app/Services/Campaign/Import/Mappers/GalleryMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public function prepare(): self
public function import(): void
{
$this->image = new Image();
//Need to set the id before saving otherwise it crashes
$this->image->id = Str::uuid();
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
$this->image->campaign_id = $this->campaign->id;
$this->mapping[$this->data['id']] = $this->image->id;
ImportIdMapper::putGallery($this->data['id'], $this->image->id);
Expand Down
39 changes: 33 additions & 6 deletions app/Services/EntityFileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
use App\Exceptions\EntityFileException;
use App\Http\Requests\StoreEntityAsset;
use App\Models\EntityAsset;
use App\Models\Image;
use App\Services\Campaign\GalleryService;
use App\Traits\CampaignAware;
use App\Traits\EntityAware;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class EntityFileService
{
Expand All @@ -16,33 +20,56 @@ class EntityFileService
/**
* @throws EntityFileException
*/
public function upload(StoreEntityAsset $request, string $field = 'file', string $folder = 'entities/files'): EntityAsset
public function upload(StoreEntityAsset $request, string $field = 'file'): EntityAsset
{
/** @var GalleryService $service */
$service = app()->make(GalleryService::class);

// Prepare the file for the journey
$uploadedFile = $request->file($field);

// Already above max capacity?
if ($this->entity->files->count() >= $this->campaign->maxEntityFiles()) {
if ($this->entity->files->count() >= $this->campaign->maxEntityFiles() || $service->campaign($this->campaign)->available() < $uploadedFile->getSize() / 1024) {
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
throw new EntityFileException('max');
}
// Prepare the file for the journey
$uploadedFile = $request->file($field);

$path = $request->file($field)->storePublicly($folder);
$name = $request->get('name');
if (empty($name)) {
$name = $uploadedFile->getClientOriginalName();
$name = Str::beforeLast($name, '.');
}

$image = new Image();
$image->campaign_id = $this->campaign->id;
$image->created_by = auth()->user()->id;
$image->ext = $uploadedFile->extension();
$image->size = (int) ceil($uploadedFile->getSize() / 1024); // kb
$image->name = mb_substr($name, 0, 45);
$image->visibility_id = $this->campaign->defaultVisibilityID();
$image->save();

$uploadedFile
->storePubliclyAs(
$image->folder,
$image->file,
['disk' => 's3']
);

$file = new EntityAsset();
$file->type_id = EntityAsset::TYPE_FILE;
$file->entity_id = $this->entity->id;
$file->metadata = [
'path' => $path,
'size' => $uploadedFile->getSize(),
'type' => $uploadedFile->getMimeType(),
];
$file->name = $name;
$file->visibility_id = $request->get('visibility_id', 1);
$file->is_pinned = $request->get('is_pinned', 1);
$file->image_uuid = $image->id;
$file->save();

Cache::forget('campaign_' . $this->campaign->id . '_gallery');

return $file;
}
}
6 changes: 3 additions & 3 deletions app/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -475,9 +475,9 @@ public function isFrauding(): bool
}*/
// Recent fails are a clear indicator of someone cycling through cards
return $this->logs()
->where('type_id', UserLog::TYPE_FAILED_CHARGE_EMAIL)
->whereDate('created_at', '>=', Carbon::now()->subHour()->toDateString())
->count() >= 2;
->where('type_id', UserLog::TYPE_FAILED_CHARGE_EMAIL)
->whereDate('created_at', '>=', Carbon::now()->subHour()->toDateString())
->count() >= 2;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class () extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('entity_assets', function (Blueprint $table) {
$table->uuid('image_uuid')->nullable();
$table->foreign('image_uuid')->references('id')->on('images')->cascadeOnDelete();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('entity_assets', function (Blueprint $table) {
$table->dropForeign('entity_assets_image_uuid_foreign');
$table->dropColumn('image_uuid');
});
}
};
2 changes: 1 addition & 1 deletion resources/views/entities/components/assets.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
?>
@foreach ($model->entity->pinnedFiles as $asset)
<a href="{{ Storage::url($asset->metadata['path']) }}" target="_blank" class="pinned-asset child icon" data-asset="{{ \Illuminate\Support\Str::slug($asset->name) }}" data-target="{{ $asset->id }}">
<a href="{{ $asset->url() }}" target="_blank" class="pinned-asset child icon" data-asset="{{ \Illuminate\Support\Str::slug($asset->name) }}" data-target="{{ $asset->id }}">
{{ $asset->name }}
</a>
@endforeach
Expand Down
2 changes: 1 addition & 1 deletion resources/views/gallery/_image.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
</div>
</div>
@else
@if ($image->isFont())
@if ($image->isFont() || $image->isFile())
spitfire305 marked this conversation as resolved.
Show resolved Hide resolved
<div class="grow w-full flex flex-col justify-center items-center gap-2">
<x-icon class="fa-regular fa-file text-4xl"></x-icon>
</div>
Expand Down
Loading