]> git.decadent.org.uk Git - memories.git/blob - Memories/Photo.pm
It's right that we want to expose this stuff to the templates, so this patch should...
[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 my %banned_tags = map { $_ => 1 }
178     qw( CodedCharacterSet ApplicationRecordVersion );
179
180 sub _exif_info {
181     my $exifTool = new Image::ExifTool;
182     $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
183     my $info = $exifTool->ImageInfo(shift->path);
184     my $hash = {};
185     foreach my $tag ($exifTool->GetFoundTags('Group0')) {
186         next if $banned_tags{$tag};
187          my $group = $exifTool->GetGroup($tag);
188          my $val = $info->{$tag};
189          next if ref $val eq 'SCALAR';
190          next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
191          $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
192     }
193     return $hash;
194 }
195
196 # XXX Cache this
197 sub dimensions { join "x", $_[0]->x, $_[0]->y }
198
199 sub is_bigger {
200     my ($self, $size) = @_;
201     return 1 if $size eq "full";
202     my ($w, $h) = ($self->x, $self->y);
203     my ($w2, $h2) = split /x/, $size;
204     return 1 if $w > $w2 or $h > $h2;
205     return 0;
206 }
207
208 sub sized_url { # Use this rather than ->path from TT
209     my ($self, $size) = @_;
210     my $url = Memories->config->{data_store_external};
211     my $resized = Memories->config->{sizes}->[$size];
212     if (!$resized) { cluck "Asked for crazy size $size"; return; }
213     if ($resized eq "full") { return $self->path("url") }
214     $self->scale($resized) 
215         unless -e $self->path( file => $resized );
216     return $self->path(url => $resized);
217 }
218
219 sub path { 
220     my ($self, $is_url, $scale) = @_;
221     my $path =
222         Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
223     if ($scale) { $path .= "$scale/" }
224     # Make dir if it doesn't exist, save trouble later
225     use File::Path;
226     if ($is_url ne "url") {mkpath($path);}
227     $path .= $self->id.".".$self->format;
228     return $path;
229 }
230
231 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
232 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
233
234 use Image::Imlib2;
235 sub scale {
236     my ($self, $scale, $swap) = @_;
237     my ($x, $y) = split /x/, $scale;
238     # Find out smaller axis
239     my ($cur_x, $cur_y) = ($self->x, $self->y);
240     if (!$swap) {
241         if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
242     } else {
243         if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
244     }
245     my $img = Image::Imlib2->load($self->path("file"));
246     unless ($img) {
247         cluck "Couldn't open image file ".$self->path("file");
248         return;
249     }
250     $img = $img->create_scaled_image($x, $y);
251     $img->image_set_format("jpeg");
252     my $file = $self->path( file => $scale );
253     $img->save($file);
254     if ($!) {
255         cluck "Couldn't write image file $file ($!)"; 
256         return;
257     }
258 }
259
260 use Text::Balanced qw(extract_multiple extract_quotelike);
261 sub edit_tags :Exported {
262     my ($self, $r) = @_;
263     my $photo = $r->objects->[0];
264     my %params = %{$r->params};
265     for (keys %params) { 
266         next unless /delete_(\d+)/;
267         my $tagging = Memories::Tagging->retrieve($1) or next;
268         next unless $tagging->photo->id == $photo->id;
269         $tagging->delete;
270     }
271     $photo->add_tags($params{newtags});
272     $r->template("view");
273 }
274
275 sub add_tags {
276     my ($photo, $tagstring) = @_;
277
278     for my $tag (map { s/^"|"$//g; $_} extract_multiple(lc $tagstring, [ \&extract_quotelike, qr/([^\s]+)/ ], undef,1)) {
279         $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
280     }
281 }
282
283 sub shot {
284   my $self = shift;
285   my $exif = $self->exif_info->{EXIF};
286   my ($dt) =
287     grep {$_ and /[^ 0:]/} 
288         ($exif->{ 'Shooting Date/Time' },
289          $exif->{ 'Date/Time Of Digitization' },
290          $exif->{ 'Date/Time Of Last Modification' });
291   if (!$dt) { return $self->uploaded }
292   return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
293 }
294 1;