<?php
namespace App\Controller;
use Pimcore\Controller\FrontendController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
use DateTime;
use App\Model\WeatherStationModel;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Service\NCMWeatherAPIService;
use App\Service\BassicAuthService;
use App\Service\MeteomaticsWeatherService;
use App\Service\UserPermission;
use Symfony\Component\HttpFoundation\Response;
use App\Model\EwsNotificationModel;
use App\Model\DeviceModel;
use App\Model\ReportLogModel;
use Pimcore\Log\ApplicationLogger;
use Symfony\Component\Templating\EngineInterface;
use App\Service\EmailService;
use App\Service\MeteomaticApiService;
use App\Service\PublicUserPermissionService;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Knp\Component\Pager\PaginatorInterface;
use App\Model\WeatherForecastCityModel;
use App\Service\CustomNotificationService;
/**
* User controller is responsible for handling various actions related to user management.
*
* @Route("/api/ncm/device")
*/
class DeviceApiController extends FrontendController
{
private $weatherStationModel;
private $ewsNotificationModel;
private $deviceModel;
private $reportLogModel;
var $emailService = null;
public function __construct(
protected TranslatorInterface $translator,
private ApplicationLogger $logger,
private EngineInterface $templating,
private NCMWeatherAPIService $ncmWeatherApiService,
private MeteomaticApiService $meteomaticApiService,
private MeteomaticsWeatherService $meteomaticsWeatherService,
private BassicAuthService $bassicAuthService,
private UserPermission $userPermission,
private TokenStorageInterface $tokenStorageInterface,
private JWTTokenManagerInterface $jwtManager,
private PublicUserPermissionService $publicUserPermissionService,
private CustomNotificationService $customNotificationService
) {
header('Content-Type: application/json; charset=UTF-8');
header("Access-Control-Allow-Origin: *");
$this->ewsNotificationModel = new EwsNotificationModel();
$this->weatherStationModel = new WeatherStationModel();
$this->deviceModel = new DeviceModel();
$this->reportLogModel = new ReportLogModel();
$this->templating = $templating;
$this->emailService = new EmailService();
}
/**
* @Route("/regions", methods={"POST"})
*/
public function regions(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);
}
$search = (isset($params['search']) && !empty($params['search'])) ? $params['search'] : null;
$result = $this->ncmWeatherApiService->getRegions($search, isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
return $this->json($result);
} catch (\Exception $ex) {
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/route-query", methods={"POST"})
*/
public function routeQuery(Request $request): JsonResponse
{
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check basic Authorization
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
// validate required parms
if (
!isset($params['date']) || !isset($params['parameters']) || !isset($params['location'])
) {
throw new \Exception('Missing required parameters');
}
$locations = $params['location'];
$parameters = $params['parameters'];
// Join the locations and parameters strings with ',' for the URL
$parameterString = $parameters;
$locationString = implode('+', $locations);
// Create a DateTime object
$date = new DateTime($params['date']);
$dateStrings = [];
// Format the DateTime object as a string and add it to the array
for ($i = 0; $i < count($locations); $i++) {
$dateStrings[] = $date->format(DateTime::ISO8601);
}
// Join the date strings with ',' for the URL
$dateString = implode(',', $dateStrings);
$response = $this->meteomaticApiService->getRouteQuery(
$dateString,
$parameterString,
$locationString
);
// For demonstration purposes, we will just return a JSON response
return $this->json($response);
}
/**
* @Route("/municipality", methods={"POST"})
*/
public function getMunicipalityAction(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['governorate_id'])) {
throw new \Exception('Missing required governorate id');
}
$governorateId = $params['governorate_id'];
$result = $this->ewsNotificationModel->getMunicipality($governorateId, $params['lang']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/governorates", methods={"POST"})
*/
public function getGovernorateByRegionAction(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['region_id'])) {
// throw new \Exception('Missing required region id');
// }
// $regionId = $params['region_id'];
$result = $this->ewsNotificationModel->getGovernoratesByRegion($params);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/tidal-amplitude", name="tidal-amplitude", methods={"POST"})
*/
public function tidalAmplitudeData(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);
}
$requiredParameters = ['hour', 'parameter', 'date', 'coordinates', 'model', 'format'];
foreach ($requiredParameters as $param) {
if (!isset($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
$hour = $params['hour'];
$parameter = $params['parameter'];
$date = $params['date'];
$coordinates = $params['coordinates'];
$model = $params['model'];
$format = $params['format'];
$response = $this->meteomaticsWeatherService->getTidalAmplitudes(
$hour,
$parameter,
$date,
$coordinates,
$model,
$format
);
// 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("/high-low-tide-times", name="high_low_tide_times", methods={"POST"})
*/
public function highLowTideTimesData(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);
}
$requiredParameters = ['hour', 'date', 'coordinates', 'model', 'format'];
foreach ($requiredParameters as $param) {
if (!isset($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
$hour = $params['hour'];
$date = $params['date'];
$coordinates = $params['coordinates'];
$model = $params['model'];
$format = $params['format'];
$response = $this->meteomaticsWeatherService->getHighLowTideTimes(
$hour,
$date,
$coordinates,
$model,
$format
);
// 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("/significant-wave-height", name="significant_wave_height", methods={"POST"})
*/
public function significantWaveHeightData(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);
}
$requiredParameters = ['hour', 'date', 'coordinates', 'format'];
foreach ($requiredParameters as $param) {
if (!isset($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
$hour = $params['hour'];
$date = $params['date'];
$coordinates = $params['coordinates'];
$format = $params['format'];
$response = $this->meteomaticsWeatherService->getSignificantWaveHeight(
$hour,
$date,
$coordinates,
$format
);
// 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("/surge-amplitude", name="surge_amplitude", methods={"POST"})
*/
public function surgeAmplitudeData(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);
}
$requiredParameters = ['hour', 'date', 'coordinates', 'model', 'format'];
foreach ($requiredParameters as $param) {
if (!isset($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
$hour = $params['hour'];
$date = $params['date'];
$coordinates = $params['coordinates'];
$model = $params['model'];
$format = $params['format'];
$response = $this->meteomaticsWeatherService->getSurgeAmplitude(
$hour,
$date,
$coordinates,
$model,
$format
);
// 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("/fog", name="fog", methods={"POST"})
*/
public function fogData(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);
}
$requiredParameters = ['hour', 'date', 'coordinates', 'format'];
foreach ($requiredParameters as $param) {
if (!isset($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
$hour = $params['hour'];
$date = $params['date'];
$coordinates = $params['coordinates'];
$format = $params['format'];
$response = $this->meteomaticsWeatherService->getFog(
$coordinates,
$date
);
// 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("/search-ews-notification", name = "search-ews-notification", methods={"POST"})
*/
public function searchEwsNotificationAction(Request $request, PaginatorInterface $paginator): JsonResponse
{
try {
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$lang = (isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$result = $this->ewsNotificationModel->searchEwsNotification($params, $lang, $paginator = null, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/translations/{locale?}", name="translations", methods={"GET"})
*/
public function frontendDashboardTranslation(Request $request, $locale = null)
{
try {
$response = [];
$db = \Pimcore\Db::get();
if ($locale) {
// Fetch translations for the provided locale
$selectedLocalities = $db->fetchAllAssociative("
SELECT * FROM translations_messages
WHERE `key` LIKE 'publicapp_%'
AND `language` = :locale
ORDER BY `creationDate` ASC
", ['locale' => $locale]);
foreach ($selectedLocalities as $value) {
$keyParts = explode('_', $value['key'], 3);
$category = $keyParts[1];
$key = $keyParts[2];
if (!isset($response[$category])) {
$response[$category] = [];
}
$response[$category][$key] = $value['text'];
}
return $this->json($response);
} else {
// Fetch translations for both 'ar' and 'en'
$selectedLocalities = $db->fetchAllAssociative("
SELECT * FROM translations_messages
WHERE `key` LIKE 'publicapp_%'
AND `language` IN ('ar', 'en')
ORDER BY `creationDate` ASC
");
foreach ($selectedLocalities as $value) {
$keyParts = explode('_', $value['key'], 3);
$category = $keyParts[1];
$key = $keyParts[2];
$language = $value['language'];
if (!isset($response[$language])) {
$response[$language] = [];
}
if (!isset($response[$language][$category])) {
$response[$language][$category] = [];
}
$response[$language][$category][$key] = $value['text'];
}
return $this->json($response);
}
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/list-ewsnotification", methods={"POST"})
*/
public function listEwsNotificationAction(Request $request, PaginatorInterface $paginator): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$params['unpublished'] = false;
$params['status'] = 'active';
$result = $this->ewsNotificationModel->notificationListing($params, $paginator = null, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/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 = $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", 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 ($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("/get-metar-data", methods={"POST"})
*/
public function getMetarData(Request $request): Response
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$requiredParameters = ['startDate', 'endDate', 'metar', 'duration'];
foreach ($requiredParameters as $param) {
if (!isset($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
$startDate = $params['startDate'];
$endDate = $params['endDate'];
$metar = $params['metar'];
$duration = $params['duration'];
$parameters = $params['parameter'] ?? null;
$genExcel = $request->get('gen_excel', false);
$metarData = $this->meteomaticsWeatherService->getMetarData($startDate, $endDate, $metar, $duration, $this->translator, $parameters, $genExcel);
return $this->json(['success' => true, 'message' => $this->translator->trans("excel_file_downloaded_successfully"), 'data' => $metarData]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-airport-stations", methods={"POST"})
*/
public function getAirportStations(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$result = $this->ncmWeatherApiService->getAirportStations($params['ccode'] ?? null);
return $this->json(['success' => true, 'data' => $result]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-forecast-cities", methods={"POST"})
*/
public function getForecastCities(Request $request): Response
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$forecastCityModel = new WeatherForecastCityModel();
$cities = $forecastCityModel->getWeatherForecastCities();
return $this->json(['success' => true, 'data' => $cities]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/momra-generate-token", methods={"POST"})
*/
public function getMomraGenerateToken(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$result = $this->ncmWeatherApiService->generateMomraToken();
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/list-weather-station", methods={"POST"})
*/
public function listWeatherStation(Request $request, PaginatorInterface $paginator): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$search = (isset($params['search']) && !empty($params['search'])) ? $params['search'] : null;
$id = (isset($params['id']) && !empty($params['id'])) ? $params['id'] : null;
$result = $this->weatherStationModel->getWeatherStations($paginator = null, null, null, $this->translator, $search, $id);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-station-data", methods={"GET"})
*/
public function getWeatherStationDataAction(Request $request)
{
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);
}
$typeName = $request->get('type_name');
$parameters = $request->get('parameters');
$dateTime = $request->get('date_time');
$bBox = $request->get('b_box');
if (!$typeName) {
throw new \InvalidArgumentException("Missing mandatory parameter: type_name");
}
if (!$parameters) {
throw new \InvalidArgumentException("Missing mandatory parameter: parameters");
}
if (!$dateTime) {
throw new \InvalidArgumentException("Missing mandatory parameter: date_time");
}
if (!$bBox) {
throw new \InvalidArgumentException("Missing mandatory parameter: b_box");
}
$result = $this->meteomaticsWeatherService->getWeatherStationData($typeName, $parameters, $dateTime, $bBox);
return $result;
} catch (\Exception $ex) {
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-push-alert-notification", methods={"POST"})
*/
public function getPushAlertNotification(Request $request): Response
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$result = $this->deviceModel->getPushAlertNotification($params, $this->translator);
return $this->json(['success' => true, 'data' => $result]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/manned-alerts", methods={"POST"})
*/
public function mannedAlerts(Request $request, PaginatorInterface $paginator): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['from_date']) || !isset($params['to_date'])) {
// throw new \Exception('Date range is required');
return $this->json(['success' => false, 'message' => $this->translator->trans('date_range_is_required')]);
}
$result = $this->customNotificationService->getMannedAlerts($params, $paginator = null);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
}
}
/**
* @Route("/get-phenomena-list", methods={"POST"})
*/
public function getPhenomenaList(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$result = $this->ewsNotificationModel->getPhenomenaList();
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-today-weather-report", methods={"POST"})
*/
public function getTodayWeatherReport(Request $request): JsonResponse
{
try {
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
// get request params
$params = json_decode($request->getContent(), true);
// set locale
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// get today weather report data
$result = $this->reportLogModel->getTodayWeatherReportData($request, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-all-weather-report", methods={"POST"})
*/
public function getAllWeatherReport(Request $request): JsonResponse
{
try {
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
// get request params
$params = json_decode($request->getContent(), true);
// set locale
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// get today weather report data
$result = $this->reportLogModel->getAllWeatherReportData($request, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-mobile-assets-list", methods={"POST"})
*/
public function getMobileAssetsList(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$data = [];
$list = new \Pimcore\Model\Asset\Listing();
$list->setCondition("path LIKE ?", ["/mobile-assets%"]);
$list->load();
foreach ($list as $key => $value) {
if ($value->getType() == "image") {
$data[] = BASE_URL . $value->getPath() . $value->getFilename();
} elseif ($value->getType() == 'video') {
$data[] = BASE_URL . $value->getPath() . $value->getFilename();
}
}
$result = ["success" => true, "data" => $data];
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/kingdom-weather-description", methods={"POST"})
*/
public function kingdomWeatherDirect(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
// get request params
$params = json_decode($request->getContent(), true);
// set locale
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
return $this->json($this->ncmWeatherApiService->getKingdomWeatherData());
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-hijri-date", name="api_ncm_device_get_hijri_date", methods={"POST"})
*/
public function getHijriDatetime(Request $request): Response
{
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$params = json_decode($request->getContent(), true);
if (isset($params['location']) && isset($params['rawOffset'])) {
$offset = $params['rawOffset'] / 3600;
$locations = $params['location'];
$parameters = ["sunset:sql"];
// Join the locations and parameters strings with ',' for the URL
$parameterString = $parameters;
$locationString = implode('+', $locations);
// Create a DateTime object
$date = new DateTime();
$dateStrings = [];
// Format the DateTime object as a string and add it to the array
for ($i = 0; $i < count($locations); $i++) {
$dateStrings[] = $date->format(DateTime::ISO8601);
}
// Join the date strings with ',' for the URL
$dateString = implode(',', $dateStrings);
$response = $this->meteomaticApiService->getRouteQuery(
$dateString,
$parameterString,
$locationString
);
$sunsetTime = "";
if ($response['success'] == true) {
$sunsetTime = $response['data']['data'][0]['parameters'][0]['value'];
$response = \App\Lib\Utility::getHijriDatetime($sunsetTime, $offset);
}
} else {
$response = \App\Lib\Utility::getHijriDatetime();
}
return $this->json(["success" => true, "date" => $response]);
}
/**
* @Route("/get-isolines", methods={"GET"})
*/
public function getIsolinesAction(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
// Get access token
$tokenResult = $this->meteomaticApiService->getToken();
if (!isset($tokenResult['access_token'])) {
throw new \RuntimeException("Failed to retrieve access token");
}
$accessToken = $tokenResult['access_token'];
$measure = $request->get('measure');
$dateTime = $request->get('date_time');
$accessToken = $accessToken;
if (!$measure) {
throw new \InvalidArgumentException("Missing mandatory parameter: measure");
}
if (!$dateTime) {
throw new \InvalidArgumentException("Missing mandatory parameter: date_time");
}
if (!$accessToken) {
throw new \InvalidArgumentException("Missing mandatory parameter: access_token");
}
$result = $this->meteomaticsWeatherService->getIsolines($measure, $dateTime, $accessToken);
return $this->json($result);
} catch (\Exception $ex) {
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
}