3 namespace Rapsys\AirBundle\Command
; 
   5 use Doctrine\Persistence\ManagerRegistry
; 
   6 use Symfony\Component\Cache\Adapter\FilesystemAdapter
; 
   7 use Symfony\Component\Console\Command\Command
; 
   8 use Symfony\Component\Console\Input\InputInterface
; 
   9 use Symfony\Component\Console\Output\OutputInterface
; 
  10 use Symfony\Component\DependencyInjection\ContainerInterface
; 
  11 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
; 
  12 use Symfony\Component\Routing\RouterInterface
; 
  13 use Symfony\Component\Translation\TranslatorInterface
; 
  14 use Twig\Extra\Markdown\DefaultMarkdown
; 
  16 use Rapsys\AirBundle\Entity\Session
; 
  18 class CalendarCommand 
extends Command 
{ 
  19         //Set failure constant 
  22         ///Set success constant 
  31          * @var ManagerRegistry 
  38         ///Translator instance 
  39         protected $translator; 
  42          * Inject doctrine, container and translator interface 
  44          * @param ContainerInterface $container The container instance 
  45          * @param ManagerRegistry $doctrine The doctrine instance 
  46          * @param RouterInterface $router The router instance 
  47          * @param TranslatorInterface $translator The translator instance 
  49     public function __construct(ContainerInterface 
$container, ManagerRegistry 
$doctrine, RouterInterface 
$router, TranslatorInterface 
$translator) { 
  50                 //Call parent constructor 
  51                 parent
::__construct(); 
  54                 $this->config 
= $container->getParameter($this->getAlias()); 
  57                 $this->locale 
= $container->getParameter('kernel.default_locale'); 
  60         $this->doctrine 
= $doctrine; 
  63         $this->router 
= $router; 
  66                 $context = $this->router
->getContext(); 
  69                 $context->setHost('airlibre.eu'); 
  72                 $context->setScheme('https'); 
  75                 $this->translator 
= $translator; 
  78         ///Configure attribute command 
  79         protected function configure() { 
  83                         ->setName('rapsysair:calendar') 
  84                         //Set description shown with bin/console list 
  85                         ->setDescription('Synchronize sessions in calendar') 
  86                         //Set description shown with bin/console --help airlibre:attribute 
  87                         ->setHelp('This command synchronize sessions in google calendar'); 
  90         ///Process the attribution 
  91         protected function execute(InputInterface 
$input, OutputInterface 
$output) { 
  93                 $period = new \
DatePeriod( 
  94                         //Start from last week 
  95                         new \
DateTime('-1 week'), 
  97                         new \
DateInterval('P1D'), 
  98                         //End with next 2 week 
  99                         new \
DateTime('+2 week') 
 102                 //Retrieve events to update 
 103                 $sessions = $this->doctrine
->getRepository(Session
::class)->fetchAllByDatePeriod($period, $this->locale
); 
 105                 //Markdown converted instance 
 106                 $markdown = new DefaultMarkdown
; 
 108                 //Retrieve cache object 
 109                 //XXX: by default stored in /tmp/symfony-cache/@/W/3/6SEhFfeIW4UMDlAII+Dg 
 110                 //XXX: stored in %kernel.project_dir%/var/cache/airlibre/0/P/IA20X0K4dkMd9-+Ohp9Q 
 111                 $cache = new FilesystemAdapter($this->config
['cache']['namespace'], $this->config
['cache']['lifetime'], $this->config
['path']['cache']); 
 114                 $cacheCalendars = $cache->getItem('calendars'); 
 117                 if (!$cacheCalendars->isHit()) { 
 119                         return self
::FAILURE
; 
 123                 $calendars = $cacheCalendars->get(); 
 125                 //Check expired token 
 126                 foreach($calendars as $clientId => $client) { 
 128                         $googleClient = new \Google\
Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]); 
 130                         //Iterate on each tokens 
 131                         foreach($client['tokens'] as $tokenId => $token) { 
 133                                 $googleClient->setAccessToken( 
 135                                                 'access_token' => $tokenId, 
 136                                                 'refresh_token' => $token['refresh'], 
 137                                                 'expires_in' => $token['expire'], 
 138                                                 'scope' => $token['scope'], 
 139                                                 'token_type' => $token['type'], 
 140                                                 'created' => $token['created'] 
 145                                 if ($exp = $googleClient->isAccessTokenExpired()) { 
 147                                         if (($refreshToken = $googleClient->getRefreshToken()) && ($googleToken = $googleClient->fetchAccessTokenWithRefreshToken($refreshToken)) && empty($googleToken['error'])) { 
 148                                                 //Add refreshed token 
 149                                                 $calendars[$clientId]['tokens'][$googleToken['access_token']] = [ 
 150                                                         'calendar' => $token['calendar'], 
 151                                                         'prefix' => $token['prefix'], 
 152                                                         'refresh' => $googleToken['refresh_token'], 
 153                                                         'expire' => $googleToken['expires_in'], 
 154                                                         'scope' => $googleToken['scope'], 
 155                                                         'type' => $googleToken['token_type'], 
 156                                                         'created' => $googleToken['created'] 
 160                                                 unset($calendars[$clientId]['tokens'][$tokenId]); 
 163                                                 unset($calendars[$clientId]['tokens'][$tokenId]); 
 166                                                 if (empty($calendars[$clientId]['tokens'])) { 
 168                                                         unset($calendars[$clientId]); 
 172                                                 $cacheCalendars->set($calendars); 
 175                                                 $cache->save($cacheCalendars); 
 177                                                 //Drop token and report 
 178                                                 echo 'Token '.$tokenId.' for calendar '.$token['calendar'].' has expired and is not refreshable'."\n"; 
 181                                                 //XXX: we want that mail and stop here 
 182                                                 return self
::FAILURE
; 
 189                 $cacheCalendars->set($calendars); 
 192                 $cache->save($cacheCalendars); 
 194                 //Iterate on each calendar client 
 195                 foreach($calendars as $clientId => $client) { 
 197                         $googleClient = new \Google\
Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]); 
 199                         //Iterate on each tokens 
 200                         foreach($client['tokens'] as $tokenId => $token) { 
 202                                 $googleClient->setAccessToken( 
 204                                                 'access_token' => $tokenId, 
 205                                                 'refresh_token' => $token['refresh'], 
 206                                                 'expires_in' => $token['expire'], 
 207                                                 'scope' => $token['scope'], 
 208                                                 'token_type' => $token['type'], 
 209                                                 'created' => $token['created'] 
 214                                 if ($exp = $googleClient->isAccessTokenExpired()) { 
 215                                         //Last chance to skip this run 
 219                                 //Get google calendar 
 220                                 $googleCalendar = new \Google\Service\
Calendar($googleClient); 
 224                                         $calendar = $googleCalendar->calendars
->get($token['calendar']); 
 226                                 } catch(\Google\Service\Exception 
$e) { 
 228                                         //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors 
 229                                         echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n"; 
 230                                         echo $e->getTraceAsString()."\n"; 
 233                                         return self
::FAILURE
; 
 241                                         //XXX: show even deleted event to be able to update them 
 242                                         'showDeleted' => true, 
 243                                         //TODO: fetch events one day before and one day after to avoid triggering double insert duplicate key 409 errors :=) on google 
 244                                         'timeMin' => $period->getStartDate()->format(\DateTime
::ISO8601
), 
 245                                         'timeMax' => $period->getEndDate()->format(\DateTime
::ISO8601
) 
 246                                         /*, 'iCalUID' => 'airlibre/?????'*//*'orderBy' => 'startTime', */ 
 249                                 //Retrieve event collection 
 250                                 $googleEvents = $googleCalendar->events
->listEvents($token['calendar'], $filters); 
 252                                 //Iterate until reached end 
 254                                         //Iterate on each event 
 255                                         foreach ($googleEvents->getItems() as $event) { 
 257                                                 if (preg_match('/^'.$token['prefix'].'([0-9]+)$/', $id = $event->getId(), $matches)) { 
 258                                                         $events[$matches[1]] = $event; 
 259                                                 //XXX: 3rd party events with id not matching prefix are skipped 
 261                                                 #       echo 'Skipping '.$event->getId().':'.$event->getSummary()."\n";*/ 
 266                                         $pageToken = $googleEvents->getNextPageToken(); 
 270                                                 //Replace collection with next one 
 271                                                 $googleEvents = $service->events
->listEvents($token['calendar'], $filters+
['pageToken' => $pageToken]); 
 277                                 //Iterate on each session to sync 
 278                                 foreach($sessions as $sessionId => $session) { 
 279                                         //Init shared properties 
 280                                         //TODO: validate for constraints here ??? https://developers.google.com/calendar/api/guides/extended-properties 
 281                                         //TODO: drop shared as unused ??? 
 283                                                 'gps' => $session['l_latitude'].','.$session['l_longitude'] 
 288                                                 'title' => $this->translator
->trans('Session %id% by %pseudonym%', ['%id%' => $sessionId, '%pseudonym%' => $session['au_pseudonym']]).' '.$this->translator
->trans('at '.$session['l_title']), 
 289                                                 'url' => $this->router
->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface
::ABSOLUTE_URL
) 
 293                                         $description = 'Description :'."\n".strip_tags(preg_replace('!<a href="([^"]+)"(?: title="[^"]+")?'.'>([^<]+)</a>!', '\1', $markdown->convert(strip_tags($session['p_description'])))); 
 294                                         $shared['description'] = $markdown->convert(strip_tags($session['p_description'])); 
 296                                         //Add class when available 
 297                                         if (!empty($session['p_class'])) { 
 298                                                 $shared['class'] = $session['p_class']; 
 299                                                 $description .= "\n\n".'Classe :'."\n".$session['p_class']; 
 302                                         //Add contact when available 
 303                                         if (!empty($session['p_contact'])) { 
 304                                                 $shared['contact'] = $session['p_contact']; 
 305                                                 $description .= "\n\n".'Contact :'."\n".$session['p_contact']; 
 308                                         //Add donate when available 
 309                                         if (!empty($session['p_donate'])) { 
 310                                                 $shared['donate'] = $session['p_donate']; 
 311                                                 $description .= "\n\n".'Contribuer :'."\n".$session['p_donate']; 
 314                                         //Add link when available 
 315                                         if (!empty($session['p_link'])) { 
 316                                                 $shared['link'] = $session['p_link']; 
 317                                                 $description .= "\n\n".'Site :'."\n".$session['p_link']; 
 320                                         //Add profile when available 
 321                                         if (!empty($session['p_profile'])) { 
 322                                                 $shared['profile'] = $session['p_profile']; 
 323                                                 $description .= "\n\n".'Réseau social :'."\n".$session['p_profile']; 
 327                                         if (!empty($session['locked']) && $events[$sessionId]) { 
 329                                                 if (!empty($event = $events[$sessionId])) { 
 332                                                                 $googleCalendar->events
->delete($token['calendar'], $event->getId()); 
 334                                                         } catch(\Google\Service\Exception 
$e) { 
 336                                                                 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors 
 337                                                                 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n"; 
 338                                                                 echo $e->getTraceAsString()."\n"; 
 341                                                                 return self
::FAILURE
; 
 345                                         } elseif (empty($events[$sessionId])) { 
 347                                                 $event = new \Google\Service\Calendar\
Event( 
 349                                                                 //TODO: replace 'airlibre' with $this->config['calendar']['prefix'] when possible with prefix validating [a-v0-9]{5,} 
 350                                                                 //XXX: see https://developers.google.com/calendar/api/v3/reference/events/insert#id 
 351                                                                 'id' => $token['prefix'].$sessionId, 
 352                                                                 'summary' => $session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']), 
 353                                                                 #'description' => $markdown->convert(strip_tags($session['p_description'])), 
 354                                                                 'description' => $description, 
 355                                                                 'status' => empty($session['a_canceled'])?'confirmed':'cancelled', 
 356                                                                 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]), 
 358                                                                 'extendedProperties' => [ 
 362                                                                 //TODO: attendees[] ? 
 364                                                                         'dateTime' => $session['start']->format(\DateTime
::ISO8601
) 
 367                                                                         'dateTime' => $session['stop']->format(\DateTime
::ISO8601
) 
 374                                                         $googleCalendar->events
->insert($token['calendar'], $event); 
 376                                                 } catch(\Google\Service\Exception 
$e) { 
 378                                                         //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors 
 379                                                         echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n"; 
 380                                                         echo $e->getTraceAsString()."\n"; 
 383                                                         return self
::FAILURE
; 
 388                                                 $event = $events[$sessionId]; 
 391                                                 if ($session['updated'] >= (new \
DateTime($event->getUpdated()))) { 
 393                                                         $event->setSummary($session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short'])); 
 396                                                         $event->setDescription($description); 
 399                                                         $event->setStatus(empty($session['a_canceled'])?'confirmed':'cancelled'); 
 402                                                         $event->setLocation(implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']])); 
 405                                                         $eventSource = $event->getSource(); 
 407                                                         //Update source title 
 408                                                         $eventSource->setTitle($source['title']); 
 411                                                         $eventSource->setUrl($source['url']); 
 414                                                         #$event->setSource($source); 
 416                                                         //Get extended properties 
 417                                                         $extendedProperties = $event->getExtendedProperties(); 
 420                                                         $extendedProperties->setShared($shared); 
 423                                                         //TODO: attendees[] ? 
 426                                                         $start = $event->getStart(); 
 428                                                         //Update start datetime 
 429                                                         $start->setDateTime($session['start']->format(\DateTime
::ISO8601
)); 
 432                                                         $end = $event->getEnd(); 
 434                                                         //Update stop datetime 
 435                                                         $end->setDateTime($session['stop']->format(\DateTime
::ISO8601
)); 
 439                                                                 $updatedEvent = $googleCalendar->events
->update($token['calendar'], $event->getId(), $event); 
 441                                                         } catch(\Google\Service\Exception 
$e) { 
 443                                                                 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors 
 444                                                                 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n"; 
 445                                                                 echo $e->getTraceAsString()."\n"; 
 448                                                                 return self
::FAILURE
; 
 452                                                 //Drop from events array 
 453                                                 unset($events[$sessionId]); 
 457                                 //Remaining events to drop 
 458                                 foreach($events as $eventId => $event) { 
 459                                         //Non canceled events 
 460                                         if ($event->getStatus() == 'confirmed') { 
 463                                                         $googleCalendar->events
->delete($token['calendar'], $event->getId()); 
 465                                                 } catch(\Google\Service\Exception 
$e) { 
 467                                                         //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors 
 468                                                         echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n"; 
 469                                                         echo $e->getTraceAsString()."\n"; 
 472                                                         return self
::FAILURE
; 
 480                 return self
::SUCCESS
; 
 484          * Return the bundle alias 
 488         public function getAlias(): string {