#!/perl -w
# NAME: downloadut02.pl
# AIM: To download a YouTube video 
# NOTE: THIS NO LONGER WORKS DUE TO MANY CHANGES IN THE YOUTUBE CONTENTS PAGE!!!
use strict;
use warnings;
use LWP::Simple;
use LWP::UserAgent;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
    my @tmpsp = split(/\\/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);
###prt( "$0 ... Hello, World ...\n" );

my $filename = '';
my $getname = '';
# shamelessly reversed engineered from a python script :-) 
prt( "starting first page retrieval\n" );
my $urlin  = shift || "http://youtube.com/watch?v=EkTpUxh8Vxc";
my $content = get( $urlin  ) or die "$!\n"; 
prt( "done first page retrieval\n" );
my @tlines = ();
my $line = '';
prt( "===================================================================\n" );
write2file( $content, "temputraw.txt" );
my @lines = split(/\n/,$content);
foreach $line (@lines) {
    chomp $line;
    $line = trim_all($line);
    push(@tlines,$line) if length($line);
    if ($line =~ /\.swf/i) {
        prt( "$line\n" );
    }
}
prt( "\n===================================================================\n" );
write2file( join("\n",@tlines), 'temput.txt' );
# regex for 2 key text strings which identify the video file
# the second one $2 is unique for each download attempt
$content =~ /player2\.swf\?video_id=([^&]+)&.*t=([^&]+)&/ ;
if ($1 && length(%1)) {
    $filename = $1;
}
if ($2 && length($2)) {
    $getname = $2;
}
print $filename, "\n" , $getname, "\n";  
my $infile = $filename.'.flv';  #add a .flv extension

if (length($filename) == 0) {
    print "FAILED to get video file name ...\n";
    exit(0);
}

prt( "Out to file $infile ...\n" );
#http://www.youtube.com/get_video?video_id=p_YMigZmUuk&t=OEgsToPDskLRl9-iKyfQVcNT8xes2OIT
my $get_url = 'http://www.youtube.com/get_video?video_id='.$filename.'&t='.$getname;

prt( "gettin video file $get_url\n" );

# don't buffer the prints to make the status update
$| = 1;

open(IN,"> $infile") or mydie( "FAILED to create $infile ... $_ ...\n" ); 
binmode(IN);

my $ua = LWP::UserAgent->new();
my $received_size = 0;
my $url = $get_url;
prt( "Fetching $url\n" );
my $request_time = time;
my $last_update = 0;
my $response = $ua->get($url,
                        ':content_cb'     => \&callback,
                        ':read_size_hint' => 8192,
                       );
prt( "\n" );
close IN;

#play the flv file with mplayer
system( "mplayer $infile" );

close_log($outfile,1);
exit(0);

###################################################################

sub callback {
  my ($data, $response, $protocol) = @_;

  my $total_size = $response->header('Content-Length') || 0;
  $received_size += length $data;

  # write the $data to a filehandle or whatever should happen
  # with it here.
  print IN $data;

  my $time_now = time;

  # this to make the status only update once per second.
  return unless $time_now > $last_update or $received_size == $total_size;
  $last_update = $time_now;

  prt( "\rReceived $received_size bytes" );
  prt( printf " (%i%%)", (100/$total_size)*$received_size ) if $total_size;
  prt( printf " %6.1f/bps", $received_size/(($time_now-$request_time)||1) ) if $received_size;
}

# eof - downloadut02.pl
