<?php
namespace App\EventSubscriber;
use Carbon\Carbon;
use Pimcore\Mail;
use Pimcore\Model\DataObject;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Model\DataObject\EwsNotification;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Service\TwitterService;
use App\C2IntegrationBundle\Service\C2Service;
use Symfony\Component\Templating\EngineInterface;
use Knp\Snappy\Pdf;
use Knp\Snappy\Image;
class TwitterEventListner
{
private $twitterService;
private $c2Service;
public function __construct(private Pdf $snappy, private Image $snappyImage, private EngineInterface $twig)
{
$this->twitterService = new TwitterService();
$this->c2Service = new C2Service();
}
public function onObjectCreate(DataObjectEvent $ewsNotificationObject)
{
$ewsNotification = $ewsNotificationObject->getObject();
if (
($ewsNotification instanceof EwsNotification) &&
($ewsNotification->isPublished(true)) &&
empty($ewsNotification->getTwitterId()) &&
empty($ewsNotification->getTwitterLog()) &&
$ewsNotification->getEnableTwitterNotification() == true &&
$ewsNotification->getStatus() != "ended"
) {
$governates = $ewsNotification->getGovernorate();
$startDate = $ewsNotification->getStartDate()->format('Y-m-d');
$currentDate = Carbon::now();
$targetDate = Carbon::parse($startDate);
$content = '';
$parameters = [];
if (!empty($ewsNotification->getRegion())) {
// $content .= 'Region : '. $ewsNotification->getRegion()->getName('en') ." \n";
$parameters['region'] = $ewsNotification->getRegion()->getName('ar');
}
if (!empty($ewsNotification->getAlertAction())) {
$alertActions = [];
//$content .= 'Alert Action: ';
foreach ($ewsNotification->getAlertAction() as $alertAction) {
// $content .= $alertAction->getName() .' , ';
$alertActions[] = $alertAction->getName('ar');
}
// $content .= " \n";
$parameters['alertAction'] = $alertActions;
}
if (!empty($ewsNotification->getAlertType())) {
$parameters['alertType'] = $ewsNotification->getAlertType()->getName('en');
// $content .= 'Alert Type: ' . $ewsNotification->getAlertType()->getName() ." \n";
}
if (!empty($ewsNotification->getWeatherPhenomenon())) {
$parameters['weatherPhenomenon'] = $ewsNotification->getWeatherPhenomenon()->getTitle('en');
// $parameters['alertStatusAr'] = $ewsNotification->getWeatherPhenomenon()->getTitle('ar');
$parameters['alertStatusAr'] = '';
//$content .= 'Weather Phenomenon: ' . $ewsNotification->getWeatherPhenomenon()->getTitle() ." \n";
}
if (!empty($ewsNotification->getAlertHazard())) {
$alertHazards = [];
//$content .= 'Alert Hazards: ';
foreach ($ewsNotification->getAlertHazard() as $hazard) {
//$content .= $hazard->getName() .' , ';
$alertHazards[] = $hazard->getName('ar');
}
$parameters['alertHazards'] = $alertHazards;
//$content .= " \n";
}
if ($ewsNotification->getGovernorate() && !empty($ewsNotification->getGovernorate())) {
$governorates = [];
//$content .= 'Governorate(s) Affected: ';
foreach ($ewsNotification->getGovernorate() as $governorate) {
$governorates[] = $governorate->getName('ar');
//$content .= $governorate->getName() .' , ';
}
$parameters['governorateAffected'] = $governorates;
//$content .= " \n";
}
//$content .= 'Alert Start Date: ' . (!empty($ewsNotification->getStartDate()) ? $ewsNotification->getStartDate()->format('Y-m-d h:i:sa') : 'Unknown') ." \n";
//$content .= 'Alert End Date: ' . (!empty($ewsNotification->getEndDate()) ? $ewsNotification->getEndDate()->format('Y-m-d h:i:sa') : 'Unknown') ." \n";
$parameters['alertStartDate'] = !empty($ewsNotification->getStartDate()) ? $ewsNotification->getStartDate()->format('Y-m-d h:i:sa') : 'Unknown';
$parameters['alertEndDate'] = !empty($ewsNotification->getEndDate()) ? $ewsNotification->getEndDate()->format('Y-m-d h:i:sa') : 'Unknown';
// $content .= 'Posted Today Date: ' . date('Y-m-d h:i:sa') ." \n";
// if (!empty($ewsNotification->getAttachment())) {
// $attachmentFile = API_BASE_URL.'/'.$ewsNotification->getAttachment()->getFullPath();
// $content .= 'Attachment : '. $attachmentFile ." \n";
// }
$HashTagcontent = "";
if (!empty($ewsNotification->getRegion())) {
$regionName = $ewsNotification->getRegion()->getName('ar');
$regionName = str_replace(' ', '_', $regionName);
// $HashTagcontent .= "اسم المنطقة: #$regionName\n";
}
if ($ewsNotification->getGovernorate() && !empty($ewsNotification->getGovernorate())) {
// $HashTagcontent .= "المحافظات المتأثرة: ";
foreach ($ewsNotification->getGovernorate() as $governorate) {
$govName = $governorate->getName('ar');
// $HashTagcontent .= "#$govName, ";
}
// $HashTagcontent = rtrim($HashTagcontent, ', ');
// $HashTagcontent .= "\n";
}
// $HashTagcontent .= "#الإنذار_المبكر #طقس_السعودية #المركز_الوطني_للأرصاد";
// $HashTagcontent .= "";
$HashTagcontent = $this->buildXPostCaption($ewsNotification);
$parameters['furtherInformation'] = 'https://beta.ncm.gov.sa/en/early-warning/' . $ewsNotification->getId();
// $content .= "For further information visit: https://beta.ncm.gov.sa/en/early-warning/" . $ewsNotification->getId() . " \n";
// $html = $this->twig->render('image_templates/x-post-template.html.twig', $parameters);
// $this->snappyImage->setOption('enable-local-file-access', true);
// $this->snappyImage->setOption('width', '787');
// $this->snappyImage->setOption('height', '797');
// $this->snappyImage->setOption('format', 'png');
// $image = $this->snappyImage->getOutputFromHtml($html);
// $asset = \App\Lib\Utility::createAsset($image, rand(0, 10000) . '_' . time() . '_custom_weather_report.jpeg', 'EWS Twitter Images');
// $asset_path = PIMCORE_PROJECT_ROOT . '/public/var/assets' . $asset->getPath() . $asset->getFileName();
// $tweet = $this->twitterService->uploadMedia($asset_path,$HashTagcontent);
$xPostMedia = $this->getXPostMedia($ewsNotification);
$tweet = $this->twitterService->uploadMedia($xPostMedia['paths'], $HashTagcontent);
if ($tweet) {
// $tweet = $this->twitterService->postTweet('', $media_id);
// $twitterResponse = $this->c2Service->sendTwitterTweetResponse($_ENV['TWITTER_POST_TEMPLATE'], $ewsNotification->getId(), $html);
if(isset($tweet['result']->data)){
$tweet_text = $tweet['result']?->data?->text;
preg_match('/https?:\/\/\S+/', $tweet_text, $matches);
$url = $matches[0] ?? null;
$twitterResponse = $this->c2Service->addAsset($xPostMedia['assets'], $url);
}
// $tweet = $this->twitterService->postTweet('', $media_id);
// $twitterResponse = $this->c2Service->sendTwitterTweetResponse($_ENV['TWITTER_POST_TEMPLATE'], $ewsNotification->getId(), $html, $url);
// $asset->delete();
if (!empty($tweet['tweetId'])) {
$ewsNotification->setTwitterId($tweet['tweetId']);
}
$ewsNotification->setTwitterLog($tweet['data']);
$ewsNotification->save();
if ($tweet['httpCode'] === 200 || $tweet['httpCode'] === 201 || $tweet['httpCode'] === 204) {
}
elseif ($tweet['httpCode'] === 403) {
// Forbidden - Duplicate content error
$responseData = json_decode($tweet['data'], true);
$errorMessage = $responseData['detail'];
// echo $errorMessage;
} else {
// echo 'Unexpected HTTP status code: ' . $tweet['httpCode'];
}
}
// $tweet = $this->twitterService->postTweet($content);
// echo 'POST_ID : '.$tweet['tweetId']. ' EWS_ID : '.$ewsNotification->getId(). ' , ';
}
}
public function onObjectUpdate(DataObjectEvent $ewsNotificationObject)
{
$ewsNotification = $ewsNotificationObject->getObject();
if (
($ewsNotification instanceof EwsNotification) &&
($ewsNotification->isPublished(true)) &&
empty($ewsNotification->getTwitterId()) &&
empty($ewsNotification->getTwitterLog()) &&
$ewsNotification->getEnableTwitterNotification() == true &&
$ewsNotification->getStatus() != "ended"
) {
$governates = $ewsNotification->getGovernorate();
$startDate = $ewsNotification->getStartDate()->format('Y-m-d');
$currentDate = Carbon::now();
$targetDate = Carbon::parse($startDate);
$content = '';
$parameters = [];
if (!empty($ewsNotification->getRegion())) {
// $content .= 'Region : '. $ewsNotification->getRegion()->getName('en') ." \n";
$parameters['region'] = $ewsNotification->getRegion()->getName('ar');
}
if (!empty($ewsNotification->getAlertAction())) {
// $content .= 'Alert Action: ';
$alertActions = [];
foreach ($ewsNotification->getAlertAction() as $alertAction) {
$alertActions[] = $alertAction->getName('ar');
//$content .= $alertAction->getName() .' , ';
}
$parameters['alertAction'] = $alertActions;
//$content .= " \n";
}
if (!empty($ewsNotification->getAlertType())) {
$parameters['alertType'] = $ewsNotification->getAlertType()->getName('en');
//$content .= 'Alert Type: ' . $ewsNotification->getAlertType()->getColor() ." \n";
}
if (!empty($ewsNotification->getWeatherPhenomenon())) {
$parameters['weatherPhenomenon'] = $ewsNotification->getWeatherPhenomenon()->getTitle('en');
$parameters['alertStatusAr'] = $ewsNotification->getWeatherPhenomenon()->getTitle('ar');
//$content .= 'Weather Phenomenon: ' . $ewsNotification->getWeatherPhenomenon()->getTitle() ." \n";
}
if (!empty($ewsNotification->getAlertHazard())) {
$alertHazards = [];
//$content .= 'Alert Hazards: ';
foreach ($ewsNotification->getAlertHazard() as $hazard) {
$alertHazards[] = $hazard->getName('ar');
//$content .= $hazard->getName() .' , ';
}
$parameters['alertHazards'] = $alertHazards;
//$content .= " \n";
}
if ($ewsNotification->getGovernorate() && !empty($ewsNotification->getGovernorate())) {
//$content .= 'Governorate(s) Affected: ';
$governorates = [];
foreach ($ewsNotification->getGovernorate() as $governorate) {
$governorates[] = $governorate->getName('ar');
//$content .= $governorate->getName() .' , ';
}
$parameters['governorateAffected'] = $governorates;
//$content .= " \n";
}
//$content .= 'Alert Start Date: ' . (!empty($ewsNotification->getStartDate()) ? $ewsNotification->getStartDate()->format('Y-m-d h:i:sa') : 'Unknown') ." \n";
//$content .= 'Alert End Date: ' . (!empty($ewsNotification->getEndDate()) ? $ewsNotification->getEndDate()->format('Y-m-d h:i:sa') : 'Unknown') ." \n";
$parameters['alertStartDate'] = !empty($ewsNotification->getStartDate()) ? $ewsNotification->getStartDate()->format('Y-m-d h:i:sa') : 'Unknown';
$parameters['alertEndDate'] = !empty($ewsNotification->getEndDate()) ? $ewsNotification->getEndDate()->format('Y-m-d h:i:sa') : 'Unknown';
// $content .= 'Posted Today Date: ' . date('Y-m-d h:i:sa') ." \n";
// if (!empty($ewsNotification->getAttachment())) {
// $attachmentFile = API_BASE_URL.'/'.$ewsNotification->getAttachment()->getFullPath();
// $content .= 'Attachment : '. $attachmentFile ." \n";
// }
//$content .= "For further information visit: https://beta.ncm.gov.sa/en/early-warning/" . $ewsNotification->getId() . " \n";
$HashTagcontent = "";
if (!empty($ewsNotification->getRegion())) {
$regionName = $ewsNotification->getRegion()->getName('ar');
$regionName = str_replace(' ', '_', $regionName);
// $HashTagcontent .= "اسم المنطقة: #$regionName\n";
}
if ($ewsNotification->getGovernorate() && !empty($ewsNotification->getGovernorate())) {
// $HashTagcontent .= "المحافظات المتأثرة: ";
foreach ($ewsNotification->getGovernorate() as $governorate) {
$govName = $governorate->getName('ar');
// $HashTagcontent .= "#$govName, ";
}
// $HashTagcontent = rtrim($HashTagcontent, ', ');
// $HashTagcontent .= "\n";
}
// $HashTagcontent .= "#الإنذار_المبكر #طقس_السعودية #المركز_الوطني_للأرصاد";
// $HashTagcontent .= "";
$HashTagcontent = $this->buildXPostCaption($ewsNotification);
$parameters['furtherInformation'] = 'https://beta.ncm.gov.sa/en/early-warning/' . $ewsNotification->getId();
// $html = $this->twig->render('image_templates/x-post-template.html.twig', $parameters);
// $this->snappyImage->setOption('enable-local-file-access', true);
// $this->snappyImage->setOption('width', '787');
// $this->snappyImage->setOption('height', '797');
// $this->snappyImage->setOption('format', 'png');
// $image = $this->snappyImage->getOutputFromHtml($html);
// $asset = \App\Lib\Utility::createAsset($image, rand(0, 10000) . '_' . time() . '_custom_weather_report.jpeg', 'EWS Twitter Images');
// $asset_path = PIMCORE_PROJECT_ROOT . '/public/var/assets' . $asset->getPath() . $asset->getFileName();
// $tweet = $this->twitterService->uploadMedia($asset_path, $HashTagcontent);
$xPostMedia = $this->getXPostMedia($ewsNotification);
$tweet = $this->twitterService->uploadMedia($xPostMedia['paths'], $HashTagcontent);
if ($tweet) {
if(isset($tweet['result']->data)){
$tweet_text = $tweet['result']?->data?->text;
preg_match('/https?:\/\/\S+/', $tweet_text, $matches);
$url = $matches[0] ?? null;
// $tweet = $this->twitterService->postTweet('', $media_id);
// $twitterResponse = $this->c2Service->sendTwitterTweetResponse($_ENV['TWITTER_POST_TEMPLATE'], $ewsNotification->getId(), $html, $url);
// $twitterResponse = $this->c2Service->addAsset([$asset],$url);
// $asset->delete();
$twitterResponse = $this->c2Service->addAsset($xPostMedia['assets'], $url);
}
if (!empty($tweet['tweetId'])) {
$ewsNotification->setTwitterId($tweet['tweetId']);
}
$ewsNotification->setTwitterLog($tweet['data']);
$ewsNotification->save();
if ($tweet['httpCode'] === 200 || $tweet['httpCode'] === 201 || $tweet['httpCode'] === 204) {
}
elseif ($tweet['httpCode'] === 403) {
// Forbidden - Duplicate content error
$responseData = json_decode($tweet['data'], true);
$errorMessage = $responseData['detail'];
// echo $errorMessage;
} else {
// echo 'Unexpected HTTP status code: ' . $tweet['httpCode'];
}
}
//$tweet = $this->twitterService->postTweet($content);
// echo 'POST_ID : '.$tweet['tweetId']. ' EWS_ID : '.$ewsNotification->getId(). ' , ';
}
}
private function getXPostMedia(EwsNotification $ewsNotification): array
{
$paths = [];
$assets = [];
$assetRoot = PIMCORE_PROJECT_ROOT . '/public/var/assets';
foreach ([
$ewsNotification->getXAttachment(),
$ewsNotification->getPolygonXAtachment(),
//$ewsNotification->getXHistoryAtachment(),
] as $asset) {
if ($asset) {
$paths[] = $assetRoot . $asset->getPath() . $asset->getFileName();
$assets[] = $asset;
}
}
return ['paths' => $paths, 'assets' => $assets];
}
/**
* Replace old NCM alert page URLs in the X caption with the public portal early-warning link.
*/
private function buildXPostCaption(EwsNotification $ewsNotification): string
{
$caption = (string) $ewsNotification->getXPost();
$earlyWarningUrl = 'https://beta.ncm.gov.sa/en/early-warning/' . $ewsNotification->getId();
$replaced = preg_replace(
'#https?://(?:www\.)?ncm\.gov\.sa/[Aa]r/alert/[Pp]ages\S*#u',
$earlyWarningUrl,
$caption
);
return is_string($replaced) ? $replaced : $caption;
}
}