Newer
Older
xmpp-bot / src / bot / context.c
@lagfra lagfra 12 days ago 1 KB free routine
/* bot/context.c
 */

#include "context.h"

void bot_free_user_data(struct BotUserInfo user, bool freeSegment)
{
    g_string_free(user.jid, freeSegment);
    g_string_free(user.pass, freeSegment);
}

int bot_xmpp_startup(struct BotUserInfo user, struct BotXmppCtx * const bctx)
{
    xmpp_log_t* newLog;
    xmpp_ctx_t* newCtx;
    xmpp_conn_t* newCon;
    int connectStatus;

    /* init library */
    xmpp_initialize();

    /* create a context */
    newLog = xmpp_get_default_logger(XMPP_LEVEL_DEBUG); /* pass NULL instead to silence output */
    newCtx = xmpp_ctx_new(NULL, newLog);

    if (!(newLog && newCtx)) {
        fprintf(stderr, "Unable to startup. Context creation failed.");
        return 1;
    }

    /* create a connection */
    newCon = xmpp_conn_new(newCtx);

    if (!newCon) {
        fprintf(stderr, "Unable to startup. Connection failed.");
        return 1;
    }

    /* setup authentication information */
    xmpp_conn_set_jid(newCon, user.jid->str);
    xmpp_conn_set_pass(newCon, user.pass->str);

    /* initiate connection */
    connectStatus = xmpp_connect_client(newCon, NULL, 0, conn_handler, newCtx);
    if(connectStatus != 0) {
        /* connecting went wrong */
        return connectStatus;
    }

    (*bctx).log = newLog;
    (*bctx).ctx = newCtx;
    (*bctx).conn = newCon;
    return 0;
}

void bot_xmpp_shutdown(struct BotXmppCtx * const bctx)
{
    /* enter the event loop - 
       our connect handler will trigger an exit */
    xmpp_run((*bctx).ctx);

    /* release our connection and context */
    xmpp_conn_release((*bctx).conn);
    xmpp_ctx_free((*bctx).ctx);

    /* final shutdown of the library */
    xmpp_shutdown();
}