]> git.decadent.org.uk Git - memories.git/blob - Memories/Photo.pm
Add interface to "most popular photos"
[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 Time::Piece;
6 use Image::Seek;
7 use constant PAGER_SYNTAX => "LimitXY";
8 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count));
9 __PACKAGE__->untaint_columns(printable => [qw/title/]);
10 __PACKAGE__->columns(TEMP => qw/exif_object/);
11 __PACKAGE__->set_sql(recent => q{
12 SELECT __ESSENTIAL__
13 FROM __TABLE__
14 ORDER BY uploaded DESC
15 LIMIT 4
16 });
17 __PACKAGE__->set_sql(popular => q{
18 SELECT __ESSENTIAL__
19 FROM __TABLE__
20 ORDER BY hit_count DESC
21 LIMIT 4
22 });
23
24 __PACKAGE__->has_many(comments => "Memories::Comment");
25 __PACKAGE__->has_a(uploader => "Memories::User");
26 __PACKAGE__->has_a(uploaded => "Time::Piece",
27     inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
28     deflate => 'datetime',
29 );
30
31 sub do_upload :Exported {
32     my ($self, $r) = @_;
33     my %upload = $r->upload("photo");
34
35     # XXX Stop anonymous uploads!
36     my $photo = $self->create({
37         uploader => $r->user,
38         uploaded => Time::Piece->new(),
39         title => $r->params->{title},
40         hit_count => 0,
41         rating => 0,
42         rated => 0, # Oh, the potential for divide by zero errors...
43     });
44
45     # Dump content
46     if (!open OUT, ">". $photo->path("file")) {
47         die "Can't write ".$photo->path("file")." because $!";
48     }
49     # XXX Check it's a JPEG, etc.
50     # XXX Unzip ZIP file
51     print OUT $upload{content};
52     close OUT;
53     my ($x, $y) = dim(image_info($photo->path));
54     $photo->x($x); $photo->y($y);
55
56     # Rotate?
57     $photo->unrotate(); 
58     if (!$photo->title){ 
59         $photo->title($photo->title_exif || $upload{filename});
60     }
61
62     $photo->make_thumb;
63     $r->{params}{tags} ||= join " ", map { qq{"$_"} } $photo->tags_exif;
64     $photo->add_tags($r->{params}{tags});
65     $photo->add_to_imageseek_library;
66     Memories->zap_cache();
67
68     # Add system tags here
69     my $tag = "date:".$photo->shot->ymd;
70     $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
71
72     # Set it up to go again
73     $r->objects([$photo]);
74     $r->template("view");
75     $r->message("Thanks for the upload! ".
76         ($r->{params}{tags} ? "" 
77         : "Don't forget to <a href=\"?".$r->config->uri_base."photo/view/".$photo->id."?active=tagedit\">tag your photo</a>"
78         )
79     ); 
80 }
81
82 sub approx_rating {
83     my $self = shift;
84     $self->rated or return 0;
85     int($self->rating/$self->rated*10)/10;
86 }
87
88 sub add_rating :Exported {
89     my ($self, $r) = @_;
90     my $photo = $r->{objects}[0];
91     my $delta = $r->{params}{rating};
92     if ($delta < 0 or $delta > 5) { return; } # Scammer
93     # XXX Race
94     $photo->rating($photo->rating() + $delta);
95     $photo->rated($photo->rated() + 1);
96     $r->output(""); # Only used by ajax
97 }
98
99 sub view :Exported {
100     my ($self, $r) = @_;
101     my $photo = $r->{objects}[0];
102     $photo->hit_count($photo->hit_count()+1);
103     if ($r->{session}{last_search}) {
104         # This is slightly inefficient
105         my @search = split/,/, $r->{session}{last_search};
106         my $found = -1;
107         for my $i (0..$#search) {
108             next unless $photo->id == $search[$i];
109             $found = $i;
110         }
111         return unless $found > -1;
112         $r->{template_args}{next} = $self->retrieve($search[$found+1]) 
113             if $found+1 <= $#search;
114         $r->{template_args}{prev} = $self->retrieve($search[$found-1])
115             if $found-1 >= 0;
116     }
117 }
118 sub upload :Exported {}
119 sub exif :Exported {}
120 sub comment :Exported {}
121 sub tagedit :Exported {}
122 sub similar :Exported {}
123
124 use Class::DBI::Plugin::Pager;
125 use Class::DBI::Plugin::AbstractCount;
126
127 sub view_paged_ordered {
128     my ($self, $r, $how) = @_;
129     my $page = $r->params->{page} || 1;
130     my $pager = $self->pager(
131         per_page => Memories->config->{photos_per_page}, 
132         page => $page,
133         syntax => PAGER_SYNTAX,
134         order_by => $how
135     );
136     $r->objects([$pager->retrieve_all ]);
137     $r->{template_args}{pager} = $pager;
138     $r->last_search;
139     $r->template("paged"); # Set the what using the action name
140 }
141
142 sub recent :Exported {
143     my ($self, $r) = @_;
144     $self->view_paged_ordered($r, "uploaded desc");
145 }
146
147 sub popular :Exported {
148     my ($self, $r) = @_;
149     $self->view_paged_ordered($r, "hit_count desc");
150 }
151
152 sub add_comment :Exported {
153     my ($self, $r, $photo) = @_;
154     $r->template("view");
155     $r->objects->[0]->add_to_comments({
156         name => $r->params->{name},
157         content => $r->params->{content}
158     });
159 }
160
161 sub format { 
162     "jpg" # For now
163
164
165 use Cache::MemoryCache;
166 use Image::Info qw(dim image_info);
167 use Image::ExifTool;
168 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
169
170 sub add_to_imageseek_library {
171     my $self = shift;
172     Image::Seek::cleardb();
173     my $img = Image::Imlib2->load($self->path("file"));
174
175     Image::Seek::add_image($img, $self->id);
176     # Merge this new one into the main database; there is a bit of a
177     # race condition here. XXX
178     Image::Seek::loaddb(Memories->config->{image_seek});
179     Image::Seek::savedb(Memories->config->{image_seek});
180 }
181
182 sub recommended_tags {
183     my $self = shift;
184     my %tags = map { $_->name => $_ }
185                map { $_->tags } 
186                $self->find_similar(3);
187     values %tags;
188 }
189
190 sub find_similar {
191     my ($self, $count) = @_;
192     Image::Seek::cleardb();
193     Image::Seek::loaddb(Memories->config->{image_seek});
194     my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
195     shift @res; # $self
196     map { $self->retrieve($_) } @res;
197 }
198
199 sub unrotate {
200     my $self = shift;
201     my $orient = $self->exif_info->{EXIF}->{Orientation};
202     return if $orient !~/Rotate (\d+)/i;
203     my $steps = $1/90;
204     my $img = Image::Imlib2->load($self->path("file"));
205     $img->image_orientate($steps);
206     $img->save($self->path("file"));
207 }
208
209 sub exif_info {
210     my $self = shift;
211     my $info = $self->exif_object;
212     return $info if $info;
213     # Get it from the Cache
214     if (!($info = $cache->get($self->id))) {
215         # Create it
216         $info = $self->_exif_info;
217         $cache->set($self->id, $info);
218     }
219     $self->exif_object($info);
220     $info;
221 }
222
223 my %banned_tags = map { $_ => 1 }
224     qw( CodedCharacterSet ApplicationRecordVersion );
225
226 sub _exif_info {
227     my $exifTool = new Image::ExifTool;
228     $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
229     my $info = $exifTool->ImageInfo(shift->path);
230     my $hash = {};
231     foreach my $tag ($exifTool->GetFoundTags('Group0')) {
232         next if $banned_tags{$tag};
233          my $group = $exifTool->GetGroup($tag);
234          my $val = $info->{$tag};
235          next if ref $val eq 'SCALAR';
236          next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
237          $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
238     }
239     return $hash;
240 }
241
242 # XXX Cache this
243 sub dimensions { join "x", $_[0]->x, $_[0]->y }
244
245 sub is_bigger {
246     my ($self, $size) = @_;
247     return 1 if $size eq "full";
248     my ($w, $h) = ($self->x, $self->y);
249     my ($w2, $h2) = split /x/, $size;
250     return 1 if $w > $w2 or $h > $h2;
251     return 0;
252 }
253
254 sub sized_url { # Use this rather than ->path from TT
255     my ($self, $size) = @_;
256     my $url = Memories->config->{data_store_external};
257     my $resized = Memories->config->{sizes}->[$size];
258     if (!$resized) { cluck "Asked for crazy size $size"; return; }
259     if ($resized eq "full") { return $self->path("url") }
260     $self->scale($resized) 
261         unless -e $self->path( file => $resized );
262     return $self->path(url => $resized);
263 }
264
265 sub path { 
266     my ($self, $is_url, $scale) = @_;
267     my $path =
268         Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
269     if ($scale) { $path .= "$scale/" }
270     # Make dir if it doesn't exist, save trouble later
271     use File::Path;
272     if ($is_url ne "url") {mkpath($path);}
273     $path .= $self->id.".".$self->format;
274     return $path;
275 }
276
277 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
278 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
279
280 use Image::Imlib2;
281 sub scale {
282     my ($self, $scale, $swap) = @_;
283     my ($x, $y) = split /x/, $scale;
284     # Find out smaller axis
285     my ($cur_x, $cur_y) = ($self->x, $self->y);
286     if (!$swap) {
287         if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
288     } else {
289         if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
290     }
291     my $img = Image::Imlib2->load($self->path("file"));
292     unless ($img) {
293         cluck "Couldn't open image file ".$self->path("file");
294         return;
295     }
296     $img = $img->create_scaled_image($x, $y);
297     $img->image_set_format("jpeg");
298     my $file = $self->path( file => $scale );
299     $img->save($file);
300     if ($!) {
301         cluck "Couldn't write image file $file ($!)"; 
302         return;
303     }
304 }
305
306 use Text::Balanced qw(extract_multiple extract_quotelike);
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 (map { s/^"|"$//g; $_} extract_multiple(lc $tagstring, [ \&extract_quotelike, qr/([^\s]+)/ ], undef,1)) {
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;