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