]> Raphaël G. Git Repositories - airbundle/blob - Command/CalendarCommand.php
Remove location short
[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
128 //Check expired token
129 foreach($calendars as $clientId => $client) {
130 //Get google client
131 $googleClient = new \Google\Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
132
133 //Iterate on each tokens
134 foreach($client['tokens'] as $tokenId => $token) {
135 //Set token
136 $googleClient->setAccessToken(
137 [
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']
144 ]
145 );
146
147 //With expired token
148 if ($exp = $googleClient->isAccessTokenExpired()) {
149 //Refresh token
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']
160 ];
161
162 //Remove old token
163 unset($calendars[$clientId]['tokens'][$tokenId]);
164 } else {
165 //Drop token
166 unset($calendars[$clientId]['tokens'][$tokenId]);
167
168 //Without tokens
169 if (empty($calendars[$clientId]['tokens'])) {
170 //Drop client
171 unset($calendars[$clientId]);
172 }
173
174 //Save calendars
175 $cacheCalendars->set($calendars);
176
177 //Save calendar
178 $cache->save($cacheCalendars);
179
180 //Drop token and report
181 //XXX: submit app to avoid expiration
182 //XXX: see https://console.cloud.google.com/apis/credentials/consent?project=calendar-317315
183 echo 'Token '.$tokenId.' for calendar '.$token['calendar'].' has expired and is not refreshable'."\n";
184
185 //Return failure
186 //XXX: we want that mail and stop here
187 return self::FAILURE;
188 }
189 }
190 }
191 }
192
193 //Save calendars
194 $cacheCalendars->set($calendars);
195
196 //Save calendar
197 $cache->save($cacheCalendars);
198
199 //Iterate on each calendar client
200 foreach($calendars as $clientId => $client) {
201 //Get google client
202 $googleClient = new \Google\Client(['application_name' => $client['project'], 'client_id' => $clientId, 'client_secret' => $client['secret'], 'redirect_uri' => $client['redirect']]);
203
204 //Iterate on each tokens
205 foreach($client['tokens'] as $tokenId => $token) {
206 //Set token
207 $googleClient->setAccessToken(
208 [
209 'access_token' => $tokenId,
210 'refresh_token' => $token['refresh'],
211 'expires_in' => $token['expire'],
212 'scope' => $token['scope'],
213 'token_type' => $token['type'],
214 'created' => $token['created']
215 ]
216 );
217
218 //With expired token
219 if ($exp = $googleClient->isAccessTokenExpired()) {
220 //Last chance to skip this run
221 continue;
222 }
223
224 //Get google calendar
225 $googleCalendar = new \Google\Service\Calendar($googleClient);
226
227 //Retrieve calendar
228 try {
229 $calendar = $googleCalendar->calendars->get($token['calendar']);
230 //Catch exception
231 } catch(\Google\Service\Exception $e) {
232 //Display exception
233 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
234 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
235 echo $e->getTraceAsString()."\n";
236
237 //Return failure
238 return self::FAILURE;
239 }
240
241 //Init events
242 $events = [];
243
244 //Set filters
245 $filters = [
246 //XXX: show even deleted event to be able to update them
247 'showDeleted' => true,
248 //TODO: fetch events one day before and one day after to avoid triggering double insert duplicate key 409 errors :=) on google
249 'timeMin' => $period->getStartDate()->format(\DateTime::ISO8601),
250 'timeMax' => $period->getEndDate()->format(\DateTime::ISO8601)
251 /*, 'iCalUID' => 'airlibre/?????'*//*'orderBy' => 'startTime', */
252 ];
253
254 //Retrieve event collection
255 $googleEvents = $googleCalendar->events->listEvents($token['calendar'], $filters);
256
257 //Iterate until reached end
258 while (true) {
259 //Iterate on each event
260 foreach ($googleEvents->getItems() as $event) {
261 //Store event by id
262 if (preg_match('/^'.$token['prefix'].'([0-9]+)$/', $id = $event->getId(), $matches)) {
263 $events[$matches[1]] = $event;
264 //XXX: 3rd party events with id not matching prefix are skipped
265 #} else {
266 # echo 'Skipping '.$event->getId().':'.$event->getSummary()."\n";*/
267 }
268 }
269
270 //Get page token
271 $pageToken = $googleEvents->getNextPageToken();
272
273 //Handle next page
274 if ($pageToken) {
275 //Replace collection with next one
276 $googleEvents = $service->events->listEvents($token['calendar'], $filters+['pageToken' => $pageToken]);
277 } else {
278 break;
279 }
280 }
281
282 //Iterate on each session to sync
283 foreach($sessions as $sessionId => $session) {
284 //Init shared properties
285 //TODO: validate for constraints here ??? https://developers.google.com/calendar/api/guides/extended-properties
286 //TODO: drop shared as unused ???
287 $shared = [
288 'gps' => $session['l_latitude'].','.$session['l_longitude']
289 ];
290
291 //Init source
292 $source = [
293 'title' => $this->translator->trans('Session %id% by %pseudonym%', ['%id%' => $sessionId, '%pseudonym%' => $session['au_pseudonym']]).' '.$this->translator->trans('at '.$session['l_title']),
294 'url' => $this->router->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface::ABSOLUTE_URL)
295 ];
296
297 //Init description
298 $description = 'Description :'."\n".strip_tags(preg_replace('!<a href="([^"]+)"(?: title="[^"]+")?'.'>([^<]+)</a>!', '\1', $markdown->convert(strip_tags($session['p_description']))));
299 $shared['description'] = $markdown->convert(strip_tags($session['p_description']));
300
301 //Add class when available
302 if (!empty($session['p_class'])) {
303 $shared['class'] = $session['p_class'];
304 $description .= "\n\n".'Classe :'."\n".$session['p_class'];
305 }
306
307 //Add contact when available
308 if (!empty($session['p_contact'])) {
309 $shared['contact'] = $session['p_contact'];
310 $description .= "\n\n".'Contact :'."\n".$session['p_contact'];
311 }
312
313 //Add donate when available
314 if (!empty($session['p_donate'])) {
315 $shared['donate'] = $session['p_donate'];
316 $description .= "\n\n".'Contribuer :'."\n".$session['p_donate'];
317 }
318
319 //Add link when available
320 if (!empty($session['p_link'])) {
321 $shared['link'] = $session['p_link'];
322 $description .= "\n\n".'Site :'."\n".$session['p_link'];
323 }
324
325 //Add profile when available
326 if (!empty($session['p_profile'])) {
327 $shared['profile'] = $session['p_profile'];
328 $description .= "\n\n".'Réseau social :'."\n".$session['p_profile'];
329 }
330
331 //Locked session
332 if (!empty($session['locked']) && $events[$sessionId]) {
333 //With events
334 if (!empty($event = $events[$sessionId])) {
335 try {
336 //Delete the event
337 $googleCalendar->events->delete($token['calendar'], $event->getId());
338 //Catch exception
339 } catch(\Google\Service\Exception $e) {
340 //Display exception
341 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
342 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
343 echo $e->getTraceAsString()."\n";
344
345 //Return failure
346 return self::FAILURE;
347 }
348 }
349 //Without event
350 } elseif (empty($events[$sessionId])) {
351 //Init event
352 $event = new \Google\Service\Calendar\Event(
353 [
354 //TODO: replace 'airlibre' with $this->config['calendar']['prefix'] when possible with prefix validating [a-v0-9]{5,}
355 //XXX: see https://developers.google.com/calendar/api/v3/reference/events/insert#id
356 'id' => $token['prefix'].$sessionId,
357 'summary' => $session['au_pseudonym'].' '.$this->translator->trans('at '.$session['l_title']),
358 #'description' => $markdown->convert(strip_tags($session['p_description'])),
359 'description' => $description,
360 'status' => empty($session['a_canceled'])?'confirmed':'cancelled',
361 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
362 'source' => $source,
363 'extendedProperties' => [
364 'shared' => $shared
365 ],
366 //TODO: colorId ?
367 //TODO: attendees[] ?
368 'start' => [
369 'dateTime' => $session['start']->format(\DateTime::ISO8601)
370 ],
371 'end' => [
372 'dateTime' => $session['stop']->format(\DateTime::ISO8601)
373 ]
374 ]
375 );
376
377 try {
378 //Insert the event
379 $googleCalendar->events->insert($token['calendar'], $event);
380 //Catch exception
381 } catch(\Google\Service\Exception $e) {
382 //Display exception
383 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
384 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
385 echo $e->getTraceAsString()."\n";
386
387 //Return failure
388 return self::FAILURE;
389 }
390 // With event
391 } else {
392 //Set event
393 $event = $events[$sessionId];
394
395 //With updated event
396 if ($session['updated'] >= (new \DateTime($event->getUpdated()))) {
397 //Set summary
398 $event->setSummary($session['au_pseudonym'].' '.$this->translator->trans('at '.$session['l_title']));
399
400 //Set description
401 $event->setDescription($description);
402
403 //Set status
404 $event->setStatus(empty($session['a_canceled'])?'confirmed':'cancelled');
405
406 //Set location
407 $event->setLocation(implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]));
408
409 //Get source
410 $eventSource = $event->getSource();
411
412 //Update source title
413 $eventSource->setTitle($source['title']);
414
415 //Update source url
416 $eventSource->setUrl($source['url']);
417
418 //Set source
419 #$event->setSource($source);
420
421 //Get extended properties
422 $extendedProperties = $event->getExtendedProperties();
423
424 //Update shared
425 $extendedProperties->setShared($shared);
426
427 //TODO: colorId ?
428 //TODO: attendees[] ?
429
430 //Set start
431 $start = $event->getStart();
432
433 //Update start datetime
434 $start->setDateTime($session['start']->format(\DateTime::ISO8601));
435
436 //Set end
437 $end = $event->getEnd();
438
439 //Update stop datetime
440 $end->setDateTime($session['stop']->format(\DateTime::ISO8601));
441
442 try {
443 //Update the event
444 $updatedEvent = $googleCalendar->events->update($token['calendar'], $event->getId(), $event);
445 //Catch exception
446 } catch(\Google\Service\Exception $e) {
447 //Display exception
448 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
449 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
450 echo $e->getTraceAsString()."\n";
451
452 //Return failure
453 return self::FAILURE;
454 }
455 }
456
457 //Drop from events array
458 unset($events[$sessionId]);
459 }
460 }
461
462 //Remaining events to drop
463 foreach($events as $eventId => $event) {
464 //Non canceled events
465 if ($event->getStatus() == 'confirmed') {
466 try {
467 //Delete the event
468 $googleCalendar->events->delete($token['calendar'], $event->getId());
469 //Catch exception
470 } catch(\Google\Service\Exception $e) {
471 //Display exception
472 //TODO: handle codes here https://developers.google.com/calendar/api/guides/errors
473 echo 'Exception '.$e->getCode().':'.$e->getMessage().' in '.$e->getFile().' +'.$e->getLine()."\n";
474 echo $e->getTraceAsString()."\n";
475
476 //Return failure
477 return self::FAILURE;
478 }
479 }
480 }
481 }
482 }
483
484 //Return success
485 return self::SUCCESS;
486 }
487
488 /**
489 * Return the bundle alias
490 *
491 * {@inheritdoc}
492 */
493 public function getAlias(): string {
494 return 'rapsys_air';
495 }
496 }