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
['cache']['directory']);
114 $cacheCalendars = $cache->getItem('calendars');
117 if (!$cacheCalendars->isHit()) {
119 return self
::FAILURE
;
123 $calendars = $cacheCalendars->get();
125 //XXX: calendars content
126 #var_export($calendars);
128 # '635317121880-usqucmne71jnmprl8br9khh2om4n8cmh.apps.googleusercontent.com' => [
129 # 'project' => 'calendar-317315',
130 # 'secret' => 'HRsKd4FIc9gxQHM4IoBWnlbD',
131 # 'redirect' => 'https://airlibre.eu/calendar/callback',
133 # 'ya29.a0ARrdaM_cNpedJ-B3irC76_0-C7cfF-WmMh0smAs4m7cSvBChnniWr-e79q0IfAbh5DSG4FlHbCMvmaYb7xX4V45PujT2U4InZmpHfspiPv-QeR4XeZJp7bLXwnw7A4M0imeeYyQcwCW7GJ8O7dGLBQlBZAvt_Q' => [
134 # 'calendar' => 'airlibre',
136 # 'scope' => 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events',
137 # 'type' => 'Bearer',
138 # 'created' => 1625417137,
144 //Check expired token
145 foreach($calendars as $clientId => $client) {
147 $googleClient = new \Google\
Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
149 //Iterate on each tokens
150 foreach($client['tokens'] as $tokenId => $token) {
152 $googleClient->setAccessToken(
154 'access_token' => $tokenId,
155 'refresh_token' => $token['refresh'],
156 'expires_in' => $token['expire'],
157 'scope' => $token['scope'],
158 'token_type' => $token['type'],
159 'created' => $token['created']
164 if ($exp = $googleClient->isAccessTokenExpired()) {
166 if ($googleClient->getRefreshToken()) {
167 //Retrieve refreshed token
168 $googleToken = $googleClient->fetchAccessTokenWithRefreshToken($googleClient->getRefreshToken());
170 //Add refreshed token
171 $calendars[$clientId]['tokens'][$googleToken['access_token']] = [
172 'calendar' => $token['calendar'],
173 'prefix' => $token['prefix'],
174 'refresh' => $googleToken['refresh_token'],
175 'expire' => $googleToken['expires_in'],
176 'scope' => $googleToken['scope'],
177 'type' => $googleToken['token_type'],
178 'created' => $googleToken['created']
182 unset($calendars[$clientId]['tokens'][$tokenId]);
185 unset($calendars[$clientId]['tokens'][$tokenId]);
188 if (empty($calendars[$clientId]['tokens'])) {
190 unset($calendars[$clientId]);
193 //Drop token and report
194 echo 'Token '.$tokenId.' for calendar '.$token['calendar'].' has expired and is not refreshable'."\n";
197 //XXX: we want that mail and stop here
198 return self
::FAILURE
;
205 $cacheCalendars->set($calendars);
208 $cache->save($cacheCalendars);
210 //Iterate on each calendar client
211 foreach($calendars as $clientId => $client) {
213 $googleClient = new \Google\
Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
215 //Iterate on each tokens
216 foreach($client['tokens'] as $tokenId => $token) {
218 $googleClient->setAccessToken(
220 'access_token' => $tokenId,
221 'refresh_token' => $token['refresh'],
222 'expires_in' => $token['expire'],
223 'scope' => $token['scope'],
224 'token_type' => $token['type'],
225 'created' => $token['created']
230 if ($exp = $googleClient->isAccessTokenExpired()) {
231 //Last chance to skip this run
235 //Get google calendar
236 $googleCalendar = new \Google\Service\
Calendar($googleClient);
240 $calendar = $googleCalendar->calendars
->get($token['calendar']);
242 } catch(\Google\Service\Exception
$e) {
244 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
245 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
246 echo $e->getTraceAsString()."\n";
249 return self
::FAILURE
;
257 //XXX: show even deleted event to be able to update them
258 'showDeleted' => true,
259 //TODO: fetch events one day before and one day after to avoid triggering double insert duplicate key 409 errors :=) on google
260 'timeMin' => $period->getStartDate()->format(\DateTime
::ISO8601
),
261 'timeMax' => $period->getEndDate()->format(\DateTime
::ISO8601
)
262 /*, 'iCalUID' => 'airlibre/?????'*//*'orderBy' => 'startTime', */
265 //Retrieve event collection
266 $googleEvents = $googleCalendar->events
->listEvents($token['calendar'], $filters);
268 //Iterate until reached end
270 //Iterate on each event
271 foreach ($googleEvents->getItems() as $event) {
273 if (preg_match('/^'.$token['prefix'].'([0-9]+)$/', $id = $event->getId(), $matches)) {
274 $events[$matches[1]] = $event;
275 //XXX: 3rd party events with id not matching prefix are skipped
277 # echo 'Skipping '.$event->getId().':'.$event->getSummary()."\n";*/
282 $pageToken = $googleEvents->getNextPageToken();
286 //Replace collection with next one
287 $googleEvents = $service->events
->listEvents($token['calendar'], $filters+
['pageToken' => $pageToken]);
293 //Iterate on each session to sync
294 foreach($sessions as $sessionId => $session) {
295 //Init shared properties
296 //TODO: validate for constraints here ??? https://developers.google.com/calendar/api/guides/extended-properties
298 'gps' => $session['l_latitude'].','.$session['l_longitude']
303 'title' => $this->translator
->trans('Session %id% by %pseudonym%', ['%id%' => $sessionId, '%pseudonym%' => $session['au_pseudonym']]).' '.$this->translator
->trans('at '.$session['l_title']),
304 'url' => $this->router
->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface
::ABSOLUTE_URL
)
308 #$description = '<dl><dt>Description</dt><dd>'.$markdown->convert(strip_tags(str_replace(["\r", "\n\n"], ['', "\n"], $session['p_description']))).'</dd></dl>';
309 $description = '<dl><dt>Description</dt><dd>'.$markdown->convert(strip_tags($session['p_description'])).'</dd></dl>';
311 //Add class when available
312 if (!empty($session['p_class'])) {
313 $shared['class'] = $session['p_class'];
314 #$description .= '<dl><dt>Classe</dt><dd>'.$markdown->convert(strip_tags(str_replace(["\r", "\n\n"], ['', "\n"], $session['p_class']))).'</dd></dl>';
315 $description .= '<dl><dt>Classe</dt><dd><p>'.$session['p_class'].'</p></dd></dl>';
318 //Add contact when available
319 if (!empty($session['p_contact'])) {
320 $shared['contact'] = $session['p_contact'];
321 $description .= '<dl><dt>Contacter</dt><dd><p>'.$session['p_contact'].'</p></dd></dl>';
324 //Add donate when available
325 if (!empty($session['p_donate'])) {
326 $shared['donate'] = $session['p_donate'];
327 $description .= '<dl><dt>Contribuer</dt><dd><p>'.$session['p_donate'].'</p></dd></dl>';
330 //Add link when available
331 if (!empty($session['p_link'])) {
332 $shared['link'] = $session['p_link'];
333 $description .= '<dl><dt>Site</dt><dd><p>'.$session['p_link'].'</p></dd></dl>';
336 //Add profile when available
337 if (!empty($session['p_profile'])) {
338 $shared['profile'] = $session['p_profile'];
339 $description .= '<dl><dt>Réseau social</dt><dd><p>'.$session['p_profile'].'</p></dd></dl>';
343 if (!empty($session['locked']) && $events[$sessionId]) {
345 if (!empty($event = $events[$sessionId])) {
348 $googleCalendar->events
->delete($token['calendar'], $event->getId());
350 } catch(\Google\Service\Exception
$e) {
352 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
353 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
354 echo $e->getTraceAsString()."\n";
357 return self
::FAILURE
;
361 } elseif (empty($events[$sessionId])) {
363 $event = new \Google\Service\Calendar\
Event(
365 //TODO: replace 'airlibre' with $this->config['calendar']['prefix'] when possible with prefix validating [a-v0-9]{5,}
366 //XXX: see https://developers.google.com/calendar/api/v3/reference/events/insert#id
367 'id' => $token['prefix'].$sessionId,
368 'summary' => $session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']),
369 #'description' => $markdown->convert(strip_tags($session['p_description'])),
370 'description' => $description,
371 'status' => empty($session['a_canceled'])?'confirmed':'cancelled',
372 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
374 'extendedProperties' => [
378 //TODO: attendees[] ?
380 'dateTime' => $session['start']->format(\DateTime
::ISO8601
)
383 'dateTime' => $session['stop']->format(\DateTime
::ISO8601
)
390 $googleCalendar->events
->insert($token['calendar'], $event);
392 } catch(\Google\Service\Exception
$e) {
394 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
395 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
396 echo $e->getTraceAsString()."\n";
399 return self
::FAILURE
;
404 $event = $events[$sessionId];
407 #if ($session['updated'] >= (new \DateTime($event->getUpdated()))) {
410 $event->setSummary($session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']));
413 $event->setDescription($description);
416 $event->setStatus(empty($session['a_canceled'])?'confirmed':'cancelled');
419 $event->setLocation(implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]));
422 $eventSource = $event->getSource();
424 //Update source title
425 $eventSource->setTitle($source['title']);
428 $eventSource->setUrl($source['url']);
431 #$event->setSource($source);
433 //Get extended properties
434 $extendedProperties = $event->getExtendedProperties();
437 $extendedProperties->setShared($shared);
440 //TODO: attendees[] ?
443 $start = $event->getStart();
445 //Update start datetime
446 $start->setDateTime($session['start']->format(\DateTime
::ISO8601
));
449 $end = $event->getEnd();
451 //Update stop datetime
452 $end->setDateTime($session['stop']->format(\DateTime
::ISO8601
));
456 $updatedEvent = $googleCalendar->events
->update($token['calendar'], $event->getId(), $event);
458 } catch(\Google\Service\Exception
$e) {
460 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
461 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
462 echo $e->getTraceAsString()."\n";
465 return self
::FAILURE
;
469 //Drop from events array
470 unset($events[$sessionId]);
474 //Remaining events to drop
475 foreach($events as $eventId => $event) {
476 //Non canceled events
477 if ($event->getStatus() == 'confirmed') {
480 $googleCalendar->events
->delete($token['calendar'], $event->getId());
482 } catch(\Google\Service\Exception
$e) {
484 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
485 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
486 echo $e->getTraceAsString()."\n";
489 return self
::FAILURE
;
497 return self
::SUCCESS
;
501 * Return the bundle alias
505 public function getAlias(): string {