forked from get-iplayer/get_iplayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_iplayer.cgi
executable file
·4009 lines (3485 loc) · 123 KB
/
get_iplayer.cgi
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/env perl
#
# The world's most insecure web-based PVR manager and streaming proxy for get_iplayer
# ** WARNING ** Never run this in an untrusted environment or facing the internet
#
# Copyright (C) 2008-2010 Phil Lewis, 2010- get_iplayer contributors
#
# 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/>.
#
# Authors: Phil Lewis, get_iplayer contributors
# Web: https://github.com/get-iplayer/get_iplayer/wiki
# License: GPLv3 (see LICENSE.txt)
#
my $VERSION = 3.35;
my $VERSION_TEXT;
$VERSION_TEXT = sprintf("v%.2f", $VERSION) unless $VERSION_TEXT;
use CGI qw(-utf8 :all);
use CGI::Cookie;
use Cwd 'abs_path';
use Encode qw(:DEFAULT :fallback_all);
use Getopt::Long;
use File::Basename;
use File::Copy;
use HTML::Entities;
use IO::File;
use IO::Handle;
use IPC::Open3;
use LWP::ConnCache;
#use LWP::Debug qw(+);
use Unicode::Normalize;
use LWP::UserAgent;
use PerlIO::encoding;
use strict;
use constant FB_EMPTY => sub { '' };
use constant IS_WIN32 => $^O eq 'MSWin32' ? 1 : 0;
use constant DEFAULT_THUMBNAIL => "https://ichef.bbci.co.uk/images/ic/480xn/p01tqv8z.png";
$PerlIO::encoding::fallback = XMLCREF;
# suppress Perl 5.22/CGI 4 warning
$CGI::LIST_CONTEXT_WARN = 0;
$| = 1;
my $opt_cmdline;
$opt_cmdline->{debug} = 0;
# Allow bundling of single char options
Getopt::Long::Configure ("bundling");
# cmdline opts take precedence
GetOptions(
"help|h" => \$opt_cmdline->{help},
"listen|address|l=s" => \$opt_cmdline->{listen},
"port|p=n" => \$opt_cmdline->{port},
"getiplayer|get_iplayer|g=s" => \$opt_cmdline->{getiplayer},
"ffmpeg=s" => \$opt_cmdline->{ffmpeg},
"debug" => \$opt_cmdline->{debug},
"baseurl|base-url|b=s" => \$opt_cmdline->{baseurl},
"encodinglocale|encoding-locale=s" => \$opt_cmdline->{encodinglocale},
"encodinglocalefs|encoding-locale-fs=s" => \$opt_cmdline->{encodinglocalefs},
"encodingconsoleout|encoding-console-out=s" => \$opt_cmdline->{encodingconsoleout},
"encodingconsolein|encoding-console-in=s" => \$opt_cmdline->{encodingconsolein},
"encodingwebrequest|encoding-webrequest=s" => \$opt_cmdline->{encodingwebrequest},
) || die usage();
# Display usage if old method of invocation is used or --help
usage() if $opt_cmdline->{help} || @ARGV;
# Usage
sub usage {
my $text = "get_iplayer Web PVR Manager $VERSION_TEXT\n";
$text .= <<'EOF';
Copyright (C) 2008-2010 Phil Lewis, 2010- get_iplayer contributors
This program comes with ABSOLUTELY NO WARRANTY; This is free software,
and you are welcome to redistribute it under certain conditions;
See the GPLv3 for details.
Options:
--listen,-l Use the built-in web server and listen on this interface address (default: 0.0.0.0)
--port,-p Use the built-in web server and listen on this TCP port
--getiplayer,-g Path to the get_iplayer script
--ffmpeg Path to the ffmpeg binary (for streaming)
--debug Debug mode
--baseurl,-b Base URL for link generation. Set to full proxy URL if running behind reverse proxy.
--help,-h This help text
--encodinglocale Encoding for command line (default: Linux/Unix/OSX = UTF-8, Windows = cp1252)
--encodinglocalefs Encoding for file names (default: Linux/Unix/OSX = UTF-8, Windows = cp1252)
--encodingconsoleout Encoding for STDOUT/STDERR (default: Linux/Unix/OSX = UTF-8, Windows = cp850)
--encodingconsolein Encoding for STDIN (default: Linux/Unix/OSX = UTF-8, Windows = cp850)
--encodingwebrequest Encoding for requests to get_iplayer (default: Linux/Unix/OSX = UTF-8, Windows = UTF-8)
EOF
print $text;
exit 1;
}
# fallback encodings
$opt_cmdline->{encodinglocale} = $opt_cmdline->{encodinglocalefs} = default_encodinglocale();
$opt_cmdline->{encodingconsoleout} = $opt_cmdline->{encodingconsolein} = default_encodingconsoleout();
$opt_cmdline->{encodingwebrequest} = default_encodingwebrequest();
# attempt to automatically determine encodings
eval {
require Encode::Locale;
};
if (!$@) {
# set encodings unless already set by PERL_UNICODE or perl -C
$opt_cmdline->{encodinglocale} = $Encode::Locale::ENCODING_LOCALE unless (${^UNICODE} & 32);
$opt_cmdline->{encodinglocalefs} = $Encode::Locale::ENCODING_LOCALE_FS unless (${^UNICODE} & 32);
$opt_cmdline->{encodingconsoleout} = $Encode::Locale::ENCODING_CONSOLE_OUT unless (${^UNICODE} & 6);
$opt_cmdline->{encodingconsolein} = $Encode::Locale::ENCODING_CONSOLE_IN unless (${^UNICODE} & 1);
}
binmode(STDOUT, ":encoding($opt_cmdline->{encodingconsoleout})");
binmode(STDERR, ":encoding($opt_cmdline->{encodingconsoleout})");
binmode(STDIN, ":encoding($opt_cmdline->{encodingconsolein})");
my $fh;
# Send log messages to this fh
my $se = *STDERR;
binmode $se, ":encoding($opt_cmdline->{encodingconsoleout})";
for my $key ( keys %{$opt_cmdline} ) {
# decode @ARGV unless already decoded by PERL_UNICODE or perl -C
unless ( ${^UNICODE} & 32 ) {
$opt_cmdline->{$key} = decode_cl($opt_cmdline->{$key});
}
# compose UTF-8 args if necessary
if ( $opt_cmdline->{encodinglocale} =~ /UTF-?8/i ) {
$opt_cmdline->{$key} = NFKC($opt_cmdline->{$key});
}
}
# Some defaults
my $default_modes = 'default';
$opt_cmdline->{listen} = '0.0.0.0' if ! $opt_cmdline->{listen};
$opt_cmdline->{baseurl} .= "/" if $opt_cmdline->{baseurl} && $opt_cmdline->{baseurl} !~ m{/$};
$opt_cmdline->{ffmpeg} = encode_fs($opt_cmdline->{ffmpeg}) || 'ffmpeg';
$opt_cmdline->{getiplayer} = encode_fs($opt_cmdline->{getiplayer}) if $opt_cmdline->{getiplayer};
# Search for get_iplayer
if ( ! $opt_cmdline->{getiplayer} ) {
for ( './get_iplayer', './get_iplayer.cmd', './get_iplayer.pl', '/usr/bin/get_iplayer', '/usr/local/bin/get_iplayer' ) {
$opt_cmdline->{getiplayer} = $_ if -x $_;
}
}
if ( ( ! $opt_cmdline->{getiplayer} ) || ! -f $opt_cmdline->{getiplayer} ) {
print "ERROR: Cannot find get_iplayer, please specify its location using the --getiplayer option.\n";
exit 2;
}
my @gip_cmd_base = (
decode_fs($opt_cmdline->{getiplayer}),
'--encoding-webrequest='.$opt_cmdline->{encodingwebrequest},
'--encoding-console-out=UTF-8',
'--nocopyright',
'--expiry=999999999',
);
# Path to get_iplayer (+ set HOME env var cos apache seems to not set it)
my $home = $ENV{HOME};
my %prog;
my @pids;
my @displaycols;
# Field names to be grabbed from get_iplayer
my @headings = qw(
index
thumbnail
pid
available
expires
type
name
episode
versions
duration
desc
channel
categories
timeadded
guidance
web
seriesnum
episodenum
filename
mode
);
# Default Displayed headings
my @headings_default = qw( thumbnail type name episode desc channel timeadded );
# Lookup table for nice field name headings
my %fieldname = (
index => 'Index',
pid => 'PID',
available => 'Available',
expires => 'Expires',
type => 'Type',
name => 'Name',
episode => 'Episode',
versions => 'Versions',
duration => 'Duration',
desc => 'Description',
channel => 'Channel',
categories => 'Categories',
thumbnail => 'Image',
timeadded => 'Time Added',
guidance => 'Guidance',
web => 'Web Page',
pvrsearch => 'PVR Search',
comment => 'Comment',
filename => 'Filename',
mode => 'Mode',
seriesnum => 'Series Number',
episodenum => 'Episode Number',
'name,episode' => 'Name+Episode',
'name,episode,desc' => 'Name+Episode+Desc',
);
my %cols_order = ();
my %cols_names = ();
my %prog_types = (
tv => 'BBC TV',
radio => 'BBC Radio'
);
my %prog_types_order = (
1 => 'tv',
2 => 'radio'
);
my $icons_base_url = './icons/';
my $cgi;
my $nextpage;
# Page routing based on NEXTPAGE CGI parameter
my %nextpages = (
'search_progs' => \&search_progs, # Main Programme Listings
'search_history' => \&search_history, # Recorded Programme Listings
'pvr_queue' => \&pvr_queue, # Queue Recording of Selected Progs
'recordings_delete' => \&recordings_delete, # Delete Files for Selected Recordings
'pvr_list' => \&show_pvr_list, # Show all current PVR searches
'pvr_del' => \&pvr_del, # Delete selected PVR searches
'pvr_add' => \&pvr_add,
'pvr_edit' => \&pvr_edit,
'pvr_save' => \&pvr_save,
'pvr_run' => \&pvr_run,
'record_now' => \&record_now,
'show_info' => \&show_info,
'refresh' => \&refresh,
);
##### Options #####
my $opt;
# Options Layout on page tabs
my $layout;
$layout->{BASICTAB}->{title} = 'Search Options',
$layout->{BASICTAB}->{heading} = 'Search Options:',
$layout->{BASICTAB}->{order} = [ qw/ SEARCH SEARCHFIELDS PROGTYPES HISTORY URL / ];
$layout->{SEARCHTAB}->{title} = 'Advanced Search';
$layout->{SEARCHTAB}->{heading} = 'Advanced Search Options:';
$layout->{SEARCHTAB}->{order} = [ qw/ EXCLUDE CATEGORY EXCLUDECATEGORY CHANNEL EXCLUDECHANNEL SINCE BEFORE FUTURE / ],
$layout->{DISPLAYTAB}->{title} = 'Display';
$layout->{DISPLAYTAB}->{heading} = 'Display Options:';
$layout->{DISPLAYTAB}->{order} = [ qw/ SORT REVERSE PAGESIZE HIDE HIDEDELETED / ];
$layout->{COLUMNSTAB}->{title} = 'Columns';
$layout->{COLUMNSTAB}->{heading} = 'Column Options:';
$layout->{COLUMNSTAB}->{order} = [ qw/ COLS / ];
$layout->{RECORDINGTAB}->{title} = 'Recording';
$layout->{RECORDINGTAB}->{heading} = 'Recording Options:';
$layout->{RECORDINGTAB}->{order} = [ qw/ OUTPUT VERSIONLIST MODES PROXY SUBTITLES METADATA THUMB PVRHOLDOFF FORCE AUTOWEBREFRESH AUTOPVRRUN REFRESHFUTURE FPS25 / ];
$layout->{STREAMINGTAB}->{title} = 'Streaming';
$layout->{STREAMINGTAB}->{heading} = 'Streaming Options:';
$layout->{STREAMINGTAB}->{order} = [ qw/ BITRATE VSIZE VFR STREAMTYPE / ];
$layout->{HIDDENTAB}->{title} = '';
$layout->{HIDDENTAB}->{heading} = '';
$layout->{HIDDENTAB}->{order} = [ qw/ SAVE SEARCHTAB COLUMNSTAB DISPLAYTAB RECORDINGTAB STREAMINGTAB PAGENO INFO NEXTPAGE ACTION / ];
# Order of displayed tab buttoms (BASICTAB and HIDDEN are always displayed regardless of order)
$layout->{taborder} = [ qw/ BASICTAB SEARCHTAB DISPLAYTAB COLUMNSTAB RECORDINGTAB STREAMINGTAB HIDDENTAB / ];
# Any params that should never get into the get_iplayer pvr-add search
my @nosearch_params = qw/ /;
### Perl CGI Web Server ###
use Socket;
use IO::Socket;
use POSIX ":sys_wait_h";
my $IGNOREEXIT = 0;
# If the port number is specified then run embedded web server
if ( $opt_cmdline->{port} > 0 ) {
# Autoreap zombies
$SIG{CHLD} = 'IGNORE';
# Need this because with $SIG{CHLD} = 'IGNORE', backticks and systems calls always return -1
$IGNOREEXIT = 1;
for (;;) {
# Setup and create socket
my $server = new IO::Socket::INET(
Proto => 'tcp',
LocalAddr => $opt_cmdline->{listen},
LocalPort => $opt_cmdline->{port},
Listen => SOMAXCONN,
Reuse => 1,
);
$server or die "Unable to create server socket: $!";
print $se "INFO: Listening on $opt_cmdline->{listen}:$opt_cmdline->{port}\n";
print $se "WARNING: Insecure Remote access is allowed, use --listen=127.0.0.1 to limit to this host only\n" if $opt_cmdline->{listen} ne '127.0.0.1';
print $se "INFO: Using base URL $opt_cmdline->{baseurl}\n" if $opt_cmdline->{baseurl};
# Await requests and handle them as they arrive
while (my $client = $server->accept()) {
my $procid = fork();
die "Cannot fork" unless defined $procid;
# Parent
if ( $procid ) {
close $client;
# must call waitpid() on Windows
if ( IS_WIN32 ) {
while ( abs(waitpid(-1, WNOHANG)) > 1 ) {}
}
next;
}
# Child
binmode $se, ":encoding($opt_cmdline->{encodingconsoleout})";
$client->autoflush(1);
my %request = ();
my $query_string;
my %data;
{
# Read Request
local $/ = Socket::CRLF;
while (<$client>) {
# Main http request
chomp;
if (/\s*(\w+)\s*([^\s]+)\s*HTTP\/(\d.\d)/) {
$request{METHOD} = uc $1;
$request{URL} = $2;
$request{HTTP_VERSION} = $3;
# Standard headers
} elsif (/:/) {
my ( $type, $val ) = split /:/, $_, 2;
$type =~ s/^\s+//;
for ($type, $val) {
s/^\s+//;
s/\s+$//;
}
$request{lc $type} = $val;
print "REQUEST HEADER: $type: $val\n" if $opt_cmdline->{debug};
# POST data
} elsif (/^$/) {
read( $client, $request{CONTENT}, $request{'content-length'} ) if defined $request{'content-length'};
last;
}
}
}
# Determine method and parse parameters
if ($request{METHOD} eq 'GET') {
if ($request{URL} =~ /(.*)\?(.*)/) {
$request{URL} = $1;
$request{CONTENT} = $2;
$query_string = $request{CONTENT};
}
$data{"_method"} = "GET";
} elsif ($request{METHOD} eq 'POST') {
$query_string = parse_post_form_string( $request{CONTENT} );
$data{"_method"} = "POST";
} else {
$data{"_method"} = "ERROR";
}
# Log Request
print $se "$data{_method}: $request{URL}\n";
# Is this the CGI or some other file request?
if ( $request{URL} =~ /^\/?(recordings_delete|playlist.+|genplaylist.+|)\/?$/ ) {
# remove any vars that might affect the CGI
#%ENV = ();
@ARGV = ();
# Setup CGI http vars
print $se "QUERY_STRING = $query_string\n" if defined $query_string;
$ENV{'QUERY_STRING'} = $query_string;
$ENV{'REQUEST_URI'} = $request{URL};
$ENV{'COOKIE'} = $request{cookie};
$ENV{'SERVER_PORT'} = $opt_cmdline->{port};
my $request_host = "http://$request{host}/";
if ( $opt_cmdline->{baseurl} ) {
$ENV{'REQUEST_URI'} = $opt_cmdline->{baseurl};
$request_host = $opt_cmdline->{baseurl};
}
# respond OK to browser
print $client "HTTP/1.1 200 OK", Socket::CRLF;
# Invoke CGI
run_cgi( $client, $query_string, $request{URL}, $request_host );
# Else 404
} else {
print $se "ERROR: 404 Not Found\n";
print $client "HTTP/1.1 404 Not Found", Socket::CRLF;
print $client Socket::CRLF;
print $client "<html><body>404 Not Found</body></html>";
$data{"_status"} = "404";
}
# Close Connection
close $client;
# Exit child
exit 0;
}
}
# If we're running as a proper CGI from a web server...
} else {
# If we were called by a webserver and not the builtin webserver then seed some vars
my $prefix = $ENV{REQUEST_URI};
my $request_uri;
# remove trailing query
$prefix =~ s/\?.*$//gi;
my $query_string = $ENV{QUERY_STRING};
my $request_host = "http://$ENV{SERVER_NAME}:$ENV{SERVER_PORT}${prefix}";
# determine whether http or https
my $request_protocol = 'http';
if ( defined $ENV{'HTTPS'} ) {
$request_protocol = $ENV{'HTTPS'}=='on'?'https':'http';
}
my $request_host = "${request_protocol}://$ENV{SERVER_NAME}:$ENV{SERVER_PORT}${prefix}";
$home = $ENV{HOME};
# Read POSTed data from STDIN if this is a form POST
if ( $ENV{REQUEST_METHOD} eq 'POST' ) {
my $content;
while ( <STDIN> ) {
$content .= $_;
}
$query_string = parse_post_form_string( $content );
}
run_cgi( *STDOUT, $query_string, undef, $request_host );
}
exit 0;
sub default_encodinglocale {
return 'UTF-8' if (${^UNICODE} & 32);
return (IS_WIN32 ? 'cp1252' : 'UTF-8');
}
sub default_encodingconsoleout {
return 'UTF-8' if (${^UNICODE} & 6);
return (IS_WIN32 ? 'cp850' : 'UTF-8');
}
sub default_encodingwebrequest {
return 'UTF-8';
}
sub encode_fs {
return encode($opt_cmdline->{encodinglocalefs}, shift, FB_EMPTY);
}
sub decode_fs {
return decode($opt_cmdline->{encodinglocalefs}, shift, FB_EMPTY);
}
sub encode_cl {
return encode($opt_cmdline->{encodinglocale}, shift, FB_EMPTY);
}
sub decode_cl {
return decode($opt_cmdline->{encodinglocale}, shift, FB_EMPTY);
}
sub encode_wr {
return encode($opt_cmdline->{encodingwebrequest}, shift, FB_EMPTY);
}
sub decode_wr {
return decode($opt_cmdline->{encodingwebrequest}, shift, FB_EMPTY);
}
sub cleanup {
my $signal = shift;
print $se "INFO: Cleaning up PID $$ (signal = $signal)\n";
exit 0;
}
# wrap HTML::Entities::encode_entities to limit encoding
sub encode_entities {
my $value = shift;
return HTML::Entities::encode_entities( $value, '&<>"\'' );
}
sub parse_post_form_string {
my $form = $_[0];
my @data;
while ( $form =~ /Content-Disposition:(.+?)--/sg ) {
$_ = $1;
# form-data; name = "KEY"
m{name.+?"(.+?)"[\n\r\s]*(.+)}sg;
my ($key, $val) = ( $1, $2 );
next if ! $1;
$val =~ s/[\r\n]//g;
$val =~ s/\+/ /g;
# Decode entities first
decode_entities($val);
# url encode each entry
# $val =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
$val = CGI::escape($val);
push @data, "$key=$val";
}
return join '&', @data;
}
sub run_cgi {
# Get filehandle for output
$fh = shift;
binmode $fh, ':utf8';
my $query_string = shift;
my $request_uri = shift;
my $request_host = shift;
# Clean globals
%prog = ();
@pids = ();
@displaycols = ();
# new cgi instance
$cgi->delete_all() if defined $cgi;
$cgi = new CGI( $query_string );
# Get next page
$nextpage = $cgi->param( 'NEXTPAGE' ) || 'search_progs';
# Process All options
process_params();
# Set HOME env var for forked processes
$ENV{HOME} = $home;
my $action = $cgi->param( 'ACTION' ) || $request_uri;
# Strip the leading '/' to get the action
$action =~ s|^\/||g;
# Stream from file (optionally transcoding if required)
if ( $action eq 'direct' || $action eq 'playdirect' ) {
binmode $fh, ':raw';
# get filename first
my $progtype = $cgi->param( 'PROGTYPES' );
my $pid = $cgi->param( 'PID' );
my $mode = $cgi->param( 'MODES' );
my $filename = get_direct_filename( $pid, $mode, $progtype );
my $ext = lc( $cgi->param('STREAMTYPE') || $cgi->param( 'OUTTYPE' ) );
# get file source ext
my $src_ext = $filename;
$src_ext =~ s/^.*\.//g;
# Stream mime types
my %mimetypes = (
aac => 'audio/aac',
adts => 'audio/aac',
flac => 'audio/x-flac',
m4a => 'audio/mp4',
mp3 => 'audio/mpeg',
oga => 'audio/vorbis',
wav => 'audio/x-wav',
asf => 'video/x-ms-asf',
avi => 'video/avi',
flv => 'video/x-flv',
matroska => 'video/x-matroska',
mkv => 'video/x-matroska',
mov => 'video/quicktime',
mp4 => 'video/mp4',
mpegts => 'video/MP2T',
rm => 'audio/x-pn-realaudio',
ts => 'video/MP2T',
);
# default recipes
my $notranscode = 0;
# Disable transcoding if none is specified as OUTTYPE/STREAMTYPE
# Or if streaming MP4 via play direct
if ( $ext =~ /none/i ) {
print $se "INFO: Transcoding disabled (OUTTYPE=$ext)\n";
$ext = $src_ext;
$notranscode = 1;
# Else known types re-mux into flv unless play direct
} elsif ( $action ne 'playdirect' && ! $ext && $src_ext =~ m{^(m4a|mp4|mp3|aac|avi|mkv|mov|ts)$} ) {
$ext = 'flv';
# Else default to no transcoding
} elsif ( ! $ext ) {
$ext = $src_ext;
}
print $se "INFO: Streaming OUTTYPE:$ext MIMETYPE=$mimetypes{$ext} FILE:$filename to client\n";
# If type is defined
if ( $mimetypes{$ext} ) {
# Output headers
# to stream
# This will enable seekable -Accept_Ranges=>'bytes',
my $headers = $cgi->header( -type => $mimetypes{$ext}, -Connection => 'close' );
# Send the headers to the browser
print $se "\r\nHEADERS:\n$headers\n"; #if $opt_cmdline->{debug};
print $fh $headers;
stream_file( $filename, $mimetypes{$ext}, $src_ext, $ext, $notranscode, $cgi->param( 'BITRATE' ), $cgi->param( 'VSIZE' ), $cgi->param( 'VFR' ) );
} else {
print $se "ERROR: Aborting client thread - output mime type is undetermined\n";
}
# Get a playlist for a specified 'PROGTYPES'
} elsif ( $action eq 'playlistdirect' || $action eq 'playlistfiles' ) {
# Output headers
my $headers = $cgi->header( -type => 'audio/x-mpegurl' );
# To save file
#my $headers = $cgi->header( -type => 'audio/x-mpegurl', -attachment => 'get_iplayer.m3u' );
# Send the headers to the browser
print $se "\r\nHEADERS:\n$headers\n"; #if $opt_cmdline->{debug};
print $fh $headers;
# determine output type
my $outtype = $cgi->param('OUTTYPE');
$outtype = $cgi->param('STREAMTYPE') || $cgi->param('OUTTYPE') if $action eq 'playlistdirect';
# ( host, outtype, modes, progtype, bitrate, search, searchfields, action )
print $fh create_playlist_m3u_single( $request_host, $outtype, $opt->{MODES}->{current}, $opt->{PROGTYPES}->{current} , $cgi->param('BITRATE') || '', $opt->{SEARCH}->{current}, $opt->{SEARCHFIELDS}->{current} || 'name', $opt->{VERSIONLIST}->{current}, $action );
# Get a playlist for a selected progs in form
} elsif ( $action eq 'genplaylistdirect' || $action eq 'genplaylistfile' ) {
# Output headers
my $headers = $cgi->header( -type => 'audio/x-mpegurl' );
# To save file
#my $headers = $cgi->header( -type => 'audio/x-mpegurl', -attachment => 'get_iplayer.m3u' );
# Send the headers to the browser
print $se "\r\nHEADERS:\n$headers\n"; #if $opt_cmdline->{debug};
print $fh $headers;
# determine output type
my $outtype = $cgi->param('OUTTYPE');
$outtype = $cgi->param('STREAMTYPE') || $cgi->param('OUTTYPE') if $action eq 'genplaylistdirect';
# ( host, outtype, modes, bitrate, action )
print $fh create_playlist_m3u_multi( $request_host, $outtype, $cgi->param('BITRATE') || '', $action );
# HTML page
} else {
# Output header and html start
begin_html( $request_host );
# Page Routing
form_header( $request_host );
#print $fh $cgi->Dump();
if ( $opt_cmdline->{debug} ) {
print $fh $cgi->Dump();
#for my $key (sort keys %ENV) {
# print $fh $key, " = ", $ENV{$key}, "\n";
#}
}
if ($nextpages{$nextpage}) {
# call the correct subroutine
$nextpages{$nextpage}->();
}
form_footer();
html_end();
}
$cgi->delete_all();
return 0;
}
sub pvr_run {
print $fh "<strong><p>The PVR will auto-run every $opt->{AUTOPVRRUN}->{current} hour(s) if you leave this page open</p></strong>" if $opt->{AUTOPVRRUN}->{current};
if ( IS_WIN32 ) {
print $fh "<strong><p>Windows users: You may encounter errors if you perform other tasks in the Web PVR Manager while this page is reloading</p></strong>" if $opt->{AUTOPVRRUN}->{current};
print $fh "<strong><p>Windows users: The Web PVR Manager may crash if you leave this window open for a long period of time</p></strong>" if $opt->{AUTOPVRRUN}->{current};
}
print $se "INFO: Starting PVR Run\n";
my @cmd = (
@gip_cmd_base,
'--hash',
'--pvr',
);
#print $se "DEBUG: running: $cmd\n";
print $fh '<pre>';
# Redirect both STDOUT and STDERR to client browser socket
run_cmd_autorefresh( $fh, $fh, 1, @cmd );
print $fh '</pre>';
print $fh p("PVR Run complete");
# Load the refresh tab if required
my $autopvrrun = $cgi->cookie( 'AUTOPVRRUN' ) || $cgi->param( 'AUTOPVRRUN' );
# Render options actions
print $fh div( { -class=>'action' },
ul( { -class=>'action' },
li( { -class=>'action' }, [
a(
{
-class=>'action',
-title => 'Run PVR Now',
-onClick => "RefreshTab( '?NEXTPAGE=pvr_run&AUTOPVRRUN=$autopvrrun', ".(1000*3600*$autopvrrun).", 1 );",
},
'PVR Run Now'
),
a(
{
-class=>'action',
-title => 'Close',
-onClick => "window.close()",
},
'Close'
),
]),
),
);
}
sub record_now {
my @record;
# The 'Record' action button uses SEARCH to pass it's pvr_queue data
if ( $cgi->param( 'SEARCH' ) ) {
push @record, $cgi->param( 'SEARCH' );
} else {
@record = ( $cgi->param( 'PROGSELECT' ) );
}
my @params = get_search_params();
my $out;
# If a URL was specified by the User (assume auto mode list is OK):
if ( $opt->{URL}->{current} =~ m{^https?://} ) {
push @record, "$opt->{PROGTYPES}->{current}|$opt->{URL}->{current}|$opt->{URL}->{current}|-";
}
print $fh "<strong><p>Please leave this page open until the recording completes</p></strong>";
# Render options actions
print $fh div( { -class=>'action' },
ul( { -class=>'action' },
li( { -class=>'action' }, [
a(
{
-class=>'action',
-title => 'Close',
-onClick => "window.close()",
},
'Close'
),
]),
),
);
print $fh "<p>Recording The Following Programmes</p><ul>\n";
for (@record) {
chomp();
my ( $type, $pid, $name, $episode ) = (split /\|/)[0,1,2,3];
next if ! ($type && $pid );
print $fh "<li>$name - $episode ($pid)</li>\n";
}
print $fh "</ul><br />\n";
print $se "INFO: Starting Recording Now\n";
# Queue all selected 'TYPE|PID|NAME|EPISODE|MODE|CHANNEL' entries in the PVR
for (@record) {
chomp();
my ( $type, $pid, $name, $episode ) = (split /\|/)[0,1,2,3];
next if ! ($type && $pid );
my $comment = "$name - $episode";
my @cmd = (
@gip_cmd_base,
'--hash',
'--webrequest',
get_iplayer_webrequest_args(
"pid=$pid",
"type=$type",
build_cmd_options( grep !/^(HISTORY|SINCE|BEFORE|HIDEDELETED|FUTURE|SEARCH|SEARCHFIELDS|PROGTYPES|EXCLUDEC.+)$/, @params )
),
);
print $fh p("Command: ".( join ' ', @cmd ) ) if $opt_cmdline->{debug};
print $fh '<pre>';
# Redirect both STDOUT and STDERR to client browser socket
run_cmd_autorefresh( $fh, $fh, 1, @cmd );
print $fh '</pre>';
}
print $fh p("Recording complete");
return 0;
}
# Stream a file to browser/client
sub stream_file {
my ( $filename, $mimetype, $src_ext, $ext, $notranscode, $abitrate, $vsize, $vfr ) = ( @_ );
print $se "INFO: Start Direct Streaming $filename to browser using mimetype '$mimetype', output ext '$ext', audio bitrate '$abitrate', video size '$vsize', video frame rate '$vfr'\n";
# If transcoding required (i.e. output ext != source ext) - OR, if one of the transcoing options is set
if ( ( ! $notranscode ) && ( lc( $ext ) ne lc( $src_ext ) || $abitrate || $vsize || $vfr ) ) {
$fh->autoflush(0);
my @cmd = build_ffmpeg_args( $filename, $mimetype, $ext, $abitrate, $vsize, $vfr, $src_ext );
run_cmd( $fh, $se, 100000, @cmd );
print $se "INFO: Finished Streaming and transcoding $filename to browser\n";
} else {
print $se "INFO: Streaming file directly: $filename\n";
if ( ! open( STREAMIN, "< $filename" ) ) {
print $se "INFO: Cannot Read file '$filename'\n";
exit 4;
}
# Read each char from command output and push to socket fh
my $char;
my $bytes;
# Assume that we don't want to buffer STDERR output of the command
my $size = 100000;
while ( $bytes = read( STREAMIN, $char, $size ) ) {
if ( $bytes <= 0 ) {
close STREAMIN;
print $se "DEBUG: Stream thread has completed\n";
exit 0;
} else {
print $fh $char;
print $se '#';
}
last if $bytes < $size;
}
close STREAMIN;
print $se "INFO: Finished Streaming $filename to browser\n";
}
return 0;
}
sub build_ffmpeg_args {
my ( $filename, $mimetype, $ext, $abitrate, $vsize, $vfr, $src_ext ) = ( @_ );
my @cmd;
my @cmd_vopts;
my @cmd_aopts;
if ( $abitrate =~ m{^\d+$} ) {
push @cmd_aopts, ( '-ab', "${abitrate}k" );
}
if ( lc( $ext ) eq 'flv' ) {
push @cmd_aopts, ( '-ar', '44100' );
}
# If conversion is necessary
# Video
if ( $mimetype =~ m{^video} && $filename !~ m{\.(aac|m4a|mp3)$} ) {
# Apply video size
push @cmd_vopts, ( '-s', "${vsize}" ) if $vsize =~ m{^\d+x\d+$};
# Apply video framerate - caveat - bitrate defaults to 200k if only vfr is set
push @cmd_vopts, ( '-r', $vfr ) if $vfr =~ m{^\d+$};
# Add in the codec if we are transcoding and not remuxing the stream
if ( @cmd_vopts ) {
push @cmd_vopts, ( '-vcodec', 'libx264' );
} else {
push @cmd_vopts, ( '-vcodec', 'copy' );
}
# Audio
} else {
push @cmd_vopts, ( '-vn' );
}
@cmd = (
decode_fs($opt_cmdline->{ffmpeg}),
'-i', decode_fs($filename),
@cmd_vopts,
@cmd_aopts,
'-ac', 2,
'-f', $ext,
'-',
);
print $se "DEBUG: Command args: ".(join ' ', @cmd)."\n";
return @cmd;
}
sub create_playlist_m3u_single {
my ( $request_host, $outtype, $modes, $type, $bitrate, $search, $searchfields, $versionlist, $request ) = ( @_ );
my @playlist;
$outtype =~ s/^.*\.//g;
my $searchterm = $search;
# make search term regex friendly
if ( $searchterm ne '.*' && $searchterm !~ m{^http} ) {
$searchterm =~ s|([\/\.\?\+\-\*\^\(\)\[\]\{\}])|\\$1|g;
}
print $se "INFO: Getting playlist for type '$type' using modes '$modes' and bitrate '$bitrate'\n";
my @cmd = (
@gip_cmd_base,
'--webrequest',
get_iplayer_webrequest_args( 'history=1', 'skipdeleted=1', "type=$type", 'listformat=ENTRY|<pid>|<name>|<episode>|<desc>|<filename>|<mode>', "fields=$searchfields", "search=$searchterm", "versionlist=$versionlist" ),
);
my @out = get_cmd_output( @cmd );
push @playlist, "#EXTM3U\n";
# Extract and rewrite into m3u format
# /home/lewispj/mp3/Rock/radiohead/Ok Computer/radiohead - (07) fitter happier.mp3||(07) Fitter Happier|, , (256kbps/44.1kHz)|<filename>|<mode>
for ( grep !/^(Added:|Matches|$)/ , @out ) {
chomp();
my $url;
my ( $pid, $name, $episode, $desc, $filename, $mode, $channel ) = (split /\|/)[1,2,3,4,5,6,7];
#print $se "DEBUG: $pid, $name, $episode, $desc, $filename, $mode\n";
# sanitze modes && filename
$mode = '' if $mode eq '<mode>';
$filename = '' if $filename eq '<filename>';
# playlist with direct streaming for files through webserver
if ( $request eq 'playlistdirect' ) {
next if ! ( $pid && $type && $mode );
$url = build_url_direct( $request_host, $type, $pid, $mode, $outtype, $opt->{STREAMTYPE}->{current}, $opt->{HISTORY}->{current}, $opt->{BITRATE}->{current}, $opt->{VSIZE}->{current}, $opt->{VFR}->{current}, $opt->{VERSIONLIST}->{current} );
# playlist with local files
} elsif ( $request eq 'playlistfiles' ) {
next if ! $filename;
$url = search_absolute_path( $filename );
}
push @playlist, "#EXTINF:-1,$type - $channel - $name - $episode - $desc";
push @playlist, "$url\n";
}
print $se join ("\n", @playlist);
return join ("\n", @playlist);
}
sub create_playlist_m3u_multi {
my ( $request_host, $outtype, $bitrate, $request ) = ( @_ );
my @playlist;
push @playlist, "#EXTM3U\n";
my @record = ( $cgi->param( 'PROGSELECT' ) );
# Create m3u from all selected 'TYPE|PID|NAME|EPISODE|MODE|CHANNEL' entries in the PVR
for (@record) {
my $url;
chomp();
my ( $type, $pid, $name, $episode, $mode, $channel ) = (split /\|/)[0,1,2,3,4,5];
next if ! ($type && $pid );
# playlist with direct streaming fo files through webserver
if ( $request eq 'genplaylistdirect' ) {
$url = build_url_direct( $request_host, $type, $pid, $mode, $outtype, $opt->{STREAMTYPE}->{current}, $opt->{HISTORY}->{current}, $opt->{BITRATE}->{current}, $opt->{VSIZE}->{current}, $opt->{VFR}->{current}, $opt->{VERSIONLIST}->{current} );
# playlist with local files
} elsif ( $request eq 'genplaylistfile' ) {
# Lookup filename (add it if defined - even if relative)
# check for -f $filename if you want to exclude files that cannot be found
my $filename = get_direct_filename( $pid, $mode, $type );
$url = $filename if -f $filename;
}
# Skip empty urls
next if ! $url;
push @playlist, "#EXTINF:-1,$type - $channel - $name - $episode";
push @playlist, "$url\n";
}
print $se join ("\n", @playlist);
return join ("\n", @playlist);