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