<?php
namespace App\Controller\Mobile;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMInvalidArgumentException;
use App\Entity\AgeGroup;
use App\Entity\Club;
use App\Entity\Equipment;
use App\Entity\Exercise;
use App\Entity\Library;
use App\Entity\Section;
use App\Entity\Tag;
use App\Repository\CapacityRepository;
use App\Repository\ClubRepository;
use App\Repository\ExerciseRatingRepository;
use App\Repository\ExerciseRepository;
use App\Repository\LibraryRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use InvalidArgumentException;
use JMS\Serializer\SerializationContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use App\Entity\ExerciseFavorite;
use App\Repository\ExerciseFavoriteRepository;
use Symfony\Component\HttpFoundation\Session\Session;
use App\Helpers\TraitCodeGenerator;
use App\Helpers\TraitHelpers;
use App\Entity\UserSearch;
use App\Repository\UserSearchRepository;
use Vimeo\Vimeo;
use App\Helpers\YoutubeDownloader;
use Symfony\Component\HttpFoundation\RequestStack;
//use App\Module\CustomController; /// Custom Controller class for handling security
class MobileExerciseController extends AbstractController
{
use TraitHelpers;
use TraitCodeGenerator;
const UPDATED_DAYS_THRESHOLD = 30;
const NEW_DAYS_THRESHOLD = 60;
private $entityName = 'exercise';
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* List all exercises available in given agegroup
*
* @Route("/mobile/exercises/{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/{tagIds}",
* requirements={"ageGroup" = "\d+", "id" = "\d+", "limit" = "\d+", "offset" = "\d+", "sort" = "asc|desc|ASC|DESC"}
* )
* @Method("GET")
*
* @param $request Request
* @param $clubId int
* @param $ageGroupId int
* @param $limit int
* @param $offset int
* @param $field string
* @param $sort string
* @param $created string
* @param $locale string
* @param $tagIds string
*
* @return JsonResponse
*/
public function allByClubAndAgeGroup(Request $request,$userId, $clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $locale, $tagIds = "")
{
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
$session = $this->requestStack->getSession();
//$session->get('user_id');
//$userId= $this->requestStack->getSession()->get('user_id');
$role = $this->requestStack->getSession()->get('user_role');
$isFavorite= $this->requestStack->getSession()->get('isFavorite');
if($isFavorite == null){
$isFavorite = false;
}
$sectionId = $request->get('section');
$club = $clubRepository->find($clubId);
$clubId = $club ? $club->getClubId() : null;
$results = $exerciseRepository->searchByClubAndAgeGroup($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role);
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$sql = $results['sql'];
$ids = $results['ids'];
$results = $results['results'];
/*
foreach ($results as $result) {
//$item = $this->checkCache($result['id'],$result);
//$item = $this->checkCache($result,$result);
$item = json_decode($result['desktop'],TRUE);
//$item['rating'] = $exerciseRatingRepository->getRating($item['id']);
//$item['userrating'] = $exerciseRatingRepository->getUserRating($item['id'],$userId);// $item['id'].'--'.$userId;
//$item['ratingCount'] = $exerciseRatingRepository->getRatingCount($item['id']);
$item['source'] = $result;
$items[] = $item;
}
*/
foreach ($ids as $result) {
$item = $this->checkCache($result,$result);
$item['lang'] = $locale;
$item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
$item['new'] = $item['createdAt'] >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$item['favorite'] = $exerciseRepository->isFavorite($userId,intval($result));
$items[] = $item;
}
$condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds);
$total = $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role);
$data = [
'count' => count($items),
'sql' => $sql,
'userId' => $userId,
'isFavorite'=> $isFavorite,
'total' => intval($total['total']),
'total_sql' => count($ids),
//'total' => $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
'condition' => $condition,
'created' => $created,
'items' => $items,
];
$response = new JsonResponse($data);
//$response
// ->setMaxAge(86400)
// ->setSharedMaxAge(86400);
return $response;
}
public function checkCache($id,$exercise,$delete = false){
if($delete == true){
$this->deleteSingleCache($id,$this->entityName);
$entity = null;
}else {
$entity = $this->getCache($id,$this->entityName);
}
if($entity){
//$entity = json_decode($entity,true);
$entity['from_cache'] = 'yes';
}else {
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
$exercise = $exerciseRepository->find($id);
$serializer = \JMS\Serializer\SerializerBuilder::create()->build();
$entity = json_decode($serializer->serialize(
$exercise,
'json',
SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('tp'))
), true);
$this->setCache($id,$this->entityName,$entity);
$entity['from_cache'] = 'no';
}
return $entity;
}
/**
* Get Exercise
*
* @Route("/mobile/exercises/{id}/{locale}/{userId}", requirements={"id" = "\d+"})
* @Method("GET")
*
* @param int $id
* @throws NotFoundHttpException
* @return JsonResponse
*/
public function getAction($id,$locale = null,$userId)
{
if($locale == null){
$locale = $this->getParameter('LHdefLang');
}
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
$exercise = $exerciseRepository->find($id);
if (!$exercise) {
throw new NotFoundHttpException(sprintf(
'Exercise with ID %s does not exist!', $id
));
}
$data = $this->checkCache($exercise->getId(),$exercise);
$data['lang'] = $locale;
/** @var ExerciseFavoriteRepository $exerciseFavoriteRepository */
$exerciseFavoriteRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseFavorite::class);
$exerciseFavorite = $exerciseFavoriteRepository->findOneBy(array('exerciseId'=>$data['id'],'userId'=>$userId));
if($exerciseFavorite){
$data['favorite'] = 1;
}else {
$data['favorite'] = 0;
}
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$exId = $exercise->getId();
$data['totalRating'] = round($exerciseRatingRepository->getRating($exId),1);
$data['stars'] = round($data['totalRating']);
$data['userRating'] = $exerciseRatingRepository->getUserRating($exId,$userId);
$data['ratingCount'] = $exerciseRatingRepository->getRatingCount($exId);
$data['clubInitials'] = $exercise->getClub() != null ? $exercise->getClub()->getInitials() : null ;
$data['new'] = $exercise->getCreatedAt() >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$data['updated'] = !$data['new'] && $exercise->getUpdatedAt() >= time() - (86400*30);
$return = [];
$video = $exercise->translate($locale)->getVideoUrl();
$data['vimeoLink'] = '';
$data['streamingUrl'] = '';
if(strpos($video, 'youtu') != false){
$videoData = $this->getVideoInfoTest($video);
//return new JsonResponse($videoData);
$data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
$data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
}
if(strpos($video, 'vimeo') != false){
$videoId = explode('/',$video);
$videoId = $videoId[count($videoId)-1];
$client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
$response = $client->request('/videos/'.$videoId, array(), 'GET');
$lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
$data['vimeoLink'] = $response['body']['files'][$lookup]['link'];
$data['streamingUrl'] = $data['vimeoLink'];
}
//return new JsonResponse($data);
$return[0] = $data;
return new JsonResponse($return);
}
/**
* Exercise Favorites
* @Route("/mobile/exercises/favoritesfilter/{userId}/{locale}/{ageGroupId}/{libId}/{search}")
* @Method("GET")
*
*
* @return array|null
*/
public function favoritesFilterAction($userId = null, $locale = "com",$ageGroupId = 0, $libId = null, $search = null)
{
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var UserRepository $userRepository */
$userRepository = $this->getDoctrine()->getRepository(\App\Entity\User::class);
/** @var CountryRepository $countryRepository */
$countryRepository = $this->getDoctrine()->getRepository(\App\Entity\Country::class);
//$locale = $request->get('locale');
//$ageGroupId = $request->get('agegroupid');
//$clubId = $request->get('clubid');
//$userId = $request->get('userid');
//echo $userId.'/'.$ageGroupId.'/'.$locale;die();
$results = $exerciseRepository->favorites($userId,$locale,$ageGroupId, $libId, $search);
$data = array();
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
foreach ($results as $key => $result) {
$items[$key] = $this->checkCache($result->getId(),$result);
//$items[$key]['rating'] = $exerciseRatingRepository->getRating($items[$key]['id']);
$items[$key]['userrating'] = $exerciseRatingRepository->getUserRating($items[$key]['id'],$userId);
$items[$key]['lang'] = $locale;
$items[$key]['clubInitials'] = $result->getClub() != null ? $result->getClub()->getInitials() : null ;
$items[$key]['new'] = $result->getCreatedAt() >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$items[$key]['updated'] = $result->getUpdatedAt() >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$items[$key]['favorite'] = $exerciseRepository->isFavorite($userId,$result->getId());
//$items[$key]['ratingCount'] = $exerciseRatingRepository->getRatingCount($items[$key]['id']);
}
//return new JsonResponse($items);
$data['count'] = count($items);
$data['items'] = $items;
return new JsonResponse($data);
}
/////////////////////////////
/**
* List all exercises available in given agegroup
*
* @Route("/mobile/exercises/memyclub/{clubId}/{userId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/{libId}/{search}",
* requirements={"ageGroup" = "\d+", "id" = "\d+", "limit" = "\d+", "offset" = "\d+", "sort" = "asc|desc|ASC|DESC"}
* )
* @Method("GET")
*
* @param $request Request
* @param $clubId int
* @param $ageGroupId int
* @param $limit int
* @param $offset int
* @param $field string
* @param $sort string
* @param $created string
* @param $locale string
* @param $tagIds string
*
* @return JsonResponse
*/
public function allByMyClubAndAgeGroup(Request $request, $clubId, $userId, $ageGroupId, $limit, $offset, $field, $created, $sort, $locale, $libId = null, $search = null)
{
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
//$session = $this->requestStack->getSession();
//$session->get('user_id');
$limit = 1000;
$role = 'user';
$tagIds = "";
$isFavorite= $this->requestStack->getSession()->get('isFavorite');
if($isFavorite == null){
$isFavorite = false;
}
$sectionId = $request->get('section');
$club = $clubRepository->find($clubId);
$clubId = $club ? $club->getClubId() : null;
$results = $exerciseRepository->MobileMeMyClubSearch($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role, $libId, $search);
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$sql = $results['sql'];
$ids = $results['ids'];
$results = $results['results'];
/*
foreach ($results as $result) {
//$item = $this->checkCache($result['id'],$result);
//$item = $this->checkCache($result,$result);
$item = json_decode($result['desktop'],TRUE);
//$item['rating'] = $exerciseRatingRepository->getRating($item['id']);
//$item['userrating'] = $exerciseRatingRepository->getUserRating($item['id'],$userId);// $item['id'].'--'.$userId;
//$item['ratingCount'] = $exerciseRatingRepository->getRatingCount($item['id']);
$item['source'] = $result;
$items[] = $item;
}
*/
foreach ($ids as $result) {
$item = $this->checkCache($result,$result);
$item['lang'] = $locale;
$item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
$item['new'] = $item['createdAt'] >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$item['favorite'] = $exerciseRepository->isFavorite($userId,$item['id']);
$items[] = $item;
}
$userId = intval($userId);
$condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds,'UserId'=>$userId);
//$isFavorite = false;
$total = $exerciseRepository->countByMyClubAndAgeGroup($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role);
$data = [
'count' => count($items),
'sql' => $sql,
'isFavorite'=> $isFavorite,
'total' => intval($total['total']),
'total_sql' => count($ids),
//'total' => $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
'condition' => $condition,
'created' => $created,
'items' => $items,
];
$response = new JsonResponse($data);
//$response
// ->setMaxAge(86400)
// ->setSharedMaxAge(86400);
return $response;
}
//////////////////////////////////////
/**
* List all exercises available in given agegroup
*
* @Route("/mobile/exercises/v2/filter",
*
* )
* @Method("POST")
*
* @param $request Request
* @param $clubId int
* @param $ageGroupId int
* @param $limit int
* @param $offset int
* @param $field string
* @param $sort string
* @param $created string
* @param $locale string
* @param $tagIds string
*
* @return JsonResponse
*/
public function filterV2Action(Request $request)
{
//{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/
$data = json_decode($request->getContent(), true);
$userId = $data['userId'];
$clubId = $data['clubId'];
$ageGroupId = $data['ageGroupId'];
$limit = $data['limit'];
$offset = $data['offset'];
$field = $data['field'];
$created = $data['created'];
$sort = $data['sort'];
$locale = $data['locale'];
$libId = $data['libId'];
$search = $data['search'];
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
$session = $this->requestStack->getSession();
$tagIds = "";
//$session->get('user_id');
//$userId= $this->requestStack->getSession()->get('user_id');
$role = $this->requestStack->getSession()->get('user_role');
$isFavorite= $this->requestStack->getSession()->get('isFavorite');
if($isFavorite == null){
$isFavorite = false;
}
$sectionId = $request->get('section');
$club = $clubRepository->find($clubId);
$clubId = $club ? $club->getClubId() : null;
$results = $exerciseRepository->searchByClubAndAgeGroupV2($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role,$libId,$search);
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$sql = $results['sql'];
$ids = $results['ids'];
$results = $results['results'];
foreach ($ids as $result) {
$item = $this->checkCache($result,$result);
$item['lang'] = $locale;
$item['clubInitials'] = !isset($item['club']) ? null : $item['club'] != null ? $item['club']['initials'] : null ;
$item['new'] = $item['createdAt'] >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$item['favorite'] = $exerciseRepository->isFavorite($userId,intval($result));
$items[] = $item;
}
$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);
$total = $exerciseRepository->countByClubAndAgeGroupV2($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$userId,$role,$libId,$search);
$data = [
'count' => count($items),
'sql' => $sql,
'userId' => $userId,
'isFavorite'=> $isFavorite,
'total' => intval($total['total']),
'total_sql' => count($ids),
//'total' => $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
'condition' => $condition,
'created' => $created,
'items' => $items,
];
$response = new JsonResponse($data);
//$response
// ->setMaxAge(86400)
// ->setSharedMaxAge(86400);
return $response;
}
/////////////////////////////////////
public function checkYoutubeVideo( $youtubeURL ='')
{
$handler = new YouTubeDownloader();
// Youtube video url
//$youtubeURL = 'https://www.youtube.com/watch?v=G9QJSjhOgM8';
$videoId = explode('/',$youtubeURL);
$videoId = $videoId[count($videoId)-1];
$youtubeURL = 'https://www.youtube.com/watch?v='.$videoId;
// Check whether the url is valid
if(!empty($youtubeURL) && !filter_var($youtubeURL, FILTER_VALIDATE_URL) === false){
// Get the downloader object
$downloader = $handler->getDownloader($youtubeURL);
// Set the url
$downloader->setUrl($youtubeURL);
// Validate the youtube video url
if($downloader->hasVideo()){
// Get the video download link info
$videoDownloadLink = $downloader->getVideoDownloadLink();
$index = 0;
$index = count($videoDownloadLink);
if($index >= 2){
$index = 1;
}
$videoTitle = $videoDownloadLink[$index]['title'];
$videoQuality = $videoDownloadLink[$index]['qualityLabel'];
$videoFormat = $videoDownloadLink[$index]['format'];
$videoFileName = strtolower(str_replace(' ', '_', $videoTitle)).'.'.$videoFormat;
$downloadURL = $videoDownloadLink[$index]['url'];
$fileName = preg_replace('/[^A-Za-z0-9.\_\-]/', '', basename($videoFileName));
if(!empty($downloadURL)){
return $videoDownloadLink[$index]['url'];
}
}else{
return '';
echo "The video is not found, please check YouTube URL.";
}
}else{
return '';
echo "Please provide valid YouTube URL.";
}
die();
}
/////////////////////////// PLAYER
/**
* Get Exercise
*
* @Route("/mobile/player/exercises/{id}/{locale}/{playerId}", requirements={"id" = "\d+"})
* @Method("GET")
*
* @param int $id
* @throws NotFoundHttpException
* @return JsonResponse
*/
public function getPlayerAction($id,$locale = null,$playerId)
{
if($locale == null){
$locale = $this->getParameter('LHdefLang');
}
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
$exercise = $exerciseRepository->find($id);
if (!$exercise) {
throw new NotFoundHttpException(sprintf(
'Exercise with ID %s does not exist!', $id
));
}
$data = $this->checkCache($exercise->getId(),$exercise);
$data['lang'] = $locale;
/** @var ExerciseFavoriteRepository $exerciseFavoriteRepository */
$exerciseFavoriteRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseFavorite::class);
$exerciseFavorite = $exerciseFavoriteRepository->findOneBy(array('exerciseId'=>$data['id'],'playerId'=>$playerId));
if($exerciseFavorite){
$data['favorite'] = 1;
}else {
$data['favorite'] = 0;
}
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$exId = $exercise->getId();
$data['totalRating'] = round($exerciseRatingRepository->getRating($exId),1);
$data['stars'] = round($data['totalRating']);
$data['userRating'] = $exerciseRatingRepository->getPlayerRating($exId,$playerId);
$data['ratingCount'] = $exerciseRatingRepository->getRatingCount($exId);
$data['clubInitials'] = $exercise->getClub() != null ? $exercise->getClub()->getInitials() : null ;
$data['new'] = $exercise->getCreatedAt() >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$data['updated'] = !$data['new'] && $exercise->getUpdatedAt() >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$return = [];
$video = $exercise->translate($locale)->getVideoUrl();
$videoId = explode('/',$video);
$videoId = $videoId[count($videoId)-1];
$data['vimeoLink'] = '';
$data['streamingUrl'] = '';
if(strpos($video, 'vimeo') != false){
$client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
$response = $client->request('/videos/'.$videoId, array(), 'GET');
$lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
$data['vimeoLink'] = $response['body']['files'][$lookup]['link'];
$data['streamingUrl'] = $data['vimeoLink'];
}
if(strpos($video, 'youtu') != false){
$videoData = $this->getVideoInfoTest($video);
//return new JsonResponse($videoData);
$data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
$data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
}
//return new JsonResponse($data);
$return[0] = $data;
return new JsonResponse($return);
}
/**
* List all exercises available in given agegroup
*
* @Route("/mobile/player/exercises/v2/filter",
*
* )
* @Method("POST")
*
* @param $request Request
* @param $clubId int
* @param $ageGroupId int
* @param $limit int
* @param $offset int
* @param $field string
* @param $sort string
* @param $created string
* @param $locale string
* @param $tagIds string
*
* @return JsonResponse
*/
public function filterPlayerV2Action(Request $request)
{
//{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/
$data = json_decode($request->getContent(), true);
$userId = $data['userId'];
$clubId = $data['clubId'];
$ageGroupId = $data['ageGroupId'];
$limit = $data['limit'];
$offset = $data['offset'];
$field = $data['field'];
$created = $data['created'];
$sort = $data['sort'];
$locale = $data['locale'];
$libId = $data['libId'];
$search = $data['search'];
$playerId = $data['playerId'];
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
$session = $this->requestStack->getSession();
$tagIds = "";
//$session->get('user_id');
//$userId= $this->requestStack->getSession()->get('user_id');
//$role = $this->requestStack->getSession()->get('user_role');
$role = "user";
$isFavorite= $this->requestStack->getSession()->get('isFavorite');
if($isFavorite == null){
$isFavorite = false;
}
$sectionId = $request->get('section');
$club = $clubRepository->find($clubId);
$clubId = $club ? $club->getClubId() : null;
$results = $exerciseRepository->searchByClubAndAgeGroupV2Player($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role,$libId,$search);
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$sql = $results['sql'];
$ids = $results['ids'];
$results = $results['results'];
foreach ($ids as $result) {
$item = $this->checkCache(intval($result),intval($result));
$item['lang'] = $locale;
//$item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
$item['new'] = $item['createdAt'] >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$item['favorite'] = $exerciseRepository->isPlayerFavorite($playerId,intval($result));
$items[] = $item;
}
$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);
$total = $exerciseRepository->countByClubAndAgeGroupV2Player($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role,$libId,$search);
$data = [
'count' => count($items),
'sql' => $sql,
'userId' => $userId,
'playerId' => $playerId,
'isFavorite'=> $isFavorite,
'total' => intval($total['total']),
'total_sql' => count($ids),
//'total' => $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
'condition' => $condition,
'created' => $created,
'items' => $items,
];
$response = new JsonResponse($data);
//$response
// ->setMaxAge(86400)
// ->setSharedMaxAge(86400);
return $response;
}
/**
* Exercise Favorites
* @Route("/mobile/player/exercises/favoritesfilter/{playerId}/{locale}/{ageGroupId}/{libId}/{search}")
* @Method("GET")
*
*
* @return array|null
*/
public function favoritesPlayerFilterAction($playerId = null, $locale = "com",$ageGroupId = 0, $libId = null, $search = null)
{
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var UserRepository $userRepository */
$userRepository = $this->getDoctrine()->getRepository(\App\Entity\User::class);
/** @var CountryRepository $countryRepository */
$countryRepository = $this->getDoctrine()->getRepository(\App\Entity\Country::class);
//$locale = $request->get('locale');
//$ageGroupId = $request->get('agegroupid');
//$clubId = $request->get('clubid');
//$userId = $request->get('userid');
//echo $userId.'/'.$ageGroupId.'/'.$locale;die();
$results = $exerciseRepository->favoritesPlayer($playerId,$locale,$ageGroupId, $libId, $search);
$data = array();
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
foreach ($results as $key => $result) {
$items[$key] = $this->checkCache($result->getId(),$result);
//$items[$key]['rating'] = $exerciseRatingRepository->getRating($items[$key]['id']);
$items[$key]['userrating'] = $exerciseRatingRepository->getPlayerRating($items[$key]['id'],$playerId);
$items[$key]['lang'] = $locale;
$items[$key]['clubInitials'] = $result->getClub() != null ? $result->getClub()->getInitials() : null ;
$items[$key]['new'] = $result->getCreatedAt() >= time() - (86400*self::NEW_DAYS_THRESHOLD) ? true : false ;
$items[$key]['favorite'] = $exerciseRepository->isPlayerFavorite($playerId,$result->getId());
//$items[$key]['ratingCount'] = $exerciseRatingRepository->getRatingCount($items[$key]['id']);
}
//return new JsonResponse($items);
$data['count'] = count($items);
$data['items'] = $items;
return new JsonResponse($data);
}
/**
* List all exercises available in given agegroup
*
* @Route("/mobile/player/exercises/memyclub/{clubId}/{playerId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/{libId}/{search}",
* requirements={"ageGroup" = "\d+", "id" = "\d+", "limit" = "\d+", "offset" = "\d+", "sort" = "asc|desc|ASC|DESC"}
* )
* @Method("GET")
*
* @param $request Request
* @param $clubId int
* @param $ageGroupId int
* @param $limit int
* @param $offset int
* @param $field string
* @param $sort string
* @param $created string
* @param $locale string
* @param $tagIds string
*
* @return JsonResponse
*/
public function allByMyClubAndAgeGroupPlayer(Request $request, $clubId, $playerId, $ageGroupId, $limit, $offset, $field, $created, $sort, $locale, $libId = null, $search = null)
{
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
/** @var ClubRepository $clubRepository */
$clubRepository = $this->getDoctrine()->getRepository(\App\Entity\Club::class);
//$session = $this->requestStack->getSession();
//$session->get('user_id');
$limit = 1000;
$role = 'user';
$tagIds = "";
$isFavorite= $this->requestStack->getSession()->get('isFavorite');
if($isFavorite == null){
$isFavorite = false;
}
$sectionId = $request->get('section');
$club = $clubRepository->find($clubId);
$clubId = $club ? $club->getClubId() : null;
$results = $exerciseRepository->MobileMeMyClubSearchPlayer($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role, $libId, $search);
$items = [];
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$sql = $results['sql'];
$ids = $results['ids'];
$results = $results['results'];
/*
foreach ($results as $result) {
//$item = $this->checkCache($result['id'],$result);
//$item = $this->checkCache($result,$result);
$item = json_decode($result['desktop'],TRUE);
//$item['rating'] = $exerciseRatingRepository->getRating($item['id']);
//$item['userrating'] = $exerciseRatingRepository->getUserRating($item['id'],$userId);// $item['id'].'--'.$userId;
//$item['ratingCount'] = $exerciseRatingRepository->getRatingCount($item['id']);
$item['source'] = $result;
$items[] = $item;
}
*/
foreach ($ids as $result) {
$item = $this->checkCache($result,$result);
$item['lang'] = $locale;
$item['clubInitials'] = $item['club'] != null ? $item['club']['initials'] : null ;
$item['new'] = $item['createdAt'] >= time() - (86400*self::NEW_DAYS_THRESHOLD);
$item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400*self::UPDATED_DAYS_THRESHOLD);
$item['favorite'] = $exerciseRepository->isPlayerFavorite($playerId,$item['id']);
$items[] = $item;
}
$playerId = intval($playerId);
$condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'sectionId'=>$sectionId,'locale'=>$locale,'tagIds'=>$tagIds,'playerId'=>$playerId);
//$isFavorite = false;
$total = $exerciseRepository->countByMyClubAndAgeGroupPlayer($clubId, $ageGroupId, $limit, $offset, $field, $created, $sort, $sectionId,$locale,$tagIds,$isFavorite,$playerId,$role);
$data = [
'count' => count($items),
'sql' => $sql,
'isFavorite'=> $isFavorite,
'total' => intval($total['total']),
'total_sql' => count($ids),
//'total' => $exerciseRepository->countByClubAndAgeGroup($clubId, $ageGroupId, 0, 0, $field, $created, $sort, $sectionId,$locale),
'condition' => $condition,
'created' => $created,
'items' => $items,
];
$response = new JsonResponse($data);
//$response
// ->setMaxAge(86400)
// ->setSharedMaxAge(86400);
return $response;
}
/**
* Get Exercise
*
* @Route("/mobile/player/exercises/{id}/{locale}/{playerId}", requirements={"id" = "\d+"})
* @Method("GET")
*
* @param int $id
* @throws NotFoundHttpException
* @return JsonResponse
*/
public function getPlayerExerciseAction($id,$locale = null,$playerId)
{
if($locale == null){
$locale = $this->getParameter('LHdefLang');
}
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
$exercise = $exerciseRepository->find($id);
if (!$exercise) {
throw new NotFoundHttpException(sprintf(
'Exercise with ID %s does not exist!', $id
));
}
$data = $this->checkCache($exercise->getId(),$exercise);
$data['lang'] = $locale;
/** @var ExerciseFavoriteRepository $exerciseFavoriteRepository */
$exerciseFavoriteRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseFavorite::class);
$exerciseFavorite = $exerciseFavoriteRepository->findOneBy(array('exerciseId'=>$data['id'],'playerId'=>$playerId));
if($exerciseFavorite){
$data['favorite'] = 1;
}else {
$data['favorite'] = 0;
}
/** @var ExerciseRatingRepository $exerciseRatingRepository */
$exerciseRatingRepository = $this->getDoctrine()->getRepository(\App\Entity\ExerciseRating::class);
$exId = $exercise->getId();
$data['totalRating'] = round($exerciseRatingRepository->getRating($exId),1);
$data['stars'] = round($data['totalRating']);
$data['userRating'] = $exerciseRatingRepository->getPlayerRating($exId,$playerId);
$data['ratingCount'] = $exerciseRatingRepository->getRatingCount($exId);
$data['clubInitials'] = $exercise->getClub() != null ? $exercise->getClub()->getInitials() : null ;
$data['new'] = $exercise->getCreatedAt() >= time() - (86400*self::NEW_DAYS_THRESHOLD) ? true : false ;
$return = [];
$video = $exercise->translate($locale)->getVideoUrl();
$videoId = explode('/',$video);
$videoId = $videoId[count($videoId)-1];
$data['vimeoLink'] = '';
$data['streamingUrl'] = '';
if(strpos($video, 'vimeo') != false){
$client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
$response = $client->request('/videos/'.$videoId, array(), 'GET');
$lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
$data['vimeoLink'] = $response['body']['files'][$lookup]['link'];
$data['streamingUrl'] = $data['vimeoLink'];
}
if(strpos($video, 'youtu') != false){
$videoData = $this->getVideoInfoTest($video);
//return new JsonResponse($videoData);
$data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
$data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
}
//return new JsonResponse($data);
$return[0] = $data;
return new JsonResponse($return);
}
function getVideoInfoTest($video){
$urlArray = explode("/", $video);
$video_id = end($urlArray);
//$video_id = $this->extractVideoId($video);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
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}');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
//$data =
return json_decode($result,true);
}
/*
* Get video Id
* @param string
* return string
*/
public function extractVideoId($video_url){
//parse the url
$parsed_url = parse_url($video_url);
if($parsed_url["path"] == "youtube.com/watch"){
$this->video_url = "https://www.".$video_url;
}elseif($parsed_url["path"] == "www.youtube.com/watch"){
$this->video_url = "https://".$video_url;
}
if(isset($parsed_url["query"])){
$query_string = $parsed_url["query"];
//parse the string separated by '&' to array
parse_str($query_string, $query_arr);
if(isset($query_arr["v"])){
return $query_arr["v"];
}
}
}
/**
* Get Exercise
*
* @Route("/mobile/youtubetest")
* @Method("GET")
*
* @param int $id
* @throws NotFoundHttpException
* @return JsonResponse
*/
public function getYoutubeTestAction()
{
$video = 'https://youtu.be/ppBhs2M2LxU';
if(strpos($video, 'youtu') != false){
$videoData = $this->getVideoInfoTest($video);
//return new JsonResponse($videoData);
$data['streamingUrl'] = $videoData['streamingData'];
}
//return new JsonResponse($data);
$return = $data;
return new JsonResponse($return);
}
/**
* Handle image upload for AgeGroup
*
* @param $uploadedImage
* @throws \ErrorException
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*
* @return string
*/
public function handleImageUpload($uploadedVideo,$size,$faId)
{
$data = explode(',', $uploadedVideo['file']);
$data = $data[1];
//echo $uploadedImage['name'];
$farray = explode(".", $uploadedVideo['name']);
$ext = $farray[count($farray)-1];
//var_dump();
//$ext = end((explode(".", $uploadedImage['name']))); # extra () to prevent notice
//die();
//echo $ext;
if (!strlen($data) || false === base64_decode($data)) {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Unable to upload image - invalid image data, cannot base64 decode.');
}
$targetFile = sprintf('%s/%s/%s',
$this->getParameter('kernel.project_dir'),
'tmp_user_uploads',
$faId.'_'.$size.'.'.$ext// $uploadedImage['name']
);
$imageContent = base64_decode($data);
if (!file_put_contents($targetFile, $imageContent)) {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Error writing image file');
}
return $targetFile;
/*
sprintf("/%s/%s",
$this->getParameter('handball.image_paths.exercisesfocusarea'),
$faId.'_'.$size.'.'.$ext //$uploadedImage['name']
);
*/
}
/**
* List all exercises available in given agegroup
*
* @Route("/exercises/upload-video",
*
* )
* @Method("POST")
*
* @param $request Request
*
* @return JsonResponse
*/
public function uploadToVimeoAction(Request $request)
{
$data = json_decode($request->getContent(), true);
if (isset($data['video'])) {
if($data['video'] != null){
$videoPath = $this->handleImageUpload($data['video'],'video',$data['id']);
}
}
//$data = [];
$data['vidoePath'] = $videoPath;
//// Master token 2a79a0a062b2a2e94581c81b7ad36c8b
//// View token 64f0d019d6e3efb9a3791b7ae80e28f4
$client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
//$response = $client->request('/videos/'.$videoId, array(), 'GET');
$response = $client->upload($videoPath, [ 'name' => 'exercise_'.$data['id'], 'privacy' => [ 'view' =>'unlisted' ] ]);
unlink($videoPath);
unset($data['video']);
///// Call Vimeo API to move video in destination folder
$urlArray = explode("/", $response);
$videoId = $urlArray[count($urlArray)-1];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.vimeo.com/users/53801163/projects/11726870/videos/".$videoId);
curl_setopt($ch, CURLOPT_PUT, 1);
$headers = [
'Authorization: bearer 2a79a0a062b2a2e94581c81b7ad36c8b', /// Admin upload token
'Content-type: application/json',
'Accept: application/vnd.vimeo.*+json;version=3.4',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
$data['vimeoResponse'] = $response;
////////////////////////////////////////
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
/** @var Exercise $exercise */
$exercise = $exerciseRepository->find($data['id']);
if (!empty($data['translations'])) {
//$this->updateTranslations($exercise, $data['translations']);
$videoUrl = "//player.vimeo.com/video/".$videoId;
foreach ($data['translations'] as $locale => $localeData) {
$data['translations'][$locale]['videoThumbnail']= null;
$data['translations'][$locale]['videoUrl']= $videoUrl;
}
$exerciseRepository->save($exercise,$data['translations']);
}
else {
$exerciseRepository->update($exercise);
}
$this->deleteSingleCache($exercise->getId(),$this->entityName);
/////////////////////////////////////////
return new JsonResponse($data);
}
/**
* Get Exercise
*
* @Route("/mobile/exercises-stream_url/{id}/{locale}/{userId}", requirements={"id" = "\d+"})
* @Method("GET")
*
* @param int $id
* @throws NotFoundHttpException
* @return JsonResponse
*/
public function getStreamUrlAction($id,$locale = null,$userId)
{
if($locale == null){
$locale = $this->getParameter('LHdefLang');
}
/** @var ExerciseRepository $exerciseRepository */
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
$exercise = $exerciseRepository->find($id);
if (!$exercise) {
throw new NotFoundHttpException(sprintf(
'Exercise with ID %s does not exist!', $id
));
}
$data['lang'] = $locale;
$return = [];
$video = $exercise->translate($locale)->getVideoUrl();
$data['vimeoLink'] = '';
$data['streamingUrl'] = '';
if(strpos($video, 'youtu') != false){
$videoData = $this->getVideoInfoTest($video);
//return new JsonResponse($videoData);
$data['vimeoLink'] = $videoData['streamingData']['adaptiveFormats']['2']['url'];
$data['streamingUrl'] = $videoData['streamingData']['dashManifestUrl'];
}
if(strpos($video, 'vimeo') != false){
$videoId = explode('/',$video);
$videoId = $videoId[count($videoId)-1];
$client = new Vimeo($this->getParameter('vimeo_client_id'), $this->getParameter('vimeo_client_secret'), $this->getParameter('vimeo_access_token'));
$response = $client->request('/videos/'.$videoId, array(), 'GET');
$lookup = array_search('hls', array_column($response['body']['files'], 'quality'));
$data['vimeoLink'] = $response['body']['files'][$lookup]['link'];
$data['streamingUrl'] = $data['vimeoLink'];
}
//return new JsonResponse($data);
$return[0] = $data;
return new JsonResponse($return);
}
/**
* List all exercises available in given agegroup
*
* @Route("/mobile/exercises/coach",
*
* )
* @Method("POST")
*
* @param $request Request
* @param $clubId int
* @param $ageGroupId int
* @param $limit int
* @param $offset int
* @param $field string
* @param $sort string
* @param $created string
* @param $locale string
* @param $tagIds string
*
* @return JsonResponse
*/
public function exercises(Request $request)
{
//{userId}/{clubId}/{ageGroupId}/{limit}/{offset}/{field}/{created}/{sort}/{locale}/
$data = json_decode($request->getContent(), true);
$userId = $data['userId'];
$clubId = $data['clubId'];
$ageGroupId = $data['ageGroupId'];
$limit = $data['limit'];
$offset = $data['offset'];
$field = $data['field'];
$created = $data['created'];
$sort = $data['sort'];
$locale = $data['locale'];
$libId = $data['libId'];
$search = $data['search'];
$club_param = $clubId ? (" OR e.club_id = ".$clubId) : '';
$userCondition = "and (e.club_id = 0 OR isnull(e.club_id) ".$club_param." OR e.user_id = ".$userId." )";
$ageGroupCondition = "a.id = ".$ageGroupId;
$activeCondition = " and (e.active = 1 OR ( e.user_id = ".$userId.$club_param." ))";
if($search){
$searchCondition = " and (et.name like '%".$search."%' OR et.description like '%".$search."%') ";
}else{
$searchCondition = "";
}
$langCondition = " and et.locale = '".$locale."' ";
if ($libId) {
$libCondition = " and l.library_id = ".$libId;
} else {
$libCondition = "";
}
if($created == 'favorites'){
$favoritesJoin = "left join exercises_favorite ef on e.id = ef.exercise_id";
$favoritesCondition = " and ef.user_id =".$userId;
}else{
$favoritesJoin = "";
$favoritesCondition = "";
}
if($created == 'club'){
$userCondition = "and (e.user_id =".$userId." OR e.club_id =".$clubId.")";
}
$sql = "
select
e.id as id,
e.user_id as user_id,
e.club_id as club_id,
c.initials as club_initials
from exercises e
left join exercises_libraries l on e.id = l.exercise_id
left join libraries libs on libs.id = l.library_id
left join exercises_tags t on e.id = t.exercise_id
left join exercises_translations et on e.id = et.translatable_id
left join clubs c on e.club_id = c.id
left join exercises_equipment eq on e.id = eq.exercise_id
left join equipment_translations eqt on eq.equipment_id = eqt.translatable_id
left join exercises_agegroups ea on e.id = ea.exercise_id
left join agegroups a on ea.age_group_id = a.id
".$favoritesJoin."
where
".$ageGroupCondition."
".$userCondition."
and !isnull(et.translatable_id)
".$searchCondition."
".$langCondition."
".$libCondition."
".$favoritesCondition."
".$activeCondition."
group by id
order by et.name
";
$conn = $this->getDoctrine()->getManager()->getConnection();
$stmt = $conn->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
$exerciseRepository = $this->getDoctrine()->getRepository(\App\Entity\Exercise::class);
$items = [];
foreach ($results as $key => $result) {
if ($key >= $offset && $key < ($limit + $offset)) {
$item = $this->checkCache($result['id'], $result['id']);
$item['lang'] = $locale;
$item['clubInitials'] = !isset($item['club']) ? null : $item['club'] != null ? $item['club']['initials'] : null;
$item['new'] = $item['createdAt'] >= time() - (86400 * self::NEW_DAYS_THRESHOLD);
$item['updated'] = !$item['new'] && isset($item['updatedAt']) && $item['updatedAt'] >= time() - (86400 * 30);
$item['favorite'] = $exerciseRepository->isFavorite($userId, intval($result['id']));
$items[] = $item;
}
}
$condition= array('clubId'=>$clubId, 'ageGroupId'=>$ageGroupId, 'limit'=>$limit,'offset'=>$offset,'field'=>$field,'created'=>$created,'sort'=>$sort,'locale'=>$locale,'libId'=>$libId,'search'=>$search);
$isFavorite= $this->requestStack->getSession()->get('isFavorite');
$data = [
'count' => count($items),
'sql' => $sql,
'userId' => $userId,
'isFavorite'=> $isFavorite,
'total' => count($results),
'total_sql' => count($items),
'condition' => $condition,
'created' => $created,
'items' => $items,
];
return new JsonResponse($data);
}
}