chiark / gitweb /
ea3b47a0b1abbbd72764576a371d1879d087cd93
[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{$SRCURL};
142 our $SRCURL = "https://git.distorted.org.uk/~mdw/tgal/";
143
144 export qw{%SIZE};
145 our %SIZE = (smallthumb => 96,
146              medthumb => 144,
147              bigthumb => 228,
148              view => 1200);
149
150 export qw{init};
151 my $initp = 0;
152 sub init () {
153   my $m = HTML::Mason::Request->instance;
154   my $r = $m->cgi_request;
155
156   $m->interp->set_escape(u => sub { my ($r) = @_; $$r = urlencode $$r; });
157
158   return unless !$initp;
159
160   $SCRIPTURL //= $r->subprocess_env("SCRIPT_NAME");
161   $initp = 1;
162 }
163
164 ###--------------------------------------------------------------------------
165 ### Temporary files.
166
167 export qw{clean_temp_files};
168 sub clean_temp_files () {
169   my $d;
170
171   eval { opendir $d, $TMP; };
172   if ($@) {
173     if ($@->isa("autodie::exception") && $@->errno == ENOENT) { return; }
174     else { die $@; }
175   }
176   my $now = time;
177   FILE: while (my $name = readdir $d) {
178     next FILE unless $name =~ /^t(\d+)\-/;
179     my $pid = $1;
180     next FILE if kill 0, $pid;
181     my $f = "$TMP/$name";
182     my $st = stat $name;
183     next FILE if $now - $st->mtime() < 300;
184     unlink $f;
185   }
186   closedir $d;
187 }
188
189 ###--------------------------------------------------------------------------
190 ### Scaled images.
191
192 my %ORIENT =
193   (1 => [0, 0],
194    2 => [0, 1],
195    3 => [2, 0],
196    4 => [2, 1],
197    5 => [3, 1],
198    6 => [1, 0],
199    7 => [1, 1],
200    8 => [3, 0]);
201
202 package TrivGal::Image {
203   use File::Path qw{make_path};
204   use File::stat;
205
206   sub new ($$) {
207     my ($cls, $path) = @_;
208     my $imgpath = "$IMGROOT/$path";
209     my $st = stat $imgpath or die "no image `$path'";
210     return bless {
211       path => $path,
212       mtime => $st->mtime,
213       img => undef
214     }, $cls;
215   }
216
217   sub scale ($$) {
218     my ($me, $scale) = @_;
219
220     my $path = $me->{path};
221     my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
222     my $thumb = "$CACHE/scale.$sz/$path";
223     my $thumburl = "$CACHEURL/scale.$sz/$path";
224     my $st = stat $thumb;
225     if (defined $st && $st->mtime > $me->{mtime}) { return $thumburl; }
226
227     my ($dir, $base, $ext) = TrivGal::split_path $thumb;
228     my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
229
230     my $img = $me->{img};
231     unless (defined $img) {
232       my $imgpath = "$IMGROOT/$path";
233       my $exif = new Image::ExifTool;
234       $exif->ExtractInfo($imgpath);
235       my $orient = $exif->GetValue("Orientation", "ValueConv");
236       $img = $me->{img} = Image::Imlib2->load($imgpath);
237       if (defined $orient) {
238         my ($rot, $flip) = @{$ORIENT{$orient}};
239         if ($rot) { $img->image_orientate($rot); }
240         if ($flip) { $img->flip_horizontal(); }
241       }
242     }
243
244     my ($wd, $ht) = ($img->width, $img->height);
245     my $max = $wd > $ht ? $wd : $ht;
246     if ($max <= $sz) { return "$IMGURL/$path"; }
247     my $sc = $sz/$max;
248     my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
249
250     $scaled->image_set_format($ty->imlibfmt);
251     $scaled->set_quality(90);
252     my $new = "$TMP/t${$}$ext";
253     make_path $TMP;
254     $scaled->save($new);
255     make_path $dir;
256     rename $new, $thumb;
257     return $thumburl;
258   }
259 }
260
261 ###--------------------------------------------------------------------------
262 ### Directory listings.
263
264 package TrivGal::Item {
265   sub new ($$) {
266     my ($cls, $name) = @_;
267     return bless { name => $name }, $cls;
268   }
269   sub name ($@) {
270     my ($me, @args) = @_;
271     return TrivGal::read_or_set $me, $me->{name}, @args;
272   }
273   sub comment ($@) {
274     my ($me, @args) = @_;
275     return TrivGal::read_or_set $me, $me->{comment}, @args;
276   }
277 }
278
279 export qw{listdir};
280 sub listdir ($) {
281   my ($path) = @_;
282   my (@d, @f);
283   my $ix = undef;
284
285   if (-f "$path/.tgal.index") {
286     open my $f, "<", "$path/.tgal.index";
287     my $item = undef;
288     my $comment = undef;
289     LINE: while (<$f>) {
290       chomp;
291       next LINE if /^\s*(\#|$)/;
292       if (s/^\s+//) {
293         die "no item" unless $item;
294         $comment = defined $comment ? $comment . "\n" . $_ : $_;
295       } else {
296         if ($item && $comment) { $item->comment($comment); }
297         my ($indexp, $name, $c) = /(!\s+)?(\S+)\s*(\S|\S.*\S)?\s*$/;
298         $name = urldecode $name;
299         my $list;
300         if ($name =~ m!/$!) {
301           $list = \@d;
302           die "can't index a folder" if $indexp;
303         } else {
304           $list = \@f;
305           my ($dir, $base, $ext) = TrivGal::split_path $name;
306           die "unknown image type" unless $TYPE{lc $ext};
307           if ($indexp) {
308             die "two index images" if defined $ix;
309             $ix = $item;
310           }
311         }
312         $item = TrivGal::Item->new($name);
313         $comment = $c;
314         push @$list, $item;
315       }
316     }
317     if ($item && $comment) { $item->comment($comment); }
318     close $f;
319   } else {
320     my $st = stat "$path/$e";
321     unless ($st->mode&0004) { return ([], [], undef); }
322
323     opendir $d, $path;
324     my @e = readdir $d;
325     closedir $d;
326
327     ENT: for my $e (sort @e) {
328       my ($dir, $base, $ext) = split_path $e;
329       my $dotp = $e =~ /^\./;
330       my $st = stat "$path/$e";
331       my $list = undef;
332       if ($dotp) { }
333       elsif (-d $st) { $list = \@d; }
334       elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
335       $list and push @$list, TrivGal::Item->new($e);
336     }
337     $ix = $f[0] if @f;
338   }
339
340   return (\@d, \@f, $ix);
341 }
342
343 export qw{contents};
344 sub contents ($) {
345   my ($file) = @_;
346   my $contents = "";
347   my $f;
348   local $@;
349   eval { open $f, "<", "$file"; };
350   if ($@) {
351     if ($@->isa("autodie::exception") && $@->errno == ENOENT)
352       { return undef; }
353     die $@;
354   }
355   while (sysread $f, $buf, 16384) { $contents .= $buf; }
356   close $f;
357   return $contents;
358 }
359
360 export qw{find_covering_file};
361 sub find_covering_file ($$$) {
362   my ($top, $path, $name) = @_;
363   for (;;) {
364     my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
365     if ($path eq "") { return undef; }
366     if ($path =~ m!^(.*)/[^/]+/?!) { $path = $1; }
367     else { $path = ""; }
368   }
369 }
370
371 ###----- That's all, folks --------------------------------------------------
372
373 clean_temp_files;
374
375 1;