Files
hstream-ddl/app/Http/Controllers/ApiController.php
2025-09-18 15:45:17 +02:00

90 lines
2.5 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
class ApiController extends Controller
{
/**
* Get Filesize of File
*/
public function getFileSize(string $folderhash, string $timehash): \Illuminate\Http\JsonResponse
{
try {
// Decrypt Hash
$file = Crypt::decryptString($folderhash);
$time = Crypt::decryptString($timehash);
} catch (DecryptException $e) {
return response()->json([
'error' => 'Invalid Token!',
], 500);
}
// Check if permitted
if (Carbon::now() > Carbon::parse($time)) {
return response()->json([
'error' => 'Link has expired!',
], 404);
}
if (!Storage::exists($file)) {
return response()->json([
'error' => 'File not found!',
], 404);
}
return response()->json([
'size' => Storage::size($file),
]);
}
/**
* Download File
*/
public function download(string $folderhash, string $timehash)
{
try {
// Decrypt Hash
$file = Crypt::decryptString($folderhash);
$time = Crypt::decryptString($timehash);
// Check if permitted
if (Carbon::now() > Carbon::parse($time)) {
return view('error', ['error' => 'Link has expired!']);
}
if (! Storage::exists($file)) {
return view('error', ['error' => 'File not found!']);
}
$filename = explode('/', $file);
$filePath = storage_path('app/' . $file);
$headers = [
'Content-Type' => Storage::mimeType($file),
'Content-Length' => Storage::size($file),
'Content-Disposition' => 'attachment; filename="' . end($filename) . '"',
];
// Stream the file in chunks to prevent memory issues
return response()->stream(
function () use ($filePath) {
$fd = fopen($filePath, 'rb');
while (!feof($fd)) {
echo fread($fd, 2048);
}
},
200,
$headers
);
} catch (DecryptException $e) { }
return view('error', ['error' => 'Invalid Token!']);
}
}