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