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