]> Raphaël G. Git Repositories - airbundle/blob - Command/CalendarCommand.php
Fix token refresh, token cache save and cache path
[airbundle] / Command / CalendarCommand.php
1 <?php
2
3 namespace Rapsys\AirBundle\Command;
4
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;
15
16 use Rapsys\AirBundle\Entity\Session;
17
18 class CalendarCommand extends Command {
19 //Set failure constant
20 const FAILURE = 1;
21
22 ///Set success constant
23 const SUCCESS = 0;
24
25 ///Config array
26 protected $config;
27
28 /**
29 * Doctrine instance
30 *
31 * @var ManagerRegistry
32 */
33 protected $doctrine;
34
35 ///Locale
36 protected $locale;
37
38 ///Translator instance
39 protected $translator;
40
41 /**
42 * Inject doctrine, container and translator interface
43 *
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
48 */
49 public function __construct(ContainerInterface $container, ManagerRegistry $doctrine, RouterInterface $router, TranslatorInterface $translator) {
50 //Call parent constructor
51 parent::__construct();
52
53 //Retrieve config
54 $this->config = $container->getParameter($this->getAlias());
55
56 //Retrieve locale
57 $this->locale = $container->getParameter('kernel.default_locale');
58
59 //Store doctrine
60 $this->doctrine = $doctrine;
61
62 //Store router
63 $this->router = $router;
64
65 //Get router context
66 $context = $this->router->getContext();
67
68 //Set host
69 $context->setHost('airlibre.eu');
70
71 //Set scheme
72 $context->setScheme('https');
73
74 //Set the translator
75 $this->translator = $translator;
76 }
77
78 ///Configure attribute command
79 protected function configure() {
80 //Configure the class
81 $this
82 //Set name
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');
88 }
89
90 ///Process the attribution
91 protected function execute(InputInterface $input, OutputInterface $output) {
92 //Compute period
93 $period = new \DatePeriod(
94 //Start from last week
95 new \DateTime('-1 week'),
96 //Iterate on each day
97 new \DateInterval('P1D'),
98 //End with next 2 week
99 new \DateTime('+2 week')
100 );
101
102 //Retrieve events to update
103 $sessions = $this->doctrine->getRepository(Session::class)->fetchAllByDatePeriod($period, $this->locale);
104
105 //Markdown converted instance
106 $markdown = new DefaultMarkdown;
107
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']);
112
113 //Retrieve calendars
114 $cacheCalendars = $cache->getItem('calendars');
115
116 //Without calendars
117 if (!$cacheCalendars->isHit()) {
118 //Return failure
119 return self::FAILURE;
120 }
121
122 //Retrieve calendars
123 $calendars = $cacheCalendars->get();
124
125 //XXX: calendars content
126 #var_export($calendars);
127 #$debug = [
128 # '635317121880-usqucmne71jnmprl8br9khh2om4n8cmh.apps.googleusercontent.com' => [
129 # 'project' => 'calendar-317315',
130 # 'secret' => 'HRsKd4FIc9gxQHM4IoBWnlbD',
131 # 'redirect' => 'https://airlibre.eu/calendar/callback',
132 # 'tokens' => [
133 # 'ya29.a0ARrdaM_cNpedJ-B3irC76_0-C7cfF-WmMh0smAs4m7cSvBChnniWr-e79q0IfAbh5DSG4FlHbCMvmaYb7xX4V45PujT2U4InZmpHfspiPv-QeR4XeZJp7bLXwnw7A4M0imeeYyQcwCW7GJ8O7dGLBQlBZAvt_Q' => [
134 # 'calendar' => 'airlibre',
135 # 'expire' => 3599,
136 # 'scope' => 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events',
137 # 'type' => 'Bearer',
138 # 'created' => 1625417137,
139 # ],
140 # ],
141 # ],
142 #];
143
144 //Check expired token
145 foreach($calendars as $clientId => $client) {
146 //Get google client
147 $googleClient = new \Google\Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
148
149 //Iterate on each tokens
150 foreach($client['tokens'] as $tokenId => $token) {
151 //Set token
152 $googleClient->setAccessToken(
153 [
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']
160 ]
161 );
162
163 //With expired token
164 if ($exp = $googleClient->isAccessTokenExpired()) {
165 //Refresh token
166 if (($refreshToken = $googleClient->getRefreshToken()) && ($googleToken = $googleClient->fetchAccessTokenWithRefreshToken($refreshToken)) && empty($googleToken['error'])) {
167 //Add refreshed token
168 $calendars[$clientId]['tokens'][$googleToken['access_token']] = [
169 'calendar' => $token['calendar'],
170 'prefix' => $token['prefix'],
171 'refresh' => $googleToken['refresh_token'],
172 'expire' => $googleToken['expires_in'],
173 'scope' => $googleToken['scope'],
174 'type' => $googleToken['token_type'],
175 'created' => $googleToken['created']
176 ];
177
178 //Remove old token
179 unset($calendars[$clientId]['tokens'][$tokenId]);
180 } else {
181 //Drop token
182 unset($calendars[$clientId]['tokens'][$tokenId]);
183
184 //Without tokens
185 if (empty($calendars[$clientId]['tokens'])) {
186 //Drop client
187 unset($calendars[$clientId]);
188 }
189
190 //Save calendars
191 $cacheCalendars->set($calendars);
192
193 //Save calendar
194 $cache->save($cacheCalendars);
195
196 //Drop token and report
197 echo 'Token '.$tokenId.' for calendar '.$token['calendar'].' has expired and is not refreshable'."\n";
198
199 //Return failure
200 //XXX: we want that mail and stop here
201 return self::FAILURE;
202 }
203 }
204 }
205 }
206
207 //Save calendars
208 $cacheCalendars->set($calendars);
209
210 //Save calendar
211 $cache->save($cacheCalendars);
212
213 //Iterate on each calendar client
214 foreach($calendars as $clientId => $client) {
215 //Get google client
216 $googleClient = new \Google\Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
217
218 //Iterate on each tokens
219 foreach($client['tokens'] as $tokenId => $token) {
220 //Set token
221 $googleClient->setAccessToken(
222 [
223 'access_token' => $tokenId,
224 'refresh_token' => $token['refresh'],
225 'expires_in' => $token['expire'],
226 'scope' => $token['scope'],
227 'token_type' => $token['type'],
228 'created' => $token['created']
229 ]
230 );
231
232 //With expired token
233 if ($exp = $googleClient->isAccessTokenExpired()) {
234 //Last chance to skip this run
235 continue;
236 }
237
238 //Get google calendar
239 $googleCalendar = new \Google\Service\Calendar($googleClient);
240
241 //Retrieve calendar
242 try {
243 $calendar = $googleCalendar->calendars->get($token['calendar']);
244 //Catch exception
245 } catch(\Google\Service\Exception $e) {
246 //Display exception
247 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
248 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
249 echo $e->getTraceAsString()."\n";
250
251 //Return failure
252 return self::FAILURE;
253 }
254
255 //Init events
256 $events = [];
257
258 //Set filters
259 $filters = [
260 //XXX: show even deleted event to be able to update them
261 'showDeleted' => true,
262 //TODO: fetch events one day before and one day after to avoid triggering double insert duplicate key 409 errors :=) on google
263 'timeMin' => $period->getStartDate()->format(\DateTime::ISO8601),
264 'timeMax' => $period->getEndDate()->format(\DateTime::ISO8601)
265 /*, 'iCalUID' => 'airlibre/?????'*//*'orderBy' => 'startTime', */
266 ];
267
268 //Retrieve event collection
269 $googleEvents = $googleCalendar->events->listEvents($token['calendar'], $filters);
270
271 //Iterate until reached end
272 while (true) {
273 //Iterate on each event
274 foreach ($googleEvents->getItems() as $event) {
275 //Store event by id
276 if (preg_match('/^'.$token['prefix'].'([0-9]+)$/', $id = $event->getId(), $matches)) {
277 $events[$matches[1]] = $event;
278 //XXX: 3rd party events with id not matching prefix are skipped
279 #} else {
280 # echo 'Skipping '.$event->getId().':'.$event->getSummary()."\n";*/
281 }
282 }
283
284 //Get page token
285 $pageToken = $googleEvents->getNextPageToken();
286
287 //Handle next page
288 if ($pageToken) {
289 //Replace collection with next one
290 $googleEvents = $service->events->listEvents($token['calendar'], $filters+['pageToken' => $pageToken]);
291 } else {
292 break;
293 }
294 }
295
296 //Iterate on each session to sync
297 foreach($sessions as $sessionId => $session) {
298 //Init shared properties
299 //TODO: validate for constraints here ??? https://developers.google.com/calendar/api/guides/extended-properties
300 $shared = [
301 'gps' => $session['l_latitude'].','.$session['l_longitude']
302 ];
303
304 //Init source
305 $source = [
306 'title' => $this->translator->trans('Session %id% by %pseudonym%', ['%id%' => $sessionId, '%pseudonym%' => $session['au_pseudonym']]).' '.$this->translator->trans('at '.$session['l_title']),
307 'url' => $this->router->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface::ABSOLUTE_URL)
308 ];
309
310 //Init description
311 $description = 'Description :'."\n".strip_tags(preg_replace('!<a href="([^"]+)"(?: title="[^"]+")?'.'>([^<]+)</a>!', '\1', $markdown->convert(strip_tags($session['p_description']))));
312 $shared['description'] = $markdown->convert(strip_tags($session['p_description']));
313
314 //Add class when available
315 if (!empty($session['p_class'])) {
316 $shared['class'] = $session['p_class'];
317 $description .= "\n\n".'Classe :'."\n".$session['p_class'];
318 }
319
320 //Add contact when available
321 if (!empty($session['p_contact'])) {
322 $shared['contact'] = $session['p_contact'];
323 $description .= "\n\n".'Contact :'."\n".$session['p_contact'];
324 }
325
326 //Add donate when available
327 if (!empty($session['p_donate'])) {
328 $shared['donate'] = $session['p_donate'];
329 $description .= "\n\n".'Contribuer :'."\n".$session['p_donate'];
330 }
331
332 //Add link when available
333 if (!empty($session['p_link'])) {
334 $shared['link'] = $session['p_link'];
335 $description .= "\n\n".'Site :'."\n".$session['p_link'];
336 }
337
338 //Add profile when available
339 if (!empty($session['p_profile'])) {
340 $shared['profile'] = $session['p_profile'];
341 $description .= "\n\n".'Réseau social :'."\n".$session['p_profile'];
342 }
343
344 //Locked session
345 if (!empty($session['locked']) && $events[$sessionId]) {
346 //With events
347 if (!empty($event = $events[$sessionId])) {
348 try {
349 //Delete the event
350 $googleCalendar->events->delete($token['calendar'], $event->getId());
351 //Catch exception
352 } catch(\Google\Service\Exception $e) {
353 //Display exception
354 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
355 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
356 echo $e->getTraceAsString()."\n";
357
358 //Return failure
359 return self::FAILURE;
360 }
361 }
362 //Without event
363 } elseif (empty($events[$sessionId])) {
364 //Init event
365 $event = new \Google\Service\Calendar\Event(
366 [
367 //TODO: replace 'airlibre' with $this->config['calendar']['prefix'] when possible with prefix validating [a-v0-9]{5,}
368 //XXX: see https://developers.google.com/calendar/api/v3/reference/events/insert#id
369 'id' => $token['prefix'].$sessionId,
370 'summary' => $session['au_pseudonym'].' '.$this->translator->trans('at '.$session['l_short']),
371 #'description' => $markdown->convert(strip_tags($session['p_description'])),
372 'description' => $description,
373 'status' => empty($session['a_canceled'])?'confirmed':'cancelled',
374 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
375 'source' => $source,
376 'extendedProperties' => [
377 'shared' => $shared
378 ],
379 //TODO: colorId ?
380 //TODO: attendees[] ?
381 'start' => [
382 'dateTime' => $session['start']->format(\DateTime::ISO8601)
383 ],
384 'end' => [
385 'dateTime' => $session['stop']->format(\DateTime::ISO8601)
386 ]
387 ]
388 );
389
390 try {
391 //Insert the event
392 $googleCalendar->events->insert($token['calendar'], $event);
393 //Catch exception
394 } catch(\Google\Service\Exception $e) {
395 //Display exception
396 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
397 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
398 echo $e->getTraceAsString()."\n";
399
400 //Return failure
401 return self::FAILURE;
402 }
403 // With event
404 } else {
405 //Set event
406 $event = $events[$sessionId];
407
408 //With updated event
409 if ($session['updated'] >= (new \DateTime($event->getUpdated()))) {
410 //Set summary
411 $event->setSummary($session['au_pseudonym'].' '.$this->translator->trans('at '.$session['l_short']));
412
413 //Set description
414 $event->setDescription($description);
415
416 //Set status
417 $event->setStatus(empty($session['a_canceled'])?'confirmed':'cancelled');
418
419 //Set location
420 $event->setLocation(implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]));
421
422 //Get source
423 $eventSource = $event->getSource();
424
425 //Update source title
426 $eventSource->setTitle($source['title']);
427
428 //Update source url
429 $eventSource->setUrl($source['url']);
430
431 //Set source
432 #$event->setSource($source);
433
434 //Get extended properties
435 $extendedProperties = $event->getExtendedProperties();
436
437 //Update shared
438 $extendedProperties->setShared($shared);
439
440 //TODO: colorId ?
441 //TODO: attendees[] ?
442
443 //Set start
444 $start = $event->getStart();
445
446 //Update start datetime
447 $start->setDateTime($session['start']->format(\DateTime::ISO8601));
448
449 //Set end
450 $end = $event->getEnd();
451
452 //Update stop datetime
453 $end->setDateTime($session['stop']->format(\DateTime::ISO8601));
454
455 try {
456 //Update the event
457 $updatedEvent = $googleCalendar->events->update($token['calendar'], $event->getId(), $event);
458 //Catch exception
459 } catch(\Google\Service\Exception $e) {
460 //Display exception
461 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
462 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
463 echo $e->getTraceAsString()."\n";
464
465 //Return failure
466 return self::FAILURE;
467 }
468 }
469
470 //Drop from events array
471 unset($events[$sessionId]);
472 }
473 }
474
475 //Remaining events to drop
476 foreach($events as $eventId => $event) {
477 //Non canceled events
478 if ($event->getStatus() == 'confirmed') {
479 try {
480 //Delete the event
481 $googleCalendar->events->delete($token['calendar'], $event->getId());
482 //Catch exception
483 } catch(\Google\Service\Exception $e) {
484 //Display exception
485 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
486 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
487 echo $e->getTraceAsString()."\n";
488
489 //Return failure
490 return self::FAILURE;
491 }
492 }
493 }
494 }
495 }
496
497 //Return success
498 return self::SUCCESS;
499 }
500
501 /**
502 * Return the bundle alias
503 *
504 * {@inheritdoc}
505 */
506 public function getAlias(): string {
507 return 'rapsys_air';
508 }
509 }