chiark / gitweb /
static/tgal.js (keyevent): Discard key events with spurious modifiers.
[tgal] / mason / .perl-lib / TrivGal.pm
1 ### -*-cperl-*-
2 ###
3 ### Main output for Trivial Gallery.
4 ###
5 ### (c) 2021 Mark Wooding
6 ###
7
8 ###----- Licensing notice ---------------------------------------------------
9 ###
10 ### This file is part of Trivial Gallery.
11 ###
12 ### Trivial Gallery is free software: you can redistribute it and/or modify
13 ### it under the terms of the GNU Affero General Public License as
14 ### published by the Free Software Foundation; either version 3 of the
15 ### License, or (at your option) any later version.
16 ###
17 ### Trivial Gallery is distributed in the hope that it will be useful, but
18 ### WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ### Affero General Public License for more details.
21 ###
22 ### You should have received a copy of the GNU Affero General Public
23 ### License along with Trivial Gallery.  If not, see
24 ### <https://www.gnu.org/licenses/>.
25
26 package TrivGal;
27
28 use autodie qw{:all};
29
30 use Errno;
31 use Exporter qw{import};
32 use File::stat;
33 use Graphics::Magick;
34 use Image::ExifTool qw{};
35 use Image::Size qw{};
36 use User::pwent;
37 use POSIX;
38
39 our @EXPORT;
40 sub export (@) { push @EXPORT, @_; }
41
42 ###--------------------------------------------------------------------------
43 ### Internal utilities.
44
45 sub read_or_set ($\$@) {
46   my ($me, $ref, @args) = @_;
47   if (@args == 0) { return $$ref; }
48   elsif (@args == 1) { $$ref = $args[0]; return $me; }
49   elsif (@args > 1) { die "too many arguments"; }
50 }
51
52 ###--------------------------------------------------------------------------
53 ### Random utilities.
54
55 export qw{join_paths};
56 sub join_paths (@) {
57   my @p = @_;
58   my $p = "";
59   ELT: for my $e (@p) {
60     $e =~ s#^/{2,}#/#;
61     $e =~ s#([^/])/+$#$1#;
62     if ($e eq "") { next ELT; }
63     elsif ($p eq "" || $e =~ m#^/#) { $p = $e; }
64     else { $p = "$p/$e"; }
65   }
66   return $p;
67 }
68
69 export qw{split_path};
70 sub split_path ($) {
71   my ($path) = @_;
72
73   my ($dir, $base, $ext) =
74     $path =~ m#^ (?: (.*) /)?
75                  (?: ([^/]*) \.)?
76                  ([^./]*) $#x;
77   if (defined $base) { $ext = ".$ext"; }
78   else { $base = $ext; $ext = ""; }
79   return ($dir, $base, $ext);
80 }
81
82 export qw{urlencode};
83 sub urlencode ($) {
84   my ($u) = @_;
85   $u =~ s#([^0-9a-zA-Z_./~-])#sprintf "%%%02x", ord $1#eg;
86   return $u;
87 }
88
89 export qw{urldecode};
90 sub urldecode ($) {
91   my ($u) = @_;
92   $u =~ s#\%([0-9a-fA-F]{2})#chr hex $1#eg;
93   return $u;
94 }
95
96 ###--------------------------------------------------------------------------
97 ### Configuration.
98
99 export qw{$SCOPE $SUFFIX};
100 our $SCOPE //= $::SCOPE;
101 our $SUFFIX //= $::SUFFIX;
102
103 export qw{$IMGROOT $CACHE $TMP};
104 our $IMGROOT //= "$ENV{HOME}/publish/$SCOPE-html$SUFFIX/tgal-images";
105 our $CACHE //=
106   ($ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache") .
107   "/tgal/$SCOPE$SUFFIX";
108 our $TMP //= "$CACHE/tmp";
109
110 export qw{$ROOTURL $IMGURL $CACHEURL $STATICURL $SCRIPTURL};
111 my $user = getpwuid($>)->name;
112 our $ROOTURL //= "/~$user";
113 our $IMGURL //= "$ROOTURL/tgal-images";
114 our $CACHEURL //= "$ROOTURL/tgal-cache";
115 our $STATICURL //= "$ROOTURL/tgal-static";
116 our $SCRIPTURL;
117
118 export qw{$SRCURL};
119 our $SRCURL = "https://git.distorted.org.uk/~mdw/tgal/";
120
121 export qw{%SIZE};
122 our %SIZE = (smallthumb => 96,
123              medthumb => 144,
124              bigthumb => 216,
125              tiny => 320,
126              small => 480,
127              embed => 720,
128              medium => 1080,
129              big => 1600,
130              large => 2400,
131              huge => 3600,
132              vast => 5400,
133              immense => 8100);
134
135 export qw{%TYPE};
136 our %TYPE = map { $_ => 1 } qw{.jpg .png};
137
138 export qw{init};
139 my $initp = 0;
140 sub init () {
141   my $m = HTML::Mason::Request->instance;
142   my $r = $m->cgi_request;
143
144   $m->interp->set_escape(u => sub { my ($r) = @_; $$r = urlencode $$r; });
145
146   return unless !$initp;
147
148   $SCRIPTURL //= $r->subprocess_env("SCRIPT_NAME");
149   $initp = 1;
150 }
151
152 ###--------------------------------------------------------------------------
153 ### Temporary files.
154
155 export qw{clean_temp_files};
156 sub clean_temp_files () {
157   my $d;
158
159   eval { opendir $d, $TMP; };
160   if ($@) {
161     if ($@->isa("autodie::exception") && $@->errno == ENOENT) { return; }
162     else { die $@; }
163   }
164   my $now = time;
165   FILE: while (my $name = readdir $d) {
166     next FILE unless $name =~ /^t(\d+)\-/;
167     my $pid = $1;
168     next FILE if kill 0, $pid;
169     my $f = "$TMP/$name";
170     my $st = stat $name;
171     next FILE if $now - $st->mtime() < 300;
172     unlink $f;
173   }
174   closedir $d;
175 }
176
177 ###--------------------------------------------------------------------------
178 ### Scaled images.
179
180 my %ORIENT =
181   (1 => [0, 0],
182    2 => [0, 1],
183    3 => [2, 0],
184    4 => [2, 1],
185    5 => [3, 1],
186    6 => [1, 0],
187    7 => [1, 1],
188    8 => [3, 0]);
189
190 package TrivGal::Image {
191   use File::Path qw{make_path};
192   use File::stat;
193
194   sub new ($$) {
195     my ($cls, $path) = @_;
196     my $imgpath = "$IMGROOT/$path";
197     my $st = stat $imgpath or die "no image `$path'";
198     return bless {
199       path => $path, imgpath => $imgpath,
200       mtime => $st->mtime,
201       img => undef,
202       rot => undef, flip => undef,
203       wd => undef, ht => undef,
204       _wd => undef, _ht => undef,
205       sz => undef
206     }, $cls;
207   }
208
209   sub _getsz ($) {
210     my ($me) = @_;
211     return if defined $me->{_wd};
212
213     my ($wd, $ht, $err) = Image::Size::imgsize $me->{imgpath};
214     defined $wd or die "failed to read size of `$me->{path}': $err";
215     my $sz = $wd; if ($sz < $ht) { $sz = $ht; }
216     @$me{"_wd", "_ht", "sz"} = ($wd, $ht, $sz);
217   }
218
219   sub _getexif ($) {
220     my ($me) = @_;
221     return if defined $me->{wd};
222
223     $me->_getsz;
224     my $exif = new Image::ExifTool; $exif->ExtractInfo($me->{imgpath});
225     my $orient = $exif->GetValue("Orientation", "ValueConv");
226     my ($wd, $ht) = @$me{"_wd", "_ht"};
227     my ($rot, $flip);
228     if (defined $orient) { ($rot, $flip) = $ORIENT{$orient}->@*; }
229     else { ($rot, $flip) = (0, 0); }
230     if ($rot%2) { ($wd, $ht) = ($ht, $wd); }
231     @$me{"rot", "flip", "wd", "ht"} = ($rot, $flip, $wd, $ht);
232   }
233
234   sub sz ($) { my ($me) = @_; $me->_getsz; return $me->{sz}; }
235   sub wd ($) { my ($me) = @_; $me->_getexif; return $me->{wd}; }
236   sub ht ($) { my ($me) = @_; $me->_getexif; return $me->{ht}; }
237
238   sub _check_gm ($) {
239     my ($rc) = @_;
240     "$rc" and die "failed to hack `$me->{img}': $rc";
241   }
242
243   sub scale ($$;$) {
244     my ($me, $scale, $forcep) = @_;
245     my $m = HTML::Mason::Request->instance;
246
247     my $path = $me->{path};
248     my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
249     my $url;
250
251     if ($me->sz <= $sz)
252       { $url = $m->interp->apply_escapes("$IMGURL/$path", "u"); }
253     else {
254       my $tail = "scale.$sz/$path";
255       my $thumb = "$CACHE/$tail";
256       my $thumburl = $m->interp->apply_escapes("$CACHEURL/$tail", "u");
257
258       my $st = stat $thumb;
259       if ($st && $st->mtime > $me->{mtime})
260         { $url = $thumburl; }
261       elsif (!$forcep) {
262         $url =
263           $m->interp->apply_escapes("$SCRIPTURL/$path", "u") .
264           "?scale=$scale";
265       } else {
266         my $img = $me->{img};
267         unless (defined $img) {
268           $img = $me->{img} = Graphics::Magick->new;
269           _check_gm $img->Read($me->{imgpath});
270         }
271
272         my ($dir, undef, $ext) = TrivGal::split_path $thumb;
273         $img = $img->Clone;
274         my $new = "$TMP/t$$-thumb$ext";
275         _check_gm $img->Resize(geometry => $sz);
276         make_path $TMP, { mode => 0771 };
277         _check_gm $img->Write($new);
278         make_path $dir, { mode => 0771 };
279         rename $new, $thumb;
280         $url = $thumburl;
281       }
282     }
283
284     return $url;
285   }
286 }
287
288 ###--------------------------------------------------------------------------
289 ### Directory listings.
290
291 package TrivGal::Item {
292   sub new ($$) {
293     my ($cls, $name) = @_;
294     return bless { name => $name }, $cls;
295   }
296   sub name ($@) {
297     my ($me, @args) = @_;
298     return TrivGal::read_or_set $me, $me->{name}, @args;
299   }
300   sub comment ($@) {
301     my ($me, @args) = @_;
302     return TrivGal::read_or_set $me, $me->{comment}, @args;
303   }
304 }
305
306 export qw{listdir};
307 sub listdir ($) {
308   my ($path) = @_;
309   my (@d, @f);
310   my $ix = undef;
311
312   $path =~ s#/$##;
313   if (-f "$path/.tgal.index") {
314     open my $f, "<", "$path/.tgal.index";
315     my $item = undef;
316     my $comment = undef;
317     LINE: while (<$f>) {
318       chomp;
319       next LINE if /^\s*(\#|$)/;
320       if (s/^\s+//) {
321         die "no item" unless $item;
322         $comment = defined $comment ? $comment . "\n" . $_ : $_;
323       } else {
324         if ($item && $comment) { $item->comment($comment); }
325         my ($flags, $name, $c) =
326           /^ (?: ([-!]+) \s+)?          # flags
327              (\S+) \s*                  # filename
328              (\S | \S.*\S )?            # start of the comment
329              \s*
330              $/x;
331         my $indexp = $flags =~ /!/;
332         my $hidep = $flags =~ /-/;
333         $name = urldecode $name;
334         my $list;
335         $item = TrivGal::Item->new($name);
336         if ($name =~ m#/$#) {
337           $list = \@d;
338           die "can't index a folder" if $indexp;
339         } else {
340           $list = \@f;
341           my (undef, undef, $ext) = split_path $name;
342           die "unknown image type" unless $TYPE{lc $ext};
343           if ($indexp) {
344             die "two index images" if defined $ix;
345             $ix = $item;
346           }
347         }
348         $comment = $c;
349         push @$list, $item unless $hidep;
350       }
351     }
352     if ($item && $comment) { $item->comment($comment); }
353     close $f;
354   } else {
355     my $st = stat $path;
356     unless ($st->mode&0004) { return ([], [], undef); }
357
358     opendir $d, $path;
359     my @e = readdir $d;
360     closedir $d;
361
362     ENT: for my $e (sort @e) {
363       my (undef, undef, $ext) = split_path $e;
364       my $dotp = $e =~ /^\./;
365       my $st = stat "$path/$e";
366       my $list = undef;
367       if ($dotp) { }
368       elsif (-d $st) { $list = \@d; $e .= "/"; }
369       elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
370       $list and push @$list, TrivGal::Item->new($e);
371     }
372     $ix = $f[0] if @f;
373   }
374
375   return (\@d, \@f, $ix);
376 }
377
378 export qw{contents};
379 sub contents ($) {
380   my ($file) = @_;
381   my $contents = "";
382   my $f;
383   local $@;
384   eval { open $f, "<", "$file"; };
385   if ($@) {
386     if ($@->isa("autodie::exception") && $@->errno == ENOENT)
387       { return undef; }
388     die $@;
389   }
390   while (sysread $f, $buf, 16384) { $contents .= $buf; }
391   close $f;
392   return $contents;
393 }
394
395 export qw{find_covering_file};
396 sub find_covering_file ($$$) {
397   my ($top, $path, $name) = @_;
398   for (;;) {
399     my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
400     if ($path eq "") { return undef; }
401     if ($path =~ m#^(.*)/[^/]+/?#) { $path = $1; }
402     else { $path = ""; }
403   }
404 }
405
406 ###----- That's all, folks --------------------------------------------------
407
408 clean_temp_files;
409
410 1;