| 1 | package Cikl::Smrt::Decoders::Zip; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Cikl::Smrt::DecoderRole; | ||
| 6 | use Cikl::Smrt::AutoDecodableRole; | ||
| 7 | use IO::Uncompress::Unzip qw(unzip $UnzipError); | ||
| 8 | use Mouse; | ||
| 9 | use namespace::autoclean; | ||
| 10 | use Cikl::Logging; | ||
| 11 | with 'Cikl::Smrt::DecoderRole'; | ||
| 12 | with 'Cikl::Smrt::AutoDecodableRole'; | ||
| 13 | |||
| 14 | my $logger = get_logger(); | ||
| 15 | |||
| 16 | has 'zip_filename' => ( | ||
| 17 | is => 'ro', | ||
| 18 | isa => 'Maybe[Str]', | ||
| 19 | required => 0 | ||
| 20 | ); | ||
| 21 | |||
| 22 | use constant MIME_TYPES => ( | ||
| 23 | 'application/x-zip', | ||
| 24 | 'application/zip' | ||
| 25 | ); | ||
| 26 | sub mime_types { return MIME_TYPES; } | ||
| 27 | |||
| 28 | sub decode { | ||
| 29 | my $self = shift; | ||
| 30 | my $fh = shift; | ||
| 31 | |||
| 32 | my $file = $self->zip_filename; | ||
| 33 | if(!defined($file)){ | ||
| 34 | $logger->warn("No zip_filename provided. We'll be extracting the FIRST file that appears within the zip, whatever that may be!"); | ||
| 35 | } | ||
| 36 | |||
| 37 | my $foundit = 0; | ||
| 38 | my $zipfh = IO::Uncompress::Unzip->new($fh, AutoClose => 1) or die($!); | ||
| 39 | my $status; | ||
| 40 | for ($status = 1; $status > 0; $status = $zipfh->nextStream()) { | ||
| 41 | if (defined($file)) { | ||
| 42 | if ($zipfh->getHeaderInfo()->{Name} eq $file) { | ||
| 43 | # Found the file. | ||
| 44 | $foundit = 1; | ||
| 45 | last; | ||
| 46 | } | ||
| 47 | } else { | ||
| 48 | $foundit = 1; | ||
| 49 | last; | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | if (!$foundit) { | ||
| 54 | die("Failed to find file named $file"); | ||
| 55 | } | ||
| 56 | return $zipfh; | ||
| 57 | } | ||
| 58 | |||
| 59 | __PACKAGE__->meta->make_immutable(); | ||
| 60 | |||
| 61 | 1; |