summaryrefslogtreecommitdiffstats
path: root/bin/lastfm_export
blob: 1f33c2d81eea56029f8366042ca64dda4e340133 (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
#!/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, $quiet);
GetOptions(
    'dsn=s' => \$dsn,
    'quiet' => \$quiet,
);
die "--dsn is required" unless $dsn;

my $dbh = DBI->connect($dsn, '', '', { RaiseError => 1, AutoCommit => 0 });
$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
);

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

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

my $count = 1;
my $s = $exporter->tracks;
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;
}