src/Controller/Mobile/MobileExerciseController.php line 602

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Mobile;
  3. use Doctrine\ORM\NoResultException;
  4. use Doctrine\ORM\OptimisticLockException;
  5. use Doctrine\ORM\ORMInvalidArgumentException;
  6. use App\Entity\AgeGroup;
  7. use App\Entity\Club;
  8. use App\Entity\Equipment;
  9. use App\Entity\Exercise;
  10. use App\Entity\Library;
  11. use App\Entity\Section;
  12. use App\Entity\Tag;
  13. use App\Repository\CapacityRepository;
  14. use App\Repository\ClubRepository;
  15. use App\Repository\ExerciseRatingRepository;
  16. use App\Repository\ExerciseRepository;
  17. use App\Repository\LibraryRepository;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  25. use InvalidArgumentException;
  26. use JMS\Serializer\SerializationContext;
  27. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
  28. use App\Entity\ExerciseFavorite;
  29. use App\Repository\ExerciseFavoriteRepository;
  30. use Symfony\Component\HttpFoundation\Session\Session;
  31. use App\Helpers\TraitCodeGenerator;
  32. use App\Helpers\TraitHelpers;
  33. use App\Entity\UserSearch;
  34. use App\Repository\UserSearchRepository;
  35. use Vimeo\Vimeo;
  36. use App\Helpers\YoutubeDownloader;
  37. use Symfony\Component\HttpFoundation\RequestStack;
  38. //use App\Module\CustomController; /// Custom Controller class for handling security
  39. class MobileExerciseController extends AbstractController
  40. {
  41.   use TraitHelpers;
  42.   use TraitCodeGenerator;
  43.   const UPDATED_DAYS_THRESHOLD = 30;
  44.   const NEW_DAYS_THRESHOLD = 60;
  45.   private $entityName = 'exercise';
  46.   private $requestStack;
  47.   public function __construct(RequestStack $requestStack)
  48.   {
  49.       $this->requestStack = $requestStack;
  50.   }
  51.     /**
  52.      * List all exercises available in given agegroup
  53.      *
  54.      * @Route("/mobile/exercises/{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/{tagIds}",
  55.      *      requirements={"ageGroup" = "\d+", "id" = "\d+", "limit" = "\d+", "offset" = "\d+", "sort" = "asc|desc|ASC|DESC"}
  56.      *  )
  57.      * @Method("GET")
  58.      *
  59.      * @param   $request    Request
  60.      * @param   $clubId     int
  61.      * @param   $ageGroupId int
  62.      * @param   $limit      int
  63.      * @param   $offset     int
  64.      * @param   $field      string
  65.      * @param   $sort       string
  66.      * @param   $created    string
  67.      * @param   $locale   string
  68.      * @param   $tagIds   string
  69.      *
  70.      * @return JsonResponse
  71.      */
  72.     public function allByClubAndAgeGroup(Request $request,$userId, $clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $locale, $tagIds = "")
  73.     {
  74.         /** @var ExerciseRepository $exerciseRepository */
  75.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  76.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  77.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  78.         /** @var ClubRepository $clubRepository */
  79.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  80.         $session = $this->requestStack->getSession();
  81.          //$session->get('user_id');
  82.         //$userId= $this->requestStack->getSession()->get('user_id');
  83.         $role = $this->requestStack->getSession()->get('user_role');
  84.         $isFavorite= $this->requestStack->getSession()->get('isFavorite');
  85.         if($isFavorite == null){
  86.           $isFavorite = false;
  87.         }
  88.         $sectionId = $request->get('section');
  89.         $club = $clubRepository->find($clubId);
  90.         $clubId = $club ? $club->getClubId() : null;
  91.         $results = $exerciseRepository->searchByClubAndAgeGroup($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role);
  92.         $items = [];
  93.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  94.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  95.         $sql = $results['sql'];
  96.         $ids = $results['ids'];
  97.         $results = $results['results'];
  98. /*
  99.         foreach ($results as $result) {
  100.             //$item = $this->checkCache($result['id'],$result);
  101.             //$item = $this->checkCache($result,$result);
  102.             $item = json_decode($result['desktop'],TRUE);
  103.             //$item['rating'] = $exerciseRatingRepository->getRating($item['id']);
  104.             //$item['userrating'] =  $exerciseRatingRepository->getUserRating($item['id'],$userId);// $item['id'].'--'.$userId;
  105.             //$item['ratingCount'] = $exerciseRatingRepository->getRatingCount($item['id']);
  106.             $item['source'] = $result;
  107.             $items[] = $item;
  108.         }
  109. */
  110.         foreach ($ids as $result) {
  111.             $item = $this->checkCache($result,$result);
  112.             $item['lang'] = $locale;
  113.             $item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
  114.             $item['new'] = $item['createdAt'] >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  115.             $item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  116.             $item['favorite'] = $exerciseRepository->isFavorite($userId,intval($result));
  117.             $items[] = $item;
  118.         }
  119.         $condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds);
  120.         $total = $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role);
  121.         $data = [
  122.             'count' => count($items),
  123.             'sql' => $sql,
  124.             'userId' => $userId,
  125.             'isFavorite'=> $isFavorite,
  126.             'total' => intval($total['total']),
  127.             'total_sql' => count($ids),
  128.             //'total' =>  $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
  129.             'condition' => $condition,
  130.             'created' => $created,
  131.             'items' => $items,
  132.         ];
  133.         $response = new JsonResponse($data);
  134.         //$response
  135.         //    ->setMaxAge(86400)
  136.         //    ->setSharedMaxAge(86400);
  137.         return $response;
  138.     }
  139.             public function checkCache($id,$exercise,$delete = false){
  140.               if($delete == true){
  141.                 $this->deleteSingleCache($id,$this->entityName);
  142.                 $entity = null;
  143.               }else {
  144.                 $entity = $this->getCache($id,$this->entityName);
  145.               }
  146.               if($entity){
  147.                 //$entity = json_decode($entity,true);
  148.                 $entity['from_cache'] = 'yes';
  149.               }else {
  150.                   /** @var ExerciseRepository $exerciseRepository */
  151.                   $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  152.                   $exercise = $exerciseRepository->find($id);
  153.                   $serializer = \JMS\Serializer\SerializerBuilder::create()->build();
  154.                   $entity = json_decode($serializer->serialize(
  155.                       $exercise,
  156.                       'json',
  157.                       SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('tp'))
  158.                   ), true);
  159.                   $this->setCache($id,$this->entityName,$entity);
  160.                   $entity['from_cache'] = 'no';
  161.               }
  162.               return $entity;
  163.             }
  164.     /**
  165.      * Get Exercise
  166.      *
  167.      * @Route("/mobile/exercises/{id}/{locale}/{userId}", requirements={"id" = "\d+"})
  168.      * @Method("GET")
  169.      *
  170.      * @param   int $id
  171.      * @throws  NotFoundHttpException
  172.      * @return  JsonResponse
  173.      */
  174.     public function getAction($id,$locale = null,$userId)
  175.     {
  176.         if($locale == null){
  177.           $locale = $this->getParameter('LHdefLang');
  178.         }
  179.         /** @var ExerciseRepository $exerciseRepository */
  180.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  181.         $exercise = $exerciseRepository->find($id);
  182.         if (!$exercise) {
  183.             throw new NotFoundHttpException(sprintf(
  184.                 'Exercise with ID %s does not exist!', $id
  185.             ));
  186.         }
  187.         $data = $this->checkCache($exercise->getId(),$exercise);
  188.         $data['lang'] = $locale;
  189.         /** @var ExerciseFavoriteRepository $exerciseFavoriteRepository */
  190.         $exerciseFavoriteRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseFavorite::class);
  191.         $exerciseFavorite = $exerciseFavoriteRepository->findOneBy(array('exerciseId'=>$data['id'],'userId'=>$userId));
  192.         if($exerciseFavorite){
  193.           $data['favorite'] = 1;
  194.         }else {
  195.           $data['favorite'] = 0;
  196.         }
  197.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  198.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  199.         $exId = $exercise->getId();
  200.         $data['totalRating'] = round($exerciseRatingRepository->getRating($exId),1);
  201.         $data['stars'] = round($data['totalRating']);
  202.         $data['userRating'] =  $exerciseRatingRepository->getUserRating($exId,$userId);
  203.         $data['ratingCount'] = $exerciseRatingRepository->getRatingCount($exId);
  204.         $data['clubInitials'] = $exercise->getClub() != null ? $exercise->getClub()->getInitials() : null ;
  205.         $data['new'] = $exercise->getCreatedAt() >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  206.         $data['updated'] = !$data['new'] && $exercise->getUpdatedAt() >=  time() - (86400*30);
  207.         $return = [];
  208.         $video = $exercise->translate($locale)->getVideoUrl();
  209.         $data['vimeoLink'] = '';
  210.         $data['streamingUrl'] = '';
  211.         if(strpos($video, 'youtu') != false){
  212.           $videoData = $this->getVideoInfoTest($video);
  213.           //return new JsonResponse($videoData);
  214.           $data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
  215.           $data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
  216.         }
  217.         if(strpos($video, 'vimeo') != false){
  218.         $videoId = explode('/',$video);
  219.         $videoId = $videoId[count($videoId)-1];
  220.         $client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
  221.         $response = $client->request('/videos/'.$videoId, array(), 'GET');
  222.         $lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
  223.         $data['vimeoLink'] =  $response['body']['files'][$lookup]['link'];
  224.         $data['streamingUrl'] = $data['vimeoLink'];
  225.         }
  226.         //return new JsonResponse($data);
  227.         $return[0] = $data;
  228.         return new JsonResponse($return);
  229.     }
  230.     /**
  231.      * Exercise Favorites
  232.      * @Route("/mobile/exercises/favoritesfilter/{userId}/{locale}/{ageGroupId}/{libId}/{search}")
  233.      * @Method("GET")
  234.      *
  235.      *
  236.      * @return array|null
  237.      */
  238.     public function favoritesFilterAction($userId = null, $locale = "com",$ageGroupId = 0, $libId = null, $search = null)
  239.     {
  240.         /** @var ClubRepository $clubRepository */
  241.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  242.         /** @var ExerciseRepository $exerciseRepository */
  243.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  244.         /** @var UserRepository $userRepository */
  245.         $userRepository = $this->getDoctrine()->getRepository(\App\Entity\User::class);
  246.         /** @var CountryRepository $countryRepository */
  247.         $countryRepository = $this->getDoctrine()->getRepository(\App\Entity\Country::class);
  248.         //$locale = $request->get('locale');
  249.         //$ageGroupId = $request->get('agegroupid');
  250.         //$clubId = $request->get('clubid');
  251.         //$userId = $request->get('userid');
  252.         //echo $userId.'/'.$ageGroupId.'/'.$locale;die();
  253.             $results = $exerciseRepository->favorites($userId,$locale,$ageGroupId, $libId, $search);
  254.         $data = array();
  255.         $items = [];
  256.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  257.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  258.         foreach ($results as $key => $result) {
  259.             $items[$key] = $this->checkCache($result->getId(),$result);
  260.             //$items[$key]['rating'] = $exerciseRatingRepository->getRating($items[$key]['id']);
  261.             $items[$key]['userrating'] = $exerciseRatingRepository->getUserRating($items[$key]['id'],$userId);
  262.             $items[$key]['lang'] = $locale;
  263.             $items[$key]['clubInitials'] = $result->getClub() != null ? $result->getClub()->getInitials() : null ;
  264.             $items[$key]['new'] = $result->getCreatedAt() >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  265.             $items[$key]['updated'] = $result->getUpdatedAt() >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  266.             $items[$key]['favorite'] = $exerciseRepository->isFavorite($userId,$result->getId());
  267.             //$items[$key]['ratingCount'] = $exerciseRatingRepository->getRatingCount($items[$key]['id']);
  268.         }
  269.         //return new JsonResponse($items);
  270.         $data['count'] = count($items);
  271.         $data['items'] = $items;
  272.         return new JsonResponse($data);
  273.     }
  274. /////////////////////////////
  275.     /**
  276.      * List all exercises available in given agegroup
  277.      *
  278.      * @Route("/mobile/exercises/memyclub/{clubId}/{userId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/{libId}/{search}",
  279.      *      requirements={"ageGroup" = "\d+", "id" = "\d+", "limit" = "\d+", "offset" = "\d+", "sort" = "asc|desc|ASC|DESC"}
  280.      *  )
  281.      * @Method("GET")
  282.      *
  283.      * @param   $request    Request
  284.      * @param   $clubId     int
  285.      * @param   $ageGroupId int
  286.      * @param   $limit      int
  287.      * @param   $offset     int
  288.      * @param   $field      string
  289.      * @param   $sort       string
  290.      * @param   $created    string
  291.      * @param   $locale   string
  292.      * @param   $tagIds   string
  293.      *
  294.      * @return JsonResponse
  295.      */
  296.     public function allByMyClubAndAgeGroup(Request $request, $clubId, $userId, $ageGroupId, $limit, $offset, $field, $created, $sort, $locale, $libId = null, $search = null)
  297.     {
  298.         /** @var ExerciseRepository $exerciseRepository */
  299.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  300.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  301.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  302.         /** @var ClubRepository $clubRepository */
  303.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  304.         //$session = $this->requestStack->getSession();
  305.          //$session->get('user_id');
  306.         $limit = 1000;
  307.         $role = 'user';
  308.         $tagIds = "";
  309.         $isFavorite= $this->requestStack->getSession()->get('isFavorite');
  310.         if($isFavorite == null){
  311.           $isFavorite = false;
  312.         }
  313.         $sectionId = $request->get('section');
  314.         $club = $clubRepository->find($clubId);
  315.         $clubId = $club ? $club->getClubId() : null;
  316.         $results = $exerciseRepository->MobileMeMyClubSearch($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role, $libId, $search);
  317.         $items = [];
  318.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  319.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  320.         $sql = $results['sql'];
  321.         $ids = $results['ids'];
  322.         $results = $results['results'];
  323. /*
  324.         foreach ($results as $result) {
  325.             //$item = $this->checkCache($result['id'],$result);
  326.             //$item = $this->checkCache($result,$result);
  327.             $item = json_decode($result['desktop'],TRUE);
  328.             //$item['rating'] = $exerciseRatingRepository->getRating($item['id']);
  329.             //$item['userrating'] =  $exerciseRatingRepository->getUserRating($item['id'],$userId);// $item['id'].'--'.$userId;
  330.             //$item['ratingCount'] = $exerciseRatingRepository->getRatingCount($item['id']);
  331.             $item['source'] = $result;
  332.             $items[] = $item;
  333.         }
  334. */
  335.         foreach ($ids as $result) {
  336.             $item = $this->checkCache($result,$result);
  337.             $item['lang'] = $locale;
  338.             $item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
  339.             $item['new'] = $item['createdAt'] >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  340.             $item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  341.             $item['favorite'] = $exerciseRepository->isFavorite($userId,$item['id']);
  342.             $items[] = $item;
  343.         }
  344. $userId = intval($userId);
  345.         $condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds,'UserId'=>$userId);
  346. //$isFavorite = false;
  347. $total = $exerciseRepository->countByMyClubAndAgeGroup($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role);
  348.         $data = [
  349.             'count' => count($items),
  350.             'sql' => $sql,
  351.             'isFavorite'=> $isFavorite,
  352.             'total' => intval($total['total']),
  353.             'total_sql' => count($ids),
  354.             //'total' =>  $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
  355.             'condition' => $condition,
  356.             'created' => $created,
  357.             'items' => $items,
  358.         ];
  359.         $response = new JsonResponse($data);
  360.         //$response
  361.         //    ->setMaxAge(86400)
  362.         //    ->setSharedMaxAge(86400);
  363.         return $response;
  364.     }
  365. //////////////////////////////////////
  366.     /**
  367.      * List all exercises available in given agegroup
  368.      *
  369.      * @Route("/mobile/exercises/v2/filter",
  370.      *
  371.      *  )
  372.      * @Method("POST")
  373.      *
  374.      * @param   $request    Request
  375.      * @param   $clubId     int
  376.      * @param   $ageGroupId int
  377.      * @param   $limit      int
  378.      * @param   $offset     int
  379.      * @param   $field      string
  380.      * @param   $sort       string
  381.      * @param   $created    string
  382.      * @param   $locale   string
  383.      * @param   $tagIds   string
  384.      *
  385.      * @return JsonResponse
  386.      */
  387.     public function filterV2Action(Request $request)
  388.     {
  389.       //{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/
  390.       $data = json_decode($request->getContent(), true);
  391.         $userId = $data['userId'];
  392.         $clubId = $data['clubId'];
  393.         $ageGroupId = $data['ageGroupId'];
  394.         $limit = $data['limit'];
  395.         $offset = $data['offset'];
  396.         $field = $data['field'];
  397.         $created = $data['created'];
  398.         $sort = $data['sort'];
  399.         $locale = $data['locale'];
  400.         $libId = $data['libId'];
  401.         $search = $data['search'];
  402.         /** @var ExerciseRepository $exerciseRepository */
  403.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  404.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  405.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  406.         /** @var ClubRepository $clubRepository */
  407.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  408.         $session = $this->requestStack->getSession();
  409.         $tagIds = "";
  410.          //$session->get('user_id');
  411.         //$userId= $this->requestStack->getSession()->get('user_id');
  412.         $role = $this->requestStack->getSession()->get('user_role');
  413.         $isFavorite= $this->requestStack->getSession()->get('isFavorite');
  414.         if($isFavorite == null){
  415.           $isFavorite = false;
  416.         }
  417.         $sectionId = $request->get('section');
  418.         $club = $clubRepository->find($clubId);
  419.         $clubId = $club ? $club->getClubId() : null;
  420.         $results = $exerciseRepository->searchByClubAndAgeGroupV2($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role,$libId,$search);
  421.         $items = [];
  422.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  423.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  424.         $sql = $results['sql'];
  425.         $ids = $results['ids'];
  426.         $results = $results['results'];
  427.         foreach ($ids as $result) {
  428.             $item = $this->checkCache($result,$result);
  429.             $item['lang'] = $locale;
  430.             $item['clubInitials'] = !isset($item['club']) ? null : $item['club'] != null ? $item['club']['initials'] : null ;
  431.             $item['new'] = $item['createdAt'] >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  432.             $item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  433.             $item['favorite'] = $exerciseRepository->isFavorite($userId,intval($result));
  434.             $items[] = $item;
  435.         }
  436.         $condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds,'libId'=>$libId,'search'=>$search);
  437.         $total = $exerciseRepository->countByClubAndAgeGroupV2($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role,$libId,$search);
  438.         $data = [
  439.             'count' => count($items),
  440.             'sql' => $sql,
  441.             'userId' => $userId,
  442.             'isFavorite'=> $isFavorite,
  443.             'total' => intval($total['total']),
  444.             'total_sql' => count($ids),
  445.             //'total' =>  $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
  446.             'condition' => $condition,
  447.             'created' => $created,
  448.             'items' => $items,
  449.         ];
  450.         $response = new JsonResponse($data);
  451.         //$response
  452.         //    ->setMaxAge(86400)
  453.         //    ->setSharedMaxAge(86400);
  454.         return $response;
  455.     }
  456. /////////////////////////////////////
  457. public function checkYoutubeVideo( $youtubeURL ='')
  458. {
  459.   $handler = new YouTubeDownloader();
  460.   // Youtube video url
  461.   //$youtubeURL = 'https://www.youtube.com/watch?v=G9QJSjhOgM8';
  462.   $videoId = explode('/',$youtubeURL);
  463.   $videoId = $videoId[count($videoId)-1];
  464.   $youtubeURL = 'https://www.youtube.com/watch?v='.$videoId;
  465.   // Check whether the url is valid
  466.   if(!empty($youtubeURL) && !filter_var($youtubeURL, FILTER_VALIDATE_URL) === false){
  467.       // Get the downloader object
  468.       $downloader = $handler->getDownloader($youtubeURL);
  469.       // Set the url
  470.       $downloader->setUrl($youtubeURL);
  471.       // Validate the youtube video url
  472.       if($downloader->hasVideo()){
  473.           // Get the video download link info
  474.           $videoDownloadLink = $downloader->getVideoDownloadLink();
  475.           $index = 0;
  476.           $index = count($videoDownloadLink);
  477.           if($index >= 2){
  478.             $index = 1;
  479.           }
  480.           $videoTitle = $videoDownloadLink[$index]['title'];
  481.           $videoQuality = $videoDownloadLink[$index]['qualityLabel'];
  482.           $videoFormat = $videoDownloadLink[$index]['format'];
  483.           $videoFileName = strtolower(str_replace(' ', '_', $videoTitle)).'.'.$videoFormat;
  484.           $downloadURL = $videoDownloadLink[$index]['url'];
  485.           $fileName = preg_replace('/[^A-Za-z0-9.\_\-]/', '', basename($videoFileName));
  486.           if(!empty($downloadURL)){
  487.               return $videoDownloadLink[$index]['url'];
  488.           }
  489.       }else{
  490.         return '';
  491.           echo "The video is not found, please check YouTube URL.";
  492.       }
  493.   }else{
  494.       return '';
  495.       echo "Please provide valid YouTube URL.";
  496.   }
  497.         die();
  498.    }
  499.    /////////////////////////// PLAYER
  500.     /**
  501.      * Get Exercise
  502.      *
  503.      * @Route("/mobile/player/exercises/{id}/{locale}/{playerId}", requirements={"id" = "\d+"})
  504.      * @Method("GET")
  505.      *
  506.      * @param   int $id
  507.      * @throws  NotFoundHttpException
  508.      * @return  JsonResponse
  509.      */
  510.     public function getPlayerAction($id,$locale = null,$playerId)
  511.     {
  512.         if($locale == null){
  513.           $locale = $this->getParameter('LHdefLang');
  514.         }
  515.         /** @var ExerciseRepository $exerciseRepository */
  516.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  517.         $exercise = $exerciseRepository->find($id);
  518.         if (!$exercise) {
  519.             throw new NotFoundHttpException(sprintf(
  520.                 'Exercise with ID %s does not exist!', $id
  521.             ));
  522.         }
  523.         $data = $this->checkCache($exercise->getId(),$exercise);
  524.         $data['lang'] = $locale;
  525.         /** @var ExerciseFavoriteRepository $exerciseFavoriteRepository */
  526.         $exerciseFavoriteRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseFavorite::class);
  527.         $exerciseFavorite = $exerciseFavoriteRepository->findOneBy(array('exerciseId'=>$data['id'],'playerId'=>$playerId));
  528.         if($exerciseFavorite){
  529.           $data['favorite'] = 1;
  530.         }else {
  531.           $data['favorite'] = 0;
  532.         }
  533.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  534.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  535.         $exId = $exercise->getId();
  536.         $data['totalRating'] = round($exerciseRatingRepository->getRating($exId),1);
  537.         $data['stars'] = round($data['totalRating']);
  538.         $data['userRating'] =  $exerciseRatingRepository->getPlayerRating($exId,$playerId);
  539.         $data['ratingCount'] = $exerciseRatingRepository->getRatingCount($exId);
  540.         $data['clubInitials'] = $exercise->getClub() != null ? $exercise->getClub()->getInitials() : null ;
  541.         $data['new'] = $exercise->getCreatedAt() >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  542.         $data['updated'] = !$data['new'] && $exercise->getUpdatedAt() >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  543.         $return = [];
  544.         $video = $exercise->translate($locale)->getVideoUrl();
  545.         $videoId = explode('/',$video);
  546.         $videoId = $videoId[count($videoId)-1];
  547.         $data['vimeoLink'] = '';
  548.         $data['streamingUrl'] = '';
  549.         if(strpos($video, 'vimeo') != false){
  550.         $client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
  551.         $response = $client->request('/videos/'.$videoId, array(), 'GET');
  552.         $lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
  553.         $data['vimeoLink'] =  $response['body']['files'][$lookup]['link'];
  554.         $data['streamingUrl'] = $data['vimeoLink'];
  555.         }
  556.         if(strpos($video, 'youtu') != false){
  557.           $videoData = $this->getVideoInfoTest($video);
  558.           //return new JsonResponse($videoData);
  559.           $data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
  560.           $data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
  561.         }
  562.         //return new JsonResponse($data);
  563.         $return[0] = $data;
  564.         return new JsonResponse($return);
  565.     }
  566.     /**
  567.      * List all exercises available in given agegroup
  568.      *
  569.      * @Route("/mobile/player/exercises/v2/filter",
  570.      *
  571.      *  )
  572.      * @Method("POST")
  573.      *
  574.      * @param   $request    Request
  575.      * @param   $clubId     int
  576.      * @param   $ageGroupId int
  577.      * @param   $limit      int
  578.      * @param   $offset     int
  579.      * @param   $field      string
  580.      * @param   $sort       string
  581.      * @param   $created    string
  582.      * @param   $locale   string
  583.      * @param   $tagIds   string
  584.      *
  585.      * @return JsonResponse
  586.      */
  587.     public function filterPlayerV2Action(Request $request)
  588.     {
  589.       //{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/
  590.       $data = json_decode($request->getContent(), true);
  591.         $userId = $data['userId'];
  592.         $clubId = $data['clubId'];
  593.         $ageGroupId = $data['ageGroupId'];
  594.         $limit = $data['limit'];
  595.         $offset = $data['offset'];
  596.         $field = $data['field'];
  597.         $created = $data['created'];
  598.         $sort = $data['sort'];
  599.         $locale = $data['locale'];
  600.         $libId = $data['libId'];
  601.         $search = $data['search'];
  602.         $playerId = $data['playerId'];
  603.         /** @var ExerciseRepository $exerciseRepository */
  604.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  605.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  606.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  607.         /** @var ClubRepository $clubRepository */
  608.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  609.         $session = $this->requestStack->getSession();
  610.         $tagIds = "";
  611.          //$session->get('user_id');
  612.         //$userId= $this->requestStack->getSession()->get('user_id');
  613.         //$role = $this->requestStack->getSession()->get('user_role');
  614.         $role = "user";
  615.         $isFavorite= $this->requestStack->getSession()->get('isFavorite');
  616.         if($isFavorite == null){
  617.           $isFavorite = false;
  618.         }
  619.         $sectionId = $request->get('section');
  620.         $club = $clubRepository->find($clubId);
  621.         $clubId = $club ? $club->getClubId() : null;
  622.         $results = $exerciseRepository->searchByClubAndAgeGroupV2Player($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role,$libId,$search);
  623.         $items = [];
  624.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  625.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  626.         $sql = $results['sql'];
  627.         $ids = $results['ids'];
  628.         $results = $results['results'];
  629.         foreach ($ids as $result) {
  630.             $item = $this->checkCache(intval($result),intval($result));
  631.             $item['lang'] = $locale;
  632.             //$item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
  633.             $item['new'] = $item['createdAt'] >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  634.             $item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  635.             $item['favorite'] = $exerciseRepository->isPlayerFavorite($playerId,intval($result));
  636.             $items[] = $item;
  637.         }
  638.         $condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds,'libId'=>$libId,'search'=>$search);
  639.         $total = $exerciseRepository->countByClubAndAgeGroupV2Player($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role,$libId,$search);
  640.         $data = [
  641.             'count' => count($items),
  642.             'sql' => $sql,
  643.             'userId' => $userId,
  644.             'playerId' => $playerId,
  645.             'isFavorite'=> $isFavorite,
  646.             'total' => intval($total['total']),
  647.             'total_sql' => count($ids),
  648.             //'total' =>  $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
  649.             'condition' => $condition,
  650.             'created' => $created,
  651.             'items' => $items,
  652.         ];
  653.         $response = new JsonResponse($data);
  654.         //$response
  655.         //    ->setMaxAge(86400)
  656.         //    ->setSharedMaxAge(86400);
  657.         return $response;
  658.     }
  659.     /**
  660.      * Exercise Favorites
  661.      * @Route("/mobile/player/exercises/favoritesfilter/{playerId}/{locale}/{ageGroupId}/{libId}/{search}")
  662.      * @Method("GET")
  663.      *
  664.      *
  665.      * @return array|null
  666.      */
  667.     public function favoritesPlayerFilterAction($playerId = null, $locale = "com",$ageGroupId = 0, $libId = null, $search = null)
  668.     {
  669.         /** @var ClubRepository $clubRepository */
  670.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  671.         /** @var ExerciseRepository $exerciseRepository */
  672.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  673.         /** @var UserRepository $userRepository */
  674.         $userRepository = $this->getDoctrine()->getRepository(\App\Entity\User::class);
  675.         /** @var CountryRepository $countryRepository */
  676.         $countryRepository = $this->getDoctrine()->getRepository(\App\Entity\Country::class);
  677.         //$locale = $request->get('locale');
  678.         //$ageGroupId = $request->get('agegroupid');
  679.         //$clubId = $request->get('clubid');
  680.         //$userId = $request->get('userid');
  681.         //echo $userId.'/'.$ageGroupId.'/'.$locale;die();
  682.             $results = $exerciseRepository->favoritesPlayer($playerId,$locale,$ageGroupId, $libId, $search);
  683.         $data = array();
  684.         $items = [];
  685.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  686.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  687.         foreach ($results as $key => $result) {
  688.             $items[$key] = $this->checkCache($result->getId(),$result);
  689.             //$items[$key]['rating'] = $exerciseRatingRepository->getRating($items[$key]['id']);
  690.             $items[$key]['userrating'] = $exerciseRatingRepository->getPlayerRating($items[$key]['id'],$playerId);
  691.             $items[$key]['lang'] = $locale;
  692.             $items[$key]['clubInitials'] = $result->getClub() != null ? $result->getClub()->getInitials() : null ;
  693.             $items[$key]['new'] = $result->getCreatedAt() >=  time() - (86400*self::NEW_DAYS_THRESHOLD) ? true : false ;
  694.             $items[$key]['favorite'] = $exerciseRepository->isPlayerFavorite($playerId,$result->getId());
  695.             //$items[$key]['ratingCount'] = $exerciseRatingRepository->getRatingCount($items[$key]['id']);
  696.         }
  697.         //return new JsonResponse($items);
  698.         $data['count'] = count($items);
  699.         $data['items'] = $items;
  700.         return new JsonResponse($data);
  701.     }
  702.     /**
  703.      * List all exercises available in given agegroup
  704.      *
  705.      * @Route("/mobile/player/exercises/memyclub/{clubId}/{playerId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/{libId}/{search}",
  706.      *      requirements={"ageGroup" = "\d+", "id" = "\d+", "limit" = "\d+", "offset" = "\d+", "sort" = "asc|desc|ASC|DESC"}
  707.      *  )
  708.      * @Method("GET")
  709.      *
  710.      * @param   $request    Request
  711.      * @param   $clubId     int
  712.      * @param   $ageGroupId int
  713.      * @param   $limit      int
  714.      * @param   $offset     int
  715.      * @param   $field      string
  716.      * @param   $sort       string
  717.      * @param   $created    string
  718.      * @param   $locale   string
  719.      * @param   $tagIds   string
  720.      *
  721.      * @return JsonResponse
  722.      */
  723.     public function allByMyClubAndAgeGroupPlayer(Request $request, $clubId, $playerId, $ageGroupId, $limit, $offset, $field, $created, $sort, $locale, $libId = null, $search = null)
  724.     {
  725.         /** @var ExerciseRepository $exerciseRepository */
  726.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  727.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  728.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  729.         /** @var ClubRepository $clubRepository */
  730.         $clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
  731.         //$session = $this->requestStack->getSession();
  732.          //$session->get('user_id');
  733.         $limit = 1000;
  734.         $role = 'user';
  735.         $tagIds = "";
  736.         $isFavorite= $this->requestStack->getSession()->get('isFavorite');
  737.         if($isFavorite == null){
  738.           $isFavorite = false;
  739.         }
  740.         $sectionId = $request->get('section');
  741.         $club = $clubRepository->find($clubId);
  742.         $clubId = $club ? $club->getClubId() : null;
  743.         $results = $exerciseRepository->MobileMeMyClubSearchPlayer($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role, $libId, $search);
  744.         $items = [];
  745.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  746.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  747.         $sql = $results['sql'];
  748.         $ids = $results['ids'];
  749.         $results = $results['results'];
  750. /*
  751.         foreach ($results as $result) {
  752.             //$item = $this->checkCache($result['id'],$result);
  753.             //$item = $this->checkCache($result,$result);
  754.             $item = json_decode($result['desktop'],TRUE);
  755.             //$item['rating'] = $exerciseRatingRepository->getRating($item['id']);
  756.             //$item['userrating'] =  $exerciseRatingRepository->getUserRating($item['id'],$userId);// $item['id'].'--'.$userId;
  757.             //$item['ratingCount'] = $exerciseRatingRepository->getRatingCount($item['id']);
  758.             $item['source'] = $result;
  759.             $items[] = $item;
  760.         }
  761. */
  762.         foreach ($ids as $result) {
  763.             $item = $this->checkCache($result,$result);
  764.             $item['lang'] = $locale;
  765.             $item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
  766.             $item['new'] = $item['createdAt'] >=  time() - (86400*self::NEW_DAYS_THRESHOLD);
  767.             $item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
  768.             $item['favorite'] = $exerciseRepository->isPlayerFavorite($playerId,$item['id']);
  769.             $items[] = $item;
  770.         }
  771. $playerId = intval($playerId);
  772.         $condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds,'playerId'=>$playerId);
  773. //$isFavorite = false;
  774. $total = $exerciseRepository->countByMyClubAndAgeGroupPlayer($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role);
  775.         $data = [
  776.             'count' => count($items),
  777.             'sql' => $sql,
  778.             'isFavorite'=> $isFavorite,
  779.             'total' => intval($total['total']),
  780.             'total_sql' => count($ids),
  781.             //'total' =>  $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
  782.             'condition' => $condition,
  783.             'created' => $created,
  784.             'items' => $items,
  785.         ];
  786.         $response = new JsonResponse($data);
  787.         //$response
  788.         //    ->setMaxAge(86400)
  789.         //    ->setSharedMaxAge(86400);
  790.         return $response;
  791.     }
  792.     /**
  793.      * Get Exercise
  794.      *
  795.      * @Route("/mobile/player/exercises/{id}/{locale}/{playerId}", requirements={"id" = "\d+"})
  796.      * @Method("GET")
  797.      *
  798.      * @param   int $id
  799.      * @throws  NotFoundHttpException
  800.      * @return  JsonResponse
  801.      */
  802.     public function getPlayerExerciseAction($id,$locale = null,$playerId)
  803.     {
  804.         if($locale == null){
  805.           $locale = $this->getParameter('LHdefLang');
  806.         }
  807.         /** @var ExerciseRepository $exerciseRepository */
  808.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  809.         $exercise = $exerciseRepository->find($id);
  810.         if (!$exercise) {
  811.             throw new NotFoundHttpException(sprintf(
  812.                 'Exercise with ID %s does not exist!', $id
  813.             ));
  814.         }
  815.         $data = $this->checkCache($exercise->getId(),$exercise);
  816.         $data['lang'] = $locale;
  817.         /** @var ExerciseFavoriteRepository $exerciseFavoriteRepository */
  818.         $exerciseFavoriteRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseFavorite::class);
  819.         $exerciseFavorite = $exerciseFavoriteRepository->findOneBy(array('exerciseId'=>$data['id'],'playerId'=>$playerId));
  820.         if($exerciseFavorite){
  821.           $data['favorite'] = 1;
  822.         }else {
  823.           $data['favorite'] = 0;
  824.         }
  825.         /** @var ExerciseRatingRepository $exerciseRatingRepository */
  826.         $exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
  827.         $exId = $exercise->getId();
  828.         $data['totalRating'] = round($exerciseRatingRepository->getRating($exId),1);
  829.         $data['stars'] = round($data['totalRating']);
  830.         $data['userRating'] =  $exerciseRatingRepository->getPlayerRating($exId,$playerId);
  831.         $data['ratingCount'] = $exerciseRatingRepository->getRatingCount($exId);
  832.         $data['clubInitials'] = $exercise->getClub() != null ? $exercise->getClub()->getInitials() : null ;
  833.         $data['new'] = $exercise->getCreatedAt() >=  time() - (86400*self::NEW_DAYS_THRESHOLD) ? true : false ;
  834.         $return = [];
  835.         $video = $exercise->translate($locale)->getVideoUrl();
  836.         $videoId = explode('/',$video);
  837.         $videoId = $videoId[count($videoId)-1];
  838.         $data['vimeoLink'] = '';
  839.         $data['streamingUrl'] = '';
  840.         if(strpos($video, 'vimeo') != false){
  841.           $client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
  842.           $response = $client->request('/videos/'.$videoId, array(), 'GET');
  843.           $lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
  844.           $data['vimeoLink'] =  $response['body']['files'][$lookup]['link'];
  845.           $data['streamingUrl'] = $data['vimeoLink'];
  846.         }
  847.         if(strpos($video, 'youtu') != false){
  848.           $videoData = $this->getVideoInfoTest($video);
  849.           //return new JsonResponse($videoData);
  850.           $data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
  851.           $data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
  852.         }
  853.         //return new JsonResponse($data);
  854.         $return[0] = $data;
  855.         return new JsonResponse($return);
  856.     }
  857.     function getVideoInfoTest($video){
  858.       $urlArray = explode("/", $video);
  859.       $video_id =  end($urlArray);
  860.       //$video_id = $this->extractVideoId($video);
  861.       $ch = curl_init();
  862.       curl_setopt($ch, CURLOPT_URL, 'https://www.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8');
  863.       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  864.       curl_setopt($ch, CURLOPT_POST, 1);
  865.       curl_setopt($ch, CURLOPT_POSTFIELDS, '{  "context": {    "client": {      "hl": "en",      "clientName": "WEB",      "clientVersion": "2.20210721.00.00",      "clientFormFactor": "UNKNOWN_FORM_FACTOR",   "clientScreen": "WATCH",      "mainAppWebInfo": {        "graftUrl": "/watch?v='.$video_id.'",           }    },    "user": {      "lockedSafetyMode": false    },    "request": {      "useSsl": true,      "internalExperimentFlags": [],      "consistencyTokenJars": []    }  },  "videoId": "'.$video_id.'",  "playbackContext": {    "contentPlaybackContext": {        "vis": 0,      "splay": false,      "autoCaptionsDefaultOn": false,      "autonavState": "STATE_NONE",      "html5Preference": "HTML5_PREF_WANTS",      "lactMilliseconds": "-1"    }  },  "racyCheckOk": false,  "contentCheckOk": false}');
  866.       curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
  867.       $headers = array();
  868.       $headers[] = 'Content-Type: application/json';
  869.       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  870.       $result = curl_exec($ch);
  871.       if (curl_errno($ch)) {
  872.           echo 'Error:' . curl_error($ch);
  873.       }
  874.       curl_close($ch);
  875.       //$data =
  876.       return json_decode($result,true);
  877.   }
  878.       /*
  879.      * Get video Id
  880.      * @param string
  881.      * return string
  882.      */
  883.     public function extractVideoId($video_url){
  884.       //parse the url
  885.       $parsed_url = parse_url($video_url);
  886.       if($parsed_url["path"] == "youtube.com/watch"){
  887.           $this->video_url = "https://www.".$video_url;
  888.       }elseif($parsed_url["path"] == "www.youtube.com/watch"){
  889.           $this->video_url = "https://".$video_url;
  890.       }
  891.       if(isset($parsed_url["query"])){
  892.           $query_string = $parsed_url["query"];
  893.           //parse the string separated by '&' to array
  894.           parse_str($query_string, $query_arr);
  895.           if(isset($query_arr["v"])){
  896.               return $query_arr["v"];
  897.           }
  898.       }
  899.   }
  900.     /**
  901.      * Get Exercise
  902.      *
  903.      * @Route("/mobile/youtubetest")
  904.      * @Method("GET")
  905.      *
  906.      * @param   int $id
  907.      * @throws  NotFoundHttpException
  908.      * @return  JsonResponse
  909.      */
  910.     public function getYoutubeTestAction()
  911.     {
  912.           $video = 'https://youtu.be/ppBhs2M2LxU';
  913.         if(strpos($video, 'youtu') != false){
  914.           $videoData = $this->getVideoInfoTest($video);
  915.           //return new JsonResponse($videoData);
  916.           $data['streamingUrl'] = $videoData['streamingData'];
  917.         }
  918.         //return new JsonResponse($data);
  919.         $return = $data;
  920.         return new JsonResponse($return);
  921.     }
  922.         /**
  923.          * Handle image upload for AgeGroup
  924.          *
  925.          * @param   $uploadedImage
  926.          * @throws  \ErrorException
  927.          * @throws  \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  928.          *
  929.          * @return string
  930.          */
  931.         public function handleImageUpload($uploadedVideo,$size,$faId)
  932.         {
  933.           $data = explode(',', $uploadedVideo['file']);
  934.           $data = $data[1];
  935.           //echo $uploadedImage['name'];
  936.            $farray = explode(".", $uploadedVideo['name']);
  937.            $ext = $farray[count($farray)-1];
  938.            //var_dump();
  939.           //$ext = end((explode(".", $uploadedImage['name']))); # extra () to prevent notice
  940. //die();
  941.           //echo $ext;
  942.             if (!strlen($data) || false === base64_decode($data)) {
  943.                 throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Unable to upload image - invalid image data, cannot base64 decode.');
  944.             }
  945.             $targetFile = sprintf('%s/%s/%s',
  946.                 $this->getParameter('kernel.project_dir'),
  947.                 'tmp_user_uploads',
  948.                 $faId.'_'.$size.'.'.$ext//  $uploadedImage['name']
  949.             );
  950.             $imageContent = base64_decode($data);
  951.             if (!file_put_contents($targetFile, $imageContent)) {
  952.                 throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Error writing image file');
  953.             }
  954.             return $targetFile;
  955.             /*
  956.             sprintf("/%s/%s",
  957.                 $this->getParameter('handball.image_paths.exercisesfocusarea'),
  958.                 $faId.'_'.$size.'.'.$ext //$uploadedImage['name']
  959.             );
  960.             */
  961.         }
  962.     /**
  963.      * List all exercises available in given agegroup
  964.      *
  965.      * @Route("/exercises/upload-video",
  966.      *
  967.      *  )
  968.      * @Method("POST")
  969.      *
  970.      * @param   $request    Request
  971.      *
  972.      * @return JsonResponse
  973.      */
  974.     public function uploadToVimeoAction(Request $request)
  975.     {
  976.       $data = json_decode($request->getContent(), true);
  977.       if (isset($data['video'])) {
  978.         if($data['video'] != null){
  979.           $videoPath = $this->handleImageUpload($data['video'],'video',$data['id']);
  980.         }
  981.       }
  982.       //$data = [];
  983.       $data['vidoePath'] = $videoPath;
  984.       ////  Master token 2a79a0a062b2a2e94581c81b7ad36c8b
  985.       //// View token 64f0d019d6e3efb9a3791b7ae80e28f4
  986.       $client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
  987.       //$response = $client->request('/videos/'.$videoId, array(), 'GET');
  988.       $response = $client->upload($videoPath, [ 'name' => 'exercise_'.$data['id'], 'privacy' => [ 'view' =>'unlisted' ] ]);
  989.       unlink($videoPath);
  990.       unset($data['video']);
  991.       ///// Call Vimeo API to move video in destination folder
  992.       $urlArray = explode("/", $response);
  993.       $videoId = $urlArray[count($urlArray)-1];
  994.       $ch = curl_init();
  995.       curl_setopt($ch, CURLOPT_URL,"https://api.vimeo.com/users/53801163/projects/11726870/videos/".$videoId);
  996.       curl_setopt($ch, CURLOPT_PUT, 1);
  997.       $headers = [
  998.           'Authorization: bearer 2a79a0a062b2a2e94581c81b7ad36c8b', /// Admin upload token
  999.           'Content-type: application/json',
  1000.           'Accept: application/vnd.vimeo.*+json;version=3.4',
  1001.       ];
  1002.       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1003.       $server_output = curl_exec ($ch);
  1004.       curl_close ($ch);
  1005.       $data['vimeoResponse'] = $response;
  1006.       ////////////////////////////////////////
  1007.       /** @var ExerciseRepository $exerciseRepository */
  1008.       $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  1009.       /** @var Exercise $exercise */
  1010.       $exercise = $exerciseRepository->find($data['id']);
  1011.       if (!empty($data['translations'])) {
  1012.           //$this->updateTranslations($exercise, $data['translations']);
  1013.           $videoUrl = "//player.vimeo.com/video/".$videoId;
  1014.           foreach ($data['translations'] as $locale => $localeData) {
  1015.               $data['translations'][$locale]['videoThumbnail']= null;
  1016.               $data['translations'][$locale]['videoUrl']= $videoUrl;
  1017.           }
  1018.           $exerciseRepository->save($exercise,$data['translations']);
  1019.       }
  1020.       else {
  1021.           $exerciseRepository->update($exercise);
  1022.       }
  1023.       $this->deleteSingleCache($exercise->getId(),$this->entityName);
  1024.       /////////////////////////////////////////
  1025.       return new JsonResponse($data);
  1026.     }
  1027.     /**
  1028.      * Get Exercise
  1029.      *
  1030.      * @Route("/mobile/exercises-stream_url/{id}/{locale}/{userId}", requirements={"id" = "\d+"})
  1031.      * @Method("GET")
  1032.      *
  1033.      * @param   int $id
  1034.      * @throws  NotFoundHttpException
  1035.      * @return  JsonResponse
  1036.      */
  1037.     public function getStreamUrlAction($id,$locale = null,$userId)
  1038.     {
  1039.         if($locale == null){
  1040.           $locale = $this->getParameter('LHdefLang');
  1041.         }
  1042.         /** @var ExerciseRepository $exerciseRepository */
  1043.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  1044.         $exercise = $exerciseRepository->find($id);
  1045.         if (!$exercise) {
  1046.             throw new NotFoundHttpException(sprintf(
  1047.                 'Exercise with ID %s does not exist!', $id
  1048.             ));
  1049.         }
  1050.         $data['lang'] = $locale;
  1051.         $return = [];
  1052.         $video = $exercise->translate($locale)->getVideoUrl();
  1053.         $data['vimeoLink'] = '';
  1054.         $data['streamingUrl'] = '';
  1055.         if(strpos($video, 'youtu') != false){
  1056.           $videoData = $this->getVideoInfoTest($video);
  1057.           //return new JsonResponse($videoData);
  1058.           $data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
  1059.           $data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
  1060.         }
  1061.         if(strpos($video, 'vimeo') != false){
  1062.         $videoId = explode('/',$video);
  1063.         $videoId = $videoId[count($videoId)-1];
  1064.         $client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
  1065.         $response = $client->request('/videos/'.$videoId, array(), 'GET');
  1066.         $lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
  1067.         $data['vimeoLink'] =  $response['body']['files'][$lookup]['link'];
  1068.         $data['streamingUrl'] = $data['vimeoLink'];
  1069.         }
  1070.         //return new JsonResponse($data);
  1071.         $return[0] = $data;
  1072.         return new JsonResponse($return);
  1073.     }
  1074.     /**
  1075.      * List all exercises available in given agegroup
  1076.      *
  1077.      * @Route("/mobile/exercises/coach",
  1078.      *
  1079.      *  )
  1080.      * @Method("POST")
  1081.      *
  1082.      * @param   $request    Request
  1083.      * @param   $clubId     int
  1084.      * @param   $ageGroupId int
  1085.      * @param   $limit      int
  1086.      * @param   $offset     int
  1087.      * @param   $field      string
  1088.      * @param   $sort       string
  1089.      * @param   $created    string
  1090.      * @param   $locale   string
  1091.      * @param   $tagIds   string
  1092.      *
  1093.      * @return JsonResponse
  1094.      */
  1095.     public function exercises(Request $request)
  1096.     {
  1097.         //{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/
  1098.         $data = json_decode($request->getContent(), true);
  1099.         $userId = $data['userId'];
  1100.         $clubId = $data['clubId'];
  1101.         $ageGroupId = $data['ageGroupId'];
  1102.         $limit = $data['limit'];
  1103.         $offset = $data['offset'];
  1104.         $field = $data['field'];
  1105.         $created = $data['created'];
  1106.         $sort = $data['sort'];
  1107.         $locale = $data['locale'];
  1108.         $libId = $data['libId'];
  1109.         $search = $data['search'];
  1110.         $club_param = $clubId ?  (" OR e.club_id = ".$clubId) : '';
  1111.         $userCondition = "and (e.club_id = 0 OR isnull(e.club_id) ".$club_param." OR e.user_id = ".$userId." )";
  1112.         $ageGroupCondition = "a.id = ".$ageGroupId;
  1113.         $activeCondition = " and (e.active = 1 OR ( e.user_id = ".$userId.$club_param." ))";
  1114.         if($search){
  1115.             $searchCondition = " and (et.name like '%".$search."%'  OR et.description like '%".$search."%') ";
  1116.         }else{
  1117.             $searchCondition = "";
  1118.         }
  1119.         $langCondition = " and et.locale = '".$locale."' ";
  1120.         if ($libId) {
  1121.             $libCondition = " and l.library_id = ".$libId;
  1122.         } else {
  1123.             $libCondition = "";
  1124.         }
  1125.         if($created == 'favorites'){
  1126.             $favoritesJoin = "left join exercises_favorite ef on e.id = ef.exercise_id";
  1127.             $favoritesCondition = " and ef.user_id =".$userId;
  1128.         }else{
  1129.             $favoritesJoin = "";
  1130.             $favoritesCondition = "";
  1131.         }
  1132.         if($created == 'club'){
  1133.             $userCondition = "and (e.user_id =".$userId." OR e.club_id =".$clubId.")";
  1134.         }
  1135.         $sql = "
  1136.         select
  1137.         e.id as id,
  1138.         e.user_id as user_id,
  1139.         e.club_id as club_id,
  1140.         c.initials as club_initials
  1141.         from exercises e
  1142.         left join exercises_libraries l on e.id = l.exercise_id
  1143.         left join libraries libs on libs.id = l.library_id
  1144.         left join exercises_tags t on e.id = t.exercise_id
  1145.         left join exercises_translations et on e.id = et.translatable_id
  1146.         left join clubs c on e.club_id = c.id
  1147.         left join exercises_equipment eq on e.id = eq.exercise_id
  1148.         left join equipment_translations eqt on eq.equipment_id = eqt.translatable_id
  1149.         left join exercises_agegroups ea on e.id = ea.exercise_id
  1150.         left join agegroups a on ea.age_group_id = a.id
  1151.         ".$favoritesJoin."
  1152.         where
  1153.         ".$ageGroupCondition."
  1154.         ".$userCondition."
  1155.         and !isnull(et.translatable_id)
  1156.         ".$searchCondition."
  1157.         ".$langCondition."
  1158.         ".$libCondition."
  1159.         ".$favoritesCondition."
  1160.         ".$activeCondition."
  1161.         group by id
  1162.         order by et.name
  1163.         ";
  1164.         $conn = $this->getDoctrine()->getManager()->getConnection();
  1165.         $stmt = $conn->prepare($sql);
  1166.         $stmt->execute();
  1167.         $results = $stmt->fetchAll();
  1168.         $exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
  1169.         $items = [];
  1170.         foreach ($results as $key => $result) {
  1171.             if ($key >= $offset && $key < ($limit + $offset)) {
  1172.                 $item = $this->checkCache($result['id'], $result['id']);
  1173.                 $item['lang'] = $locale;
  1174.                 $item['clubInitials'] = !isset($item['club']) ? null : $item['club'] != null ? $item['club']['initials'] : null;
  1175.                 $item['new'] = $item['createdAt'] >= time() - (86400 * self::NEW_DAYS_THRESHOLD);
  1176.                 $item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400 * 30);
  1177.                 $item['favorite'] = $exerciseRepository->isFavorite($userId, intval($result['id']));
  1178.                 $items[] = $item;
  1179.             }
  1180.         }
  1181.         $condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'locale'=>$locale,'libId'=>$libId,'search'=>$search);
  1182.         $isFavorite= $this->requestStack->getSession()->get('isFavorite');
  1183.         $data = [
  1184.             'count' => count($items),
  1185.             'sql' => $sql,
  1186.             'userId' => $userId,
  1187.             'isFavorite'=> $isFavorite,
  1188.             'total' => count($results),
  1189.             'total_sql' => count($items),
  1190.             'condition' => $condition,
  1191.             'created' => $created,
  1192.             'items' => $items,
  1193.         ];
  1194.         return  new JsonResponse($data);
  1195.     }
  1196. }