<?php
declare(strict_types=1);
namespace Hitso\Bundle\FileManagerBundle\Controller\Front;
use Hitso\Bundle\CommonBundle\Controller\Controller;
use Hitso\Bundle\FileManagerBundle\Entity\DisposableLink;
use Hitso\Bundle\FileManagerBundle\Entity\Download;
use Hitso\Bundle\FileManagerBundle\Entity\File;
use Hitso\Bundle\FileManagerBundle\Manager\DisposableLinkManager;
use Hitso\Bundle\FileManagerBundle\Manager\FileManager;
use Hitso\Bundle\FileManagerBundle\Repository\DownloadRepository;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
class DownloadController extends Controller
{
/**
* @var FileManager
*/
protected $fileManager;
/**
* @var DisposableLinkManager
*/
protected $disposableLinkManager;
public function __construct(FileManager $fileManager, DisposableLinkManager $disposableLinkManager)
{
$this->fileManager = $fileManager;
$this->disposableLinkManager = $disposableLinkManager;
}
/**
* @Route("/share/{token}", name="fm_share", defaults={"token"=null})
*/
public function shareAction(string $token)
{
$disposableLink = $this->disposableLinkManager->getRepository()->findOneBy(['token' => $token]);
if ($disposableLink instanceof DisposableLink && $disposableLink->isValid()) {
$file = $disposableLink->getFile();
$fileName = $this->fileManager->getFs()->getFullPathname($file);
$response = new StreamedResponse(
function () use ($fileName) {
readfile($fileName);
}, 200, [
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment;filename="' . $file->getName() . '"',
]
);
$this->disposableLinkManager->removeResource($disposableLink);
return $response;
}
throw $this->createNotFoundException('Podany plik nie istnieje lub link utracił ważność.');
}
/**
* @Route("/file/stream/{id}/{name}", name="fm_file", defaults={"id"=null,"name"=null})
*/
public function streamAction(File $file): BinaryFileResponse
{
if ($file->isDisposable()) {
return $this->redirectToRoute('homepage');
}
$path = $this->fileManager->getFs()->getFullPathname($file);
return $this->file($path, $file->getName(), ResponseHeaderBag::DISPOSITION_INLINE);
}
/**
* @Route("/file/download/{id}", name="file_download", defaults={"id"=null})
*/
public function downloadAction(File $file): StreamedResponse
{
if ($file->isDisposable()) {
return $this->redirectToRoute('homepage');
}
$fileName = $this->fileManager->getFs()->getFullPathname($file);
$response = new StreamedResponse(
function () use ($fileName) {
readfile($fileName);
}, 200, [
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment;filename="' . $file->getName() . '"',
]
);
return $response;
}
}