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