Skip to content

Instantly share code, notes, and snippets.

@h2oota
Created November 16, 2012 13:02
Show Gist options
  • Save h2oota/4087184 to your computer and use it in GitHub Desktop.
Save h2oota/4087184 to your computer and use it in GitHub Desktop.
CGI TS生成プロセスの起動、プレイリストのアクセストラック cgi/watch
#!/usr/local/bin/perl -w
use strict;
use CGI::Lite;
use File::Temp qw/ tempdir /;
use Digest::MD5 qw(md5 md5_hex md5_base64);
our $cgi = new CGI::Lite;
our %form = $cgi->parse_form_data('POST');
our %cookies = $cgi->parse_cookies;
our %channels;
our $key = pack('H*', '11111111111111111111111111111111');
#use constant WORKDIR => '/home/u/work/DTV/';
our $WORKDIR = $ENV{DATA_PATH} || '/var/one_seg/';
open(CH, '../channels.txt') || die;
while (<CH>) {
$channels{$2} = $1 if (/(\d+)\s+(\S+)/);
}
close(CH);
our ($dir, $id);
if (defined($cookies{id})
&& $cookies{id} =~ /([^-]+)-([^-]+)/
&& $2 eq md5_hex($1 . $key)) {
$id = $cookies{id}
}
if ($id && defined($ENV{PATH_INFO}) && -r "${WORKDIR}$ENV{PATH_INFO}") {
$dir = "/var/one_seg/$1";
open(PL, "${WORKDIR}$ENV{PATH_INFO}") || die;
print <<EOT
Content-type: application/vnd.apple.mpegurl
Set-Cookie: $id=id;path=/
Set-Cookie2: $id=id;path=/
EOT
;
print $_ while(<PL>);
close(PL);
open (T, ">${WORKDIR}$ENV{PATH_INFO}.last");
print T time;
close(T);
} else {
unless ($form{channel} && $channels{$form{channel}}) {
print <<EOT
Status: 404 not found
Content-type: text/html
<html>
<body>
EOT
;
for (sort keys %ENV) {
print "$_ : $ENV{$_}<br/>\n";
}
print "<hr/>";
for (keys %form) {
print "$_ : $form{$_}<br/>\n";
}
print <<EOT
</body>
</html>
EOT
;
exit;
}
if (defined($id)
&& $id =~ /([^-]+)-/
&& -r "${WORKDIR}${1}/stream.m3u8"
&& -r "${WORKDIR}${1}/pid") {
my $d = $1;
open(PID, "${WORKDIR}${d}/pid");
kill 2, 0 + <PID>;
close(PID);
}
$dir = tempdir($WORKDIR . "XXXXXXXX");
chmod 0755, $dir;
$dir =~ m!.*/([^/]+)$!;
$id = "${1}-" . md5_hex($1 . $key);
open (T, ">$dir/stream.m3u8.last") || die;
print T time;
close(T);
system("daemon", "-f", "/usr/local/bin/perl",
"../bin/start_watch", "$dir", "$channels{$form{channel}}");
my $retry;
for ($retry = 0; $retry < 15; $retry++) {
last if (-r "$dir/stream.m3u8");
sleep 1;
}
if (-r "$dir/stream.m3u8") {
print <<EOT
Status: 302 Moved
Location: /cgi/watch/$1/stream.m3u8
Content-type: text/html
Set-Cookie: id=$id;path=/
Set-Cookie2: id=$id;path=/
<html>
<body>
Moved /cgi/watch/$1/stream.m3u8
</body>
</html>
EOT
;
} else {
print <<EOT
Status: 503 Service Unavailable
Content-type: text/plane
Service Unavailable
EOT
;
print "$dir $retry\n";
open(LOG, "ls -la $dir $dir/stream.m3u8 2>&1|");
while (<LOG>) {
print $_;
}
close (LOG);
open(LOG, "$dir/log");
while (<LOG>) {
print $_;
}
close (LOG);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment