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