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