2011-02-18

Spotify web services - a Perl example

IRC might be an oldskool medium today, but it is still used both for fun and a lot of open source projects.

From time to time, people tend to post Spotify URLs. Some uses the spotify: scheme and others uses the http://open.spotify.com/ format.

The identifiers for these URLs make no sense for humans, and to translate them, I made this Perl script, added a regexp hook in a bot and can now identify if I want to listen to what is pasted.

10:05 <@runesk> spotify:track:0UZRFYMoz9xmeE2AQUhTDl
10:05 <@Crunchy> [SPOTIFY: Daft Punk / Human After All / 2. The Prime Time Of Your Life]


The script uses the CPAN modules LWP::UserAgent and JSON and the Spotify Metadata API


#!/usr/bin/perl -w
#
# Query the Spotify web services for artist, track and album info
#
# Copyright 2011 - Rune Nordbøe Skillingstad
#
# License: GPLv2 - http://www.fsf.org/licensing/licenses/info/GPLv2.html
#
use warnings;
use strict;

use LWP::UserAgent;
use JSON;

if(!@ARGV || $ARGV[0] eq "") {
print "HALP! Nothing to look up :(\n";
exit(1);
}

my $query = join(" ", @ARGV);
if ($query !~ /(http:\/\/open.spotify.com\/|spotify:)(album|artist|track)([:\/])([a-zA-Z0-9]+)\/?/) {
print STDERR "Illegal query string\n";
exit(1);
}

my $ws_url = "http://ws.spotify.com/lookup/1/.json?uri=";

my $ua = LWP::UserAgent->new(env_proxy=>1,
keep_alive=>0, timeout=>5);

my $res = $ua->request(HTTP::Request->new('GET', $ws_url . $query));
if ($res->is_success()) {
my $json = decode_json($res->content);
if($json->{info}->{type} eq "album") {
print "[SPOTIFY: " . $json->{album}->{artist} ." / ". $json->{album}->{name} . "]\n";
} elsif($json->{info}->{type} eq "track") {
print "[SPOTIFY: " . join(", ", map{$_->{name}}@{$json->{track}->{artists}}) .
" / " . $json->{track}->{album}->{name} .
" / " . $json->{track}->{'track-number'} .
". " . $json->{track}->{name} . "]\n";
} elsif($json->{info}->{type} eq "artist") {
print "[SPOTIFY: " . $json->{artist}->{name} . "]\n";
} else {
# Add Use Data::Dumper and uncomment to debug
# print STDERR Dumper($json);
}
}

exit(0);:


The regexp in line 21 /(http:\/\/open.spotify.com\/|spotify:)(album|artist|track)([:\/])([a-zA-Z0-9]+)\/?/
is identical to the one used as a hook.

No comments:

Post a Comment