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