chiark / gitweb /
mason/.perl-lib/TrivGal.pm: Explicitly ignore values from `split_path'.
[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 Image::ExifTool qw{};
34 use Image::Imlib2;
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 ### Image types.
98
99 our %TYPE;
100
101 package TrivGal::ImageType {
102   sub new ($$) {
103     my ($cls, $ext) = @_;
104     return $TYPE{$ext} = bless { ext => $ext }, $cls;
105   }
106   sub ext ($) {
107     my ($me, @args) = @_;
108     return $me->{ext};
109   }
110   sub mimetype ($@) {
111     my ($me, @args) = @_;
112     return TrivGal::read_or_set $me, $me->{mimetype}, @args;
113   }
114   sub imlibfmt ($@) {
115     my ($me, @args) = @_;
116     return TrivGal::read_or_set $me, $me->{imlibfmt}, @args;
117   }
118 }
119
120 TrivGal::ImageType->new(".jpg")->mimetype("image/jpeg")->imlibfmt("jpeg");
121 TrivGal::ImageType->new(".png")->mimetype("image/png")->imlibfmt("png");
122
123 ###--------------------------------------------------------------------------
124 ### Configuration.
125
126 export qw{$SCOPE $SUFFIX};
127 our $SCOPE //= $::SCOPE;
128 our $SUFFIX //= $::SUFFIX;
129
130 export qw{$IMGROOT $CACHE $TMP};
131 our $IMGROOT //= "$ENV{HOME}/publish/$SCOPE-html$SUFFIX/tgal-images";
132 our $CACHE //=
133   ($ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache") .
134   "/tgal/$SCOPE$SUFFIX";
135 our $TMP //= "$CACHE/tmp";
136
137 export qw{$ROOTURL $IMGURL $CACHEURL $STATICURL $SCRIPTURL};
138 my $user = getpwuid($>)->name;
139 our $ROOTURL //= "/~$user";
140 our $IMGURL //= "$ROOTURL/tgal-images";
141 our $CACHEURL //= "$ROOTURL/tgal-cache";
142 our $STATICURL //= "$ROOTURL/tgal-static";
143 our $SCRIPTURL;
144
145 export qw{$SRCURL};
146 our $SRCURL = "https://git.distorted.org.uk/~mdw/tgal/";
147
148 export qw{%SIZE};
149 our %SIZE = (smallthumb => 96,
150              medthumb => 144,
151              bigthumb => 228,
152              small => 480,
153              embed => 720,
154              view => 1200);
155
156 export qw{init};
157 my $initp = 0;
158 sub init () {
159   my $m = HTML::Mason::Request->instance;
160   my $r = $m->cgi_request;
161
162   $m->interp->set_escape(u => sub { my ($r) = @_; $$r = urlencode $$r; });
163
164   return unless !$initp;
165
166   $SCRIPTURL //= $r->subprocess_env("SCRIPT_NAME");
167   $initp = 1;
168 }
169
170 ###--------------------------------------------------------------------------
171 ### Temporary files.
172
173 export qw{clean_temp_files};
174 sub clean_temp_files () {
175   my $d;
176
177   eval { opendir $d, $TMP; };
178   if ($@) {
179     if ($@->isa("autodie::exception") && $@->errno == ENOENT) { return; }
180     else { die $@; }
181   }
182   my $now = time;
183   FILE: while (my $name = readdir $d) {
184     next FILE unless $name =~ /^t(\d+)\-/;
185     my $pid = $1;
186     next FILE if kill 0, $pid;
187     my $f = "$TMP/$name";
188     my $st = stat $name;
189     next FILE if $now - $st->mtime() < 300;
190     unlink $f;
191   }
192   closedir $d;
193 }
194
195 ###--------------------------------------------------------------------------
196 ### Scaled images.
197
198 my %ORIENT =
199   (1 => [0, 0],
200    2 => [0, 1],
201    3 => [2, 0],
202    4 => [2, 1],
203    5 => [3, 1],
204    6 => [1, 0],
205    7 => [1, 1],
206    8 => [3, 0]);
207
208 package TrivGal::Image {
209   use File::Path qw{make_path};
210   use File::stat;
211
212   sub new ($$) {
213     my ($cls, $path) = @_;
214     my $imgpath = "$IMGROOT/$path";
215     my $st = stat $imgpath or die "no image `$path'";
216     return bless {
217       path => $path, imgpath => $imgpath,
218       mtime => $st->mtime,
219       img => undef,
220       _wd => undef, _ht => undef,
221       sz => undef
222     }, $cls;
223   }
224
225   sub _getsz ($) {
226     my ($me) = @_;
227     return if defined $me->{_wd};
228
229     my ($wd, $ht, $err) = Image::Size::imgsize $me->{imgpath};
230     defined $wd or die "failed to read size of `$me->{path}': $err";
231     my $sz = $wd; if ($sz < $ht) { $sz = $ht; }
232     @$me{"_wd", "_ht", "sz"} = ($wd, $ht, $sz);
233   }
234
235   sub sz ($) { my ($me) = @_; $me->_getsz; return $me->{sz}; }
236
237   sub scale ($$;$) {
238     my ($me, $scale, $forcep) = @_;
239     my $m = HTML::Mason::Request->instance;
240
241     my $path = $me->{path};
242     my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
243     my $url;
244
245     if ($me->sz <= $sz)
246       { $url = $m->interp->apply_escapes("$IMGURL/$path", "u"); }
247     else {
248       my $tail = "scale.$sz/$path";
249       my $thumb = "$CACHE/$tail";
250       my $thumburl = $m->interp->apply_escapes("$CACHEURL/$tail", "u");
251
252       my $st = stat $thumb;
253       if ($st && $st->mtime > $me->{mtime})
254         { $url = $thumburl; }
255       elsif (!$forcep) {
256         $url =
257           $m->interp->apply_escapes("$SCRIPTURL/$path", "u") .
258           "?scale=$scale";
259       } else {
260         my ($dir, undef, $ext) = TrivGal::split_path $thumb;
261         my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
262
263         my $img = $me->{img};
264         unless (defined $img) {
265           my $exif = new Image::ExifTool;
266           $exif->ExtractInfo($me->{imgpath});
267           my $orient = $exif->GetValue("Orientation", "ValueConv");
268           $img = $me->{img} = Image::Imlib2->load($me->{imgpath});
269           if (defined $orient) {
270             my ($rot, $flip) = @{$ORIENT{$orient}};
271             if ($rot) { $img->image_orientate($rot); }
272             if ($flip) { $img->flip_horizontal(); }
273           }
274         }
275
276         my $sc = $sz/$me->sz;
277         my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
278
279         $scaled->image_set_format($ty->imlibfmt);
280         $scaled->set_quality(90);
281         my $new = "$TMP/t$$-$ext";
282         make_path $TMP, { mode => 0771 };
283         $scaled->save($new);
284         make_path $dir, { mode => 0771 };
285         rename $new, $thumb;
286         $url = $thumburl;
287       }
288     }
289
290     return $url;
291   }
292 }
293
294 ###--------------------------------------------------------------------------
295 ### Directory listings.
296
297 package TrivGal::Item {
298   sub new ($$) {
299     my ($cls, $name) = @_;
300     return bless { name => $name }, $cls;
301   }
302   sub name ($@) {
303     my ($me, @args) = @_;
304     return TrivGal::read_or_set $me, $me->{name}, @args;
305   }
306   sub comment ($@) {
307     my ($me, @args) = @_;
308     return TrivGal::read_or_set $me, $me->{comment}, @args;
309   }
310 }
311
312 export qw{listdir};
313 sub listdir ($) {
314   my ($path) = @_;
315   my (@d, @f);
316   my $ix = undef;
317
318   $path =~ s#/$##;
319   if (-f "$path/.tgal.index") {
320     open my $f, "<", "$path/.tgal.index";
321     my $item = undef;
322     my $comment = undef;
323     LINE: while (<$f>) {
324       chomp;
325       next LINE if /^\s*(\#|$)/;
326       if (s/^\s+//) {
327         die "no item" unless $item;
328         $comment = defined $comment ? $comment . "\n" . $_ : $_;
329       } else {
330         if ($item && $comment) { $item->comment($comment); }
331         my ($flags, $name, $c) =
332           /^ (?: ([-!]+) \s+)?          # flags
333              (\S+) \s*                  # filename
334              (\S | \S.*\S )?            # start of the comment
335              \s*
336              $/x;
337         my $indexp = $flags =~ /!/;
338         my $hidep = $flags =~ /-/;
339         $name = urldecode $name;
340         my $list;
341         $item = TrivGal::Item->new($name);
342         if ($name =~ m#/$#) {
343           $list = \@d;
344           die "can't index a folder" if $indexp;
345         } else {
346           $list = \@f;
347           my (undef, undef, $ext) = split_path $name;
348           die "unknown image type" unless $TYPE{lc $ext};
349           if ($indexp) {
350             die "two index images" if defined $ix;
351             $ix = $item;
352           }
353         }
354         $comment = $c;
355         push @$list, $item unless $hidep;
356       }
357     }
358     if ($item && $comment) { $item->comment($comment); }
359     close $f;
360   } else {
361     my $st = stat $path;
362     unless ($st->mode&0004) { return ([], [], undef); }
363
364     opendir $d, $path;
365     my @e = readdir $d;
366     closedir $d;
367
368     ENT: for my $e (sort @e) {
369       my (undef, undef, $ext) = split_path $e;
370       my $dotp = $e =~ /^\./;
371       my $st = stat "$path/$e";
372       my $list = undef;
373       if ($dotp) { }
374       elsif (-d $st) { $list = \@d; $e .= "/"; }
375       elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
376       $list and push @$list, TrivGal::Item->new($e);
377     }
378     $ix = $f[0] if @f;
379   }
380
381   return (\@d, \@f, $ix);
382 }
383
384 export qw{contents};
385 sub contents ($) {
386   my ($file) = @_;
387   my $contents = "";
388   my $f;
389   local $@;
390   eval { open $f, "<", "$file"; };
391   if ($@) {
392     if ($@->isa("autodie::exception") && $@->errno == ENOENT)
393       { return undef; }
394     die $@;
395   }
396   while (sysread $f, $buf, 16384) { $contents .= $buf; }
397   close $f;
398   return $contents;
399 }
400
401 export qw{find_covering_file};
402 sub find_covering_file ($$$) {
403   my ($top, $path, $name) = @_;
404   for (;;) {
405     my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
406     if ($path eq "") { return undef; }
407     if ($path =~ m#^(.*)/[^/]+/?#) { $path = $1; }
408     else { $path = ""; }
409   }
410 }
411
412 ###----- That's all, folks --------------------------------------------------
413
414 clean_temp_files;
415
416 1;