#!/usr/bin/perl -w use strict; use LWP::UserAgent; use HTTP::Request::Common; use Digest::MD5 qw(md5_hex); use DBI; my $lastfmuser = 'USERNAME'; my $lastfmpass = 'PASSWORD'; my $dbuser = 'mythtv'; my $dbpass = 'mythtv'; my $debug = $ARGV[0]; my $clientid = 'mmc'; my $clientver = '0.1'; my $timestamp = time(); my $authtoken = md5_hex(md5_hex($lastfmpass).$timestamp); # Get the time we last run my $lastrun; open(LASTRUN, 'lastrun') || die("Cannot open lastrun file"); while () { chomp; $lastrun = $_; } close(LASTRUN); if (!$lastrun) { print "lastrun file is empty\n" if $debug; exit; } # Get recently played tracks from database my $dbh = DBI->connect('DBI:mysql:mythconverg',$dbuser,$dbpass); my $query = "SELECT ms.track, ms.name, mt.artist_name, ma.album_name, CAST(ms.length/1000 AS UNSIGNED) AS length, UNIX_TIMESTAMP(ms.lastplay) AS lastplay FROM music_songs AS ms LEFT JOIN music_artists AS mt ON ms.artist_id=mt.artist_id LEFT JOIN music_albums AS ma ON ms.album_id=ma.album_id WHERE ms.numplays>0 AND UNIX_TIMESTAMP(ms.lastplay)>$lastrun ORDER BY ms.lastplay ASC LIMIT 50"; my $queryh = $dbh->prepare($query); $queryh->execute(); my $trackno; my $trackname; my $artist; my $album; my $length; my $lastplay; $queryh->bind_columns(\$trackno,\$trackname,\$artist,\$album,\$length,\$lastplay); print "Found ".$queryh->rows." track(s) to submit\n" if $debug; if ($queryh->rows > 0) { print "Preparing tracks...\n" if $debug; sub URLEncode($) { my $theURL = $_[0]; $theURL =~ s/([^a-zA-Z0-9_])/'%' . uc(sprintf("%2.2x",ord($1)));/eg; return $theURL; } my $subnum = 0; my $postbody; while($queryh->fetch()) { print "[$artist - $trackname]\n" if $debug; $postbody .= "&a[$subnum]=".URLEncode($artist). "&t[$subnum]=".URLEncode($trackname). "&i[$subnum]=$lastplay". "&o[$subnum]=P". "&r[$subnum]=". "&l[$subnum]=$length". "&b[$subnum]=".URLEncode($album). "&n[$subnum]=$trackno". "&m[$subnum]="; $subnum++; } $postbody .= "\r\n"; # Handshake my $url = "http://post.audioscrobbler.com/?hs=true&p=1.2&c=$clientid&v=$clientver&u=$lastfmuser&t=$timestamp&a=$authtoken"; my $browser = new LWP::UserAgent; my $response = $browser->get($url); unless ($response->is_success) { warn "Couldn't get [$url]: ", $response->status_line, "\n"; exit; } (my $status,my $sessionid,my $nowplayurl,my $submiturl) = split(/\n/,$response->content); print " Status: $status\n" if $debug; print " Session ID: $sessionid\n" if $debug; print "Now Play URL: $nowplayurl\n" if $debug; print " Submit URL: $submiturl\n\n" if $debug; # Submittion if ($status eq 'OK') { my $req = HTTP::Request->new('POST', $submiturl); $req->content_type('application/x-www-form-urlencoded; charset="UTF-8"'); $postbody = "s=$sessionid".$postbody; print "Submitting tracks: " if $debug; $req->content($postbody); $response = $browser->request($req); print $response->status_line."\n" if $debug; if (!$response->is_success) { exit; } open(LASTRUN, '>lastrun') || die("Cannot open lastrun file"); print LASTRUN $lastplay; close(LASTRUN); } }