PageRenderTime 274ms CodeModel.GetById 111ms app.highlight 12ms RepoModel.GetById 149ms app.codeStats 0ms

/lib/Teto/Worker/FeedTracksToQueue.pm

http://github.com/motemen/Teto
Perl | 79 lines | 60 code | 19 blank | 0 comment | 1 complexity | 0de5f5a2f11f170849abfefe47926f72 MD5 | raw file
 1package Teto::Worker::FeedTracksToQueue;
 2use Mouse;
 3use MouseX::Types::URI;
 4use Coro;
 5
 6with 'Teto::Role::Log';
 7
 8has playlist => (
 9    is  => 'rw',
10    isa => 'Teto::Playlist',
11);
12
13has queue => (
14    is  => 'rw',
15    isa => 'Teto::Queue',
16);
17
18has dismissed => (
19    is  => 'rw',
20);
21
22__PACKAGE__->meta->make_immutable;
23
24no Mouse;
25
26sub spawn {
27    my ($class, %args) = @_;
28    my $self = $class->new(%args);
29    $self->work_async;
30    return $self;
31}
32
33sub work_async {
34    my $self = shift;
35
36    async {
37        $Coro::current->{desc} = 'FeedTracksToQueue';
38        $self->work;
39    };
40}
41
42sub work {
43    my $self = shift;
44
45    $self->queue->clear;
46
47    my @tracks = $self->playlist->tracks;
48    $self->queue->add_track(@tracks);
49
50    until ($self->dismissed) {
51        $self->log(debug => 'wait for playlist signal');
52        $self->playlist->track_signal->wait;
53
54        my @new_tracks = do {
55            my @tt = $self->playlist->tracks;
56            splice @tt, scalar @tracks;
57        };
58        $self->log(debug => 'playlist signal: got ' . scalar(@new_tracks) . ' new tracks');
59        $self->queue->add_track(@new_tracks);
60
61        push @tracks, @new_tracks;
62    }
63}
64
65sub dismiss {
66    my $self = shift;
67    $self->{dismissed}++;
68    $self->log(debug => 'dismissed');
69}
70
71sub DESTROY {
72    my $self = shift;
73
74    local $@;
75    eval { $self->dismiss };
76    warn $@ if $@;
77}
78
791;