+# Simple Photo Gallery: Image Hashes
+# (c) 2015 Martin Mares <mj@ucw.cz>
+
+package UCW::Gallery::Hashes;
+
+use strict;
+use warnings;
+
+use File::stat ();
+use Digest::SHA;
+
+sub new {
+ my ($class, $gal) = @_;
+ my $self = { gal => $gal };
+
+ if ($gal->get('CacheHashes') && -f 'gallery.cache') {
+ print "Loading gallery.cache\n";
+ $self->{cache} = $gal->read_meta('gallery.cache');
+ } else {
+ $self->{cache} = {};
+ }
+
+ return bless $self, $class;
+}
+
+sub write {
+ my ($self) = @_;
+ my $gal = $self->{gal};
+ if ($gal->get('CacheHashes')) {
+ print "Writing gallery.cache\n";
+ $gal->write_meta('gallery.cache', $self->{cache});
+ }
+}
+
+sub hash_image {
+ my ($self, $path) = @_;
+ my $cache = $self->{cache};
+
+ my $st = File::stat::stat($path) or die "Cannot access $path: $!\n";
+ my $key_text = join(":", $path, $st->dev, $st->ino, $st->mtime);
+ my $key = Digest::SHA->sha1_base64($key_text);
+
+ if (!exists $cache->{$key}) {
+ my $sha = Digest::SHA->new(1);
+ $sha->addfile($path) or die "Cannot hash $path\n";
+ $cache->{$key} = substr($sha->hexdigest, 0, 16);
+ }
+ return $cache->{$key};
+}
+
+42;