-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
YoutubeViewer.pm
1173 lines (862 loc) · 33.3 KB
/
YoutubeViewer.pm
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package WWW::YoutubeViewer;
use utf8;
use 5.016;
use warnings;
use parent qw(
WWW::YoutubeViewer::Search
WWW::YoutubeViewer::Videos
WWW::YoutubeViewer::Channels
WWW::YoutubeViewer::Playlists
WWW::YoutubeViewer::ParseJSON
WWW::YoutubeViewer::Activities
WWW::YoutubeViewer::Subscriptions
WWW::YoutubeViewer::PlaylistItems
WWW::YoutubeViewer::CommentThreads
WWW::YoutubeViewer::Authentication
WWW::YoutubeViewer::VideoCategories
);
=head1 NAME
WWW::YoutubeViewer - A very easy interface to YouTube.
=cut
our $VERSION = '3.7.8';
=head1 SYNOPSIS
use WWW::YoutubeViewer;
my $yv_obj = WWW::YoutubeViewer->new();
...
=head1 SUBROUTINES/METHODS
=cut
my %valid_options = (
# Main options
v => {valid => q[], default => 3},
page => {valid => qr/^(?!0+\z)\d+\z/, default => 1},
http_proxy => {valid => qr/./, default => undef},
hl => {valid => qr/^\w+(?:[\-_]\w+)?\z/, default => undef},
maxResults => {valid => [1 .. 50], default => 10},
topicId => {valid => qr/./, default => undef},
order => {valid => [qw(relevance date rating viewCount title videoCount)], default => undef},
publishedAfter => {valid => qr/^\d+/, default => undef},
publishedBefore => {valid => qr/^\d+/, default => undef},
channelId => {valid => qr/^[-\w]{2,}\z/, default => undef},
channelType => {valid => [qw(any show)], default => undef},
# Video only options
videoCaption => {valid => [qw(any closedCaption none)], default => undef},
videoDefinition => {valid => [qw(any high standard)], default => undef},
videoCategoryId => {valid => qr/^\d+\z/, default => undef},
videoDimension => {valid => [qw(any 2d 3d)], default => undef},
videoDuration => {valid => [qw(any short medium long)], default => undef},
videoEmbeddable => {valid => [qw(any true)], default => undef},
videoLicense => {valid => [qw(any creativeCommon youtube)], default => undef},
videoSyndicated => {valid => [qw(any true)], default => undef},
eventType => {valid => [qw(completed live upcoming)], default => undef},
chart => {valid => [qw(mostPopular)], default => undef},
regionCode => {valid => qr/^[A-Z]{2}\z/i, default => undef},
relevanceLanguage => {valid => qr/^[a-z]+(?:\-\w+)?\z/i, default => undef},
safeSearch => {valid => [qw(none moderate strict)], default => undef},
videoType => {valid => [qw(any episode movie)], default => undef},
comments_order => {valid => [qw(time relevance)], default => 'time'},
subscriptions_order => {valid => [qw(alphabetical relevance unread)], default => undef},
# Misc
debug => {valid => [0 .. 3], default => 0},
timeout => {valid => qr/^\d+\z/, default => 10},
config_dir => {valid => qr/^./, default => q{.}},
cache_dir => {valid => qr/^./, default => q{.}},
cookie_file => {valid => qr/^./, default => undef},
# Booleans
env_proxy => {valid => [1, 0], default => 1},
escape_utf8 => {valid => [1, 0], default => 0},
prefer_mp4 => {valid => [1, 0], default => 0},
prefer_av1 => {valid => [1, 0], default => 0},
# API/OAuth
key => {valid => qr/^.{15}/, default => undef},
client_id => {valid => qr/^.{15}/, default => undef},
client_secret => {valid => qr/^.{15}/, default => undef},
redirect_uri => {valid => qr/^.{15}/, default => 'urn:ietf:wg:oauth:2.0:oob'},
access_token => {valid => qr/^.{15}/, default => undef},
refresh_token => {valid => qr/^.{15}/, default => undef},
authentication_file => {valid => qr/^./, default => undef},
# No input value allowed
feeds_url => {valid => q[], default => 'https://www.googleapis.com/youtube/v3/'},
video_info_url => {valid => q[], default => 'https://www.youtube.com/get_video_info'},
oauth_url => {valid => q[], default => 'https://accounts.google.com/o/oauth2/'},
video_info_args => {valid => q[], default => '?video_id=%s&el=detailpage&ps=default&eurl=&gl=US&hl=en'},
www_content_type => {valid => q[], default => 'application/x-www-form-urlencoded'},
#<<<
# LWP user agent
user_agent => {valid => qr/^.{5}/, default => 'Mozilla/5.0 (Windows NT 10.0; Win64; gzip; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.0.0 Safari/537.36'},
#>>>
);
sub _our_smartmatch {
my ($value, $arg) = @_;
$value // return 0;
if (not ref($arg)) {
return ($value eq $arg);
}
if (ref($arg) eq ref(qr//)) {
return scalar($value =~ $arg);
}
if (ref($arg) eq 'ARRAY') {
foreach my $item (@$arg) {
return 1 if __SUB__->($value, $item);
}
}
return 0;
}
{
no strict 'refs';
foreach my $key (keys %valid_options) {
if (ref($valid_options{$key}{valid})) {
# Create the 'set_*' subroutines
*{__PACKAGE__ . '::set_' . $key} = sub {
my ($self, $value) = @_;
$self->{$key} =
_our_smartmatch($value, $valid_options{$key}{valid})
? $value
: $valid_options{$key}{default};
};
}
# Create the 'get_*' subroutines
*{__PACKAGE__ . '::get_' . $key} = sub {
my ($self) = @_;
if (not exists $self->{$key}) {
return ($self->{$key} = $valid_options{$key}{default});
}
$self->{$key};
};
}
}
=head2 new(%opts)
Returns a blessed object.
=cut
sub new {
my ($class, %opts) = @_;
my $self = bless {}, $class;
foreach my $key (keys %valid_options) {
if (exists $opts{$key}) {
my $method = "set_$key";
$self->$method(delete $opts{$key});
}
}
foreach my $invalid_key (keys %opts) {
warn "Invalid key: '${invalid_key}'";
}
return $self;
}
sub page_token {
my ($self, $number) = @_;
my $page = $number // $self->get_page;
# Don't generate the token for the first page
return undef if $page == 1;
my $index = $page * $self->get_maxResults() - $self->get_maxResults();
my $k = int($index / 128) - 1;
$index -= 128 * $k;
my @f = (8, $index);
if ($k > 0 or $index > 127) {
push @f, $k + 1;
}
require MIME::Base64;
MIME::Base64::encode_base64(pack('C*', @f, 16, 0)) =~ tr/=\n//dr;
}
=head2 escape_string($string)
Escapes a string with URI::Escape and returns it.
=cut
sub escape_string {
my ($self, $string) = @_;
require URI::Escape;
$self->get_escape_utf8
? URI::Escape::uri_escape_utf8($string)
: URI::Escape::uri_escape($string);
}
=head2 set_lwp_useragent()
Initializes the LWP::UserAgent module and returns it.
=cut
sub set_lwp_useragent {
my ($self) = @_;
my $lwp = (
eval { require LWP::UserAgent::Cached; 'LWP::UserAgent::Cached' }
// do { require LWP::UserAgent; 'LWP::UserAgent' }
);
$self->{lwp} = $lwp->new(
cookie_jar => {}, # temporary cookies
timeout => $self->get_timeout,
show_progress => $self->get_debug,
agent => $self->get_user_agent,
ssl_opts => {verify_hostname => 1},
$lwp eq 'LWP::UserAgent::Cached'
? (
cache_dir => $self->get_cache_dir,
nocache_if => sub {
my ($response) = @_;
my $code = $response->code;
$code >= 300 # do not cache any bad response
or $response->request->method ne 'GET' # cache only GET requests
# don't cache if "cache-control" specifies "max-age=0" or "no-store"
or (($response->header('cache-control') // '') =~ /\b(?:max-age=0|no-store)\b/)
# don't cache video or audio files
or (($response->header('content-type') // '') =~ /\b(?:video|audio)\b/);
},
recache_if => sub {
my ($response, $path) = @_;
not($response->is_fresh) # recache if the response expired
or ($response->code == 404 && -M $path > 1); # recache any 404 response older than 1 day
}
)
: (),
env_proxy => (defined($self->get_http_proxy) ? 0 : $self->get_env_proxy),
);
require LWP::ConnCache;
state $cache = LWP::ConnCache->new;
$cache->total_capacity(undef); # no limit
state $accepted_encodings = do {
require HTTP::Message;
HTTP::Message::decodable();
};
my $agent = $self->{lwp};
$agent->ssl_opts(Timeout => $self->get_timeout);
$agent->default_header('Accept-Encoding' => $accepted_encodings);
$agent->conn_cache($cache);
$agent->proxy(['http', 'https'], $self->get_http_proxy) if defined($self->get_http_proxy);
my $cookie_file = $self->get_cookie_file;
if (defined($cookie_file) and -f $cookie_file) {
if ($self->get_debug) {
say STDERR ":: Using cookies from: $cookie_file";
}
## Netscape HTTP Cookies
# Chrome extension:
# https://chrome.google.com/webstore/detail/cookiestxt/njabckikapfpffapmjgojcnbfjonfjfg
# Firefox extension:
# https://addons.mozilla.org/en-US/firefox/addon/cookies-txt/
# See also:
# https://github.com/ytdl-org/youtube-dl#how-do-i-pass-cookies-to-youtube-dl
require HTTP::Cookies::Netscape;
my $cookies = HTTP::Cookies::Netscape->new(
hide_cookie2 => 1,
autosave => 1,
file => $cookie_file,
);
$cookies->load;
$agent->cookie_jar($cookies);
}
push @{$self->{lwp}->requests_redirectable}, 'POST';
return $self->{lwp};
}
=head2 prepare_access_token()
Returns a string. used as header, with the access token.
=cut
sub prepare_access_token {
my ($self) = @_;
if (defined(my $auth = $self->get_access_token)) {
return "Bearer $auth";
}
return;
}
sub _auth_lwp_header {
my ($self) = @_;
my %lwp_header;
if (defined $self->get_access_token) {
$lwp_header{'Authorization'} = $self->prepare_access_token;
}
return %lwp_header;
}
sub _warn_reponse_error {
my ($resp, $url) = @_;
warn sprintf("[%s] Error occurred on URL: %s\n", $resp->status_line, $url =~ s/([&?])key=(.*?)&/${1}key=[...]&/r);
}
=head2 lwp_get($url, %opt)
Get and return the content for $url.
Where %opt can be:
simple => [bool]
When the value of B<simple> is set to a true value, the
authentication header will not be set in the HTTP request.
=cut
sub lwp_get {
my ($self, $url, %opt) = @_;
$url // return;
$self->{lwp} // $self->set_lwp_useragent();
if (not defined($self->get_key)) {
return undef if not $opt{simple};
}
my %lwp_header = ($opt{simple} ? () : $self->_auth_lwp_header);
my $response = $self->{lwp}->get($url, %lwp_header);
if ($response->is_success) {
return $response->decoded_content;
}
if ($response->status_line() =~ /^401 / and defined($self->get_refresh_token)) {
if (defined(my $refresh_token = $self->oauth_refresh_token())) {
if (defined $refresh_token->{access_token}) {
$self->set_access_token($refresh_token->{access_token});
# Don't be tempted to use recursion here, because bad things will happen!
$response = $self->{lwp}->get($url, $self->_auth_lwp_header);
if ($response->is_success) {
$self->save_authentication_tokens();
return $response->decoded_content;
}
elsif ($response->status_line() =~ /^401 /) {
$self->set_refresh_token(); # refresh token was invalid
$self->set_access_token(); # access token is also broken
warn "[!] Can't refresh the access token! Logging out...\n";
}
}
else {
warn "[!] Can't get the access_token! Logging out...\n";
$self->set_refresh_token();
$self->set_access_token();
}
}
else {
warn "[!] Invalid refresh_token! Logging out...\n";
$self->set_refresh_token();
$self->set_access_token();
}
}
$opt{depth} ||= 0;
# Try again on 500+ HTTP errors
if ( $opt{depth} <= 3
and $response->code() >= 500
and $response->status_line() =~ /(?:Temporary|Server) Error|Timeout|Service Unavailable/i) {
return $self->lwp_get($url, %opt, depth => $opt{depth} + 1);
}
_warn_reponse_error($response, $url);
return;
}
=head2 lwp_post($url, [@args])
Post and return the content for $url.
=cut
sub lwp_post {
my ($self, $url, @args) = @_;
$self->{lwp} // $self->set_lwp_useragent();
my $response = $self->{lwp}->post($url, @args);
if ($response->is_success) {
return $response->decoded_content;
}
else {
_warn_reponse_error($response, $url);
}
return;
}
=head2 lwp_mirror($url, $output_file)
Downloads the $url into $output_file. Returns true on success.
=cut
sub lwp_mirror {
my ($self, $url, $output_file) = @_;
$self->{lwp} // $self->set_lwp_useragent();
$self->{lwp}->mirror($url, $output_file);
}
sub _get_results {
my ($self, $url, %opt) = @_;
return
scalar {
url => $url,
results => $self->parse_json_string($self->lwp_get($url, %opt)),
};
}
=head2 list_to_url_arguments(\%options)
Returns a valid string of arguments, with defined values.
=cut
sub list_to_url_arguments {
my ($self, %args) = @_;
join(q{&}, map { "$_=$args{$_}" } grep { defined $args{$_} } sort keys %args);
}
sub _append_url_args {
my ($self, $url, %args) = @_;
%args
? ($url . ($url =~ /\?/ ? '&' : '?') . $self->list_to_url_arguments(%args))
: $url;
}
sub _simple_feeds_url {
my ($self, $suburl, %args) = @_;
$self->get_feeds_url() . $suburl . '?' . $self->list_to_url_arguments(key => $self->get_key, %args);
}
=head2 default_arguments(%args)
Merge the default arguments with %args and concatenate them together.
=cut
sub default_arguments {
my ($self, %args) = @_;
my %defaults = (
key => $self->get_key,
part => 'snippet',
prettyPrint => 'false',
maxResults => $self->get_maxResults,
regionCode => $self->get_regionCode,
%args,
);
$self->list_to_url_arguments(%defaults);
}
sub _make_feed_url {
my ($self, $path, %args) = @_;
$self->get_feeds_url() . $path . '?' . $self->default_arguments(%args);
}
sub get_invidious_instances {
my ($self) = @_;
require File::Spec;
my $instances_file = File::Spec->catfile($self->get_config_dir, 'instances.json');
# Get the "instances.json" file when the local copy is too old or non-existent
if ((not -e $instances_file) or (-M _) > 1 / 24) {
require LWP::UserAgent;
my $lwp = LWP::UserAgent->new(timeout => $self->get_timeout);
$lwp->show_progress(1) if $self->get_debug;
my $resp = $lwp->get("https://instances.invidio.us/instances.json");
$resp->is_success() or return;
my $json = $resp->decoded_content() || return;
open(my $fh, '>', $instances_file) or return;
print $fh $json;
close $fh;
}
open(my $fh, '<', $instances_file) or return;
my $json_string = do {
local $/;
<$fh>;
};
$self->parse_json_string($json_string);
}
sub select_good_invidious_instances {
my ($self) = @_;
state $instances = $self->get_invidious_instances;
ref($instances) eq 'ARRAY' or return;
my %ignored = (
'yewtu.be' => 1,
'invidiou.site' => 1,
'invidious.xyz' => 1,
'vid.mint.lgbt' => 1,
'invidious.ggc-project.de' => 1,
'invidious.toot.koeln' => 1,
'invidious.snopyta.org' => 1, # too popular == too slow
);
my @candidates =
grep { not $ignored{$_->[0]} }
grep { ref($_->[1]{monitor}) eq 'HASH' ? ($_->[1]{monitor}{statusClass} eq 'success') : 1 }
grep { lc($_->[1]{type} // '') eq 'https' } @$instances;
if ($self->get_debug) {
print STDERR ":: Found ", scalar(@candidates), " invidious instances.\n";
}
return @candidates;
}
sub _extract_from_invidious {
my ($self, $videoID) = @_;
my @instances = $self->select_good_invidious_instances();
if (@instances) {
require List::Util;
@instances = List::Util::shuffle(map { $_->[0] } @instances);
}
else {
@instances = qw(
invidious.tube
invidious.site
invidious.fdn.fr
invidious.snopyta.org
invidious.13ad.de
);
}
if ($self->get_debug) {
print STDERR ":: Invidious instances: @instances\n";
}
my $tries = 2 * scalar(@instances);
my $instance = shift(@instances);
my $url_format = "https://%s/api/v1/videos/%s?fields=formatStreams,adaptiveFormats";
my $url = sprintf($url_format, $instance, $videoID);
my $resp = $self->{lwp}->get($url);
while (not $resp->is_success() and --$tries >= 0) {
$url = sprintf($url_format, shift(@instances), $videoID) if (@instances and ($tries % 2 == 0));
$resp = $self->{lwp}->get($url);
}
$resp->is_success() || return;
my $json = $resp->decoded_content() // return;
my $ref = $self->parse_json_string($json) // return;
my @formats;
# The entries are already in the format that we want.
if (exists($ref->{adaptiveFormats}) and ref($ref->{adaptiveFormats}) eq 'ARRAY') {
push @formats, @{$ref->{adaptiveFormats}};
}
if (exists($ref->{formatStreams}) and ref($ref->{formatStreams}) eq 'ARRAY') {
push @formats, @{$ref->{formatStreams}};
}
return @formats;
}
sub _ytdl_is_available {
(state $x = system('youtube-dl', '--version')) == 0;
}
sub _extract_from_ytdl {
my ($self, $videoID) = @_;
$self->_ytdl_is_available() || return;
my @ytdl_cmd = ('youtube-dl', '--all-formats', '--dump-single-json');
my $cookie_file = $self->get_cookie_file;
if (defined($cookie_file) and -f $cookie_file) {
push @ytdl_cmd, '--cookies', $cookie_file;
}
my $json = $self->proxy_stdout(@ytdl_cmd, quotemeta("https://www.youtube.com/watch?v=" . $videoID));
my $ref = $self->parse_json_string($json);
my @formats;
if (ref($ref) eq 'HASH' and exists($ref->{formats}) and ref($ref->{formats}) eq 'ARRAY') {
foreach my $format (@{$ref->{formats}}) {
if (exists($format->{format_id}) and exists($format->{url})) {
my $entry = {
itag => $format->{format_id},
url => $format->{url},
type => ((($format->{format} // '') =~ /audio only/i) ? 'audio/' : 'video/') . $format->{ext},
};
push @formats, $entry;
}
}
}
return @formats;
}
sub _fallback_extract_urls {
my ($self, $videoID) = @_;
my @formats;
# Use youtube-dl
if ($self->_ytdl_is_available) {
if ($self->get_debug) {
say STDERR ":: Using youtube-dl to extract the streaming URLs...";
}
push @formats, $self->_extract_from_ytdl($videoID);
if ($self->get_debug) {
my $count = scalar(@formats);
say STDERR ":: youtube-dl: found $count streaming URLs...";
}
@formats && return @formats;
}
# Use the API of invidio.us
if ($self->get_debug) {
say STDERR ":: Using invidio.us to extract the streaming URLs...";
}
push @formats, $self->_extract_from_invidious($videoID);
if ($self->get_debug) {
my $count = scalar(@formats);
say STDERR ":: invidious: found $count streaming URLs...";
}
return @formats;
}
=head2 parse_query_string($string, multi => [0,1])
Parse a query string and return a data structure back.
When the B<multi> option is set to a true value, the function will store multiple values for a given key.
Returns back a list of key-value pairs.
=cut
sub parse_query_string {
my ($self, $str, %opt) = @_;
if (not defined($str)) {
return;
}
require URI::Escape;
my @pairs;
foreach my $statement (split(/,/, $str)) {
foreach my $pair (split(/&/, $statement)) {
push @pairs, $pair;
}
}
my %result;
foreach my $pair (@pairs) {
my ($key, $value) = split(/=/, $pair, 2);
if (not defined($value) or $value eq '') {
next;
}
$value = URI::Escape::uri_unescape($value =~ tr/+/ /r);
if ($opt{multi}) {
push @{$result{$key}}, $value;
}
else {
$result{$key} = $value;
}
}
return %result;
}
sub _group_keys_with_values {
my ($self, %data) = @_;
my @hashes;
foreach my $key (keys %data) {
foreach my $i (0 .. $#{$data{$key}}) {
$hashes[$i]{$key} = $data{$key}[$i];
}
}
return @hashes;
}
sub _check_streaming_urls {
my ($self, $videoID, $results) = @_;
foreach my $video (@$results) {
if ( exists $video->{s}
or exists $video->{signatureCipher}
or exists $video->{cipher}) { # has an encrypted signature :(
if ($self->get_debug) {
say STDERR ":: Detected an encrypted signature...";
}
my @formats = $self->_fallback_extract_urls($videoID);
foreach my $format (@formats) {
foreach my $ref (@$results) {
if (defined($ref->{itag}) and ($ref->{itag} eq $format->{itag})) {
$ref->{url} = $format->{url};
last;
}
}
}
last;
}
}
foreach my $video (@$results) {
if (exists $video->{mimeType}) {
$video->{type} = $video->{mimeType};
}
}
return 1;
}
sub _old_extract_streaming_urls {
my ($self, $info, $videoID) = @_;
if ($self->get_debug) {
say STDERR ":: Using `url_encoded_fmt_stream_map` to extract the streaming URLs...";
}
my %stream_map = $self->parse_query_string($info->{url_encoded_fmt_stream_map}, multi => 1);
my %adaptive_fmts = $self->parse_query_string($info->{adaptive_fmts}, multi => 1);
if ($self->get_debug >= 2) {
require Data::Dump;
Data::Dump::pp(\%stream_map);
Data::Dump::pp(\%adaptive_fmts);
}
my @results;
push @results, $self->_group_keys_with_values(%stream_map);
push @results, $self->_group_keys_with_values(%adaptive_fmts);
$self->_check_streaming_urls($videoID, \@results);
if ($info->{livestream} or $info->{live_playback}) {
if ($self->get_debug) {
say STDERR ":: Live stream detected...";
}
if (my @formats = $self->_fallback_extract_urls($videoID)) {
@results = @formats;
}
elsif (exists $info->{hlsvp}) {
push @results,
{
itag => 38,
type => 'video/ts',
url => $info->{hlsvp},
};
}
}
return @results;
}
sub _extract_streaming_urls {
my ($self, $info, $videoID) = @_;
if (exists $info->{url_encoded_fmt_stream_map}) {
return $self->_old_extract_streaming_urls($info, $videoID);
}
if ($self->get_debug) {
say STDERR ":: Using `player_response` to extract the streaming URLs...";
}
my $json = $self->parse_json_string($info->{player_response} // return);
if ($self->get_debug >= 2) {
require Data::Dump;
Data::Dump::pp($json);
}
ref($json) eq 'HASH' or return;
my @results;
if (exists $json->{streamingData}) {
my $streamingData = $json->{streamingData};
if (exists $streamingData->{adaptiveFormats}) {
push @results, @{$streamingData->{adaptiveFormats}};
}
if (exists $streamingData->{formats}) {
push @results, @{$streamingData->{formats}};
}
}
$self->_check_streaming_urls($videoID, \@results);
# Keep only streams with contentLength > 0.
@results = grep { $_->{itag} == 22 or (exists($_->{contentLength}) and $_->{contentLength} > 0) } @results;
# Detect livestream
if (!@results and exists($json->{streamingData}) and exists($json->{streamingData}{hlsManifestUrl})) {
if ($self->get_debug) {
say STDERR ":: Live stream detected...";
}
@results = $self->_fallback_extract_urls($videoID);
if (!@results) {
push @results,
{
itag => 38,
type => "video/ts",
url => $json->{streamingData}{hlsManifestUrl},
};
}
}
return @results;
}
sub _get_video_info {
my ($self, $videoID) = @_;
my $url = $self->get_video_info_url() . sprintf($self->get_video_info_args(), $videoID);
my $content = $self->lwp_get($url, simple => 1) // return;
my %info = $self->parse_query_string($content);
return %info;
}
=head2 get_streaming_urls($videoID)
Returns a list of streaming URLs for a videoID.
({itag=>..., url=>...}, {itag=>..., url=>....}, ...)
=cut
sub get_streaming_urls {
my ($self, $videoID) = @_;
my %info = $self->_get_video_info($videoID);
my @streaming_urls = $self->_extract_streaming_urls(\%info, $videoID);
my @caption_urls;
if (exists $info{player_response}) {
my $captions_json = $info{player_response}; # don't run uri_unescape() on this
my $caption_data = $self->parse_json_string($captions_json);
if (eval { ref($caption_data->{captions}{playerCaptionsTracklistRenderer}{captionTracks}) eq 'ARRAY' }) {
push @caption_urls, @{$caption_data->{captions}{playerCaptionsTracklistRenderer}{captionTracks}};
}
}
if ($self->get_debug) {
my $count = scalar(@streaming_urls);
say STDERR ":: Found $count streaming URLs...";
}
# Try again with youtube-dl
if (!@streaming_urls or $info{status} =~ /fail|error/i) {
@streaming_urls = $self->_fallback_extract_urls($videoID);
}
if ($self->get_prefer_mp4 or $self->get_prefer_av1) {
my @video_urls;
my @audio_urls;
require WWW::YoutubeViewer::Itags;
state $itags = WWW::YoutubeViewer::Itags::get_itags();
my %audio_itags;
@audio_itags{map { $_->{value} } @{$itags->{audio}}} = ();
foreach my $url (@streaming_urls) {
if (exists($audio_itags{$url->{itag}})) {
push @audio_urls, $url;
next;
}
if ($url->{type} =~ /\bvideo\b/i) {
if ($url->{type} =~ /\bav[0-9]+\b/i) { # AV1
if ($self->get_prefer_av1) {
push @video_urls, $url;
}
}
elsif ($self->get_prefer_mp4 and $url->{type} =~ /\bmp4\b/i) {
push @video_urls, $url;
}
}
else {
push @audio_urls, $url;
}
}