File Coverage

blib/lib/Wiktionary/Parser/Section/Pronunciation/Audio.pm
Criterion Covered Total %
statement 10 37 27.0
branch 0 14 0.0
condition 0 3 0.0
subroutine 3 7 42.8
pod 0 5 0.0
total 13 66 19.7


line stmt bran cond sub pod time code
1             package Wiktionary::Parser::Section::Pronunciation::Audio;
2              
3 3     3   1144 use MediaWiki::API;
  3         96829  
  3         99  
4 3     3   23 use File::Path;
  3         7  
  3         1529  
5              
6             # keys:
7             # file: name of the audio file
8             # text: text label for this file
9             # context: e.g. en(US), en(UK)
10             sub new {
11 5     5 0 8 my $class = shift;
12 5         17 my %args = @_;
13 5         18 my $self = bless \%args, $class;
14 5         17 return $self;
15             }
16              
17             sub get_file {
18 0     0 0   my $self = shift;
19 0           return $self->{file};
20             }
21              
22             sub get_text {
23 0     0 0   my $self = shift;
24 0           return $self->{text};
25             }
26              
27             sub get_context {
28 0     0 0   my $self = shift;
29 0           return $self->{context};
30             }
31              
32             sub download_file {
33 0     0 0   my $self = shift;
34 0           my %args = @_;
35 0 0         my $directory = $args{directory} or die 'you need to specify a directory to download to';
36 0           my $filename = $self->{file};
37              
38 0 0         return unless $filename;
39              
40 0           my $api = MediaWiki::API->new({
41             api_url => 'http://en.wiktionary.org/w/api.php',
42             });
43              
44 0           my $file_content = $api->download({title => "File:$filename"});
45              
46 0 0         if ($api->{error}->{code}) {
47 0           print STDERR $api->{error}->{code} . ': ' . $api->{error}->{details};
48             }
49              
50 0 0 0       unless (defined $file_content && bytes::length($file_content)) {
51 0           print STDERR "'$filename' doesn't exist or failed to download";
52 0           return;
53             }
54              
55             # create local directory if it doesn't exist
56 0 0         unless (-e $directory) {
57 0           File::Path::make_path($directory);
58             }
59              
60             # also verify directory is writable
61 0 0         unless (-w $directory) {
62 0           die "unable to write to '$directory'";
63             }
64 0           my $download_location = "$directory/$filename";
65 0 0         open (my $fh, ">",$download_location) or die $!;
66 0           print $fh $file_content;
67 0           close $fh;
68              
69 0           return $download_location;
70             }
71              
72             1;