summaryrefslogtreecommitdiffstats
path: root/bin/lastfm_export
blob: eb721dafcd336c6e3693626dbe68a2ab02dc79a7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env perl
use strict;
use warnings;
# PODNAME: lastfm_export
# ABSTRACT: data exporter for last.fm

use DBI;
use Getopt::Long qw(:config pass_through);
use LastFM::Export;
use Term::ProgressBar;

my ($dsn, $user, $quiet);
GetOptions(
    'dsn=s'  => \$dsn,
    'user=s' => \$user,
    'quiet'  => \$quiet,
);
die "--dsn is required" unless $dsn;
die "--user is required" unless $user;

my $dbh = DBI->connect($dsn, '', '', { RaiseError => 1, AutoCommit => 0 });
my $from = 0;
if (!$dbh->tables(undef, undef, 'tracks')) {
    $dbh->do(<<'');
    CREATE TABLE `tracks` (
        artist varchar(1024) NOT NULL,
        album varchar(1024) DEFAULT NULL,
        name varchar(1024) NOT NULL,
        timestamp integer(11) NOT NULL
    );

}
else {
    ($from) = $dbh->selectrow_array('SELECT timestamp FROM tracks ORDER BY timestamp DESC LIMIT 1');
}

my $exporter = LastFM::Export->new(user => $user);

my $track_count = $exporter->track_count(from => $from);
if (!$track_count) {
    $dbh->disconnect;
    exit(0);
}

my $progress;
if (!$quiet) {
    $progress = Term::ProgressBar->new({
        count => $track_count,
        ETA   => 'linear',
    });
}

my $sth = $dbh->prepare(
    'INSERT INTO tracks (artist, album, name, timestamp) VALUES (?, ?, ?, ?)'
);

my $count = 1;
my $s = $exporter->tracks(from => $from);
while (my $block = $s->next) {
    for my $item (@$block) {
        $sth->execute(
            $item->{artist}{'#text'},
            $item->{album}{'#text'},
            $item->{name},
            $item->{date}{uts},
        );
        $progress->update($count++) unless $quiet;
    }
    $dbh->commit;
    sleep 1;
}

$dbh->disconnect;