src/Controller/IndexController.php line 52

Open in your IDE?
  1. <?php
  2. /** @noinspection PhpUnused */
  3. namespace App\Controller;
  4. use App\Component\Traits\EntityManagerTrait;
  5. use App\Component\Traits\KernelTrait;
  6. use App\Entity\FtpConfig;
  7. use App\Service\GoogleCloud\StorageService;
  8. use App\Service\MenuService;
  9. use Google\Cloud\Storage\StorageObject;
  10. use Psr\Cache\InvalidArgumentException;
  11. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  17. use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
  18. use Symfony\Contracts\Cache\ItemInterface;
  19. use Symfony\Contracts\Cache\TagAwareCacheInterface;
  20. /**
  21. * @Route("")
  22. */
  23. class IndexController extends AbstractLelpController
  24. {
  25. use KernelTrait;
  26. use EntityManagerTrait;
  27. private MenuService $menuService;
  28. private StorageService $storageService;
  29. private RoleHierarchyInterface $roleHierarchy;
  30. private TagAwareCacheInterface $cache;
  31. public function __construct(
  32. MenuService $menuService,
  33. StorageService $storageService,
  34. RoleHierarchyInterface $roleHierarchy,
  35. TagAwareCacheInterface $cache
  36. ) {
  37. $this->menuService = $menuService;
  38. $this->storageService = $storageService;
  39. $this->roleHierarchy = $roleHierarchy;
  40. $this->cache = $cache;
  41. }
  42. /**
  43. * @Route("/")
  44. */
  45. public function index(): Response
  46. {
  47. $actionForm = $this->createFormBuilder()
  48. ->add('new', SubmitType::class, ['label' => 'Modifier mes informations'])
  49. ->getForm();
  50. $user = $this->getUser();
  51. if ($user->getDepots()->isEmpty()) {
  52. $depots = null;
  53. } else {
  54. $depots = $user->getDepots();
  55. }
  56. $user->setDatelastlogin(new \DateTime());
  57. $this->entityManager->persist($user);
  58. $this->entityManager->flush();
  59. return $this->render('index-info.html.twig', [
  60. 'user' => $user,
  61. 'depots' => $depots,
  62. 'actionForm' => $actionForm->createView(),
  63. ]);
  64. }
  65. /**
  66. * @Route("/APK/proxidriver.apk")
  67. *
  68. * @return RedirectResponse|Response
  69. */
  70. public function apk(): RedirectResponse|Response
  71. {
  72. return $this->getBucketFile('EXPORT_APK', 'proxidriver.apk');
  73. }
  74. /**
  75. * @param string|FtpConfig $ftpConfig
  76. *
  77. * @return RedirectResponse|Response
  78. */
  79. private function getBucketFile($ftpConfig, string $filename): RedirectResponse|Response
  80. {
  81. try {
  82. if (!$ftpConfig instanceof FtpConfig) {
  83. $ftpConfig = $this->repositoryService->getFtpConfig()->findOneByCode($ftpConfig);
  84. }
  85. $objects = $this->storageService->getObjects($ftpConfig, $filename);
  86. if (!$objects->current()) {
  87. $this->addAdminError(
  88. $ftpConfig->getServer()->getUriWithoutPassword().'/'.$ftpConfig->getDistantPath().'/'.$filename
  89. );
  90. throw new \LogicException('Le fichier est introuvable');
  91. }
  92. /** @var StorageObject $o */
  93. $o = $objects->current();
  94. $this->repositoryService->getStatistiqueTelechargementFichier()->incrementCompteur($filename);
  95. $this->entityManager->flush();
  96. $response = new Response();
  97. $response->headers->set('Cache-Control', 'private');
  98. $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'";');
  99. $response->headers->set('Content-length', $o->info()['size']);
  100. $response->headers->set('Content-type', $o->info()['contentType']);
  101. $response->sendHeaders();
  102. $response->setContent($o->downloadAsString());
  103. $response->sendContent();
  104. return $response;
  105. } catch (\LogicException $e) {
  106. $this->addFlash('danger', $e->getMessage());
  107. } catch (\Throwable $e) {
  108. $this->addAdminError($e);
  109. }
  110. return $this->redirectToRoute('app_index_index');
  111. }
  112. /**
  113. * @Route("/FILE/{name}")
  114. *
  115. * @param string $name base64 encoded path of the file
  116. *
  117. * @return Response
  118. */
  119. public function gcsFile(string $name): Response
  120. {
  121. $name = base64_decode($name);
  122. $filename = basename($name);
  123. $ftpConfig = clone $this->repositoryService->getFtpConfig()->findOneByCode('EXPORT');
  124. $ftpConfig->setFileRegex($name);
  125. // Ne pas changer FILES
  126. // C'est le seul répertoire du bucket autorisé pour le téléchargement direct
  127. $ftpConfig->setDistantPath('FILES');
  128. return $this->getBucketFile($ftpConfig, $filename);
  129. }
  130. /**
  131. * @Route("/PDF/{filename}")
  132. * @param $filename
  133. * @return RedirectResponse|Response
  134. */
  135. public function pdfFilename($filename): RedirectResponse|Response
  136. {
  137. return $this->getBucketFile('EXPORT_PDF', $filename);
  138. }
  139. /**
  140. * @Route("/privacy-policy")
  141. */
  142. public function privacyPolicy(): Response
  143. {
  144. return $this->render('privacy_policy.html.twig', []);
  145. }
  146. /**
  147. * @Route("/user-roles")
  148. * @param AuthorizationCheckerInterface $authChecker
  149. * @return JsonResponse
  150. * @throws InvalidArgumentException
  151. */
  152. public function userRoles(AuthorizationCheckerInterface $authChecker): JsonResponse
  153. {
  154. $user = $this->getUser();
  155. if (!$user) {
  156. return $this->json(['roles' => []]);
  157. }
  158. $cacheKey = 'user_roles_'.$user->getId();
  159. $userKey = $user->getId();
  160. $allRoles = $this->cache->get($cacheKey, function (ItemInterface $item) use ($authChecker, $userKey) {
  161. $item->expiresAfter(86400);
  162. $item->tag(['user_'.$userKey]);
  163. $allPossibleRoles = $this->getAllPossibleRoles();
  164. $grantedRoles = [];
  165. foreach ($allPossibleRoles as $role) {
  166. if ($authChecker->isGranted($role)) {
  167. $grantedRoles[] = $role;
  168. }
  169. }
  170. return $grantedRoles;
  171. });
  172. return $this->json([
  173. 'roles' => $allRoles,
  174. ]);
  175. }
  176. /**
  177. * @throws InvalidArgumentException
  178. */
  179. private function getAllPossibleRoles(): array
  180. {
  181. return $this->cache->get('all_reachable_roles', function (ItemInterface $item) {
  182. $item->expiresAfter(86400);
  183. $item->tag(['roles_hierarchy']);
  184. $reachableRoles = $this->roleHierarchy->getReachableRoleNames(['ROLE_ADMIN']);
  185. if (!in_array('ROLE_USER', $reachableRoles)) {
  186. $reachableRoles[] = 'ROLE_USER';
  187. }
  188. return array_unique($reachableRoles);
  189. });
  190. }
  191. }