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