<?php
namespace App\Controller;
use App\Model\EwsNotificationModel;
use DateTime;
use Pimcore\Db;
use App\Service\UserPermission;
use Pimcore\Log\ApplicationLogger;
use App\Service\MeteomaticApiService;
use App\Service\MeteomaticsWeatherService;
use App\Service\BassicAuthService;
use App\Service\PublicUserPermissionService;
use Pimcore\Controller\FrontendController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\Translation\TranslatorInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Matches /blog exactly
*
* @Route("/api/ncm")
*/
class GenericMateoMaticsController extends FrontendController
{
private $organizationModel;
private $userModel;
private $lang;
private $ewsNotificationModel;
public function __construct(
private TokenStorageInterface $tokenStorageInterface,
private JWTTokenManagerInterface $jwtManager,
private UserPermission $userPermission,
private PublicUserPermissionService $publicUserPermissionService,
protected TranslatorInterface $translator,
private ApplicationLogger $logger,
private MeteomaticApiService $meteomaticApiService,
private MeteomaticsWeatherService $meteomaticsWeatherService,
private BassicAuthService $bassicAuthService
) {
header('Content-Type: application/json; charset=UTF-8');
header("Access-Control-Allow-Origin: *");
$this->meteomaticApiService = $meteomaticApiService;
$this->ewsNotificationModel = new EwsNotificationModel();
$this->publicUserPermissionService = $publicUserPermissionService;
}
/**
* @Route("/query", name="query", methods={"POST"})
*/
public function fetchMeteomaticData(Request $request): JsonResponse
{
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
if (!isset($params['format'])) {
throw new \InvalidArgumentException('Missing "format" parameter');
}
if ($params['format'] == "json") {
if (
!isset($params['startdate']) ||
!isset($params['enddate']) ||
!isset($params['resolution']) ||
!isset($params['parameters']) ||
!isset($params['lat']) ||
!isset($params['lon']) ||
!isset($params['format'])
) {
throw new \Exception('Missing required parameters');
}
// date_default_timezone_set('UTC');
//$hour = $params['hour'];
$format = $params['format'];
// $startDate = new DateTime($params['startdate']);
// $endDate = new DateTime($params['enddate']);
$startDate = $params['startdate'];
$endDate = $params['enddate'];
$resolution = $params['resolution'];
$parameters = $params['parameters'];
$model = $params['model'];
$lat = $params['lat'];
$lon = $params['lon'];
$response = $this->meteomaticApiService->timeSeriesQuery(
$startDate,
$endDate,
$resolution,
$parameters,
$model,
$lat,
$lon,
$format,
$this->translator
);
} else {
$mandatoryParams = ['version', 'request', 'layers', 'crs', 'bbox', 'format', 'width', 'height', 'tiled'];
foreach ($mandatoryParams as $param) {
if (!isset($params[$param]) || empty($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
throw new \InvalidArgumentException(sprintf($this->translator->trans("missing_or_empty_mandatory_parameter: %s"), $parameterList));
}
header('Content-Type: image/png');
$result = $this->meteomaticsWeatherService->getWeatherMap($params['version'], $params['request'], $params['layers'], $params['crs'], $params['bbox'], $params['format'], $params['width'], $params['height'], $params['tiled']);
echo $result;
exit;
}
// You can return or process the $data as needed
// For demonstration purposes, we will just return a JSON response
return $this->json($response);
}
/**
* @Route("/public-query", name="public_query", methods={"POST"})
*/
public function publicMetarQuery(Request $request): JsonResponse
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
//check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
if (
!isset($params['startdate']) ||
!isset($params['enddate']) ||
!isset($params['resolution']) ||
!isset($params['parameters']) ||
!isset($params['coordinate']) ||
!isset($params['format'])
) {
throw new \Exception('Missing required parameters');
}
// date_default_timezone_set('UTC');
//$hour = $params['hour'];
$format = $params['format'];
$startDate = $params['startdate'];
$endDate = $params['enddate'];
$resolution = $params['resolution'];
$parametersArray = $params['parameters'];
$coordinate = $params['coordinate'];
$parameters = implode(',', $parametersArray);
$model = '';
if (isset($params['model']) && !empty($params['model'])) {
$model = $params['model'];
}
$source = '';
if (isset($params['source']) && !empty($params['source'])) {
$source = $params['source'];
}
$onInvalid = '';
if (isset($params['on_invalid']) && !empty($params['on_invalid'])) {
$onInvalid = $params['on_invalid'];
}
// Convert dates to the desired format (assuming start time is 00:00:00 and end time is 23:59:59)
$startDate = new DateTime($params['startdate']);
$endDate = new DateTime($params['enddate']);
// $startDateStr = $startDate->format(DateTime::ISO8601);
// $endDateStr = $endDate->format(DateTime::ISO8601);
// $dateRange = $startDateStr . "--" . $endDateStr . ':' . $resolution;
$response = $this->meteomaticApiService->publicRouteQuery(
$startDate,
$endDate,
$resolution,
$parametersArray,
$coordinate,
$format,
$model,
$source,
$onInvalid,
);
// You can return or process the $data as needed
// For demonstration purposes, we will just return a JSON response
return $this->json($response);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/industry/query", name="industry_query", methods={"POST"})
*/
public function fetchIndustryMeteomaticData(Request $request): JsonResponse
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$user = $response['user'];
// Varify user allowed permissions
$reslult = $this->publicUserPermissionService->publicUserPermissionCheck($user, $params['parameters'], $this->translator);
if ($reslult['success'] !== true) {
return $this->json($reslult);
}
if (!isset($params['format'])) {
throw new \InvalidArgumentException('Missing "format" parameter');
}
if ($params['format'] == "json") {
if (
!isset($params['startdate']) ||
!isset($params['enddate']) ||
!isset($params['resolution']) ||
!isset($params['parameters']) ||
!isset($params['lat']) ||
!isset($params['lon']) ||
!isset($params['format'])
) {
throw new \Exception('Missing required parameters');
}
// date_default_timezone_set('UTC');
//$hour = $params['hour'];
$format = $params['format'];
$startDate = new DateTime($params['startdate']);
$endDate = new DateTime($params['enddate']);
$resolution = $params['resolution'];
$parameters = $params['parameters'];
$model = $params['model'];
$lat = $params['lat'];
$lon = $params['lon'];
$response = $this->meteomaticApiService->timeSeriesQuery(
$startDate,
$endDate,
$resolution,
$parameters,
$model,
$lat,
$lon,
$format,
$this->translator
);
} else {
$mandatoryParams = ['version', 'request', 'layers', 'crs', 'bbox', 'format', 'width', 'height', 'tiled'];
foreach ($mandatoryParams as $param) {
if (!isset($params[$param]) || empty($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
throw new \InvalidArgumentException(sprintf($this->translator->trans("missing_or_empty_mandatory_parameter: %s"), $parameterList));
}
header('Content-Type: image/png');
$result = $this->meteomaticsWeatherService->getWeatherMap($params['version'], $params['request'], $params['layers'], $params['crs'], $params['bbox'], $params['format'], $params['width'], $params['height'], $params['tiled']);
echo $result;
exit;
}
// You can return or process the $data as needed
// For demonstration purposes, we will just return a JSON response
return $this->json($response);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/governorate", methods={"GET"})
*/
public function getGovernorateAction(Request $request)
{
try {
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$result = $this->ewsNotificationModel->getGovernorates();
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/municipality", methods={"GET"})
*/
public function getMunicipalityAction(Request $request)
{
try {
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$result = $this->ewsNotificationModel->getMunicipality();
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
}