src/Controller/FrontController.php line 60

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Account;
  4. use App\Entity\Live;
  5. use App\Entity\Planning;
  6. use App\Entity\Program;
  7. use App\Entity\Video;
  8. use App\Entity\VideoReading;
  9. use App\Form\AccountType;
  10. use Doctrine\DBAL\Exception;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  18. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  19. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  20. use Symfony\Component\Serializer\Serializer;
  21. class FrontController extends AbstractController
  22. {
  23.     protected $messages = [];
  24.     protected $session;
  25.     protected $em;
  26.     public function __construct(SessionInterface $sessionEntityManagerInterface $entityManager)
  27.     {
  28.         $this->em $entityManager;
  29.         $this->session $session;
  30.         $this->messages = [
  31.             'infos' => [],
  32.             'errors' => []
  33.         ];
  34.     }
  35.     /**
  36.      * @param string $info
  37.      */
  38.     protected function addInfo(string $info) : void{
  39.         $this->messages['infos'][] = $info;
  40.     }
  41.     /**
  42.      * @param string $error
  43.      */
  44.     protected function addError(string $error) : void{
  45.         $this->messages['errors'][] = $error;
  46.     }
  47.     /**
  48.      * Display all available videos + live
  49.      * path : /
  50.      * @param Request $request
  51.      * @return Response
  52.      */
  53.     public function displayVideos(Request $request): Response
  54.     {
  55.         // If the user is connected
  56.         if ($this->session->get('ce') !== null) {
  57.             // Get the planning today's planning
  58.             $allPlannings $this->em->getRepository(Planning::class)
  59.                 ->findAll();
  60.             $plannings = [];
  61.             $days = [
  62.                 'Monday' => 'Lundi',
  63.                 'Tuesday' => 'Mardi',
  64.                 'Wednesday' => 'Mercredi',
  65.                 'Thursday' => 'Jeudi',
  66.                 'Friday' => 'Vendredi',
  67.                 'Saturday' => 'Samedi',
  68.                 'Sunday' => 'Dimanche',
  69.             ];
  70.             foreach ($allPlannings as $planning){
  71.                 // check if the days is == today
  72.                 if(strtolower($planning->getDay()) === strtolower($days[date("l")])){
  73.                     $plannings[] = $planning;
  74.                 }
  75.             }
  76.             // get all programs if planning doenst exist
  77.             $programs $this->em->getRepository(Program::class)
  78.                 ->findAll();
  79.             //get active live id
  80.             $live $this->em->getRepository(Live::class)
  81.                 ->findOneBy(["isActive" => true]);
  82.             if($live == null) {
  83.                 $liveId 0;
  84.             } else {
  85.                 $liveId $live->getLiveId();
  86.             }
  87.             // Get all videos from database
  88. //            todo : lang selector ?
  89.             $videos $this->em->getRepository(Video::class)
  90.                 ->findBy(['displayed' => '1']);
  91.             return $this->render('front/videos.html.twig', [
  92.                 'messages' => $this->messages,
  93.                 'ce' => $this->session->get('ce'),
  94.                 'plannings' => $plannings,
  95.                 'videos' => $videos,
  96.                 'live' => $liveId,
  97.                 'imgPath' => 'img/vignettes/',
  98.                 'vimeoUrl' => 'https://player.vimeo.com/video/',
  99.                 'programs' => $programs,
  100.             ]);
  101.         }
  102.         else{
  103.             return $this->redirectToRoute('signIn');
  104.         }
  105.     }
  106.     /**
  107.      * Display the LM video Player
  108.      * path: /lesmills-video-player
  109.      * @param Request $request
  110.      * @return Response
  111.      */
  112.     public function displayLMVideos(Request $request): Response
  113.     {
  114.         // If the user is connected
  115.         if ($this->session->get('ce') !== null) {
  116.             return $this->render('front/LMVideoPlayer.html.twig', [
  117.                 'messages' => $this->messages,
  118.                 'ce' => $this->session->get('ce'),
  119.             ]);
  120.         }
  121.         else{
  122.             return $this->redirectToRoute('signIn');
  123.         }
  124.     }
  125.     /**
  126.      * bad 6f18e73f49
  127.      * good 42c241ea77
  128.      * Allow the user to sign in with the club access code
  129.      * path: /signIn
  130.      * @param Request $request
  131.      * @return Response
  132.      */
  133.     public function signIn(Request $request) : Response
  134.     {
  135.         // If the user is connected
  136.         if ($this->session->get('ce') !== null) {
  137.             return $this->redirectToRoute('videos');
  138.         }
  139.         else{
  140.             $account = new Account();
  141.             $form $this->createForm(AccountType::class, $account);
  142.             if ($request->isMethod('POST')) {
  143.                 $form->submit($request->request->get($form->getName()));
  144.                 if ($form->isSubmitted() && $form->isValid()) {
  145.                     // set the CE from access code
  146.                     $account->getCEByCode();
  147.                     // check the accessCode
  148.                     // If it doesn't work
  149.                     if (!$account->isEligible()) {
  150.                         $this->addError('Le code est erroné, veuillez contacter le référent de votre club pour l\'obtenir');
  151.                     }
  152.                     // if it works
  153.                     else {
  154.                         $this->session->set('accessCode'$account->getAccessCode());
  155.                         $this->session->set('ce'$account->getCe());
  156.                         return $this->redirectToRoute('videos');
  157.                     }
  158.                 }
  159.             }
  160.             return $this->render('front/signIn.html.twig', [
  161.                 'form' => $form->createView(),
  162.                 'messages' => $this->messages,
  163.             ]);
  164.         }
  165.     }
  166.     /**
  167.      * Sign out a user
  168.      * path: /signOut
  169.      * @return RedirectResponse
  170.      */
  171.     public function signOut() : RedirectResponse
  172.     {
  173.         // If the user is connected
  174.         if ($this->session->get('ce') === null) {
  175.             return $this->redirectToRoute('signIn');
  176.         }
  177.         else{
  178.             $this->session->set('accessCode'null);
  179.             $this->session->set('ce'null);
  180.             return $this->redirectToRoute('signIn');
  181.         }
  182.     }
  183.     /**
  184.      * Display the planning from today to future
  185.      * path: /planning
  186.      */
  187.     public function displayPlanning() : Response
  188.     {
  189.         $planningsByDay = [];
  190.         // get all Planning objects of date >= today
  191.         $plannings $this->em->getRepository(Planning::class)
  192.             ->findBy([], ['day' => 'asc''hour'=>'asc']);
  193.         if(count($plannings) === 0){
  194.             $this->addError('Aucun planning disponible actuellement');
  195.         }
  196.         else{
  197.             foreach ($plannings as $planning){
  198.                 $day $planning->getDay()->getName();
  199.                 if(!empty($day) && !array_key_exists($day$planningsByDay)){
  200.                     $planningsByDay[$day] = [];
  201.                 }
  202.                 $planningsByDay[$day][] = $planning;
  203.             }
  204.         }
  205.         // Display them
  206.         return $this->render('front/plannings.html.twig', [
  207.             'plannings' => $planningsByDay,
  208.             'messages' => $this->messages,
  209.         ]);
  210.     }
  211.     /**
  212.      * Adds a video view when an user clicks on a video
  213.      * path: /addVideoView (POST)
  214.      * @param Request $request
  215.      * @return JsonResponse
  216.      */
  217.     public function AjaxAddVideoView(Request $request) : JsonResponse
  218.     {
  219.         // get The Video ID from the Ajax
  220.         $videoId $request->request->get('videoId'0);
  221.         $video $this->em->find(Video::class, (int)$videoId);
  222.         $ceCode $this->session->get('ce');
  223.         if($video !== null && $video instanceof Video && !is_null($ceCode)){
  224.             // add a new VideoReading
  225.             $videoReading = (new VideoReading())
  226.                 ->setCodeCE($ceCode)
  227.                 ->setUserIp($_SERVER['REMOTE_ADDR'])
  228.                 ->setVideo($video)
  229.                 ->setReadingDate(new \DateTime('NOW'));
  230.             $this->em->persist($videoReading);
  231.             $this->em->flush();
  232.             return new JsonResponse('ok');
  233.         }
  234.         else{
  235.             return new JsonResponse('error');
  236.         }
  237.     }
  238.     /**
  239.      * Get all videos corresponding to criteria
  240.      * @param Request $request
  241.      * @return JsonResponse
  242.      */
  243.     public function AjaxGetVideos(Request $request): JsonResponse
  244.     {
  245.         $programId = (int)$request->query->get('programId'0);
  246.         if($programId === 0){
  247.             $videos $this->em->getRepository(Video::class)->findAll();
  248.         }
  249.         else{
  250. //            $program = $this->em->find(Program::class, (int)$programId);
  251. //            $videos = $program->getVideos();
  252.             $videos $this->em->getRepository(Video::class)->findBy(['program'=> $programId]);
  253.         }
  254.         // avoid circular reference exception
  255.         $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
  256. //        $data = $serializer->normalize($videos, 'json', ['groups' => 'lightGroup']);
  257. //        return $this->json($data);
  258.         $jsonObject $serializer->serialize($videos'json', [
  259.             'circular_reference_handler' => function ($object) {
  260.                 return $object->getId();
  261.             }
  262.         ]);
  263.         return $this->json($jsonObjectResponse::HTTP_OK, [], [ObjectNormalizer::GROUPS => ['lightGroup']]);
  264. //        return new JsonResponse($jsonObject);
  265.     }
  266.     /**
  267.      * Generate a analytics file frome database
  268.      * returns the file
  269.      * path: /admin-generate-analytics
  270.      * @return Response
  271.      * @throws \Doctrine\DBAL\Driver\Exception
  272.      * @throws \Doctrine\DBAL\Exception
  273.      */
  274.     public function generateAnalyticsCSVExport() : response
  275.     {
  276.         $rawQuery '
  277.         SELECT vr.code_ce as Code_CE, vr.user_ip as User_IP, v.vimeo_number as Vimeo_number, p.program_name as Programme, vr.reading_date as heure
  278.         FROM video_reading vr
  279.         INNER JOIN video v 
  280.         ON vr.video_id = v.id
  281.         INNER JOIN video_program vp
  282.         ON v.id=vp.video_id
  283.         INNER JOIN program p 
  284.         ON vp.program_id = p.id';
  285.         $statement $this->em->getConnection()->prepare($rawQuery);
  286.         $statement->execute();
  287.         $results $statement->fetchAllAssociative();
  288.         $newFileName $this->getParameter('kernel.project_dir') . '/public/files/export_csv/analytics/' sha1((new \DateTime('now'))->format('Y-m-d H:i:s')) . '.csv';
  289.         $data 'Code CE;User IP;Vimeo number;Program name;Date;' .
  290.             "\r\n";
  291.         foreach ($results as $result){
  292.             $data .=
  293.                 $result['Code_CE'] . ';' .
  294.                 $result['User_IP'] . ';' .
  295.                 $result['Vimeo_number'] . ';' .
  296.                 $result['Programme'] . ';' .
  297.                 $result['heure'] . ';' .
  298.                 "\r\n";
  299.         }
  300.         file_put_contents($newFileName$data);
  301.         return $this->file($newFileName'analytics.csv');
  302.     }
  303.     /**
  304.      * Generate a analytics file frome database
  305.      * returns the result as JSON
  306.      * path: /webservice-video-analytics
  307.      * @param Request $request
  308.      * @return JsonResponse
  309.      */
  310.     public function generateAnalyticsJson(Request $request) : JsonResponse
  311.     {
  312.         $token $request->query->get('API_Token');
  313.         $response = new JsonResponse();
  314.         if($token === substr(sha1('Planet Fitness'), 050)){
  315.             $rawQuery '
  316.             SELECT vr.code_ce as Code_CE, vr.user_ip as User_IP, v.vimeo_number as Vimeo_number, p.program_name as Programme, vr.reading_date as heure
  317.             FROM video_reading vr
  318.             INNER JOIN video v 
  319.             ON vr.video_id = v.id
  320.             INNER JOIN video_program vp
  321.             ON v.id=vp.video_id
  322.             INNER JOIN program p 
  323.             ON vp.program_id = p.id';
  324.             try {
  325.                 $statement $this->em->getConnection()->prepare($rawQuery);
  326.             }
  327.             catch (Exception $e) {
  328.                 $response->setData($e->getMessage());
  329.                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
  330.                 return $response;
  331.             }
  332.             try {
  333.                 $statement->execute();
  334.             }
  335.             catch (\Doctrine\DBAL\Driver\Exception $e) {
  336.                 $response->setData($e->getMessage());
  337.                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
  338.                 return $response;
  339.             }
  340.             try {
  341.                 $results $statement->fetchAllAssociative();
  342.             }
  343.             catch (\Doctrine\DBAL\Driver\Exception $e) {
  344.                 $response->setData($e->getMessage());
  345.                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
  346.                 return $response;
  347.             }
  348.             $response->setData($results);
  349.             $response->headers->set('Content-Type''application/json');
  350.             $response->setStatusCode(Response::HTTP_OK);
  351.         }
  352.         else{
  353.             $response->setData('You don\'t have the right authorization to see this content');
  354.             $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
  355.         }
  356.         return $response;
  357.     }
  358. }