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