| 1 | package App::Pimpd::Playlist::Randomize; | ||
| 2 | |||
| 3 | BEGIN { | ||
| 4 | use Exporter; | ||
| 5 | use vars qw(@ISA @EXPORT); | ||
| 6 | @ISA = qw(Exporter); | ||
| 7 | @EXPORT = qw( | ||
| 8 | randomize | ||
| 9 | randomize_albums | ||
| 10 | random_track_in_playlist | ||
| 11 | ); | ||
| 12 | } | ||
| 13 | |||
| 14 | use strict; | ||
| 15 | |||
| 16 | use App::Pimpd; | ||
| 17 | use App::Pimpd::Validate; | ||
| 18 | use List::Util 'shuffle'; | ||
| 19 | |||
| 20 | |||
| 21 | sub randomize { | ||
| 22 | my($no_songs, $artist) = (100, undef); | ||
| 23 | my(@songs, @random); | ||
| 24 | |||
| 25 | # artist provided. | ||
| 26 | # Dont allow randomize(undef, 'Laleh'); | ||
| 27 | if( (defined($_[1])) and (defined($_[0])) ) { | ||
| 28 | $no_songs = shift(@_); | ||
| 29 | $artist = shift(@_); | ||
| 30 | |||
| 31 | use App::Pimpd::Collection::Search; | ||
| 32 | @songs = shuffle(search_db_artist($artist)); | ||
| 33 | @random = @songs[0 .. $no_songs -1]; | ||
| 34 | } | ||
| 35 | else { | ||
| 36 | $no_songs = shift(@_) // 100; | ||
| 37 | @songs = shuffle($mpd->collection->all_pathes); | ||
| 38 | @random = (@songs[0 .. $no_songs - 1]); | ||
| 39 | } | ||
| 40 | return (wantarray()) ? @random : \@random; | ||
| 41 | } | ||
| 42 | |||
| 43 | |||
| 44 | sub randomize_albums { | ||
| 45 | my $no_albums = shift // 10; | ||
| 46 | my @albums = shuffle($mpd->collection->all_albums); | ||
| 47 | |||
| 48 | my @songs; | ||
| 49 | for(@albums) { | ||
| 50 | if($no_albums == 0) { | ||
| 51 | last; | ||
| 52 | } | ||
| 53 | my @songs_on_album = $mpd->collection->songs_from_album($_); | ||
| 54 | if(scalar(@songs_on_album) <= 2) { | ||
| 55 | next; | ||
| 56 | } | ||
| 57 | else { | ||
| 58 | push(@songs, map { $_->file } @songs_on_album); | ||
| 59 | $no_albums--; | ||
| 60 | } | ||
| 61 | } | ||
| 62 | return (wantarray()) ? @songs : scalar(@songs); | ||
| 63 | } | ||
| 64 | |||
| 65 | sub random_track_in_playlist { | ||
| 66 | if(empty_playlist()) { | ||
| 67 | print STDERR "Playlist is empty - nothing to play\n"; | ||
| 68 | return 1; | ||
| 69 | } | ||
| 70 | my @items = $mpd->playlist->as_items; | ||
| 71 | |||
| 72 | @items = shuffle(@items); | ||
| 73 | |||
| 74 | return $items[0]->pos; | ||
| 75 | } | ||
| 76 | |||
| 77 | |||
| 78 | 1; | ||
| 79 | |||
| 80 | __END__ |