correctly encode utf-8 filenames in json
[bookreader.git] / plack / lib / Plack / App / BookReader.pm
index 9731530..03b67ba 100644 (file)
@@ -9,19 +9,20 @@ use DirHandle;
 use URI::Escape;
 use Plack::Request;
 use Data::Dump qw(dump);
-use File::Path;
+use File::Path qw(make_path remove_tree);
 use Graphics::Magick;
 use File::Slurp;
-use Image::Size;
 use JSON;
-use Time::Piece ();
-use Time::Seconds 'ONE_YEAR';
+use autodie;
+use Time::HiRes qw(time);
+use Encode;
 
 sub make_basedir {
        my $path = shift;
        return if -e $path;
        $path =~ s{/[^/]+$}{} || die "no dir/file in $path";
-       File::Path::make_path $path;
+       warn "# make_basedir $path\n";
+       -e $path ? 0 : File::Path::make_path $path;
 }
 
 # Stolen from rack/directory.rb
@@ -169,7 +170,7 @@ br.numLeafs = pages.length;
 
 // Book title and the URL used for the book title link
 br.bookTitle= '%s';
-br.bookUrl  = 'http://openlibrary.org';
+br.bookUrl  = '%s';
 
 // Override the path used to find UI images
 br.imagesBaseURL = '/BookReader/images/';
@@ -225,31 +226,105 @@ sub return_dir_redirect {
     ];
 }
 
+sub convert { gm('convert',@_) }
+sub montage { gm('montage',@_) }
+
+sub gm {
+       my $command = shift;
+       warn "# $command ",dump(@_);
+       my $t = time();
+       system 'gm', $command, @_;
+       $t = time() - $t;
+       warn sprintf("## $command %d bytes in %.2f s %s\n", -s $_[-1], $t, $_[-1]);
+}
+
+sub longest_common_prefix {
+          my $prefix = shift;
+       for (@_) {
+               chop $prefix while (! /^\Q$prefix\E/i);
+       }
+       warn "# longest_common_prefix [$prefix]\n";
+       return $prefix;
+}
+
+sub sort_pages {
+       my $prefix = longest_common_prefix @_;
+       sort {
+                       my ( $an,$bn ) = ( $a,$b );
+                       $an =~ s/^\Q$prefix\E//i; $an =~ s/\D+//g;
+                       $bn =~ s/^\Q$prefix\E//i; $bn =~ s/\D+//g;
+                       warn "## sort [$a] $an <=> $bn [$b]\n";
+                       $an <=> $bn;
+       } @_;
+}
+
+sub convert_pdf_page {
+       my ($pdf, $page, $path) = @_;
+       my $t = time();
+
+       make_path $path;
+
+       warn "# pdfimages $page $pdf -> $path/\n";
+       system 'pdfimages', '-f', $page, '-l', $page, '-q', '-j', '-p', $pdf, "$path/p";
+
+       my @parts = ();
+       # glob split on spaces!
+       opendir(my $dh, $path);
+       while (readdir($dh)) {
+               my $full = "$path/$_";
+               warn "## readdir $full\n";
+               next unless -f $full; # skip . ..
+               push @parts, $_;
+       }
+       closedir $dh;
+
+       die "can't find images for $pdf in $path" unless $#parts >= 0;
+
+       @parts = sort_pages @parts;
+
+       my $image = "$path.jpg";
+
+       if ( $#parts == 0 ) { # single image
+                       my $part = "$path/$parts[0]";
+                       convert( $part => $image );
+       } else {
+                       my @full = map { "$path/$_" } @parts;
+                       montage( @full, '-tile', '1x'.scalar(@full), '-geometry', '+1+1' => $image );
+       }
+
+       die "$image: $!" unless -r $image;
+
+       remove_tree $path;
+
+       $t = time() - $t;
+       warn sprintf("## page: %d in %.2f s for %s\n", $page, $t, $image);
+       return $image;
+}
+
 sub serve_path {
     my($self, $env, $path, $fullpath) = @_;
 
        my $req = Plack::Request->new($env);
 
-    if (-f $path) {
+    my $dir_url = $env->{SCRIPT_NAME} . $env->{PATH_INFO};
+       my @files = ();
+       my @page_files;
+
+       if ( -f $path && $path =~ s{/([^/]+\.pdf)$}{} ) {
+               push @page_files, $1;
+               warn "# single pdf: $path / $1\n";
+    } elsif (-f $path ) {
 
                if ( my $reduce = $req->param('reduce') ) {
                        $reduce = int($reduce); # BookReader javascript somethimes returns float
                        warn "# reduce $reduce $path\n";
 
-                       my $cache_path = "cache/$path.reduce.$reduce.jpg";
+                       my $cache_path = "cache/$dir_url.reduce.$reduce.jpg";
                        if ( $reduce <= 1 && $path =~ m/\.jpe?g$/ ) {
                                $cache_path = $path;
                        } elsif ( ! -e $cache_path ) {
-                               my $image = Graphics::Magick->new( magick => 'jpg' );
-                               $image->Read($path);
-                               my ( $w, $h ) = $image->Get('width','height');
-                               $image->Resize(
-                                       width  => $w / $reduce,
-                                       height => $h / $reduce
-                               );
                                make_basedir $cache_path;
-                               $image->Write( filename => $cache_path );
-                               warn "# created $cache_path ", -s $cache_path, " bytes\n";
+                               convert( '-scale', ( 100 / $reduce ) .'%', $path => $cache_path );
                        }
 
                return $self->SUPER::serve_path($env, $cache_path, $fullpath);
@@ -257,68 +332,95 @@ sub serve_path {
                }
 
         return $self->SUPER::serve_path($env, $path, $fullpath);
-    }
+     } elsif ( -d $path ) {
 
-    my $dir_url = $env->{SCRIPT_NAME} . $env->{PATH_INFO};
+               if ($dir_url !~ m{/$}) {
+                       return $self->return_dir_redirect($env);
+               }
 
-    if ($dir_url !~ m{/$}) {
-        return $self->return_dir_redirect($env);
-    }
+               my $dh = DirHandle->new($path);
+               my @children;
+               while (defined(my $ent = $dh->read)) {
+                       next if $ent eq '.';
+                       push @children, $ent;
+               }
 
-    my @files = ([ "../", "Parent Directory", '', '', '' ]);
+               for my $basename (sort { $a cmp $b } @children) {
+                       push @page_files, $basename if $basename =~ m/\d+\D?\.(jpg|gif|pdf)$/;
+                       my $file = "$path/$basename";
+                       my $url = $dir_url . $basename;
 
-    my $dh = DirHandle->new($path);
-    my @children;
-    while (defined(my $ent = $dh->read)) {
-        next if $ent eq '.';
-        push @children, $ent;
-    }
+                       my $is_dir = -d $file;
+                       my @stat = stat _;
 
-       my @page_files;
-
-    for my $basename (sort { $a cmp $b } @children) {
-               push @page_files, $basename if $basename =~ m/\.(jpg|gif)$/;
-        my $file = "$path/$basename";
-        my $url = $dir_url . $basename;
 
-        my $is_dir = -d $file;
-        my @stat = stat _;
+                       $url = join '/', map {uri_escape($_)} split m{/}, $url;
 
+                       if ($is_dir) {
+                               $basename .= "/";
+                               $url      .= "/";
+                       }
 
-        $url = join '/', map {uri_escape($_)} split m{/}, $url;
+                       my $mime_type = $is_dir ? 'directory' : ( Plack::MIME->mime_type($file) || 'text/plain' );
+                       push @files, [ $url, $basename, $stat[7], $mime_type, HTTP::Date::time2str($stat[9]) ];
+               }
 
-        if ($is_dir) {
-            $basename .= "/";
-            $url      .= "/";
-        }
+       } else {
+               die "Unsupported format: $path";
+       }
 
-        my $mime_type = $is_dir ? 'directory' : ( Plack::MIME->mime_type($file) || 'text/plain' );
-        push @files, [ $url, $basename, $stat[7], $mime_type, HTTP::Date::time2str($stat[9]) ];
-    }
+       if ( @page_files ) {
+               @page_files = sort_pages @page_files;
+               warn "# page_files = ",dump( @page_files );
+       }
 
     my $dir  = Plack::Util::encode_html( $env->{PATH_INFO} );
        my $page = 'empty';
 
        if ( $req->param('bookreader') ) {
 
-               my $pages;
+               my $pages; # []
                my $pages_path = "cache/$dir_url/bookreader.json";
-               if ( 0 && -e $pages_path ) {
+               if ( -e $pages_path ) {
                        $pages = decode_json read_file $pages_path;
                } else {
-                       $pages = [
-                               grep { defined $_ }
-                               map {
-                                       my ( $w, $h ) = imgsize("$path/$_"); 
-                                       $w && $h ? [ "$dir_url/$_", $w, $h ] : undef
-                               } sort { $a <=> $b } @page_files
-                       ];
+                       foreach my $page ( @page_files ) {
+                               my $image = Graphics::Magick->new;
+                               if ( $page =~ m/\.pdf$/ ) {
+                                       die "$path/$page: $!" unless -r "$path/$page";
+
+                                       my $info = `pdfinfo $path/$page`;
+                                       warn "# pdfinfo $path/$page\n$info\n";
+                                       my $pdf_pages = $1 if ( $info =~ m/Pages:\s*(\d+)/s );
+                                       die "can't find number of pages for $path/$page in:\n$pdf_pages\n" unless $pdf_pages;
+
+
+                                       $pdf_pages = $ENV{MAX_PAGES} if $pdf_pages > $ENV{MAX_PAGES}; # FIXME
+
+                                       foreach my $nr ( 1 .. $pdf_pages ) {
+                                               my $cache_path = "cache/$dir_url/$page";
+                                               my $page_url = convert_pdf_page( "$path/$page", $nr, $cache_path . '.' . $nr );
+                                               warn "## ping $page_url\n";
+                                               my ( $w, $h, $size, $format ) = $image->ping($page_url);
+                                               warn "## image size $w*$h $size $format $page_url\n";
+                                               my $url = decode('utf-8',"/$page_url");
+                                               push @$pages, [ $url, $w, $h ] if $w && $h;
+                                       }
+
+                               } else {
+                                       die "$path/$page: $!" unless -r "$path/$page";
+                                       my ( $w, $h, $size, $format ) = $image->ping("$path/$page");
+                                       warn "# image size $w*$h $size $format $path/$page\n";
+                                       my $url = decode('utf-8',"$dir_url/$page");
+                                       push @$pages, [ $url, $w, $h ] if $w && $h;
+                               }
+                       }
                        make_basedir $pages_path;
-                       write_file $pages_path => encode_json( $pages );
+                       write_file $pages_path, => encode_json( $pages );
                        warn "# created $pages_path ", -s $pages_path, " bytes\n";
                }
                warn "# pages = ",dump($pages);
-               $page = sprintf $reader_page, $dir, encode_json( $pages ), $dir; # FIXME: title
+               $page = sprintf $reader_page, $dir, encode_json( $pages ), $dir, '..';
 
        } else {
 
@@ -327,7 +429,8 @@ sub serve_path {
                        sprintf $dir_file, map Plack::Util::encode_html($_), @$f;
                } @files;
 
-               $page = sprintf $dir_page, $dir, $dir, $files;
+               $page = sprintf $dir_page, $dir, $dir, $files, 
+                       @page_files ? '<form><input type=submit name=bookreader value="Read"></form>' . dump( [ @page_files ] ) : '';
 
        }