File Coverage

blib/lib/Net/SFTP/Foreign/Tempdir/Extract.pm
Criterion Covered Total %
statement 18 115 15.6
branch 0 80 0.0
condition 0 6 0.0
subroutine 6 22 27.2
pod 13 13 100.0
total 37 236 15.6


line stmt bran cond sub pod time code
1             package Net::SFTP::Foreign::Tempdir::Extract;
2 7     7   599578 use strict;
  7         71  
  7         206  
3 7     7   40 use warnings;
  7         14  
  7         206  
4 7     7   35 use base qw{Package::New};
  7         15  
  7         3270  
5 7     7   3568 use File::Tempdir qw{};
  7         90371  
  7         155  
6 7     7   7109 use Net::SFTP::Foreign qw{};
  7         415758  
  7         229  
7 7     7   3597 use Net::SFTP::Foreign::Tempdir::Extract::File;
  7         29  
  7         9140  
8              
9             our $VERSION = '0.14';
10              
11             =head1 NAME
12              
13             Net::SFTP::Foreign::Tempdir::Extract - Secure FTP client integrating Path::Class, Tempdir, and Archive Extraction
14              
15             =head1 SYNOPSIS
16              
17             use Net::SFTP::Foreign::Tempdir::Extract;
18             my $sftp = Net::SFTP::Foreign::Tempdir::Extract->new(
19             host => $host,
20             user => $user,
21             match => qr/\.zip\Z/,
22             backup => './backup', #default is not to backup
23             delete => 1, #default is not to delete
24             );
25             my $file = $sftp->next;
26              
27             =head1 DESCRIPTION
28              
29             Secure FTP client which downloads files locally to a temp directory for operations and automatically cleans up all temp files after variables are out of scope.
30              
31             This package assume SSH keys are correctly installed on local account and remote server.
32              
33             =head1 USAGE
34              
35             =head2 File Downloader
36              
37             This is a simple file downloader implementation
38              
39             use Net::SFTP::Foreign::Tempdir::Extract;
40             my $sftp = Net::SFTP::Foreign::Tempdir::Extract->new(host=>$remote_host, user=>$remote_user);
41             my $file = $sftp->download($remote_folder, $remote_filename);
42              
43             =head2 File Watcher
44              
45             This is a simple file watcher implementation
46              
47             use Net::SFTP::Foreign::Tempdir::Extract;
48             my $sftp = Net::SFTP::Foreign::Tempdir::Extract->new(
49             host=>'remote_server',
50             user=>'remote_account',
51             match=>qr/\.zip\Z/,
52             folder=>'/remote_folder'
53             );
54             my $file = $sftp->next or exit; #nothing to process so exit
55             print "$file"; #process file here
56              
57             =head2 Subclass
58              
59             This is a typical subclass implementation for a particular infrastructure
60              
61             {
62             package My::SFTP;
63             use base qw{Net::SFTP::Foreign::Tempdir::Extract};
64             sub host {'remote_server.domain.tld'};
65             sub folder {'/remote_folder'};
66             sub match {qr/\.zip\Z/};
67             sub backup {time};
68             1;
69             }
70              
71             my $sftp = My::SFTP->new;
72             while (my $file = $sftp->next) {
73             printf "File %s is a %s\n", "$file", ref($file);
74             }
75              
76             Which outputs something like this.
77              
78             File /tmp/hwY9jVeYo3/file1.zip is a Net::SFTP::Foreign::Tempdir::Extract::File
79             File /tmp/ytWaYdPXuD/file2.zip is a Net::SFTP::Foreign::Tempdir::Extract::File
80             File /tmp/JrsrkleBOy/file3.zip is a Net::SFTP::Foreign::Tempdir::Extract::File
81              
82             =head1 CONSTRUCTOR
83              
84             =head2 new
85              
86             =head1 METHODS
87              
88             =head2 download
89              
90             Downloads the named file in the folder.
91              
92             my $file = $sftp->download('remote_file.zip'); #isa Net::SFTP::Foreign::Tempdir::Extract::File
93             my $file = $sftp->download('/remote_folder', 'remote_file.zip'); # which isa Path::Class::File object with an extract method
94              
95             =cut
96              
97             sub download {
98 0     0 1   my $self = shift;
99 0           my $sftp = $self->sftp;
100 0 0         my $remote = pop or die('Error: filename required.');
101 0   0       my $folder = shift || $self->folder;
102 0 0         my $tmpdir = File::Tempdir->new or die('Error: Could not create File::Tempdir object');
103 0 0         my $local_folder = $tmpdir->name or die('Error: Temporary directory not configured.');
104 0 0         $sftp->setcwd($folder) or die(sprintf('Error: %s', $sftp->error));
105 0 0         $sftp->mget($remote, $local_folder) or die(sprintf('Error: %s', $sftp->error));
106 0           my $file = Net::SFTP::Foreign::Tempdir::Extract::File->new($local_folder => $remote);
107 0 0         die("Error: Could not read $file.") unless -r $file;
108 0           $file->{'__tmpdir'}=$tmpdir; #must keep tmpdir scope alive
109 0           my $backup = $self->backup;
110 0 0         if ($backup) {
    0          
111 0 0         $sftp->mkpath($backup) or die('Error: Cannot create backup directory');
112 0 0         $sftp->rename($remote, "$backup/$remote") or die("Error: Cannot rename remote file $remote to $backup/$remote");
113             } elsif ($self->delete) {
114 0 0         $sftp->remove($remote) or warn("Warning: Cannot delete remote file $remote");
115             }
116 0           return $file;
117             }
118              
119             =head2 next
120              
121             Downloads the next file in list and saves it locally to a temporary folder. Returns a L object or undef if there are no more files.
122              
123             my $file = $sftp->next or exit; #get file or exit
124              
125             while (my $file = $sftp->next) {
126             print "$file";
127             }
128              
129             =cut
130              
131             sub next {
132 0     0 1   my $self=shift;
133 0           my $list=$self->list;
134 0 0         if (@$list) {
135 0           my $file=shift @$list;
136             #print Dumper($file);
137 0           return $self->download($file);
138             } else {
139 0           return;
140             }
141             }
142              
143             =head2 list
144              
145             Returns list of filenames remaining to be processed that match the folder and regular expression
146              
147             Note: List is shifted for each call to next method
148              
149             =cut
150              
151             sub list {
152 0     0 1   my $self=shift;
153 0 0         $self->{'list'}=shift if @_;
154 0 0         unless (defined($self->{'list'})) {
155             #printf "%s: Listing files in folder: %s\n", DateTime->now, $self->folder;
156 0           $self->{'list'}=$self->sftp->ls(
157             $self->folder,
158             wanted => $self->match,
159             ordered => 1,
160             no_wanted => qr/\A\.{1,2}\Z/,
161             names_only => 1,
162             );
163             die(sprintf(qq{Error: File list did not return as expected. Verify folder "%s" exists and is readable.}, $self->folder))
164 0 0 0       unless (defined($self->{'list'}) and ref($self->{'list'}) eq 'ARRAY');
165             }
166 0 0         return wantarray ? @{$self->{'list'}} : $self->{'list'};
  0            
167             }
168              
169             =head2 upload
170              
171             Uploads file to the folder and returns the count of uploaded files.
172              
173             $sftp->folder("/remote_folder"); #or set on construction
174             $sftp->upload('local_file.zip');
175             $sftp->upload('local_file1.zip', 'local_file2.zip');
176              
177             The upload method is a simple wrapper around Net::SFTP::Foreign->mput that is parallel to download.
178              
179             =cut
180              
181             sub upload {
182 0     0 1   my $self = shift;
183 0           my @files = @_;
184 0           my $sftp = $self->sftp;
185 0           return $sftp->mput(\@files, $self->folder);
186             }
187              
188             =head1 PROPERTIES
189              
190             =head2 host
191              
192             SFTP server host name.
193              
194             $sftp->host(""); #default
195              
196             =cut
197              
198             sub host {
199 0     0 1   my $self=shift;
200 0 0         if (@_) {
201 0           $self->{'host'} = shift;
202 0           delete $self->{'list'};
203 0           delete $self->{'sftp'};
204             }
205 0 0         $self->{'host'}=$self->_host_default unless defined($self->{'host'});
206 0           return $self->{'host'};
207             }
208              
209             sub _host_default {
210 0     0     return '';
211             }
212              
213             =head2 user
214              
215             SFTP user name (defaults to current user)
216              
217             $sftp->user(undef); #default
218              
219             =cut
220              
221             sub user {
222 0     0 1   my $self=shift;
223 0 0         if (@_) {
224 0           $self->{'user'} = shift;
225 0           delete $self->{'list'};
226 0           delete $self->{'sftp'};
227             }
228 0           return $self->{'user'};
229             }
230              
231             =head2 port
232              
233             SFTP port number (defaults to undef not passed through)
234              
235             $sftp->port(undef); #default
236              
237             =cut
238              
239             sub port {
240 0     0 1   my $self=shift;
241 0 0         if (@_) {
242 0           $self->{'port'} = shift;
243 0           delete $self->{'list'};
244 0           delete $self->{'sftp'};
245             }
246 0 0         $self->{'port'}=undef unless defined $self->{'port'};
247 0           return $self->{'port'};
248             }
249              
250             =head2 options
251              
252             SSH options passed to the more property of L as an array reference.
253              
254             $sftp->options(['-q']); #default
255             $sftp->options([]); #no options
256             $sftp->options(['-v']); #verbose
257              
258             =cut
259              
260             sub options {
261 0     0 1   my $self=shift;
262 0 0         if (@_) {
263 0           $self->{'options'} = shift;
264 0           delete $self->{'list'};
265 0           delete $self->{'sftp'};
266             }
267 0 0         $self->{'options'}=['-q'] unless defined $self->{'options'};
268 0 0         die 'Error: options must be an array reference.' unless ref($self->{'options'}) eq 'ARRAY';
269 0           return $self->{'options'};
270             }
271              
272             =head2 folder
273              
274             Folder on remote SFTP server.
275              
276             $sftp->folder("/home/user/download");
277              
278             Note: Some SFTP servers put clients in a change rooted environment.
279              
280             =cut
281              
282             sub folder {
283 0     0 1   my $self=shift;
284 0 0         if (@_) {
285 0           $self->{'folder'} = shift;
286 0           delete $self->{'list'};
287             }
288 0 0         $self->{'folder'}=$self->_folder_default unless defined $self->{'folder'};
289 0           return $self->{'folder'};
290             }
291              
292             sub _folder_default {
293 0     0     return '/incoming';
294             }
295              
296             =head2 match
297              
298             Regular Expression to match file names for the next iterator
299              
300             $sftp->match(qr/\Aremote_file\.zip\Z/); #exact file
301             $sftp->match(qr/\.zip\Z/); #any zip file
302             $sftp->match(undef); #reset to default - all files
303              
304             =cut
305              
306             sub match {
307 0     0 1   my $self=shift;
308 0 0         if (@_) {
309 0           $self->{'match'} = shift;
310 0           delete $self->{'list'};
311             }
312 0 0         $self->{'match'}=$self->_match_default unless defined($self->{'match'});
313 0           return $self->{'match'};
314             }
315              
316             sub _match_default {
317 0     0     return qr//;
318             }
319              
320             =head2 backup
321              
322             Sets or returns the backup folder property.
323              
324             $sftp->backup(""); #don't backup
325             $sftp->backup("./folder"); #backup to folder
326              
327             Note: If configured, backup overrides delete option.
328              
329             =cut
330              
331             sub backup {
332 0     0 1   my $self=shift;
333 0 0         $self->{'backup'}=shift if @_;
334 0 0         $self->{'backup'}='' unless defined($self->{'backup'});
335 0           return $self->{'backup'};
336             }
337              
338             =head2 delete
339              
340             Sets or returns the delete boolean property.
341              
342             $sftp->delete(0); #don't delete
343             $sftp->delete(1); #delete after downloaded
344              
345             Note: Ineffective when backup option is configured.
346              
347             =cut
348              
349             sub delete {
350 0     0 1   my $self=shift;
351 0 0         $self->{'delete'}=shift if @_;
352 0 0         $self->{'delete'}=0 unless defined($self->{'delete'});
353 0           return $self->{'delete'};
354             }
355              
356             =head1 OBJECT ACCESSORS
357              
358             =head2 sftp
359              
360             Returns a cached connected L object
361              
362             =cut
363              
364             sub sftp {
365 0     0 1   my $self=shift;
366 0 0         unless (defined $self->{'sftp'}) {
367 0           my %params = ();
368 0 0         $params{'host'} = $self->host or die('Error: host required');
369 0 0         $params{'user'} = $self->user if $self->user; #not required
370 0 0         $params{'port'} = $self->port if defined($self->port); #not required
371 0 0         $params{'more'} = $self->options if @{$self->options} > 0; #not required
  0            
372 0           my $sftp = Net::SFTP::Foreign->new($params{'host'}, %params);
373             die(
374             sprintf("Error connecting to sftp://%s%s%s/ - %s",
375             ($params{'user'} ? $params{'user'} . '@' : ''),
376             $params{'host'},
377 0 0         ($params{'port'} ? ':' . $params{'port'} : ''),
    0          
    0          
378             $sftp->error
379             )
380             ) if $sftp->error;
381 0           $self->{'sftp'} = $sftp;
382             }
383 0           return $self->{'sftp'};
384             }
385              
386             =head1 BUGS
387              
388             Send email to author and log on RT.
389              
390             =head1 SUPPORT
391              
392             DavisNetworks.com supports all Perl applications including this package.
393              
394             =head2 Testing
395              
396             This packages relies on the SSH keys to be operational for the local account. To test your SSH keys from the command line type `sftp user@server`. If this command prompts the user for a password, then your SSH keys are not installed correctly. You cannot reliably test with `ssh user@server` as the remote administrator may have disabled the terminal service over SSH.
397              
398             =head1 AUTHOR
399              
400             Michael R. Davis
401             CPAN ID: MRDVT
402             Satellite Tracking of People, LLC
403             mdavis@stopllc.com
404             http://www.stopllc.com/
405              
406             =head1 COPYRIGHT
407              
408             This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
409              
410             The full text of the license can be found in the LICENSE file included with this module.
411              
412             =head1 SEE ALSO
413              
414             =head2 Building Blocks
415              
416             L, L, L
417              
418             =cut
419              
420             1;