src/irc_log.c
author Tero Marttila <terom@fixme.fi>
Sun, 15 Mar 2009 23:24:21 +0200
changeset 58 65bd90f94f4e
parent 57 ce1accba5fc7
child 61 4ba21936518a
permissions -rw-r--r--
merge modules -> default, this is a bit early as it breaks functionality, but who cares, need to replace the build system now :)
#include "module.h"
#include "irc_chan.h"
#include "error.h"
#include "log.h"

#include <stdlib.h>
#include <string.h>

#include <event2/event.h>
// XXX: fix this err_t crap
#define LIB_ERR_H
#include <evsql.h>

/**
 * The irc_log module state
 */
struct irc_log_ctx {
    /** The nexus this module is loaded for */
    struct nexus *nexus;

    /** The database connection */
    struct evsql *db;

};

static void on_chan_msg (struct irc_chan *chan, const struct irc_nm *source, const char *message, void *arg)
{
    struct irc_log_ctx *ctx = arg;

    (void) ctx;

    // log it! :P
    log_debug("%s: %s: %s", source ? source->nickname : "???", irc_chan_name(chan), message);
}

static struct irc_chan_callbacks _chan_callbacks = {
    .on_msg         = on_chan_msg,
};

static err_t irc_log_init (struct nexus *nexus, void **ctx_ptr, struct error_info *err)
{
    struct irc_log_ctx *ctx;
    
    // allocate
    if ((ctx = calloc(1, sizeof(*ctx))) == NULL)
        return SET_ERROR(err, ERR_CALLOC);

    // initialize
    memset(ctx, 0, sizeof(*ctx));

    // store
    ctx->nexus = nexus;

    // ok
    *ctx_ptr = ctx;

    return SET_ERROR(err, SUCCESS);
}

static err_t irc_log_conf (void *mod_ctx, const char *name, char *value, struct error_info *err)
{
    struct irc_log_ctx *ctx = mod_ctx;

    if (strcmp(name, "db_info") == 0) {
        log_info("connect to database: %s", value);

        if ((ctx->db = evsql_new_pq(ctx->nexus->ev_base, value, NULL, NULL)) == NULL)
           return ERR_EVSQL_NEW_PQ;

    } else if (strcmp(name, "channel") == 0) {
        const char *network = strsep(&value, "/");
        const char *channel = value;

        struct irc_chan *chan;
        
        // kill missing tokens
        if (!network || !channel) 
            RETURN_SET_ERROR_STR(err, ERR_MODULE_CONF, "invalid '<network>/<channel>' value");

        // get the channel?
        if ((chan = irc_client_get_chan(ctx->nexus->client, network, channel)) == NULL)
            RETURN_SET_ERROR_STR(err, ERR_MODULE_CONF, "unknown channel name");

        // add channel callbacks
        if ((ERROR_CODE(err) = irc_chan_add_callbacks(chan, &_chan_callbacks, ctx)))
            return ERROR_CODE(err);

    } else {
        return -1;

    }

    // ok
    return SUCCESS;
}

/**
 * The module function table
 */
struct module_funcs irc_log_funcs = {
    .init       = &irc_log_init,
    .conf       = &irc_log_conf,
};