-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
youtube-viewer
executable file
·4252 lines (3506 loc) · 138 KB
/
youtube-viewer
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
#!/usr/bin/perl
# Copyright (C) 2010-2020 Trizen <echo dHJpemVuQHByb3Rvbm1haWwuY29tCg== | base64 -d>.
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See https://dev.perl.org/licenses/ for more information.
#
#-------------------------------------------------------
# youtube-viewer
# Created on: 02 June 2010
# Latest edit on: 17 September 2020
# https://github.com/trizen/youtube-viewer
#-------------------------------------------------------
# youtube-viewer is a command line utility for streaming YouTube videos in mpv/vlc.
# Many thanks to everyone who contributed in making this application:
# https://github.com/trizen/youtube-viewer/graphs/contributors
# Special thanks to:
# - Army (for the bug reports and for his great ideas: https://aur.archlinux.org/packages.php?ID=37779&comments=all)
# - dhn (for adding youtube-viewer in freshports.org: http://www.freshports.org/multimedia/youtube-viewer)
# - stressat (for the great review of youtube-viewer: http://stressat.blogspot.com/2012/01/youtube-viewer.html)
# - symbianflo (for packaging youtube-viewer for Mandriva: https://abf.rosalinux.ru/symbianflo/youtube-viewer)
# - gotbletu (for the great video review of youtube-viewer: http://www.youtube.com/watch?v=FnJ67oAxVQ4)
# - Julian Ospald (for adding youtube-viewer in the gentoo portage tree: http://packages.gentoo.org/package/net-misc/youtube-viewer)
# - 666philb (for packaging gtk-youtube-viewer for Puppy Linux: http://www.murga-linux.com/puppy/viewtopic.php?t=76835)
# - Kevin Lemonnier (for adding proxy support - https://github.com/trizen/youtube-viewer/pull/18)
# - Georgo (for adding the 'Watch Later' feature - https://github.com/trizen/youtube-viewer/pull/44)
# - Daniel Wallace (for adding youtube-viewer in the Arch Official Community repository - https://www.archlinux.org/packages/community/any/youtube-viewer/)
# - NTmatter (for adding reverse range support - https://github.com/trizen/youtube-viewer/pull/2)
# - Andrew (for a nice review of (gtk-)youtube-viewer: http://www.webupd8.org/2015/02/youtube-viewer-complete-youtube-client.html)
# - AnyComputer (for a complete french review of gtk-youtube-viewer: https://www.youtube.com/watch?v=6-qbdDUlBqg)
# - Jookia (for fixing the proxy system and improving the support for encrypted videos - https://github.com/Jookia)
=head1 NAME
youtube-viewer - YouTube from command line.
See: youtube-viewer --help
youtube-viewer --tricks
youtube-viewer --examples
youtube-viewer --stdin-help
=head1 LICENSE AND COPYRIGHT
Copyright 2010-2020 Trizen.
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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See L<https://dev.perl.org/licenses/> for more information.
=cut
use utf8;
use 5.016;
use warnings;
no warnings 'once';
my $DEVEL; # true in devel mode
use if ($DEVEL = 0), lib => qw(../lib); # devel mode
use WWW::YoutubeViewer v3.7.9;
use WWW::YoutubeViewer::RegularExpressions;
use File::Spec::Functions qw(
catdir
catfile
curdir
path
rel2abs
file_name_is_absolute
);
binmode(STDOUT, ':utf8');
my $appname = 'YouTube Viewer';
my $version = $WWW::YoutubeViewer::VERSION;
my $execname = 'youtube-viewer';
# A better <STDIN> support:
require Term::ReadLine;
my $term = Term::ReadLine->new("$appname $version");
sub VIDEO_PART () { 'contentDetails,statistics,snippet' }
# Options (key=>value) goes here
my %opt;
my $term_width = 80;
# Keep track of watched videos by their ID
my %watched_videos;
# Unchangeable data goes here
my %constant = (win32 => ($^O eq 'MSWin32' ? 1 : 0)); # doh
my $home_dir;
my $xdg_config_home = $ENV{XDG_CONFIG_HOME};
if ($xdg_config_home and -d -w $xdg_config_home) {
require File::Basename;
$home_dir = File::Basename::dirname($xdg_config_home);
if (not -d -w $home_dir) {
$home_dir = $ENV{HOME} || curdir();
}
}
else {
$home_dir =
$ENV{HOME}
|| $ENV{LOGDIR}
|| ($constant{win32} ? '\Local Settings\Application Data' : ((getpwuid($<))[7] || `echo -n ~`));
if (not -d -w $home_dir) {
$home_dir = curdir();
}
$xdg_config_home = catdir($home_dir, '.config');
}
# Configuration dir/file
my $config_dir = catdir($xdg_config_home, $execname);
my $config_file = catfile($config_dir, "$execname.conf");
my $authentication_file = catfile($config_dir, 'reg.dat');
my $history_file = catfile($config_dir, 'cli-history.txt');
my $watched_file = catfile($config_dir, 'watched.txt');
my $api_file = catfile($config_dir, 'api.json');
my $default_api_file = '/etc/youtube-viewer/api.json';
if (not -d $config_dir) {
require File::Path;
File::Path::make_path($config_dir)
or warn "[!] Can't create dir '$config_dir': $!";
}
sub which_command {
my ($cmd) = @_;
if (file_name_is_absolute($cmd)) {
return $cmd;
}
state $paths = [path()];
foreach my $path (@{$paths}) {
my $cmd_path = catfile($path, $cmd);
if (-f -x $cmd_path) {
return $cmd_path;
}
}
return;
}
# Main configuration
my %CONFIG = (
video_players => {
vlc => {
cmd => q{vlc},
srt => q{--sub-file=*SUB*},
audio => q{--input-slave=*AUDIO*},
fs => q{--fullscreen},
arg => q{--quiet --play-and-exit --no-video-title-show --input-title-format=*TITLE*},
novideo => q{--intf=dummy --novideo},
},
mpv => {
cmd => q{mpv},
srt => q{--sub-file=*SUB*},
audio => q{--audio-file=*AUDIO*},
fs => q{--fullscreen},
arg => q{--really-quiet --title=*TITLE* --no-ytdl},
novideo => q{--no-video},
},
},
video_player_selected => (
$constant{win32}
? 'vlc'
: undef # auto-defined
),
# YouTube options
dash_support => 1,
dash_mp4_audio => 1,
dash_segmented => 1, # may load slow
maxResults => 20,
hfr => 1,
resolution => 'best',
videoDefinition => undef,
videoDimension => undef,
videoLicense => undef,
safeSearch => undef,
videoCaption => undef,
videoDuration => undef,
videoSyndicated => undef,
publishedBefore => undef,
publishedAfter => undef,
order => undef,
comments_order => 'time', # valid values: time, relevance
subscriptions_order => 'relevance', # valid values: alphabetical, relevance, unread
hl => 'en_US',
regionCode => undef,
# URI options
youtube_video_url => 'https://www.youtube.com/watch?v=%s',
# Subtitle options
srt_languages => ['en', 'es'],
get_captions => 1,
auto_captions => 0,
copy_caption => 0,
cache_dir => undef, # auto-defined
# Others
autoplay_mode => 0,
http_proxy => undef,
cookie_file => undef,
user_agent => undef,
timeout => undef,
env_proxy => 1,
confirm => 0,
debug => 0,
page => 1,
colors => $constant{win32} ^ 1,
skip_if_exists => 1,
prefer_mp4 => 0,
prefer_av1 => 0,
ignore_av1 => 0,
fat32safe => $constant{win32},
fullscreen => 0,
results_with_details => 0,
results_with_colors => 0,
results_fixed_width => undef, # auto-defined
show_video_info => 1,
interactive => 1,
get_term_width => $constant{win32} ^ 1,
download_with_wget => undef, # auto-defined
thousand_separator => q{,},
downloads_dir => curdir(),
keep_original_video => 0,
download_and_play => 0,
skip_watched => 0,
remember_watched => 0,
watched_file => $watched_file,
highlight_watched => 1,
highlight_color => 'bold',
remove_played_file => 0,
history => undef, # auto-defined
history_limit => 100_000,
history_file => $history_file,
convert_cmd => 'ffmpeg -i *IN* *OUT*',
convert_to => undef,
custom_layout => undef, # auto-defined
custom_layout_format => [{width => 3, align => "right", color => "bold", text => "*NO*.",},
{width => "55%", align => "left", color => "bold blue", text => "*TITLE*",},
{width => "15%", align => "left", color => "yellow", text => "*AUTHOR*",},
{width => 3, align => "right", color => "green", text => "*AGE_SHORT*",},
{width => 5, align => "right", color => "green", text => "*VIEWS_SHORT*",},
{width => 8, align => "right", color => "blue", text => "*TIME*",},
],
ffmpeg_cmd => 'ffmpeg',
wget_cmd => 'wget',
merge_into_mkv => undef, # auto-defined later
merge_into_mkv_args => '-loglevel warning -c:s srt -c:v copy -c:a copy -disposition:s forced',
merge_with_captions => 1,
video_filename_format => '*FTITLE* - *ID*.*FORMAT*',
);
local $SIG{__WARN__} = sub { warn @_; ++$opt{_error} };
my %MPLAYER; # will store video player arguments
my $base_options = <<'BASE';
# Base
[keywords] : search for YouTube videos
[youtube-url] : play a video by YouTube URL
:v(ideoid)=ID : play videos by YouTube video IDs
[playlist-url] : display videos from a playlistURL
:playlist=ID : display videos from a playlistID
BASE
my $action_options = <<'ACTIONS';
# Actions
:login : will prompt you for login
:logout : will delete the authentication key
ACTIONS
my $control_options = <<'CONTROL';
# Control
:n(ext) : get the next page of results
:b(ack) : get the previous page of results
CONTROL
my $other_options = <<'OTHER';
# Others
:r(eturn) : return to previous page of results
:refresh : refresh the current list of results
:dv=i : display the data structure of result i
-argv -argv2=v : apply some arguments (e.g.: -u=google)
:reset, :reload : restart the application
:q, :quit, :exit : close the application
OTHER
my $notes_options = <<'NOTES';
NOTES:
1. You can specify more options in a row, separated by spaces.
2. A stdin option is valid only if it begins with '=', ';' or ':'.
3. Quoting a group of space separated keywords or option-values,
the group will be considered a single keyword or a single value.
NOTES
my $general_help = <<"HELP";
$action_options
$control_options
$other_options
$notes_options
Examples:
3 : select the 3rd result
-sv funny cats : search for videos
-sc mathematics : search for channels
-sp classical music : search for playlists
HELP
my $playlists_help = <<"PL_HELP" . $general_help;
# Playlists
:pp=i,i : play videos from the selected playlists
PL_HELP
my $comments_help = <<"COM_HELP" . $general_help;
# Comments
:c(omment) : send a comment to this video
COM_HELP
my $complete_help = <<"STDIN_HELP";
$base_options
$control_options
$action_options
# YouTube
:i(nfo)=i,i : display more information
:d(ownload)=i,i : download the selected videos
:c(omments)=i : display video comments
:r(elated)=i : display related videos
:u(ploads)=i : display author's latest uploads
:pv=i :popular=i : display author's popular uploads
:A(ctivity)=i : display author's recent activity
:p(laylists)=i : display author's playlists
:ps=i :s2p=i,i : save videos to a post-selected playlist
:subscribe=i : subscribe to author's channel
:(dis)like=i : like or dislike a video
:fav(orite)=i : favorite a video
:autoplay=i : autoplay mode, starting from video i
:page=i : jump to page i of results
:beg :end : jump to first or last page of results
# Playing
<number> : play the corresponding video
3-8, 3..8 : same as 3 4 5 6 7 8
8-3, 8..3 : same as 8 7 6 5 4 3
8 2 12 4 6 5 1 : play the videos in a specific order
10.. : play all the videos onwards from 10
:q(ueue)=i,i,... : enqueue videos for playing them later
:pq, :play-queue : play the enqueued videos (if any)
:anp, :nnp : auto-next-page, no-next-page
:play=i,i,... : play a group of selected videos
:regex=my?[regex] : play videos matched by a regex (/i)
:kregex=KEY,RE : play videos if the value of KEY matches the RE
$other_options
$notes_options
** Examples:
:regex="\\w \\d" -> play videos matched by a regular expression.
:info=1 -> show extra information for the first video.
:d18-20,1,2 -> download the selected videos: 18, 19, 20, 1 and 2.
3 4 :next 9 -> play the 3rd and 4th videos from the current
page, go to the next page and play the 9th video.
STDIN_HELP
{
my $config_documentation = <<"EOD";
#!/usr/bin/perl
# $appname $version - configuration file
EOD
sub dump_configuration {
my ($config_file) = @_;
require Data::Dump;
open my $config_fh, '>', $config_file
or do { warn "[!] Can't open '${config_file}' for write: $!"; return };
my $dumped_config = q{our $CONFIG = } . Data::Dump::pp(\%CONFIG) . "\n";
if (defined($ENV{HOME}) and $home_dir eq $ENV{HOME}) {
$dumped_config =~ s/\Q$home_dir\E/\$ENV{HOME}/g;
}
print $config_fh $config_documentation, $dumped_config;
close $config_fh;
}
}
our $CONFIG;
sub load_config {
my ($config_file) = @_;
if (not -e $config_file or -z _ or $opt{reconfigure}) {
dump_configuration($config_file);
}
require $config_file; # Load the configuration file
if (ref $CONFIG ne 'HASH') {
die "[ERROR] Invalid configuration file!\n\t\$CONFIG is not an HASH ref!";
}
# Get valid config keys
my @valid_keys = grep { exists $CONFIG{$_} } keys %{$CONFIG};
@CONFIG{@valid_keys} = @{$CONFIG}{@valid_keys};
my $update_config = 0;
# Define the cache directory
if (not defined $CONFIG{cache_dir}) {
my $cache_dir =
($ENV{XDG_CACHE_HOME} and -d -w $ENV{XDG_CACHE_HOME})
? $ENV{XDG_CACHE_HOME}
: catdir($home_dir, '.cache');
if (not -d -w $cache_dir) {
$cache_dir = catdir(curdir(), '.cache');
}
$CONFIG{cache_dir} = catdir($cache_dir, 'youtube-viewer');
$update_config = 1;
}
# Locating a video player
if (not $CONFIG{video_player_selected}) {
foreach my $key (sort keys %{$CONFIG{video_players}}) {
if (defined(my $abs_player_path = which_command($CONFIG{video_players}{$key}{cmd}))) {
$CONFIG{video_players}{$key}{cmd} = $abs_player_path;
$CONFIG{video_player_selected} = $key;
$update_config = 1;
last;
}
}
if (not $CONFIG{video_player_selected}) {
warn "\n[!] Please install a supported video player! (e.g.: mpv)\n\n";
$CONFIG{video_player_selected} = 'mpv';
}
}
# Download with wget if it is installed
if (not defined $CONFIG{download_with_wget}) {
my $wget_path = which_command('wget');
if (defined($wget_path)) {
$CONFIG{wget_cmd} = $wget_path;
$CONFIG{download_with_wget} = 1;
}
else {
$CONFIG{download_with_wget} = 0;
}
$update_config = 1;
}
# Merge into MKV if ffmpeg is installed
if (not defined $CONFIG{merge_into_mkv}) {
my $ffmpeg_path = which_command('ffmpeg');
if (defined($ffmpeg_path)) {
$CONFIG{ffmpeg_cmd} = $ffmpeg_path;
$CONFIG{merge_into_mkv} = 1;
}
else {
$CONFIG{merge_into_mkv} = 0;
}
$update_config = 1;
}
# Fixed-width format and custom layout
if ( not defined($CONFIG{results_fixed_width})
or not defined($CONFIG{custom_layout})) {
if ( eval { require Unicode::GCString; 1 }
or eval { require Text::CharWidth; 1 }) {
$CONFIG{custom_layout} //= 1;
$CONFIG{results_fixed_width} //= 1;
}
else {
$CONFIG{custom_layout} = 0;
$CONFIG{results_fixed_width} = 0;
}
$update_config = 1;
}
# Enable history if Term::ReadLine::Gnu::XS is installed
if (not defined $CONFIG{history}) {
if (eval { $term->can('ReadHistory') }) {
$CONFIG{history} = 1;
}
else {
$CONFIG{history} = 0;
}
$update_config = 1;
}
foreach my $key (keys %CONFIG) {
if (not exists $CONFIG->{$key}) {
$update_config = 1;
last;
}
}
dump_configuration($config_file) if $update_config;
# Create the cache directory (if needed)
foreach my $path ($CONFIG{cache_dir}) {
next if -d $path;
require File::Path;
File::Path::make_path($path)
or warn "[!] Can't create path <<$path>>: $!";
}
@opt{keys %CONFIG} = values(%CONFIG);
}
load_config($config_file);
if ($opt{remember_watched}) {
if (-f $opt{watched_file}) {
if (open my $fh, '<', $opt{watched_file}) {
chomp(my @ids = <$fh>);
@watched_videos{@ids} = ();
close $fh;
}
else {
warn "[!] Can't open the watched file `$opt{watched_file}' for reading: $!";
}
}
}
if ($opt{history}) {
# Create the history file.
if (not -e $opt{history_file}) {
require File::Basename;
my $dir = File::Basename::dirname($opt{history_file});
if (not -d $dir) {
require File::Path;
File::Path::make_path($dir)
or warn "[!] Can't create path <<$dir>>: $!";
}
open my $fh, '>', $opt{history_file}
or warn "[!] Can't create the history file `$opt{history_file}': $!";
}
# Add history to Term::ReadLine
eval { $term->ReadHistory($opt{history_file}) };
# All history entries
my @history = $term->history_list;
# Rewrite the history file, when the history_limit has been reached.
if ($opt{history_limit} > 0 and @history > $opt{history_limit}) {
# Try to create a backup, first
require File::Copy;
File::Copy::cp($opt{history_file}, "$opt{history_file}.bak");
if (open my $fh, '>', $opt{history_file}) {
# Keep only the most recent half part of the history file
say {$fh} join("\n", @history[($opt{history_limit} >> 1) .. $#history]);
close $fh;
}
}
}
my $yv_obj = WWW::YoutubeViewer->new(
escape_utf8 => 1,
config_dir => $config_dir,
cache_dir => $opt{cache_dir},
env_proxy => $opt{env_proxy},
cookie_file => $opt{cookie_file},
http_proxy => $opt{http_proxy},
user_agent => $opt{user_agent},
timeout => $opt{timeout},
authentication_file => $authentication_file,
);
if (-f $default_api_file) {
$yv_obj->load_credentials($default_api_file);
}
if (-f $api_file) {
$yv_obj->load_credentials($api_file);
}
else {
open(my $fh, '>', $api_file) or warn "[!] Can't create file <<$api_file>>: $!\n";
print $fh <<"EOT";
{
"key": "API_KEY",
"client_id": "CLIENT_ID",
"client_secret": "CLIENT_SECRET"
}
EOT
close $fh;
}
if (not defined $yv_obj->get_key) {
warn join("\n",
"\nError: no API key has been set!\n\nFor creating/setting an YouTube API key, please see:",
"https://github.com/trizen/youtube-viewer#logging-in\n\n");
}
$yv_obj->load_authentication_tokens();
require WWW::YoutubeViewer::Utils;
my $yv_utils = WWW::YoutubeViewer::Utils->new(youtube_url_format => $opt{youtube_video_url},
thousand_separator => $opt{thousand_separator},);
{ # Apply the configuration file
my %temp = %CONFIG;
apply_configuration(\%temp);
}
#---------------------- YOUTUBE-VIEWER USAGE ----------------------#
sub help {
my $eqs = q{=} x 30;
local $" = ', ';
print <<"HELP";
\n $eqs \U$appname\E $eqs
usage: $execname [options] ([url] | [keywords])
== Base ==
[URL] : play an YouTube video by URL
[keywords] : search for YouTube videos
[playlist URL] : display a playlist of YouTube videos
== YouTube Options ==
* Categories
-c --categories : display the available YouTube categories
-hl --catlang=s : language for categories (default: en_US)
* Region
--region=s : set the region code (default: US)
* Videos
-uv --uploads=s : list videos uploaded by a specific channel or user
-pv --popular=s : list the most popular videos from a specific channel
-uf --favorites=s : list the favorite videos of a specific user
-id --videoids=s,s : play YouTube videos by their IDs
-rv --related=s : show related videos for a video ID or URL
-sv --search-videos : search for YouTube videos (default mode)
* Playlists
-up --playlists=s : list playlists created by a specific channel or user
-sp --search-pl : search for playlists of videos
--pid=s : list a playlist of videos by playlist ID
--pp=s,s : play the videos from the given playlist IDs
--ps=s : add video by ID or URL to a post-selected playlist
or in a given playlist ID specified with `--pid`
--position=i : position in the playlist where to add the video
* Activities
-ua --activities:s : show activity events for a given channel
* Trending
--trending:s : show trending videos in a given category ID or name
use "--region=XX" to change the region
* Channels
-sc --channels : search for YouTube channels
* Comments
--comments=s : display comments for a video by ID or URL
--comments-order=s : change the order of YouTube comments
valid values: relevance, time
* Filtering
--author=s : search in videos uploaded by a specific user
--duration=s : filter search results based on video length
valid values are: short medium long
--caption=s : only videos with/without closed captions
valid values are: any closedCaption none
--category=s : search only for videos in a specific category name/ID
--safe-search=s : YouTube will skip restricted videos for your location
valid values are: none moderate strict
--order=s : order the results using a specific sorting method
valid values: date rating viewCount title videoCount
--within=s : show only videos uploaded within the specified time
valid values are: Nd, Nw, Nm, Ny, where N is a number
--hd! : search only for videos available in at least 720p
--vd=s : set the video definition (any, high or standard)
--page=i : get results starting with a specific page number
--results=i : how many results to display per page (max: 50)
--hfr! : prefer high frame rate (HFR) videos
-2 -3 -4 -7 -1 : resolutions: 240p, 360p, 480p, 720p and 1080p
--resolution=s : supported resolutions: best, 2160p, 1440p,
1080p, 720p, 480p, 360p, 240p, 144p, audio.
* Account
--login : will prompt for authentication (OAuth 2.0)
--logout : will delete the authentication key
* [GET] Personal
-U --uploads:s : show the uploads from your channel *
-P --playlists:s : show the playlists from your channel *
-F --favorites:s : show the latest favorite videos *
-S --subscriptions:s : show the subscribed channels *
-SV --subs-videos:s : show the subscription videos (slow) *
--subs-order=s : change the subscription order
valid values: alphabetical, relevance, unread
-L --likes : show the videos that you liked on YouTube *
--dislikes : show the videos that you disliked on YouTube *
* [POST] Personal
--subscribe=s : subscribe to a given channel ID or username *
--favorite=s : favorite a video by URL or ID *
--like=s : send a 'like' rating to a video URL or ID *
--dislike=s : send a 'dislike' rating to a video URL or ID *
== Player Options ==
* Arguments
-f --fullscreen! : play videos in fullscreen mode
-n --audio! : play audio only, without displaying video
--append-arg=s : append some command-line parameters to the media player
--player=s : select a player to stream videos
available players: @{[keys %{$CONFIG->{video_players}}]}
== Download Options ==
* Download
-d --download! : activate the download mode
-dp --dl-play! : play the video after download (with -d)
-rp --rem-played! : delete a local video after played (with -dp)
--wget-dl! : download videos with wget (recommended)
--skip-if-exists! : don't download videos which already exist (with -d)
--copy-caption! : copy and rename the caption for downloaded videos
--downloads-dir=s : downloads directory (set: '$opt{downloads_dir}')
--filename=s : set a custom format for the video filename (see: -T)
--fat32safe! : makes filenames FAT32 safe (includes Unicode)
--mkv-merge! : merge audio and video into an MKV container
--merge-captions! : include closed-captions in the MKV container
* Convert
--convert-cmd=s : command for converting videos after download
which include the *IN* and *OUT* tokens
--convert-to=s : convert video to a specific format (with -d)
--keep-original! : keep the original video after converting
== Other Options ==
* Behavior
-A --all! : play the video results in order
-B --backwards! : play the video results in reverse order
-s --shuffle! : shuffle the results of videos
-I --interactive! : interactive mode, prompting for user input
--autoplay! : autoplay mode, automatically playing related videos
--std-input=s : use this value as the first standard input
--max-seconds=i : ignore videos longer than i seconds
--min-seconds=i : ignore videos shorter than i seconds
--get-term-width! : allow $execname to read your terminal width
--skip-watched! : don't play already watched videos
--highlight! : remember and highlight selected videos
--confirm! : show a confirmation message after each play
--prefer-mp4! : prefer videos in MP4 format, instead of WEBM
--prefer-av1! : prefer videos in AV1 format, instead of WEBM
--ignore-av1! : ignore videos in AV1 format
* Closed-captions
--get-captions! : download closed-captions for videos
--auto-captions! : include or exclude auto-generated captions
* Config
--config=s : configuration file
--update-config! : update the configuration file
* Output
-C --colorful! : use colors to delimit the video results
-D --details! : display the results with extra details
-W --fixed-width! : adjust the results to fit inside the term width
--custom-layout! : display the results using a custom layout (see conf)
-i --info=s : show information for a video ID or URL
-e --extract=s : extract information from videos (see: -T)
--extract-file=s : extract information from videos in this file
--dump=format : dump metadata information in `videoID.format` files
valid formats: json, perl
-q --quiet : do not display any warning
--really-quiet : do not display any warning or output
--video-info! : show video information before playing
--escape-info! : quotemeta() the fields of the `--extract`
--use-colors! : enable or disable the ANSI colors for text
* Other
--cookies=s : file to read cookies from and dump cookie
--user-agent=s : specify a custom user agent
--proxy=s : set HTTP(S)/SOCKS proxy: 'proto://domain.tld:port/'
If authentication required,
use 'proto://user:pass\@domain.tld:port/'
--dash! : include or exclude the DASH itags
--dash-mp4a! : include or exclude the itags for MP4 audio streams
--dash-segmented! : include or exclude segmented DASH streams
Help options:
-T --tricks : show more 'hidden' features of $execname
-E --examples : show several usage examples of $execname
-H --stdin-help : show the valid stdin options for $execname
-v --version : print version and exit
-h --help : print help and exit
--debug:1..3 : see behind the scenes
NOTES:
* -> requires authentication
! -> the argument can be negated with '--no-'
=i -> requires an integer argument
=s -> requires an argument
:s -> can take an optional argument
=s,s -> can take more arguments separated by commas
HELP
main_quit(0);
}
sub wrap_text {
my (%args) = @_;
require Text::Wrap;
local $Text::Wrap::columns = ($args{columns} || $term_width) - 8;
my $text = "@{$args{text}}";
$text =~ tr{\r}{}d;
return eval { Text::Wrap::wrap($args{i_tab}, $args{s_tab}, $text) } // $text;
}
sub tricks {
print <<"TRICKS";
== youtube-viewer -- tips and tricks ==
-> Playing videos
> To stream the videos in other players, you need to change the
configuration file. Where it says "video_player_selected", change it
to any player which is defined inside the "video_players" hash.
-> Arguments
> Almost all boolean arguments can be negated with a "--no-" prefix.
> Arguments that require an ID/URL, you can specify more than one,
separated by whitespace (quoted), or separated by commas.
-> My channel
> By using the string "mine" where a channel ID is required, "mine" will be
automatically replaced with your channel ID. (requires authentication)
Examples:
$execname --uploads=mine
$execname --likes=mine
$execname --favorites=mine
$execname --playlists=mine
-> More STDIN help:
> ":r", ":return" will return to the previous page of results.
For example, if you search for playlists, then select a playlist
of videos, inserting ":r" will return back to the playlist results.
Also, for the previous page, you can insert ':b', but ':r' is faster!
> "6" (quoted) will search for videos with the keyword '6'.
> If a stdin option is followed by one or more digits, the equal sign,
which separates the option from value, can be omitted.
Example:
:i2,4 is equivalent with :i=2,4
:d1-5 is equivalent with :d=1,2,3,4,5
:c10 is equivalent with :c=10
> When more videos are selected to play, you can stop them by
pressing CTRL+C. $execname will return to the previous section.
> Space inside the values of STDIN options, can be either quoted
or backslashed.
Example:
:re=video\\ title == :re="video title"
> ":anp" stands for "Auto Next Page". How do we use it?
Well, let's search for some videos. Now, if we want to play
only the videos matched by a regex, we'd say :re="REGEX".
But, what if we want to play the videos from the next pages too?
In this case, ":anp" is your friend. Use it wisely!
-> Special tokens:
*ID* : the YouTube video ID
*AUTHOR* : the author name of the video
*CHANNELID* : the channel ID of the video
*RESOLUTION* : the resolution of the video
*VIEWS* : the number of views
*VIEWS_SHORT* : the number of views in abbreviated notation
*LIKES* : the number of likes
*DISLIKES* : the number of dislikes
*RATING* : the rating of the video from 0 to 5
*COMMENTS* : the number of comments
*DURATION* : the duration of the video in seconds
*PUBLISHED* : the publication date as "DD MMM YYYY"
*AGE* : the age of a video (N days, N months, N years)
*AGE_SHORT* : the abbreviated age of a video (Nd, Nm, Ny)
*DIMENSION* : the dimension of the video (2D or 3D)
*DEFINITION* : the definition of the video (HD or SD)
*TIME* : the duration of the video as "HH::MM::SS"
*TITLE* : the title of the video
*FTITLE* : the title of the video (filename safe)
*DESCRIPTION* : the description of the video
*URL* : the YouTube URL of the video
*ITAG* : the itag value of the video
*FORMAT* : the extension of the video (without the dot)
*CAPTION* : true if the video has captions
*SUB* : the local subtitle file (if any)
*AUDIO* : the audio URL of the video (only in DASH mode)
*VIDEO* : the video URL of the video (it might not contain audio)
*AOV* : audio URL (if any) or video URL (in this order)
-> Special escapes:
\\t tab
\\n newline
\\r return
\\f form feed
\\b backspace
\\a alarm (bell)
\\e escape
-> Extracting information from videos:
> Extracting information can be achieved by using the "--extract" command-line
option which takes a given format as its argument, which is defined by using
special tokens, special escapes or literals.
Example:
$execname --no-interactive --extract '*TITLE* (*ID*)' [URL]
-> Configuration file: $config_file
-> Donations gladly accepted:
https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=75FUVBE6Q73T8
TRICKS
main_quit(0);
}