src/Controller/DeviceApiController.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Pimcore\Controller\FrontendController;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Contracts\Translation\TranslatorInterface;
  8. use DateTime;
  9. use App\Model\WeatherStationModel;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. use App\Service\NCMWeatherAPIService;
  12. use App\Service\BassicAuthService;
  13. use App\Service\MeteomaticsWeatherService;
  14. use App\Service\UserPermission;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use App\Model\EwsNotificationModel;
  17. use App\Model\DeviceModel;
  18. use App\Model\ReportLogModel;
  19. use Pimcore\Log\ApplicationLogger;
  20. use Symfony\Component\Templating\EngineInterface;
  21. use App\Service\EmailService;
  22. use App\Service\MeteomaticApiService;
  23. use App\Service\PublicUserPermissionService;
  24. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  25. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  26. use Knp\Component\Pager\PaginatorInterface;
  27. use App\Model\WeatherForecastCityModel;
  28. use App\Service\CustomNotificationService;
  29. /**
  30. * User controller is responsible for handling various actions related to user management.
  31. *
  32. * @Route("/api/ncm/device")
  33. */
  34. class DeviceApiController extends FrontendController
  35. {
  36. private $weatherStationModel;
  37. private $ewsNotificationModel;
  38. private $deviceModel;
  39. private $reportLogModel;
  40. var $emailService = null;
  41. public function __construct(
  42. protected TranslatorInterface $translator,
  43. private ApplicationLogger $logger,
  44. private EngineInterface $templating,
  45. private NCMWeatherAPIService $ncmWeatherApiService,
  46. private MeteomaticApiService $meteomaticApiService,
  47. private MeteomaticsWeatherService $meteomaticsWeatherService,
  48. private BassicAuthService $bassicAuthService,
  49. private UserPermission $userPermission,
  50. private TokenStorageInterface $tokenStorageInterface,
  51. private JWTTokenManagerInterface $jwtManager,
  52. private PublicUserPermissionService $publicUserPermissionService,
  53. private CustomNotificationService $customNotificationService,
  54. private \Doctrine\DBAL\Connection $connection,
  55. ) {
  56. header('Content-Type: application/json; charset=UTF-8');
  57. header("Access-Control-Allow-Origin: *");
  58. $this->ewsNotificationModel = new EwsNotificationModel();
  59. $this->weatherStationModel = new WeatherStationModel();
  60. $this->deviceModel = new DeviceModel();
  61. $this->reportLogModel = new ReportLogModel();
  62. $this->templating = $templating;
  63. $this->emailService = new EmailService();
  64. }
  65. /**
  66. * @Route("/regions", methods={"POST"})
  67. */
  68. public function regions(Request $request): JsonResponse
  69. {
  70. try {
  71. $params = json_decode($request->getContent(), true);
  72. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  73. // check user credentials and expiry
  74. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  75. if ($response['success'] !== true) {
  76. return $this->json($response);
  77. }
  78. $search = (isset($params['search']) && !empty($params['search'])) ? $params['search'] : null;
  79. $result = $this->ncmWeatherApiService->getRegions($search, isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  80. return $this->json($result);
  81. } catch (\Exception $ex) {
  82. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  83. }
  84. }
  85. /**
  86. * @Route("/route-query", methods={"POST"})
  87. */
  88. public function routeQuery(Request $request): JsonResponse
  89. {
  90. $params = json_decode($request->getContent(), true);
  91. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  92. // check basic Authorization
  93. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  94. if ($response['success'] !== true) {
  95. return $this->json($response);
  96. }
  97. // validate required parms
  98. if (
  99. !isset($params['date']) || !isset($params['parameters']) || !isset($params['location'])
  100. ) {
  101. throw new \Exception('Missing required parameters');
  102. }
  103. $locations = $params['location'];
  104. $parameters = $params['parameters'];
  105. // Join the locations and parameters strings with ',' for the URL
  106. $parameterString = $parameters;
  107. $locationString = implode('+', $locations);
  108. // Create a DateTime object
  109. $date = new DateTime($params['date']);
  110. $dateStrings = [];
  111. // Format the DateTime object as a string and add it to the array
  112. for ($i = 0; $i < count($locations); $i++) {
  113. $dateStrings[] = $date->format(DateTime::ISO8601);
  114. }
  115. // Join the date strings with ',' for the URL
  116. $dateString = implode(',', $dateStrings);
  117. $response = $this->meteomaticApiService->getRouteQuery(
  118. $dateString,
  119. $parameterString,
  120. $locationString
  121. );
  122. // For demonstration purposes, we will just return a JSON response
  123. return $this->json($response);
  124. }
  125. /**
  126. * @Route("/municipality", methods={"POST"})
  127. */
  128. public function getMunicipalityAction(Request $request): JsonResponse
  129. {
  130. try {
  131. $params = json_decode($request->getContent(), true);
  132. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  133. // check user credentials and expiry
  134. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  135. if ($response['success'] !== true) {
  136. return $this->json($response);
  137. }
  138. if (!isset($params['governorate_id'])) {
  139. throw new \Exception('Missing required governorate id');
  140. }
  141. $governorateId = $params['governorate_id'];
  142. $result = $this->ewsNotificationModel->getMunicipality($governorateId, $params['lang']);
  143. return $this->json($result);
  144. } catch (\Exception $ex) {
  145. $this->logger->error($ex->getMessage());
  146. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  147. }
  148. }
  149. /**
  150. * @Route("/governorates", methods={"POST"})
  151. */
  152. public function getGovernorateByRegionAction(Request $request): JsonResponse
  153. {
  154. try {
  155. $params = json_decode($request->getContent(), true);
  156. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  157. // check user credentials and expiry
  158. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  159. if ($response['success'] !== true) {
  160. return $this->json($response);
  161. }
  162. // if (!isset($params['region_id'])) {
  163. // throw new \Exception('Missing required region id');
  164. // }
  165. // $regionId = $params['region_id'];
  166. $result = $this->ewsNotificationModel->getGovernoratesByRegion($params);
  167. return $this->json($result);
  168. } catch (\Exception $ex) {
  169. $this->logger->error($ex->getMessage());
  170. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  171. }
  172. }
  173. /**
  174. * @Route("/tidal-amplitude", name="tidal-amplitude", methods={"POST"})
  175. */
  176. public function tidalAmplitudeData(Request $request): JsonResponse
  177. {
  178. try {
  179. $params = json_decode($request->getContent(), true);
  180. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  181. // check user credentials and expiry
  182. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  183. if ($response['success'] !== true) {
  184. return $this->json($response);
  185. }
  186. $requiredParameters = ['hour', 'parameter', 'date', 'coordinates', 'model', 'format'];
  187. foreach ($requiredParameters as $param) {
  188. if (!isset($params[$param])) {
  189. $missingParams[] = $param;
  190. }
  191. }
  192. if (!empty($missingParams)) {
  193. // Throw an exception with a message that includes the missing parameters
  194. $parameterList = implode(", ", $missingParams);
  195. return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  196. }
  197. $hour = $params['hour'];
  198. $parameter = $params['parameter'];
  199. $date = $params['date'];
  200. $coordinates = $params['coordinates'];
  201. $model = $params['model'];
  202. $format = $params['format'];
  203. $response = $this->meteomaticsWeatherService->getTidalAmplitudes(
  204. $hour,
  205. $parameter,
  206. $date,
  207. $coordinates,
  208. $model,
  209. $format
  210. );
  211. // You can return or process the $data as needed
  212. // For demonstration purposes, we will just return a JSON response
  213. return $this->json($response);
  214. } catch (\Exception $ex) {
  215. $this->logger->error($ex->getMessage());
  216. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  217. }
  218. }
  219. /**
  220. * @Route("/high-low-tide-times", name="high_low_tide_times", methods={"POST"})
  221. */
  222. public function highLowTideTimesData(Request $request): JsonResponse
  223. {
  224. try {
  225. $params = json_decode($request->getContent(), true);
  226. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  227. // check user credentials and expiry
  228. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  229. if ($response['success'] !== true) {
  230. return $this->json($response);
  231. }
  232. $requiredParameters = ['hour', 'date', 'coordinates', 'model', 'format'];
  233. foreach ($requiredParameters as $param) {
  234. if (!isset($params[$param])) {
  235. $missingParams[] = $param;
  236. }
  237. }
  238. if (!empty($missingParams)) {
  239. // Throw an exception with a message that includes the missing parameters
  240. $parameterList = implode(", ", $missingParams);
  241. return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  242. }
  243. $hour = $params['hour'];
  244. $date = $params['date'];
  245. $coordinates = $params['coordinates'];
  246. $model = $params['model'];
  247. $format = $params['format'];
  248. $response = $this->meteomaticsWeatherService->getHighLowTideTimes(
  249. $hour,
  250. $date,
  251. $coordinates,
  252. $model,
  253. $format
  254. );
  255. // You can return or process the $data as needed
  256. // For demonstration purposes, we will just return a JSON response
  257. return $this->json($response);
  258. } catch (\Exception $ex) {
  259. $this->logger->error($ex->getMessage());
  260. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  261. }
  262. }
  263. /**
  264. * @Route("/significant-wave-height", name="significant_wave_height", methods={"POST"})
  265. */
  266. public function significantWaveHeightData(Request $request): JsonResponse
  267. {
  268. try {
  269. $params = json_decode($request->getContent(), true);
  270. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  271. // check user credentials and expiry
  272. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  273. if ($response['success'] !== true) {
  274. return $this->json($response);
  275. }
  276. $requiredParameters = ['hour', 'date', 'coordinates', 'format'];
  277. foreach ($requiredParameters as $param) {
  278. if (!isset($params[$param])) {
  279. $missingParams[] = $param;
  280. }
  281. }
  282. if (!empty($missingParams)) {
  283. // Throw an exception with a message that includes the missing parameters
  284. $parameterList = implode(", ", $missingParams);
  285. return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  286. }
  287. $hour = $params['hour'];
  288. $date = $params['date'];
  289. $coordinates = $params['coordinates'];
  290. $format = $params['format'];
  291. $response = $this->meteomaticsWeatherService->getSignificantWaveHeight(
  292. $hour,
  293. $date,
  294. $coordinates,
  295. $format
  296. );
  297. // You can return or process the $data as needed
  298. // For demonstration purposes, we will just return a JSON response
  299. return $this->json($response);
  300. } catch (\Exception $ex) {
  301. $this->logger->error($ex->getMessage());
  302. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  303. }
  304. }
  305. /**
  306. * @Route("/surge-amplitude", name="surge_amplitude", methods={"POST"})
  307. */
  308. public function surgeAmplitudeData(Request $request): JsonResponse
  309. {
  310. try {
  311. $params = json_decode($request->getContent(), true);
  312. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  313. // check user credentials and expiry
  314. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  315. if ($response['success'] !== true) {
  316. return $this->json($response);
  317. }
  318. $requiredParameters = ['hour', 'date', 'coordinates', 'model', 'format'];
  319. foreach ($requiredParameters as $param) {
  320. if (!isset($params[$param])) {
  321. $missingParams[] = $param;
  322. }
  323. }
  324. if (!empty($missingParams)) {
  325. // Throw an exception with a message that includes the missing parameters
  326. $parameterList = implode(", ", $missingParams);
  327. return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  328. }
  329. $hour = $params['hour'];
  330. $date = $params['date'];
  331. $coordinates = $params['coordinates'];
  332. $model = $params['model'];
  333. $format = $params['format'];
  334. $response = $this->meteomaticsWeatherService->getSurgeAmplitude(
  335. $hour,
  336. $date,
  337. $coordinates,
  338. $model,
  339. $format
  340. );
  341. // You can return or process the $data as needed
  342. // For demonstration purposes, we will just return a JSON response
  343. return $this->json($response);
  344. } catch (\Exception $ex) {
  345. $this->logger->error($ex->getMessage());
  346. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  347. }
  348. }
  349. /**
  350. * @Route("/fog", name="fog", methods={"POST"})
  351. */
  352. public function fogData(Request $request): JsonResponse
  353. {
  354. try {
  355. $params = json_decode($request->getContent(), true);
  356. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  357. // check user credentials and expiry
  358. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  359. if ($response['success'] !== true) {
  360. return $this->json($response);
  361. }
  362. $requiredParameters = ['hour', 'date', 'coordinates', 'format'];
  363. foreach ($requiredParameters as $param) {
  364. if (!isset($params[$param])) {
  365. $missingParams[] = $param;
  366. }
  367. }
  368. if (!empty($missingParams)) {
  369. // Throw an exception with a message that includes the missing parameters
  370. $parameterList = implode(", ", $missingParams);
  371. return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  372. }
  373. $hour = $params['hour'];
  374. $date = $params['date'];
  375. $coordinates = $params['coordinates'];
  376. $format = $params['format'];
  377. $response = $this->meteomaticsWeatherService->getFog(
  378. $coordinates,
  379. $date
  380. );
  381. // You can return or process the $data as needed
  382. // For demonstration purposes, we will just return a JSON response
  383. return $this->json($response);
  384. } catch (\Exception $ex) {
  385. $this->logger->error($ex->getMessage());
  386. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  387. }
  388. }
  389. /**
  390. * @Route("/search-ews-notification", name = "search-ews-notification", methods={"POST"})
  391. */
  392. public function searchEwsNotificationAction(Request $request, PaginatorInterface $paginator): JsonResponse
  393. {
  394. try {
  395. // check user credentials and expiry
  396. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  397. if ($response['success'] !== true) {
  398. return $this->json($response);
  399. }
  400. $params = json_decode($request->getContent(), true);
  401. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  402. $lang = (isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  403. $paginator = (isset($params["paginator"]) ? $paginator : null);
  404. $result = $this->ewsNotificationModel->searchEwsNotification($params, $lang, $paginator, $this->translator);
  405. return $this->json($result);
  406. } catch (\Exception $ex) {
  407. $this->logger->error($ex->getMessage());
  408. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  409. }
  410. }
  411. /**
  412. * @Route("/ews-analytics", methods={"POST"})
  413. */
  414. public function ewsAnalyticsAction(Request $request): JsonResponse
  415. {
  416. try {
  417. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  418. if ($response['success'] !== true) {
  419. return $this->json($response);
  420. }
  421. $params = json_decode($request->getContent(), true);
  422. $lang = ($request->headers->has('lang')) ? $request->headers->get('lang') : "en";
  423. $result = $this->ewsNotificationModel->ewsAnalytics($params, $this->connection, $lang);
  424. return $this->json($result);
  425. } catch (\Exception $ex) {
  426. $this->logger->error($ex->getMessage());
  427. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  428. }
  429. }
  430. /**
  431. * @Route("/translations/{locale?}", name="translations", methods={"GET"})
  432. */
  433. public function frontendDashboardTranslation(Request $request, $locale = null)
  434. {
  435. try {
  436. $response = [];
  437. $db = \Pimcore\Db::get();
  438. if ($locale) {
  439. // Fetch translations for the provided locale
  440. $selectedLocalities = $db->fetchAllAssociative("
  441. SELECT * FROM translations_messages
  442. WHERE `key` LIKE 'publicapp_%'
  443. AND `language` = :locale
  444. ORDER BY `creationDate` ASC
  445. ", ['locale' => $locale]);
  446. foreach ($selectedLocalities as $value) {
  447. $keyParts = explode('_', $value['key'], 3);
  448. $category = $keyParts[1];
  449. $key = $keyParts[2];
  450. if (!isset($response[$category])) {
  451. $response[$category] = [];
  452. }
  453. $response[$category][$key] = $value['text'];
  454. }
  455. return $this->json($response);
  456. } else {
  457. // Fetch translations for both 'ar' and 'en'
  458. $selectedLocalities = $db->fetchAllAssociative("
  459. SELECT * FROM translations_messages
  460. WHERE `key` LIKE 'publicapp_%'
  461. AND `language` IN ('ar', 'en')
  462. ORDER BY `creationDate` ASC
  463. ");
  464. foreach ($selectedLocalities as $value) {
  465. $keyParts = explode('_', $value['key'], 3);
  466. $category = $keyParts[1];
  467. $key = $keyParts[2];
  468. $language = $value['language'];
  469. if (!isset($response[$language])) {
  470. $response[$language] = [];
  471. }
  472. if (!isset($response[$language][$category])) {
  473. $response[$language][$category] = [];
  474. }
  475. $response[$language][$category][$key] = $value['text'];
  476. }
  477. return $this->json($response);
  478. }
  479. } catch (\Exception $ex) {
  480. $this->logger->error($ex->getMessage());
  481. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  482. }
  483. }
  484. /**
  485. * @Route("/list-ewsnotification", methods={"POST"})
  486. */
  487. public function listEwsNotificationAction(Request $request, PaginatorInterface $paginator): JsonResponse
  488. {
  489. try {
  490. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  491. if ($response['success'] !== true) {
  492. return $this->json($response);
  493. }
  494. $params = json_decode($request->getContent(), true);
  495. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  496. $params['unpublished'] = false;
  497. $params['status'] = 'active';
  498. $result = $this->ewsNotificationModel->notificationListing($params, $paginator = null, $this->translator);
  499. return $this->json($result);
  500. } catch (\Exception $ex) {
  501. $this->logger->error($ex->getMessage());
  502. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  503. }
  504. }
  505. /**
  506. * @Route("/query", methods={"POST"})
  507. */
  508. public function fetchMeteomaticData(Request $request): JsonResponse
  509. {
  510. $params = json_decode($request->getContent(), true);
  511. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  512. // check user credentials and expiry
  513. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  514. if ($response['success'] !== true) {
  515. return $this->json($response);
  516. }
  517. if (!isset($params['format'])) {
  518. throw new \InvalidArgumentException('Missing "format" parameter');
  519. }
  520. if ($params['format'] == "json") {
  521. if (
  522. !isset($params['startdate']) ||
  523. !isset($params['enddate']) ||
  524. !isset($params['resolution']) ||
  525. !isset($params['parameters']) ||
  526. !isset($params['lat']) ||
  527. !isset($params['lon']) ||
  528. !isset($params['format'])
  529. ) {
  530. throw new \Exception('Missing required parameters');
  531. }
  532. // date_default_timezone_set('UTC');
  533. //$hour = $params['hour'];
  534. $format = $params['format'];
  535. $startDate = $params['startdate'];
  536. $endDate = $params['enddate'];
  537. $resolution = $params['resolution'];
  538. $parameters = $params['parameters'];
  539. $model = $params['model'];
  540. $lat = $params['lat'];
  541. $lon = $params['lon'];
  542. $response = $this->meteomaticApiService->timeSeriesQuery(
  543. $startDate,
  544. $endDate,
  545. $resolution,
  546. $parameters,
  547. $model,
  548. $lat,
  549. $lon,
  550. $format,
  551. $this->translator
  552. );
  553. } else {
  554. $mandatoryParams = ['version', 'request', 'layers', 'crs', 'bbox', 'format', 'width', 'height', 'tiled'];
  555. foreach ($mandatoryParams as $param) {
  556. if (!isset($params[$param]) || empty($params[$param])) {
  557. $missingParams[] = $param;
  558. }
  559. }
  560. if (!empty($missingParams)) {
  561. // Throw an exception with a message that includes the missing parameters
  562. $parameterList = implode(", ", $missingParams);
  563. throw new \InvalidArgumentException(sprintf($this->translator->trans("missing_or_empty_mandatory_parameter: %s"), $parameterList));
  564. }
  565. header('Content-Type: image/png');
  566. $result = $this->meteomaticsWeatherService->getWeatherMap($params['version'], $params['request'], $params['layers'], $params['crs'], $params['bbox'], $params['format'], $params['width'], $params['height'], $params['tiled']);
  567. echo $result;
  568. exit;
  569. }
  570. // You can return or process the $data as needed
  571. // For demonstration purposes, we will just return a JSON response
  572. return $this->json($response);
  573. }
  574. /**
  575. * @Route("/public-query", methods={"POST"})
  576. */
  577. public function publicMetarQuery(Request $request): JsonResponse
  578. {
  579. try {
  580. $params = json_decode($request->getContent(), true);
  581. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  582. //check user credentials and expiry
  583. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  584. if ($response['success'] !== true) {
  585. return $this->json($response);
  586. }
  587. if ($response['success'] !== true) {
  588. return $this->json($response);
  589. }
  590. if (
  591. !isset($params['startdate']) ||
  592. !isset($params['enddate']) ||
  593. !isset($params['resolution']) ||
  594. !isset($params['parameters']) ||
  595. !isset($params['coordinate']) ||
  596. !isset($params['format'])
  597. ) {
  598. throw new \Exception('Missing required parameters');
  599. }
  600. // date_default_timezone_set('UTC');
  601. //$hour = $params['hour'];
  602. $format = $params['format'];
  603. $startDate = $params['startdate'];
  604. $endDate = $params['enddate'];
  605. $resolution = $params['resolution'];
  606. $parametersArray = $params['parameters'];
  607. $coordinate = $params['coordinate'];
  608. $parameters = implode(',', $parametersArray);
  609. $model = '';
  610. if (isset($params['model']) && !empty($params['model'])) {
  611. $model = $params['model'];
  612. }
  613. $source = '';
  614. if (isset($params['source']) && !empty($params['source'])) {
  615. $source = $params['source'];
  616. }
  617. $onInvalid = '';
  618. if (isset($params['on_invalid']) && !empty($params['on_invalid'])) {
  619. $onInvalid = $params['on_invalid'];
  620. }
  621. // Convert dates to the desired format (assuming start time is 00:00:00 and end time is 23:59:59)
  622. $startDate = new DateTime($params['startdate']);
  623. $endDate = new DateTime($params['enddate']);
  624. $startDateStr = $startDate->format(DateTime::ISO8601);
  625. $endDateStr = $endDate->format(DateTime::ISO8601);
  626. $dateRange = $startDateStr . "--" . $endDateStr . ':' . $resolution;
  627. $response = $this->meteomaticApiService->publicRouteQuery(
  628. $startDate,
  629. $endDate,
  630. $resolution,
  631. $parametersArray,
  632. $coordinate,
  633. $format,
  634. $model,
  635. $source,
  636. $onInvalid,
  637. );
  638. // You can return or process the $data as needed
  639. // For demonstration purposes, we will just return a JSON response
  640. return $this->json($response);
  641. } catch (\Exception $ex) {
  642. $this->logger->error($ex->getMessage());
  643. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  644. }
  645. }
  646. /**
  647. * @Route("/get-metar-data", methods={"POST"})
  648. */
  649. public function getMetarData(Request $request): Response
  650. {
  651. try {
  652. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  653. if ($response['success'] !== true) {
  654. return $this->json($response);
  655. }
  656. $params = json_decode($request->getContent(), true);
  657. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  658. $requiredParameters = ['startDate', 'endDate', 'metar', 'duration'];
  659. foreach ($requiredParameters as $param) {
  660. if (!isset($params[$param])) {
  661. $missingParams[] = $param;
  662. }
  663. }
  664. if (!empty($missingParams)) {
  665. // Throw an exception with a message that includes the missing parameters
  666. $parameterList = implode(", ", $missingParams);
  667. return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  668. }
  669. $startDate = $params['startDate'];
  670. $endDate = $params['endDate'];
  671. $metar = $params['metar'];
  672. $duration = $params['duration'];
  673. $parameters = $params['parameter'] ?? null;
  674. $genExcel = $request->get('gen_excel', false);
  675. $metarData = $this->meteomaticsWeatherService->getMetarData($startDate, $endDate, $metar, $duration, $this->translator, $parameters, $genExcel);
  676. return $this->json(['success' => true, 'message' => $this->translator->trans("excel_file_downloaded_successfully"), 'data' => $metarData]);
  677. } catch (\Exception $ex) {
  678. $this->logger->error($ex->getMessage());
  679. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  680. }
  681. }
  682. /**
  683. * @Route("/get-forecast-cities", methods={"POST"})
  684. */
  685. public function getForecastCities(Request $request): Response
  686. {
  687. try {
  688. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  689. if ($response['success'] !== true) {
  690. return $this->json($response);
  691. }
  692. $params = json_decode($request->getContent(), true);
  693. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  694. $forecastCityModel = new WeatherForecastCityModel();
  695. $cities = $forecastCityModel->getWeatherForecastCities();
  696. return $this->json(['success' => true, 'data' => $cities]);
  697. } catch (\Exception $ex) {
  698. $this->logger->error($ex->getMessage());
  699. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  700. }
  701. }
  702. /**
  703. * @Route("/momra-generate-token", methods={"POST"})
  704. */
  705. public function getMomraGenerateToken(Request $request): JsonResponse
  706. {
  707. try {
  708. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  709. if ($response['success'] !== true) {
  710. return $this->json($response);
  711. }
  712. $result = $this->ncmWeatherApiService->generateMomraToken();
  713. return $this->json($result);
  714. } catch (\Exception $ex) {
  715. $this->logger->error($ex->getMessage());
  716. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  717. }
  718. }
  719. /**
  720. * @Route("/list-weather-station", methods={"POST"})
  721. */
  722. public function listWeatherStation(Request $request, PaginatorInterface $paginator): JsonResponse
  723. {
  724. try {
  725. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  726. if ($response['success'] !== true) {
  727. return $this->json($response);
  728. }
  729. $params = json_decode($request->getContent(), true);
  730. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  731. $result = $this->weatherStationModel->getWeatherStations($paginator = null, null, null, $this->translator);
  732. return $this->json($result);
  733. } catch (\Exception $ex) {
  734. $this->logger->error($ex->getMessage());
  735. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  736. }
  737. }
  738. /**
  739. * @Route("/get-station-data", methods={"GET"})
  740. */
  741. public function getWeatherStationDataAction(Request $request)
  742. {
  743. try {
  744. $params = json_decode($request->getContent(), true);
  745. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  746. // check user credentials and expiry
  747. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  748. if ($response['success'] !== true) {
  749. return $this->json($response);
  750. }
  751. $typeName = $request->get('type_name');
  752. $parameters = $request->get('parameters');
  753. $dateTime = $request->get('date_time');
  754. $bBox = $request->get('b_box');
  755. if (!$typeName) {
  756. throw new \InvalidArgumentException("Missing mandatory parameter: type_name");
  757. }
  758. if (!$parameters) {
  759. throw new \InvalidArgumentException("Missing mandatory parameter: parameters");
  760. }
  761. if (!$dateTime) {
  762. throw new \InvalidArgumentException("Missing mandatory parameter: date_time");
  763. }
  764. if (!$bBox) {
  765. throw new \InvalidArgumentException("Missing mandatory parameter: b_box");
  766. }
  767. $result = $this->meteomaticsWeatherService->getWeatherStationData($typeName, $parameters, $dateTime, $bBox);
  768. return $result;
  769. } catch (\Exception $ex) {
  770. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  771. }
  772. }
  773. /**
  774. * @Route("/get-push-alert-notification", methods={"POST"})
  775. */
  776. public function getPushAlertNotification(Request $request): Response
  777. {
  778. try {
  779. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  780. if ($response['success'] !== true) {
  781. return $this->json($response);
  782. }
  783. $params = json_decode($request->getContent(), true);
  784. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  785. $result = $this->deviceModel->getPushAlertNotification($params, $this->translator);
  786. return $this->json(['success' => true, 'data' => $result]);
  787. } catch (\Exception $ex) {
  788. $this->logger->error($ex->getMessage());
  789. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  790. }
  791. }
  792. /**
  793. * @Route("/manned-alerts", methods={"POST"})
  794. */
  795. public function mannedAlerts(Request $request, PaginatorInterface $paginator): JsonResponse
  796. {
  797. try {
  798. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  799. if ($response['success'] !== true) {
  800. return $this->json($response);
  801. }
  802. $params = json_decode($request->getContent(), true);
  803. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  804. if (!isset($params['from_date']) || !isset($params['to_date'])) {
  805. // throw new \Exception('Date range is required');
  806. return $this->json(['success' => false, 'message' => $this->translator->trans('date_range_is_required')]);
  807. }
  808. $result = $this->customNotificationService->getMannedAlerts($params, $paginator = null);
  809. return $this->json($result);
  810. } catch (\Exception $ex) {
  811. $this->logger->error($ex->getMessage());
  812. return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
  813. }
  814. }
  815. /**
  816. * @Route("/get-phenomena-list", methods={"POST"})
  817. */
  818. public function getPhenomenaList(Request $request): JsonResponse
  819. {
  820. try {
  821. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  822. if ($response['success'] !== true) {
  823. return $this->json($response);
  824. }
  825. $params = json_decode($request->getContent(), true);
  826. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  827. $result = $this->ewsNotificationModel->getPhenomenaList();
  828. return $this->json($result);
  829. } catch (\Exception $ex) {
  830. $this->logger->error($ex->getMessage());
  831. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  832. }
  833. }
  834. /**
  835. * @Route("/get-today-weather-report", methods={"POST"})
  836. */
  837. public function getTodayWeatherReport(Request $request): JsonResponse
  838. {
  839. try {
  840. // check user credentials and expiry
  841. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  842. if ($response['success'] !== true) {
  843. return $this->json($response);
  844. }
  845. // get request params
  846. $params = json_decode($request->getContent(), true);
  847. // set locale
  848. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  849. // get today weather report data
  850. $result = $this->reportLogModel->getTodayWeatherReportData($request, $this->translator);
  851. return $this->json($result);
  852. } catch (\Exception $ex) {
  853. $this->logger->error($ex->getMessage());
  854. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  855. }
  856. }
  857. /**
  858. * @Route("/get-all-weather-report", methods={"POST"})
  859. */
  860. public function getAllWeatherReport(Request $request): JsonResponse
  861. {
  862. try {
  863. // check user credentials and expiry
  864. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  865. if ($response['success'] !== true) {
  866. return $this->json($response);
  867. }
  868. // get request params
  869. $params = json_decode($request->getContent(), true);
  870. // set locale
  871. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  872. // get today weather report data
  873. $result = $this->reportLogModel->getAllWeatherReportData($request, $this->translator);
  874. return $this->json($result);
  875. } catch (\Exception $ex) {
  876. $this->logger->error($ex->getMessage());
  877. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  878. }
  879. }
  880. /**
  881. * @Route("/get-mobile-assets-list", methods={"POST"})
  882. */
  883. public function getMobileAssetsList(Request $request): JsonResponse
  884. {
  885. try {
  886. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  887. if ($response['success'] !== true) {
  888. return $this->json($response);
  889. }
  890. $data = [];
  891. $list = new \Pimcore\Model\Asset\Listing();
  892. $list->setCondition("path LIKE ?", ["/mobile-assets%"]);
  893. $list->load();
  894. foreach ($list as $key => $value) {
  895. if ($value->getType() == "image") {
  896. $data[] = BASE_URL . $value->getPath() . $value->getFilename();
  897. } elseif ($value->getType() == 'video') {
  898. $data[] = BASE_URL . $value->getPath() . $value->getFilename();
  899. }
  900. }
  901. $result = ["success" => true, "data" => $data];
  902. return $this->json($result);
  903. } catch (\Exception $ex) {
  904. $this->logger->error($ex->getMessage());
  905. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  906. }
  907. }
  908. /**
  909. * @Route("/kingdom-weather-description", methods={"POST"})
  910. */
  911. public function kingdomWeatherDirect(Request $request): JsonResponse
  912. {
  913. try {
  914. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  915. if ($response['success'] !== true) {
  916. return $this->json($response);
  917. }
  918. // get request params
  919. $params = json_decode($request->getContent(), true);
  920. // set locale
  921. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  922. return $this->json($this->ncmWeatherApiService->getKingdomWeatherData());
  923. } catch (\Exception $ex) {
  924. $this->logger->error($ex->getMessage());
  925. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  926. }
  927. }
  928. /**
  929. * @Route("/get-hijri-date", name="api_ncm_device_get_hijri_date", methods={"POST"})
  930. */
  931. public function getHijriDatetime(Request $request): Response
  932. {
  933. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  934. if ($response['success'] !== true) {
  935. return $this->json($response);
  936. }
  937. $params = json_decode($request->getContent(), true);
  938. if (isset($params['location']) && isset($params['rawOffset'])) {
  939. $offset = $params['rawOffset'] / 3600;
  940. $locations = $params['location'];
  941. $parameters = ["sunset:sql"];
  942. // Join the locations and parameters strings with ',' for the URL
  943. $parameterString = $parameters;
  944. $locationString = implode('+', $locations);
  945. // Create a DateTime object
  946. $date = new DateTime();
  947. $dateStrings = [];
  948. // Format the DateTime object as a string and add it to the array
  949. for ($i = 0; $i < count($locations); $i++) {
  950. $dateStrings[] = $date->format(DateTime::ISO8601);
  951. }
  952. // Join the date strings with ',' for the URL
  953. $dateString = implode(',', $dateStrings);
  954. $response = $this->meteomaticApiService->getRouteQuery(
  955. $dateString,
  956. $parameterString,
  957. $locationString
  958. );
  959. $sunsetTime = "";
  960. if ($response['success'] == true) {
  961. $sunsetTime = $response['data']['data'][0]['parameters'][0]['value'];
  962. $response = \App\Lib\Utility::getHijriDatetime($sunsetTime, $offset);
  963. }
  964. } else {
  965. $response = \App\Lib\Utility::getHijriDatetime();
  966. }
  967. return $this->json(["success" => true, "date" => $response]);
  968. }
  969. /**
  970. * @Route("/get-isolines", methods={"GET"})
  971. */
  972. public function getIsolinesAction(Request $request): JsonResponse
  973. {
  974. try {
  975. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  976. if ($response['success'] !== true) {
  977. return $this->json($response);
  978. }
  979. // Get access token
  980. $tokenResult = $this->meteomaticApiService->getToken();
  981. if (!isset($tokenResult['access_token'])) {
  982. throw new \RuntimeException("Failed to retrieve access token");
  983. }
  984. $accessToken = $tokenResult['access_token'];
  985. $measure = $request->get('measure');
  986. $dateTime = $request->get('date_time');
  987. $accessToken = $accessToken;
  988. if (!$measure) {
  989. throw new \InvalidArgumentException("Missing mandatory parameter: measure");
  990. }
  991. if (!$dateTime) {
  992. throw new \InvalidArgumentException("Missing mandatory parameter: date_time");
  993. }
  994. if (!$accessToken) {
  995. throw new \InvalidArgumentException("Missing mandatory parameter: access_token");
  996. }
  997. $result = $this->meteomaticsWeatherService->getIsolines($measure, $dateTime, $accessToken);
  998. return $this->json($result);
  999. } catch (\Exception $ex) {
  1000. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  1001. }
  1002. }
  1003. /**
  1004. * @Route("/view-ews-notification", methods={"POST"})
  1005. */
  1006. public function detailEwsNotificationAction(Request $request): JsonResponse
  1007. {
  1008. try {
  1009. $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  1010. if ($response['success'] !== true) {
  1011. return $this->json($response);
  1012. }
  1013. $params = json_decode($request->getContent(), true);
  1014. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1015. if (!isset($params['id'])) {
  1016. return $this->json(['success' => false, 'message' => $this->translator->trans('EWS Alert ID must be provided to proceed.')]);
  1017. }
  1018. if (is_array($params['id'])) {
  1019. $ids = array_values(array_filter($params['id'], static function ($v) {
  1020. return $v !== null && $v !== '' && $v !== false;
  1021. }));
  1022. if ($ids === []) {
  1023. return $this->json(['success' => false, 'message' => $this->translator->trans('EWS Alert ID must be provided to proceed.')]);
  1024. }
  1025. } elseif ($params['id'] === '' || $params['id'] === null) {
  1026. return $this->json(['success' => false, 'message' => $this->translator->trans('EWS Alert ID must be provided to proceed.')]);
  1027. }
  1028. $result = $this->ewsNotificationModel->viewNotification($params, $this->translator);
  1029. return $this->json($result);
  1030. } catch (\Exception $ex) {
  1031. $this->logger->error($ex->getMessage());
  1032. return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
  1033. }
  1034. }
  1035. /**
  1036. * @Route("/search-ews-notification-by-region", methods={"POST"})
  1037. */
  1038. public function searchEwsNotificationByRegionAction(Request $request): JsonResponse
  1039. {
  1040. try {
  1041. // $response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
  1042. // if ($response['success'] !== true) {
  1043. // return $this->json($response);
  1044. // }
  1045. $params = json_decode($request->getContent(), true);
  1046. $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1047. if (!isset($params['region_id'])) {
  1048. return $this->json(['success' => false, 'message' => $this->translator->trans('Region ID must be provided to proceed.')]);
  1049. }
  1050. $regionId = $params['region_id'];
  1051. $result = $this->ewsNotificationModel->searchEwsNotificationByRegion($regionId, $this->translator);
  1052. return $this->json($result);
  1053. } catch (\Exception $ex) {
  1054. $this->logger->error($ex->getMessage());
  1055. return $this->json(['success' => false, 'message' => $ex->getMessage()]);
  1056. }
  1057. }
  1058. }