src/Controller/ChannelController.php line 111

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Channel;
  4. use App\Form\ChannelType;
  5. use App\Image\Processor;
  6. use App\Repository\ChannelRepository;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\File\UploadedFile;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  12. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  13. use Symfony\Component\HttpKernel\Exception\HttpException;
  14. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  17. /**
  18.  * @Route("/channel")
  19.  */
  20. class ChannelController extends AbstractController
  21. {
  22.     /**
  23.      * @IsGranted("ROLE_USER")
  24.      * @Route("/new", name="channel_new", methods={"GET","POST"})
  25.      */
  26.     public function new(Request $request): Response
  27.     {
  28.         $channel = new Channel();
  29.         $channel->setKey(substr(base64_encode(random_bytes(30)), 016));
  30.         $channel->setUser($this->getUser());
  31.         $form $this->createForm(ChannelType::class, $channel);
  32.         $form->handleRequest($request);
  33.         if ($form->isSubmitted() && $form->isValid()) {
  34.             $entityManager $this->getDoctrine()->getManager();
  35.             $entityManager->persist($channel);
  36.             $entityManager->flush();
  37.             return $this->redirectToRoute('channel_edit', ['id' => $channel->getId()], Response::HTTP_SEE_OTHER);
  38.         }
  39.         return $this->renderForm('channel/new.html.twig', [
  40.             'channel' => $channel,
  41.             'form' => $form,
  42.         ]);
  43.     }
  44.     private function getFileName(Channel $channel): string
  45.     {
  46.         return "raw.jpg";
  47.     }
  48.     private function processPostFile(Request $requestChannel $channel)
  49.     {
  50.         if($request->files->count() === 0) {
  51.             throw new BadRequestHttpException("No file uploaded");
  52.         }
  53.         $first $request->files->keys()[0];
  54.         /** @var UploadedFile $uploadedImage */
  55.         $uploadedImage $request->files->get($first);
  56.         if ($uploadedImage->getError()) {
  57.             throw new BadRequestHttpException($uploadedImage->getErrorMessage());
  58.         }
  59.         if (!$uploadedImage->getSize()) {
  60.             throw new BadRequestHttpException("Zero size");
  61.         }
  62.         $mime $uploadedImage->getMimeType();
  63.         $allowedMime = ['image/jpeg'];
  64.         if (!in_array($mime$allowedMime)) {
  65.             throw new BadRequestHttpException("MIME \"$mime\" is not allowed");
  66.         }
  67.         $processor = new Processor();
  68.         $path $channel->getDataDirectory(true) . $this->getFileName($channel);
  69.         $processor->process($uploadedImage->getContent(), $path$channel);
  70.         
  71.         $channel->ensureDirectory();
  72.         $uploadedImage->move($channel->getDataDirectory(), $this->getFileName($channel));
  73.     }
  74.     private function processPutFile(Request $requestChannel $channel)
  75.     {
  76.         $content $request->getContent();
  77.         $channel->ensureDirectory();
  78.         $path $channel->getDataDirectory(true) . $this->getFileName($channel);
  79.         $res file_put_contents($path$content);
  80.         if ($res === false) {
  81.             throw new BadRequestHttpException("Write file error");
  82.         }
  83.         if ($res === 0) {
  84.             @unlink($path);
  85.             throw new BadRequestHttpException("Zero file written?!");
  86.         }
  87.         $processor = new Processor();
  88.         $path $channel->getDataDirectory(true) . $this->getFileName($channel);
  89.         $processor->process($content$path$channel);
  90.     }
  91.     /**
  92.      * @Route("/{slug}", name="channel_show", methods={"GET", "POST", "PUT"})
  93.      */
  94.     public function show(Request $requestChannel $channel): Response
  95.     {
  96.         if ($request->getMethod() !== 'GET') {
  97.             $key $request->get('key') ?? $request->server->get('QUERY_STRING');
  98.             if (empty($key)) {
  99.                 throw new BadRequestHttpException("No key in request");
  100.             }
  101.             if ($key !== $channel->getKey()) {
  102.                 throw new BadRequestHttpException("Invalid channel key '".$key."'");
  103.             }
  104.             if ($request->getMethod() === 'POST') {
  105.                 $this->processPostFile($request$channel);
  106.             } else if ($request->getMethod() === 'PUT') {
  107.                 $this->processPutFile($request$channel);
  108.             } else {
  109.                 throw new BadRequestHttpException("Method ".$request->getMethod()." not yet allowed");
  110.             }
  111.             $channel->setLastUploadAt(new \DateTime());
  112.             $this->getDoctrine()->getManager()->flush();
  113.             return new Response('OK');
  114.         }
  115.         return $this->render('channel/show.html.twig', [
  116.             'channel' => $channel,
  117.         ]);
  118.     }
  119.     /**
  120.      * @Route("/{slug}/last", name="channel_last", methods={"GET"})
  121.      */
  122.     public function last(Request $requestChannel $channel): Response
  123.     {
  124.         return new Response($channel->getLastUploadAt()->getTimestamp());
  125.     }
  126.     /**
  127.      * @IsGranted("ROLE_USER")
  128.      * @Route("/{id}/edit", name="channel_edit", methods={"GET","POST"})
  129.      */
  130.     public function edit(Request $requestChannel $channel): Response
  131.     {
  132.         $this->checkOwnership($channel);
  133.         $form $this->createForm(ChannelType::class, $channel);
  134.         $form->handleRequest($request);
  135.         if ($form->isSubmitted() && $form->isValid()) {
  136.             $this->getDoctrine()->getManager()->flush();
  137.             return $this->redirectToRoute('user', [], Response::HTTP_SEE_OTHER);
  138.         }
  139.         return $this->renderForm('channel/edit.html.twig', [
  140.             'channel' => $channel,
  141.             'form' => $form,
  142.         ]);
  143.     }
  144.     /**
  145.      * @IsGranted("ROLE_USER")
  146.      * @Route("/{id}/rekey", name="channel_rekey", methods={"GET"})
  147.      */
  148.     public function rekey(Request $requestChannel $channel): Response
  149.     {
  150.         $this->checkOwnership($channel);
  151.         $channel->setKey(substr(base64_encode(random_bytes(30)), 016));
  152.         $entityManager $this->getDoctrine()->getManager();
  153.         $entityManager->flush();
  154.         return $this->redirectToRoute('channel_edit', ['id' => $channel->getId()], Response::HTTP_SEE_OTHER);
  155.     }
  156.     /**
  157.      * @IsGranted("ROLE_USER")
  158.      * @Route("/{id}/delete", name="channel_delete", methods={"POST"})
  159.      */
  160.     public function delete(Request $requestChannel $channel): Response
  161.     {
  162.         $this->checkOwnership($channel);
  163.         if ($this->isCsrfTokenValid('delete'.$channel->getId(), $request->request->get('_token'))) {
  164.             $entityManager $this->getDoctrine()->getManager();
  165.             $entityManager->remove($channel);
  166.             $entityManager->flush();
  167.         }
  168.         return $this->redirectToRoute('user', [], Response::HTTP_SEE_OTHER);
  169.     }
  170.     private function checkOwnership(Channel $channel)
  171.     {
  172.         if ($channel->getUser()->getId() != $this->getUser()->getId()) {
  173.             throw new AccessDeniedHttpException("Nice try, you don't have permissions to do that");
  174.         }
  175.     }
  176. }