]> git.decadent.org.uk Git - memories.git/blob - Memories/Photo.pm
Start to do some more with the metadata. References #1, #2.
[memories.git] / Memories / Photo.pm
1 package Memories::Photo;
2 use strict;
3 use Carp qw(cluck confess);
4 use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
5 use Time::Piece;
6 use Image::Seek;
7 use constant PAGER_SYNTAX => "LimitXY";
8 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y));
9 __PACKAGE__->untaint_columns(printable => [qw/title/]);
10 __PACKAGE__->columns(TEMP => qw/exif_object/);
11 __PACKAGE__->set_sql(recent => q{
12 SELECT __ESSENTIAL__
13 FROM __TABLE__
14 ORDER BY uploaded DESC
15 LIMIT 4
16 });
17
18 __PACKAGE__->has_many(comments => "Memories::Comment");
19 __PACKAGE__->has_a(uploader => "Memories::User");
20 __PACKAGE__->has_a(uploaded => "Time::Piece",
21     inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
22     deflate => 'datetime',
23 );
24
25 sub do_upload :Exported {
26     my ($self, $r) = @_;
27     my %upload = $r->upload("photo");
28
29     # XXX Stop anonymous uploads!
30     my $photo = $self->create({
31         uploader => $r->user,
32         uploaded => Time::Piece->new(),
33         title => $r->params->{title}
34     });
35
36     # Dump content
37     if (!open OUT, ">". $photo->path("file")) {
38         die "Can't write ".$photo->path("file")." because $!";
39     }
40     # XXX Check it's a JPEG, etc.
41     # XXX Unzip ZIP file
42     print OUT $upload{content};
43     close OUT;
44     my ($x, $y) = dim(image_info($photo->path));
45     $photo->x($x); $photo->y($y);
46
47     # Rotate?
48     $photo->unrotate(); 
49     if (!$photo->title){ 
50         $photo->title($photo->title_exif || $upload{filename});
51     }
52
53     $photo->make_thumb;
54     $photo->add_tags($r->{params}{tags});
55     $photo->add_to_imageseek_library;
56     Memories->zap_cache();
57
58     # Add system tags here
59     my $tag = "date:".$photo->shot->ymd;
60     $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
61
62     # Set it up to go again
63     $r->objects([$photo]);
64     $r->template("view");
65     $r->message("Thanks for the upload! ".
66         ($r->{params}{tags} ? "" 
67         : "Don't forget to <a href=\"?".$r->config->uri_base."photo/view/".$photo->id."?active=tagedit\">tag your photo</a>"
68         )
69     ); 
70 }
71
72 sub view :Exported {
73     my ($self, $r) = @_;
74     if ($r->{session}{last_search}) {
75         my $photo = $r->{objects}[0];
76         # This is slightly inefficient
77         my @search = split/,/, $r->{session}{last_search};
78         my $found = -1;
79         for my $i (0..$#search) {
80             next unless $photo->id == $search[$i];
81             $found = $i;
82         }
83         return unless $found > -1;
84         $r->{template_args}{next} = $self->retrieve($search[$found+1]) 
85             if $found+1 <= $#search;
86         $r->{template_args}{prev} = $self->retrieve($search[$found-1])
87             if $found-1 >= 0;
88     }
89 }
90 sub upload :Exported {}
91
92 use Class::DBI::Plugin::Pager;
93 use Class::DBI::Plugin::AbstractCount;
94
95 sub recent :Exported {
96     my ($self, $r) = @_;
97     my $page = $r->params->{page} || 1;
98     my $pager = $self->pager(
99         per_page => Memories->config->{photos_per_page}, 
100         page => $page,
101         syntax => PAGER_SYNTAX,
102         order_by => "uploaded desc"
103     );
104     $r->objects([$pager->retrieve_all ]);
105     $r->{template_args}{pager} = $pager;
106     $r->last_search;
107 }
108
109 sub add_comment :Exported {
110     my ($self, $r, $photo) = @_;
111     $r->template("view");
112     $r->objects->[0]->add_to_comments({
113         name => $r->params->{name},
114         content => $r->params->{content}
115     });
116 }
117
118 sub format { 
119     "jpg" # For now
120
121
122 use Cache::MemoryCache;
123 use Image::Info qw(dim image_info);
124 use Image::ExifTool;
125 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
126
127 sub add_to_imageseek_library {
128     my $self = shift;
129     Image::Seek::cleardb();
130     my $img = Image::Imlib2->load($self->path("file"));
131
132     Image::Seek::add_image($img, $self->id);
133     # Merge this new one into the main database; there is a bit of a
134     # race condition here. XXX
135     Image::Seek::loaddb(Memories->config->{image_seek});
136     Image::Seek::savedb(Memories->config->{image_seek});
137 }
138
139 sub recommended_tags {
140     my $self = shift;
141     my %tags = map { $_->name => $_ }
142                map { $_->tags } 
143                $self->find_similar(3);
144     values %tags;
145 }
146
147 sub find_similar {
148     my ($self, $count) = @_;
149     Image::Seek::cleardb();
150     Image::Seek::loaddb(Memories->config->{image_seek});
151     my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
152     shift @res; # $self
153     map { $self->retrieve($_) } @res;
154 }
155
156 sub unrotate {
157     my $self = shift;
158     my $orient = $self->exif_info->{EXIF}->{Orientation};
159     return if $orient !~/Rotate (\d+)/i;
160     my $steps = $1/90;
161     my $img = Image::Imlib2->load($self->path("file"));
162     $img->image_orientate($steps);
163     $img->save($self->path("file"));
164 }
165
166 sub exif_info {
167     my $self = shift;
168     my $info = $self->exif_object;
169     return $info if $info;
170     # Get it from the Cache
171     if (!($info = $cache->get($self->id))) {
172         # Create it
173         $info = $self->_exif_info;
174         $cache->set($self->id, $info);
175     }
176     $self->exif_object($info);
177     $info;
178 }
179
180 my %banned_tags = map { $_ => 1 }
181     qw( CodedCharacterSet ApplicationRecordVersion );
182
183 sub _exif_info {
184     my $exifTool = new Image::ExifTool;
185     $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
186     my $info = $exifTool->ImageInfo(shift->path);
187     my $hash = {};
188     foreach my $tag ($exifTool->GetFoundTags('Group0')) {
189         next if $banned_tags{$tag};
190          my $group = $exifTool->GetGroup($tag);
191          my $val = $info->{$tag};
192          next if ref $val eq 'SCALAR';
193          next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
194          $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
195     }
196     return $hash;
197 }
198
199 # XXX Cache this
200 sub dimensions { join "x", $_[0]->x, $_[0]->y }
201
202 sub is_bigger {
203     my ($self, $size) = @_;
204     return 1 if $size eq "full";
205     my ($w, $h) = ($self->x, $self->y);
206     my ($w2, $h2) = split /x/, $size;
207     return 1 if $w > $w2 or $h > $h2;
208     return 0;
209 }
210
211 sub sized_url { # Use this rather than ->path from TT
212     my ($self, $size) = @_;
213     my $url = Memories->config->{data_store_external};
214     my $resized = Memories->config->{sizes}->[$size];
215     if (!$resized) { cluck "Asked for crazy size $size"; return; }
216     if ($resized eq "full") { return $self->path("url") }
217     $self->scale($resized) 
218         unless -e $self->path( file => $resized );
219     return $self->path(url => $resized);
220 }
221
222 sub path { 
223     my ($self, $is_url, $scale) = @_;
224     my $path =
225         Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
226     if ($scale) { $path .= "$scale/" }
227     # Make dir if it doesn't exist, save trouble later
228     use File::Path;
229     if ($is_url ne "url") {mkpath($path);}
230     $path .= $self->id.".".$self->format;
231     return $path;
232 }
233
234 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
235 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
236
237 use Image::Imlib2;
238 sub scale {
239     my ($self, $scale, $swap) = @_;
240     my ($x, $y) = split /x/, $scale;
241     # Find out smaller axis
242     my ($cur_x, $cur_y) = ($self->x, $self->y);
243     if (!$swap) {
244         if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
245     } else {
246         if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
247     }
248     my $img = Image::Imlib2->load($self->path("file"));
249     unless ($img) {
250         cluck "Couldn't open image file ".$self->path("file");
251         return;
252     }
253     $img = $img->create_scaled_image($x, $y);
254     $img->image_set_format("jpeg");
255     my $file = $self->path( file => $scale );
256     $img->save($file);
257     if ($!) {
258         cluck "Couldn't write image file $file ($!)"; 
259         return;
260     }
261 }
262
263 use Text::Balanced qw(extract_multiple extract_quotelike);
264 sub edit_tags :Exported {
265     my ($self, $r) = @_;
266     my $photo = $r->objects->[0];
267     my %params = %{$r->params};
268     for (keys %params) { 
269         next unless /delete_(\d+)/;
270         my $tagging = Memories::Tagging->retrieve($1) or next;
271         next unless $tagging->photo->id == $photo->id;
272         $tagging->delete;
273     }
274     $photo->add_tags($params{newtags});
275     $r->template("view");
276 }
277
278 sub add_tags {
279     my ($photo, $tagstring) = @_;
280
281     for my $tag (map { s/^"|"$//g; $_} extract_multiple(lc $tagstring, [ \&extract_quotelike, qr/([^\s]+)/ ], undef,1)) {
282         $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
283     }
284 }
285
286 # Work out some common properties from a set of potential photo metadata
287 # tags
288 sub _grovel_metadata {
289     my ($self, @tags) = @_;
290     my %md = map {%$_} values %{$self->exif_info};
291     for (@tags) {
292         if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
293     }
294     return;
295 }
296
297 sub shot {
298     my $self = shift;
299     my $dt = $self->_grovel_metadata(
300         'Shooting Date/Time',
301         'Date/Time Of Digitization',
302         'Date/Time Of Last Modification'
303     );
304     if (!$dt) { return $self->uploaded }
305     return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
306 }
307
308 sub description {
309     shift->_grovel_metadata(
310         'Description', 'Image Description', 'Caption-Abstract'
311     );
312 }
313
314 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
315 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
316 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
317 1;