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