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 //XXX: calendars content
126 #var_export($calendars);
128 //Check expired token
129 foreach($calendars as $clientId => $client) {
131 $googleClient = new \Google\
Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
133 //Iterate on each tokens
134 foreach($client['tokens'] as $tokenId => $token) {
136 $googleClient->setAccessToken(
138 'access_token' => $tokenId,
139 'refresh_token' => $token['refresh'],
140 'expires_in' => $token['expire'],
141 'scope' => $token['scope'],
142 'token_type' => $token['type'],
143 'created' => $token['created']
148 if ($exp = $googleClient->isAccessTokenExpired()) {
150 if (($refreshToken = $googleClient->getRefreshToken()) && ($googleToken = $googleClient->fetchAccessTokenWithRefreshToken($refreshToken)) && empty($googleToken['error'])) {
151 //Add refreshed token
152 $calendars[$clientId]['tokens'][$googleToken['access_token']] = [
153 'calendar' => $token['calendar'],
154 'prefix' => $token['prefix'],
155 'refresh' => $googleToken['refresh_token'],
156 'expire' => $googleToken['expires_in'],
157 'scope' => $googleToken['scope'],
158 'type' => $googleToken['token_type'],
159 'created' => $googleToken['created']
163 unset($calendars[$clientId]['tokens'][$tokenId]);
166 unset($calendars[$clientId]['tokens'][$tokenId]);
169 if (empty($calendars[$clientId]['tokens'])) {
171 unset($calendars[$clientId]);
175 $cacheCalendars->set($calendars);
178 $cache->save($cacheCalendars);
180 //Drop token and report
181 echo 'Token '.$tokenId.' for calendar '.$token['calendar'].' has expired and is not refreshable'."\n";
184 //XXX: we want that mail and stop here
185 return self
::FAILURE
;
192 $cacheCalendars->set($calendars);
195 $cache->save($cacheCalendars);
197 //Iterate on each calendar client
198 foreach($calendars as $clientId => $client) {
200 $googleClient = new \Google\
Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
202 //Iterate on each tokens
203 foreach($client['tokens'] as $tokenId => $token) {
205 $googleClient->setAccessToken(
207 'access_token' => $tokenId,
208 'refresh_token' => $token['refresh'],
209 'expires_in' => $token['expire'],
210 'scope' => $token['scope'],
211 'token_type' => $token['type'],
212 'created' => $token['created']
217 if ($exp = $googleClient->isAccessTokenExpired()) {
218 //Last chance to skip this run
222 //Get google calendar
223 $googleCalendar = new \Google\Service\
Calendar($googleClient);
227 $calendar = $googleCalendar->calendars
->get($token['calendar']);
229 } catch(\Google\Service\Exception
$e) {
231 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
232 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
233 echo $e->getTraceAsString()."\n";
236 return self
::FAILURE
;
244 //XXX: show even deleted event to be able to update them
245 'showDeleted' => true,
246 //TODO: fetch events one day before and one day after to avoid triggering double insert duplicate key 409 errors :=) on google
247 'timeMin' => $period->getStartDate()->format(\DateTime
::ISO8601
),
248 'timeMax' => $period->getEndDate()->format(\DateTime
::ISO8601
)
249 /*, 'iCalUID' => 'airlibre/?????'*//*'orderBy' => 'startTime', */
252 //Retrieve event collection
253 $googleEvents = $googleCalendar->events
->listEvents($token['calendar'], $filters);
255 //Iterate until reached end
257 //Iterate on each event
258 foreach ($googleEvents->getItems() as $event) {
260 if (preg_match('/^'.$token['prefix'].'([0-9]+)$/', $id = $event->getId(), $matches)) {
261 $events[$matches[1]] = $event;
262 //XXX: 3rd party events with id not matching prefix are skipped
264 # echo 'Skipping '.$event->getId().':'.$event->getSummary()."\n";*/
269 $pageToken = $googleEvents->getNextPageToken();
273 //Replace collection with next one
274 $googleEvents = $service->events
->listEvents($token['calendar'], $filters+
['pageToken' => $pageToken]);
280 //Iterate on each session to sync
281 foreach($sessions as $sessionId => $session) {
282 //Init shared properties
283 //TODO: validate for constraints here ??? https://developers.google.com/calendar/api/guides/extended-properties
285 'gps' => $session['l_latitude'].','.$session['l_longitude']
290 'title' => $this->translator
->trans('Session %id% by %pseudonym%', ['%id%' => $sessionId, '%pseudonym%' => $session['au_pseudonym']]).' '.$this->translator
->trans('at '.$session['l_title']),
291 'url' => $this->router
->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface
::ABSOLUTE_URL
)
295 $description = 'Description :'."\n".strip_tags(preg_replace('!<a href="([^"]+)"(?: title="[^"]+")?'.'>([^<]+)</a>!', '\1', $markdown->convert(strip_tags($session['p_description']))));
296 $shared['description'] = $markdown->convert(strip_tags($session['p_description']));
298 //Add class when available
299 if (!empty($session['p_class'])) {
300 $shared['class'] = $session['p_class'];
301 $description .= "\n\n".'Classe :'."\n".$session['p_class'];
304 //Add contact when available
305 if (!empty($session['p_contact'])) {
306 $shared['contact'] = $session['p_contact'];
307 $description .= "\n\n".'Contact :'."\n".$session['p_contact'];
310 //Add donate when available
311 if (!empty($session['p_donate'])) {
312 $shared['donate'] = $session['p_donate'];
313 $description .= "\n\n".'Contribuer :'."\n".$session['p_donate'];
316 //Add link when available
317 if (!empty($session['p_link'])) {
318 $shared['link'] = $session['p_link'];
319 $description .= "\n\n".'Site :'."\n".$session['p_link'];
322 //Add profile when available
323 if (!empty($session['p_profile'])) {
324 $shared['profile'] = $session['p_profile'];
325 $description .= "\n\n".'Réseau social :'."\n".$session['p_profile'];
329 if (!empty($session['locked']) && $events[$sessionId]) {
331 if (!empty($event = $events[$sessionId])) {
334 $googleCalendar->events
->delete($token['calendar'], $event->getId());
336 } catch(\Google\Service\Exception
$e) {
338 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
339 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
340 echo $e->getTraceAsString()."\n";
343 return self
::FAILURE
;
347 } elseif (empty($events[$sessionId])) {
349 $event = new \Google\Service\Calendar\
Event(
351 //TODO: replace 'airlibre' with $this->config['calendar']['prefix'] when possible with prefix validating [a-v0-9]{5,}
352 //XXX: see https://developers.google.com/calendar/api/v3/reference/events/insert#id
353 'id' => $token['prefix'].$sessionId,
354 'summary' => $session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']),
355 #'description' => $markdown->convert(strip_tags($session['p_description'])),
356 'description' => $description,
357 'status' => empty($session['a_canceled'])?'confirmed':'cancelled',
358 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
360 'extendedProperties' => [
364 //TODO: attendees[] ?
366 'dateTime' => $session['start']->format(\DateTime
::ISO8601
)
369 'dateTime' => $session['stop']->format(\DateTime
::ISO8601
)
376 $googleCalendar->events
->insert($token['calendar'], $event);
378 } catch(\Google\Service\Exception
$e) {
380 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
381 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
382 echo $e->getTraceAsString()."\n";
385 return self
::FAILURE
;
390 $event = $events[$sessionId];
393 if ($session['updated'] >= (new \
DateTime($event->getUpdated()))) {
395 $event->setSummary($session['au_pseudonym'].' '.$this->translator
->trans('at '.$session['l_short']));
398 $event->setDescription($description);
401 $event->setStatus(empty($session['a_canceled'])?'confirmed':'cancelled');
404 $event->setLocation(implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]));
407 $eventSource = $event->getSource();
409 //Update source title
410 $eventSource->setTitle($source['title']);
413 $eventSource->setUrl($source['url']);
416 #$event->setSource($source);
418 //Get extended properties
419 $extendedProperties = $event->getExtendedProperties();
422 $extendedProperties->setShared($shared);
425 //TODO: attendees[] ?
428 $start = $event->getStart();
430 //Update start datetime
431 $start->setDateTime($session['start']->format(\DateTime
::ISO8601
));
434 $end = $event->getEnd();
436 //Update stop datetime
437 $end->setDateTime($session['stop']->format(\DateTime
::ISO8601
));
441 $updatedEvent = $googleCalendar->events
->update($token['calendar'], $event->getId(), $event);
443 } catch(\Google\Service\Exception
$e) {
445 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
446 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
447 echo $e->getTraceAsString()."\n";
450 return self
::FAILURE
;
454 //Drop from events array
455 unset($events[$sessionId]);
459 //Remaining events to drop
460 foreach($events as $eventId => $event) {
461 //Non canceled events
462 if ($event->getStatus() == 'confirmed') {
465 $googleCalendar->events
->delete($token['calendar'], $event->getId());
467 } catch(\Google\Service\Exception
$e) {
469 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
470 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
471 echo $e->getTraceAsString()."\n";
474 return self
::FAILURE
;
482 return self
::SUCCESS
;
486 * Return the bundle alias
490 public function getAlias(): string {