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 = 'Description :'."\n".strip_tags(preg_replace('!<a href="([^"]+)"(?: title="[^"]+")?'.'>([^<]+)</a>!', '\1', $markdown->convert(strip_tags($session['p_description']))));
309 $shared['description'] = $markdown->convert(strip_tags($session['p_description']));
311 //Add class when available
312 if (!empty($session['p_class'])) {
313 $shared['class'] = $session['p_class'];
314 $description .= "\n\n".'Classe :'."\n".$session['p_class'];
317 //Add contact when available
318 if (!empty($session['p_contact'])) {
319 $shared['contact'] = $session['p_contact'];
320 $description .= "\n\n".'Contact :'."\n".$session['p_contact'];
323 //Add donate when available
324 if (!empty($session['p_donate'])) {
325 $shared['donate'] = $session['p_donate'];
326 $description .= "\n\n".'Contribuer :'."\n".$session['p_donate'];
329 //Add link when available
330 if (!empty($session['p_link'])) {
331 $shared['link'] = $session['p_link'];
332 $description .= "\n\n".'Site :'."\n".$session['p_link'];
335 //Add profile when available
336 if (!empty($session['p_profile'])) {
337 $shared['profile'] = $session['p_profile'];
338 $description .= "\n\n".'Réseau social :'."\n".$session['p_profile'];
342 if (!empty($session['locked']) && $events[$sessionId]) {
344 if (!empty($event = $events[$sessionId])) {
347 $googleCalendar->events
->delete($token['calendar'], $event->getId());
349 } catch(\Google\Service\Exception
$e) {
351 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
352 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
353 echo $e->getTraceAsString()."\n";
356 return self
::FAILURE
;
360 } elseif (empty($events[$sessionId])) {
362 $event = new \Google\Service\Calendar\
Event(
364 //TODO: replace 'airlibre' with $this->config['calendar']['prefix'] when possible with prefix validating [a-v0-9]{5,}
365 //XXX: see https://developers.google.com/calendar/api/v3/reference/events/insert#id
366 'id' => $token['prefix'].$sessionId,
367 'summary' => $session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']),
368 #'description' => $markdown->convert(strip_tags($session['p_description'])),
369 'description' => $description,
370 'status' => empty($session['a_canceled'])?'confirmed':'cancelled',
371 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
373 'extendedProperties' => [
377 //TODO: attendees[] ?
379 'dateTime' => $session['start']->format(\DateTime
::ISO8601
)
382 'dateTime' => $session['stop']->format(\DateTime
::ISO8601
)
389 $googleCalendar->events
->insert($token['calendar'], $event);
391 } catch(\Google\Service\Exception
$e) {
393 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
394 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
395 echo $e->getTraceAsString()."\n";
398 return self
::FAILURE
;
403 $event = $events[$sessionId];
406 if ($session['updated'] >= (new \
DateTime($event->getUpdated()))) {
408 $event->setSummary($session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']));
411 $event->setDescription($description);
414 $event->setStatus(empty($session['a_canceled'])?'confirmed':'cancelled');
417 $event->setLocation(implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]));
420 $eventSource = $event->getSource();
422 //Update source title
423 $eventSource->setTitle($source['title']);
426 $eventSource->setUrl($source['url']);
429 #$event->setSource($source);
431 //Get extended properties
432 $extendedProperties = $event->getExtendedProperties();
435 $extendedProperties->setShared($shared);
438 //TODO: attendees[] ?
441 $start = $event->getStart();
443 //Update start datetime
444 $start->setDateTime($session['start']->format(\DateTime
::ISO8601
));
447 $end = $event->getEnd();
449 //Update stop datetime
450 $end->setDateTime($session['stop']->format(\DateTime
::ISO8601
));
454 $updatedEvent = $googleCalendar->events
->update($token['calendar'], $event->getId(), $event);
456 } catch(\Google\Service\Exception
$e) {
458 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
459 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
460 echo $e->getTraceAsString()."\n";
463 return self
::FAILURE
;
467 //Drop from events array
468 unset($events[$sessionId]);
472 //Remaining events to drop
473 foreach($events as $eventId => $event) {
474 //Non canceled events
475 if ($event->getStatus() == 'confirmed') {
478 $googleCalendar->events
->delete($token['calendar'], $event->getId());
480 } catch(\Google\Service\Exception
$e) {
482 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
483 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
484 echo $e->getTraceAsString()."\n";
487 return self
::FAILURE
;
495 return self
::SUCCESS
;
499 * Return the bundle alias
503 public function getAlias(): string {