blib/script/cutfb3.pl untested

filter: Statementstmt 0.0% 0 / 257 Branchbran 0.0% 0 / 124 Conditioncond 0.0% 0 / 109 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 525 CC 48 SCAR 54.0
CC
48
Cov
0%
ProceedNodeTrial
600.0
CollectElementStat
72.0
CleanLinks
72.0
CRAP 222.3
1 #!/usr/local/bin/perl
2 use strict;
3  
4 use XML::LibXML;
5 use OPC::Node;
6 use FB3;
7 use FB3::Validator;
8 use File::Copy;
9 use File::Temp;
10 use File::Basename qw(basename);
11 use Cwd qw(cwd abs_path);
12 use Getopt::Long;
13 use utf8;
14  
15 my ($Help, $Force, $In, $Out, $CutChars, $XsdPath, $ImagesPath, $ImageFileName, $WorkType);
16 my $r = GetOptions(
17 'help|h' => \$Help,
18 'force|f' => \$Force,
19 'in|i=s' => \$In,
20 'out|o=s' => \$Out,
21 'chars|c=i' => \$CutChars,
22 'xsd|x=s' => \$XsdPath, # optional
23 'imagespath|p=s' => \$ImagesPath,
24 'type|t=s' => \$WorkType,
25 );
26  
27 help() if $Help;
28  
29 unless ($In and $Out) {
30 print "\nrequired params 'in'/'out' not defined\n";
31 help();
32 }
33  
34 if ($ImagesPath) {
35 die "Path $ImagesPath not found\n" unless -d $ImagesPath;
36 $ImagesPath = $ImagesPath.'/' if $ImagesPath !~ /\/$/;
37 }
38  
39 if ( not $WorkType ) {
40  
41 $WorkType = 'trial';
42  
43 } elsif ( $WorkType !~ /^(trial|output)$/ ) {
44  
45 print "\nparams 'type' must be trial|output\n";
46 help();
47 }
48  
49 use constant {
50 NS_XLINK => 'http://www.w3.org/1999/xlink',
51 NS_FB3_DESCRIPTION => 'http://www.fictionbook.org/FictionBook3/description',
52 NS_FB3_BODY => 'http://www.fictionbook.org/FictionBook3/body',
53 DEFAULT_TRIAL_PERCENT => 24,
54 };
55  
56 my $Blocks = qr/^(p|subtitle|ol|ul|pre|table|poem|blockquote|div|subscription)$/;
57  
58 use constant {
59 RELATION_TYPE_FB3_BOOK =>
60 'http://www.fictionbook.org/FictionBook3/relationships/Book',
61 RELATION_TYPE_FB3_BODY =>
62 'http://www.fictionbook.org/FictionBook3/relationships/body',
63 RELATION_TYPE_OPC_THUMBNAIL =>
64 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail',
65 RELATION_TYPE_CORE_PROP =>
66 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
67 RELATION_TYPE_FB3_IMAGES =>
68 'http://www.fictionbook.org/FictionBook3/relationships/image',
69 };
70  
71 our $Validator = FB3::Validator->new( $XsdPath );
72  
73 my $Finish;
74 my $CharsProcessed = 0;
75 my %ImageHash;
76 my %HrefHash;
77 my %IdHash;
78 my %NoteHash;
79 my %NoteIdHash;
80  
81 my $TmpDir = File::Temp::tempdir( CLEANUP => 1 );
82 my $FB3TmpDir = $TmpDir.'/unzipped_'.File::Basename::basename($In);
83 my $UnzipMessage = `/usr/bin/unzip -o -d $FB3TmpDir $In 2>&1`;
84 die "Unzipping fb3 error: $UnzipMessage" if $?;
85  
86 my $FB3Package = FB3->new( from_dir => $FB3TmpDir );
87 my $FB3Body = $FB3Package->Body;
88 my $BodyXML = $FB3Body->Content;
89 my $Parser = XML::LibXML->new();
90 my $BodyDoc = $Parser->load_xml( string => $BodyXML, huge => 1 );
91 my $RootNode = $BodyDoc->getDocumentElement();
92 my $XPC = XML::LibXML::XPathContext->new($RootNode);
93 $XPC->registerNs('fb', &NS_FB3_BODY);
94 $XPC->registerNs('fbd', &NS_FB3_DESCRIPTION);
95  
96 my $CharsFull;
97  
98 if ($WorkType eq 'trial') {
99 $CharsFull = length($RootNode->textContent);
100 foreach my $TrialOnlyNode ($XPC->findnodes('/fb:fb3-body/fb:section[@output="trial-only"]',$RootNode)) {
101 $CharsFull -= (length($TrialOnlyNode->textContent) || 0);
102 }
103 $CutChars ||= DEFAULT_TRIAL_PERCENT * 0.01 * $CharsFull;
104 ProceedNodeTrial($RootNode);
105 } elsif ($WorkType eq 'output') {
106 ProceedNodeOut($RootNode);
107 }
108  
109 CollectElementStat($RootNode);
110 CleanLinks($FB3Body);
111 CleanImages($FB3Package);
112 CleanNotes($FB3Package);
113  
114 $BodyDoc->toFile($FB3Body->PhysicalName, 0);
115  
116 if ($WorkType eq 'trial') {
117  
118 my $CharsTrial = length($RootNode->textContent);
119 my $FB3Descr = $FB3Package->Meta;
120 my $DescrXML = $FB3Descr->Content;
121 my $DescrDoc = $Parser->load_xml( string => $DescrXML, huge => 1 );
122 my $DescrNode = $DescrDoc->getDocumentElement();
123  
124 if ( my $FragNode = $XPC->findnodes("/fbd:fb3-description/fbd:fb3-fragment", $DescrDoc)->[0] ) {
125 $FragNode->unbindNode();
126 }
127  
128 my $FB3FragmentNode = $DescrDoc->createElement('fb3-fragment');
129  
130 $FB3FragmentNode->setAttribute('full_length', $CharsFull);
131 $FB3FragmentNode->setAttribute('fragment_length', $CharsTrial);
132  
133 $DescrNode->appendChild($FB3FragmentNode);
134 $DescrDoc->toFile($FB3Descr->PhysicalName, 0);
135 }
136  
137 die "Empty body in result file" unless scalar @{$XPC->findnodes("/fb:fb3-body/fb:section", $RootNode)};
138  
139 ZipFolder("$FB3TmpDir/", $Out);
140 if ( my $ValidationError = $Validator->Validate($Out) ) {
141 unless ($Force) {
142 unlink $Out;
143 die "Validation error: $ValidationError";
144 }
145 }
146  
147 sub CollectElementStat {
148 my $Node = shift || return;
149 #быстрее, чем //xpath
150 for my $ChildNode ($Node->childNodes) {
151  
152 next if $ChildNode->nodeName eq '#text';
153  
154 CollectElementStat($ChildNode);
155  
156 $ImageHash{$ChildNode->getAttribute('src')} = 1 if $ChildNode->nodeName eq 'img';
157 $NoteHash{$ChildNode->getAttribute('href')} = 1 if $ChildNode->nodeName eq 'note';
158  
159 if (my $Id = $ChildNode->getAttribute('id')) {
160  
161 if ($ChildNode->nodeName eq 'notebody') {
162 $NoteIdHash{$Id} = 1;
163 } else {
164 $IdHash{$Id} = 1;
165 }
166 }
167  
168 if ($ChildNode->nodeName eq 'a') {
169 my $Href = $ChildNode->getAttribute('xlink:href');
170 $HrefHash{$Href} = 1 if ($Href and $Href =~ s/^#//);
171 }
172 }
173 }
174  
175 sub ProceedNodeOut {
176 my $Node = shift || return;
177  
178 #актуален только первый уровень section
179 for my $ChildNode ($Node->childNodes) {
180 next unless $ChildNode->nodeName eq 'section';
181 my $Output = $ChildNode->getAttribute('output');
182 $ChildNode->unbindNode() if ($Output and $Output eq 'trial-only');
183 }
184 }
185  
186 sub ProceedNodeTrial {
187 my $Node = shift || return;
188 my $ImmortalBranch = shift || 0; # не убивать потомков
189  
190 my $NodeName = $Node->nodeName;
191 if ($NodeName eq '#text') {
192 $CharsProcessed += length($Node->nodeValue);
193 $Node->unbindNode() if ($Finish && !$ImmortalBranch);
194 return;
195 }
196  
197 my $OuterImmortal;
198 if ($NodeName eq 'section') {
199  
200 if ( #обрабатываем логику атрибута 'output' #только внешние section
201 $Node->parentNode->nodeName eq 'fb3-body'
202 && defined $Node->getAttribute('output')
203 ) {
204 my $SectionOutput = $Node->getAttribute('output');
205 if ($SectionOutput eq 'payed') { #пропускаем ноду и забываем
206 $Node->unbindNode();
207 return $Node;
208 }
209 if ($SectionOutput eq 'trial' || $SectionOutput eq 'trial-only') { #всегда бессмертны
210 $OuterImmortal = 1;
211 $ImmortalBranch = 1;
212 }
213 }
214  
215 $Node->setAttribute('first-char-pos', $CharsProcessed+1);
216  
217 } elsif ($NodeName eq 'title' && ($Node->parentNode->nodeName eq 'section' || $Node->parentNode->nodeName eq 'notes')) { # заголовок секции, пригодится
218 $ImmortalBranch = 1;
219  
220 } elsif ( $NodeName eq 'img' && (!$Finish || $ImmortalBranch) ) {
221  
222 my $ImgSrc = $Node->getAttribute('src');
223 $ImageHash{$ImgSrc} = 1 if $ImgSrc;
224  
225 } elsif ( $NodeName eq 'note' && (!$Finish || $ImmortalBranch) ) {
226  
227 my $NoteHref = $Node->getAttribute('href');
228 $NoteHash{$NoteHref} = 1 if $NoteHref;
229  
230 } elsif ($NodeName eq 'notebody') {
231  
232 if (!$NoteHash{$Node->getAttribute('id')}) {
233 $Node->unbindNode();
234 } else {
235 $ImmortalBranch = 1;
236 }
237  
238 }
239  
240 for my $ChildNode ($Node->childNodes) {
241  
242 if ($ChildNode->nodeName =~ /$Blocks/) {
243 if ( ($CharsProcessed + length($ChildNode->textContent)) >= $CutChars ) {
244 $Finish = 1;
245 }
246 }
247  
248 ProceedNodeTrial($ChildNode, $ImmortalBranch);
249 }
250  
251 if ($NodeName eq 'section') {
252 my @SectionChildren = $Node->nonBlankChildNodes;
253 $Node->setAttribute('clipped', 'true') if $Finish && !$OuterImmortal;
254 if (scalar @SectionChildren == 0 || (scalar @SectionChildren == 1 && $SectionChildren[0]->nodeName eq 'title')
255 || (scalar @SectionChildren == 2 && $SectionChildren[0]->nodeName eq 'title' && ($SectionChildren[1]->nodeName eq 'epigraph' || $SectionChildren[1]->nodeName eq 'annotation'))
256 ) { # проверка, что в секции нет ничего кроме заголовка
257 $SectionChildren[1]->unbindNode() if ($SectionChildren[1] && ($SectionChildren[1]->nodeName eq 'epigraph' || $SectionChildren[1]->nodeName eq 'annotation'));
258 my $ClippedNode = XML::LibXML::Element->new('clipped');
259 $Node->appendChild($ClippedNode);
260 }
261 }
262  
263 if ($NodeName eq 'image') {
264 $ImageFileName = $Node->getAttribute('href');
265 $ImageFileName =~ s/^#//;
266 # Если нет, то игнорируем, потому что мы уже получили триал и теперь уже работаем с ним
267 if ( -f $ImagesPath.$ImageFileName ) {
268 my ($x, $y) = imgsize($ImagesPath.$ImageFileName);
269 $CharsProcessed += 200 if ($x && $y && $x >= 100 && $y >= 100);
270 }
271 }
272  
273 if ( $Finish && !$ImmortalBranch && (!$Node->firstChild || Trim(InNode($Node)) eq '') ) {
274 $Node->unbindNode(); # если нет потомков - рубим.
275 }
276  
277 return $Node;
278 }
279  
280 sub InNode {
281 my $Node = shift;
282 join "",map {$_->toString} $Node->childNodes;
283 }
284  
285 sub Trim {
286 my $Str = shift;
287 $Str =~ s/[\n\r]//g;
288 $Str =~ s/^\s+//g;
289 $Str =~ s/\s+$//g;
290 return $Str;
291 }
292  
293 sub NReplace {
294 my $Node = shift;
295 my $Parent = $Node->parentNode();
296 my $Clone = $BodyDoc->createElement($Parent->nodeName());
297 foreach ($Parent->getAttributes) {
298 $Clone->setAttribute($_->nodeName => $_->value);
299 }
300 foreach my $PNode ($Parent->childNodes()) {
301 if ($PNode == $Node) {
302 foreach ($PNode->childNodes) {
303 $Clone->appendChild($_);
304 }
305 next;
306 }
307 $Clone->appendChild($PNode);
308 }
309 $Parent->replaceNode($Clone);
310 }
311  
312 sub CleanLinks {
313 my $FB3Body = shift;
314  
315 #notebody
316 foreach my $Id (keys %NoteIdHash) {
317 next if exists $NoteHash{$Id};
318 my $Ids = $XPC->findnodes('/fb:fb3-body/fb:notes/fb:notebody[@id="'.$Id.'"]');
319 foreach my $NodeIds (@$Ids) {
320 $NodeIds->unbindNode();
321 }
322 }
323  
324 #остальные ноды
325 foreach my $Id (keys %IdHash) {
326 next if exists $HrefHash{$Id};
327 my $Ids = $XPC->findnodes('//*[@id="'.$Id.'"]');
328 foreach my $NodeIds (@$Ids) {
329 next if $NodeIds->nodeName() eq 'section';
330 next if $NodeIds->nodeName() eq 'notebody';
331 if ($NodeIds->nodeName eq 'span') {
332 NReplace($NodeIds);
333 } else {
334 $NodeIds->removeAttribute('id');
335 }
336 }
337 delete $IdHash{$Id};
338 }
339  
340 #ссылки
341 foreach my $Href (keys %HrefHash) {
342 next if exists $IdHash{$Href};
343 my $Hrefs = $XPC->findnodes('//fb:a[@xlink:href="#'.$Href.'"]');
344 foreach my $NodeHrefs (@$Hrefs) {
345 if ($NodeHrefs->getAttribute('id')) {
346 $NodeHrefs->removeAttribute('xlink:href');
347 next;
348 }
349 NReplace($NodeHrefs);
350 }
351 delete $HrefHash{$Href};
352 }
353  
354 }
355  
356 sub CleanNotes {
357 my $Node = $XPC->findnodes("/fb:fb3-body/fb:notes",$RootNode)->[0];
358 return unless $Node;
359 my @NotesChildren = $Node->nonBlankChildNodes;
360 if ( scalar @NotesChildren == 0
361 || (scalar @NotesChildren == 1 && $NotesChildren[0]->nodeName eq 'title')
362 || (scalar @NotesChildren == 2 && $NotesChildren[0]->nodeName eq 'title' && $NotesChildren[1]->nodeName eq 'epigraph')
363 ) {
364 $Node->unbindNode();
365 }
366 }
367  
368 sub CleanImages {
369 my $FB3 = shift;
370 my $FB3Body = $FB3->Body;
371  
372 my %TrialImageFiles;
373 my @FilePathes;
374  
375 # иногда так случается, что в исходном FB3 нет обложки
376 my $cover = eval { $FB3->Cover->PhysicalName };
377 # следующая строка чтобы не удалить обложку
378 $TrialImageFiles{$cover} = 1 if $cover;
379  
380 my @ImagesAll = $FB3Body->Relations(type => RELATION_TYPE_FB3_IMAGES);
381 foreach (@ImagesAll) { # эта картинка сохранилась в триалке
382 my $NewPart = $FB3->Part( $_->{TargetFullName} );
383 my $FullPath = $NewPart->PhysicalName;
384 push (@FilePathes, $FullPath);
385 if ($ImageHash{$_->{Id}}) {
386 $TrialImageFiles{$FullPath} = 1; # Нужный файлик, запомним.
387 } else {
388 $FB3Body->RemoveRelations( id => $_->{Id} );
389 }
390 }
391  
392 foreach (@FilePathes) {
393 unlink $_ unless $TrialImageFiles{$_};
394 }
395  
396 return 1;
397 }
398  
399 sub ZipFolder {
400  
401 my ($SourceFileName, $TargetFileName, @first) = @_;
402  
403 open my $FH, '>', "$TargetFileName";
404 close $FH;
405 my $fn_abs = abs_path("$TargetFileName");
406 unlink "$TargetFileName";
407  
408 my $old_dir = cwd();
409 chdir "$SourceFileName";
410 my $cmd = "zip -Xr9Dq $fn_abs " . join(' ', @first) . " *";
411 my $CmdResult = `$cmd`;
412 warn $CmdResult if $CmdResult;
413 chdir $old_dir if $old_dir;
414 }
415  
416 sub help {
417  
418 print qq{
419 USAGE: cutfb3.pl --in <input.file> --out <output.file> [options]
420  
421 --chars|c : maximum caracters in trial fragment. default is @{[DEFAULT_TRIAL_PERCENT]}% of text.
422 --imagespath : /path/to/fb3/images
423 --type|t : type of work `trial' or `output'. default is `trial'
424 --help|h : print this text
425  
426 };
427 exit;
428 }
429  
430  
431 1;