Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
159 changes: 107 additions & 52 deletions app/Http/Controllers/MediaController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,98 +2,126 @@

namespace App\Http\Controllers;

use App\Models\BlogPost;
use App\Models\Clientele;
use App\Models\CoreValue;
use App\Models\CustomPage;
use App\Models\Event;
use App\Models\HomeBanner;
use App\Models\JobApplication;
use App\Models\NewsPost;
use App\Models\Review;
use App\Models\Service;
use App\Models\StaticInformation;
use App\Models\TeamMember;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;
use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidConversion;

class MediaController extends Controller
{
protected $imageManager;

protected $mediaModelsToBeRestrict = [];
protected $mediaModelsToBeRestrict = [
'businessDocumentTransactions',
'emailTemplates',
'emails'
];

public function __construct()
{
$this->middleware('cache.headers:private;max_age=2592000;etag');
if (in_array(request()->route('model'), $this->mediaModelsToBeRestrict))
$this->middleware('auth')->except(['getDefaultImage']);
$this->middleware('auth')->except(['getDefaultImage']);
$this->imageManager = new ImageManager(
driver: new Driver()
);
}


/**
* Returns default image
*
* @param string $resolution
* @param string $type
* @return mixed
*/
public function getDefaultImage($resolution = "",$type = ""){
public function getDefaultImage($resolution = "", $type = "")
{
$resolution = $resolution != "" ? ("_" . $resolution) : "";
$complete_path = resource_path('assets' . DIRECTORY_SEPARATOR . 'images/default/default-image' . $resolution . '.jpg');

if (!empty($type)) {
switch ($type){
switch ($type) {
case '404':
$complete_path = resource_path('assets' . DIRECTORY_SEPARATOR . 'images/404/default-image-404' . $resolution . '.jpg');
break;
default:
$complete_path = resource_path('assets' . DIRECTORY_SEPARATOR . 'images/404/default-image-404' . $resolution . '.jpg');
}
}
return Image::make($complete_path)->response();
}

$image = $this->imageManager->read($complete_path);
return response($image->encode())->header('Content-Type', 'image/jpeg');
}

public function responseImage($model, $modelUuid, $collection, $mediaId, $conversion, $name){
public function responseImage($model, $modelUuid, $collection, $mediaId, $conversion, $name)
{
$modelObject = $this->getModelInstance($model)->findWithUuid($modelUuid);

//Some basic level validations
$media = $modelObject->getMedia($collection)->where('id',$mediaId)->first();
if($media->name != $name){
if (is_null($modelObject)) {
return abort(404);
}
if(is_null($modelObject)){

$media = $modelObject->getMedia($collection)->where('id', $mediaId)->first();

if (!$media || $media->name != $name) {
return abort(404);
}

try {
$conversion = $conversion == "NoC" ? "" : $conversion; // NoC ~ NoConversion
$complete_path = $media->getPath($conversion);
if(file_exists($complete_path)){
return Image::make($complete_path)->response();
}else{
return $this->getDefaultImage($this->getDefaultImageResolutionFromConversion($conversion),'404');

if (file_exists($complete_path)) {
$image = $this->imageManager->read($complete_path);
return response($image->encode())->header('Content-Type', $media->mime_type);
} else {
return $this->getDefaultImage($this->getDefaultImageResolutionFromConversion($conversion), '404');
}
}catch (InvalidConversion $e){
} catch (InvalidConversion $e) {
Log::info("[MODEL OBJECT#$modelObject->id][COLLECTION $collection][CONVERSION $conversion]MEDIA #$media->id] Invalid Conversion");
return abort(404);
}
}


public function response($model, $modelUuid, $collection, $mediaId, $name){
public function response($model, $modelUuid, $collection, $mediaId, $name)
{
$modelObject = $this->getModelInstance($model)->findWithUuid($modelUuid);

//Some basic level validations
$media = $modelObject->getMedia($collection)->where('id',$mediaId)->first();
if(is_null($modelObject)){
if (is_null($modelObject)) {
return abort(404);
}
if(!$media || $media->name != $name){

$media = $modelObject->getMedia($collection)->where('id', $mediaId)->first();

if (!$media || $media->name != $name) {
return abort(404);
}

try {
$complete_path = $media->getPath();
if (file_exists($complete_path)) {
if ($media->mime_type === "application/pdf")
if ($media->mime_type === "application/pdf") {
return response()->file($complete_path);
else
} else {
return response()->download($complete_path);
}
} else {
return abort(404);
}
}catch (\Exception $e){
Log::info("[OTHER MEDIA][MODEL OBJECT#$modelObject->id][COLLECTION $collection][MEDIA #$media->id] Some Exception caught " . $e);
} catch (\Exception $e) {
Log::info("[OTHER MEDIA][MODEL OBJECT#$modelObject->id][COLLECTION $collection][MEDIA #$media->id] Exception: " . $e->getMessage());
return abort(404);
}
}
Expand All @@ -106,33 +134,60 @@ public function getModelInstance($model = 'users'){
return (new User());
}

protected function getDefaultImageResolutionFromConversion($conversion = 'NoC')
{
return match ($conversion) {
'NoC' => '500x500',
'thumb_50x50' => '50x50',
'thumb_100x100' => '100x100',
'thumb_250x250' => '250x250',
'thumb_500x500' => '500x500',
'thumb_1024x1024' => '1024x1024',
'thumb_1500x1500' => '1500x1500',
default => '500x500',
};
}

public function getDefaultImageResolutionFromConversion($conversion = 'NoC'){
switch($conversion){
case 'NoC': return '500x500';
case 'thumb_50x50': return '50x50';
case 'thumb_100x100': return '100x100';
case 'thumb_250x250': return '250x250';
case 'thumb_500x500': return '500x500';
case 'thumb_1024x1024': return '1024x1024';
case 'thumb_1500x1500': return '1500x1500';
default: return '500x500';
}
public function responseMedia($model, $collection, $mediaId, $fileName)
{
$path = $this->getMediaPath($model, $collection, $mediaId, $fileName);
$image = $this->imageManager->read($path);
return response($image->encode())->header('Content-Type', $this->getMimeType($path));
}

public function responseResponsiveMedia($model, $collection, $mediaId, $fileName)
{
$path = $this->getMediaPath($model, $collection, $mediaId, 'responsive-images/' . $fileName);
$image = $this->imageManager->read($path);
return response($image->encode())->header('Content-Type', $this->getMimeType($path));
}

public function responseMedia($model,$collection,$mediaId,$fileName) {
$path = env('CUSTOM_LOCAL_STORE_PATH') . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $model
. DIRECTORY_SEPARATOR . $collection . DIRECTORY_SEPARATOR . $mediaId . DIRECTORY_SEPARATOR . $fileName;
// return $path;
return Image::make($path)->response();
public function responseConversions($model, $collection, $mediaId, $fileName)
{
$path = $this->getMediaPath($model, $collection, $mediaId, 'conversions/' . $fileName);
$image = $this->imageManager->read($path);
return response($image->encode())->header('Content-Type', $this->getMimeType($path));
}
public function responseResponsiveMedia($model,$collection,$mediaId,$fileName) {
$path = env('CUSTOM_LOCAL_STORE_PATH') . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $model
. DIRECTORY_SEPARATOR . $collection . DIRECTORY_SEPARATOR . $mediaId . DIRECTORY_SEPARATOR
. 'responsive-images' . DIRECTORY_SEPARATOR . $fileName;
// return $path;
return Image::make($path)->response();

protected function getMediaPath($model, $collection, $mediaId, $fileName)
{
return config('filesystems.disks.localStore.root')
. DIRECTORY_SEPARATOR . 'media'
. DIRECTORY_SEPARATOR . $model
. DIRECTORY_SEPARATOR . $collection
. DIRECTORY_SEPARATOR . $mediaId
. DIRECTORY_SEPARATOR . $fileName;
}

protected function getMimeType($path)
{
$extension = pathinfo($path, PATHINFO_EXTENSION);
return match (strtolower($extension)) {
'jpg', 'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
default => 'application/octet-stream',
};
}
}
110 changes: 62 additions & 48 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
@@ -1,55 +1,69 @@
<?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
use App\Http\Middleware\Admin\SetFiltersToSession;
use Illuminate\Foundation\Application;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Global Middleware
$middleware->use([
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
]);

/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
// Web Middleware Group
$middleware->group('web', [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
SetFiltersToSession::class,
]);

$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
// API Middleware Group
$middleware->group('api', [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);

$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
// Named/Route Middleware
$middleware->alias([
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,

$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/

return $app;
]);
})
->withSchedule(function (Schedule $schedule) {
// Define scheduled tasks
$schedule->command('temp-uploads:delete')->everyTenMinutes();
})
->withExceptions(function (Exceptions $exceptions) {
//
})
->create();
12 changes: 12 additions & 0 deletions bootstrap/providers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

return [
Codiksh\Generator\CodikshGeneratorServiceProvider::class,
Spatie\Html\HtmlServiceProvider::class,
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
\App\Providers\ViewServiceProvider::class,
];
Loading