1 | package MP3::Find::Filesystem; |
---|
2 | |
---|
3 | use strict; |
---|
4 | use warnings; |
---|
5 | |
---|
6 | use base 'MP3::Find::Base'; |
---|
7 | |
---|
8 | use File::Find; |
---|
9 | use MP3::Info; |
---|
10 | use Scalar::Util qw(looks_like_number); |
---|
11 | |
---|
12 | use_winamp_genres(); |
---|
13 | |
---|
14 | sub search { |
---|
15 | my $self = shift; |
---|
16 | my ($query, $dirs, $sort, $options) = @_; |
---|
17 | |
---|
18 | # prep the search patterns as regexes |
---|
19 | foreach (keys(%$query)) { |
---|
20 | my $ref = ref $$query{$_}; |
---|
21 | # make arrays into 'OR' searches |
---|
22 | if ($ref eq 'ARRAY') { |
---|
23 | $$query{$_} = '(' . join('|', @{ $$query{$_} }) . ')'; |
---|
24 | } |
---|
25 | # convert to a regex unless it already IS a regex |
---|
26 | unless ($ref eq 'Regexp') { |
---|
27 | $$query{$_} = "^$$query{$_}\$" if $$options{exact_match}; |
---|
28 | $$query{$_} = $$options{ignore_case} ? qr[$$query{$_}]i : qr[$$query{$_}]; |
---|
29 | } |
---|
30 | } |
---|
31 | |
---|
32 | # run the actual find |
---|
33 | my @results; |
---|
34 | find(sub { match_mp3($File::Find::name, $query, \@results) }, $_) foreach @$dirs; |
---|
35 | |
---|
36 | # sort the results |
---|
37 | if (@$sort) { |
---|
38 | @results = sort { |
---|
39 | my $compare; |
---|
40 | foreach (map { uc } @$sort) { |
---|
41 | # use Scalar::Util to do the right sort of comparison |
---|
42 | $compare = (looks_like_number($a->{$_}) && looks_like_number($b->{$_})) ? |
---|
43 | $a->{$_} <=> $b->{$_} : |
---|
44 | $a->{$_} cmp $b->{$_}; |
---|
45 | # we found a field they differ on |
---|
46 | last if $compare; |
---|
47 | } |
---|
48 | return $compare; |
---|
49 | } @results; |
---|
50 | } |
---|
51 | |
---|
52 | return @results |
---|
53 | } |
---|
54 | |
---|
55 | sub match_mp3 { |
---|
56 | my ($filename, $query, $results) = @_; |
---|
57 | |
---|
58 | return unless $filename =~ m{[^/]\.mp3$}; |
---|
59 | my $mp3 = { |
---|
60 | FILENAME => $filename, |
---|
61 | %{ get_mp3tag($filename) || {} }, |
---|
62 | %{ get_mp3info($filename) || {} }, |
---|
63 | }; |
---|
64 | for my $field (keys(%{ $query })) { |
---|
65 | my $value = $mp3->{uc($field)}; |
---|
66 | return unless defined $value; |
---|
67 | return unless $value =~ $query->{$field}; |
---|
68 | } |
---|
69 | |
---|
70 | push @{ $results }, $mp3; |
---|
71 | } |
---|
72 | |
---|
73 | # module return |
---|
74 | 1; |
---|