]> git.decadent.org.uk Git - memories.git/blob - Memories/Photo.pm
8286480aa1f952191c75216b33664978e48f3379
[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     copy($filename, $photo->path("file"));
72     my ($x, $y) = dim(image_info($photo->path));
73     $photo->x($x); $photo->y($y);
74
75     # Rotate?
76     $photo->unrotate(); 
77     if (!$photo->title){ 
78         $photo->title($photo->title_exif || basename($filename));
79     }
80
81     $photo->make_thumb;
82     $tags ||= join " ", map { qq{"$_"} } $photo->tags_exif;
83     $photo->add_tags($tags);
84     $photo->add_to_imageseek_library;
85     Memories->zap_cache();
86
87     # Add system tags here
88     my $tag = "date:".$photo->shot->ymd;
89     $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
90     return $photo;
91 }
92
93 sub approx_rating {
94     my $self = shift;
95     $self->rated or return 0;
96     int($self->rating/$self->rated*10)/10;
97 }
98
99 sub add_rating :Exported {
100     my ($self, $r) = @_;
101     my $photo = $r->{objects}[0];
102     my $delta = $r->{params}{rating};
103     if ($delta < 0 or $delta > 5) { return; } # Scammer
104     # XXX Race
105     $photo->rating($photo->rating() + $delta);
106     $photo->rated($photo->rated() + 1);
107     $r->output(""); # Only used by ajax
108 }
109
110 sub view :Exported {
111     my ($self, $r) = @_;
112     my $photo = $r->{objects}[0];
113     $photo->hit_count($photo->hit_count()+1);
114     if ($r->{session}{last_search}) {
115         # This is slightly inefficient
116         my @search = split/,/, $r->{session}{last_search};
117         my $found = -1;
118         for my $i (0..$#search) {
119             next unless $photo->id == $search[$i];
120             $found = $i;
121         }
122         return unless $found > -1;
123         $r->{template_args}{next} = $self->retrieve($search[$found+1]) 
124             if $found+1 <= $#search;
125         $r->{template_args}{prev} = $self->retrieve($search[$found-1])
126             if $found-1 >= 0;
127     }
128 }
129 sub upload :Exported {}
130 sub exif :Exported {}
131 sub comment :Exported {}
132 sub tagedit :Exported {}
133 sub similar :Exported {}
134 sub sized :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;