cleanup MAX_PAGES to make it optional
[bookreader.git] / plack / lib / Plack / App / BookReader.pm
1 package Plack::App::BookReader;
2 use parent qw(Plack::App::File);
3 use strict;
4 use warnings;
5 use Plack::Util;
6 use HTTP::Date;
7 use Plack::MIME;
8 use DirHandle;
9 use URI::Escape;
10 use Plack::Request;
11 use Data::Dump qw(dump);
12 use File::Path qw(make_path remove_tree);
13 use Graphics::Magick;
14 use File::Slurp;
15 use JSON;
16 use autodie;
17 use Time::HiRes qw(time);
18 use Encode;
19
20 sub make_basedir {
21         my $path = shift;
22         return if -e $path;
23         $path =~ s{/[^/]+$}{} || die "no dir/file in $path";
24         warn "# make_basedir $path\n";
25         -e $path ? 0 : File::Path::make_path $path;
26 }
27
28 # Stolen from rack/directory.rb
29 my $dir_file = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>";
30 my $dir_page = <<PAGE;
31 <html><head>
32   <title>%s</title>
33   <meta http-equiv="content-type" content="text/html; charset=utf-8" />
34   <style type='text/css'>
35 table { width:100%%; }
36 .name { text-align:left; }
37 .size, .mtime { text-align:right; }
38 .type { width:11em; }
39 .mtime { width:15em; }
40   </style>
41 </head><body>
42 <h1>%s</h1>
43 <hr />
44 <table>
45   <tr>
46     <th class='name'>Name</th>
47     <th class='size'>Size</th>
48     <th class='type'>Type</th>
49     <th class='mtime'>Last Modified</th>
50   </tr>
51 %s
52 </table>
53 <hr />
54 <code>%s</code>
55 </body></html>
56 PAGE
57
58 my $reader_page = <<'PAGE';
59 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
60 <html>
61 <head>
62     <title>%s</title>
63     
64     <link rel="stylesheet" type="text/css" href="/BookReader/BookReader.css"/>
65     <script type="text/javascript" src="http://www.archive.org/includes/jquery-1.4.2.min.js"></script>
66     <script type="text/javascript" src="http://www.archive.org/bookreader/jquery-ui-1.8.5.custom.min.js"></script>
67
68     <script type="text/javascript" src="http://www.archive.org/bookreader/dragscrollable.js"></script>
69     <script type="text/javascript" src="http://www.archive.org/bookreader/jquery.colorbox-min.js"></script>
70     <script type="text/javascript" src="http://www.archive.org/bookreader/jquery.ui.ipad.js"></script>
71     <script type="text/javascript" src="http://www.archive.org/bookreader/jquery.bt.min.js"></script>
72
73     <script type="text/javascript" src="/BookReader/BookReader.js"></script>
74
75 <style type="text/css">
76
77 /* Hide print and embed functionality */
78 #BRtoolbar .embed, .print {
79     display: none;
80 }
81
82 </style>
83
84 <script type="text/javascript">
85 $(document).ready( function() {
86
87 // 
88 // This file shows the minimum you need to provide to BookReader to display a book
89 //
90 // Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
91
92 // Create the BookReader object
93 var br = new BookReader();
94
95 var pages = %s;
96
97 // Return the width of a given page.  Here we assume all images are 800 pixels wide
98 br.getPageWidth = function(index) {
99         if ( ! pages[index] ) return;
100     return parseInt( pages[index][1] );
101 }
102
103 // Return the height of a given page.  Here we assume all images are 1200 pixels high
104 br.getPageHeight = function(index) {
105         if ( ! pages[index] ) return;
106     return parseInt( pages[index][2] );
107 }
108
109 // We load the images from archive.org -- you can modify this function to retrieve images
110 // using a different URL structure
111 br.getPageURI = function(index, reduce, rotate) {
112         if ( ! pages[index] ) return;
113     // reduce and rotate are ignored in this simple implementation, but we
114     // could e.g. look at reduce and load images from a different directory
115     // or pass the information to an image server
116         var url = pages[index][0] + '?reduce='+reduce;
117         console.debug('getPageURI', index, reduce, rotate, url);
118     return url;
119 }
120
121 // Return which side, left or right, that a given page should be displayed on
122 br.getPageSide = function(index) {
123     if (0 == (index & 0x1)) {
124         return 'R';
125     } else {
126         return 'L';
127     }
128 }
129
130 // This function returns the left and right indices for the user-visible
131 // spread that contains the given index.  The return values may be
132 // null if there is no facing page or the index is invalid.
133 br.getSpreadIndices = function(pindex) {   
134     var spreadIndices = [null, null]; 
135     if ('rl' == this.pageProgression) {
136         // Right to Left
137         if (this.getPageSide(pindex) == 'R') {
138             spreadIndices[1] = pindex;
139             spreadIndices[0] = pindex + 1;
140         } else {
141             // Given index was LHS
142             spreadIndices[0] = pindex;
143             spreadIndices[1] = pindex - 1;
144         }
145     } else {
146         // Left to right
147         if (this.getPageSide(pindex) == 'L') {
148             spreadIndices[0] = pindex;
149             spreadIndices[1] = pindex + 1;
150         } else {
151             // Given index was RHS
152             spreadIndices[1] = pindex;
153             spreadIndices[0] = pindex - 1;
154         }
155     }
156     
157     return spreadIndices;
158 }
159
160 // For a given "accessible page index" return the page number in the book.
161 //
162 // For example, index 5 might correspond to "Page 1" if there is front matter such
163 // as a title page and table of contents.
164 br.getPageNum = function(index) {
165     return index+1;
166 }
167
168 // Total number of leafs
169 br.numLeafs = pages.length;
170
171 // Book title and the URL used for the book title link
172 br.bookTitle= '%s';
173 br.bookUrl  = '%s';
174
175 // Override the path used to find UI images
176 br.imagesBaseURL = '/BookReader/images/';
177
178 br.getEmbedCode = function(frameWidth, frameHeight, viewParams) {
179     return "Embed code not supported in bookreader demo.";
180 }
181
182 // Let's go!
183 br.init();
184
185 // read-aloud and search need backend compenents and are not supported in the demo
186 $('#BRtoolbar').find('.read').hide();
187 $('#textSrch').hide();
188 $('#btnSrch').hide();
189
190 } );
191 </script>
192
193 </head>
194 <body style="background-color: ##939598;">
195
196 <div id="BookReader">
197     Internet Archive BookReader<br/>
198     
199     <noscript>
200     <p>
201         The BookReader requires JavaScript to be enabled. Please check that your browser supports JavaScript and that it is enabled in the browser settings.
202     </p>
203     </noscript>
204 </div>
205
206
207 </body>
208 </html>
209 PAGE
210
211 sub should_handle {
212     my($self, $file) = @_;
213     return -d $file || -f $file;
214 }
215
216 sub return_dir_redirect {
217     my ($self, $env) = @_;
218     my $uri = Plack::Request->new($env)->uri;
219     return [ 301,
220         [
221             'Location' => $uri . '/',
222             'Content-Type' => 'text/plain',
223             'Content-Length' => 8,
224         ],
225         [ 'Redirect' ],
226     ];
227 }
228
229 sub convert { gm('convert',@_) }
230 sub montage { gm('montage',@_) }
231
232 sub gm {
233         my $command = shift;
234         warn "# $command ",dump(@_);
235         my $t = time();
236         system 'gm', $command, @_;
237         $t = time() - $t;
238         warn sprintf("## $command %d bytes in %.2f s %s\n", -s $_[-1], $t, $_[-1]);
239 }
240
241 sub longest_common_prefix {
242            my $prefix = shift;
243         for (@_) {
244                 chop $prefix while (! /^\Q$prefix\E/i);
245         }
246         warn "# longest_common_prefix [$prefix]\n";
247         return $prefix;
248 }
249
250 sub sort_pages {
251         my $prefix = longest_common_prefix @_;
252         sort {
253                         my ( $an,$bn ) = ( $a,$b );
254                         $an =~ s/^\Q$prefix\E//i; $an =~ s/\D+//g;
255                         $bn =~ s/^\Q$prefix\E//i; $bn =~ s/\D+//g;
256                         warn "## sort [$a] $an <=> $bn [$b]\n";
257                         $an <=> $bn;
258         } @_;
259 }
260
261 sub convert_pdf_page {
262         my ($pdf, $page, $path) = @_;
263         my $t = time();
264
265         make_path $path;
266
267         warn "# pdfimages $page $pdf -> $path/\n";
268         system 'pdfimages', '-f', $page, '-l', $page, '-q', '-j', '-p', $pdf, "$path/p";
269
270         my @parts = ();
271         # glob split on spaces!
272         opendir(my $dh, $path);
273         while (readdir($dh)) {
274                 my $full = "$path/$_";
275                 warn "## readdir $full\n";
276                 next unless -f $full; # skip . ..
277                 push @parts, $_;
278         }
279         closedir $dh;
280
281         die "can't find images for $pdf in $path" unless $#parts >= 0;
282
283         @parts = sort_pages @parts;
284
285         my $image = "$path.jpg";
286
287         if ( $#parts == 0 ) { # single image
288                         my $part = "$path/$parts[0]";
289                         convert( $part => $image );
290         } else {
291                         my @full = map { "$path/$_" } @parts;
292                         montage( @full, '-tile', '1x'.scalar(@full), '-geometry', '+1+1' => $image );
293         }
294
295         die "$image: $!" unless -r $image;
296
297         remove_tree $path;
298
299         $t = time() - $t;
300         warn sprintf("## page: %d in %.2f s for %s\n", $page, $t, $image);
301         return $image;
302 }
303
304 sub render_pdf_page {
305         my ( $pdf, $page, $path ) = @_;
306         my $t = time();
307
308         warn "# pdftocairo $pdf\n";
309         system('pdftocairo', '-jpeg', '-f', $page, '-l', $page, $pdf, $path);
310
311         my $image = sprintf( '%s-%03d.jpg', $path, $page );
312
313         die "can't find $image: $!" unless -r $image;
314
315         $t = time() - $t;
316         warn sprintf("## page: %d in %.2f s for %s\n", $page, $t, $image);
317         return $image;
318 }
319
320 sub serve_path {
321     my($self, $env, $path, $fullpath) = @_;
322
323         my $req = Plack::Request->new($env);
324
325     my $dir_url = $env->{SCRIPT_NAME} . $env->{PATH_INFO};
326         my @files = ();
327         my @page_files;
328
329         if ( -f $path && $path =~ s{/([^/]+\.pdf)$}{} ) {
330                 push @page_files, $1;
331                 warn "# single pdf: $path / $1\n";
332     } elsif (-f $path ) {
333
334                 if ( my $reduce = $req->param('reduce') ) {
335                         $reduce = int($reduce); # BookReader javascript somethimes returns float
336                         warn "# reduce $reduce $path\n";
337
338                         my $cache_path = "cache/$dir_url.reduce.$reduce.jpg";
339                         if ( $reduce <= 1 && $path =~ m/\.jpe?g$/ ) {
340                                 $cache_path = $path;
341                         } elsif ( ! -e $cache_path ) {
342                                 make_basedir $cache_path;
343                                 convert( '-scale', ( 100 / $reduce ) .'%', $path => $cache_path );
344                         }
345
346                 return $self->SUPER::serve_path($env, $cache_path, $fullpath);
347
348                 }
349
350         return $self->SUPER::serve_path($env, $path, $fullpath);
351      } elsif ( -d $path ) {
352
353                 if ($dir_url !~ m{/$}) {
354                         return $self->return_dir_redirect($env);
355                 }
356
357                 my $dh = DirHandle->new($path);
358                 my @children;
359                 while (defined(my $ent = $dh->read)) {
360                         next if $ent eq '.';
361                         push @children, $ent;
362                 }
363
364                 for my $basename (sort { $a cmp $b } @children) {
365                         push @page_files, $basename if $basename =~ m/\d+\D?\.(jpg|gif|pdf)$/;
366                         my $file = "$path/$basename";
367                         my $url = $dir_url . $basename;
368
369                         my $is_dir = -d $file;
370                         my @stat = stat _;
371
372
373                         $url = join '/', map {uri_escape($_)} split m{/}, $url;
374
375                         if ($is_dir) {
376                                 $basename .= "/";
377                                 $url      .= "/";
378                         }
379
380                         my $mime_type = $is_dir ? 'directory' : ( Plack::MIME->mime_type($file) || 'text/plain' );
381                         push @files, [ $url, $basename, $stat[7], $mime_type, HTTP::Date::time2str($stat[9]) ];
382                 }
383
384         } else {
385                 die "Unsupported format: $path";
386         }
387
388         if ( @page_files ) {
389                 @page_files = sort_pages @page_files;
390                 warn "# page_files = ",dump( @page_files );
391         }
392
393     my $dir  = Plack::Util::encode_html( $env->{PATH_INFO} );
394         my $page = 'empty';
395
396         if ( $req->param('bookreader') ) {
397
398                 my $pages; # []:
399                 my $pages_path = "meta/$dir_url/bookreader.json";
400                 if ( -e $pages_path ) {
401                         $pages = decode_json read_file $pages_path;
402                 } else {
403                         foreach my $page ( @page_files ) {
404                                 my $image = Graphics::Magick->new;
405                                 if ( $page =~ m/\.pdf$/ ) {
406                                         die "$path/$page: $!" unless -r "$path/$page";
407
408                                         my $info = `pdfinfo "$path/$page"`;
409                                         warn "# pdfinfo $path/$page\n$info\n";
410                                         my $pdf_pages = $1 if ( $info =~ m/Pages:\s*(\d+)/s );
411                                         die "can't find number of pages for $path/$page in:\n$pdf_pages\n" unless $pdf_pages;
412
413                                         my $cache_path = "cache/$dir_url/$page";
414                                         my $txt = "$cache_path.txt";
415                                         make_basedir $txt;
416                                         system('pdftotext', "$path/$page", $txt);
417                                         warn "# pdftotext $txt ", -s $txt, " bytes\n";
418
419                                         my $is_bitmap = -s $txt == $pdf_pages;
420
421                                         $pdf_pages = $ENV{MAX_PAGES} if defined $ENV{MAX_PAGES} && $pdf_pages > $ENV{MAX_PAGES}; # FIXME
422
423                                         warn "DIAG: bitmap:$is_bitmap pdf_pages:$pdf_pages\n";
424
425                                         foreach my $nr ( 1 .. $pdf_pages ) {
426                                                 my $page_url = $is_bitmap
427                                                         ? convert_pdf_page( "$path/$page", $nr, "$cache_path.$nr" )
428                                                         : render_pdf_page(  "$path/$page", $nr, "$cache_path" )
429                                                 ;
430                                                 warn "## ping $page_url\n";
431                                                 my ( $w, $h, $size, $format ) = $image->ping($page_url);
432                                                 warn "## image size $w*$h $size $format $page_url\n";
433                                                 my $url = decode('utf-8',"/$page_url");
434                                                 push @$pages, [ $url, $w, $h ] if $w && $h;
435                                         }
436
437                                 } else {
438                                         die "$path/$page: $!" unless -r "$path/$page";
439                                         my ( $w, $h, $size, $format ) = $image->ping("$path/$page");
440                                         warn "# image size $w*$h $size $format $path/$page\n";
441                                         my $url = decode('utf-8',"$dir_url/$page");
442                                         push @$pages, [ $url, $w, $h ] if $w && $h;
443                                 }
444                         }
445                         make_basedir $pages_path;
446                         write_file $pages_path, => encode_json( $pages );
447                         warn "# created $pages_path ", -s $pages_path, " bytes\n";
448                 }
449                 warn "# pages = ",dump($pages);
450                 $page = sprintf $reader_page, $dir, encode_json( $pages ), $dir, $dir =~ m/\/$/ ? '..' : '.';
451
452         } else {
453
454                 my $files = join "\n", map {
455                         my $f = $_;
456                         sprintf $dir_file, map Plack::Util::encode_html($_), @$f;
457                 } @files;
458
459                 $page = sprintf $dir_page, $dir, $dir, $files, 
460                         @page_files ? '<form><input type=submit name=bookreader value="Read"></form>' . dump( [ @page_files ] ) : '';
461
462         }
463
464     return [ 200, ['Content-Type' => 'text/html; charset=utf-8'], [ $page ] ];
465 }
466
467 1;
468
469 __END__
470
471 =head1 NAME
472
473 Plack::App::BookReader - Internet Archive Book Reader with directory index
474
475 =head1 SYNOPSIS
476
477   # app.psgi
478   use Plack::App::BookReader;
479   my $app = Plack::App::BookReader->new({ root => "/path/to/htdocs" })->to_app;
480
481 =head1 DESCRIPTION
482
483 This is a static file server PSGI application with directory index a la Apache's mod_autoindex.
484
485 =head1 CONFIGURATION
486
487 =over 4
488
489 =item root
490
491 Document root directory. Defaults to the current directory.
492
493 =back
494
495 =head1 AUTHOR
496
497 Dobrica Pavlinusic
498 Tatsuhiko Miyagawa (based on L<Plack::App::Directory>
499
500 =head1 SEE ALSO
501
502 L<Plack::App::File>
503
504 =cut
505