#!/usr/bin/perl
#
# asnowplaying.pl - version 1.0
#
# Copyright (c) 2004 Dominic Hargreaves <dom@earth.li>
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

use strict;
use warnings;

use Cache::FileCache;

sub get_content;
sub parse_content;

## Change this variable
my $user = "jmdh";
##

my $data = "trackname";
my $cache = new Cache::FileCache( { 'namespace' => "scrobbler$user",
                                    'default_expires_in' => 300,
				    'cache_root' => "/tmp/Cache".$<,
				    'directory_umask' => 077 } );
my $track = $cache->get($data);
if (not defined $track) {
    $track = get_content;
    $cache->set($data, $track);
}

print "Content-Type: text/html\n\n" . $track . "\n";

sub get_content {
    require LWP::UserAgent;
    my $ua = LWP::UserAgent->new;
    $ua->timeout(5);
    my $response = $ua->get("http://ws.audioscrobbler.com/rdf/history/$user");
    if ($response->is_success) {
        return parse_content($response);
    } else {
        return "Error fetching now playing data from remote site!\n";
    }
}

sub parse_content {
    require XML::RSS;
    my $response = shift or die $!;
    my $output = $response->content;
    my $rss = new XML::RSS;
    $rss->parse($output);
    # Just grab the first line
    my $link = $rss->{items}->[0]->{link};
    my $description = $rss->{items}->[0]->{description};
    my $date = $rss->{items}->[0]->{dc}->{date};
    $date =~ s/T/ /;
    $date =~ s/\+.*//;
    return "On $date I was listening to <a href=\"$link\">$description</a>";
}
    
