mason/.perl-lib/TrivGal.pm: Handle EXIF `Orientation'.
[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 User::pwent;
36 use POSIX;
37
38 our @EXPORT;
39 sub export (@) { push @EXPORT, @_; }
40
41 ###--------------------------------------------------------------------------
42 ### Internal utilities.
43
44 sub read_or_set ($\$@) {
45 my ($me, $ref, @args) = @_;
46 if (@args == 0) { return $$ref; }
47 elsif (@args == 1) { $$ref = $args[0]; return $me; }
48 elsif (@args > 1) { die "too many arguments"; }
49 }
50
51 ###--------------------------------------------------------------------------
52 ### Random utilities.
53
54 export qw{join_paths};
55 sub join_paths (@) {
56 my @p = @_;
57 my $p = "";
58 ELT: for my $e (@p) {
59 $e =~ s:^/{2,}:/:;
60 $e =~ s,([^/])/+$,$1,;
61 if ($e eq "") { next ELT; }
62 elsif ($p eq "" || $e =~ m,^/,) { $p = $e; }
63 else { $p = "$p/$e"; }
64 }
65 return $p;
66 }
67
68 export qw{split_path};
69 sub split_path ($) {
70 my ($path) = @_;
71
72 my ($dir, $base, $ext) = $path =~ m,^(?:(.*)/)?(?:([^/]*)\.)?([^./]*)$,;
73 if (defined $base) { $ext = ".$ext"; }
74 else { $base = $ext; $ext = ""; }
75 return ($dir, $base, $ext);
76 }
77
78 export qw{urlencode};
79 sub urlencode ($) {
80 my ($u) = @_;
81 $u =~ s:([^0-9a-zA-Z_./~-]):sprintf "%%%02x", ord $1:eg;
82 return $u;
83 }
84
85 export qw{urldecode};
86 sub urldecode ($) {
87 my ($u) = @_;
88 $u =~ s:\%([0-9a-fA-F]{2}):chr hex $1:eg;
89 return $u;
90 }
91
92 ###--------------------------------------------------------------------------
93 ### Image types.
94
95 our %TYPE;
96
97 package TrivGal::ImageType {
98 sub new ($$) {
99 my ($cls, $ext) = @_;
100 return $TYPE{$ext} = bless { ext => $ext }, $cls;
101 }
102 sub ext ($) {
103 my ($me, @args) = @_;
104 return $me->{ext};
105 }
106 sub mimetype ($@) {
107 my ($me, @args) = @_;
108 return TrivGal::read_or_set $me, $me->{mimetype}, @args;
109 }
110 sub imlibfmt ($@) {
111 my ($me, @args) = @_;
112 return TrivGal::read_or_set $me, $me->{imlibfmt}, @args;
113 }
114 }
115
116 TrivGal::ImageType->new(".jpg")->mimetype("image/jpeg")->imlibfmt("jpeg");
117 TrivGal::ImageType->new(".png")->mimetype("image/png")->imlibfmt("png");
118
119 ###--------------------------------------------------------------------------
120 ### Configuration.
121
122 export qw{$SCOPE $SUFFIX};
123 our $SCOPE //= $::SCOPE;
124 our $SUFFIX //= $::SUFFIX;
125
126 export qw{$IMGROOT $CACHE $TMP};
127 our $IMGROOT //= "$ENV{HOME}/publish/$SCOPE-html$SUFFIX/tgal-images";
128 our $CACHE //=
129 ($ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache") .
130 "/tgal/$SCOPE$SUFFIX";
131 our $TMP //= "$CACHE/tmp";
132
133 export qw{$ROOTURL $IMGURL $CACHEURL $STATICURL $SCRIPTURL};
134 my $user = getpwuid($>)->name;
135 our $ROOTURL //= "/~$user";
136 our $IMGURL //= "$ROOTURL/tgal-images";
137 our $CACHEURL //= "$ROOTURL/tgal-cache";
138 our $STATICURL //= "$ROOTURL/tgal-static";
139 our $SCRIPTURL;
140
141 export qw{%SIZE};
142 our %SIZE = (smallthumb => 96,
143 medthumb => 144,
144 bigthumb => 228,
145 view => 1200);
146
147 export qw{init};
148 my $initp = 0;
149 sub init () {
150 my $m = HTML::Mason::Request->instance;
151 my $r = $m->cgi_request;
152
153 $m->interp->set_escape(u => sub { my ($r) = @_; $$r = urlencode $$r; });
154
155 return unless !$initp;
156
157 $SCRIPTURL //= $r->subprocess_env("SCRIPT_NAME");
158 $initp = 1;
159 }
160
161 ###--------------------------------------------------------------------------
162 ### Temporary files.
163
164 export qw{clean_temp_files};
165 sub clean_temp_files () {
166 my $d;
167
168 eval { opendir $d, $TMP; };
169 if ($@) {
170 if ($@->isa("autodie::exception") && $@->errno == ENOENT) { return; }
171 else { die $@; }
172 }
173 my $now = time;
174 FILE: while (my $name = readdir $d) {
175 next FILE unless $name =~ /^t(\d+)\-/;
176 my $pid = $1;
177 next FILE if kill 0, $pid;
178 my $f = "$TMP/$name";
179 my $st = stat $name;
180 next FILE if $now - $st->mtime() < 300;
181 unlink $f;
182 }
183 closedir $d;
184 }
185
186 ###--------------------------------------------------------------------------
187 ### Scaled images.
188
189 my %ORIENT =
190 (1 => [0, 0],
191 2 => [0, 1],
192 3 => [2, 0],
193 4 => [2, 1],
194 5 => [3, 1],
195 6 => [1, 0],
196 7 => [1, 1],
197 8 => [3, 0]);
198
199 package TrivGal::Image {
200 use File::Path qw{make_path};
201 use File::stat;
202
203 sub new ($$) {
204 my ($cls, $path) = @_;
205 my $imgpath = "$IMGROOT/$path";
206 my $st = stat $imgpath or die "no image `$path'";
207 return bless {
208 path => $path,
209 mtime => $st->mtime,
210 img => undef
211 }, $cls;
212 }
213
214 sub scale ($$) {
215 my ($me, $scale) = @_;
216
217 my $path = $me->{path};
218 my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
219 my $thumb = "$CACHE/scale.$sz/$path";
220 my $thumburl = "$CACHEURL/scale.$sz/$path";
221 my $st = stat $thumb;
222 if (defined $st && $st->mtime > $me->{mtime}) { return $thumburl; }
223
224 my ($dir, $base, $ext) = TrivGal::split_path $thumb;
225 my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
226
227 my $img = $me->{img};
228 unless (defined $img) {
229 my $imgpath = "$IMGROOT/$path";
230 my $exif = new Image::ExifTool;
231 $exif->ExtractInfo($imgpath);
232 my $orient = $exif->GetValue("Orientation", "ValueConv");
233 $img = $me->{img} = Image::Imlib2->load($imgpath);
234 if (defined $orient) {
235 my ($rot, $flip) = @{$ORIENT{$orient}};
236 if ($rot) { $img->image_orientate($rot); }
237 if ($flip) { $img->flip_horizontal($rot); }
238 }
239 }
240
241 my ($wd, $ht) = ($img->width, $img->height);
242 my $max = $wd > $ht ? $wd : $ht;
243 if ($max <= $sz) { return "$IMGURL/$path"; }
244 my $sc = $sz/$max;
245 my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
246
247 $scaled->image_set_format($ty->imlibfmt);
248 $scaled->set_quality(90);
249 my $new = "$TMP/t${$}$ext";
250 make_path $TMP;
251 $scaled->save($new);
252 make_path $dir;
253 rename $new, $thumb;
254 return $thumburl;
255 }
256 }
257
258 ###--------------------------------------------------------------------------
259 ### Directory listings.
260
261 package TrivGal::Item {
262 sub new ($$) {
263 my ($cls, $name) = @_;
264 return bless { name => $name }, $cls;
265 }
266 sub name ($@) {
267 my ($me, @args) = @_;
268 return TrivGal::read_or_set $me, $me->{name}, @args;
269 }
270 sub comment ($@) {
271 my ($me, @args) = @_;
272 return TrivGal::read_or_set $me, $me->{comment}, @args;
273 }
274 }
275
276 export qw{listdir};
277 sub listdir ($) {
278 my ($path) = @_;
279 my (@d, @f);
280 my $ix = undef;
281
282 if (-f "$path/.tgal.index") {
283 open my $f, "<", "$path/.tgal.index";
284 my $item = undef;
285 my $comment = undef;
286 LINE: while (<$f>) {
287 chomp;
288 next LINE if /^\s*(\#|$)/;
289 if (s/^\s+//) {
290 die "no item" unless $item;
291 $comment = defined $comment ? $comment . "\n" . $_ : $_;
292 } else {
293 if ($item && $comment) { $item->comment($comment); }
294 my ($indexp, $name, $c) = /(!\s+)?(\S+)\s*(\S|\S.*\S)?\s*$/;
295 $name = urldecode $name;
296 my $list;
297 if ($name =~ m!/$!) {
298 $list = \@d;
299 die "can't index a folder" if $indexp;
300 } else {
301 $list = \@f;
302 my ($dir, $base, $ext) = TrivGal::split_path $name;
303 die "unknown image type" unless $TYPE{lc $ext};
304 if ($indexp) {
305 die "two index images" if defined $ix;
306 $ix = $item;
307 }
308 }
309 $item = TrivGal::Item->new($name);
310 $comment = $c;
311 push @$list, $item;
312 }
313 }
314 if ($item && $comment) { $item->comment($comment); }
315 close $f;
316 } else {
317 my $st = stat "$path/$e";
318 unless ($st->mode&0004) { return ([], [], undef); }
319
320 opendir $d, $path;
321 my @e = readdir $d;
322 closedir $d;
323
324 ENT: for my $e (sort @e) {
325 my ($dir, $base, $ext) = split_path $e;
326 my $dotp = $e =~ /^\./;
327 my $st = stat "$path/$e";
328 my $list = undef;
329 if ($dotp) { }
330 elsif (-d $st) { $list = \@d; }
331 elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
332 $list and push @$list, TrivGal::Item->new($e);
333 }
334 $ix = $f[0] if @f;
335 }
336
337 return (\@d, \@f, $ix);
338 }
339
340 export qw{contents};
341 sub contents ($) {
342 my ($file) = @_;
343 my $contents = "";
344 my $f;
345 local $@;
346 eval { open $f, "<", "$file"; };
347 if ($@) {
348 if ($@->isa("autodie::exception") && $@->errno == ENOENT)
349 { return undef; }
350 die $@;
351 }
352 while (sysread $f, $buf, 16384) { $contents .= $buf; }
353 close $f;
354 return $contents;
355 }
356
357 export qw{find_covering_file};
358 sub find_covering_file ($$$) {
359 my ($top, $path, $name) = @_;
360 for (;;) {
361 my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
362 if ($path eq "") { return undef; }
363 if ($path =~ m!^(.*)/[^/]+/?!) { $path = $1; }
364 else { $path = ""; }
365 }
366 }
367
368 ###----- That's all, folks --------------------------------------------------
369
370 clean_temp_files;
371
372 1;