Changes URL to eztv.ag and tries to fix DOM parsing.
[cascardo/www-eztv.git] / lib / WWW / EZTV / Show.pm
1 package WWW::EZTV::Show;
2
3 use Moose;
4 use v5.10;
5 with 'WWW::EZTV::UA';
6 use WWW::EZTV::Link;
7 use WWW::EZTV::Episode;
8
9 # ABSTRACT: Show object
10
11 has title    => is => 'ro', isa => 'Str', required => 1;
12 has name     => is => 'ro', lazy => 1, default => \&_name;
13 has year     => is => 'ro', lazy => 1, default => \&_year;
14 has url      => is => 'ro', isa => 'Mojo::URL', required => 1;
15 has status   => is => 'ro', isa => 'Str', required => 1;
16 has rating   => is => 'ro', isa => 'Num', default => sub {0};
17 has episodes =>
18     is      => 'ro',
19     lazy    => 1,
20     builder => '_build_episodes',
21     handles => {
22         find_episode => 'first',
23         has_episodes => 'size',
24     };
25
26 sub _build_episodes {
27     my $self = shift;
28     $self->get_response($self->url)->dom->find('table tr[name="hover"]')->map(sub{
29         my $tr = shift;
30         my $link = $tr->at('td:nth-child(2) a');
31
32         WWW::EZTV::Episode->new(
33             title    => $link->attr('alt'),
34             url      => $self->url->clone->path($link->attr('href')),
35             links    => $tr->find('td:nth-child(3) a')->map(sub{
36                 WWW::EZTV::Link->new( url => $_[0]->attr('href')
37                                           || $_[0]->attr('data-url')
38                                           || $_[0]->attr('data-bx-magnet') )
39             }),
40             released => $tr->at('td:nth-child(4)')->all_text,
41             show     => $self
42         );
43     });
44 }
45
46 sub _name {
47     my $self = shift;
48     my $name = $self->title;
49
50     # Chasers War on Everything, The
51     if ( $name =~ /^(.+),\s*([^,]+)$/ ) { $name = "$2 $1" }
52
53     # Remove year: Castle (2009)
54     $name =~ s/\s* \(\d{4}\) \s*/ /x;
55
56     # Trim and cleanup spaces
57     $self->_cleanup_str($name);
58 }
59
60 sub _year {
61     my $self = shift;
62     if ( $self->title =~ /\((\d{4})\)/ ) {
63         return $1;
64     }
65 }
66
67 sub _cleanup_str {
68     my $str = pop;
69     $str =~ s/^\s+|\s+$//g;
70     $str =~ s/\s+/ /g;
71     $str;
72 }
73
74 1;
75
76 =attr title
77 =cut
78
79 =attr name
80 =cut
81
82 =attr year
83 =cut
84
85 =attr url
86 =cut
87
88 =attr status
89 =cut
90
91 =attr rating
92 =cut
93
94 =attr episodes
95
96 Collection of episodes fetched for this show.
97
98 =cut
99
100 =attr has_episodes
101
102 How many episodes has this show.
103
104 =cut
105
106 =method find_episode
107
108 Find first L<WWW::EZTV::Episode> object matching the given criteria. 
109 This method accept an anon function.
110
111 =cut
112