| 1 | package VFSsimple::Drv::Http; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use base qw(VFSsimple::Base); | ||
| 6 | use Net::HTTP (); | ||
| 7 | use URI (); | ||
| 8 | use File::Temp qw(tempfile); | ||
| 9 | |||
| 10 | our $VERSION = '0.03'; | ||
| 11 | |||
| 12 | =head1 NAME | ||
| 13 | |||
| 14 | VFSsimple::Drv::Http - A VFSsimple implementation over http protocol | ||
| 15 | |||
| 16 | =head1 DESCRIPTION | ||
| 17 | |||
| 18 | This module provide access method for VFSsimple module to access to file on | ||
| 19 | http server. | ||
| 20 | |||
| 21 | Access is provided using L<Net::Http> module. | ||
| 22 | |||
| 23 | =cut | ||
| 24 | |||
| 25 | sub drv_new { | ||
| 26 | my ($self) = @_; | ||
| 27 | my $uri = URI->new($self->{root}); | ||
| 28 | my $http = Net::HTTP->new($uri->host()); | ||
| 29 | |||
| 30 | $self->{uri} = $uri; | ||
| 31 | $self->{http} = $http; | ||
| 32 | return $http ? $self : (); | ||
| 33 | } | ||
| 34 | |||
| 35 | sub drv_get { | ||
| 36 | my ($self, $src) = @_; | ||
| 37 | my (undef, $dest) = tempfile(UNLINK => 0); | ||
| 38 | $self->drv_copy($src, $dest); | ||
| 39 | } | ||
| 40 | |||
| 41 | sub drv_copy { | ||
| 42 | my ($self, $src, $dest) = @_; | ||
| 43 | my $path = $self->{uri}->path() . '/' . $src; | ||
| 44 | $self->{http}->write_request(GET => $path, 'User-Agent' => "Mozilla/5.0 VFSsimple::Http") or return; | ||
| 45 | my $code = $self->{http}->read_response_headers; | ||
| 46 | open(my $fh, '>', $dest) or return; | ||
| 47 | while (1) { | ||
| 48 | my $buf; | ||
| 49 | my $n = $self->{http}->read_entity_body($buf, 1024); | ||
| 50 | return() unless defined $n; | ||
| 51 | last unless $n; | ||
| 52 | print $fh $buf; | ||
| 53 | } | ||
| 54 | close($fh); | ||
| 55 | return $dest; | ||
| 56 | } | ||
| 57 | |||
| 58 | sub drv_exists { | ||
| 59 | my ($self, $file) = @_; | ||
| 60 | my $path = $self->{uri}->path() . '/' . "$file"; | ||
| 61 | $self->{http}->write_request( | ||
| 62 | HEAD => $path, | ||
| 63 | 'User-Agent' => "Mozilla/5.0 VFSsimple::Http" | ||
| 64 | ) or return; | ||
| 65 | my $code = $self->{http}->read_response_headers; | ||
| 66 | return($code eq '200'); | ||
| 67 | } | ||
| 68 | |||
| 69 | 1; | ||
| 70 | |||
| 71 | __END__ |