Sat Mar 26 11:08:02 2011

Asterisk developer's documentation


res_calendar.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2008 - 2009, Digium, Inc.
00005  *
00006  * Terry Wilson <twilson@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  * \brief Calendaring API
00021  * 
00022  * \todo Support responding to a meeting invite
00023  * \todo Support writing attendees
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 284849 $")
00029 
00030 #include "asterisk/_private.h"
00031 #include "asterisk/calendar.h"
00032 #include "asterisk/utils.h"
00033 #include "asterisk/astobj2.h"
00034 #include "asterisk/module.h"
00035 #include "asterisk/config.h"
00036 #include "asterisk/channel.h"
00037 #include "asterisk/devicestate.h"
00038 #include "asterisk/linkedlists.h"
00039 #include "asterisk/sched.h"
00040 #include "asterisk/dial.h"
00041 #include "asterisk/cli.h"
00042 #include "asterisk/pbx.h"
00043 #include "asterisk/app.h"
00044 
00045 /*** DOCUMENTATION
00046    <function name="CALENDAR_BUSY" language="en_US">
00047       <synopsis>
00048          Determine if the calendar is marked busy at this time.
00049       </synopsis>
00050       <syntax>
00051          <parameter name="calendar" required="true" />
00052       </syntax>
00053       <description>
00054          <para>Check the specified calendar's current busy status.</para>
00055       </description>
00056    </function>
00057    <function name="CALENDAR_EVENT" language="en_US">
00058       <synopsis>
00059          Get calendar event notification data from a notification call.
00060       </synopsis>
00061       <syntax>
00062          <parameter name="field" required="true">
00063             <enumlist>
00064                <enum name="summary"><para>The VEVENT SUMMARY property or Exchange event 'subject'</para></enum>
00065                <enum name="description"><para>The text description of the event</para></enum>
00066                <enum name="organizer"><para>The organizer of the event</para></enum>
00067                <enum name="location"><para>The location of the eventt</para></enum>
00068                <enum name="categories"><para>The categories of the event</para></enum>
00069                <enum name="priority"><para>The priority of the event</para></enum>
00070                <enum name="calendar"><para>The name of the calendar associated with the event</para></enum>
00071                <enum name="uid"><para>The unique identifier for this event</para></enum>
00072                <enum name="start"><para>The start time of the event</para></enum>
00073                <enum name="end"><para>The end time of the event</para></enum>
00074                <enum name="busystate"><para>The busy state of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
00075             </enumlist>
00076          </parameter>
00077       </syntax>
00078       <description>
00079          <para>Whenever a calendar event notification call is made, the event data
00080          may be accessed with this function.</para>
00081       </description>
00082    </function>
00083    <function name="CALENDAR_QUERY" language="en_US">
00084       <synopsis>Query a calendar server and store the data on a channel
00085       </synopsis>
00086       <syntax>
00087          <parameter name="calendar" required="true">
00088             <para>The calendar that should be queried</para>
00089          </parameter>
00090          <parameter name="start" required="false">
00091             <para>The start time of the query (in seconds since epoch)</para>
00092          </parameter>
00093          <parameter name="end" required="false">
00094             <para>The end time of the query (in seconds since epoch)</para>
00095          </parameter>
00096       </syntax>
00097       <description>
00098          <para>Get a list of events in the currently accessible timeframe of the <replaceable>calendar</replaceable>
00099          The function returns the id for accessing the result with CALENDAR_QUERY_RESULT()</para>
00100       </description>
00101    </function>
00102    <function name="CALENDAR_QUERY_RESULT" language="en_US">
00103       <synopsis>
00104          Retrieve data from a previously run CALENDAR_QUERY() call
00105       </synopsis>
00106       <syntax>
00107          <parameter name="id" required="true">
00108             <para>The query ID returned by <literal>CALENDAR_QUERY</literal></para>
00109          </parameter>
00110          <parameter name="field" required="true">
00111             <enumlist>
00112                <enum name="getnum"><para>number of events occurring during time range</para></enum>
00113                <enum name="summary"><para>A summary of the event</para></enum>
00114                <enum name="description"><para>The full event description</para></enum>
00115                <enum name="organizer"><para>The event organizer</para></enum>
00116                <enum name="location"><para>The event location</para></enum>
00117                <enum name="categories"><para>The categories of the event</para></enum>
00118                <enum name="priority"><para>The priority of the event</para></enum>
00119                <enum name="calendar"><para>The name of the calendar associted with the event</para></enum>
00120                <enum name="uid"><para>The unique identifier for the event</para></enum>
00121                <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
00122                <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
00123                <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
00124             </enumlist>
00125          </parameter>
00126          <parameter name="entry" required="false" default="1">
00127             <para>Return data from a specific event returned by the query</para>
00128          </parameter>
00129       </syntax>
00130       <description>
00131          <para>After running CALENDAR_QUERY and getting a result <replaceable>id</replaceable>, calling
00132          <literal>CALENDAR_QUERY</literal> with that <replaceable>id</replaceable> and a <replaceable>field</replaceable>
00133          will return the data for that field. If multiple events matched the query, and <replaceable>entry</replaceable>
00134          is provided, information from that event will be returned.</para>
00135       </description>
00136    </function>
00137    <function name="CALENDAR_WRITE" language="en_US">
00138       <synopsis>Write an event to a calendar</synopsis>
00139       <syntax>
00140          <parameter name="calendar" required="true">
00141             <para>The calendar to write to</para>
00142          </parameter>
00143          <parameter name="field" multiple="true" required="true">
00144             <enumlist>
00145                <enum name="summary"><para>A summary of the event</para></enum>
00146                <enum name="description"><para>The full event description</para></enum>
00147                <enum name="organizer"><para>The event organizer</para></enum>
00148                <enum name="location"><para>The event location</para></enum>
00149                <enum name="categories"><para>The categories of the event</para></enum>
00150                <enum name="priority"><para>The priority of the event</para></enum>
00151                <enum name="uid"><para>The unique identifier for the event</para></enum>
00152                <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
00153                <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
00154                <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
00155             </enumlist>
00156          </parameter>
00157       </syntax>
00158       <description>
00159          <para>Example: CALENDAR_WRITE(calendar,field1,field2,field3)=val1,val2,val3</para>
00160          <para>The field and value arguments can easily be set/passed using the HASHKEYS() and HASH() functions</para>
00161       </description>
00162    </function>
00163 
00164 ***/
00165 #define CALENDAR_BUCKETS 19
00166 
00167 static struct ao2_container *calendars;
00168 static struct sched_context *sched;
00169 static pthread_t refresh_thread = AST_PTHREADT_NULL;
00170 static ast_mutex_t refreshlock;
00171 static ast_cond_t refresh_condition;
00172 static ast_mutex_t reloadlock;
00173 
00174 static void event_notification_destroy(void *data);
00175 static void *event_notification_duplicate(void *data);
00176 static void eventlist_destroy(void *data);
00177 static void *eventlist_duplicate(void *data);
00178 
00179 static const struct ast_datastore_info event_notification_datastore = {
00180    .type = "EventNotification",
00181    .destroy = event_notification_destroy,
00182    .duplicate = event_notification_duplicate,
00183 };
00184 
00185 static const struct ast_datastore_info eventlist_datastore_info = {
00186    .type = "CalendarEventList",
00187    .destroy = eventlist_destroy,
00188    .duplicate = eventlist_duplicate,
00189 };
00190 
00191 struct evententry {
00192    struct ast_calendar_event *event;
00193    AST_LIST_ENTRY(evententry) list;
00194 };
00195 
00196 static AST_LIST_HEAD_STATIC(techs, ast_calendar_tech);
00197 AST_LIST_HEAD_NOLOCK(eventlist, evententry); /* define the type */
00198 
00199 static struct ast_config *calendar_config;
00200 AST_RWLOCK_DEFINE_STATIC(config_lock);
00201 
00202 const struct ast_config *ast_calendar_config_acquire(void)
00203 {
00204    ast_rwlock_rdlock(&config_lock);
00205 
00206    if (!calendar_config) {
00207       ast_rwlock_unlock(&config_lock);
00208       return NULL;
00209    }
00210 
00211    return calendar_config;
00212 }
00213 
00214 void ast_calendar_config_release(void)
00215 {
00216    ast_rwlock_unlock(&config_lock);
00217 }
00218 
00219 static struct ast_calendar *unref_calendar(struct ast_calendar *cal)
00220 {
00221    ao2_ref(cal, -1);
00222    return NULL;
00223 }
00224 
00225 static int calendar_hash_fn(const void *obj, const int flags)
00226 {
00227    const struct ast_calendar *cal = obj;
00228    return ast_str_case_hash(cal->name);
00229 }
00230 
00231 static int calendar_cmp_fn(void *obj, void *arg, int flags)
00232 {
00233    const struct ast_calendar *one = obj, *two = arg;
00234    return !strcasecmp(one->name, two->name) ? CMP_MATCH | CMP_STOP: 0;
00235 }
00236 
00237 static struct ast_calendar *find_calendar(const char *name)
00238 {
00239    struct ast_calendar tmp = {
00240       .name = name,
00241    };
00242    return ao2_find(calendars, &tmp, OBJ_POINTER);
00243 }
00244 
00245 static int event_hash_fn(const void *obj, const int flags)
00246 {
00247    const struct ast_calendar_event *event = obj;
00248    return ast_str_hash(event->uid);
00249 }
00250 
00251 static int event_cmp_fn(void *obj, void *arg, int flags)
00252 {
00253    const struct ast_calendar_event *one = obj, *two = arg;
00254    return !strcmp(one->uid, two->uid) ? CMP_MATCH | CMP_STOP : 0;
00255 }
00256 
00257 static struct ast_calendar_event *find_event(struct ao2_container *events, const char *uid)
00258 {
00259    struct ast_calendar_event tmp = {
00260       .uid = uid,
00261    };
00262    return ao2_find(events, &tmp, OBJ_POINTER);
00263 }
00264 
00265 struct ast_calendar_event *ast_calendar_unref_event(struct ast_calendar_event *event)
00266 {
00267    ao2_ref(event, -1);
00268    return NULL;
00269 }
00270 
00271 static void calendar_destructor(void *obj)
00272 {
00273    struct ast_calendar *cal = obj;
00274 
00275    ast_debug(3, "Destroying calendar %s\n", cal->name);
00276 
00277    ao2_lock(cal);
00278    cal->unloading = 1;
00279    ast_cond_signal(&cal->unload);
00280    pthread_join(cal->thread, NULL);
00281    if (cal->tech_pvt) {
00282       cal->tech_pvt = cal->tech->unref_calendar(cal->tech_pvt);
00283    }
00284    ast_calendar_clear_events(cal);
00285    ast_string_field_free_memory(cal);
00286    ao2_ref(cal->events, -1);
00287    ao2_unlock(cal);
00288 }
00289 
00290 static void eventlist_destructor(void *obj)
00291 {
00292    struct eventlist *events = obj;
00293    struct evententry *entry;
00294 
00295    while ((entry = AST_LIST_REMOVE_HEAD(events, list))) {
00296       ao2_ref(entry->event, -1);
00297       ast_free(entry);
00298    }
00299 }
00300 
00301 static int calendar_busy_callback(void *obj, void *arg, int flags)
00302 {
00303    struct ast_calendar_event *event = obj;
00304    int *is_busy = arg;
00305    struct timeval tv = ast_tvnow();
00306 
00307    if (tv.tv_sec >= event->start && tv.tv_sec <= event->end && event->busy_state > AST_CALENDAR_BS_FREE) {
00308       *is_busy = 1;
00309       return CMP_STOP;
00310    }
00311 
00312    return 0;
00313 }
00314 
00315 static int calendar_is_busy(struct ast_calendar *cal)
00316 {
00317    int is_busy = 0;
00318 
00319    ao2_callback(cal->events, OBJ_NODATA, calendar_busy_callback, &is_busy);
00320 
00321    return is_busy;
00322 }
00323 
00324 static enum ast_device_state calendarstate(const char *data)
00325 {
00326    struct ast_calendar *cal;
00327 
00328    if (ast_strlen_zero(data) || (!(cal = find_calendar(data)))) {
00329       return AST_DEVICE_INVALID;
00330    }
00331 
00332    if (cal->tech->is_busy) {
00333       return cal->tech->is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
00334    }
00335 
00336    return calendar_is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
00337 }
00338 
00339 static struct ast_calendar *build_calendar(struct ast_config *cfg, const char *cat, const struct ast_calendar_tech *tech)
00340 {
00341    struct ast_calendar *cal;
00342    struct ast_variable *v;
00343    int new_calendar = 0;
00344 
00345    if (!(cal = find_calendar(cat))) {
00346       new_calendar = 1;
00347       if (!(cal = ao2_alloc(sizeof(*cal), calendar_destructor))) {
00348          ast_log(LOG_ERROR, "Could not allocate calendar structure. Stopping.\n");
00349          return NULL;
00350       }
00351 
00352       if (!(cal->events = ao2_container_alloc(CALENDAR_BUCKETS, event_hash_fn, event_cmp_fn))) {
00353          ast_log(LOG_ERROR, "Could not allocate events container for %s\n", cat);
00354          cal = unref_calendar(cal);
00355          return NULL;
00356       }
00357 
00358       if (ast_string_field_init(cal, 32)) {
00359          ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", cat);
00360          cal = unref_calendar(cal);
00361          return NULL;
00362       }
00363    } else {
00364       cal->pending_deletion = 0;
00365    }
00366 
00367    ast_string_field_set(cal, name, cat);
00368    cal->tech = tech;
00369 
00370    cal->refresh = 3600;
00371    cal->timeframe = 60;
00372 
00373    for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
00374       if (!strcasecmp(v->name, "autoreminder")) {
00375          cal->autoreminder = atoi(v->value);
00376       } else if (!strcasecmp(v->name, "channel")) {
00377          ast_string_field_set(cal, notify_channel, v->value);
00378       } else if (!strcasecmp(v->name, "context")) {
00379          ast_string_field_set(cal, notify_context, v->value);
00380       } else if (!strcasecmp(v->name, "extension")) {
00381          ast_string_field_set(cal, notify_extension, v->value);
00382       } else if (!strcasecmp(v->name, "waittime")) {
00383          cal->notify_waittime = atoi(v->value);
00384       } else if (!strcasecmp(v->name, "app")) {
00385          ast_string_field_set(cal, notify_app, v->value);
00386       } else if (!strcasecmp(v->name, "appdata")) {
00387          ast_string_field_set(cal, notify_appdata, v->value);
00388       } else if (!strcasecmp(v->name, "refresh")) {
00389          cal->refresh = atoi(v->value);
00390       } else if (!strcasecmp(v->name, "timeframe")) {
00391          cal->timeframe = atoi(v->value);
00392       }
00393    }
00394 
00395    if (new_calendar) {
00396       cal->thread = AST_PTHREADT_NULL;
00397       ast_cond_init(&cal->unload, NULL);
00398       ao2_link(calendars, cal);
00399       if (ast_pthread_create(&cal->thread, NULL, cal->tech->load_calendar, cal)) {
00400          /* If we start failing to create threads, go ahead and return NULL
00401           * and the tech module will be unregistered
00402           */ 
00403          ao2_unlink(calendars, cal);
00404          cal = unref_calendar(cal);
00405       }
00406    }
00407 
00408    return cal;
00409 }
00410 
00411 static int load_tech_calendars(struct ast_calendar_tech *tech)
00412 {
00413    struct ast_calendar *cal;
00414    const char *cat = NULL;
00415    const char *val;
00416 
00417    if (!calendar_config) {
00418       ast_log(LOG_WARNING, "Calendar support disabled, not loading %s calendar module\n", tech->type);
00419       return -1;
00420    }
00421 
00422    ast_rwlock_wrlock(&config_lock);
00423    while ((cat = ast_category_browse(calendar_config, cat))) {
00424       if (!strcasecmp(cat, "general")) {
00425          continue;
00426       }
00427 
00428       if (!(val = ast_variable_retrieve(calendar_config, cat, "type")) || strcasecmp(val, tech->type)) {
00429          continue;
00430       }
00431 
00432       /* A serious error occurred loading calendars from this tech and it should be disabled */
00433       if (!(cal = build_calendar(calendar_config, cat, tech))) {
00434          ast_calendar_unregister(tech);
00435          ast_rwlock_unlock(&config_lock);
00436          return -1;
00437       }
00438 
00439       cal = unref_calendar(cal);
00440    }
00441 
00442    ast_rwlock_unlock(&config_lock);
00443 
00444    return 0;
00445 }
00446 
00447 int ast_calendar_register(struct ast_calendar_tech *tech)
00448 {
00449    struct ast_calendar_tech *iter;
00450 
00451    AST_LIST_LOCK(&techs);
00452    AST_LIST_TRAVERSE(&techs, iter, list) {
00453       if(!strcasecmp(tech->type, iter->type)) {
00454          ast_log(LOG_WARNING, "Already have a handler for calendar type '%s'\n", tech->type);
00455          AST_LIST_UNLOCK(&techs);
00456          return -1;
00457       }
00458    }
00459    AST_LIST_INSERT_HEAD(&techs, tech, list);
00460    AST_LIST_UNLOCK(&techs);
00461 
00462    ast_verb(2, "Registered calendar type '%s' (%s)\n", tech->type, tech->description);
00463 
00464    return load_tech_calendars(tech);
00465 }
00466 
00467 static int match_caltech_cb(void *user_data, void *arg, int flags)
00468 {
00469    struct ast_calendar *cal = user_data;
00470    struct ast_calendar_tech *tech = arg;
00471 
00472    if (cal->tech == tech) {
00473       return CMP_MATCH;
00474    }
00475 
00476    return 0;
00477 }
00478 
00479 void ast_calendar_unregister(struct ast_calendar_tech *tech)
00480 {
00481    struct ast_calendar_tech *iter;
00482 
00483    AST_LIST_LOCK(&techs);
00484    AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, iter, list) {
00485       if (iter != tech) {
00486          continue;
00487       }
00488 
00489       ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, match_caltech_cb, tech);
00490 
00491       AST_LIST_REMOVE_CURRENT(list);
00492       ast_verb(2, "Unregistered calendar type '%s'\n", tech->type);
00493       break;
00494    }
00495    AST_LIST_TRAVERSE_SAFE_END;
00496    AST_LIST_UNLOCK(&techs);
00497 
00498 }
00499 
00500 static void calendar_event_destructor(void *obj)
00501 {
00502    struct ast_calendar_event *event = obj;
00503    struct ast_calendar_attendee *attendee;
00504 
00505    ast_debug(3, "Destroying event for calendar '%s'\n", event->owner->name);
00506    ast_string_field_free_memory(event);
00507    while ((attendee = AST_LIST_REMOVE_HEAD(&event->attendees, next))) {
00508       if (attendee->data) {
00509          ast_free(attendee->data);
00510       }
00511       ast_free(attendee);
00512    }
00513 }
00514 
00515 /* This is only called from ao2_callbacks that are going to unref the event for us,
00516  * so we don't unref the event here.  */
00517 static struct ast_calendar_event *destroy_event(struct ast_calendar_event *event)
00518 {
00519    if (event->notify_sched > -1 && ast_sched_del(sched, event->notify_sched)) {
00520       ast_debug(3, "Notification running, can't delete sched entry\n");
00521    }
00522    if (event->bs_start_sched > -1 && ast_sched_del(sched, event->bs_start_sched)) {
00523       ast_debug(3, "Devicestate update (start) running, can't delete sched entry\n");
00524    }
00525    if (event->bs_end_sched > -1 && ast_sched_del(sched, event->bs_end_sched)) {
00526       ast_debug(3, "Devicestate update (end) running, can't delete sched entry\n");
00527    }
00528 
00529    /* If an event is being deleted and we've fired an event changing the status at the beginning,
00530     * but haven't hit the end event yet, go ahead and set the devicestate to the current busy status */
00531    if (event->bs_start_sched < 0 && event->bs_end_sched >= 0) {
00532       if (!calendar_is_busy(event->owner)) {
00533          ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Calendar:%s", event->owner->name);
00534       } else {
00535          ast_devstate_changed(AST_DEVICE_BUSY, "Calendar:%s", event->owner->name);
00536       }
00537    }
00538 
00539    return NULL;
00540 }
00541 
00542 static int clear_events_cb(void *user_data, void *arg, int flags)
00543 {
00544    struct ast_calendar_event *event = user_data;
00545 
00546    event = destroy_event(event);
00547 
00548    return CMP_MATCH;
00549 }
00550 
00551 void ast_calendar_clear_events(struct ast_calendar *cal)
00552 {
00553    ast_debug(3, "Clearing all events for calendar %s\n", cal->name);
00554 
00555    ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, clear_events_cb, NULL);
00556 }
00557 
00558 struct ast_calendar_event *ast_calendar_event_alloc(struct ast_calendar *cal)
00559 {
00560    struct ast_calendar_event *event;
00561    if (!(event = ao2_alloc(sizeof(*event), calendar_event_destructor))) {
00562       return NULL;
00563    }
00564 
00565    if (ast_string_field_init(event, 32)) {
00566       event = ast_calendar_unref_event(event);
00567       return NULL;
00568    }
00569 
00570    event->owner = cal;
00571    event->notify_sched = -1;
00572    event->bs_start_sched = -1;
00573    event->bs_end_sched = -1;
00574 
00575    AST_LIST_HEAD_INIT_NOLOCK(&event->attendees);
00576 
00577    return event;
00578 }
00579 
00580 struct ao2_container *ast_calendar_event_container_alloc(void)
00581 {
00582    return ao2_container_alloc(CALENDAR_BUCKETS, event_hash_fn, event_cmp_fn);
00583 }
00584 
00585 static void event_notification_destroy(void *data)
00586 {
00587    struct ast_calendar_event *event = data;
00588 
00589    event = ast_calendar_unref_event(event);
00590 
00591 }
00592 
00593 static void *event_notification_duplicate(void *data)
00594 {
00595    struct ast_calendar_event *event = data;
00596 
00597    if (!event) {
00598       return NULL;
00599    }
00600 
00601    ao2_ref(event, +1);
00602 
00603    return event;
00604 }
00605 
00606 /*! \brief Generate 32 byte random string (stolen from chan_sip.c)*/
00607 static char *generate_random_string(char *buf, size_t size)
00608 {
00609    long val[4];
00610    int x;
00611 
00612    for (x = 0; x < 4; x++) {
00613       val[x] = ast_random();
00614    }
00615    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
00616 
00617    return buf;
00618 }
00619 
00620 static int null_chan_write(struct ast_channel *chan, struct ast_frame *frame)
00621 {
00622    return 0;
00623 }
00624 
00625 static const struct ast_channel_tech null_tech = {
00626         .type = "NULL",
00627         .description = "Null channel (should not see this)",
00628       .write = null_chan_write,
00629 };
00630 
00631 static void *do_notify(void *data)
00632 {
00633    struct ast_calendar_event *event = data;
00634    struct ast_dial *dial = NULL;
00635    struct ast_str *apptext = NULL;
00636    struct ast_datastore *datastore;
00637    enum ast_dial_result res;
00638    struct ast_channel *chan = NULL;
00639    char *tech, *dest;
00640    char buf[8];
00641 
00642    tech = ast_strdupa(event->owner->notify_channel);
00643 
00644    if ((dest = strchr(tech, '/'))) {
00645       *dest = '\0';
00646       dest++;
00647    } else {
00648       ast_log(LOG_WARNING, "Channel should be in form Tech/Dest (was '%s')\n", tech);
00649       goto notify_cleanup;
00650    }
00651 
00652    if (!(dial = ast_dial_create())) {
00653       ast_log(LOG_ERROR, "Could not create dial structure\n");
00654       goto notify_cleanup;
00655    }
00656 
00657    if (ast_dial_append(dial, tech, dest) < 0) {
00658       ast_log(LOG_ERROR, "Could not append channel\n");
00659       goto notify_cleanup;
00660    }
00661 
00662    ast_dial_set_global_timeout(dial, event->owner->notify_waittime);
00663    generate_random_string(buf, sizeof(buf));
00664 
00665    if (!(chan = ast_channel_alloc(1, AST_STATE_DOWN, 0, 0, 0, 0, 0, 0, 0, "Calendar/%s-%s", event->owner->name, buf))) {
00666       ast_log(LOG_ERROR, "Could not allocate notification channel\n");
00667       goto notify_cleanup;
00668    }
00669 
00670    chan->tech = &null_tech;
00671    chan->nativeformats = chan->writeformat = chan->rawwriteformat =
00672       chan->readformat = chan->rawreadformat = AST_FORMAT_SLINEAR;
00673 
00674    if (!(datastore = ast_datastore_alloc(&event_notification_datastore, NULL))) {
00675       ast_log(LOG_ERROR, "Could not allocate datastore, notification not being sent!\n");
00676       goto notify_cleanup;
00677    }
00678 
00679    datastore->data = event;
00680    datastore->inheritance = DATASTORE_INHERIT_FOREVER;
00681 
00682    ao2_ref(event, +1);
00683    res = ast_channel_datastore_add(chan, datastore);
00684 
00685    if (!(apptext = ast_str_create(32))) {
00686       goto notify_cleanup;
00687    }
00688 
00689    if (!ast_strlen_zero(event->owner->notify_app)) {
00690       ast_str_set(&apptext, 0, "%s,%s", event->owner->notify_app, event->owner->notify_appdata);
00691       ast_dial_option_global_enable(dial, AST_DIAL_OPTION_ANSWER_EXEC, ast_str_buffer(apptext));
00692    } else {
00693    }
00694 
00695    ast_verb(3, "Dialing %s for notification on calendar %s\n", event->owner->notify_channel, event->owner->name);
00696    res = ast_dial_run(dial, chan, 0);
00697 
00698    if (res != AST_DIAL_RESULT_ANSWERED) {
00699       ast_verb(3, "Notification call for %s was not completed\n", event->owner->name);
00700    } else {
00701       struct ast_channel *answered;
00702 
00703       answered = ast_dial_answered_steal(dial);
00704       if (ast_strlen_zero(event->owner->notify_app)) {
00705          ast_copy_string(answered->context, event->owner->notify_context, sizeof(answered->context));
00706          ast_copy_string(answered->exten, event->owner->notify_extension, sizeof(answered->exten));
00707          answered->priority = 1;
00708          ast_pbx_run(answered);
00709       }
00710    }
00711 
00712 notify_cleanup:
00713    if (apptext) {
00714       ast_free(apptext);
00715    }
00716    if (dial) {
00717       ast_dial_destroy(dial);
00718    }
00719    if (chan) {
00720       ast_channel_release(chan);
00721    }
00722 
00723    event = ast_calendar_unref_event(event);
00724 
00725    return NULL;
00726 }
00727 
00728 static int calendar_event_notify(const void *data)
00729 {
00730    struct ast_calendar_event *event = (void *)data;
00731    int res = -1;
00732    pthread_t notify_thread = AST_PTHREADT_NULL;
00733 
00734    if (!(event && event->owner)) {
00735       ast_log(LOG_ERROR, "Extremely low-cal...in fact cal is NULL!\n");
00736       return res;
00737    }
00738 
00739    ao2_ref(event, +1);
00740    event->notify_sched = -1;
00741 
00742    if (ast_pthread_create_background(&notify_thread, NULL, do_notify, event) < 0) {
00743       ast_log(LOG_ERROR, "Could not create notification thread\n");
00744       return res;
00745    }
00746 
00747    res = 0;
00748 
00749    return res;
00750 }
00751 
00752 static int calendar_devstate_change(const void *data)
00753 {
00754    struct ast_calendar_event *event = (struct ast_calendar_event *)data;
00755    struct timeval now = ast_tvnow();
00756    int is_end_event;
00757 
00758    if (!event) {
00759       ast_log(LOG_WARNING, "Event was NULL!\n");
00760       return 0;
00761    }
00762 
00763    ao2_ref(event, +1);
00764 
00765    is_end_event = event->end <= now.tv_sec;
00766 
00767    if (is_end_event) {
00768       event->bs_end_sched = -1;
00769    } else {
00770       event->bs_start_sched = -1;
00771    }
00772 
00773    /* We can have overlapping events, so ignore the event->busy_state and check busy state
00774     * based on all events in the calendar */
00775    if (!calendar_is_busy(event->owner)) {
00776       ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Calendar:%s", event->owner->name);
00777    } else {
00778       ast_devstate_changed(AST_DEVICE_BUSY, "Calendar:%s", event->owner->name);
00779    }
00780 
00781    event = ast_calendar_unref_event(event);
00782 
00783    return 0;
00784 }
00785 
00786 static void copy_event_data(struct ast_calendar_event *dst, struct ast_calendar_event *src)
00787 {
00788    struct ast_calendar_attendee *attendee;
00789 
00790    ast_string_field_set(dst, summary, src->summary);
00791    ast_string_field_set(dst, description, src->description);
00792    ast_string_field_set(dst, organizer, src->organizer);
00793    ast_string_field_set(dst, location, src->location);
00794    ast_string_field_set(dst, uid, src->uid);
00795    ast_string_field_set(dst, categories, src->categories);
00796    dst->priority = src->priority;
00797    dst->owner = src->owner;
00798    dst->start = src->start;
00799    dst->end = src->end;
00800    dst->alarm = src->alarm;
00801    dst->busy_state = src->busy_state;
00802 
00803    /* Delete any existing attendees */
00804    while ((attendee = AST_LIST_REMOVE_HEAD(&dst->attendees, next))) {
00805       ast_free(attendee);
00806    }
00807 
00808    /* Copy over the new attendees */
00809    while ((attendee = AST_LIST_REMOVE_HEAD(&src->attendees, next))) {
00810       AST_LIST_INSERT_TAIL(&dst->attendees, attendee, next);
00811    }
00812 }
00813 
00814 static int schedule_calendar_event(struct ast_calendar *cal, struct ast_calendar_event *old_event, struct ast_calendar_event *cmp_event)
00815 {
00816    struct timeval now = ast_tvnow();
00817    struct ast_calendar_event *event;
00818    time_t alarm_notify_sched = 0, devstate_sched_start, devstate_sched_end;
00819    int changed = 0;
00820 
00821    event = cmp_event ? cmp_event : old_event;
00822 
00823    ao2_lock(event);
00824    if (!cmp_event || old_event->alarm != event->alarm) {
00825       changed = 1;
00826       if (cal->autoreminder) {
00827          alarm_notify_sched = (event->start - (60 * cal->autoreminder) - now.tv_sec) * 1000;
00828       } else if (event->alarm) {
00829          alarm_notify_sched = (event->alarm - now.tv_sec) * 1000;
00830       }
00831 
00832       /* For now, send the notification if we missed it, but the meeting hasn't happened yet */
00833       if (event->start >=  now.tv_sec) {
00834          if (alarm_notify_sched <= 0) {
00835             alarm_notify_sched = 1;
00836          }
00837          ast_mutex_lock(&refreshlock);
00838          AST_SCHED_REPLACE(old_event->notify_sched, sched, alarm_notify_sched, calendar_event_notify, old_event);
00839          ast_mutex_unlock(&refreshlock);
00840          ast_debug(3, "Calendar alarm event notification scheduled to happen in %ld ms\n", (long) alarm_notify_sched);
00841       }
00842    }
00843 
00844    if (!cmp_event || old_event->start != event->start) {
00845       changed = 1;
00846       devstate_sched_start = (event->start - now.tv_sec) * 1000;
00847 
00848       if (devstate_sched_start < 1) {
00849          devstate_sched_start = 1;
00850       }
00851 
00852       ast_mutex_lock(&refreshlock);
00853       AST_SCHED_REPLACE(old_event->bs_start_sched, sched, devstate_sched_start, calendar_devstate_change, old_event);
00854       ast_mutex_unlock(&refreshlock);
00855       ast_debug(3, "Calendar bs_start event notification scheduled to happen in %ld ms\n", (long) devstate_sched_start);
00856    }
00857 
00858    if (!cmp_event || old_event->end != event->end) {
00859       changed = 1;
00860       devstate_sched_end = (event->end - now.tv_sec) * 1000;
00861       ast_mutex_lock(&refreshlock);
00862       AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
00863       ast_mutex_unlock(&refreshlock);
00864       ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", (long) devstate_sched_end);
00865    }
00866 
00867    if (changed) {
00868       ast_cond_signal(&refresh_condition);
00869    }
00870 
00871    ao2_unlock(event);
00872 
00873    return 0;
00874 }
00875 
00876 static int merge_events_cb(void *obj, void *arg, int flags)
00877 {
00878    struct ast_calendar_event *old_event = obj, *new_event;
00879    struct ao2_container *new_events = arg;
00880 
00881    /* If we don't find the old_event in new_events, then we can safely delete the old_event */
00882    if (!(new_event = find_event(new_events, old_event->uid))) {
00883       old_event = destroy_event(old_event);
00884       return CMP_MATCH;
00885    }
00886 
00887    /* We have events to merge.  If any data that will affect a scheduler event has changed,
00888     * then we need to replace the scheduler event */
00889    schedule_calendar_event(old_event->owner, old_event, new_event);
00890 
00891    /* Since we don't want to mess with cancelling sched events and adding new ones, just
00892     * copy the internals of the new_event to the old_event */
00893    copy_event_data(old_event, new_event);
00894 
00895    /* Now we can go ahead and unlink the new_event from new_events and unref it so that only completely
00896     * new events remain in the container */
00897    ao2_unlink(new_events, new_event);
00898    new_event = ast_calendar_unref_event(new_event);
00899 
00900    return 0;
00901 }
00902 
00903 static int add_new_event_cb(void *obj, void *arg, int flags)
00904 {
00905    struct ast_calendar_event *new_event = obj;
00906    struct ao2_container *events = arg;
00907 
00908    ao2_link(events, new_event);
00909    schedule_calendar_event(new_event->owner, new_event, NULL);
00910    return CMP_MATCH;
00911 }
00912 
00913 void ast_calendar_merge_events(struct ast_calendar *cal, struct ao2_container *new_events)
00914 {
00915    /* Loop through all events attached to the calendar.  If there is a matching new event
00916     * merge its data over and handle any schedule changes that need to be made.  Then remove
00917     * the new_event from new_events so that we are left with only new_events that we can add later. */
00918    ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, merge_events_cb, new_events);
00919 
00920    /* Now, we should only have completely new events in new_events.  Loop through and add them */
00921    ao2_callback(new_events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, add_new_event_cb, cal->events);
00922 }
00923 
00924 
00925 static int load_config(void *data)
00926 {
00927    struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
00928    struct ast_config *tmpcfg;
00929 
00930    if (!(tmpcfg = ast_config_load2("calendar.conf", "calendar", config_flags)) ||
00931       tmpcfg == CONFIG_STATUS_FILEINVALID) {
00932       ast_log(LOG_ERROR, "Unable to load config calendar.conf\n");
00933       return -1;
00934    }
00935 
00936    if (tmpcfg == CONFIG_STATUS_FILEUNCHANGED) {
00937       return 0;
00938    }
00939 
00940    ast_rwlock_wrlock(&config_lock);
00941    if (calendar_config) {
00942       ast_config_destroy(calendar_config);
00943    }
00944 
00945    calendar_config = tmpcfg;
00946    ast_rwlock_unlock(&config_lock);
00947 
00948    return 0;
00949 }
00950 
00951 /*! \brief A dialplan function that can be used to determine the busy status of a calendar */
00952 static int calendar_busy_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
00953 {
00954    struct ast_calendar *cal;
00955 
00956    if (ast_strlen_zero(data)) {
00957       ast_log(LOG_WARNING, "CALENDAR_BUSY requires an argument: CALENDAR_BUSY(<calendar_name>)\n");
00958       return -1;
00959    }
00960 
00961    cal = find_calendar(data);
00962 
00963    if (!cal) {
00964       ast_log(LOG_WARNING, "Could not find calendar '%s'\n", data);
00965       return -1;
00966    }
00967 
00968    strcpy(buf, calendar_is_busy(cal) ? "1" : "0");
00969 
00970    return 0;
00971 }
00972 
00973 static struct ast_custom_function calendar_busy_function = {
00974     .name = "CALENDAR_BUSY",
00975     .read = calendar_busy_exec,
00976 };
00977 
00978 static int add_event_to_list(struct eventlist *events, struct ast_calendar_event *event, time_t start, time_t end)
00979 {
00980    struct evententry *entry, *iter;
00981    int event_startdiff = abs(start - event->start);
00982    int event_enddiff = abs(end - event->end);
00983    int i = 0;
00984 
00985    if (!(entry = ast_calloc(1, sizeof(*entry)))) {
00986       ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
00987       return -1;
00988    }
00989 
00990    entry->event = event;
00991    ao2_ref(event, +1);
00992 
00993    if (start == end) {
00994       AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
00995          int startdiff = abs(iter->event->start - start);
00996 
00997          ast_debug(10, "Comparing %s with startdiff %d to %s with startdiff %d\n", event->summary, event_startdiff, iter->event->summary, startdiff);
00998          ++i;
00999          if (startdiff > event_startdiff) {
01000             AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
01001             return i;
01002          }
01003          if (startdiff == event_startdiff) {
01004             int enddiff = abs(iter->event->end - end);
01005 
01006             if (enddiff > event_enddiff) {
01007                AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
01008                return i;
01009             }
01010             if (event_startdiff == enddiff) {
01011                if (strcmp(event->uid, iter->event->uid) < 0) {
01012                   AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
01013                   return i;
01014                }
01015             }
01016          }
01017       }
01018       AST_LIST_TRAVERSE_SAFE_END;
01019 
01020       AST_LIST_INSERT_TAIL(events, entry, list);
01021 
01022       return i;
01023    }
01024 
01025    AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
01026       ++i;
01027       if (iter->event->start > event->start) {
01028          AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
01029          return i;
01030       }
01031 
01032       if (iter->event->start == event->start) {
01033          if ((iter->event->end - iter->event->start) == (event->end - event->start)) {
01034             if (strcmp(event->uid, iter->event->uid) < 0) {
01035                AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
01036                return i;
01037             }
01038          }
01039          if ((iter->event->end - iter->event->start) < (event->end - event->start)) {
01040             AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
01041             return i;
01042          }
01043       }
01044    }
01045    AST_LIST_TRAVERSE_SAFE_END;
01046 
01047    AST_LIST_INSERT_TAIL(events, entry, list);
01048 
01049    return i;
01050 }
01051 
01052 static void eventlist_destroy(void *data)
01053 {
01054    struct eventlist *events = data;
01055 
01056    ao2_ref(events, -1);
01057 }
01058 
01059 static void *eventlist_duplicate(void *data)
01060 {
01061    struct eventlist *events = data;
01062 
01063    if (!events) {
01064       return NULL;
01065    }
01066 
01067    ao2_ref(events, +1);
01068 
01069    return events;
01070 }
01071 
01072 static int calendar_query_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
01073 {
01074    struct ast_calendar *cal;
01075    struct ao2_iterator i;
01076    struct ast_calendar_event *event;
01077    struct eventlist *events;
01078    time_t start = INT_MIN, end = INT_MAX;
01079    struct ast_datastore *eventlist_datastore;
01080    AST_DECLARE_APP_ARGS(args,
01081       AST_APP_ARG(calendar);
01082       AST_APP_ARG(start);
01083       AST_APP_ARG(end);
01084    );
01085 
01086    if (!chan) {
01087       ast_log(LOG_WARNING, "%s requires a channel to store the data on\n", cmd);
01088       return -1;
01089    }
01090 
01091    AST_STANDARD_APP_ARGS(args, data);
01092 
01093    if (ast_strlen_zero(args.calendar)) {
01094       ast_log(LOG_WARNING, "%s requires a calendar argument\n", cmd);
01095       return -1;
01096    }
01097 
01098    if (!(cal = find_calendar(args.calendar))) {
01099       ast_log(LOG_WARNING, "Unknown calendar '%s'\n", args.calendar);
01100       return -1;
01101    }
01102 
01103    if (!(events = ao2_alloc(sizeof(*events), eventlist_destructor))) {
01104       ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
01105       cal = unref_calendar(cal);
01106       return -1;
01107    }
01108 
01109    if (!ast_strlen_zero(args.start)) {
01110       start = atoi(args.start);
01111    }
01112 
01113    if (!ast_strlen_zero(args.end)) {
01114       end = atoi(args.end);
01115    }
01116 
01117    i = ao2_iterator_init(cal->events, 0);
01118    while ((event = ao2_iterator_next(&i))) {
01119       if (!(start > event->end || end < event->start)) {
01120          ast_debug(10, "%s (%ld - %ld) overlapped with (%ld - %ld)\n", event->summary, (long) event->start, (long) event->end, (long) start, (long) end);
01121          if (add_event_to_list(events, event, start, end) < 0) {
01122             event = ast_calendar_unref_event(event);
01123             ao2_iterator_destroy(&i);
01124             return -1;
01125          }
01126       }
01127 
01128       event = ast_calendar_unref_event(event);
01129    }
01130    ao2_iterator_destroy(&i);
01131 
01132    ast_channel_lock(chan);
01133    do {
01134       generate_random_string(buf, len);
01135    } while (ast_channel_datastore_find(chan, &eventlist_datastore_info, buf));
01136    ast_channel_unlock(chan);
01137 
01138    if (!(eventlist_datastore = ast_datastore_alloc(&eventlist_datastore_info, buf))) {
01139       ast_log(LOG_ERROR, "Could not allocate datastore!\n");
01140       return -1;
01141    }
01142 
01143    eventlist_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
01144    eventlist_datastore->data = events;
01145 
01146    ast_channel_lock(chan);
01147    ast_channel_datastore_add(chan, eventlist_datastore);
01148    ast_channel_unlock(chan);
01149 
01150    return 0;
01151 }
01152 
01153 static struct ast_custom_function calendar_query_function = {
01154     .name = "CALENDAR_QUERY",
01155     .read = calendar_query_exec,
01156 };
01157 
01158 static void calendar_join_attendees(struct ast_calendar_event *event, char *buf, size_t len)
01159 {
01160    struct ast_str *tmp;
01161    struct ast_calendar_attendee *attendee;
01162 
01163    if (!(tmp = ast_str_create(32))) {
01164       ast_log(LOG_ERROR, "Could not allocate memory for attendees!\n");
01165       return;
01166    }
01167 
01168    AST_LIST_TRAVERSE(&event->attendees, attendee, next) {
01169       ast_str_append(&tmp, 0, "%s%s", attendee == AST_LIST_FIRST(&event->attendees) ? "" : ",", attendee->data);
01170    }
01171 
01172    ast_copy_string(buf, ast_str_buffer(tmp), len);
01173    ast_free(tmp);
01174 }
01175 
01176 static int calendar_query_result_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
01177 {
01178    struct ast_datastore *datastore;
01179    struct eventlist *events;
01180    struct evententry *entry;
01181    int row = 1;
01182    size_t listlen = 0;
01183    AST_DECLARE_APP_ARGS(args,
01184       AST_APP_ARG(id);
01185       AST_APP_ARG(field);
01186       AST_APP_ARG(row);
01187    );
01188 
01189    if (!chan) {
01190       ast_log(LOG_WARNING, "%s requires a channel\n", cmd);
01191       return -1;
01192    }
01193 
01194    AST_STANDARD_APP_ARGS(args, data);
01195 
01196    if (ast_strlen_zero(args.id) || ast_strlen_zero(args.field)) {
01197       ast_log(LOG_WARNING, "%s requires an id and a field", cmd);
01198       return -1;
01199    }
01200 
01201    ast_channel_lock(chan);
01202    if (!(datastore = ast_channel_datastore_find(chan, &eventlist_datastore_info, args.id))) {
01203       ast_log(LOG_WARNING, "There is no event notification datastore with id '%s' on '%s'!\n", args.id, chan->name);
01204       ast_channel_unlock(chan);
01205       return -1;
01206    }
01207    ast_channel_unlock(chan);
01208 
01209    if (!(events = datastore->data)) {
01210       ast_log(LOG_WARNING, "The datastore contains no data!\n");
01211       return -1;
01212    }
01213 
01214    if (!ast_strlen_zero(args.row)) {
01215       row = atoi(args.row);
01216    }
01217 
01218    AST_LIST_TRAVERSE(events, entry, list) {
01219       listlen++;
01220    }
01221 
01222    if (!strcasecmp(args.field, "getnum")) {
01223       snprintf(buf, len, "%zu", listlen);
01224       return 0;
01225    }
01226 
01227    AST_LIST_TRAVERSE(events, entry, list) {
01228       if (--row) {
01229          continue;
01230       }
01231       if (!strcasecmp(args.field, "summary")) {
01232          ast_copy_string(buf, entry->event->summary, len);
01233       } else if (!strcasecmp(args.field, "description")) {
01234          ast_copy_string(buf, entry->event->description, len);
01235       } else if (!strcasecmp(args.field, "organizer")) {
01236          ast_copy_string(buf, entry->event->organizer, len);
01237       } else if (!strcasecmp(args.field, "location")) {
01238          ast_copy_string(buf, entry->event->location, len);
01239       } else if (!strcasecmp(args.field, "categories")) {
01240          ast_copy_string(buf, entry->event->categories, len);
01241       } else if (!strcasecmp(args.field, "priority")) {
01242          snprintf(buf, len, "%d", entry->event->priority);
01243       } else if (!strcasecmp(args.field, "calendar")) {
01244          ast_copy_string(buf, entry->event->owner->name, len);
01245       } else if (!strcasecmp(args.field, "uid")) {
01246          ast_copy_string(buf, entry->event->uid, len);
01247       } else if (!strcasecmp(args.field, "start")) {
01248          snprintf(buf, len, "%ld", (long) entry->event->start);
01249       } else if (!strcasecmp(args.field, "end")) {
01250          snprintf(buf, len, "%ld", (long) entry->event->end);
01251       } else if (!strcasecmp(args.field, "busystate")) {
01252          snprintf(buf, len, "%d", entry->event->busy_state);
01253       } else if (!strcasecmp(args.field, "attendees")) {
01254          calendar_join_attendees(entry->event, buf, len);
01255       } else {
01256          ast_log(LOG_WARNING, "Unknown field '%s'\n", args.field);
01257       }
01258       break;
01259    }
01260 
01261    return 0;
01262 }
01263 
01264 static struct ast_custom_function calendar_query_result_function = {
01265    .name = "CALENDAR_QUERY_RESULT",
01266    .read = calendar_query_result_exec,
01267 };
01268 
01269 static int calendar_write_exec(struct ast_channel *chan, const char *cmd, char *data, const char *value)
01270 {
01271    int i, j, ret = -1;
01272    char *val_dup = NULL;
01273    struct ast_calendar *cal = NULL;
01274    struct ast_calendar_event *event = NULL;
01275    struct timeval tv = ast_tvnow();
01276    AST_DECLARE_APP_ARGS(fields,
01277       AST_APP_ARG(field)[10];
01278    );
01279    AST_DECLARE_APP_ARGS(values,
01280       AST_APP_ARG(value)[10];
01281    );
01282 
01283    if (!(val_dup = ast_strdup(value))) {
01284       ast_log(LOG_ERROR, "Could not allocate memory for values\n");
01285       return -1;
01286    }
01287 
01288    AST_STANDARD_APP_ARGS(fields, data);
01289    AST_STANDARD_APP_ARGS(values, val_dup);
01290 
01291    /* XXX Eventually we will support unnamed calendars, so if we don't find one, we parse
01292     * for a calendar type and create it */
01293    if (!(cal = find_calendar(fields.field[0]))) {
01294       ast_log(LOG_WARNING, "Couldn't find calendar '%s'\n", fields.field[0]);
01295       goto write_cleanup;
01296    }
01297 
01298    if (!(cal->tech->write_event)) {
01299       ast_log(LOG_WARNING, "Calendar '%s' has no write function!\n", cal->name);
01300       goto write_cleanup;
01301    }
01302 
01303    if (!(event = ast_calendar_event_alloc(cal))) {
01304       goto write_cleanup;
01305    }
01306 
01307    if (ast_strlen_zero(fields.field[0])) {
01308       ast_log(LOG_WARNING, "CALENDAR_WRITE requires a calendar name!\n");
01309       goto write_cleanup;
01310    }
01311 
01312    if (fields.argc - 1 != values.argc) {
01313       ast_log(LOG_WARNING, "CALENDAR_WRITE should have the same number of fields (%d) and values (%d)!\n", fields.argc - 1, values.argc);
01314       goto write_cleanup;
01315    }
01316 
01317    event->owner = cal;
01318 
01319    for (i = 1, j = 0; i < fields.argc; i++, j++) {
01320       if (!strcasecmp(fields.field[i], "summary")) {
01321          ast_string_field_set(event, summary, values.value[j]);
01322       } else if (!strcasecmp(fields.field[i], "description")) {
01323          ast_string_field_set(event, description, values.value[j]);
01324       } else if (!strcasecmp(fields.field[i], "organizer")) {
01325          ast_string_field_set(event, organizer, values.value[j]);
01326       } else if (!strcasecmp(fields.field[i], "location")) {
01327          ast_string_field_set(event, location, values.value[j]);
01328       } else if (!strcasecmp(fields.field[i], "categories")) {
01329          ast_string_field_set(event, categories, values.value[j]);
01330       } else if (!strcasecmp(fields.field[i], "priority")) {
01331          event->priority = atoi(values.value[j]);
01332       } else if (!strcasecmp(fields.field[i], "uid")) {
01333          ast_string_field_set(event, uid, values.value[j]);
01334       } else if (!strcasecmp(fields.field[i], "start")) {
01335          event->start = atoi(values.value[j]);
01336       } else if (!strcasecmp(fields.field[i], "end")) {
01337          event->end = atoi(values.value[j]);
01338       } else if (!strcasecmp(fields.field[i], "busystate")) {
01339          event->busy_state = atoi(values.value[j]);
01340       } else {
01341          ast_log(LOG_WARNING, "Unknown calendar event field '%s'\n", fields.field[i]);
01342       }
01343    }
01344 
01345    if (!event->start) {
01346       event->start = tv.tv_sec;
01347    }
01348 
01349    if (!event->end) {
01350       event->end = tv.tv_sec;
01351    }
01352 
01353    if((ret = cal->tech->write_event(event))) {
01354       ast_log(LOG_WARNING, "Writing event to calendar '%s' failed!\n", cal->name);
01355    }
01356 
01357 write_cleanup:
01358    if (cal) {
01359       cal = unref_calendar(cal);
01360    }
01361    if (event) {
01362       event = ast_calendar_unref_event(event);
01363    }
01364    if (val_dup) {
01365       ast_free(val_dup);
01366    }
01367 
01368    return ret;
01369 }
01370 
01371 static struct ast_custom_function calendar_write_function = {
01372    .name = "CALENDAR_WRITE",
01373    .write = calendar_write_exec,
01374 };
01375 
01376 /*! \brief CLI command to list available calendars */
01377 static char *handle_show_calendars(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01378 {
01379 #define FORMAT "%-20.20s %-10.10s %-6.6s\n"
01380    struct ao2_iterator i;
01381    struct ast_calendar *cal;
01382 
01383    switch(cmd) {
01384    case CLI_INIT:
01385       e->command = "calendar show calendars";
01386       e->usage =
01387          "Usage: calendar show calendars\n"
01388          "       Lists all registered calendars.\n";
01389       return NULL;
01390    case CLI_GENERATE:
01391       return NULL;
01392    }
01393 
01394    ast_cli(a->fd, FORMAT, "Calendar", "Type", "Status");
01395    ast_cli(a->fd, FORMAT, "--------", "----", "------");
01396    i = ao2_iterator_init(calendars, 0);
01397    while ((cal = ao2_iterator_next(&i))) {
01398       ast_cli(a->fd, FORMAT, cal->name, cal->tech->type, calendar_is_busy(cal) ? "busy" : "free");
01399       cal = unref_calendar(cal);
01400    }
01401    ao2_iterator_destroy(&i);
01402 
01403    return CLI_SUCCESS;
01404 #undef FORMAT
01405 }
01406 
01407 static char *epoch_to_string(char *buf, size_t buflen, time_t epoch)
01408 {
01409    struct ast_tm tm;
01410    struct timeval tv = {
01411       .tv_sec = epoch,
01412    };
01413 
01414    if (!epoch) {
01415       *buf = '\0';
01416       return buf;
01417    }
01418    ast_localtime(&tv, &tm, NULL);
01419    ast_strftime(buf, buflen, "%F %r %z", &tm);
01420 
01421    return buf;
01422 }
01423 
01424 static char *handle_show_calendar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01425 {
01426 #define FORMAT "%-17.17s : %-20.20s\n"
01427 #define FORMAT2 "%-12.12s: %-40.60s\n"
01428    struct ao2_iterator i;
01429    struct ast_calendar *cal;
01430    struct ast_calendar_event *event;
01431    int which = 0;
01432    char *ret = NULL;
01433 
01434    switch(cmd) {
01435    case CLI_INIT:
01436       e->command = "calendar show calendar";
01437       e->usage =
01438          "Usage: calendar show calendar <calendar name>\n"
01439          "       Displays information about a calendar\n";
01440       return NULL;
01441 
01442    case CLI_GENERATE:
01443       if (a->pos != 3) {
01444          return NULL;
01445       }
01446       i = ao2_iterator_init(calendars, 0);
01447       while ((cal = ao2_iterator_next(&i))) {
01448          if (!strncasecmp(a->word, cal->name, strlen(a->word)) && ++which > a->n) {
01449             ret = ast_strdup(cal->name);
01450             cal = unref_calendar(cal);
01451             break;
01452          }
01453          cal = unref_calendar(cal);
01454       }
01455       ao2_iterator_destroy(&i);
01456       return ret;
01457    }
01458 
01459    if (a->argc != 4) {
01460       return CLI_SHOWUSAGE;
01461    }
01462 
01463    if (!(cal = find_calendar(a->argv[3]))) {
01464       return NULL;
01465    }
01466 
01467    ast_cli(a->fd, FORMAT, "Name", cal->name);
01468    ast_cli(a->fd, FORMAT, "Notify channel", cal->notify_channel);
01469    ast_cli(a->fd, FORMAT, "Notify context", cal->notify_context);
01470    ast_cli(a->fd, FORMAT, "Notify extension", cal->notify_extension);
01471    ast_cli(a->fd, FORMAT, "Notify application", cal->notify_app);
01472    ast_cli(a->fd, FORMAT, "Notify appdata", cal->notify_appdata);
01473    ast_cli(a->fd, "%-17.17s : %d\n", "Refresh time", cal->refresh);
01474    ast_cli(a->fd, "%-17.17s : %d\n", "Timeframe", cal->timeframe);
01475    ast_cli(a->fd, "%-17.17s : %d\n", "Autoreminder", cal->autoreminder);
01476    ast_cli(a->fd, "%s\n", "Events");
01477    ast_cli(a->fd, "%s\n", "------");
01478 
01479    i = ao2_iterator_init(cal->events, 0);
01480    while ((event = ao2_iterator_next(&i))) {
01481       char buf[100];
01482 
01483       ast_cli(a->fd, FORMAT2, "Summary", event->summary);
01484       ast_cli(a->fd, FORMAT2, "Description", event->description);
01485       ast_cli(a->fd, FORMAT2, "Organizer", event->organizer);
01486       ast_cli(a->fd, FORMAT2, "Location", event->location);
01487       ast_cli(a->fd, FORMAT2, "Cartegories", event->categories);
01488       ast_cli(a->fd, "%-12.12s: %d\n", "Priority", event->priority);
01489       ast_cli(a->fd, FORMAT2, "UID", event->uid);
01490       ast_cli(a->fd, FORMAT2, "Start", epoch_to_string(buf, sizeof(buf), event->start));
01491       ast_cli(a->fd, FORMAT2, "End", epoch_to_string(buf, sizeof(buf), event->end));
01492       ast_cli(a->fd, FORMAT2, "Alarm", epoch_to_string(buf, sizeof(buf), event->alarm));
01493       ast_cli(a->fd, "\n");
01494 
01495       event = ast_calendar_unref_event(event);
01496    }
01497    ao2_iterator_destroy(&i);
01498    cal = unref_calendar(cal);
01499    return CLI_SUCCESS;
01500 #undef FORMAT
01501 #undef FORMAT2
01502 }
01503 
01504 static char *handle_dump_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01505 {
01506    switch(cmd) {
01507    case CLI_INIT:
01508       e->command = "calendar dump sched";
01509       e->usage =
01510          "Usage: calendar dump sched\n"
01511          "       Dump the calendar sched context";
01512       return NULL;
01513 
01514    case CLI_GENERATE:
01515       return NULL;
01516    }
01517 
01518    ast_sched_dump(sched);
01519 
01520    return CLI_SUCCESS;
01521 }
01522 
01523 static struct ast_cli_entry calendar_cli[] = {
01524    AST_CLI_DEFINE(handle_show_calendar, "Display information about a calendar"),
01525    AST_CLI_DEFINE(handle_show_calendars, "Show registered calendars"),
01526    AST_CLI_DEFINE(handle_dump_sched, "Dump calendar sched context"),
01527 };
01528 
01529 static int calendar_event_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
01530 {
01531    struct ast_datastore *datastore;
01532    struct ast_calendar_event *event;
01533 
01534    if (ast_strlen_zero(data)) {
01535       ast_log(LOG_WARNING, "%s requires an argument\n", cmd);
01536       return -1;
01537    }
01538 
01539    ast_channel_lock(chan);
01540    if (!(datastore = ast_channel_datastore_find(chan, &event_notification_datastore, NULL))) {
01541       ast_log(LOG_WARNING, "There is no event notification datastore on '%s'!\n", chan->name);
01542       ast_channel_unlock(chan);
01543       return -1;
01544    }
01545    ast_channel_unlock(chan);
01546 
01547    if (!(event = datastore->data)) {
01548       ast_log(LOG_WARNING, "The datastore contains no data!\n");
01549       return -1;
01550    }
01551 
01552    if (!strcasecmp(data, "summary")) {
01553       ast_copy_string(buf, event->summary, len);
01554    } else if (!strcasecmp(data, "description")) {
01555       ast_copy_string(buf, event->description, len);
01556    } else if (!strcasecmp(data, "organizer")) {
01557       ast_copy_string(buf, event->organizer, len);
01558    } else if (!strcasecmp(data, "location")) {
01559       ast_copy_string(buf, event->location, len);
01560    } else if (!strcasecmp(data, "categories")) {
01561       ast_copy_string(buf, event->categories, len);
01562    } else if (!strcasecmp(data, "priority")) {
01563       snprintf(buf, len, "%d", event->priority);
01564    } else if (!strcasecmp(data, "calendar")) {
01565       ast_copy_string(buf, event->owner->name, len);
01566    } else if (!strcasecmp(data, "uid")) {
01567       ast_copy_string(buf, event->uid, len);
01568    } else if (!strcasecmp(data, "start")) {
01569       snprintf(buf, len, "%ld", (long)event->start);
01570    } else if (!strcasecmp(data, "end")) {
01571       snprintf(buf, len, "%ld", (long)event->end);
01572    } else if (!strcasecmp(data, "busystate")) {
01573       snprintf(buf, len, "%d", event->busy_state);
01574    } else if (!strcasecmp(data, "attendees")) {
01575       calendar_join_attendees(event, buf, len);
01576    }
01577 
01578 
01579    return 0;
01580 }
01581 
01582 static struct ast_custom_function calendar_event_function = {
01583    .name = "CALENDAR_EVENT",
01584    .read = calendar_event_read,
01585 };
01586 
01587 static int cb_pending_deletion(void *user_data, void *arg, int flags)
01588 {
01589    struct ast_calendar *cal = user_data;
01590 
01591    cal->pending_deletion = 1;
01592 
01593    return CMP_MATCH;
01594 }
01595 
01596 static int cb_rm_pending_deletion(void *user_data, void *arg, int flags)
01597 {
01598    struct ast_calendar *cal = user_data;
01599 
01600    return cal->pending_deletion ? CMP_MATCH : 0;
01601 }
01602 
01603 static int reload(void)
01604 {
01605    struct ast_calendar_tech *iter;
01606 
01607    ast_mutex_lock(&reloadlock);
01608 
01609    /* Mark existing calendars for deletion */
01610    ao2_callback(calendars, OBJ_NODATA | OBJ_MULTIPLE, cb_pending_deletion, NULL);
01611    load_config(NULL);
01612 
01613    AST_LIST_LOCK(&techs);
01614    AST_LIST_TRAVERSE(&techs, iter, list) {
01615       if (load_tech_calendars(iter)) {
01616          ast_log(LOG_WARNING, "Failed to reload %s calendars, module disabled\n", iter->type);
01617       }
01618    }
01619    AST_LIST_UNLOCK(&techs);
01620 
01621    /* Delete calendars that no longer show up in the config */
01622    ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_rm_pending_deletion, NULL);
01623 
01624    ast_mutex_unlock(&reloadlock);
01625 
01626    return 0;
01627 }
01628 
01629 static void *do_refresh(void *data)
01630 {
01631    for (;;) {
01632       struct timeval now = ast_tvnow();
01633       struct timespec ts = {0,};
01634       int res, wait;
01635 
01636       ast_mutex_lock(&refreshlock);
01637 
01638       if ((wait = ast_sched_wait(sched)) < 0) {
01639          wait = 1000;
01640       }
01641 
01642       ts.tv_sec = (now.tv_sec + wait / 1000) + 1;
01643       res = ast_cond_timedwait(&refresh_condition, &refreshlock, &ts);
01644 
01645       ast_mutex_unlock(&refreshlock);
01646 
01647       ast_sched_runq(sched);
01648    }
01649 
01650    return NULL;
01651 }
01652 
01653 /* If I were to allow unloading it would look something like this */
01654 static int unload_module(void)
01655 {
01656    struct ast_calendar_tech *tech;
01657 
01658    ast_devstate_prov_del("calendar");
01659    ast_custom_function_unregister(&calendar_busy_function);
01660    ast_custom_function_unregister(&calendar_event_function);
01661    ast_custom_function_unregister(&calendar_query_function);
01662    ast_custom_function_unregister(&calendar_query_result_function);
01663    ast_custom_function_unregister(&calendar_write_function);
01664    ast_cli_unregister_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
01665 
01666    /* Remove all calendars */
01667    ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
01668 
01669    AST_LIST_LOCK(&techs);
01670    AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, tech, list) {
01671       ast_unload_resource(tech->module, 0);
01672    }
01673    AST_LIST_TRAVERSE_SAFE_END;
01674    AST_LIST_UNLOCK(&techs);
01675 
01676    return 0;
01677 }
01678 
01679 static int load_module(void)
01680 {
01681    if (!(calendars = ao2_container_alloc(CALENDAR_BUCKETS, calendar_hash_fn, calendar_cmp_fn))) {
01682       ast_log(LOG_ERROR, "Unable to allocate calendars container!\n");
01683       return AST_MODULE_LOAD_FAILURE;
01684    }
01685 
01686    if (load_config(NULL)) {
01687       /* We don't have calendar support enabled */
01688       return AST_MODULE_LOAD_DECLINE;
01689    }
01690 
01691    ast_mutex_init(&refreshlock);
01692    ast_cond_init(&refresh_condition, NULL);
01693    ast_mutex_init(&reloadlock);
01694 
01695    if (!(sched = sched_context_create())) {
01696       ast_log(LOG_ERROR, "Unable to create sched context\n");
01697       return AST_MODULE_LOAD_FAILURE;
01698    }
01699 
01700    if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
01701       ast_log(LOG_ERROR, "Unable to start refresh thread--notifications disabled!\n");
01702    }
01703 
01704    ast_custom_function_register(&calendar_busy_function);
01705    ast_custom_function_register(&calendar_event_function);
01706    ast_custom_function_register(&calendar_query_function);
01707    ast_custom_function_register(&calendar_query_result_function);
01708    ast_custom_function_register(&calendar_write_function);
01709    ast_cli_register_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
01710 
01711    ast_devstate_prov_add("Calendar", calendarstate);
01712 
01713    /* Since other modules depend on this, disable unloading */
01714    ast_module_ref(ast_module_info->self);
01715 
01716    return AST_MODULE_LOAD_SUCCESS;
01717 }
01718 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk Calendar integration",
01719       .load = load_module,
01720       .unload = unload_module,
01721       .reload = reload,
01722       .load_pri = AST_MODPRI_DEVSTATE_PROVIDER,
01723    );

Generated on Sat Mar 26 11:08:02 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9