e916ac0f01d96459a84ee6b9f7e33868fe72ae80
[asterisk/asterisk.git] / res / res_calendar.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008 - 2009, Digium, Inc.
5  *
6  * Terry Wilson <twilson@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  * \brief Calendaring API
21  * 
22  * \todo Support responding to a meeting invite
23  * \todo Support writing attendees
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31 #include "asterisk/calendar.h"
32 #include "asterisk/utils.h"
33 #include "asterisk/astobj2.h"
34 #include "asterisk/module.h"
35 #include "asterisk/config.h"
36 #include "asterisk/channel.h"
37 #include "asterisk/devicestate.h"
38 #include "asterisk/linkedlists.h"
39 #include "asterisk/sched.h"
40 #include "asterisk/dial.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/app.h"
44
45 /*** DOCUMENTATION
46         <function name="CALENDAR_BUSY" language="en_US">
47                 <synopsis>
48                         Determine if the calendar is marked busy at this time.
49                 </synopsis>
50                 <syntax>
51                         <parameter name="calendar" required="true" />
52                 </syntax>
53         <description>
54                         <para>Check the specified calendar's current busy status.</para>
55                 </description>
56         </function>
57         <function name="CALENDAR_EVENT" language="en_US">
58                 <synopsis>
59                         Get calendar event notification data from a notification call.
60                 </synopsis>
61                 <syntax>
62                         <parameter name="field" required="true">
63                                 <enumlist>
64                                         <enum name="summary"><para>The VEVENT SUMMARY property or Exchange event 'subject'</para></enum>
65                                         <enum name="description"><para>The text description of the event</para></enum>
66                                         <enum name="organizer"><para>The organizer of the event</para></enum>
67                                         <enum name="location"><para>The location of the eventt</para></enum>
68                                         <enum name="calendar"><para>The name of the calendar associated with the event</para></enum>
69                                         <enum name="uid"><para>The unique identifier for this event</para></enum>
70                                         <enum name="start"><para>The start time of the event</para></enum>
71                                         <enum name="end"><para>The end time of the event</para></enum>
72                                         <enum name="busystate"><para>The busy state of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
73                                 </enumlist>
74                         </parameter>
75                 </syntax>
76                 <description>
77                         <para>Whenever a calendar event notification call is made, the event data
78                         may be accessed with this function.</para>
79                 </description>
80         </function>
81         <function name="CALENDAR_QUERY" language="en_US">
82                 <synopsis>Query a calendar server and store the data on a channel
83                 </synopsis>
84                 <syntax>
85                         <parameter name="calendar" required="true">
86                                 <para>The calendar that should be queried</para>
87                         </parameter>
88                         <parameter name="start" required="false">
89                                 <para>The start time of the query (in seconds since epoch)</para>
90                         </parameter>
91                         <parameter name="end" required="false">
92                                 <para>The end time of the query (in seconds since epoch)</para>
93                         </parameter>
94                 </syntax>
95                 <description>
96                         <para>Get a list of events in the currently accessible timeframe of the <replaceable>calendar</replaceable>
97                         The function returns the id for accessing the result with CALENDAR_QUERY_RESULT()</para>
98                 </description>
99         </function>
100         <function name="CALENDAR_QUERY_RESULT" language="en_US">
101                 <synopsis>
102                         Retrieve data from a previously run CALENDAR_QUERY() call
103                 </synopsis>
104                 <syntax>
105                         <parameter name="id" required="true">
106                                 <para>The query ID returned by <literal>CALENDAR_QUERY</literal></para>
107                         </parameter>
108                         <parameter name="field" required="true">
109                                 <enumlist>
110                                         <enum name="getnum"><para>number of events occurring during time range</para></enum>
111                                         <enum name="summary"><para>A summary of the event</para></enum>
112                                         <enum name="description"><para>The full event description</para></enum>
113                                         <enum name="organizer"><para>The event organizer</para></enum>
114                                         <enum name="location"><para>The event location</para></enum>
115                                         <enum name="calendar"><para>The name of the calendar associted with the event</para></enum>
116                                         <enum name="uid"><para>The unique identifier for the event</para></enum>
117                                         <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
118                                         <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
119                                         <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
120                                 </enumlist>
121                         </parameter>
122                         <parameter name="entry" required="false" default="1">
123                                 <para>Return data from a specific event returned by the query</para>
124                         </parameter>
125                 </syntax>
126                 <description>
127                         <para>After running CALENDAR_QUERY and getting a result <replaceable>id</replaceable>, calling
128                         <literal>CALENDAR_QUERY</literal> with that <replaceable>id</replaceable> and a <replaceable>field</replaceable>
129                         will return the data for that field. If multiple events matched the query, and <replaceable>entry</replaceable>
130                         is provided, information from that event will be returned.</para>
131                 </description>
132         </function>
133         <function name="CALENDAR_WRITE" language="en_US">
134                 <synopsis>Write an event to a calendar</synopsis>
135                 <syntax>
136                         <parameter name="calendar" required="true">
137                                 <para>The calendar to write to</para>
138                         </parameter>
139                         <parameter name="field" multiple="true" required="true">
140                                 <enumlist>
141                                         <enum name="summary"><para>A summary of the event</para></enum>
142                                         <enum name="description"><para>The full event description</para></enum>
143                                         <enum name="organizer"><para>The event organizer</para></enum>
144                                         <enum name="location"><para>The event location</para></enum>
145                                         <enum name="uid"><para>The unique identifier for the event</para></enum>
146                                         <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
147                                         <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
148                                         <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
149                                 </enumlist>
150                         </parameter>
151                 </syntax>
152                 <description>
153                         <para>Example: CALENDAR_WRITE(calendar,field1,field2,field3)=val1,val2,val3</para>
154                         <para>The field and value arguments can easily be set/passed using the HASHKEYS() and HASH() functions</para>
155                 </description>
156         </function>
157
158 ***/
159 #define CALENDAR_BUCKETS 19
160
161 static struct ao2_container *calendars;
162 static struct sched_context *sched;
163 static pthread_t refresh_thread = AST_PTHREADT_NULL;
164 static ast_mutex_t refreshlock;
165 static ast_cond_t refresh_condition;
166 static ast_mutex_t reloadlock;
167
168 static void event_notification_destroy(void *data);
169 static void *event_notification_duplicate(void *data);
170 static void eventlist_destroy(void *data);
171 static void *eventlist_duplicate(void *data);
172
173 static const struct ast_datastore_info event_notification_datastore = {
174         .type = "EventNotification",
175         .destroy = event_notification_destroy,
176         .duplicate = event_notification_duplicate,
177 };
178
179 static const struct ast_datastore_info eventlist_datastore_info = {
180         .type = "CalendarEventList",
181         .destroy = eventlist_destroy,
182         .duplicate = eventlist_duplicate,
183 };
184
185 struct evententry {
186         struct ast_calendar_event *event;
187         AST_LIST_ENTRY(evententry) list;
188 };
189
190 static AST_LIST_HEAD_STATIC(techs, ast_calendar_tech);
191 AST_LIST_HEAD_NOLOCK(eventlist, evententry); /* define the type */
192
193 struct ast_config *ast_calendar_config;
194
195 static struct ast_calendar *unref_calendar(struct ast_calendar *cal)
196 {
197         ao2_ref(cal, -1);
198         return NULL;
199 }
200
201 static int calendar_hash_fn(const void *obj, const int flags)
202 {
203         const struct ast_calendar *cal = obj;
204         return ast_str_case_hash(cal->name);
205 }
206
207 static int calendar_cmp_fn(void *obj, void *arg, int flags)
208 {
209         const struct ast_calendar *one = obj, *two = arg;
210         return !strcasecmp(one->name, two->name) ? CMP_MATCH | CMP_STOP: 0;
211 }
212
213 static struct ast_calendar *find_calendar(const char *name)
214 {
215         struct ast_calendar tmp = {
216                 .name = name,
217         };
218         return ao2_find(calendars, &tmp, OBJ_POINTER);
219 }
220
221 static int event_hash_fn(const void *obj, const int flags)
222 {
223         const struct ast_calendar_event *event = obj;
224         return ast_str_hash(event->uid);
225 }
226
227 static int event_cmp_fn(void *obj, void *arg, int flags)
228 {
229         const struct ast_calendar_event *one = obj, *two = arg;
230         return !strcmp(one->uid, two->uid) ? CMP_MATCH | CMP_STOP : 0;
231 }
232
233 static struct ast_calendar_event *find_event(struct ao2_container *events, const char *uid)
234 {
235         struct ast_calendar_event tmp = {
236                 .uid = uid,
237         };
238         return ao2_find(events, &tmp, OBJ_POINTER);
239 }
240
241 struct ast_calendar_event *ast_calendar_unref_event(struct ast_calendar_event *event)
242 {
243         ao2_ref(event, -1);
244         return NULL;
245 }
246
247 static void calendar_destructor(void *obj)
248 {
249         struct ast_calendar *cal = obj;
250
251         ast_debug(3, "Destroying calendar %s\n", cal->name);
252
253         ao2_lock(cal);
254         cal->unloading = 1;
255         ast_cond_signal(&cal->unload);
256         pthread_join(cal->thread, NULL);
257         if (cal->tech_pvt) {
258                 cal->tech_pvt = cal->tech->unref_calendar(cal->tech_pvt);
259         }
260         ast_calendar_clear_events(cal);
261         ast_string_field_free_memory(cal);
262         ao2_ref(cal->events, -1);
263         ao2_unlock(cal);
264 }
265
266 static void eventlist_destructor(void *obj)
267 {
268         struct eventlist *events = obj;
269         struct evententry *entry;
270
271         while ((entry = AST_LIST_REMOVE_HEAD(events, list))) {
272                 ao2_ref(entry->event, -1);
273                 ast_free(entry);
274         }
275 }
276
277 static int calendar_busy_callback(void *obj, void *arg, int flags)
278 {
279         struct ast_calendar_event *event = obj;
280         int *is_busy = arg;
281         struct timeval tv = ast_tvnow();
282
283         if (tv.tv_sec >= event->start && tv.tv_sec <= event->end && event->busy_state > AST_CALENDAR_BS_FREE) {
284                 *is_busy = 1;
285                 return CMP_STOP;
286         }
287
288         return 0;
289 }
290
291 static int calendar_is_busy(struct ast_calendar *cal)
292 {
293         int is_busy = 0;
294
295         ao2_callback(cal->events, OBJ_NODATA, calendar_busy_callback, &is_busy);
296
297         return is_busy;
298 }
299
300 static enum ast_device_state calendarstate(const char *data)
301 {
302         struct ast_calendar *cal;
303
304         if (ast_strlen_zero(data) || (!(cal = find_calendar(data)))) {
305                 return AST_DEVICE_INVALID;
306         }
307
308         if (cal->tech->is_busy) {
309                 return cal->tech->is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
310         }
311
312         return calendar_is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
313 }
314
315 static struct ast_calendar *build_calendar(struct ast_config *cfg, const char *cat, const struct ast_calendar_tech *tech)
316 {
317         struct ast_calendar *cal;
318         struct ast_variable *v;
319         int new_calendar = 0;
320
321         if (!(cal = find_calendar(cat))) {
322                 new_calendar = 1;
323                 if (!(cal = ao2_alloc(sizeof(*cal), calendar_destructor))) {
324                         ast_log(LOG_ERROR, "Could not allocate calendar structure. Stopping.\n");
325                         return NULL;
326                 }
327
328                 if (!(cal->events = ao2_container_alloc(CALENDAR_BUCKETS, event_hash_fn, event_cmp_fn))) {
329                         ast_log(LOG_ERROR, "Could not allocate events container for %s\n", cat);
330                         cal = unref_calendar(cal);
331                         return NULL;
332                 }
333
334                 if (ast_string_field_init(cal, 32)) {
335                         ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", cat);
336                         cal = unref_calendar(cal);
337                         return NULL;
338                 }
339         } else {
340                 cal->pending_deletion = 0;
341         }
342
343         ast_string_field_set(cal, name, cat);
344         cal->tech = tech;
345
346         cal->refresh = 3600;
347         cal->timeframe = 60;
348
349         for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
350                 if (!strcasecmp(v->name, "autoreminder")) {
351                         cal->autoreminder = atoi(v->value);
352                 } else if (!strcasecmp(v->name, "channel")) {
353                         ast_string_field_set(cal, notify_channel, v->value);
354                 } else if (!strcasecmp(v->name, "context")) {
355                         ast_string_field_set(cal, notify_context, v->value);
356                 } else if (!strcasecmp(v->name, "extension")) {
357                         ast_string_field_set(cal, notify_extension, v->value);
358                 } else if (!strcasecmp(v->name, "waittime")) {
359                         cal->notify_waittime = atoi(v->value);
360                 } else if (!strcasecmp(v->name, "app")) {
361                         ast_string_field_set(cal, notify_app, v->value);
362                 } else if (!strcasecmp(v->name, "appdata")) {
363                         ast_string_field_set(cal, notify_appdata, v->value);
364                 } else if (!strcasecmp(v->name, "refresh")) {
365                         cal->refresh = atoi(v->value);
366                 } else if (!strcasecmp(v->name, "timeframe")) {
367                         cal->timeframe = atoi(v->value);
368                 }
369         }
370
371         if (new_calendar) {
372                 cal->thread = AST_PTHREADT_NULL;
373                 ast_cond_init(&cal->unload, NULL);
374                 ao2_link(calendars, cal);
375                 if (ast_pthread_create(&cal->thread, NULL, cal->tech->load_calendar, cal)) {
376                         /* If we start failing to create threads, go ahead and return NULL
377                          * and the tech module will be unregistered
378                          */ 
379                         ao2_unlink(calendars, cal);
380                         cal = unref_calendar(cal);
381                 }
382         }
383
384         return cal;
385 }
386
387 static int load_tech_calendars(struct ast_calendar_tech *tech)
388 {
389         struct ast_calendar *cal;
390         const char *cat = NULL;
391         const char *val;
392
393         if (!ast_calendar_config) {
394                 ast_log(LOG_WARNING, "Calendar support disabled, not loading %s calendar module\n", tech->type);
395                 return -1;
396         }
397
398         while ((cat = ast_category_browse(ast_calendar_config, cat))) {
399                 if (!strcasecmp(cat, "general")) {
400                         continue;
401                 }
402
403                 if (!(val = ast_variable_retrieve(ast_calendar_config, cat, "type")) || strcasecmp(val, tech->type)) {
404                         continue;
405                 }
406
407                 /* A serious error occurred loading calendars from this tech and it should be disabled */
408                 if (!(cal = build_calendar(ast_calendar_config, cat, tech))) {
409                         ast_calendar_unregister(tech);
410                         return -1;
411                 }
412
413                 cal = unref_calendar(cal);
414         }
415
416         return 0;
417 }
418
419 int ast_calendar_register(struct ast_calendar_tech *tech)
420 {
421         struct ast_calendar_tech *iter;
422
423         AST_LIST_LOCK(&techs);
424         AST_LIST_TRAVERSE(&techs, iter, list) {
425                 if(!strcasecmp(tech->type, iter->type)) {
426                         ast_log(LOG_WARNING, "Already have a handler for calendar type '%s'\n", tech->type);
427                         AST_LIST_UNLOCK(&techs);
428                         return -1;
429                 }
430         }
431         AST_LIST_INSERT_HEAD(&techs, tech, list);
432         AST_LIST_UNLOCK(&techs);
433
434         ast_verb(2, "Registered calendar type '%s' (%s)\n", tech->type, tech->description);
435
436         return load_tech_calendars(tech);
437 }
438
439 static int match_caltech_cb(void *user_data, void *arg, int flags)
440 {
441         struct ast_calendar *cal = user_data;
442         struct ast_calendar_tech *tech = arg;
443
444         if (cal->tech == tech) {
445                 return CMP_MATCH;
446         }
447
448         return 0;
449 }
450
451 void ast_calendar_unregister(struct ast_calendar_tech *tech)
452 {
453         struct ast_calendar_tech *iter;
454
455         AST_LIST_LOCK(&techs);
456         AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, iter, list) {
457                 if (iter != tech) {
458                         continue;
459                 }
460
461                 ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, match_caltech_cb, tech);
462
463                 AST_LIST_REMOVE_CURRENT(list);
464                 ast_verb(2, "Unregistered calendar type '%s'\n", tech->type);
465                 break;
466         }
467         AST_LIST_TRAVERSE_SAFE_END;
468         AST_LIST_UNLOCK(&techs);
469
470 }
471
472 static void calendar_event_destructor(void *obj)
473 {
474         struct ast_calendar_event *event = obj;
475         struct ast_calendar_attendee *attendee;
476
477         ast_debug(3, "Destroying event for calendar '%s'\n", event->owner->name);
478         ast_string_field_free_memory(event);
479         while ((attendee = AST_LIST_REMOVE_HEAD(&event->attendees, next))) {
480                 if (attendee->data) {
481                         ast_free(attendee->data);
482                 }
483                 ast_free(attendee);
484         }
485 }
486
487 /* This is only called from ao2_callbacks that are going to unref the event for us,
488  * so we don't unref the event here.  */
489 static struct ast_calendar_event *destroy_event(struct ast_calendar_event *event)
490 {
491         if (event->notify_sched > -1 && ast_sched_del(sched, event->notify_sched)) {
492                 ast_debug(3, "Notification running, can't delete sched entry\n");
493         }
494         if (event->bs_start_sched > -1 && ast_sched_del(sched, event->bs_start_sched)) {
495                 ast_debug(3, "Devicestate update (start) running, can't delete sched entry\n");
496         }
497         if (event->bs_end_sched > -1 && ast_sched_del(sched, event->bs_end_sched)) {
498                 ast_debug(3, "Devicestate update (end) running, can't delete sched entry\n");
499         }
500
501         /* If an event is being deleted and we've fired an event changing the status at the beginning,
502          * but haven't hit the end event yet, go ahead and set the devicestate to the current busy status */
503         if (event->bs_start_sched < 0 && event->bs_end_sched >= 0) {
504                 if (!calendar_is_busy(event->owner)) {
505                         ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Calendar/%s", event->owner->name);
506                 } else {
507                         ast_devstate_changed(AST_DEVICE_BUSY, "Calendar/%s", event->owner->name);
508                 }
509         }
510
511         return NULL;
512 }
513
514 static int clear_events_cb(void *user_data, void *arg, int flags)
515 {
516         struct ast_calendar_event *event = user_data;
517
518         event = destroy_event(event);
519
520         return CMP_MATCH;
521 }
522
523 void ast_calendar_clear_events(struct ast_calendar *cal)
524 {
525         ast_debug(3, "Clearing all events for calendar %s\n", cal->name);
526
527         ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, clear_events_cb, NULL);
528 }
529
530 struct ast_calendar_event *ast_calendar_event_alloc(struct ast_calendar *cal)
531 {
532         struct ast_calendar_event *event;
533         if (!(event = ao2_alloc(sizeof(*event), calendar_event_destructor))) {
534                 return NULL;
535         }
536
537         if (ast_string_field_init(event, 32)) {
538                 event = ast_calendar_unref_event(event);
539                 return NULL;
540         }
541
542         event->owner = cal;
543         event->notify_sched = -1;
544         event->bs_start_sched = -1;
545         event->bs_end_sched = -1;
546
547         AST_LIST_HEAD_INIT_NOLOCK(&event->attendees);
548
549         return event;
550 }
551
552 struct ao2_container *ast_calendar_event_container_alloc(void)
553 {
554         return ao2_container_alloc(CALENDAR_BUCKETS, event_hash_fn, event_cmp_fn);
555 }
556
557 static void event_notification_destroy(void *data)
558 {
559         struct ast_calendar_event *event = data;
560
561         event = ast_calendar_unref_event(event);
562
563 }
564
565 static void *event_notification_duplicate(void *data)
566 {
567         struct ast_calendar_event *event = data;
568
569         if (!event) {
570                 return NULL;
571         }
572
573         ao2_ref(event, +1);
574
575         return event;
576 }
577
578 /*! \brief Generate 32 byte random string (stolen from chan_sip.c)*/
579 static char *generate_random_string(char *buf, size_t size)
580 {
581         long val[4];
582         int x;
583
584         for (x = 0; x < 4; x++) {
585                 val[x] = ast_random();
586         }
587         snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
588
589         return buf;
590 }
591
592 static int calendar_event_notify(const void *data)
593 {
594         struct ast_calendar_event *event = (void *)data;
595         char tech[256], dest[256], buf[8], *tmp;
596         struct ast_dial *dial = NULL;
597         struct ast_channel *chan = NULL;
598         struct ast_str *apptext = NULL;
599         int res = -1;
600         char start[12], end[12], busystate[2];
601         struct ast_datastore *datastore;
602
603         if (!(event && event->owner)) {
604                 ast_log(LOG_ERROR, "Extremely low-cal...in fact cal is NULL!\n");
605                 goto notify_cleanup;
606         }
607
608         ao2_ref(event, +1);
609         event->notify_sched = -1;
610
611         ast_copy_string(tech, event->owner->notify_channel, sizeof(tech));
612
613         if ((tmp = strchr(tech, '/'))) {
614                 *tmp = '\0';
615                 tmp++;
616                 ast_copy_string(dest, tmp, sizeof(dest));
617         } else {
618                 ast_log(LOG_WARNING, "Channel should be in form Tech/Dest\n");
619                 goto notify_cleanup;
620         }
621
622         if (!(dial = ast_dial_create())) {
623                 ast_log(LOG_ERROR, "Could not create dial structure\n");
624                 goto notify_cleanup;
625         }
626
627         if (ast_dial_append(dial, tech, dest) < 0) {
628                 ast_log(LOG_ERROR, "Could not append channel\n");
629                 goto notify_cleanup;
630         }
631
632         ast_dial_set_global_timeout(dial, event->owner->notify_waittime);
633         generate_random_string(buf, sizeof(buf));
634         if (!(chan = ast_channel_alloc(1, AST_STATE_DOWN, 0, 0, 0, 0, 0, 0, 0, "Calendar/%s-%s", event->owner->name, buf))) {
635                 ast_log(LOG_ERROR, "Could not allocate notification channel\n");
636                 goto notify_cleanup;
637         }
638
639         snprintf(busystate, sizeof(busystate), "%d", event->busy_state);
640         snprintf(start, sizeof(start), "%lu", (long) event->start);
641         snprintf(end, sizeof(end), "%lu", (long) event->end);
642
643         chan->nativeformats = AST_FORMAT_SLINEAR;
644
645         if (!(datastore = ast_datastore_alloc(&event_notification_datastore, NULL))) {
646                 ast_log(LOG_ERROR, "Could not allocate datastore, notification not being sent!\n");
647                 goto notify_cleanup;
648         }
649
650         datastore->data = event;
651         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
652
653         ao2_ref(event, +1);
654         res = ast_channel_datastore_add(chan, datastore);
655
656         if (!(apptext = ast_str_create(32))) {
657                 goto notify_cleanup;
658         }
659
660         if (!ast_strlen_zero(event->owner->notify_app)) {
661                 ast_str_set(&apptext, 0, "%s,%s", event->owner->notify_app, event->owner->notify_appdata);
662         } else {
663                 ast_str_set(&apptext, 0, "Dial,Local/%s@%s", event->owner->notify_extension, event->owner->notify_context);
664         }
665         ast_dial_option_global_enable(dial, AST_DIAL_OPTION_ANSWER_EXEC, ast_str_buffer(apptext));
666
667         ast_dial_run(dial, chan, 1);
668         res = 0;
669
670 notify_cleanup:
671         event = ast_calendar_unref_event(event);
672         if (res == -1 && dial) {
673                 ast_dial_destroy(dial);
674         }
675         if (apptext) {
676                 ast_free(apptext);
677         }
678         if (chan) {
679                 ast_channel_release(chan);
680         }
681
682         return res;
683 }
684
685 static int calendar_devstate_change(const void *data)
686 {
687         struct ast_calendar_event *event = (struct ast_calendar_event *)data;
688         struct timeval now = ast_tvnow();
689         int is_end_event;
690
691         if (!event) {
692                 ast_log(LOG_WARNING, "Event was NULL!\n");
693                 return 0;
694         }
695
696         ao2_ref(event, +1);
697
698         is_end_event = event->end <= now.tv_sec;
699
700         if (is_end_event) {
701                 event->bs_end_sched = -1;
702         } else {
703                 event->bs_start_sched = -1;
704         }
705
706         /* We can have overlapping events, so ignore the event->busy_state and check busy state
707          * based on all events in the calendar */
708         if (!calendar_is_busy(event->owner)) {
709                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Calendar/%s", event->owner->name);
710         } else {
711                 ast_devstate_changed(AST_DEVICE_BUSY, "Calendar/%s", event->owner->name);
712         }
713
714         event = ast_calendar_unref_event(event);
715
716         return 0;
717 }
718
719 static void copy_event_data(struct ast_calendar_event *dst, struct ast_calendar_event *src)
720 {
721         struct ast_calendar_attendee *attendee;
722
723         ast_string_field_set(dst, summary, src->summary);
724         ast_string_field_set(dst, description, src->description);
725         ast_string_field_set(dst, organizer, src->organizer);
726         ast_string_field_set(dst, location, src->location);
727         ast_string_field_set(dst, uid, src->uid);
728         dst->owner = src->owner;
729         dst->start = src->start;
730         dst->end = src->end;
731         dst->alarm = src->alarm;
732         dst->busy_state = src->busy_state;
733
734         while ((attendee = AST_LIST_REMOVE_HEAD(&src->attendees, next))) {
735                 AST_LIST_INSERT_TAIL(&dst->attendees, attendee, next);
736         }
737 }
738
739 static int schedule_calendar_event(struct ast_calendar *cal, struct ast_calendar_event *old_event, struct ast_calendar_event *cmp_event)
740 {
741         struct timeval now = ast_tvnow();
742         struct ast_calendar_event *event;
743         time_t alarm_notify_sched = 0, devstate_sched_start, devstate_sched_end;
744         int changed = 0;
745
746         event = cmp_event ? cmp_event : old_event;
747
748         ao2_lock(event);
749         if (!cmp_event || old_event->alarm != event->alarm) {
750                 changed = 1;
751                 if (cal->autoreminder) {
752                         alarm_notify_sched = (event->start - (60 * cal->autoreminder) - now.tv_sec) * 1000;
753                 } else if (event->alarm) {
754                         alarm_notify_sched = (event->alarm - now.tv_sec) * 1000;
755                 }
756
757                 /* For now, send the notification if we missed it, but the meeting hasn't happened yet */
758                 if (event->start >=  now.tv_sec) {
759                         if (alarm_notify_sched <= 0) {
760                                 alarm_notify_sched = 1;
761                         }
762                         ast_mutex_lock(&refreshlock);
763                         AST_SCHED_REPLACE(old_event->notify_sched, sched, alarm_notify_sched, calendar_event_notify, old_event);
764                         ast_mutex_unlock(&refreshlock);
765                         ast_debug(3, "Calendar alarm event notification scheduled to happen in %ld ms\n", (long) alarm_notify_sched);
766                 }
767         }
768
769         if (!cmp_event || old_event->start != event->start) {
770                 changed = 1;
771                 devstate_sched_start = (event->start - now.tv_sec) * 1000;
772
773                 if (devstate_sched_start < 1) {
774                         devstate_sched_start = 1;
775                 }
776
777                 ast_mutex_lock(&refreshlock);
778                 AST_SCHED_REPLACE(old_event->bs_start_sched, sched, devstate_sched_start, calendar_devstate_change, old_event);
779                 ast_mutex_unlock(&refreshlock);
780                 ast_debug(3, "Calendar bs_start event notification scheduled to happen in %ld ms\n", (long) devstate_sched_start);
781         }
782
783         if (!cmp_event || old_event->end != event->end) {
784                 changed = 1;
785                 devstate_sched_end = (event->end - now.tv_sec) * 1000;
786                 ast_mutex_lock(&refreshlock);
787                 AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
788                 ast_mutex_unlock(&refreshlock);
789                 ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", (long) devstate_sched_end);
790         }
791
792         if (changed) {
793                 ast_cond_signal(&refresh_condition);
794         }
795
796         ao2_unlock(event);
797
798         return 0;
799 }
800
801 static int merge_events_cb(void *obj, void *arg, int flags)
802 {
803         struct ast_calendar_event *old_event = obj, *new_event;
804         struct ao2_container *new_events = arg;
805
806         /* If we don't find the old_event in new_events, then we can safely delete the old_event */
807         if (!(new_event = find_event(new_events, old_event->uid))) {
808                 old_event = destroy_event(old_event);
809                 return CMP_MATCH;
810         }
811
812         /* We have events to merge.  If any data that will affect a scheduler event has changed,
813          * then we need to replace the scheduler event */
814         schedule_calendar_event(old_event->owner, old_event, new_event);
815
816         /* Since we don't want to mess with cancelling sched events and adding new ones, just
817          * copy the internals of the new_event to the old_event */
818         copy_event_data(old_event, new_event);
819
820         /* Now we can go ahead and unlink the new_event from new_events and unref it so that only completely
821          * new events remain in the container */
822         ao2_unlink(new_events, new_event);
823         new_event = ast_calendar_unref_event(new_event);
824
825         return 0;
826 }
827
828 static int add_new_event_cb(void *obj, void *arg, int flags)
829 {
830         struct ast_calendar_event *new_event = obj;
831         struct ao2_container *events = arg;
832
833         ao2_link(events, new_event);
834         schedule_calendar_event(new_event->owner, new_event, NULL);
835         return CMP_MATCH;
836 }
837
838 void ast_calendar_merge_events(struct ast_calendar *cal, struct ao2_container *new_events)
839 {
840         /* Loop through all events attached to the calendar.  If there is a matching new event
841          * merge its data over and handle any schedule changes that need to be made.  Then remove
842          * the new_event from new_events so that we are left with only new_events that we can add later. */
843         ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, merge_events_cb, new_events);
844
845         /* Now, we should only have completely new events in new_events.  Loop through and add them */
846         ao2_callback(new_events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, add_new_event_cb, cal->events);
847 }
848
849
850 static int load_config(void *data)
851 {
852         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
853         struct ast_config *tmpcfg;
854
855         if (!(tmpcfg = ast_config_load2("calendar.conf", "calendar", config_flags)) ||
856                 tmpcfg == CONFIG_STATUS_FILEINVALID) {
857                 ast_log(LOG_ERROR, "Unable to load config calendar.conf\n");
858                 return -1;
859         }
860
861         if (tmpcfg == CONFIG_STATUS_FILEUNCHANGED) {
862                 return 0;
863         }
864
865         if (ast_calendar_config) {
866                 ast_config_destroy(ast_calendar_config);
867         }
868
869         ast_calendar_config = tmpcfg;
870
871         return 0;
872 }
873
874 /*! \brief A dialplan function that can be used to determine the busy status of a calendar */
875 static int calendar_busy_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
876 {
877         struct ast_calendar *cal;
878
879         if (ast_strlen_zero(data)) {
880                 ast_log(LOG_WARNING, "CALENDAR_BUSY requires an argument: CALENDAR_BUSY(<calendar_name>)\n");
881                 return -1;
882         }
883
884         cal = find_calendar(data);
885
886         if (!cal) {
887                 ast_log(LOG_WARNING, "Could not find calendar '%s'\n", data);
888                 return -1;
889         }
890
891         strcpy(buf, calendar_is_busy(cal) ? "1" : "0");
892
893         return 0;
894 }
895
896 static struct ast_custom_function calendar_busy_function = {
897     .name = "CALENDAR_BUSY",
898     .read = calendar_busy_exec,
899 };
900
901 static int add_event_to_list(struct eventlist *events, struct ast_calendar_event *event, time_t start, time_t end)
902 {
903         struct evententry *entry, *iter;
904         int event_startdiff = abs(start - event->start);
905         int event_enddiff = abs(end - event->end);
906         int i = 0;
907
908         if (!(entry = ast_calloc(1, sizeof(*entry)))) {
909                 ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
910                 return -1;
911         }
912
913         entry->event = event;
914         ao2_ref(event, +1);
915
916         if (start == end) {
917                 AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
918                         int startdiff = abs(iter->event->start - start);
919
920                         ast_debug(10, "Comparing %s with startdiff %d to %s with startdiff %d\n", event->summary, event_startdiff, iter->event->summary, startdiff);
921                         ++i;
922                         if (startdiff > event_startdiff) {
923                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
924                                 return i;
925                         }
926                         if (startdiff == event_startdiff) {
927                                 int enddiff = abs(iter->event->end - end);
928
929                                 if (enddiff > event_enddiff) {
930                                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
931                                         return i;
932                                 }
933                                 if (event_startdiff == enddiff) {
934                                         if (strcmp(event->uid, iter->event->uid) < 0) {
935                                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
936                                                 return i;
937                                         }
938                                 }
939                         }
940                 }
941                 AST_LIST_TRAVERSE_SAFE_END;
942
943                 AST_LIST_INSERT_TAIL(events, entry, list);
944
945                 return i;
946         }
947
948         AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
949                 ++i;
950                 if (iter->event->start > event->start) {
951                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
952                         return i;
953                 }
954
955                 if (iter->event->start == event->start) {
956                         if ((iter->event->end - iter->event->start) == (event->end - event->start)) {
957                                 if (strcmp(event->uid, iter->event->uid) < 0) {
958                                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
959                                         return i;
960                                 }
961                         }
962                         if ((iter->event->end - iter->event->start) < (event->end - event->start)) {
963                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
964                                 return i;
965                         }
966                 }
967         }
968         AST_LIST_TRAVERSE_SAFE_END;
969
970         AST_LIST_INSERT_TAIL(events, entry, list);
971
972         return i;
973 }
974
975 static void eventlist_destroy(void *data)
976 {
977         struct eventlist *events = data;
978
979         ao2_ref(events, -1);
980 }
981
982 static void *eventlist_duplicate(void *data)
983 {
984         struct eventlist *events = data;
985
986         if (!events) {
987                 return NULL;
988         }
989
990         ao2_ref(events, +1);
991
992         return events;
993 }
994
995 static int calendar_query_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
996 {
997         struct ast_calendar *cal;
998         struct ao2_iterator i;
999         struct ast_calendar_event *event;
1000         struct eventlist *events;
1001         time_t start = INT_MIN, end = INT_MAX;
1002         struct ast_datastore *eventlist_datastore;
1003         AST_DECLARE_APP_ARGS(args,
1004                 AST_APP_ARG(calendar);
1005                 AST_APP_ARG(start);
1006                 AST_APP_ARG(end);
1007         );
1008
1009         if (!chan) {
1010                 ast_log(LOG_WARNING, "%s requires a channel to store the data on\n", cmd);
1011                 return -1;
1012         }
1013
1014         AST_STANDARD_APP_ARGS(args, data);
1015
1016         if (ast_strlen_zero(args.calendar)) {
1017                 ast_log(LOG_WARNING, "%s requires a calendar argument\n", cmd);
1018                 return -1;
1019         }
1020
1021         if (!(cal = find_calendar(args.calendar))) {
1022                 ast_log(LOG_WARNING, "Unknown calendar '%s'\n", args.calendar);
1023                 return -1;
1024         }
1025
1026         if (!(events = ao2_alloc(sizeof(*events), eventlist_destructor))) {
1027                 ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
1028                 cal = unref_calendar(cal);
1029                 return -1;
1030         }
1031
1032         if (!ast_strlen_zero(args.start)) {
1033                 start = atoi(args.start);
1034         }
1035
1036         if (!ast_strlen_zero(args.end)) {
1037                 end = atoi(args.end);
1038         }
1039
1040         i = ao2_iterator_init(cal->events, 0);
1041         while ((event = ao2_iterator_next(&i))) {
1042                 if (!(start > event->end || end < event->start)) {
1043                         ast_debug(10, "%s (%ld - %ld) overlapped with (%ld - %ld)\n", event->summary, (long) event->start, (long) event->end, (long) start, (long) end);
1044                         if (add_event_to_list(events, event, start, end) < 0) {
1045                                 event = ast_calendar_unref_event(event);
1046                                 ao2_iterator_destroy(&i);
1047                                 return -1;
1048                         }
1049                 }
1050
1051                 event = ast_calendar_unref_event(event);
1052         }
1053         ao2_iterator_destroy(&i);
1054
1055         ast_channel_lock(chan);
1056         do {
1057                 generate_random_string(buf, len);
1058         } while (ast_channel_datastore_find(chan, &eventlist_datastore_info, buf));
1059         ast_channel_unlock(chan);
1060
1061         if (!(eventlist_datastore = ast_datastore_alloc(&eventlist_datastore_info, buf))) {
1062                 ast_log(LOG_ERROR, "Could not allocate datastore!\n");
1063                 return -1;
1064         }
1065
1066         eventlist_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
1067         eventlist_datastore->data = events;
1068
1069         ast_channel_lock(chan);
1070         ast_channel_datastore_add(chan, eventlist_datastore);
1071         ast_channel_unlock(chan);
1072
1073         return 0;
1074 }
1075
1076 static struct ast_custom_function calendar_query_function = {
1077     .name = "CALENDAR_QUERY",
1078     .read = calendar_query_exec,
1079 };
1080
1081 static void calendar_join_attendees(struct ast_calendar_event *event, char *buf, size_t len)
1082 {
1083         struct ast_str *tmp;
1084         struct ast_calendar_attendee *attendee;
1085
1086         if (!(tmp = ast_str_create(32))) {
1087                 ast_log(LOG_ERROR, "Could not allocate memory for attendees!\n");
1088                 return;
1089         }
1090
1091         AST_LIST_TRAVERSE(&event->attendees, attendee, next) {
1092                 ast_str_append(&tmp, 0, "%s%s", attendee == AST_LIST_FIRST(&event->attendees) ? "" : ",", attendee->data);
1093         }
1094
1095         ast_copy_string(buf, ast_str_buffer(tmp), len);
1096         ast_free(tmp);
1097 }
1098
1099 static int calendar_query_result_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1100 {
1101         struct ast_datastore *datastore;
1102         struct eventlist *events;
1103         struct evententry *entry;
1104         int row = 1;
1105         AST_DECLARE_APP_ARGS(args,
1106                 AST_APP_ARG(id);
1107                 AST_APP_ARG(field);
1108                 AST_APP_ARG(row);
1109         );
1110
1111         if (!chan) {
1112                 ast_log(LOG_WARNING, "%s requires a channel\n", cmd);
1113                 return -1;
1114         }
1115
1116         AST_STANDARD_APP_ARGS(args, data);
1117
1118         if (ast_strlen_zero(args.id) || ast_strlen_zero(args.field)) {
1119                 ast_log(LOG_WARNING, "%s requires an id and a field", cmd);
1120                 return -1;
1121         }
1122
1123         ast_channel_lock(chan);
1124         if (!(datastore = ast_channel_datastore_find(chan, &eventlist_datastore_info, args.id))) {
1125                 ast_log(LOG_WARNING, "There is no event notification datastore with id '%s' on '%s'!\n", args.id, chan->name);
1126                 ast_channel_unlock(chan);
1127                 return -1;
1128         }
1129         ast_channel_unlock(chan);
1130
1131         if (!(events = datastore->data)) {
1132                 ast_log(LOG_WARNING, "The datastore contains no data!\n");
1133                 return -1;
1134         }
1135
1136         if (!ast_strlen_zero(args.row)) {
1137                 row = atoi(args.row);
1138         }
1139
1140         AST_LIST_TRAVERSE(events, entry, list) {
1141                 if (--row) {
1142                         continue;
1143                 }
1144                 if (!strcasecmp(args.field, "summary")) {
1145                         ast_copy_string(buf, entry->event->summary, len);
1146                 } else if (!strcasecmp(args.field, "description")) {
1147                         ast_copy_string(buf, entry->event->description, len);
1148                 } else if (!strcasecmp(args.field, "organizer")) {
1149                         ast_copy_string(buf, entry->event->organizer, len);
1150                 } else if (!strcasecmp(args.field, "location")) {
1151                         ast_copy_string(buf, entry->event->location, len);
1152                 } else if (!strcasecmp(args.field, "calendar")) {
1153                         ast_copy_string(buf, entry->event->owner->name, len);
1154                 } else if (!strcasecmp(args.field, "uid")) {
1155                         ast_copy_string(buf, entry->event->uid, len);
1156                 } else if (!strcasecmp(args.field, "start")) {
1157                         snprintf(buf, len, "%ld", (long) entry->event->start);
1158                 } else if (!strcasecmp(args.field, "end")) {
1159                         snprintf(buf, len, "%ld", (long) entry->event->end);
1160                 } else if (!strcasecmp(args.field, "busystate")) {
1161                         snprintf(buf, len, "%d", entry->event->busy_state);
1162                 } else if (!strcasecmp(args.field, "attendees")) {
1163                         calendar_join_attendees(entry->event, buf, len);
1164                 } else {
1165                         ast_log(LOG_WARNING, "Unknown field '%s'\n", args.field);
1166                 }
1167                 break;
1168         }
1169
1170         return 0;
1171 }
1172
1173 static struct ast_custom_function calendar_query_result_function = {
1174         .name = "CALENDAR_QUERY_RESULT",
1175         .read = calendar_query_result_exec,
1176 };
1177
1178 static int calendar_write_exec(struct ast_channel *chan, const char *cmd, char *data, const char *value)
1179 {
1180         int i, j, ret = -1;
1181         char *val_dup = NULL;
1182         struct ast_calendar *cal = NULL;
1183         struct ast_calendar_event *event = NULL;
1184         AST_DECLARE_APP_ARGS(fields,
1185                 AST_APP_ARG(field)[10];
1186         );
1187         AST_DECLARE_APP_ARGS(values,
1188                 AST_APP_ARG(value)[10];
1189         );
1190
1191         if (!(val_dup = ast_strdup(value))) {
1192                 ast_log(LOG_ERROR, "Could not allocate memory for values\n");
1193                 return -1;
1194         }
1195
1196         AST_STANDARD_APP_ARGS(fields, data);
1197         AST_STANDARD_APP_ARGS(values, val_dup);
1198
1199         /* XXX Eventually we will support unnamed calendars, so if we don't find one, we parse
1200          * for a calendar type and create it */
1201         if (!(cal = find_calendar(fields.field[0]))) {
1202                 ast_log(LOG_WARNING, "Couldn't find calendar '%s'\n", fields.field[0]);
1203                 goto write_cleanup;
1204         }
1205
1206         if (!(cal->tech->write_event)) {
1207                 ast_log(LOG_WARNING, "Calendar '%s' has no write function!\n", cal->name);
1208                 goto write_cleanup;
1209         }
1210
1211         if (!(event = ast_calendar_event_alloc(cal))) {
1212                 goto write_cleanup;
1213         }
1214
1215         if (ast_strlen_zero(fields.field[0])) {
1216                 ast_log(LOG_WARNING, "CALENDAR_WRITE requires a calendar name!\n");
1217                 goto write_cleanup;
1218         }
1219
1220         if (fields.argc - 1 != values.argc) {
1221                 ast_log(LOG_WARNING, "CALENDAR_WRITE should have the same number of fields (%d) and values (%d)!\n", fields.argc - 1, values.argc);
1222                 goto write_cleanup;
1223         }
1224
1225         event->owner = cal;
1226
1227         for (i = 1, j = 0; i < fields.argc; i++, j++) {
1228                 if (!strcasecmp(fields.field[i], "summary")) {
1229                         ast_string_field_set(event, summary, values.value[j]);
1230                 } else if (!strcasecmp(fields.field[i], "description")) {
1231                         ast_string_field_set(event, description, values.value[j]);
1232                 } else if (!strcasecmp(fields.field[i], "organizer")) {
1233                         ast_string_field_set(event, organizer, values.value[j]);
1234                 } else if (!strcasecmp(fields.field[i], "location")) {
1235                         ast_string_field_set(event, location, values.value[j]);
1236                 } else if (!strcasecmp(fields.field[i], "uid")) {
1237                         ast_string_field_set(event, uid, values.value[j]);
1238                 } else if (!strcasecmp(fields.field[i], "start")) {
1239                         event->start = atoi(values.value[j]);
1240                 } else if (!strcasecmp(fields.field[i], "end")) {
1241                         event->end = atoi(values.value[j]);
1242                 } else if (!strcasecmp(fields.field[i], "busystate")) {
1243                         event->busy_state = atoi(values.value[j]);
1244                 } else {
1245                         ast_log(LOG_WARNING, "Unknown calendar event field '%s'\n", fields.field[i]);
1246                 }
1247         }
1248
1249         if((ret = cal->tech->write_event(event))) {
1250                 ast_log(LOG_WARNING, "Writing event to calendar '%s' failed!\n", cal->name);
1251         }
1252
1253 write_cleanup:
1254         if (cal) {
1255                 cal = unref_calendar(cal);
1256         }
1257         if (event) {
1258                 event = ast_calendar_unref_event(event);
1259         }
1260         if (val_dup) {
1261                 ast_free(val_dup);
1262         }
1263
1264         return ret;
1265 }
1266
1267 static struct ast_custom_function calendar_write_function = {
1268         .name = "CALENDAR_WRITE",
1269         .write = calendar_write_exec,
1270 };
1271
1272 /*! \brief CLI command to list available calendars */
1273 static char *handle_show_calendars(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1274 {
1275 #define FORMAT "%-20.20s %-10.10s %-6.6s\n"
1276         struct ao2_iterator i;
1277         struct ast_calendar *cal;
1278
1279         switch(cmd) {
1280         case CLI_INIT:
1281                 e->command = "calendar show calendars";
1282                 e->usage =
1283                         "Usage: calendar show calendars\n"
1284                         "       Lists all registered calendars.\n";
1285                 return NULL;
1286         case CLI_GENERATE:
1287                 return NULL;
1288         }
1289
1290         ast_cli(a->fd, FORMAT, "Calendar", "Type", "Status");
1291         ast_cli(a->fd, FORMAT, "--------", "----", "------");
1292         i = ao2_iterator_init(calendars, 0);
1293         while ((cal = ao2_iterator_next(&i))) {
1294                 ast_cli(a->fd, FORMAT, cal->name, cal->tech->type, calendar_is_busy(cal) ? "busy" : "free");
1295                 cal = unref_calendar(cal);
1296         }
1297         ao2_iterator_destroy(&i);
1298
1299         return CLI_SUCCESS;
1300 #undef FORMAT
1301 }
1302
1303 static char *epoch_to_string(char *buf, size_t buflen, time_t epoch)
1304 {
1305         struct ast_tm tm;
1306         struct timeval tv = {
1307                 .tv_sec = epoch,
1308         };
1309
1310         if (!epoch) {
1311                 *buf = '\0';
1312                 return buf;
1313         }
1314         ast_localtime(&tv, &tm, NULL);
1315         ast_strftime(buf, buflen, "%F %r", &tm);
1316
1317         return buf;
1318 }
1319
1320 static char *handle_show_calendar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1321 {
1322 #define FORMAT "%-17.17s : %-20.20s\n"
1323 #define FORMAT2 "%-12.12s: %-40.60s\n"
1324         struct ao2_iterator i;
1325         struct ast_calendar *cal;
1326         struct ast_calendar_event *event;
1327         int which = 0;
1328         char *ret = NULL;
1329
1330         switch(cmd) {
1331         case CLI_INIT:
1332                 e->command = "calendar show calendar";
1333                 e->usage =
1334                         "Usage: calendar show calendar <calendar name>\n"
1335                         "       Displays information about a calendar\n";
1336                 return NULL;
1337
1338         case CLI_GENERATE:
1339                 if (a->pos != 3) {
1340                         return NULL;
1341                 }
1342                 i = ao2_iterator_init(calendars, 0);
1343                 while ((cal = ao2_iterator_next(&i))) {
1344                         if (!strncasecmp(a->word, cal->name, strlen(a->word)) && ++which > a->n) {
1345                                 ret = ast_strdup(cal->name);
1346                                 cal = unref_calendar(cal);
1347                                 break;
1348                         }
1349                         cal = unref_calendar(cal);
1350                 }
1351                 ao2_iterator_destroy(&i);
1352                 return ret;
1353         }
1354
1355         if (a->argc != 4) {
1356                 return CLI_SHOWUSAGE;
1357         }
1358
1359         if (!(cal = find_calendar(a->argv[3]))) {
1360                 return NULL;
1361         }
1362
1363         ast_cli(a->fd, FORMAT, "Name", cal->name);
1364         ast_cli(a->fd, FORMAT, "Notify channel", cal->notify_channel);
1365         ast_cli(a->fd, FORMAT, "Notify context", cal->notify_context);
1366         ast_cli(a->fd, FORMAT, "Notify extension", cal->notify_extension);
1367         ast_cli(a->fd, FORMAT, "Notify application", cal->notify_app);
1368         ast_cli(a->fd, FORMAT, "Notify appdata", cal->notify_appdata);
1369         ast_cli(a->fd, "%-17.17s : %d\n", "Refresh time", cal->refresh);
1370         ast_cli(a->fd, "%-17.17s : %d\n", "Timeframe", cal->timeframe);
1371         ast_cli(a->fd, "%-17.17s : %d\n", "Autoreminder", cal->autoreminder);
1372         ast_cli(a->fd, "%s\n", "Events");
1373         ast_cli(a->fd, "%s\n", "------");
1374
1375         i = ao2_iterator_init(cal->events, 0);
1376         while ((event = ao2_iterator_next(&i))) {
1377                 char buf[100];
1378
1379                 ast_cli(a->fd, FORMAT2, "Summary", event->summary);
1380                 ast_cli(a->fd, FORMAT2, "Description", event->description);
1381                 ast_cli(a->fd, FORMAT2, "Organizer", event->organizer);
1382                 ast_cli(a->fd, FORMAT2, "Location", event->location);
1383                 ast_cli(a->fd, FORMAT2, "UID", event->uid);
1384                 ast_cli(a->fd, FORMAT2, "Start", epoch_to_string(buf, sizeof(buf), event->start));
1385                 ast_cli(a->fd, FORMAT2, "End", epoch_to_string(buf, sizeof(buf), event->end));
1386                 ast_cli(a->fd, FORMAT2, "Alarm", epoch_to_string(buf, sizeof(buf), event->alarm));
1387                 ast_cli(a->fd, "\n");
1388
1389                 event = ast_calendar_unref_event(event);
1390         }
1391         ao2_iterator_destroy(&i);
1392         cal = unref_calendar(cal);
1393         return CLI_SUCCESS;
1394 #undef FORMAT
1395 #undef FORMAT2
1396 }
1397
1398 static char *handle_dump_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1399 {
1400         switch(cmd) {
1401         case CLI_INIT:
1402                 e->command = "calendar dump sched";
1403                 e->usage =
1404                         "Usage: calendar dump sched\n"
1405                         "       Dump the calendar sched context";
1406                 return NULL;
1407
1408         case CLI_GENERATE:
1409                 return NULL;
1410         }
1411
1412         ast_sched_dump(sched);
1413
1414         return CLI_SUCCESS;
1415 }
1416
1417 static struct ast_cli_entry calendar_cli[] = {
1418         AST_CLI_DEFINE(handle_show_calendar, "Display information about a calendar"),
1419         AST_CLI_DEFINE(handle_show_calendars, "Show registered calendars"),
1420         AST_CLI_DEFINE(handle_dump_sched, "Dump calendar sched context"),
1421 };
1422
1423 static int calendar_event_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1424 {
1425         struct ast_datastore *datastore;
1426         struct ast_calendar_event *event;
1427
1428         if (ast_strlen_zero(data)) {
1429                 ast_log(LOG_WARNING, "%s requires an argument\n", cmd);
1430                 return -1;
1431         }
1432
1433         ast_channel_lock(chan);
1434         if (!(datastore = ast_channel_datastore_find(chan, &event_notification_datastore, NULL))) {
1435                 ast_log(LOG_WARNING, "There is no event notification datastore on '%s'!\n", chan->name);
1436                 ast_channel_unlock(chan);
1437                 return -1;
1438         }
1439         ast_channel_unlock(chan);
1440
1441         if (!(event = datastore->data)) {
1442                 ast_log(LOG_WARNING, "The datastore contains no data!\n");
1443                 return -1;
1444         }
1445
1446         if (!strcasecmp(data, "summary")) {
1447                 ast_copy_string(buf, event->summary, len);
1448         } else if (!strcasecmp(data, "description")) {
1449                 ast_copy_string(buf, event->description, len);
1450         } else if (!strcasecmp(data, "organizer")) {
1451                 ast_copy_string(buf, event->organizer, len);
1452         } else if (!strcasecmp(data, "location")) {
1453                 ast_copy_string(buf, event->location, len);
1454         } else if (!strcasecmp(data, "calendar")) {
1455                 ast_copy_string(buf, event->owner->name, len);
1456         } else if (!strcasecmp(data, "uid")) {
1457                 ast_copy_string(buf, event->uid, len);
1458         } else if (!strcasecmp(data, "start")) {
1459                 snprintf(buf, len, "%ld", (long)event->start);
1460         } else if (!strcasecmp(data, "end")) {
1461                 snprintf(buf, len, "%ld", (long)event->end);
1462         } else if (!strcasecmp(data, "busystate")) {
1463                 snprintf(buf, len, "%d", event->busy_state);
1464         } else if (!strcasecmp(data, "attendees")) {
1465                 calendar_join_attendees(event, buf, len);
1466         }
1467
1468
1469         return 0;
1470 }
1471
1472 static struct ast_custom_function calendar_event_function = {
1473         .name = "CALENDAR_EVENT",
1474         .read = calendar_event_read,
1475 };
1476
1477 static int cb_pending_deletion(void *user_data, void *arg, int flags)
1478 {
1479         struct ast_calendar *cal = user_data;
1480
1481         cal->pending_deletion = 1;
1482
1483         return CMP_MATCH;
1484 }
1485
1486 static int cb_rm_pending_deletion(void *user_data, void *arg, int flags)
1487 {
1488         struct ast_calendar *cal = user_data;
1489
1490         return cal->pending_deletion ? CMP_MATCH : 0;
1491 }
1492
1493 static int reload(void)
1494 {
1495         struct ast_calendar_tech *iter;
1496
1497         ast_mutex_lock(&reloadlock);
1498
1499         /* Mark existing calendars for deletion */
1500         ao2_callback(calendars, OBJ_NODATA | OBJ_MULTIPLE, cb_pending_deletion, NULL);
1501         load_config(NULL);
1502
1503         AST_LIST_LOCK(&techs);
1504         AST_LIST_TRAVERSE(&techs, iter, list) {
1505                 if (load_tech_calendars(iter)) {
1506                         ast_log(LOG_WARNING, "Failed to reload %s calendars, module disabled\n", iter->type);
1507                 }
1508         }
1509         AST_LIST_UNLOCK(&techs);
1510
1511         /* Delete calendars that no longer show up in the config */
1512         ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_rm_pending_deletion, NULL);
1513
1514         ast_mutex_unlock(&reloadlock);
1515
1516         return 0;
1517 }
1518
1519 static void *do_refresh(void *data)
1520 {
1521         for (;;) {
1522                 struct timeval now = ast_tvnow();
1523                 struct timespec ts = {0,};
1524                 int res, wait;
1525
1526                 ast_mutex_lock(&refreshlock);
1527
1528                 if ((wait = ast_sched_wait(sched)) < 0) {
1529                         wait = 1000;
1530                 }
1531
1532                 ts.tv_sec = (now.tv_sec + wait / 1000) + 1;
1533                 res = ast_cond_timedwait(&refresh_condition, &refreshlock, &ts);
1534
1535                 ast_mutex_unlock(&refreshlock);
1536
1537                 ast_sched_runq(sched);
1538         }
1539
1540         return NULL;
1541 }
1542
1543 /* If I were to allow unloading it would look something like this */
1544 static int unload_module(void)
1545 {
1546         struct ast_calendar_tech *tech;
1547
1548         ast_devstate_prov_del("calendar");
1549         ast_custom_function_unregister(&calendar_busy_function);
1550         ast_custom_function_unregister(&calendar_event_function);
1551         ast_custom_function_unregister(&calendar_query_function);
1552         ast_custom_function_unregister(&calendar_query_result_function);
1553         ast_custom_function_unregister(&calendar_write_function);
1554         ast_cli_unregister_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
1555
1556         /* Remove all calendars */
1557         ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
1558
1559         AST_LIST_LOCK(&techs);
1560         AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, tech, list) {
1561                 ast_unload_resource(tech->module, 0);
1562         }
1563         AST_LIST_TRAVERSE_SAFE_END;
1564         AST_LIST_UNLOCK(&techs);
1565
1566         return 0;
1567 }
1568
1569 static int load_module(void)
1570 {
1571         if (load_config(NULL)) {
1572                 /* We don't have calendar support enabled */
1573                 return 0;
1574         }
1575
1576         if (!(calendars = ao2_container_alloc(CALENDAR_BUCKETS, calendar_hash_fn, calendar_cmp_fn))) {
1577                 ast_log(LOG_ERROR, "Unable to allocate calendars container!\n");
1578                 return -1;
1579         }
1580
1581         ast_mutex_init(&refreshlock);
1582         ast_cond_init(&refresh_condition, NULL);
1583         ast_mutex_init(&reloadlock);
1584
1585         if (!(sched = sched_context_create())) {
1586                 ast_log(LOG_ERROR, "Unable to create sched context\n");
1587                 return -1;
1588         }
1589
1590         if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
1591                 ast_log(LOG_ERROR, "Unable to start refresh thread--notifications disabled!\n");
1592         }
1593
1594         ast_custom_function_register(&calendar_busy_function);
1595         ast_custom_function_register(&calendar_event_function);
1596         ast_custom_function_register(&calendar_query_function);
1597         ast_custom_function_register(&calendar_query_result_function);
1598         ast_custom_function_register(&calendar_write_function);
1599         ast_cli_register_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
1600
1601         ast_devstate_prov_add("Calendar", calendarstate);
1602
1603         /* Since other modules depend on this, disable unloading */
1604         ast_module_ref(ast_module_info->self);
1605
1606         return 0;
1607 }
1608 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Asterisk Calendar integration",
1609                 .load = load_module,
1610                 .unload = unload_module,
1611                 .reload = reload,
1612         );