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