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