]> git.decadent.org.uk Git - memories.git/blob - Memories/Photo.pm
A bit of defense.
[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     # Set it up to go again
54     $r->objects(\@photos);
55     $r->template("view");
56     $r->message("Thanks for the upload!"); 
57     # Deal with the quarantined
58 }
59
60 sub upload_jpeg {
61     my ($self, $filename, $title, $tags, $r) = @_;
62     my $quarantine;
63     my $photo = $self->create({
64         uploader => $r->user,
65         uploaded => Time::Piece->new(),
66         title => $title,
67         hit_count => 0,
68         rating => 0,
69         rated => 0,
70     });
71     if (!copy($filename, $photo->path("file"))) {
72         $photo->delete(); die "Couldn't copy photo: $!";
73     }
74     my ($x, $y) = dim(image_info($photo->path));
75     $photo->x($x); $photo->y($y);
76
77     # Rotate?
78     $photo->unrotate(); 
79     if (!$photo->title){ 
80         $photo->title($photo->title_exif || basename($filename));
81     }
82
83     $photo->make_thumb;
84     $tags ||= join " ", map { qq{"$_"} } $photo->tags_exif;
85     $photo->add_tags($tags);
86     $photo->add_to_imageseek_library;
87     Memories->zap_cache();
88
89     # Add system tags here
90     my $tag = "date:".$photo->shot->ymd;
91     $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
92     return $photo;
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 sub sized :Exported {}
137
138 use Class::DBI::Plugin::Pager;
139 use Class::DBI::Plugin::AbstractCount;
140
141 sub view_paged_ordered {
142     my ($self, $r, $how) = @_;
143     my $page = $r->params->{page} || 1;
144     my $pager = $self->pager(
145         per_page => Memories->config->{photos_per_page}, 
146         page => $page,
147         syntax => PAGER_SYNTAX,
148         order_by => $how
149     );
150     $r->objects([$pager->retrieve_all ]);
151     $r->{template_args}{pager} = $pager;
152     $r->last_search;
153     $r->template("paged"); # Set the what using the action name
154 }
155
156 sub add_comment :Exported {
157     my ($self, $r, $photo) = @_;
158     $r->template("view");
159     $r->objects->[0]->add_to_comments({
160         name => $r->params->{name},
161         content => $r->params->{content}
162     });
163 }
164
165 sub format { 
166     "jpg" # For now
167
168
169 use Cache::MemoryCache;
170 use Image::Info qw(dim image_info);
171 use Image::ExifTool;
172 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
173
174 sub add_to_imageseek_library {
175     my $self = shift;
176     Image::Seek::cleardb();
177     my $img = Image::Imlib2->load($self->path("file"));
178
179     Image::Seek::add_image($img, $self->id);
180     # Merge this new one into the main database; there is a bit of a
181     # race condition here. XXX
182     Image::Seek::loaddb(Memories->config->{image_seek});
183     Image::Seek::savedb(Memories->config->{image_seek});
184 }
185
186 sub recommended_tags {
187     my $self = shift;
188     my %tags = map { $_->name => $_ }
189                map { $_->tags } 
190                $self->find_similar(3);
191     values %tags;
192 }
193
194 sub find_similar {
195     my ($self, $count) = @_;
196     Image::Seek::cleardb();
197     Image::Seek::loaddb(Memories->config->{image_seek});
198     my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
199     shift @res; # $self
200     map { $self->retrieve($_) } @res;
201 }
202
203 sub unrotate {
204     my $self = shift;
205     my $orient = $self->exif_info->{EXIF}->{Orientation};
206     return if $orient !~/Rotate (\d+)/i;
207     my $steps = $1/90;
208     my $img = Image::Imlib2->load($self->path("file"));
209     $img->image_orientate($steps);
210     $img->save($self->path("file"));
211 }
212
213 sub exif_info {
214     my $self = shift;
215     my $info = $self->exif_object;
216     return $info if $info;
217     # Get it from the Cache
218     if (!($info = $cache->get($self->id))) {
219         # Create it
220         $info = $self->_exif_info;
221         $cache->set($self->id, $info);
222     }
223     $self->exif_object($info);
224     $info;
225 }
226
227 my %banned_tags = map { $_ => 1 }
228     qw( CodedCharacterSet ApplicationRecordVersion );
229
230 sub _exif_info {
231     my $exifTool = new Image::ExifTool;
232     $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
233     my $info = $exifTool->ImageInfo(shift->path);
234     my $hash = {};
235     foreach my $tag ($exifTool->GetFoundTags('Group0')) {
236         next if $banned_tags{$tag};
237          my $group = $exifTool->GetGroup($tag);
238          my $val = $info->{$tag};
239          next if ref $val eq 'SCALAR';
240          next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
241          $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
242     }
243     return $hash;
244 }
245
246 # XXX Cache this
247 sub dimensions { join "x", $_[0]->x, $_[0]->y }
248
249 sub is_bigger {
250     my ($self, $size) = @_;
251     return 1 if $size eq "full";
252     my ($w, $h) = ($self->x, $self->y);
253     my ($w2, $h2) = split /x/, $size;
254     return 1 if $w > $w2 or $h > $h2;
255     return 0;
256 }
257
258 sub sized_url { # Use this rather than ->path from TT
259     my ($self, $size) = @_;
260     my $url = Memories->config->{data_store_external};
261     my $resized = Memories->config->{sizes}->[$size];
262     if (!$resized) { cluck "Asked for crazy size $size"; return; }
263     if ($resized eq "full") { return $self->path("url") }
264     $self->scale($resized) 
265         unless -e $self->path( file => $resized );
266     return $self->path(url => $resized);
267 }
268
269 sub path { 
270     my ($self, $is_url, $scale) = @_;
271     my $path =
272         Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
273     if ($scale) { $path .= "$scale/" }
274     # Make dir if it doesn't exist, save trouble later
275     use File::Path;
276     if ($is_url ne "url") {mkpath($path);}
277     $path .= $self->id.".".$self->format;
278     return $path;
279 }
280
281 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
282 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
283
284 use Image::Imlib2;
285 sub scale {
286     my ($self, $scale, $swap) = @_;
287     my ($x, $y) = split /x/, $scale;
288     # Find out smaller axis
289     my ($cur_x, $cur_y) = ($self->x, $self->y);
290     if (!$swap) {
291         if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
292     } else {
293         if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
294     }
295     my $img = Image::Imlib2->load($self->path("file"));
296     unless ($img) {
297         cluck "Couldn't open image file ".$self->path("file");
298         return;
299     }
300     $img = $img->create_scaled_image($x, $y);
301     $img->image_set_format("jpeg");
302     my $file = $self->path( file => $scale );
303     $img->save($file);
304     if ($!) {
305         cluck "Couldn't write image file $file ($!)"; 
306         return;
307     }
308 }
309
310 sub edit_tags :Exported {
311     my ($self, $r) = @_;
312     my $photo = $r->objects->[0];
313     my %params = %{$r->params};
314     for (keys %params) { 
315         next unless /delete_(\d+)/;
316         my $tagging = Memories::Tagging->retrieve($1) or next;
317         next unless $tagging->photo->id == $photo->id;
318         $tagging->delete;
319     }
320     $photo->add_tags($params{newtags});
321     $r->template("view");
322 }
323
324 sub add_tags {
325     my ($photo, $tagstring) = @_;
326
327     for my $tag (Tagtools->separate_tags($tagstring)) {
328         $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
329     }
330 }
331
332 # Work out some common properties from a set of potential photo metadata
333 # tags
334 sub _grovel_metadata {
335     my ($self, @tags) = @_;
336     my %md = map {%$_} values %{$self->exif_info};
337     for (@tags) {
338         if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
339     }
340     return;
341 }
342
343 sub shot {
344     my $self = shift;
345     my $dt = $self->_grovel_metadata(
346         'Shooting Date/Time',
347         'Date/Time Of Digitization',
348         'Date/Time Of Last Modification'
349     );
350     if (!$dt) { return $self->uploaded }
351     return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
352 }
353
354 sub description {
355     shift->_grovel_metadata(
356         'Description', 'Image Description', 'Caption-Abstract'
357     );
358 }
359
360 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
361 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
362 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
363
364 # This one's slightly different since we want everything we can get...
365 sub tags_exif {
366     my $self = shift;
367     my %md = map {%$_} values %{$self->exif_info};
368     my %tags = 
369         map { s/\s+/-/g; lc $_ => 1  }
370         map { split /\s*,\s*/, $md{$_}}
371         grep {$md{$_} and $md{$_} =~/[^ 0:]/}
372         (qw(Keywords Subject City State Location Country Province-State), 
373         'Transmission Reference', 'Intellectual Genre', 
374         'Country-Primary Location Name'
375         );
376     return keys %tags;
377 }
378 1;