fix quoting in AsyncWgetFileGetter again
[videosite.git] / videosite / AsyncWgetFileGetter.pm
1 # (c) 2007 by Ralf Ertzinger <ralf@camperquake.de>
2 #     2008-2009,2011-2012 by Christian Garbs <mitch@cgarbs.de>
3 #     2010 by Maximilian Rehkopf <otakon@gmx.net>
4 #
5 # licensed under GNU GPL v2
6 #
7 # A getter which will download the media to a local file storage
8 # in the background using wget
9 #
10
11 package videosite::AsyncWgetFileGetter;
12
13 use videosite::FileGetter;
14 @ISA = qw(videosite::FileGetter);
15
16 use strict;
17 use File::Basename;
18 use File::Temp qw(tempfile);
19 use MIME::Base64;
20
21 sub new {
22     my $class = shift;
23     my $self = $class->SUPER::new(
24         NAME => 'asyncwgetfilegetter',
25         @_,
26     );
27
28     return bless($self, $class);
29 }
30
31 sub get {
32     my $self = shift;
33     my $video = shift;
34
35     # saving the environment has nice race conditions... :(
36     my %saved_env;
37     
38     if (exists($video->{'CONNECTOR'})) {
39         my $schemas = $video->{'CONNECTOR'}->{'schemas'};
40         foreach my $schemakey(keys(%{$schemas})) {
41             $self->debug("Setting %s_proxy to %s", $schemakey, $schemas->{$schemakey});
42             my $envkey = $schemakey.'_proxy';
43             $saved_env{ $envkey } = $ENV{ $envkey };
44             $ENV{ $envkey } = $schemas->{$schemakey};
45         }
46     }
47
48     # dispatch to super class method
49     $self->SUPER::get($video);
50
51     # restore environment
52     foreach my $envkey (keys %saved_env) {
53         $self->debug("Restoring environment: %s=%s", $envkey, $saved_env{ $envkey} );
54         $ENV{ $envkey } = $saved_env{ $envkey };
55     }
56
57     return 1;
58 }
59
60 sub _download {
61     my $self = shift;
62     my $dlurl = shift;
63     my $dlfile = shift;
64     my $video = shift;
65     my $res;
66     my $cookie = '';
67     my $useragent = qq{ --user-agent='Mozilla/4.0 (compatible; MSIE 5.0; Linux) Opera 5.0  [en]' };
68
69     $dlfile =~ s/'/'"'"'/g; # escape ' as '"'"' (end current 'string', new "string" containing a ', start new 'string')
70     
71     my (undef, $tmpfile) = tempfile('videosite.tmp.XXXXXXXXXXXX', DIR => dirname($dlfile));
72
73     $self->debug('Going to download %s to %s (%s)', $dlurl, $dlfile, $tmpfile);
74
75     $cookie = qq{ --header='Cookie: $video->{'COOKIE'}'} if (defined $video->{'COOKIE'});
76     my $cmdline = qq{ ( wget -q -O'$tmpfile' $useragent $cookie '$dlurl' && mv '$tmpfile' '$dlfile' && chmod =rw '$dlfile' && touch '$dlfile' || rm -f '$tmpfile' ) & };
77     $self->debug("Going to execute: %s", $cmdline);
78     system($cmdline);
79
80     return 1;
81 }