muxtapeからテープをダウンロードしてiTunesにプレイリストとして追加する

koyachi2008-03-30


以下のスクリプトをdlmuxtape.plとして保存し、

$ perl dlmuxtape.pl tape_name

などとするとiTunesを起動して"muxtape / tape_name"のような新規プレイリストを作成してhttp://tape_name.muxtape.comからダウンロードしたテープを追加します。

#!/usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use List::MoreUtils qw/each_array/;
use Mac::iTunes;

my $tape_id = $ARGV[0] || "justin";
my $muxtape_url = "http://$tape_id.muxtape.com";
my $download_dir = $ARGV[1] || "./download";

unless (-d $download_dir) {
    mkdir $download_dir;
}
unless (-d "$download_dir/$tape_id") {
    mkdir "$download_dir/$tape_id";
}

my $itunes = Mac::iTunes->controller;
$itunes->activate;

my $playlist_name = "muxtape / $tape_id";
if ($itunes->playlist_exists($playlist_name)) {
    die "$playlist_name already exist";
}
$itunes->add_playlist($playlist_name);

my $ua = LWP::UserAgent->new;
$ua->agent('Firefox');
my $response = $ua->get($muxtape_url);
if ($response->is_success) {
    my $data = $response->content;
    $data =~ s!.*var muxtape = new Kettle\((.*?)\);.*!$1!s;

    my $ids = $data;
    $ids=~ s/^\[(.*)\],.*$/$1/;
    my @ids = map { s/'(.*?)'/$1/; $_; } split /,/, $ids;

    my $sigs = $data;
    $sigs =~ s/^\[.*?\],\[(.*?)\]$/$1/;
    my @sigs = map { s/'(.*?)'/$1/; $_; } split /,/, $sigs;

    my $count = 1;
    my $total = scalar @ids;
    my $ea = each_array(@ids, @sigs);
    while (my($id, $sig) = $ea->()) {
        my $song_url = song_url($id, $sig);
        print "[$count / $total] downloading... $song_url\n";
        $response = $ua->get($song_url);
        if ($response->is_success) {
            my $file_name = sprintf "%s/%s/%02d_%s.mp3", $download_dir, $tape_id, $count, $id;
            open FH, "> $file_name";
            binmode FH;
            print FH $response->content;
            close FH;

            $itunes->add_track($file_name, $playlist_name);
            $count++;
        }
        else {
            die "Can't get $song_url : " . $response->status;
        }
    }
}
else {
    die "Can't get $muxtape_url : " . $response->status;
}

sub song_url {
    my($hex, $sig) = @_;
    my $song_url = join "",
        "http://muxtape.s3.amazonaws.com/songs/",
        $hex,
        "?PLEASE=DO_NOT_STEAL_MUSIC&",
        $sig
    ;
    $song_url;
}