aboutsummaryrefslogtreecommitdiffstats
path: root/lib/WWW/FairViewer/Search.pm
blob: 69ae5600c4f945c7064ab28420e4c04ca28951b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package WWW::FairViewer::Search;

use utf8;
use 5.014;
use warnings;

=head1 NAME

WWW::FairViewer::Search - Search functions for Fair API v3

=head1 SYNOPSIS

    use WWW::FairViewer;
    my $obj = WWW::FairViewer->new(%opts);
    $obj->search_videos(@keywords);

=head1 SUBROUTINES/METHODS

=cut

sub _make_search_url {
    my ($self, %opts) = @_;

    my @features;

    if (defined(my $vd = $self->get_videoDefinition)) {
        if ($vd eq 'high') {
            push @features, 'hd';
        }
    }

    if (defined(my $vc = $self->get_videoCaption)) {
        if ($vc eq 'true' or $vc eq '1') {
            push @features, 'subtitles';
        }
    }

    if (defined(my $vd = $self->get_videoDimension)) {
        if ($vd eq '3d') {
            push @features, '3d';
        }
    }

    if (defined(my $license = $self->get_videoLicense)) {
        if ($license eq 'creative_commons') {
            push @features, 'creative_commons';
        }
    }

    return $self->_make_feed_url(
        'search',

        region    => $self->get_region,
        sort_by   => $self->get_order,
        date      => $self->get_date,
        pageToken => $self->page_token,
        duration  => $self->get_videoDuration,

        (@features ? (features => join(',', @features)) : ()),

        %opts,
                                );
}

=head2 search_for($types,$keywords;\%args)

Search for a list of types (comma-separated).

=cut

sub search_for {
    my ($self, $type, $keywords, $args) = @_;

    if (ref($args) ne 'HASH') {
        $args = {};
    }

    $keywords //= [];

    if (ref($keywords) ne 'ARRAY') {
        $keywords = [split ' ', $keywords];
    }

    $keywords = $self->escape_string(join(' ', @{$keywords}));

    # Search in a channel's videos
    if (defined(my $channel_id = $self->get_channelId)) {
        my $url = $self->_make_feed_url("channels/search/$channel_id", q => $keywords,);
        return $self->_get_results($url);
    }

    my $url = $self->_make_search_url(
                                      type => $type,
                                      q    => $keywords,
                                      %$args,
                                     );

    return $self->_get_results($url);
}

{
    no strict 'refs';

    foreach my $pair (
                      {
                       name => 'videos',
                       type => 'video',
                      },
                      {
                       name => 'playlists',
                       type => 'playlist',
                      },
                      {
                       name => 'channels',
                       type => 'channel',
                      },
                      {
                       name => 'all',
                       type => 'all',
                      }
      ) {
        *{__PACKAGE__ . '::' . "search_$pair->{name}"} = sub {
            my $self = shift;
            $self->search_for($pair->{type}, @_);
        };
    }
}

=head2 search_videos($keywords;\%args)

Search and return the found video results.

=cut

=head2 search_playlists($keywords;\%args)

Search and return the found playlists.

=cut

=head2 search_channels($keywords;\%args)

Search and return the found channels.

=cut

=head2 search_all($keywords;\%args)

Search and return the results.

=cut

=head2 related_to_videoID($id)

Retrieves a list of videos that are related to the video
that the parameter value identifies. The parameter value must
be set to a YouTube video ID.

=cut

sub related_to_videoID {
    my ($self, $videoID) = @_;

    my %info                = $self->_get_video_info($videoID);
    my $watch_next_response = $self->parse_json_string($info{watch_next_response});
    my $related =
      eval { $watch_next_response->{contents}{twoColumnWatchNextResults}{secondaryResults}{secondaryResults}{results} }
      // return {results => []};

    #use Data::Dump qw(pp);
    #pp $related;

    my @results;

    foreach my $entry (@$related) {

        my $info  = $entry->{compactVideoRenderer} // next;
        my $title = $info->{title}{simpleText}     // next;

        my $viewCount = 0;

        if (($info->{viewCountText}{simpleText} // '') =~ /^([\d,]+) views/) {
            $viewCount = ($1 =~ tr/,//dr);
        }
        elsif (($info->{viewCountText}{simpleText} // '') =~ /Recommended for you/i) {
            next;    # filter out recommended videos from related videos
        }

        my $lengthSeconds = 0;

        if (($info->{lengthText}{simpleText} // '') =~ /([\d:]+)/) {
            my $time   = $1;
            my @fields = split(/:/, $time);

            my $seconds = pop(@fields) // 0;
            my $minutes = pop(@fields) // 0;
            my $hours   = pop(@fields) // 0;

            $lengthSeconds = 3600 * $hours + 60 * $minutes + $seconds;
        }

        my $published = 0;
        if (exists $info->{publishedTimeText} and $info->{publishedTimeText}{simpleText} =~ /(\d+)\s+(\w+)\s+ago/) {

            my $quantity = $1;
            my $period   = $2;

            $period =~ s/s\z//;    # make it singural

            my %table = (
                         year   => 31556952,      # seconds in a year
                         month  => 2629743.83,    # seconds in a month
                         week   => 604800,        # seconds in a week
                         day    => 86400,         # seconds in a day
                         hour   => 3600,          # seconds in a hour
                         minute => 60,            # seconds in a minute
                         second => 1,             # seconds in a second
                        );

            if (exists $table{$period}) {
                $published = int(time - $quantity * $table{$period});
            }
            else {
                warn "BUG: cannot parse: <<$quantity $period>>";
            }
        }

        push @results, {
            type     => "video",
            title    => $title,
            videoId  => $info->{videoId},
            author   => $info->{longBylineText}{runs}[0]{text},
            authorId => $info->{longBylineText}{runs}[0]{navigationEndpoint}{browseEndpoint}{browseId},

            #authorUrl => $info->{longBylineText}{runs}[0]{navigationEndpoint}{browseEndpoint}{browseId},

            description     => $info->{accessibility}{accessibilityData}{label},
            descriptionHtml => undef,
            viewCount       => $viewCount,
            published       => $published,
            publishedText   => $info->{publishedTimeText}{simpleText},
            lengthSeconds   => $lengthSeconds,
            liveNow         => ($lengthSeconds == 0),                              # maybe it's live if lengthSeconds == 0?
            paid            => 0,
            premium         => 0,

            videoThumbnails => [
                map {
                    scalar {
                            quality => 'medium',
                            url     => $_->{url},
                            width   => $_->{width},
                            height  => $_->{height},
                           }
                } @{$info->{thumbnail}{thumbnails}}
            ],
        };
    }

    return
      scalar {
              url     => undef,
              results => \@results,
             };
}

=head1 AUTHOR

Trizen, C<< <echo dHJpemVuQHByb3Rvbm1haWwuY29tCg== | base64 -d> >>

Jesus, C<< <echo aGVja3llbEBoeXBlcmJvbGEuaW5mbw== | base64 -d> >>


=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc WWW::FairViewer::Search


=head1 LICENSE AND COPYRIGHT

Copyright 2013-2015 Trizen.

Copyright 2020 Jesus E.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See L<http://dev.perl.org/licenses/> for more information.

=cut

1;    # End of WWW::FairViewer::Search