chiark / gitweb /
mason/.perl-lib/TrivGal.pm (Image::scale): Factor out thumbnail path tail.
[tgal] / mason / .perl-lib / TrivGal.pm
CommitLineData
6ac5dde2
MW
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
26package TrivGal;
27
28use autodie qw{:all};
29
30use Errno;
31use Exporter qw{import};
6ac5dde2 32use File::stat;
bda837fc 33use Image::ExifTool qw{};
6ac5dde2 34use Image::Imlib2;
8b97a4e3 35use Image::Size qw{};
6ac5dde2
MW
36use User::pwent;
37use POSIX;
38
39our @EXPORT;
40sub export (@) { push @EXPORT, @_; }
41
42###--------------------------------------------------------------------------
43### Internal utilities.
44
45sub 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
55export qw{join_paths};
56sub join_paths (@) {
57 my @p = @_;
58 my $p = "";
59 ELT: for my $e (@p) {
e9eac06d
MW
60 $e =~ s#^/{2,}#/#;
61 $e =~ s#([^/])/+$#$1#;
6ac5dde2 62 if ($e eq "") { next ELT; }
e9eac06d 63 elsif ($p eq "" || $e =~ m#^/#) { $p = $e; }
6ac5dde2
MW
64 else { $p = "$p/$e"; }
65 }
66 return $p;
67}
68
69export qw{split_path};
70sub split_path ($) {
71 my ($path) = @_;
72
9fc5e8c1
MW
73 my ($dir, $base, $ext) =
74 $path =~ m#^ (?: (.*) /)?
75 (?: ([^/]*) \.)?
76 ([^./]*) $#x;
6ac5dde2
MW
77 if (defined $base) { $ext = ".$ext"; }
78 else { $base = $ext; $ext = ""; }
79 return ($dir, $base, $ext);
80}
81
82export qw{urlencode};
83sub urlencode ($) {
84 my ($u) = @_;
e9eac06d 85 $u =~ s#([^0-9a-zA-Z_./~-])#sprintf "%%%02x", ord $1#eg;
6ac5dde2
MW
86 return $u;
87}
88
89export qw{urldecode};
90sub urldecode ($) {
91 my ($u) = @_;
e9eac06d 92 $u =~ s#\%([0-9a-fA-F]{2})#chr hex $1#eg;
6ac5dde2
MW
93 return $u;
94}
95
96###--------------------------------------------------------------------------
97### Image types.
98
99our %TYPE;
100
101package 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 }
65e4ebfd 118}
6ac5dde2
MW
119
120TrivGal::ImageType->new(".jpg")->mimetype("image/jpeg")->imlibfmt("jpeg");
121TrivGal::ImageType->new(".png")->mimetype("image/png")->imlibfmt("png");
122
123###--------------------------------------------------------------------------
124### Configuration.
125
126export qw{$SCOPE $SUFFIX};
127our $SCOPE //= $::SCOPE;
128our $SUFFIX //= $::SUFFIX;
129
130export qw{$IMGROOT $CACHE $TMP};
131our $IMGROOT //= "$ENV{HOME}/publish/$SCOPE-html$SUFFIX/tgal-images";
132our $CACHE //=
133 ($ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache") .
134 "/tgal/$SCOPE$SUFFIX";
135our $TMP //= "$CACHE/tmp";
136
137export qw{$ROOTURL $IMGURL $CACHEURL $STATICURL $SCRIPTURL};
138my $user = getpwuid($>)->name;
139our $ROOTURL //= "/~$user";
140our $IMGURL //= "$ROOTURL/tgal-images";
141our $CACHEURL //= "$ROOTURL/tgal-cache";
142our $STATICURL //= "$ROOTURL/tgal-static";
143our $SCRIPTURL;
144
a38a867d
MW
145export qw{$SRCURL};
146our $SRCURL = "https://git.distorted.org.uk/~mdw/tgal/";
147
6ac5dde2 148export qw{%SIZE};
1408b7a2
MW
149our %SIZE = (smallthumb => 96,
150 medthumb => 144,
151 bigthumb => 228,
40c686c2
MW
152 small => 480,
153 embed => 720,
1408b7a2 154 view => 1200);
6ac5dde2
MW
155
156export qw{init};
157my $initp = 0;
158sub 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
173export qw{clean_temp_files};
174sub 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
bda837fc
MW
198my %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
4e74ddf4
MW
208package 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 {
4fcd273f 217 path => $path, imgpath => $imgpath,
4e74ddf4 218 mtime => $st->mtime,
8b97a4e3
MW
219 img => undef,
220 _wd => undef, _ht => undef,
221 sz => undef
4e74ddf4
MW
222 }, $cls;
223 }
224
8b97a4e3
MW
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
784bdf8f
MW
237 sub scale ($$;$) {
238 my ($me, $scale, $forcep) = @_;
1b3d6791 239 my $m = HTML::Mason::Request->instance;
4e74ddf4
MW
240
241 my $path = $me->{path};
242 my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
373818eb
MW
243 if ($me->sz <= $sz)
244 { return $m->interp->apply_escapes("$IMGURL/$path", "u"); }
245
2c1f91c4
MW
246 my $tail = "scale.$sz/$path";
247 my $thumb = "$CACHE/$tail";
248 my $thumburl = $m->interp->apply_escapes("$CACHEURL/$tail", "u");
4e74ddf4
MW
249 my $st = stat $thumb;
250 if (defined $st && $st->mtime > $me->{mtime}) { return $thumburl; }
784bdf8f
MW
251 return
252 $m->interp->apply_escapes("$SCRIPTURL/$path", "u") . "?scale=$scale"
253 unless $forcep;
4e74ddf4
MW
254
255 my ($dir, $base, $ext) = TrivGal::split_path $thumb;
256 my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
257
258 my $img = $me->{img};
259 unless (defined $img) {
bda837fc 260 my $exif = new Image::ExifTool;
4fcd273f 261 $exif->ExtractInfo($me->{imgpath});
bda837fc 262 my $orient = $exif->GetValue("Orientation", "ValueConv");
4fcd273f 263 $img = $me->{img} = Image::Imlib2->load($me->{imgpath});
bda837fc
MW
264 if (defined $orient) {
265 my ($rot, $flip) = @{$ORIENT{$orient}};
266 if ($rot) { $img->image_orientate($rot); }
f6158607 267 if ($flip) { $img->flip_horizontal(); }
bda837fc 268 }
4e74ddf4
MW
269 }
270
8b97a4e3 271 my $sc = $sz/$me->sz;
4e74ddf4
MW
272 my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
273
274 $scaled->image_set_format($ty->imlibfmt);
275 $scaled->set_quality(90);
227d23a0 276 my $new = "$TMP/t$$-$ext";
2306963b 277 make_path $TMP, { mode => 0771 };
4e74ddf4 278 $scaled->save($new);
2306963b 279 make_path $dir, { mode => 0771 };
4e74ddf4
MW
280 rename $new, $thumb;
281 return $thumburl;
282 }
6ac5dde2
MW
283}
284
285###--------------------------------------------------------------------------
286### Directory listings.
287
288package TrivGal::Item {
289 sub new ($$) {
290 my ($cls, $name) = @_;
291 return bless { name => $name }, $cls;
292 }
293 sub name ($@) {
294 my ($me, @args) = @_;
295 return TrivGal::read_or_set $me, $me->{name}, @args;
296 }
297 sub comment ($@) {
298 my ($me, @args) = @_;
299 return TrivGal::read_or_set $me, $me->{comment}, @args;
300 }
65e4ebfd 301}
6ac5dde2
MW
302
303export qw{listdir};
304sub listdir ($) {
305 my ($path) = @_;
306 my (@d, @f);
307 my $ix = undef;
308
24f4eac3 309 $path =~ s#/$##;
6ac5dde2
MW
310 if (-f "$path/.tgal.index") {
311 open my $f, "<", "$path/.tgal.index";
312 my $item = undef;
313 my $comment = undef;
314 LINE: while (<$f>) {
315 chomp;
316 next LINE if /^\s*(\#|$)/;
317 if (s/^\s+//) {
318 die "no item" unless $item;
319 $comment = defined $comment ? $comment . "\n" . $_ : $_;
320 } else {
321 if ($item && $comment) { $item->comment($comment); }
9940cc5a 322 my ($flags, $name, $c) =
6e51720c 323 /^ (?: ([-!]+) \s+)? # flags
9fc5e8c1
MW
324 (\S+) \s* # filename
325 (\S | \S.*\S )? # start of the comment
326 \s*
327 $/x;
9940cc5a 328 my $indexp = $flags =~ /!/;
6e51720c 329 my $hidep = $flags =~ /-/;
6ac5dde2
MW
330 $name = urldecode $name;
331 my $list;
0485371e 332 $item = TrivGal::Item->new($name);
e9eac06d 333 if ($name =~ m#/$#) {
6ac5dde2
MW
334 $list = \@d;
335 die "can't index a folder" if $indexp;
336 } else {
337 $list = \@f;
b39b2681 338 my ($dir, $base, $ext) = split_path $name;
6ac5dde2
MW
339 die "unknown image type" unless $TYPE{lc $ext};
340 if ($indexp) {
341 die "two index images" if defined $ix;
342 $ix = $item;
343 }
344 }
6ac5dde2 345 $comment = $c;
6e51720c 346 push @$list, $item unless $hidep;
6ac5dde2
MW
347 }
348 }
349 if ($item && $comment) { $item->comment($comment); }
350 close $f;
351 } else {
ebe19115 352 my $st = stat $path;
32fc7001
MW
353 unless ($st->mode&0004) { return ([], [], undef); }
354
6ac5dde2
MW
355 opendir $d, $path;
356 my @e = readdir $d;
357 closedir $d;
358
359 ENT: for my $e (sort @e) {
360 my ($dir, $base, $ext) = split_path $e;
361 my $dotp = $e =~ /^\./;
362 my $st = stat "$path/$e";
363 my $list = undef;
32fc7001 364 if ($dotp) { }
24f4eac3 365 elsif (-d $st) { $list = \@d; $e .= "/"; }
6ac5dde2
MW
366 elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
367 $list and push @$list, TrivGal::Item->new($e);
368 }
369 $ix = $f[0] if @f;
370 }
371
372 return (\@d, \@f, $ix);
373}
374
375export qw{contents};
376sub contents ($) {
377 my ($file) = @_;
378 my $contents = "";
379 my $f;
380 local $@;
381 eval { open $f, "<", "$file"; };
382 if ($@) {
383 if ($@->isa("autodie::exception") && $@->errno == ENOENT)
384 { return undef; }
385 die $@;
386 }
387 while (sysread $f, $buf, 16384) { $contents .= $buf; }
388 close $f;
389 return $contents;
390}
391
392export qw{find_covering_file};
393sub find_covering_file ($$$) {
394 my ($top, $path, $name) = @_;
395 for (;;) {
396 my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
397 if ($path eq "") { return undef; }
e9eac06d 398 if ($path =~ m#^(.*)/[^/]+/?#) { $path = $1; }
6ac5dde2
MW
399 else { $path = ""; }
400 }
401}
402
403###----- That's all, folks --------------------------------------------------
404
405clean_temp_files;
406
4071;