-
Notifications
You must be signed in to change notification settings - Fork 0
/
next-song.pl
executable file
·124 lines (92 loc) · 2.14 KB
/
next-song.pl
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/perl
use strict;
use warnings;
use Pod::Usage;
use Getopt::Long qw(GetOptions);
use File::Find::Rule;
use DBI;
use MP3::Info;
use File::Basename;
use File::Slurper 'write_text';
my %opt;
GetOptions(
'i|init=s' => \$opt{i},
'h|help' => \$opt{h},
);
my $dbfile = '/tmp/music.sql3';
my $jsonfile = '/home/www/radio/song.json'
my $dsn = "dbi:SQLite:dbname=$dbfile";
if( ! -f $dbfile){
my $dbh = DBI->connect($dsn, "", "", {
PrintError => 0,
RaiseError => 1,
AutoCommit => 1,
FetchHashKeyName => 'NAME_lc',
});
my $sql = <<'SCHEMA';
CREATE TABLE music (
path TEXT PRIMARY KEY,
count INTEGER DEFAULT 0
);
SCHEMA
$dbh->do($sql);
$dbh->disconnect;
}
if($opt{h}){
pod2usage(-verbose => 2, -output => '-');
exit;
}
my $dbh = DBI->connect($dsn, "", "", {
PrintError => 0,
RaiseError => 1,
AutoCommit => 1,
FetchHashKeyName => 'NAME_lc',
});
if($opt{i}){
$dbh->do("DELETE FROM music");
my @files = File::Find::Rule->file()
->name( "*.mp3" )
->nonempty()
->in( $opt{i} );
$dbh->do("PRAGMA synchronous = OFF");
foreach my $path (@files){
$dbh->do("INSERT INTO music (path,count) VALUES ('$path', 0)");
}
$dbh->disconnect;
exit;
}
my $sql = 'SELECT min(count) FROM music;';
my $sth = $dbh->prepare($sql);
$sth->execute();
my @row = $sth->fetchrow_array;
my $min = $row[0];
$sql = 'SELECT path FROM music WHERE count = ? ORDER BY RANDOM() LIMIT 1;';
$sth = $dbh->prepare($sql);
$sth->execute($min);
@row = $sth->fetchrow_array;
my $file = $row[0];
my $dir = dirname($file);
my $cover = '/cover.png';
if( -f "$dir/cover.jpg"){
$cover = "$dir/cover.jpg";
$cover =~ s/\/home\/data\/mp3\//\/covers\//;
}
$dbh->do('UPDATE music SET count = count + 1 WHERE path = ?', undef, $file);
my $tag = get_mp3tag($file);
write_text($jsonfile, sprintf ('{"artist":"%s","album":"%s","song":"%s","cover":"%s"}',
$tag->{'ARTIST'},
$tag->{'ALBUM'},
$tag->{'TITLE'},
$cover
)
);
print "$file\n";
__END__
=head1 SYNOPSIS
next-song.pl [OPTIONS]
=head1 OPTIONS AND ARGUMENTS
-i, --init /paht/to/mp3/files
Initialize song database
-h, --help
Show help
=cut