Getting track info from the Last.fm player
Tagged:  •    •  

I'm an addict when it comes to personal status messages in instant messenger protocols. I like to express thoughts, funny things (fortunes) and especially like to use the Now Listening feature. Which I've implemented differently than the Kopete media plugin, to suit my needs.

However, the script was only able to extract info from my favorite music player, Amarok. It couldn't show what I was playing when I was listening to my Last.fm.

So that made me investigating the Last.fm Player more closely. On the surface, there didn't seem to be an interface to get track info. So I downloaded the source (it's GPL'd, baby!) and see if there was a hidden way to retrieve track info. But also that resulted in nothing.

Right... that's not gonna work. There should be another way of retrieving track info from that thing. Something I noticed that the player sends a message to Last.fm whenever it starts to play a track, so it updates my profile page accordingly. And if it is online on some web page, then I can retrieve it, right? So that's what I did:

wget -q -O - http://www.last.fm/user/bram85 | \
sed -nf /home/bram/bin/processlastfmprofile.sed

The -q and -O flags mean to keep wget silent and spit out the web page contents to standard output, such that it can be piped to sed.

And these are the contents of the processlastfmprofile.sed file:

#!/usr/bin/sed -f

/<tr class="nowListening">/,/<.tr>/ {
/<a/ s|.*<a.*>\(.*\)</a>.*<a.*>\(.*\)</a>|\1 - \2|p
}

I think it receives the Dirtiest Hack Award 2007, but hey, it works. The wget command actually spits out the artist and track name. And now I can use it in Kopete to show what I'm listening to.

Update 18 July 2008:

The new Last.fm layout invalidated this solution, so I was forced to find a new solution. And eventually a better solution. And I succeeded.

I used the wmctrl(1) tool to retrieve the window title of the Last.fm player, which solely consists of the artist and track name. wmctrl should operate fine with most major window managers.

I used this construction in order to obtain the window title:

wmctrl -l -p | grep `pidof lastfm` | sed -e "s/.*`hostname` //" | sed 's/.รข../ -/'

The latter sed command is to replace some character mess to a single dash.