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