-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
youtube-viewer
executable file
·3887 lines (3282 loc) · 132 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-2015 Trizen <echo dHJpemVueEBnbWFpbC5jb20K | base64 -d>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#-------------------------------------------------------
# Appname: youtube-viewer
# Created on: 02 June 2010
# Latest edit on: 01 October 2015
# Website: https://github.com/trizen/youtube-viewer
#-------------------------------------------------------
#
# youtube-viewer is a command line utility for viewing youtube-videos in MPlayer.
#
# [CHANGELOG]
# - Added support for downloading multiple videos in parallel (--dl-parallel) - NEW (v3.1.4)
# - Migration to APIv3; some features has been lost in the process, but nothing too critical. - NEW (v3.1.4)
# - Added built-in support for [auto-generated] closed-captions (gcap is no longer required) - NEW (v3.1.3)
# - Added support for specifying the filename format when downloading videos (--filename=s) - NEW (v3.1.3)
# - Added support for special tokens and for extracting information about videos (--extract=s) - NEW (v3.1.3)
# - Added support for playing DASH videos and the `--no-dash` option to deactivate it at will - NEW (v3.1.2)
# - Added the options `--ps` and `--pid` to add videos by URL or ID to a given playlistID - NEW (v3.1.2)
# - Added the stdin commands ":ps" and ":s2p" to add one or more videos to a selected playlist - NEW (v3.1.2)
# - Added the `--std-input=s` option which can be used to specify the first standard input - NEW (v3.1.1)
# - Added input history support across sessions, with the 'history' config-key - NEW (v3.1.1)
# - Added support for more video players (--player=s) // Added support for shows (--us=author) - NEW (v3.1.0)
# - Added support to --copy-caption for downloaded videos // Added fixed-width for playlists - NEW (v3.1.0)
# - Added the ':play' stdin option // Added the support for 'watch_later' videos (-L) - NEW (v3.1.0)
# - Added a new option to combine multiple videos into one play instance (--combine-multiple) - NEW (v3.1.0)
# - New authentication support (OAuth 2.0) // Added support for download & play (-dp) - (v3.0.7)
# - Added support for YouTube EDU categories (-edu) // Options: :dv, :lec, :courses, :course - (v3.0.4)
# - Some minor bug-fixes // New options has been added: --pp, :pp, :anp, :kregex - (v3.0.3)
# - Added support for more resolutions, UTF-8 support, --convert-to=FMT and many bug-fixes - (v3.0.1)
# - Youtube Viewer 3.0 has been released! New options, better functionality and new bugs :) - (v3.0.0)
# - Added support for detailed results (usage: -D or --details) // Support for comments - (v2.5.8)
# - Switched to Term::ReadLine for a better STDIN support // Better colors // Info support - (v2.5.7)
# - Added support for: -duration, -caption=s, -safe-search=s, -hd // Improved code quality - (v2.5.6)
# - Added support for configuration file, improved stability, improved debug mode - (v2.5.5)
# - Switched to XML::Fast for parsing gdata XML, in consequence, youtube-viewer is faster! - (v2.5.5)
# - Switched to Getopt::Long, added SIGINT handler and a better way to execute mplayer - (v2.5.5)
# - Added support to list playlists created by a specific user (usage: -up <USERNAME>) - (v2.5.4)
# - Improved parsing support for arguments, including arguments specified via STDIN. - (v2.5.4)
# - Added support to search for videos uploaded by a particular YouTube user (-author=USER) - (v2.5.4)
# - Added support to get video results starting with a predefined page (e.g.: -page=4) - (v2.5.4)
# - Added support for previous page and support to list youtube usernames from a file - (v2.5.2)
# - Added colors for text (--use_colors), 360p support (-3), playlist support - (v2.5.0)
# - Added support for today and all time Youtube tops (usage: -t, --tops, -a, --all-time) - (v2.4.*)
# - Re-added the support for the next page / Added support for download (-d, --download) - (v2.4.*)
# - Added support for Youtube CCaptions. (Depends on: 'gcap' - http://gcap.googlecode.com) - (v2.4.*)
# - First version with Windows support. Require SMPlayer to play videos. See MPlayer Line - (v2.4.*)
# - Code has been changed in a proportion of ~60% and optimized for speed // --480 became -4 - (v2.4.*)
# - Added mega-powers of omnibox to the STDIN :) - (v2.3.*)
# - Re-added the option to list and play youtube videos from a user profile. Usage: -u [user] - (v2.3.*)
# - Added a new option to play only the audio track of a videoclip. Usage: [words] -n - (v2.3.*)
# - Added option for fullscreen (-f, --fullscreen). Usage: youtube-viewer [words] -f - (v2.3.*)
# - Added one new option '-c'. It shows available categories and will let you to choose one. - (v2.3.*)
# - Added one new option '-m'. It shows 3 pages of youtube video results. Usage: [words] -m - (v2.3.*)
# - For "-A" option has been added 3 pages of youtube video results (50 clips) - (v2.3.*)
# - Added "-prefer-ipv4" to the mplayer line (videoclips starts in no time now). - (v2.3.*)
# - Search and play videos at 480p, 720p. Ex: [words] --480, [words] -A --480 - (v2.3.*)
# - Added support to play a video at 480p even if it's resolution is higher. Ex: [url] --480 - (v2.2.*)
# - Added a nice feature which prints some informations about the current playing video - (v2.2.*)
# - Added support to play videos by your order. Example: after search results, insert: 3 5 2 1 - (v2.1.*)
# - Added support for next pages of video results (press <ENTER> after search results) - (v2.1.*)
# - Added support to continue playing searched videos, usage: "youtube-viewer [words] -A" - (v2.1.*)
# - Added support to print counted videos and support to insert a number instead of video code - (v2.1.*)
# - Added support to search YouTube Videos in script (e.g.: youtube-viewer avatar trailer) - (v2.0.*)
# - Added support to choose the quality only between 720p and 1080p (if it is available) - (v2.0.*)
# - Added support for YouTube video codes (e.g.: youtube-viewer WVTWCPoUt8w) - (v1.0.*)
# - Added support for 720p and 1080p YouTube Videos... - (v1.0.*)
# 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-2015 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.
See http://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
no if $] >= 5.018, warnings => 'experimental::smartmatch';
use File::Spec::Functions qw(
catdir
catfile
curdir
path
rel2abs
tmpdir
);
binmode(STDOUT, ':utf8');
my $appname = 'Youtube Viewer';
my $version = '3.1.9';
my $execname = 'youtube-viewer';
# A better <STDIN> support:
require Term::ReadLine;
my $term = Term::ReadLine->new("$appname $version");
# Developer key
my $key = 'aXalQYmzI8gPkMSLyMhpApfMAiU2b23Qz2nE3mq';
sub VIDEO_PART () { 'contentDetails,statistics' }
sub EXTRA_VIDEO_PART () { join(',', 'snippet', VIDEO_PART()) }
# Options (key=>value) goes here
my %opt;
my $term_width = 80;
# Unchangeable data goes here
my %constant = (win32 => $^O eq 'MSWin32'); # doh
my $xdg_config_home = $ENV{XDG_CONFIG_HOME}
|| catdir(
(
my $home_dir =
$ENV{HOME}
|| $ENV{LOGDIR}
|| ($constant{win32} ? '\Local Settings\Application Data' : ((getpwuid($<))[7] || `echo -n ~`))
),
'.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, 'history.txt');
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) = @_;
state $paths = [path()];
foreach my $path (@{$paths}) {
if (-e (my $cmd_path = catfile($path, $cmd))) {
return $cmd_path;
}
}
return;
}
# Regular expressions
use WWW::YoutubeViewer::RegularExpressions;
# 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*},
novideo => q{--no-video},
},
},
video_player_selected => (
$constant{win32}
? 'mplayer'
: undef # autodetect it later
),
combine_multiple_videos => 0,
# YouTube options
dash_support => 1,
dash_mp4_audio => 0,
maxResults => 20,
resolution => 'original',
videoDefinition => undef,
videoDimension => undef,
videoLicense => undef,
safeSearch => undef,
videoCaption => undef,
videoDuration => undef,
videoSyndicated => undef,
publishedBefore => undef,
publishedAfter => undef,
order => undef,
subscriptions_order => 'relevance',
hl => 'en_US',
cats_region => 'us',
# URI options
youtube_video_url => 'http://www.youtube.com/watch?v=%s',
# Subtitle options
srt_languages => ['en', 'es'],
captions_dir => tmpdir(),
get_captions => 1,
copy_caption => 0,
cache_dir => undef, # will be defined later
# Others
http_proxy => undef,
debug => 0,
page => 1,
colors => $constant{win32} ^ 1,
clobber => 0,
skip_if_exists => 0,
fullscreen => 0,
results_with_details => 0,
results_with_colors => 0,
results_fixed_width => 0,
interactive => 1,
get_term_width => $constant{win32} ^ 1,
download_with_wget => 0,
download_in_parallel => 0,
thousand_separator => q{,},
downloads_dir => curdir(),
keep_original_video => 0,
download_and_play => 0,
autohide_watched => 0,
remove_played_file => 0,
history => 0,
history_limit => 10_000,
history_file => $history_file,
convert_cmd => q{ffmpeg -i *IN* *OUT*},
convert_to => undef,
video_filename_format => q{*FTITLE*.*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
:lectures=ID : display lectures from a categoryID
:course=ID : display lectures from a courseID
:courses=ID : display courses of lectures from a categoryID
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 section
:refresh : refresh the current list of results
:dv=i : dump 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 just like a single value/keyword.
NOTES
my $general_help = <<"HELP";
$action_options
$control_options
$other_options
$notes_options
Examples:
3 : select the 3rd result
-V funny cats : search for videos
-p classical music : search for playlists of videos
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
:a(uthor)=i : display latest author's uploads
: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
# 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 your order
: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,4 -> show informations for the first and 4th video.
:d18-20,1,2 -> download the videos: 18, 19, 20, 1 and 2.
-u=google -D -> list videos from google with extra details.
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 {
state $x = 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";
print $config_fh $config_documentation, $dumped_config;
close $config_fh;
}
}
if (not -e $config_file or -z _ or $opt{reconfigure}) {
dump_configuration();
}
our $CONFIG;
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!";
}
# Add audio support to players (backwards compatibility)
while (my ($player, $data) = each %{$CONFIG->{video_players}}) {
if ( exists $CONFIG{video_players}{$player}
and not exists $data->{audio}
and exists $CONFIG{video_players}{$player}{audio}) {
$data->{audio} = $CONFIG{video_players}{$player}{audio};
}
}
# 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 =
(defined($ENV{XDG_CACHE_HOME}) and -w $ENV{XDG_CACHE_HOME})
? $ENV{XDG_CACHE_HOME}
: catdir($home_dir, '.cache');
if (not -w $cache_dir) {
$cache_dir = '.cache';
}
$CONFIG{cache_dir} = catdir($cache_dir, 'youtube-viewer');
$update_config = 1;
}
# Locating a video player
if (not defined $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 ($update_config or not \%CONFIG ~~ $CONFIG) {
dump_configuration();
}
}
# Create the cache directory (if needed)
if (not -d $CONFIG{cache_dir}) {
require File::Path;
File::Path::make_path($CONFIG{cache_dir})
or warn "[!] Can't create dir `$CONFIG{cache_dir}': $!";
}
@opt{keys %CONFIG} = values(%CONFIG);
if ($opt{history}) {
if (open($opt{history_fh}, '>>:utf8', $opt{history_file})) {
select((select($opt{history_fh}), $| = 1)[0]); # autoflush
}
else {
warn "[!] Can't open history file `$opt{history_file}' for appending: $!";
}
# Add history to Term::ReadLine
$term->ReadHistory($opt{history_file});
# Read back the history list from memory
# and create a dictionary to avoid duplicates
require Encode;
my @history = map { Encode::decode_utf8($_) } $term->history_list;
@{$opt{history_hash}}{map { lc } @history} = ();
# Rewrite the history file when the history size limit has been reached in order to keep
# only the last n entries, minus some random number to avoid an imediate second rewrite.
# - the 'rand' part implies that you're lucky :) -
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");
# Now, try to rewrite the history file
if (open(my $fh, '>:utf8', $opt{history_file})) {
say {$fh} join("\n", @history[(@history - $opt{history_limit}) + int(rand($opt{history_limit})) .. $#history]);
close $fh;
}
}
}
{
my $i = length $key;
$key =~ s/(.{$i})(.)/$2$1/g while --$i;
}
require WWW::YoutubeViewer;
my $yv_obj = WWW::YoutubeViewer->new(
escape_utf8 => 1,
key => $key,
config_dir => $config_dir,
cache_dir => $opt{cache_dir},
authentication_file => $authentication_file,
);
{
$yv_obj->set_client_id('923751928481.apps.googleusercontent.com');
$yv_obj->set_client_secret("\26/Ae]3\b\6\x186a:*#0\32\t\f\n\27\17GC`" ^ substr($key, -24));
$yv_obj->set_redirect_uri('urn:ietf:wg:oauth:2.0:oob');
}
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
\t\t\t\t\t\t by Trizen (trizenx\@gmail.com)
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 ==
* Video tops:
-t --tops : display the YouTube video tops
--tops=all : display all time YouTube video tops
-r --region=s : list top videos for a specific region
-M --movies : display the YouTube category of movies
* Categories
-c --categories : display the available YouTube categories
--edu-categories : display the YouTube EDU categories
--course-id=s : list the video lectures from a course_ID
-hl --catlang=s : language for categories (default: en_US)
--cats-region=s : region code for categories (default: us)
* Videos
-u --user=s : list videos uploaded by a specific user
-cv --channel-vid=s : list videos uploaded to a specific channel
-uf --user-fav=s : list the videos favorited by 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
--search=s : search for YouTube videos (default mode)
* Playlists
-p --playlists : search for playlists of videos
--pid=s : list a playlist of videos by playlistID
--pp=s,s : play the videos from the given playlist IDs
--ps=s : add videos by ID or URL to a post-selected playlist
or in a given playlistID specified with `--pid`
--position=i : the position in a playlist where to add a video
-up --user-pl=s : list the playlists created by a specific user
* Channels
--channels : search for Youtube channels
--channel-suggest : show the suggested YouTube channels for you *
* Shows
-us --user-shows=s : display the shows belonging to a user
--seasons=s : get and print the seasons of a YouTube show_ID
--episodes=s : get and print the episodes for a show season_ID
--clips=s : get and print the clips for a show season_ID
* Comments
--comments=s : display comments for a YouTube video by ID or URL
* Filtering
--author=s : search in videos uploaded by a specific user
--channel-id=s : search in videos belonging to a specific channel ID
--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: true, false
--category=i : search only for videos in a specific category 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, 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
--results=i : how many results to display per page (max: 50)
-2 -3 -4 -7 -1 : resolutions: 240p, 360p, 480p, 720p and 1080p
--resolution=s : supported resolutions: original, 2160p, 1440p,
1080p, 720p, 480p, 360p, 240p, 144p, audio.
* Account
--login : will prompt you for login
--logout : will delete the authentication key
* [GET] Personal
-F --favorites:s : show the latest favorited videos *
-R --recommended : show the recommended videos for you *
-S --subscriptions:s : show the subscribed channels *
-SV --subs-videos:s : show the subscription videos *
--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 channel *
--user-subscribe=s : subscribe to a channel via username *
--favorite=s : favorite a YouTube 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! : set the fullscreen mode for the selected video player
-n --novideo! : play the music only without a video in the foreground
--vo=s : specify the video output for MPlayer
--af=s : specify an audio filter for MPlayer
--append-arg=s : append some command-line parameters to the media player
--video-player=s : select a video player to stream videos
available players: @{[keys %{$CONFIG->{video_players}}]}
== Download Options ==
* Download
-d --download! : activate the download mode
-dp --downl-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 (default: LWP)
--dl-parallel : download multiple videos at once
--clobber! : overwrite an existent video (with -d)
--skip-if-exists! : don't download videos which already exists (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)
* 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 all the video results in order
-B --backwards! : play all video results in reverse order
-s --shuffle! : shuffle the results of videos and playlists
-I --interactive! : prompt for the first user input
--std-input=s : use this value as the first standard input
--max-seconds=i : don't play videos longer than i seconds
--min-seconds=i : don't play videos shorter than i seconds
--combine-multi! : combine multiple videos into one play instance
--get-term-width! : allow $execname to read your terminal width
--autohide! : automatically hide watched videos
* Closed-captions
--get-captions! : download the closed captions for videos
--captions-dir=s : the directory where to download the .srt files
* Config
-U --update-config! : update the configuration file before exit
* Output
-C --colorful! : use colors to delimit the video results
-D --details! : a new look for the results, with more details
-W --fixed-width! : adjust the results to fit inside the term width
-i --info=s : show some info for a videoID or URL
-e --extract=s : extract information from videos (see: -T)
-q --quiet : do not display any warning
--really-quiet : do not display any warning or output
--escape-info! : quotemeta() the fields of the `--extract`
--use-colors! : enable or disable the ANSI colors for text
* Other
--http_proxy=s : HTTP proxy to use, format 'http://domain.tld:port/'.
If authentication required,
use 'http://user:pass\@domain.tld:port/'
--dash! : include or exclude the DASH itags
--dash-m4a! : include or exclude the itags for MP4 audio URLs
Help options:
-T --tricks : show more 'hidden' features of $execname
-E --examples : show some useful usage examples for $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,2 : 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) = @_;
state $x = require Text::Wrap;
${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.
-> More STDIN help:
> ":r", ":return" will return to the previous section.
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) or -V=6 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 omited.
For 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.
For example:
:re=video\\ title == :re="video title"
> ":anp" stands for the "Auto Next Page". How do we use it?
Well, let's search for some videos. Now, if we'd want to play
only the videos matched by a regex, we'd say :re="REGEX".
But, what if we'd 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
*LIKES* : the number of likes
*DISLIKES* : the number of dislikes
*COMMENTS* : the number of comments
*DURATION* : the duration of the video in seconds
*DIMENSION* : the dimension of the video (2D or 3D)
*DEFINITION* : the defintion of the video (HD or SD)
*TIME* : the duration of the video in 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 caption.
*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 achevied 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);
}
sub examples {
print <<"EXAMPLES";
==== COMMAND LINE EXAMPLES ====
Command: $execname -A -n -4 russian music -category=10
Results: play all the video results (-A)
only audio, no video (-n)
quality 480p (-4)
search for "russian music"
in the "10" category, which is the Music category.
-A will include the videos from the next pages as well.
Command: $execname -comments=http://www.youtube.com/watch?v=U6_8oIPFREY
Results: show video comments for a specific video URL or videoID
Command: $execname -results=5 -up=khanacademy -D
Results: set 5 results,
get playlists created by a specific user
and print them with details (-D)
Command: $execname -author=UCBerkeley atom
Results: search only in videos uploaded by a specific author
Command: $execname -S=vsauce
Results: get the video subscriptions for a username
Command: $execname --page=2 -u=Google
Results: show latest videos uploaded by Google,
starting with the page number 2.
Command: $execname --category=10 --tops
Results: show today tops for Music category.
Command: $execname --tops=all --region=JP
Results: show all time tops for the Japan country.
Command: $execname --tops --region=RU --category=Music
Results: show today tops of RUssian Music
Command: $execname cats -order=viewCount -duration=short
Results: search for 'cats' videos, ordered by ViewCount and short length.
Command: $execname --channels russian music
Results: search for channels.
Command: $execname --uf=Google
Results: show latest videos favorited by a user.
==== USER INPUT EXAMPLES ====
A STDIN option can begin with ':', ';' or '='.
Command: <ENTER>, :n, :next, CTRL+D
Results: get the next page of results.
Command: :b, :back (:r, :return)
Results: get the previous page of results.
Command: :i4..6, :i7-9, :i20-4, :i2, :i=4, :info=4
Results: show video informations for the selected videos.
Command: :d5,2, :d=3, :download=8
Results: download the selected videos.
Command: :c2, :comments=4
Results: show comments for a selected video.
Command: :r4, :related=6
Results: show related videos for a selected video.
Command: :a14, :author=12
Results: show videos uploaded by the author who uploaded the selected video.
Command: :p9, :playlists=14
Results: show playlists created by the author who uploaded the selected video.
Command: :subscribe=7
Results: subscribe to the author's channel who uploaded the selected video.
Command: :like=2, :dislike=4,5
Results: like or dislike the selected videos.
Command: :course=EC7AEDF86AABA1AA9A
Results: list videos lectures from course ID.
Command: :courses=285
Results: list courses of lectures from EDU category ID.
Command: :lectures=361
Results: list video lectures from EDU category ID.
Command: :fav=4, :favorite=3..5
Results: favorite the selected videos.
Command: 3, 5..7, 12-1, 9..4, 2 3 9
Results: play the selected videos.
Command: :q3,5, :q=4, :queue=3-9
Results: enqueue the selected videos to play them later.
Command: :pq, :play-queue
Results: play the videos enqueued by the :queue option.
Command: :re="^Google Tricks"
Results: play videos matched by a regex.
Example: valid title: "Google Tricks & Easter eggs"
Command: :regex="Google.*part \\d+/\\d+"
Example: valid title: "The GOOGLE company (part 1/4)"
Command: :kregex=author,^google\$
Results: play only the videos uploaded by google.
Command: :kre=category,"^(?:People & Blogs|Entertainment)\$"
Results: play only the videos from the specified categories.
Command: :kre=views,"^(\\d+)\\z(?(?{ \$1 > 1000 })(?=)|(?!))"
Results: play only the videos which have more than 1000 of views.
Command: :anp 1 2 3
Results: play the first three videos from every page.
Command: :r, :return
Results: return to the previous section.
EXAMPLES
main_quit(0);
}
sub stdin_help {
print $complete_help;
main_quit(0);
}
# Print version
sub version {
print "YouTube Viewer $version\n";
main_quit(0);