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