#!/usr/bin/perl

# -----------------------------------------------------------------------------
# httpnp.pl - "HTTP Now Playing" script
# by Frank 'yogan' Blendinger (fb@intoxicatedmind.net)
# http://yogan.meinungsverstaerker.de/irssi/
# -----------------------------------------------------------------------------
#
# This scripts reads information about your currently playing song from a file
# that has to be accessible by HTTP and prints it either to the current 
# channel/query or privately to you.
#
# You need a mediaplayer that can write such a file on song-change (I use xmms
# and a small shell script to do that job) and of course a webserver that makes
# that file accessible to the world.
#
# The format of the file has to be as follows:
# variable: Some value
# There has to be a space after the ':', no whitespaces before the variable and
# there may be only one variable per line.
# Currently supported values for variables are "title", "artist", "album" and
# "year".
# 
# -----------------------------------------------------------------------------
#
# USAGE:
# 	/httpnp [-p]
# 	  Prints your currently playing song to the active channel/query. If
# 	  the parameter -p is given, it will only be shown to yourself.
# 	
# 	Don't forget to /set httpnp_url http://your.server/songinfofile
#
# 	Settings:
# 	  httpnp_show_album true|false    show album name or not
# 	  httpnp_show_year  true|false    show year or not
#
#	There are four format settings:
#	  httpnp_format     used when show_album = false and show_year = false
#	  httpnp_format_a   used when show_album = true and show_year = false
#	  httpnp_format_y   used when show_album = false and show_year = true
#	  httpnp_format_ay  used when show_album = true and show_year = true
#
#	When setting a custom format, be sure to put in "%artist" and "%title"
#	in all formats, "%year" in httpnp_format_y and httpnp_format_ay and
#	"%album" in httpnp_format_a and httpnp_format_ay. These tokens will be
#	replaced with the actual values.
#	
#	Default values:
#	  See the settings_add_str lines at the bottom of this script.
#
# HISTORY:
# 	- 2005-02-08 - v0.0.1
# 	  Initial release
#	- 2005-12-17 - v0.0.2
#	  Minor bugfix
#	- 2005-12-18 - v0.1.0
#	  Script can also show album and year now. See httpnp_show_* settings.
#	- 2005-12-19 - v0.2.0
#	  Output string is now completely customizable.
#	- 2005-12-20 - v0.2.1
#	  Minor bugfix, format is chosen more wisely now.
#	- 2006-02-02 - v0.2.2
#	  Bugfix. Characters like " ' and ; in the song file broke the script
#	  due to bad quoting. This should be fixed now. I should still do
#	  better parsing of the infofile though.
#	- 2008-12-09 - v0.2.3
#         Small fix to prevent displaying empty album or year fields.
#
# -----------------------------------------------------------------------------




use vars qw($VERSION %IRSSI);
$VERSION = '0.2.3';
%IRSSI = (
        authors         => 'Frank \'yogan\' Blendinger',
        contact         => 'fb\@intoxicatedmind.net',
        name            => 'httpnp',
        description     => 'Displays your currently playing song, getting the info from a web server',
        license         => 'GPL',
        url             => 'http://yogan.meinungsverstaerker.de/irssi/',
        changed         => '2008-12-09',
); 


use Irssi qw(
	command_bind
	settings_get_int settings_add_int
	settings_get_str settings_add_str
);
use POSIX;
use LWP::Simple;


sub playing {

	# Switch to private mode if -p parameter was given
	my ($data, $server, $witem) = @_;
	$mode = "public";
	if ($data =~ /-p/ ) { $mode = "private"; }

	# Load settings
	$url = settings_get_str('httpnp_url');
	$show_album = settings_get_str('httpnp_show_album');
	$show_year = settings_get_str('httpnp_show_year');

	if ( $url eq "SET_ME" ) {
		print '%R>>%n Set a URL first: /set httpnp_url http://your.server/songinfo-file';
		return;
	}

	# Load the URL
	my $message = get($url);

	if ( $message eq "" ) {
		print '%R>>%n Could not get song information from '.$url;
		return;
	}

	# Split the text to lines
	@alllines = split /\n/, $message;

	# Get artist and song
	@mylines = grep { /^artist: / } @alllines;
	my $artist = $mylines[0];
	$artist =~ s/^artist: //;
	@mylines = grep { /^title: / } @alllines;
	my $title = $mylines[0];
	$title =~ s/^title: //;
	
	if ( $artist eq "" && $title eq "" ) {
		if ($witem && ($witem->{type} eq "CHANNEL" || $witem->{type} eq "QUERY")) {
			$witem->command("/echo No song playing at the moment.");
		} else {
			print '%R>>%n No song playing at the moment.';
		}
		return;
	}

        # Get album and year
        @mylines = grep { /^album: / } @alllines;
        my $album = $mylines[0];
        $album =~ s/^album: //;
        @mylines = grep { /^year: / } @alllines;
        my $year = $mylines[0];
        $year =~ s/^year: //;

	# Build the message
	if ($show_album eq "true") {
		if ($show_year eq "true") {
			# show album and year
			if ($album ne "") {
				if ($year ne "" && $year ne "0") {
					$message = settings_get_str('httpnp_format_ay');
					$message =~ s/%album/$album/;
					$message =~ s/%year/$year/;
				} else {
					# no year information found
					$message = settings_get_str('httpnp_format_a');
					$message =~ s/%album/$album/;
					$message =~ s/%year//;
				}
			} else {
				# no album information found
				if ($year ne "" && $year ne "0") {
					$message = settings_get_str('httpnp_format_y');
					$message =~ s/%album//;
					$message =~ s/%year/$year/;
				} else {
					# no year information found
					$message = settings_get_str('httpnp_format');
					$message =~ s/%album//;
					$message =~ s/%year//;
				}
			}
		} else {
                        # no year
			if ($album ne "") {
                            # show album
                            $message = settings_get_str('httpnp_format_a');
                            $message =~ s/%album/$album/;
                        } else {
                            # no album information found
                            $message = settings_get_str('httpnp_format');
                        }
                        $message =~ s/%year//;
		}
	} else {
		if ($show_year eq "true") {
			# show year
			if ($year ne "" && $year ne "0") {
				$message = settings_get_str('httpnp_format_y');
				$message =~ s/%year/$year/;
			} else {
				# no year information found
				$message = settings_get_str('httpnp_format');
				$message =~ s/%year//;
			}
		} else {
			# don't show album and year
			$message = settings_get_str('httpnp_format');
			$message =~ s/%year//;
		}
                $message =~ s/%album//;
	}

        # insert artist and title
        $message =~ s/%artist/$artist/;
        $message =~ s/%title/$title/;
        
        # fix for missing artist
        $message =~ s/^np:  -/np:/;
	
	# Print the message to channel/query or privately
	if ( $mode eq "private" ) {
		if ($witem && ($witem->{type} eq "CHANNEL" || $witem->{type} eq "QUERY")) {
			$witem->command("/echo $message");
		} else {
			print '%R>>%n '.$message;
		}
	} else {
		if ($witem && ($witem->{type} eq "CHANNEL" || $witem->{type} eq "QUERY")) { 
			$witem->command("/me $message");
		} else {
			print '%R>>%n '.$message;
		}
	}

}


settings_add_str($IRSSI{name}, 'httpnp_url', 'SET_ME' );
settings_add_str($IRSSI{name}, 'httpnp_show_album', 'false' );
settings_add_str($IRSSI{name}, 'httpnp_show_year', 'false' );
settings_add_str($IRSSI{name}, 'httpnp_format', 'np: %artist - %title' );
settings_add_str($IRSSI{name}, 'httpnp_format_a', 'np: %artist - %title from "%album"' );
settings_add_str($IRSSI{name}, 'httpnp_format_y', 'np: %artist - %title (%year)' );
settings_add_str($IRSSI{name}, 'httpnp_format_ay', 'np: %artist - %title from "%album" (%year)' );
command_bind('httpnp','playing');

print CLIENTCRAP '%R>>%n '.$IRSSI{name}.' '.$VERSION.' loaded';
if (settings_get_str('httpnp_url') eq "SET_ME") {
	print CLIENTCRAP '%R>>%n Set a URL first: /set httpnp_url http://your.server/songinfo-file';
}


