pep_tune.c
author Myhailo Danylenko <isbear@ukrpost.net>
Sun, 23 Sep 2012 15:38:29 +0300
changeset 40 574e404ab82f
parent 35 a77a8e7ab8ae
permissions -rw-r--r--
[geoloc] fix missing symbol


/* Copyright 2009-2012 Myhailo Danylenko
 *
 * This file is part of mcabber-pep
 *
 * mcabber-pep is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <glib.h>
#include <loudmouth/loudmouth.h>
#include <stdlib.h>                 // atoi
#include <time.h>

#include <mcabber/settings.h>
#include <mcabber/utils.h>
#include <mcabber/xmpp.h>
#include <mcabber/xmpp_helper.h>
#include <mcabber/logprint.h>
#include <mcabber/hooks.h>
#include <mcabber/modules.h>

#include "pep.h"
#include "pep_tune.h"

#include "config.h"

//
//  module description
//

void pep_tune_init   (void);
void pep_tune_uninit (void);

#define DESCRIPTION ( PEP_TUNE_DESCRIPTION )

static const gchar *deps[] = { "pep", NULL };

module_info_t info_pep_tune = {
	.branch      = MCABBER_BRANCH,
	.api         = MCABBER_API_VERSION,
	.version     = PROJECT_VERSION,
	.description = DESCRIPTION,
	.requires    = deps,
	.init        = pep_tune_init,
	.uninit      = pep_tune_uninit,
	.next        = NULL,
};

//
//  globals
//

#define MAX_NO ( 6 )

static tune_pair_t info[] = {
	{ "artist", NULL },
	{ "length", NULL },
	{ "rating", NULL },
	{ "source", NULL },
	{ "title",  NULL },
	{ "track",  NULL },
	{ "uri",    NULL },
	{ NULL,     NULL },
};

static GQuark            tune_gerror_quark    = 0;
static gboolean          publish_delayed      = FALSE;
static guint             tune_hid_connect     = 0;
static guint             tune_hid_disconnect  = 0;
static guint             tune_hid_tuneout     = 0;
static guint             tune_interval        = 0;
static time_t            tune_timestamp       = 0;
static LmMessageHandler *tune_reply_handler   = NULL;
static guint             tune_source          = 0;
static gboolean          tune_guard_installed = FALSE;

//
//  predeclarations
//

static void tune_publish_info (void);

//
//  code
//

static LmHandlerResult tune_publish_reply_handler (LmMessageHandler *handler, LmConnection *connection, LmMessage *message, gpointer userdata)
{
	switch (lm_message_get_sub_type (message)) {
	case LM_MESSAGE_SUB_TYPE_RESULT:
		break;
	
	case LM_MESSAGE_SUB_TYPE_ERROR:
		
		{
			LmMessageNode *node   = lm_message_get_node (message);
			const gchar   *type;
			const gchar   *reason;

			node = lm_message_node_get_child (node, "error");
			type = lm_message_node_get_attribute (node, "type");
			if (node->children)
				reason = node->children->name;
			else
				reason = "undefined";

			scr_log_print (LPRINT_LOGNORM, "pep_tune: Publish failed: %s - %s", type, reason);
		}

		break;
	
	default:
		return LM_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
		break;
	}

	return LM_HANDLER_RESULT_REMOVE_MESSAGE;
}

static gboolean tune_delayed_publish_cb (gpointer data)
{
	tune_source = 0;
	tune_publish_info ();
	return FALSE;
}

static void tune_publish_info (void)
{
	if (!xmpp_is_online ()) {
		scr_log_print (LPRINT_DEBUG, "pep_tune: Not online, delaying publish.");
		publish_delayed = TRUE;
		return;
	}

	// check for frequency of publihes
	if (tune_interval) {
		time_t now = time (NULL);

		if (now - tune_timestamp < tune_interval) {

			scr_log_print (LPRINT_DEBUG, "pep_tune: Publish interval not passed, delaying publish.");
			if (!tune_source)
				tune_source = g_timeout_add_seconds ( tune_interval - ( now - tune_timestamp ), tune_delayed_publish_cb, NULL );
			return;

		} else
			tune_timestamp = now;
	}

	// publish
	LmMessage     *request = lm_message_new_with_sub_type (NULL, LM_MESSAGE_TYPE_IQ, LM_MESSAGE_SUB_TYPE_SET);
	LmMessageNode *node    = lm_message_get_node (request);
	lm_message_node_set_attribute (node, "from", lm_connection_get_jid (lconnection));

	node = lm_message_node_add_child (node, "pubsub", NULL);
	lm_message_node_set_attribute (node, "xmlns", NS_PUBSUB);

	node = lm_message_node_add_child (node, "publish", NULL);
	lm_message_node_set_attribute (node, "node", NS_TUNE);

	node = lm_message_node_add_child (node, "item", NULL);

	node = lm_message_node_add_child (node, "tune", NULL);
	lm_message_node_set_attribute (node, "xmlns", NS_TUNE);

	{ // put data inside
		int i;

		for (i = 0; i <= MAX_NO; ++i)
			if (info[i].value)
				lm_message_node_add_child (node, info[i].name, info[i].value);
	}

	{ // send
		GError *error = NULL;

		lm_connection_send_with_reply (lconnection, request, tune_reply_handler, &error);

		if (error) {
			scr_log_print (LPRINT_DEBUG, "pep_tune: Publishing error: %s.", error -> message);
			g_error_free (error);
		}
	}

	lm_message_unref (request);
}

gboolean pep_tune_request ( const gchar *to, GError **err )
{
	LmMessage *request;
	LmMessageNode *node;

	if (!xmpp_is_online ()) {
		g_set_error ( err, tune_gerror_quark, TUNE_ERROR_NOTCONNECTED, "You are not connected" );
		return FALSE;
	}

	request = lm_message_new_with_sub_type ( to, LM_MESSAGE_TYPE_IQ, LM_MESSAGE_SUB_TYPE_GET );
	node = lm_message_get_node (request);
	lm_message_node_set_attribute (node, "from", lm_connection_get_jid (lconnection));

	node = lm_message_node_add_child (node, "pubsub", NULL);
	lm_message_node_set_attribute (node, "xmlns", NS_PUBSUB);

	node = lm_message_node_add_child (node, "items", NULL);
	lm_message_node_set_attribute (node, "node", NS_TUNE);

	{ // send, result will be handled by pep
		GError *error = NULL;

		lm_connection_send ( lconnection, request, &error );

		if ( error ) {
			g_propagate_error ( err, error );
			return FALSE;
		}
	}

	lm_message_unref (request);

	return TRUE;
}

static void tune_handler ( const gchar *from, const gchar *node, LmMessageNode *n, const gchar *id, gpointer ignore )
{
	LmMessageNode *tag;
	hk_arg_t args[] = {
		{ "artist", NULL },
		{ "length", NULL },
		{ "rating", NULL },
		{ "source", NULL },
		{ "title",  NULL },
		{ "track",  NULL },
		{ "uri",    NULL },
		{ "from",   from },
		{ NULL,     NULL },
	};

	for ( tag = n -> children; tag; tag = tag -> next ) {
		const gchar *name  = tag -> name;
		if ( name ) {
			int i;
			for ( i = 0; i <= MAX_NO; ++i )
				if ( ! g_strcmp0 ( name, args[i].name ) ) {
					const gchar *value = lm_message_node_get_value ( tag );
					if ( value )
						args[i].value = value;
				}
		}
	}

	hk_run_handlers ( HOOK_TUNE_IN, args );
}

static guint tune_hch (const gchar *htype, hk_arg_t *args, gpointer udata)
{
	if (publish_delayed) {
		scr_log_print (LPRINT_DEBUG, "pep_tune: Publishing delayed data.");

		publish_delayed = FALSE;
		tune_publish_info ();
	}

	return HOOK_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
}

static guint tune_hdh (const gchar *htype, hk_arg_t *args, gpointer udata)
{
#ifdef HAVE_LM_CONNECTION_UNREGISTER_REPLY_HANDLER
	if (lconnection && tune_reply_handler)
		lm_connection_unregister_reply_handler (lconnection, tune_reply_handler);
#endif

	return HOOK_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
}

static guint tune_htoh ( const gchar *htype, hk_arg_t *args, gpointer udata )
{
	gboolean        publish = FALSE;
	gboolean        stop    = FALSE;

	{ // check state
		const hk_arg_t *arg;
		for ( arg = args; arg -> name != NULL; ++ arg ) {
			if ( ! g_strcmp0 ( arg -> name, "state" ) ) {
				stop = ( ! g_strcmp0 ( arg -> value, "stop" ) ) ||
					   ( ( ! g_strcmp0 ( arg -> value, "pause" ) ) && settings_opt_get_int ( OPT_TUNE_PAUSE_IS_STOP ) );
				break;
			}
		}
	}

	if ( stop ) { // ignore info
		int i;
		for ( i = 0; i <= MAX_NO; ++ i )
			if ( info [ i ] .value != NULL ) {
				g_free ( info [ i ] .value );
				info [ i ] .value = NULL;
				publish = TRUE;
			}
	} else { // populate info with new values
		int i;
		for ( i = 0; i <= MAX_NO; ++ i ) {
			const hk_arg_t *arg;
			for ( arg = args; arg -> name != NULL; ++ arg ) {
				if ( ! g_strcmp0 ( arg -> name, info [ i ] .name ) ) {
					if ( g_strcmp0 ( arg -> value, info [ i ] .value ) ) {
						if ( info [ i ] .value )
							g_free ( info [ i ] .value );
						info [ i ] .value = g_strdup ( arg -> value );
						publish = TRUE;
					}
					break;
				}
			}
		}
	}

	if ( publish )
		tune_publish_info ();

	return HOOK_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
}

static gchar *tune_guard (const char *key, const char *new_value)
{
	if (new_value)
		tune_interval = atoi (new_value);
	else
		tune_interval = 0;

	if (tune_source) {
		g_source_remove (tune_source);
		tune_source = 0;
		// this will reinstall source with proper timeout, if necessary
		tune_publish_info ();
	}

	return g_strdup (new_value);
}

void pep_tune_init(void)
{
	tune_gerror_quark = g_quark_from_string ( "pep-tune-gerror-quark" );

	tune_interval = settings_opt_get_int ( OPT_TUNE_INTERVAL );

	tune_guard_installed = settings_set_guard ( OPT_TUNE_INTERVAL, tune_guard );
	if ( ! tune_guard_installed )
		scr_log_print (LPRINT_LOGNORM, "pep_tune: Warning: cannot install option guard for '" OPT_TUNE_INTERVAL "'");

	pep_register_xmlns_handler (NS_TUNE, tune_handler, NULL, NULL);

	tune_reply_handler = lm_message_handler_new ( tune_publish_reply_handler, NULL, NULL );

	tune_hid_connect    = hk_add_handler ( tune_hch,  HOOK_POST_CONNECT, G_PRIORITY_DEFAULT, NULL );
	tune_hid_disconnect = hk_add_handler ( tune_hdh,  HOOK_PRE_DISCONNECT, G_PRIORITY_DEFAULT, NULL );
	tune_hid_tuneout    = hk_add_handler ( tune_htoh, HOOK_TUNE_OUT, G_PRIORITY_DEFAULT, NULL );

	xmpp_add_feature ( NS_TUNE        );
	xmpp_add_feature ( NS_TUNE_NOTIFY );
}

void pep_tune_uninit ( void )
{
	xmpp_del_feature ( NS_TUNE        );
	xmpp_del_feature ( NS_TUNE_NOTIFY );

	hk_del_handler ( HOOK_POST_CONNECT,   tune_hid_connect );
	hk_del_handler ( HOOK_PRE_DISCONNECT, tune_hid_disconnect );
	hk_del_handler ( HOOK_TUNE_OUT,       tune_hid_tuneout );

	if ( tune_source )
		g_source_remove ( tune_source );

	pep_unregister_xmlns_handler ( NS_TUNE );

	if ( tune_reply_handler ) {
#ifdef HAVE_LM_CONNECTION_UNREGISTER_REPLY_HANDLER
		if ( lconnection )
			lm_connection_unregister_reply_handler ( lconnection, tune_reply_handler  );
#endif

		lm_message_handler_invalidate ( tune_reply_handler );
		lm_message_handler_unref ( tune_reply_handler );
	}

	{
		int i;
		for ( i = 0; i <= MAX_NO; i ++ )
			g_free ( info[i].value );
	}

	if ( tune_guard_installed )
		settings_del_guard ( OPT_TUNE_INTERVAL );
}

/* vim: se ts=4 sw=4: */