]> git.decadent.org.uk Git - memories.git/blob - Memories/Photo.pm
I *think* this fixes #18.
[memories.git] / Memories / Photo.pm
1 package Memories::Photo;
2 use Apache2::Upload;
3 use File::Basename;
4 use File::Copy;
5 use Archive::Any;
6 use File::Temp qw(tempdir tmpnam);
7 use File::Path qw(rmtree);
8 use File::Find;
9 use File::MMagic;
10 use strict;
11 use Carp qw(cluck confess);
12 use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
13 use constant INTERESTINGNESS_ALGORITHM => '((rating+3)/(rated+1))*(1+rated/hit_count)*(1+hit_count/(select max(hit_count) from photo))';
14 use Time::Piece;
15 use Image::Seek;
16 use constant PAGER_SYNTAX => "LimitXY";
17 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count format));
18 __PACKAGE__->untaint_columns(printable => [qw/title/]);
19 __PACKAGE__->columns(TEMP => qw/exif_object/);
20
21 BEGIN {
22 my %order_by = (
23      recent => "uploaded",
24      popular => "hit_count",
25      loved => "rating/(1+rated)",
26      interesting => INTERESTINGNESS_ALGORITHM,
27      random => "rand()"
28 );
29
30 while (my($label, $how) = each %order_by) {
31     __PACKAGE__->set_sql($label => qq{
32     SELECT __ESSENTIAL__
33     FROM __TABLE__
34     ORDER BY $how DESC
35     LIMIT 4
36     });
37     no strict;
38     *$label = sub {
39         my ($self, $r) = @_;
40         $self->view_paged_ordered($r, "$how desc");
41     };
42     __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
43 }
44 }
45 __PACKAGE__->has_many(comments => "Memories::Comment");
46 __PACKAGE__->has_a(uploader => "Memories::User");
47 __PACKAGE__->has_a(uploaded => "Time::Piece",
48     inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
49     deflate => 'datetime',
50 );
51
52 sub do_upload :Exported {
53     my ($self, $r) = @_;
54     my $upload = $r->{ar}->upload("photo");
55     # Check $self->type
56     my @photos = ($self->upload_file($r, $upload->tempname, $upload->filename));
57     my @quarantined = grep { !$_->tags } @photos;
58     # Set it up to go again
59     if (@quarantined) { 
60         $r->{session}{quarantined} = join ",", sort map { $_->id} @quarantined;
61         $r->objects(\@quarantined);
62         $r->template("quarantine");
63         return;
64     }
65     $r->objects(\@photos);
66     if (@photos == 0) { $r->template("upload"); return  }
67     if (@photos > 1) { $r->template("list") } 
68     else { $r->template("view"); }
69     $r->message("Thanks for the upload!"); 
70 }
71
72 sub quarantine :Exported {
73     my ($self, $r) = @_;
74     my @quarantined = split /,/, $r->{session}{quarantined};
75     my %q = map { $_ => 1 } @quarantined;
76     for (map /(\d+)/,grep /tags\d+/, keys %{$r->{params}}) {
77         my $tags = $r->{params}{"tags$_"};
78         next unless $tags;
79         if (my $photo = $self->retrieve($_)) {
80             $photo->add_tags($tags);
81             delete $q{$_};
82         }
83     }
84     $r->{session}{quarantined} = join ",", sort keys %q;
85     if (!$r->{session}{quarantined}) {
86         $r->template("list");
87         $r->objects([ map { $self->retrieve($_) } @quarantined ]);
88     } else {
89         $r->objects([ map { $self->retrieve($_) } sort keys %q ]);
90     }
91 }
92
93 sub upload_file {
94     my ($self, $r, $filename, $offered_name) = @_;
95     my $mm = File::MMagic->new;
96     my $res = $mm->checktype_filename($filename);
97     warn "$filename is a $res\n";
98     if ($res =~ m{/x-zip} or $offered_name =~ /t(ar\.)?gz$/i) {
99         return $self->upload_archive($r, $filename);
100     } elsif ($offered_name =~ /\.(raw|nef|dng|cr2)/i) {
101         return $self->upload_raw($r, $filename, $offered_name);
102     } elsif ($res =~ m{image/jpeg}) {
103         return $self->upload_jpeg($r, $filename, $offered_name);
104     } else {
105         $r->message(basename($offered_name).": I can't handle $res files yet");
106         return ();
107     }
108 }
109
110 sub upload_archive {
111     my ($self, $r, $filename, $tags) = @_;
112     $r->{params}{title} = ""; # Kill that dead.
113     my $archive = Archive::Any->new($filename);
114     my $dir = tempdir();
115     $archive->extract($dir);
116     my @results; 
117     find({ wanted   => sub { return unless -f $_; 
118                              push @results, $self->upload_file($r, $_, $_) }, 
119            no_chdir => 1}, $dir);
120     rmtree($dir);
121     return @results;
122 }
123
124 sub upload_raw {
125     my ($self, $r, $filename, $offered_name) = @_;
126     my $jpg = tmpnam().".jpg";
127     system("dcraw -c $filename | convert - $jpg");
128     my $photo = $self->upload_jpeg($r, $jpg, $offered_name);
129     $filename =~ /\.(.*)$/;
130     my $format = $1;
131     $photo->format($format);
132     # Put the file in place
133     copy($filename, 
134          Memories->config->{data_store}."/".$photo->id.".".$format);
135     return $photo;
136 }
137
138 sub upload_jpeg {
139     my ($self, $r, $filename, $offered_name) = @_;
140     my $photo = $self->create({
141         uploader => $r->user,
142         uploaded => Time::Piece->new(),
143         title => ($r->{params}{title} || basename($offered_name)),
144         hit_count => 0,
145         rating => 0,
146         rated => 0,
147     });
148     if (!copy($filename, $photo->path("file"))) {
149         warn "Couldn't copy photo to ".$photo->path("file").": $!";
150         $photo->delete(); die;
151     }
152     my ($x, $y) = dim(image_info($photo->path));
153     $photo->x($x); $photo->y($y);
154
155     # Rotate?
156     $photo->unrotate(); 
157     if (!$photo->title){ 
158         $photo->title($photo->title_exif || basename($filename));
159     }
160
161     $photo->make_thumb;
162     my $tags = $r->{params}{tags}.join " ", map { qq{"$_"} } $photo->tags_exif;
163     $photo->add_tags($tags);
164 warn "D";
165     $photo->add_to_imageseek_library;
166     Memories->zap_cache();
167 warn "E";
168
169     # Add system tags here
170     my $tag = "date:".$photo->shot->ymd;
171     $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
172     return $photo;
173 }
174
175 sub approx_rating {
176     my $self = shift;
177     $self->rated or return 0;
178     int($self->rating/$self->rated*10)/10;
179 }
180
181 sub add_rating :Exported {
182     my ($self, $r) = @_;
183     my $photo = $r->{objects}[0];
184     my $delta = $r->{params}{rating};
185     if ($delta < 0 or $delta > 5) { return; } # Scammer
186     # XXX Race
187     $photo->rating($photo->rating() + $delta);
188     $photo->rated($photo->rated() + 1);
189     $r->output(""); # Only used by ajax
190 }
191
192 sub view :Exported {
193     my ($self, $r) = @_;
194     my $photo = $r->{objects}[0];
195     $photo->hit_count($photo->hit_count()+1);
196     if ($r->{session}{last_search}) {
197         # This is slightly inefficient
198         my @search = split/,/, $r->{session}{last_search};
199         my $found = -1;
200         for my $i (0..$#search) {
201             next unless $photo->id == $search[$i];
202             $found = $i;
203         }
204         return unless $found > -1;
205         $r->{template_args}{next} = $self->retrieve($search[$found+1]) 
206             if $found+1 <= $#search;
207         $r->{template_args}{prev} = $self->retrieve($search[$found-1])
208             if $found-1 >= 0;
209     }
210 }
211 sub upload :Exported {}
212 sub exif :Exported {}
213 sub comment :Exported {}
214 sub tagedit :Exported {}
215 sub similar :Exported {}
216 sub sized :Exported {}
217
218 use Class::DBI::Plugin::Pager;
219 use Class::DBI::Plugin::AbstractCount;
220
221 sub view_paged_ordered {
222     my ($self, $r, $how) = @_;
223     my $page = $r->params->{page} || 1;
224     my $pager = $self->pager(
225         per_page => Memories->config->{photos_per_page}, 
226         page => $page,
227         syntax => PAGER_SYNTAX,
228         order_by => $how
229     );
230     $r->objects([$pager->retrieve_all ]);
231     $r->{template_args}{pager} = $pager;
232     $r->last_search;
233     $r->template("paged"); # Set the what using the action name
234 }
235
236 sub add_comment :Exported {
237     my ($self, $r, $photo) = @_;
238     $r->template("view");
239     $r->objects->[0]->add_to_comments({
240         name => $r->params->{name},
241         content => $r->params->{content}
242     });
243 }
244
245 use Cache::MemoryCache;
246 use Image::Info qw(dim image_info);
247 use Image::ExifTool;
248 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
249
250 sub add_to_imageseek_library {
251     my $self = shift;
252     Image::Seek::cleardb();
253     my $img = Image::Imlib2->load($self->path("file"));
254
255     Image::Seek::add_image($img, $self->id);
256     # Merge this new one into the main database; there is a bit of a
257     # race condition here. XXX
258     Image::Seek::loaddb(Memories->config->{image_seek});
259     Image::Seek::savedb(Memories->config->{image_seek});
260 }
261
262 sub recommended_tags {
263     my $self = shift;
264     my %tags = map { $_->name => $_ }
265                map { $_->tags } 
266                $self->find_similar(3);
267     values %tags;
268 }
269
270 sub find_similar {
271     my ($self, $count) = @_;
272     Image::Seek::cleardb();
273     Image::Seek::loaddb(Memories->config->{image_seek});
274     my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
275     shift @res; # $self
276     map { $self->retrieve($_) } @res;
277 }
278
279 sub unrotate {
280     my $self = shift;
281     my $orient = $self->exif_info->{EXIF}->{Orientation};
282     return if $orient !~/Rotate (\d+)/i;
283     my $steps = $1/90;
284     my $img = Image::Imlib2->load($self->path("file"));
285     $img->image_orientate($steps);
286     $img->save($self->path("file"));
287 }
288
289 sub exif_info {
290     my $self = shift;
291     my $info = $self->exif_object;
292     return $info if $info;
293     # Get it from the Cache
294     if (!($info = $cache->get($self->id))) {
295         # Create it
296         $info = $self->_exif_info;
297         $cache->set($self->id, $info);
298     }
299     $self->exif_object($info);
300     $info;
301 }
302
303 my %banned_tags = map { $_ => 1 }
304     qw( CodedCharacterSet ApplicationRecordVersion );
305
306 sub _exif_info {
307     my $exifTool = new Image::ExifTool;
308     $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
309     my $info = $exifTool->ImageInfo(shift->path(0,0,1));
310     my $hash = {};
311     foreach my $tag ($exifTool->GetFoundTags('Group0')) {
312         next if $banned_tags{$tag};
313          my $group = $exifTool->GetGroup($tag);
314          my $val = $info->{$tag};
315          next if ref $val eq 'SCALAR';
316          next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
317          $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
318     }
319     return $hash;
320 }
321
322 # XXX Cache this
323 sub dimensions { join "x", $_[0]->x, $_[0]->y }
324
325 sub is_bigger {
326     my ($self, $size) = @_;
327     return 1 if $size eq "full";
328     my ($w, $h) = ($self->x, $self->y);
329     my ($w2, $h2) = split /x/, $size;
330     return 1 if $w > $w2 or $h > $h2;
331     return 0;
332 }
333
334 sub sized_url { # Use this rather than ->path from TT
335     my ($self, $size) = @_;
336     my $url = Memories->config->{data_store_external};
337     my $resized = Memories->config->{sizes}->[$size];
338     if (!$resized) { cluck "Asked for crazy size $size"; return; }
339     if ($resized eq "full") { return $self->path("url") }
340     warn "Looking for path ".$self->path(file => $resized);
341     $self->scale($resized) 
342         unless -e $self->path( file => $resized );
343     return $self->path(url => $resized);
344 }
345
346 sub path { 
347     my ($self, $is_url, $scale, $raw) = @_;
348     my $path =
349         Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
350     if ($scale) { $path .= "$scale/" }
351     # Make dir if it doesn't exist, save trouble later
352     use File::Path;
353     if ($is_url ne "url" and ! -d $path) {mkpath($path) or die "Couldn't make path $path: $!";}
354     if ($scale or ($is_url ne "url" and !$raw)) { 
355         $path .= $self->id.".jpg";
356     } else {
357         $path .= $self->id.".".($self->format||"jpg");
358     }
359     return $path;
360 }
361
362 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
363 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
364
365 use Image::Imlib2;
366 sub scale {
367     my ($self, $scale, $swap) = @_;
368     my ($x, $y) = split /x/, $scale;
369     # Find out smaller axis
370     my ($cur_x, $cur_y) = ($self->x, $self->y);
371     if (!$swap) {
372         if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
373     } else {
374         if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
375     }
376     my $img = Image::Imlib2->load($self->path("file"));
377     unless ($img) {
378         cluck "Couldn't open image file ".$self->path("file");
379         return;
380     }
381     $img = $img->create_scaled_image($x, $y);
382     $img->image_set_format("jpeg");
383     my $file = $self->path( file => $scale );
384     $img->save($file);
385     if ($!) {
386         cluck "Couldn't write image file $file ($!)"; 
387         return;
388     }
389 }
390
391 sub edit_tags :Exported {
392     my ($self, $r) = @_;
393     my $photo = $r->objects->[0];
394     my %params = %{$r->params};
395     my $exifTool = new Image::ExifTool;
396     for (keys %params) { 
397         next unless /delete_(\d+)/;
398         my $tagging = Memories::Tagging->retrieve($1) or next;
399         next unless $tagging->photo->id == $photo->id;
400         $exifTool->SetNewValue(Keywords => $1, DelValue => 1);
401         $tagging->delete;
402     }
403     $exifTool->WriteInfo($photo->path);
404     $photo->add_tags($params{newtags});
405     $r->template("view");
406 }
407
408 sub add_tags {
409     my ($photo, $tagstring) = @_;
410     my $exifTool = new Image::ExifTool;
411
412     for my $tag (Tagtools->separate_tags($tagstring)) {
413         $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) });
414         $exifTool->SetNewValue(Keywords => $tag, AddValue => 1);
415     }
416     $exifTool->WriteInfo($photo->path);
417 }
418
419 # Work out some common properties from a set of potential photo metadata
420 # tags
421 sub _grovel_metadata {
422     my ($self, @tags) = @_;
423     my %md = map {%$_} values %{$self->exif_info};
424     for (@tags) {
425         if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
426     }
427     return;
428 }
429
430 sub shot {
431     my $self = shift;
432     my $dt = $self->_grovel_metadata(
433         'Shooting Date/Time',
434         'Date/Time Of Digitization',
435         'Date/Time Of Last Modification'
436     );
437     if (!$dt) { return $self->uploaded }
438     return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
439 }
440
441 sub description {
442     shift->_grovel_metadata(
443         'Description', 'Image Description', 'Caption-Abstract'
444     );
445 }
446
447 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
448 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
449 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
450
451 # This one's slightly different since we want everything we can get...
452 sub tags_exif {
453     my $self = shift;
454     my %md = map {%$_} values %{$self->exif_info};
455     my %tags = 
456         map { s/\s+/-/g; lc $_ => 1  }
457         map { split /\s*,\s*/, $md{$_}}
458         grep {$md{$_} and $md{$_} =~/[^ 0:]/}
459         (qw(Keywords Subject City State Location Country Province-State), 
460         'Transmission Reference', 'Intellectual Genre', 
461         'Country-Primary Location Name'
462         );
463     return keys %tags;
464 }
465 1;