🚚 Passe toutes les images sous MediaLibrary

Fix #14
This commit is contained in:
Clement Desmidt 2020-03-19 12:11:21 +01:00
parent 9ec28afa4a
commit 3ab7e495e9
10 changed files with 131 additions and 73 deletions

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Requests\AddPost;
use App\Post; use App\Post;
use App\PostsTag; use App\PostsTag;
use App\Services\ImageService; use App\Services\ImageService;
@ -11,6 +12,9 @@ use DateTime;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Redirect;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\DiskDoesNotExist;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileDoesNotExist;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileIsTooBig;
class DashboardController extends Controller class DashboardController extends Controller
{ {
@ -72,39 +76,35 @@ class DashboardController extends Controller
/** /**
* Edit today's entry * Edit today's entry
* @param AddPost $request
* @param TagDetectorService $tag_detector
* @return
* @throws \Exception
*/ */
public function edit(TagDetectorService $tag_detector) public function edit(AddPost $request, TagDetectorService $tag_detector)
{ {
/** @var Post $today_post */ /** @var Post $today_post */
$today_post = Post::whereDate('date_post', '=', (new DateTime())->format('Y-m-d')) $today_post = Post::whereDate('date_post', '=', (new DateTime())->format('Y-m-d'))
->where('user_id', Auth::user()->getAuthIdentifier()) ->where('user_id', Auth::user()->getAuthIdentifier())
->firstOrFail(); ->firstOrFail();
$data = request()->validate([ $data = $request->validated();
'message' => 'required'
]);
$today_post->deleteTags(); if (!empty($validated_data['file'])) {
try {
$tags = $tag_detector->detectFrom($data['message']); $today_post->addMediaFromRequest('file')->toMediaCollection('post_image');
} catch (DiskDoesNotExist $e) {
$today_post->content = $data['message']; } catch (FileDoesNotExist $e) {
$today_post->save(); } catch (FileIsTooBig $e) {
$all_tags = Tag::all();
$all_tags_names = [];
foreach ($all_tags as $tag) {
$all_tags_names[$tag->id] = $tag->name;
}
foreach ($tags as $tag) {
if (in_array($tag, $all_tags_names)) {
PostsTag::create([
'post_id' => $today_post->id,
'tag_id' => array_search($tag, $all_tags_names),
]);
} }
} }
$today_post->deleteTags();
$today_post->content = $data['message'];
$today_post->save();
$this->setPostsTagsForPost($today_post, $tag_detector->detectFrom($data['message']));
return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.'); return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.');
} }
@ -127,37 +127,42 @@ class DashboardController extends Controller
} }
/** /**
* @param AddPost $request
* @param TagDetectorService $tag_detector * @param TagDetectorService $tag_detector
* @return mixed * @return mixed
* @throws \Exception * @throws \Exception
*/ */
public function store(TagDetectorService $tag_detector, ImageService $image_service) public function store(AddPost $request, TagDetectorService $tag_detector)
{ {
$user_id = Auth::user()->getAuthIdentifier(); $validated_data = $request->validated();
$validated_data = request()->validate([ /** @var Post $post */
'message' => 'required', $post = Post::create([
'file' => 'file|mimes:jpeg,png,jpg,gif,svg', 'user_id' => Auth::user()->getAuthIdentifier(),
]);
$data = [
'user_id' => $user_id,
'date_post' => new DateTime(), 'date_post' => new DateTime(),
'content' => $validated_data['message'], 'content' => $validated_data['message'],
]; ]);
if (!empty($validated_data['file'])) { if (!empty($validated_data['file'])) {
/** @var UploadedFile $uploaded_document */ try {
$uploaded_document = $validated_data['file']; $post->addMediaFromRequest('file')->toMediaCollection('post_image');
$file_name = $uploaded_document->getClientOriginalName(); } catch (DiskDoesNotExist $e) {
$uploaded_document->storeAs(Auth::user()->getFolder(), $file_name); } catch (FileDoesNotExist $e) {
$image_service->makeThumbnail($uploaded_document->getRealPath(), ['width' => 300]); } catch (FileIsTooBig $e) {
$data['image'] = $file_name; }
} }
$tags = $tag_detector->detectFrom($data['content']); $this->setPostsTagsForPost($post, $tag_detector->detectFrom($validated_data['message']));
$check = Post::create($data); return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.');
}
/**
* @param Post $post
* @param $tags
*/
private function setPostsTagsForPost(Post $post, $tags)
{
$all_tags = Tag::all(); $all_tags = Tag::all();
$all_tags_names = []; $all_tags_names = [];
foreach ($all_tags as $tag) { foreach ($all_tags as $tag) {
@ -165,14 +170,12 @@ class DashboardController extends Controller
} }
foreach ($tags as $tag) { foreach ($tags as $tag) {
if (in_array($tag, $all_tags_names)) { if (in_array($tag, $all_tags_names, true)) {
PostsTag::create([ PostsTag::create([
'post_id' => $check->id, 'post_id' => $post->id,
'tag_id' => array_search($tag, $all_tags_names), 'tag_id' => array_search($tag, $all_tags_names),
]); ]);
} }
} }
return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.');
} }
} }

View File

@ -4,10 +4,11 @@ namespace App\Http\Controllers;
use App\Post; use App\Post;
use App\Services\ImageService; use App\Services\ImageService;
use App\User;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image; use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\File;
use Spatie\MediaLibrary\Models\Media;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
@ -15,28 +16,40 @@ class ImageController extends Controller
{ {
/** /**
* @param int $post_id * @param int $post_id
* @param string|array $options * @param string $alias
* @param string $image * @param string $image
* @param ImageService $image_service * @param ImageService $image_service
* *
* @return mixed * @return mixed
*/ */
public function display($post_id, $options = 'o:full', $image, ImageService $image_service) public function display($post_id, $alias = '')
{ {
/** @var Post $post */
$post = Post::find($post_id); $post = Post::find($post_id);
if (Auth::user()->getAuthIdentifier() !== (int)$post->user_id) { if (Auth::user()->getAuthIdentifier() !== (int)$post->user_id) {
throw new UnauthorizedHttpException('Cette image ne vous appartient pas.'); throw new UnauthorizedHttpException('Cette image ne vous appartient pas.');
} }
$original = sprintf('%s/%s/%s', storage_path('app'), Auth::user()->getFolder(), $image); $first_media = $post->getFirstMedia('post_image');
if ('o:full' === $options) { if (!$first_media instanceof Media) {
$img = $image_service->makeThumbnail($original); throw new NotFoundHttpException('Média non trouvé en base.');
} else {
$img = $image_service->makeThumbnail($original, ['width' => 300]);
} }
return $img->response(File::extension($original)); return Image::make($first_media->getPath($alias))->response($first_media->mime_type);
}
/**
* @param string $alias
* @return mixed
*/
public function avatar($alias = '')
{
/** @var User $user */
$user = User::find(Auth::user()->getAuthIdentifier());
readfile($user->getFirstMediaPath('avatars', $alias));
exit;
} }
/** /**

View File

@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class AddPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return !Auth::guest();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'message' => 'required',
'file' => 'file|mimes:jpeg,png,jpg,gif,svg',
];
}
}

View File

@ -3,9 +3,15 @@
namespace App; namespace App;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Spatie\Image\Exceptions\InvalidManipulation;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\Models\Media;
class Post extends Model class Post extends Model implements HasMedia
{ {
use HasMediaTrait;
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
* *
@ -52,4 +58,18 @@ class Post extends Model
->orderBy('date_post') ->orderBy('date_post')
->get(); ->get();
} }
/**
* @param Media|null $media
*/
public function registerMediaConversions(Media $media = null)
{
try {
$this->addMediaConversion('list')
->width(300)
->optimize();
} catch (InvalidManipulation $e) {
Log::alert(sprintf('Error while manipulating Post Image for %s (%s)', $this->id, $e->getMessage()));
}
}
} }

View File

@ -72,13 +72,4 @@ class User extends Authenticatable implements HasMedia
Log::alert(sprintf('Error while manipulating Avatar for %s (%s)', $this->email, $e->getMessage())); Log::alert(sprintf('Error while manipulating Avatar for %s (%s)', $this->email, $e->getMessage()));
} }
} }
/**
* @param string $alias
* @return string
*/
public function getAvatar($alias = 'thumb'): string
{
return $this->getFirstMediaUrl('avatars', $alias);
}
} }

View File

@ -21,7 +21,7 @@
<div class="card-body"> <div class="card-body">
<p> <p>
<a href="{{ route('display_image', ['post_id' => $post->id, 'options' => 'o:full', 'image_name' => $post->image]) }}"> <a href="{{ route('display_image', ['post_id' => $post->id, 'options' => 'o:full', 'image_name' => $post->image]) }}">
<img src="{{ route('display_image', ['post_id' => $post->id, 'options' => 'w:300', 'image_name' => $post->image]) }}"/> <img src="{{ route('display_image', ['post_id' => $post->id, 'alias' => 'list']) }}"/>
</a> </a>
</p> </p>
</div> </div>

View File

@ -126,8 +126,7 @@
</div> </div>
</div> </div>
<div class="card-body @if($today->format('Y-m-d') === \Carbon\Carbon::instance($post->date_post)->format('Y-m-d')) already @endif "> <div class="card-body @if($today->format('Y-m-d') === \Carbon\Carbon::instance($post->date_post)->format('Y-m-d')) already @endif ">
@if($post->image != '')<p><img src="{{ route('display_image', ['post_id' => $post->id, 'options' => 'w:300', 'image_name' => $post->image]) }}"/></p>@endif @if($post->hasMedia('post_image'))<p><img src="{{ route('display_image', ['post_id' => $post->id]) }}"/></p>@endif <p data-encrypt>{!! $tag_detector->linkTagFrom($post->content) !!}</p>
<p data-encrypt>{!! $tag_detector->linkTagFrom($post->content) !!}</p>
</div> </div>
<div class="card-footer"> <div class="card-footer">
{{ \Carbon\Carbon::instance($post->date_post)->format('d F Y') }} {{ \Carbon\Carbon::instance($post->date_post)->format('d F Y') }}

View File

@ -55,10 +55,10 @@
</div> </div>
<div class="dropdown"> <div class="dropdown">
<a href="#" class="nav-link pr-0 leading-none" data-toggle="dropdown"> <a href="#" class="nav-link pr-0 leading-none" data-toggle="dropdown">
@php($avatar = Auth::user()->getAvatar('icon')) @php($avatar = Auth::user()->hasMedia('avatars'))
@if($avatar !== '') @if($avatar !== '')
<span> <span>
<img src="{{ $avatar }}"/> <img src="{{ route('display_avatar', ['alias' => 'icon']) }}"/>
</span> </span>
@else @else
<span class="avatar"> <span class="avatar">

View File

@ -81,9 +81,8 @@
<div class="col-md-6 col-lg-4"> <div class="col-md-6 col-lg-4">
<div class="form-group"> <div class="form-group">
<div class="form-label">{{ __('Avatar') }}</div> <div class="form-label">{{ __('Avatar') }}</div>
@php($avatar = Auth::user()->getAvatar()) @if(Auth::user()->hasMedia('avatars'))
@if($avatar !== '') <img src="{{ route('display_avatar', ['alias' => 'thumb'])}}">
<img src="{{ $avatar}}">
@endif @endif
<div class="custom-file"> <div class="custom-file">
<input type="file" class="custom-file-input" name="avatar"> <input type="file" class="custom-file-input" name="avatar">

View File

@ -32,7 +32,8 @@ Route::group(['middleware' => ['auth']], function() {
Route::get('/calendar/{type}/{year?}/{month?}', 'StatsController@calendar')->name('calendar'); Route::get('/calendar/{type}/{year?}/{month?}', 'StatsController@calendar')->name('calendar');
// gallery // gallery
Route::get('/display/{post_id}/{options}/{image_name}', 'ImageController@display')->name('display_image'); Route::get('/avatar/{alias}', 'ImageController@avatar')->name('display_avatar');
Route::get('/display/{post_id}/{alias?}', 'ImageController@display')->name('display_image');
Route::get('/gallery', 'ImageController@gallery')->name('gallery'); Route::get('/gallery', 'ImageController@gallery')->name('gallery');
// user // user