aboutsummaryrefslogtreecommitdiff
path: root/src/planner-eds.c
blob: b188392da05b26b92a2e7087cc848cd29daa989e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/*
 * Copyright 2013 Canonical Ltd.
 *
 * Authors:
 *   Charles Kerr <charles.kerr@canonical.com>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3, as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <libical/ical.h>
#include <libical/icaltime.h>
#include <libecal/libecal.h>
#include <libedataserver/libedataserver.h>

#include "planner-eds.h"

struct _IndicatorDatetimePlannerEdsPriv
{
  GSList * sources;
  GCancellable * cancellable;
  ESourceRegistry * source_registry;
};

typedef IndicatorDatetimePlannerEdsPriv priv_t;

G_DEFINE_TYPE (IndicatorDatetimePlannerEds,
               indicator_datetime_planner_eds,
               INDICATOR_TYPE_DATETIME_PLANNER)

G_DEFINE_QUARK ("source-client", source_client)

/***
****
****  my_get_appointments() helpers
****
***/

/* whole-task data that all the subtasks can see */
struct appointment_task_data
{
  /* a ref to the planner's cancellable */
  GCancellable * cancellable;

  /* how many subtasks are still running on */
  int subtask_count;

  /* the list of appointments to be returned */
  GSList * appointments;
};

static struct appointment_task_data *
appointment_task_data_new (GCancellable * cancellable)
{
  struct appointment_task_data * data;

  data = g_slice_new0 (struct appointment_task_data);
  data->cancellable = g_object_ref (cancellable);
  return data;
}

static void
appointment_task_data_free (gpointer gdata)
{
  struct appointment_task_data * data = gdata;

  g_object_unref (data->cancellable);

  g_slice_free (struct appointment_task_data, data);
}

static void
appointment_task_done (GTask * task)
{
  struct appointment_task_data * data = g_task_get_task_data (task);

  g_task_return_pointer (task, data->appointments, NULL);
  g_object_unref (task);
}

static void
appointment_task_decrement_subtasks (GTask * task)
{
  struct appointment_task_data * data = g_task_get_task_data (task);

  if (g_atomic_int_dec_and_test (&data->subtask_count))
    appointment_task_done (task);
}

static void
appointment_task_increment_subtasks (GTask * task)
{
  struct appointment_task_data * data = g_task_get_task_data (task);

  g_atomic_int_inc (&data->subtask_count);
}

/**
***  get-the-appointment's-uri subtasks
**/

struct appointment_uri_subtask_data
{
  /* The parent task */
  GTask * task;

  /* The appointment whose uri we're looking for.
     This pointer is owned by the Task and isn't reffed/unreffed by the subtask */
  struct IndicatorDatetimeAppt * appt;
};

static void
appointment_uri_subtask_done (struct appointment_uri_subtask_data * subdata)
{
  GTask * task = subdata->task;

  /* free the subtask data */
  g_slice_free (struct appointment_uri_subtask_data, subdata);

  appointment_task_decrement_subtasks (task);
}

static struct appointment_uri_subtask_data *
appointment_uri_subtask_data_new (GTask * task, struct IndicatorDatetimeAppt * appt)
{
  struct appointment_uri_subtask_data * subdata;

  appointment_task_increment_subtasks (task);

  subdata = g_slice_new0 (struct appointment_uri_subtask_data);
  subdata->task = task;
  subdata->appt = appt;
  return subdata;
}

static void
on_appointment_uris_ready (GObject      * client,
                           GAsyncResult * res,
                           gpointer       gsubdata)
{
  GSList * uris;
  GError * error;
  struct appointment_uri_subtask_data * subdata = gsubdata;

  uris = NULL;
  error = NULL;
  e_cal_client_get_attachment_uris_finish (E_CAL_CLIENT(client), res, &uris, &error);
  if (error != NULL)
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        g_warning ("Error getting appointment uris: %s", error->message);

      g_error_free (error);
    }
  else if (uris != NULL)
    {
      struct IndicatorDatetimeAppt * appt = subdata->appt;
      appt->url = g_strdup (uris->data); /* copy the first URL */
      g_debug ("found url '%s' for appointment '%s'", appt->url, appt->summary);
      e_client_util_free_string_slist (uris);
    }

  appointment_uri_subtask_done (subdata);
}

/**
***  enumerate-the-components subtasks
**/

/* data struct for the enumerate-components subtask */
struct appointment_component_subtask_data
{
  /* The parent task */
  GTask * task;

  /* The client we're walking through. The subtask owns a ref to this */
  ECalClient * client;

  /* The appointment's color coding. The subtask owns this string */
  gchar * color;
};

static void
on_appointment_component_subtask_done (gpointer gsubdata)
{
  struct appointment_component_subtask_data * subdata = gsubdata;
  GTask * task = subdata->task;

  /* free the subtask data */
  g_free (subdata->color);
  g_object_unref (subdata->client);
  g_slice_free (struct appointment_component_subtask_data, subdata);

  appointment_task_decrement_subtasks (task);
}

static struct appointment_component_subtask_data *
appointment_component_subtask_data_new (GTask * task, ECalClient * client, const gchar * color)
{
  struct appointment_component_subtask_data * subdata;

  appointment_task_increment_subtasks (task);

  subdata = g_slice_new0 (struct appointment_component_subtask_data);
  subdata->task = task;
  subdata->client = g_object_ref (client);
  subdata->color = g_strdup (color);
  return subdata;
}

static gboolean
my_get_appointments_foreach (ECalComponent * component,
                             time_t          begin,
                             time_t          end,
                             gpointer        gsubdata)
{
  const ECalComponentVType vtype = e_cal_component_get_vtype (component);
  struct appointment_component_subtask_data * subdata = gsubdata;
  struct appointment_task_data * data = g_task_get_task_data (subdata->task);

  if ((vtype == E_CAL_COMPONENT_EVENT) || (vtype == E_CAL_COMPONENT_TODO))
    {
      const gchar * uid = NULL;
      icalproperty_status status = 0;

      e_cal_component_get_uid (component, &uid);
      e_cal_component_get_status (component, &status);

      if ((uid != NULL) &&
          (status != ICAL_STATUS_COMPLETED) &&
          (status != ICAL_STATUS_CANCELLED))
        {
          GList * alarm_uids;
          GSList * l;
          GSList * recur_list;
          ECalComponentText text;
          struct IndicatorDatetimeAppt * appt;
          struct appointment_uri_subtask_data * uri_subdata;

          appt = g_slice_new0 (struct IndicatorDatetimeAppt);

          /* Determine whether this is a recurring event.
             NB: icalrecurrencetype supports complex recurrence patterns;
             however, since design only allows daily recurrence,
             that's all we support here. */
          e_cal_component_get_rrule_list (component, &recur_list);
          for (l=recur_list; l!=NULL; l=l->next)
            {
              const struct icalrecurrencetype * recur = l->data;
              appt->is_daily |= ((recur->freq == ICAL_DAILY_RECURRENCE)
                                  && (recur->interval == 1));
            }
          e_cal_component_free_recur_list (recur_list);

          text.value = "";
          e_cal_component_get_summary (component, &text);
 
          appt->begin = g_date_time_new_from_unix_local (begin);
          appt->end = g_date_time_new_from_unix_local (end);
          appt->color = g_strdup (subdata->color);
          appt->is_event = vtype == E_CAL_COMPONENT_EVENT;
          appt->summary = g_strdup (text.value);
          appt->uid = g_strdup (uid);

          alarm_uids = e_cal_component_get_alarm_uids (component);
          appt->has_alarms = alarm_uids != NULL;
          cal_obj_uid_list_free (alarm_uids);

          data->appointments = g_slist_prepend (data->appointments, appt);

          /* start a new subtask to get the associated URIs */
          uri_subdata = appointment_uri_subtask_data_new (subdata->task, appt);
          e_cal_client_get_attachment_uris (subdata->client,
                                            uid,
                                            NULL,
                                            data->cancellable,
                                            on_appointment_uris_ready,
                                            uri_subdata);
        }
    }

  return G_SOURCE_CONTINUE;
}

/***
****  IndicatorDatetimePlanner virtual funcs
***/

static void
my_get_appointments (IndicatorDatetimePlanner  * planner,
                     GDateTime                 * begin_datetime,
                     GDateTime                 * end_datetime,
                     GAsyncReadyCallback         callback,
                     gpointer                    user_data)
{
  GSList * l;
  priv_t * p;
  const char * str;
  icaltimezone * default_timezone;
  const int64_t begin = g_date_time_to_unix (begin_datetime);
  const int64_t end = g_date_time_to_unix (end_datetime);
  GTask * task;
  gboolean subtasks_added;

  p = INDICATOR_DATETIME_PLANNER_EDS (planner)->priv;

  /**
  ***  init the default timezone
  **/

  default_timezone = NULL;

  if ((str = indicator_datetime_planner_get_timezone (planner)))
    {
      default_timezone = icaltimezone_get_builtin_timezone (str);

      if (default_timezone == NULL) /* maybe str is a tzid? */
        default_timezone = icaltimezone_get_builtin_timezone_from_tzid (str);
    }

  /**
  ***  walk through the sources to build the appointment list
  **/

  task = g_task_new (planner, p->cancellable, callback, user_data);
  g_task_set_task_data (task,
                        appointment_task_data_new (p->cancellable),
                        appointment_task_data_free);

  subtasks_added = FALSE;
  for (l=p->sources; l!=NULL; l=l->next)
    {
      ESource * source;
      ECalClient * client;
      const char * color;
      struct appointment_component_subtask_data * subdata;

      source = l->data;
      client = g_object_get_qdata (l->data, source_client_quark());
      if (client == NULL)
        continue;

      if (default_timezone != NULL)
        e_cal_client_set_default_timezone (client, default_timezone);

      /* start a new subtask to enumerate all the components in this client. */
      color = e_source_selectable_get_color (e_source_get_extension (source, E_SOURCE_EXTENSION_CALENDAR));
      subdata = appointment_component_subtask_data_new (task, client, color);
      subtasks_added = TRUE;
      e_cal_client_generate_instances (client,
                                       begin,
                                       end,
                                       p->cancellable,
                                       my_get_appointments_foreach,
                                       subdata,
                                       on_appointment_component_subtask_done);
    }

  if (!subtasks_added)
    appointment_task_done (task);
}

static GSList *
my_get_appointments_finish (IndicatorDatetimePlanner  * self  G_GNUC_UNUSED,
                            GAsyncResult              * res,
                            GError                   ** error)
{
  return g_task_propagate_pointer (G_TASK(res), error);
}

gboolean
my_is_configured (IndicatorDatetimePlanner * planner)
{
  IndicatorDatetimePlannerEds * self;

  /* confirm that it's installed... */
  gchar *evo = g_find_program_in_path ("evolution");
  if (evo == NULL)
    return FALSE;

  g_debug ("found calendar app: '%s'", evo);
  g_free (evo);

  /* see if there are any calendar sources */
  self = INDICATOR_DATETIME_PLANNER_EDS (planner);
  return self->priv->sources != NULL;
}

static void
my_activate (IndicatorDatetimePlanner * self G_GNUC_UNUSED)
{
  GError * error = NULL;
  const char * const command = "evolution -c calendar";

  if (!g_spawn_command_line_async (command, &error))
    {
      g_warning ("Unable to start %s: %s", command, error->message);
      g_error_free (error);
    }
}

static void
my_activate_time (IndicatorDatetimePlanner * self G_GNUC_UNUSED,
                  GDateTime * activate_time)
{
  gchar * isodate;
  gchar * command;
  GError * err;

  isodate = g_date_time_format (activate_time, "%Y%m%d");
  command = g_strdup_printf ("evolution \"calendar:///?startdate=%s\"", isodate);
  err = 0;
  if (!g_spawn_command_line_async (command, &err))
    {
      g_warning ("Unable to start %s: %s", command, err->message);
      g_error_free (err);
    }

  g_free (command);
  g_free (isodate);
}

/***
****  Source / Client Wrangling
***/

static void
on_client_connected (GObject      * unused G_GNUC_UNUSED,
                     GAsyncResult * res,
                     gpointer       gself)
{
  GError * error;
  EClient * client;

  error = NULL;
  client = e_cal_client_connect_finish (res, &error);
  if (error != NULL)
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        g_warning ("indicator-datetime cannot connect to EDS source: %s", error->message);

      g_error_free (error);
    }
  else
    {
      /* we've got a new connected ECalClient, so store it & notify clients */

      g_object_set_qdata_full (G_OBJECT(e_client_get_source(client)),
                               source_client_quark(),
                               client,
                               g_object_unref);

      indicator_datetime_planner_emit_appointments_changed (gself);
    }
}

static void
on_source_enabled (ESourceRegistry * registry  G_GNUC_UNUSED,
                   ESource         * source,
                   gpointer          gself)
{
  IndicatorDatetimePlannerEds * self = INDICATOR_DATETIME_PLANNER_EDS (gself);
  priv_t * p = self->priv;

  e_cal_client_connect (source,
                        E_CAL_CLIENT_SOURCE_TYPE_EVENTS,
                        p->cancellable,
                        on_client_connected,
                        self);
}

static void
on_source_added (ESourceRegistry * registry,
                 ESource         * source,
                 gpointer          gself)
{
  IndicatorDatetimePlannerEds * self = INDICATOR_DATETIME_PLANNER_EDS (gself);
  priv_t * p = self->priv;

  p->sources = g_slist_prepend (p->sources, g_object_ref(source));

  if (e_source_get_enabled (source))
    on_source_enabled (registry, source, gself);
}

static void
on_source_disabled (ESourceRegistry * registry  G_GNUC_UNUSED,
                    ESource         * source,
                    gpointer          gself)
{
  ECalClient * client;

  /* If this source has a connected ECalClient, remove it & notify clients */
  if ((client = g_object_steal_qdata (G_OBJECT(source), source_client_quark())))
    {
      g_object_unref (client);
      indicator_datetime_planner_emit_appointments_changed (gself);
    }
}

static void
on_source_removed (ESourceRegistry * registry,
                   ESource         * source,
                   gpointer          gself)
{
  IndicatorDatetimePlannerEds * self = INDICATOR_DATETIME_PLANNER_EDS (gself);
  priv_t * p = self->priv;

  on_source_disabled (registry, source, gself);

  p->sources = g_slist_remove (p->sources, source);
  g_object_unref (source);
}

static void
on_source_changed (ESourceRegistry * registry  G_GNUC_UNUSED,
                   ESource         * source    G_GNUC_UNUSED,
                   gpointer          gself)
{
  indicator_datetime_planner_emit_appointments_changed (gself);
}

static void
on_source_registry_ready (GObject      * source_object  G_GNUC_UNUSED,
                          GAsyncResult * res,
                          gpointer       gself)
{
  GError * error;
  ESourceRegistry * r;

  error = NULL;
  r = e_source_registry_new_finish (res, &error);
  if (error != NULL)
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        g_warning ("indicator-datetime cannot show EDS appointments: %s", error->message);

      g_error_free (error);
    }
  else
    {
      IndicatorDatetimePlannerEds * self;
      priv_t * p;
      GList * l;
      GList * sources;

      self = INDICATOR_DATETIME_PLANNER_EDS (gself);
      p = self->priv;

      g_signal_connect (r, "source-added",    G_CALLBACK(on_source_added), self);
      g_signal_connect (r, "source-removed",  G_CALLBACK(on_source_removed), self);
      g_signal_connect (r, "source-changed",  G_CALLBACK(on_source_changed), self);
      g_signal_connect (r, "source-disabled", G_CALLBACK(on_source_disabled), self);
      g_signal_connect (r, "source-enabled",  G_CALLBACK(on_source_enabled), self);

      p->source_registry = r;

      sources = e_source_registry_list_sources (r, E_SOURCE_EXTENSION_CALENDAR);
      for (l=sources; l!=NULL; l=l->next)
        on_source_added (r, l->data, self);
      g_list_free_full (sources, g_object_unref);
    }
}

/***
****  GObject virtual funcs
***/

static void
my_dispose (GObject * o)
{
  IndicatorDatetimePlannerEds * self = INDICATOR_DATETIME_PLANNER_EDS (o);
  priv_t * p = self->priv;

  if (p->cancellable != NULL)
    {
      g_cancellable_cancel (p->cancellable);
      g_clear_object (&p->cancellable);
    }

  if (p->source_registry != NULL)
    {
      g_signal_handlers_disconnect_by_func (p->source_registry,
                                            indicator_datetime_planner_emit_appointments_changed,
                                            self);

      g_clear_object (&self->priv->source_registry);
    }

  G_OBJECT_CLASS (indicator_datetime_planner_eds_parent_class)->dispose (o);
}

/***
****  Instantiation
***/

static void
indicator_datetime_planner_eds_class_init (IndicatorDatetimePlannerEdsClass * klass)
{
  GObjectClass * object_class;
  IndicatorDatetimePlannerClass * planner_class;

  object_class = G_OBJECT_CLASS (klass);
  object_class->dispose = my_dispose;

  planner_class = INDICATOR_DATETIME_PLANNER_CLASS (klass);
  planner_class->is_configured = my_is_configured;
  planner_class->activate = my_activate;
  planner_class->activate_time = my_activate_time;
  planner_class->get_appointments = my_get_appointments;
  planner_class->get_appointments_finish = my_get_appointments_finish;

  g_type_class_add_private (klass, sizeof (IndicatorDatetimePlannerEdsPriv));
}

static void
indicator_datetime_planner_eds_init (IndicatorDatetimePlannerEds * self)
{
  priv_t * p;

  p = G_TYPE_INSTANCE_GET_PRIVATE (self,
                                   INDICATOR_TYPE_DATETIME_PLANNER_EDS,
                                   IndicatorDatetimePlannerEdsPriv);

  self->priv = p;

  p->cancellable = g_cancellable_new ();

  e_source_registry_new (p->cancellable,
                         on_source_registry_ready,
                         self);
}

/***
****  Public
***/

IndicatorDatetimePlanner *
indicator_datetime_planner_eds_new (void)
{
  gpointer o = g_object_new (INDICATOR_TYPE_DATETIME_PLANNER_EDS, NULL);

  return INDICATOR_DATETIME_PLANNER (o);
}