source: mp3-find/trunk/lib/MP3/Find/Filesystem.pm @ 1

Last change on this file since 1 was 1, checked in by peter, 18 years ago

Initial import

File size: 1.9 KB
Line 
1package MP3::Find::Filesystem;
2
3use strict;
4use warnings;
5
6use base 'MP3::Find::Base';
7
8use File::Find;
9use MP3::Info;
10use Scalar::Util qw(looks_like_number);
11
12use_winamp_genres();
13
14sub 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
55sub 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
741;
Note: See TracBrowser for help on using the repository browser.