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