Tools/Unpack.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Tools/LZSS.pm ↑ Summary Tools.pm »
1 package EBook::Tools::Unpack;
2 2 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use version 0.74; our $VERSION = qv("0.5.0");
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # Perl Critic overrides:
7 ## no critic (Package variable)
8 # RequireBriefOpen seems to be way too brief to be useful
9 ## no critic (RequireBriefOpen)
10 # Builtin homonyms are methods and flagged as such
11 ## no critic (ProhibitBuiltinHomonyms)
12 # Double-sigils are needed for lexical filehandles in clear print statements
13 ## no critic (Double-sigil dereference)
14  
15 =head1 NAME
16  
17 EBook::Tools::Unpack - Object class for unpacking e-book files into their component parts and metadata
18  
19 =head1 SYNOPSIS
20  
21 use EBook::Tools::Unpack;
22 my $unpacker = EBook::Tools::Unpack->new(
23 'file' => $filename,
24 'dir' => $dir,
25 'encoding' => $encoding,
26 'format' => $format,
27 'raw' => $raw,
28 'author' => $author,
29 'title' => $title,
30 'opffile' => $opffile,
31 'tidy' => $tidy,
32 'nosave' => $nosave,
33 );
34 $unpacker->unpack;
35  
36 or, more simply:
37  
38 use EBook::Tools::Unpack;
39 my $unpacker = EBook::Tools::Unpack->new('file' => 'mybook.prc');
40 $unpacker->unpack;
41  
42 =cut
43  
44 require Exporter;
45 2 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 our @EXPORT_OK;
48 @EXPORT_OK = qw (
49 );
50  
51 2 ▶use Archive::Zip qw(:ERROR_CODES);
Subroutine BEGIN: called CC=1 SCAR=0.0
52 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 0 ▶use EBook::Tools qw(:all);
Subroutine BEGIN: called CC=1 SCAR=2.6
54 use EBook::Tools::EReader qw(:all);
55 use EBook::Tools::IMP qw(:all);
56 use EBook::Tools::Mobipocket qw(:all);
57 use EBook::Tools::MSReader qw(:all);
58 use EBook::Tools::PalmDoc qw(uncompress_palmdoc);
59 use Encode;
60 use Fcntl qw(SEEK_CUR SEEK_SET);
61 use File::Basename qw(dirname fileparse);
62 use File::Path; # Exports 'mkpath' and 'rmtree'
63 use File::Which; # Exports 'which'
64 binmode(STDERR,':encoding(UTF-8)');
65  
66 my $drmsupport = 0;
67 eval
68 {
69 require EBook::Tools::DRM;
70 EBook::Tools::DRM->import();
71 }; # Trailing semicolon is required here
72 unless($@){ $drmsupport = 1; }
73  
74  
75 our %palmdbcodes = (
76 '.pdfADBE' => 'adobereader',
77 'TEXtREAd' => 'palmdoc',
78 'BVokBDIC' => 'bdicty',
79 'DB99DBOS' => 'db',
80 'PNPdPPrs' => 'ereader',
81 'PNRdPPrs' => 'ereader',
82 'vIMGView' => 'fireviewer',
83 'PmDBPmDB' => 'handbase',
84 'InfoINDB' => 'infoview',
85 'ToGoToGo' => 'isilo1',
86 'SDocSilX' => 'isilo3',
87 'JbDbJBas' => 'jfile',
88 'JfDbJFil' => 'jfilepro',
89 'DATALSdb' => 'list',
90 'Mdb1Mdb1' => 'mobiledb',
91 'BOOKMOBI' => 'mobipocket',
92 'DataPlkr' => 'plucker',
93 'DataSprd' => 'quicksheet',
94 'SM01SMem' => 'supermemo',
95 'TEXtTlDc' => 'tealdoc',
96 'InfoTlIf' => 'tealinfo',
97 'DataTlMl' => 'tealmeal',
98 'DataTlPt' => 'tealpaint',
99 'dataTDBP' => 'thinkdb',
100 'TdatTide' => 'tides',
101 'ToRaTRPW' => 'tomeraider',
102 'BDOCWrdS' => 'wordsmith',
103 'zTXTGPlm' => 'ztxt',
104 );
105  
106 our %pdbcompression = (
107 1 => 'no compression',
108 2 => 'PalmDoc compression',
109 17480 => 'Mobipocket DRM',
110 );
111  
112  
113 #################################
114 ########## CONSTRUCTOR ##########
115 #################################
116  
117 =head1 CONSTRUCTOR
118  
119 =head2 C<new(%args)>
120  
121 Instantiates a new Ebook::Tools::Unpack object.
122  
123 =head3 Arguments
124  
125 =over
126  
127 =item * C<file>
128  
129 The file to unpack. Specifying this is mandatory.
130  
131 =item * C<dir>
132  
133 The directory to unpack into. If not specified, defaults to the
134 basename of the file.
135  
136 =item * C<encoding>
137  
138 If specified, overrides the encoding to use when unpacking. This is
139 normally detected from the file and does not need to be specified.
140  
141 Valid values are '1252' (specifying Windows-1252) and '65001'
142 (specifying UTF-8).
143  
144 =item * C<htmlconvert>
145  
146 If set to true, an attempt will be made to convert non-HTML output
147 text to HTML where possible.
148  
149 =item * C<key>
150  
151 The decryption key to use if necessary (not yet implemented)
152  
153 =item * C<keyfile>
154  
155 The file holding the decryption keys to use if necessary (not yet
156 implemented)
157  
158 =item * C<language>
159  
160 If specified, overrides the detected language information.
161  
162 =item * C<opffile>
163  
164 The name of the file in which the metadata will be stored. If not
165 specified, defaults to C<content.opf>.
166  
167 =item * C<raw>
168  
169 If set true, this forces no corrections to be done on any extracted
170 text and a lot of raw, unparsed, unmodified data to be dumped into the
171 directory along with everything else. It's useful for debugging
172 exactly what was in the file being unpacked, and (when combined with
173 C<nosave>) reducing the time needed to extract parsed data from an
174 ebook container without actually unpacking it.
175  
176 =item * C<author>
177  
178 Overrides the detected author name.
179  
180 =item * C<title>
181  
182 Overrides the detected title.
183  
184 =item * C<tidy>
185  
186 If set to true, the unpacker will run tidy on any HTML output files to
187 convert them to valid XHTML. Be warned that this can occasionally
188 change the formatting, as Tidy isn't very forgiving on certain common
189 tricks (such as empty <pre> elements with style elements) that abuse
190 the standard.
191  
192 =item * C<nosave>
193  
194 If set to true, the unpacker will run through all of the unpacking
195 steps except those that actually write to the disk. This is useful
196 for testing, but also (particularly when combined with C<raw>) can be
197 used for extracting parsed data from an ebook container without
198 actually unpacking it.
199  
200 =back
201  
202 =cut
203  
204 my @fields = (
205 'file',
206 'dir',
207 'encoding',
208 'format',
209 'formatinfo',
210 'htmlconvert',
211 'raw',
212 'key',
213 'keyfile',
214 'opffile',
215 'author',
216 'language',
217 'title',
218 'datahashes',
219 'detected',
220 'tidy',
221 'nosave',
222 );
223  
224 require fields;
225 fields->import(@fields);
226  
227 sub new ## no critic (Always unpack @_ first)
228 {
229 my $self = shift;
230 my (%args) = @_;
231 my $class = ref($self) || $self;
232 my $subname = (caller(0))[3];
233 debug(2,"DEBUG[",$subname,"]");
234  
235 my %valid_args = (
236 'file' => 1,
237 'dir' => 1,
238 'encoding' => 1,
239 'key' => 1,
240 'keyfile' => 1,
241 'format' => 1,
242 'htmlconvert' => 1,
243 'raw' => 1,
244 'author' => 1,
245 'language' => 1,
246 'title' => 1,
247 'opffile' => 1,
248 'tidy' => 1,
249 'nosave' => 1,
250 );
251 foreach my $arg (keys %args)
252 {
253 croak($subname,"(): invalid argument '",$arg,"'")
254 if(!$valid_args{$arg});
255 }
256 croak($subname,"(): no input file specified")
257 unless($args{file});
258 croak($subname,"(): '",$args{file},"' not found")
259 unless(-f $args{file});
260  
261 $self = fields::new($class);
262 $self->{file} = $args{file};
263 $self->{dir} = $args{dir} || $self->filebase;
264 $self->{encoding} = $args{encoding};
265 $self->{format} = $args{format} if($args{format});
266 $self->{key} = $args{key} if($args{key});
267 $self->{keyfile} = $args{keyfile} if($args{keyfile});
268 $self->{opffile} = $args{opffile} || "content.opf";
269 $self->{author} = $args{author} if($args{author});
270 $self->{title} = $args{title} if($args{title});
271 $self->{datahashes} = {};
272 $self->{detected} = {};
273 $self->{htmlconvert} = $args{htmlconvert};
274 $self->{raw} = $args{raw};
275 $self->{tidy} = $args{tidy};
276 $self->{nosave} = $args{nosave};
277  
278 $self->detect_format unless($self->{format});
279 return $self;
280 }
281  
282  
283 =head1 ACCESSOR METHODS
284  
285 See L</new()> for more details on what some of these mean. Note
286 that some values cannot be autodetected until an unpack method
287 executes.
288  
289 =head2 C<author>
290  
291 =head2 C<dir>
292  
293 =head2 C<file>
294  
295 =head2 C<filebase>
296  
297 In scalar context, this is the basename of C<file>. In list context,
298 it actually returns the basename, directory, and extension as per
299 C<fileparse> from L<File::Basename>.
300  
301 =head2 C<format>
302  
303 =head2 C<key>
304  
305 =head2 C<keyfile>
306  
307 =head2 C<language>
308  
309 This returns the language specified by the user, if any. It remains
310 undefined if the user has not requested that a language code be set
311 even if a language was autodetected.
312  
313 =head2 C<opffile>
314  
315 =head2 C<raw>
316  
317 =head2 C<title>
318  
319 This returns the title specified by the user, if any. It remains
320 undefined if the user has not requested a title be set even if a title
321 was autodetected.
322  
323 =head2 C<detected>
324  
325 This returns a hash containing the autodetected metadata, if any.
326  
327 =cut
328  
329 sub author :method
330 {
331 my $self = shift;
332 return $$self{author};
333 }
334  
335 sub dir :method
336 {
337 my $self = shift;
338 return $$self{dir};
339 }
340  
341 sub file :method
342 {
343 my $self = shift;
344 return $$self{file};
345 }
346  
347 sub filebase :method
348 {
349 my $self = shift;
350 return fileparse($$self{file},'\.\w+$');
351 }
352  
353 sub format :method
354 {
355 my $self = shift;
356 return $$self{format};
357 }
358  
359 sub key :method
360 {
361 my $self = shift;
362 return $$self{key};
363 }
364  
365 sub keyfile :method
366 {
367 my $self = shift;
368 return $$self{keyfile};
369 }
370  
371 sub language :method
372 {
373 my $self = shift;
374 return $$self{language};
375 }
376  
377 sub opffile :method
378 {
379 my $self = shift;
380 return $$self{opffile};
381 }
382  
383 sub raw :method
384 {
385 my $self = shift;
386 return $$self{raw};
387 }
388  
389 sub title :method
390 {
391 my $self = shift;
392 return $$self{title};
393 }
394  
395 sub detected :method
396 {
397 my $self = shift;
398 return $$self{detected};
399 }
400  
401  
402 =head1 MODIFIER METHODS
403  
404 =head2 C<detect_format()>
405  
406 Attempts to automatically detect the format of the input file and set
407 the internal object attributes C<< $self->{format} >> and
408 C<< $self->{formatinfo} >>, where the former is a one-word string used by
409 the dispatcher to select the correct unpacking method and the latter
410 may contain additional detected information (such as a title or
411 version).
412  
413 Croaks if detection fails.
414  
415 In scalar context, returns C<< $self->{format} >>. In list context,
416 returns the two element list C<< ($self->{format},$self->{formatinfo}) >>
417  
418 This is automatically called by L</new()> if the C<format> argument is
419 not specified.
420  
421 =cut
422  
423 sub detect_format :method
424 {
425 my $self = shift;
426 my $subname = ( caller(0) )[3];
427 my $filename = $$self{file};
428 my $fh;
429 my $headerdata;
430 my $ident;
431 my $info;
432 my $index;
433 debug(2,"DEBUG[",$subname,"]");
434  
435 open($fh,"<",$filename)
436 or croak($subname,"(): failed to open '",$filename,"' for reading!\n");
437 sysread($fh,$headerdata,68);
438 close($fh)
439 or croak($subname,"(): failed to close '",$filename,"'!\n");
440  
441 # Check for PalmDB identifiers
442 $ident = substr($headerdata,60,8);
443 debug(3,"DEBUG: PalmDB ident = '$ident'");
444 if($palmdbcodes{$ident})
445 {
446 $$self{format} = $palmdbcodes{$ident};
447 $info = substr($headerdata,0,32);
448 $index = index($info,"\0");
449 if($index < 0)
450 {
451 debug(0,"WARNING: detected header in '",$filename,
452 "' is not null-terminated.");
453 }
454 else
455 {
456 $info = substr($info,0,$index);
457 }
458 debug(1,"DEBUG: Autodetected book format '",$$self{format},
459 "', info '",$info,"'");
460 $$self{formatinfo} = $info;
461 # The info here is always the title, but there may be better
462 # ways of extracting it later.
463 $$self{detected}{title} = $info;
464 }
465  
466 # Check for Microsoft Reader
467 $ident = substr($headerdata,0,8);
468 debug(3,"DEBUG: MS Reader ident = '$ident'");
469 if($ident eq 'ITOLITLS')
470 {
471 $$self{format} = 'msreader';
472 $$self{formatinfo} = unpack("c",substr($headerdata,8,1));
473 debug(1,"DEBUG: Autodetected book format '",$$self{format},
474 "', version ",$$self{formatinfo});
475 }
476  
477 # Check for ePub
478 $ident = substr($headerdata,30,28);
479 $info = substr($headerdata,0,2);
480 if($ident eq 'mimetypeapplication/epub+zip'
481 && $info eq 'PK')
482 {
483 $$self{format} = 'epub';
484 $$self{formatinfo} = '';
485 debug(1,"DEBUG: autodetected book format '",$$self{format},"'");
486 }
487  
488 # Check for .IMP
489 $ident = substr($headerdata,2,8);
490 $info = unpack('n',substr($headerdata,0,2));
491 if($ident eq 'BOOKDOUG')
492 {
493 $$self{format} = 'imp';
494 $$self{formatinfo} = $info;
495 debug(1,"DEBUG: autodetected book format '",$$self{format},
496 "' version ",$$self{formatinfo});
497 }
498  
499 # Check for miscellaneous zip archive (OEBZip?)
500 $ident = substr($headerdata,0,4);
501 if($ident eq "PK\x{03}\x{04}")
502 {
503 $$self{format} = 'ziparchive';
504 $$self{formatinfo} = unpack('c',substr($headerdata,4,1)) / 10;
505 debug(1,"DEBUG: autodetected book format '",$$self{format},
506 "', version ",$$self{formatinfo});
507 }
508  
509 croak($subname,"(): unable to determine book format")
510 unless($$self{format});
511  
512 if(wantarray) { return ($$self{format},$$self{formatinfo}); }
513 else { return $$self{format}; }
514 }
515  
516  
517 =head2 C<detect_from_mobi_exth()>
518  
519 Detects metadata values from the MOBI EXTH headers retrieved via
520 L</unpack_mobi_exth()> and places them into the C<detected> attribute.
521  
522 =cut
523  
524 sub detect_from_mobi_exth :method
525 {
526 my $self = shift;
527 my $subname = ( caller(0) )[3];
528 debug(2,"DEBUG[",$subname,"]");
529  
530 my @mobiexth;
531 if(defined $self->{datahashes}{mobiexth})
532 {
533 @mobiexth = @{$self->{datahashes}{mobiexth}};
534 }
535 my $data;
536 my %exthtypes = %EBook::Tools::Mobipocket::exthtypes;
537 my %exth_is_int = %EBook::Tools::Mobipocket::exth_is_int;
538 my %exth_repeats = %EBook::Tools::Mobipocket::exth_repeats;
539  
540 # EXTH records
541 foreach my $exth (@mobiexth)
542 {
543 my $type = $exthtypes{$$exth{type}};
544 unless($type)
545 {
546 carp($subname,"(): unknown EXTH record type ",$$exth{type});
547 next;
548 }
549 if($exth_is_int{$$exth{type}})
550 {
551 $data = '0x' . hexstring($$exth{data});
552 }
553 else
554 {
555 $data = $$exth{data};
556 }
557  
558 if($exth_repeats{$$exth{type}})
559 {
560 debug(2,"DEBUG: Repeating EXTH ",$type," = '",$data,"'");
561 my @extharray = ();
562 my $oldexth = $$self{detected}{$type};
563 if(ref $oldexth eq 'ARRAY') { @extharray = @$oldexth; }
564 elsif($oldexth) { push(@extharray,$oldexth); }
565 push(@extharray,$data);
566 $$self{detected}{$type} = \@extharray;
567 }
568 else
569 {
570 debug(2,"DEBUG: Single EXTH ",$type," = '",$data,"'");
571 $$self{detected}{$type} = $data;
572 }
573 }
574  
575 return 1;
576 }
577  
578  
579 =head2 C<gen_opf(%args)>
580  
581 This generates an OPF file from detected and specified metadata. It
582 does not honor the C<nosave> flag, and will always write its output.
583  
584 Normally this is called automatically from inside the C<unpack>
585 methods, but can be called manually after an unpack if the C<nosave>
586 flag was set to write an OPF anyway.
587  
588 Returns the filename of the OPF file.
589  
590 =head3 Arguments
591  
592 =over
593  
594 =item * C<opffile> (optional)
595  
596 If specified, this overrides the object attribute C<opffile>, and
597 determines the filename to use for the generated OPF file. If not
598 specified, and the object attribute C<opffile> has somehow been
599 cleared (the attribute is set during L</new()>), it will be generated
600 by looking at the C<textfile> argument. If no value can be found, the
601 method croaks. If a value was found somewhere other than the object
602 attribute C<opffile>, then the object attribute is updated to match.
603  
604 =item * C<textfile> (optional)
605  
606 The file containing the main text of the document. If specified, the
607 method will attempt to split metadata out of the file and add whatever
608 remains to the manifest of the OPF.
609  
610 =item * C<mediatype> (optional)
611  
612 The media type (mime type) of the document specified via C<textfile>.
613 If C<textfile> is not specified, this argument is ignored. If C<textfile> is specified, but
614  
615 =back
616  
617 =cut
618  
619 sub gen_opf :method ## no critic (Always unpack @_ first)
620 {
621 my $self = shift;
622 my (%args) = @_;
623 my $subname = ( caller(0) )[3];
624 debug(2,"DEBUG[",$subname,"]");
625 my %valid_args = (
626 'opffile' => 1,
627 'textfile' => 1,
628 'mediatype' => 1,
629 );
630 foreach my $arg (keys %args)
631 {
632 croak($subname,"(): invalid argument '",$arg,"'")
633 if(!$valid_args{$arg});
634 }
635 my $ebook = EBook::Tools->new();
636 my $textfile = $args{textfile};
637 my $opffile = $args{opffile} || $$self{opffile};
638 my $mediatype = $args{mediatype};
639 unless($self->{raw})
640 {
641 $opffile = split_metadata($textfile,$opffile) if($textfile);
642 }
643 my $detected;
644 my $code;
645 my $index;
646  
647 croak($subname,"(): could not determine OPF filename\n")
648 unless($opffile);
649 $$self{opffile} ||= $opffile;
650  
651 if(-f $opffile)
652 {
653 $ebook->init($opffile);
654 }
655 else
656 {
657 $ebook->init_blank(opffile => $opffile,
658 title => $$self{title},
659 author => $$self{author});
660 }
661 $ebook->fix_metastructure_oeb12();
662 $ebook->add_document($textfile,'text-main',$mediatype) if($textfile);
663  
664 # Set author, title, and opffile from manual overrides
665 $ebook->set_primary_author(text => $$self{author}) if($$self{author});
666 $ebook->set_title(text => $$self{title}) if($$self{title});
667 $ebook->set_opffile($$self{opffile}) if($$self{opffile});
668  
669 # If we still don't have author or title, set it from the best
670 # extraction we have
671 $ebook->set_primary_author(text => $$self{detected}{author})
672 if(!$$self{author} && $$self{detected}{author});
673 $ebook->set_title(text => $$self{detected}{title})
674 if(!$$self{title} && $$self{detected}{title});
675  
676 # Set the language codes
677 $ebook->set_language(text => $$self{detected}{language})
678 if($$self{detected}{language});
679 $ebook->set_metadata(gi => 'DictionaryInLanguage',
680 text => $$self{detected}{dictionaryinlanguage})
681 if($$self{detected}{dictionaryinlanguage});
682 $ebook->set_metadata(gi => 'DictionaryOutLanguage',
683 text => $$self{detected}{dictionaryoutlanguage})
684 if($$self{detected}{dictionaryoutlanguage});
685  
686  
687 # Set the remaining autodetected metadata, some of which may or
688 # may not be in array form
689 $detected = $$self{detected}{contributor};
690 if( $detected && (ref($detected) eq 'ARRAY') )
691 {
692 foreach my $text (@$detected)
693 {
694 $ebook->add_metadata(gi => 'dc:Contributor',
695 parent => 'dc-metadata',
696 text => $text);
697 }
698 }
699 elsif($detected)
700 {
701 $ebook->add_metadata(gi => 'dc:Contributor',
702 parent => 'dc-metadata',
703 text => $detected);
704 }
705  
706 $detected = $$self{detected}{publisher};
707 if( $detected && (ref($detected) eq 'ARRAY') )
708 {
709 foreach my $text (@$detected)
710 {
711 $ebook->add_metadata(gi => 'dc:Publisher',
712 parent => 'dc-metadata',
713 text => $text);
714 }
715 }
716 elsif($detected)
717 {
718 $ebook->set_publisher(text => $detected);
719 }
720  
721 $ebook->set_description(text => decode_utf8($$self{detected}{description}))
722 if($$self{detected}{description});
723  
724 $detected = $$self{detected}{isbn};
725 if( $detected && (ref($detected) eq 'ARRAY') )
726 {
727 foreach my $text (@$detected)
728 {
729 $ebook->add_identifier(text => $text,
730 scheme => 'ISBN')
731 }
732 }
733 elsif($detected)
734 {
735 $ebook->add_identifier(text => $detected,
736 scheme => 'ISBN')
737 }
738  
739 $detected = $$self{detected}{subject};
740 if( $detected && (ref($detected) eq 'ARRAY') )
741 {
742 debug(2,"Multiple dc:Subject entries");
743 $index = 0;
744 foreach my $text (@$detected)
745 {
746 $code = @{$$self{detected}{subjectcode}}[$index];
747 $ebook->add_subject(text => $text,
748 basiccode => $code);
749 $index++;
750 }
751 }
752 elsif($detected)
753 {
754 debug(2,"Single dc:Subject entry");
755 $code = $$self{detected}{subjectcode};
756 $ebook->add_subject(text => $$self{detected}{subject},
757 basiccode => $code)
758 }
759  
760 $ebook->set_date(text => $$self{detected}{publicationdate},
761 event => 'publication')
762 if($$self{detected}{publicationdate});
763 $ebook->set_rights(text => $$self{detected}{rights})
764 if($$self{detected}{rights});
765 $ebook->set_type(text => $$self{detected}{type})
766 if($$self{detected}{type});
767 $ebook->set_adult($$self{detected}{adult})
768 if($$self{detected}{adult});
769 $ebook->set_review(text => decode_utf8($$self{detected}{review}))
770 if($$self{detected}{review});
771 $ebook->set_retailprice(text => $$self{detected}{retailprice},
772 currency => $$self{detected}{currency})
773 if($$self{detected}{retailprice});
774  
775 # Automatically clean up any mess
776 $ebook->fix_misc;
777 $ebook->fix_oeb12;
778 $ebook->fix_mobi;
779 unlink($opffile);
780 $ebook->save;
781 return 1;
782 }
783  
784  
785 =head2 C<unpack()>
786  
787 This is a dispatcher for the specific unpacking methods needed to
788 unpack a particular format. Unless you feel a need to override the
789 unpacking method specified or detected during object construction, it
790 is probalby better to call this than the specific unpacking methods.
791  
792 =cut
793  
794 sub unpack :method
795 {
796 my $self = shift;
797 my $subname = ( caller(0) )[3];
798 debug(2,"DEBUG[",$subname,"]");
799  
800 my $filename = $$self{file};
801 croak($subname,"(): no input file specified\n")
802 unless($filename);
803 my $retval;
804  
805 my %unpack_dispatch = (
806 'ereader' => \&unpack_ereader,
807 'imp' => \&unpack_imp,
808 'mobipocket' => \&unpack_mobi,
809 'msreader' => \&unpack_msreader,
810 'palmdoc' => \&unpack_palmdoc,
811 'aportisdoc' => \&unpack_palmdoc,
812 'ziparchive' => \&unpack_zip,
813 );
814  
815 croak($subname,
816 "(): don't know how to handle format '",$$self{format},"'\n")
817 if(!$unpack_dispatch{$$self{format}});
818 $retval = $unpack_dispatch{$$self{format}}->($self);
819 return $retval;
820 }
821  
822  
823 =head2 C<unpack_ereader()>
824  
825 Unpacks Fictionwise/PeanutPress eReader (-er.pdb) files.
826  
827 =cut
828  
829 sub unpack_ereader :method
830 {
831 my $self = shift;
832 my $subname = ( caller(0) )[3];
833 debug(2,"DEBUG[",$subname,"]");
834  
835 my $pdb = EBook::Tools::EReader->new();
836 my $textname;
837  
838 $pdb->Load($$self{file});
839  
840 $$self{datahashes}{ereader} = $pdb->{header};
841 $$self{detected}{title} = decode('Windows-1252',$pdb->{title});
842 $$self{detected}{author} = decode('Windows-1252',$pdb->{author});
843 $$self{detected}{rights} = decode('Windows-1252',$pdb->{rights});
844 $$self{detected}{publisher} = decode('Windows-1252',$pdb->{publisher});
845 $$self{detected}{isbn} = decode('Windows-1252',$pdb->{isbn});
846 debug(1,"DEBUG: PDB title: '",$$self{detected}{title},"'");
847 debug(1,"DEBUG: PDB author: '",$$self{detected}{author},"'");
848 debug(1,"DEBUG: PDB copyright: '",$$self{detected}{rights},"'");
849 debug(1,"DEBUG: PDB publisher: '",$$self{detected}{publisher},"'");
850 debug(1,"DEBUG: PDB ISBN: '",$$self{detected}{isbn},"'");
851  
852 unless($$self{nosave})
853 {
854 my $cwd = usedir($self->{dir});
855 $pdb->write_images;
856 $pdb->write_unknown_records if($$self{raw});
857 if($$self{htmlconvert})
858 {
859 $textname = $pdb->write_html();
860 $self->gen_opf(textfile => $textname,
861 mediatype => 'application/xhtml+xml');
862 }
863 else
864 {
865 $textname = $pdb->write_pml();
866 $self->gen_opf(textfile => $textname,
867 mediatype => 'text/plain');
868 }
869 chdir($cwd);
870 }
871 return 1;
872 }
873  
874  
875 =head2 C<unpack_imp()>
876  
877 Unpacks SoftBook/GEB/REB/eBookWise (.imp) files.
878  
879 =cut
880  
881 sub unpack_imp
882 {
883 my $self = shift;
884 my $subname = ( caller(0) )[3];
885 debug(2,"DEBUG[",$subname,"]");
886  
887 my $imp = EBook::Tools::IMP->new();
888 $imp->load($self->{file});
889  
890 $self->{detected}->{author} = $imp->author;
891 $self->{detected}->{title} = $imp->title;
892  
893 if($self->{raw})
894 {
895 $imp->write_resdir();
896 }
897  
898 $imp->write_text(dir => $self->{dir});
899 $imp->write_images(dir => $self->{dir});
900  
901 print {*STDERR} "WARNING: IMP support not yet functional!\n";
902 return 0;
903 }
904  
905  
906 =head2 C<unpack_mobi()>
907  
908 Unpacks Mobipocket (.prc / .mobi) files.
909  
910 =cut
911  
912 sub unpack_mobi :method
913 {
914 my $self = shift;
915 my $subname = ( caller(0) )[3];
916 debug(2,"DEBUG[",$subname,"]");
917  
918 my $mobi = EBook::Tools::Mobipocket->new();
919 my @records;
920 my $data;
921 my $opffile;
922  
923 # Used for extracting images
924 my $imageid = 0;
925 my $firstimagerec = 0;
926  
927 # Used for file output
928 my $htmlname;
929  
930 my $reccount = 0; # The Record ID cannot be reliably used to identify
931 # the first record. This increments as each
932 # record is examined
933  
934 $mobi->Load($$self{file});
935  
936 @records = @{$mobi->{records}};
937 croak($subname,"(): no pdb records found!") unless(@records);
938  
939 $$self{datahashes}{palm} = $mobi->{header}{palm};
940 $$self{datahashes}{mobi} = $mobi->{header}{mobi};
941 $$self{datahashes}{mobiexth} = $mobi->{header}{exth};
942 $$self{encoding}
943 = $$self{datahashes}{mobi}{encoding} unless($$self{encoding});
944 $$self{detected}{title} = $mobi->{title};
945 $$self{detected}{language} = $mobi->{header}{mobi}{language};
946 $$self{detected}{dictionaryinlanguage}
947 = $mobi->{header}{mobi}{dilanguage};
948 $$self{detected}{dictionaryoutlanguage}
949 = $mobi->{header}{mobi}{dolanguage};
950  
951 $self->detect_from_mobi_exth();
952 if($self->{detected}->{title}) {
953 $htmlname = clean_filename($self->{detected}->{title} . ".html");
954 }
955 else {
956 $htmlname = clean_filename($self->filebase . ".html");
957 }
958  
959 if($$self{raw} && !$$self{nosave})
960 {
961 $mobi->write_unknown_records();
962 }
963  
964 croak($subname,"(): found no text in '",$$self{file},"'!")
965 unless($mobi->{text});
966  
967 $mobi->fix_html(filename => $htmlname) unless($$self{raw});
968  
969 unless($$self{nosave})
970 {
971 my $cwd = usedir($self->{dir});
972 $mobi->write_text($htmlname);
973 $mobi->write_images();
974 $self->gen_opf(textfile => $htmlname);
975  
976 if($$self{tidy})
977 {
978 debug(1,"Tidying '",$htmlname,"'");
979 system_tidy_xhtml($htmlname);
980 }
981 chdir($cwd);
982 }
983 return 1;
984 }
985  
986  
987 =head2 C<unpack_msreader()>
988  
989 Unpacks Microsoft Reader (.lit) files
990  
991 =cut
992  
993 sub unpack_msreader :method
994 {
995 my $self = shift;
996 my $subname = ( caller(0) )[3];
997 debug(2,"DEBUG[",$subname,"]");
998  
999 my $convertlit = find_convertlit();
1000 my $keys = find_convertlit_keys($$self{file});
1001  
1002 my $retval = system_convertlit(infile => $$self{file},
1003 keyfile => $keys,
1004 dir => $$self{dir});
1005 return $retval;
1006 }
1007  
1008  
1009 =head2 C<unpack_palmdoc()>
1010  
1011 Unpacks PalmDoc / AportisDoc (.pdb) files
1012  
1013 =cut
1014  
1015 sub unpack_palmdoc :method
1016 {
1017 my $self = shift;
1018 my $subname = ( caller(0) )[3];
1019 debug(2,"DEBUG[",$subname,"]");
1020  
1021 my $filename = $$self{file};
1022  
1023 my $ebook = EBook::Tools->new();
1024 my $pdb = EBook::Tools::PalmDoc->new();
1025 my ($outfile,$bookmarkfile,$fh);
1026 my %bookmarks;
1027 $bookmarkfile = $self->filebase . "-bookmarks.txt";
1028  
1029 $pdb->Load($filename);
1030 debug(2,"DEBUG: PalmDoc Name: ",$pdb->{'name'});
1031 debug(2,"DEBUG: PalmDoc Version: ",$pdb->{'version'});
1032 debug(2,"DEBUG: PalmDoc Type: ",$pdb->{'type'});
1033 debug(2,"DEBUG: PalmDoc Creator: ",$pdb->{'creator'});
1034  
1035 $$self{title} ||= $pdb->{'name'};
1036 $$self{author} ||= 'Unknown Author';
1037 $$self{opffile} ||= $$self{title} . ".opf";
1038  
1039 unless($$self{nosave})
1040 {
1041 usedir($self->{dir});
1042 if($$self{htmlconvert})
1043 {
1044 $outfile = $self->filebase . ".html";
1045 open($fh,'>:encoding(UTF-8)',$outfile)
1046 or croak($subname,"(): unable to open '",$outfile,
1047 "' for writing!\n");
1048 print {*$fh} $pdb->html;
1049 close($fh)
1050 or croak("Failed to close '",$outfile,"'!");
1051 }
1052 else
1053 {
1054 $outfile = $self->filebase . ".txt";
1055 open($fh,">:raw",$outfile)
1056 or croak("Failed to open '",$outfile,"' for writing!");
1057 print {*$fh} $pdb->text;
1058 close($fh)
1059 or croak("Failed to close '",$outfile,"'!");
1060 }
1061  
1062 open($fh,">:raw",$bookmarkfile)
1063 or croak("Failed to open '",$bookmarkfile,"' for writing!");
1064 %bookmarks = $pdb->bookmarks;
1065 if(%bookmarks)
1066 {
1067 foreach my $offset (sort {$a <=> $b} keys %bookmarks)
1068 {
1069 print {*$fh} $offset,"\t",$bookmarks{$offset},"\n";
1070 }
1071 close($fh)
1072 or croak("Failed to close '",$bookmarkfile,"'!");
1073 }
1074  
1075 $ebook->init_blank(opffile => $$self{opffile},
1076 title => $$self{title},
1077 author => $$self{author});
1078 $ebook->add_document($outfile,'text-main');
1079 $ebook->save;
1080 }
1081 return $$self{opffile};
1082 }
1083  
1084  
1085 =head2 C<unpack_zip()>
1086  
1087 Unpacks Zip archives (including ePub files).
1088  
1089 =cut
1090  
1091 sub unpack_zip :method
1092 {
1093 my $self = shift;
1094 my $subname = ( caller(0) )[3];
1095 debug(2,"DEBUG[",$subname,"]");
1096  
1097 unless($self->{nosave})
1098 {
1099 my $cwd = usedir($self->{dir});
1100  
1101 if (which('unzip')) {
1102 my @syscmd = ( 'unzip', '-q', $cwd . '/' . $self->{file} );
1103 system(@syscmd);
1104 system_result($subname,$CHILD_ERROR,@syscmd);
1105 }
1106 else {
1107 my $zip = Archive::Zip->new();
1108 my $status = $zip->read($cwd.'/'.$self->{file});
1109 if ($status != AZ_OK) {
1110 croak($subname,'(): error while parsing zip file "',$self->{file},'" (',$status,')!');
1111 }
1112  
1113 $status = $zip->extractTree(undef);
1114 if ($status != AZ_OK) {
1115 croak($subname,'(): error while extracting zip file "',$self->{file},'" (',$status,')!');
1116 }
1117 }
1118 chdir($cwd);
1119 }
1120 return 1;
1121 }
1122  
1123  
1124 ########## PROCEDURES ##########
1125  
1126 # No procedures
1127  
1128  
1129 ########## END CODE ##########
1130  
1131 =head1 BUGS AND LIMITATIONS
1132  
1133 =over
1134  
1135 =item * DRM isn't handled. Infrastructure to support this via an
1136 external plug-in module may eventually be built, but it will never
1137 become part of the main module for legal reasons.
1138  
1139 =item * Unit tests are incomplete
1140  
1141 =item * Documentation is incomplete. Accessors in particular could
1142 use some cleaning up.
1143  
1144 =item * Need to implement setter methods for object attributes
1145  
1146 =item * Import/extraction/unpacking is currently limited to PalmDoc,
1147 Mobipocket, and eReader. Extraction from Microsoft Reader (.lit) and
1148 ePub is also eventually planned. Other formats may follow from there.
1149  
1150 =back
1151  
1152 =head1 AUTHOR
1153  
1154 Zed Pobre <zed@debian.org>
1155  
1156 =head1 LICENSE AND COPYRIGHT
1157  
1158 Copyright 2008 Zed Pobre
1159  
1160 Licensed to the public under the terms of the GNU GPL, version 2
1161  
1162 =cut
1163  
1164 1;
1165 __END__
« Tools/LZSS.pm ↑ Summary Tools.pm »