a1e987a505b4890105d49e2f24fc31099b36813a
[Sone.git] / src / main / java / net / pterodactylus / sone / web / UploadImagePage.java
1 /*
2  * Sone - UploadImagePage.java - Copyright © 2011–2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web;
19
20 import static com.google.common.base.Optional.fromNullable;
21 import static java.util.logging.Logger.getLogger;
22
23 import java.awt.Image;
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.Iterator;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import javax.imageio.ImageIO;
33 import javax.imageio.ImageReader;
34 import javax.imageio.stream.ImageInputStream;
35
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Image.Modifier.ImageTitleMustNotBeEmpty;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.data.TemporaryImage;
40 import net.pterodactylus.sone.text.TextFilter;
41 import net.pterodactylus.sone.web.page.FreenetRequest;
42 import net.pterodactylus.util.io.Closer;
43 import net.pterodactylus.util.template.Template;
44 import net.pterodactylus.util.template.TemplateContext;
45 import net.pterodactylus.util.web.Method;
46
47 import com.google.common.io.ByteStreams;
48
49 import freenet.support.api.Bucket;
50 import freenet.support.api.HTTPUploadedFile;
51
52 /**
53  * Page implementation that lets the user upload an image.
54  *
55  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56  */
57 public class UploadImagePage extends SoneTemplatePage {
58
59         private static final Logger logger = getLogger(UploadImagePage.class.getName());
60         private static final String UNKNOWN_MIME_TYPE = "application/octet-stream";
61
62         /**
63          * Creates a new “upload image” page.
64          *
65          * @param template
66          *            The template to render
67          * @param webInterface
68          *            The Sone web interface
69          */
70         public UploadImagePage(Template template, WebInterface webInterface) {
71                 super("uploadImage.html", template, "Page.UploadImage.Title", webInterface, true);
72         }
73
74         //
75         // SONETEMPLATEPAGE METHODS
76         //
77
78         /**
79          * {@inheritDoc}
80          */
81         @Override
82         protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
83                 super.processTemplate(request, templateContext);
84                 if (request.getMethod() == Method.POST) {
85                         Sone currentSone = getCurrentSone(request.getToadletContext());
86                         String parentId = request.getHttpRequest().getPartAsStringFailsafe("parent", 36);
87                         Album parent = webInterface.getCore().getAlbum(parentId);
88                         if (parent == null) {
89                                 throw new RedirectException("noPermission.html");
90                         }
91                         if (!currentSone.equals(parent.getSone())) {
92                                 throw new RedirectException("noPermission.html");
93                         }
94                         String name = request.getHttpRequest().getPartAsStringFailsafe("title", 200);
95                         String description = request.getHttpRequest().getPartAsStringFailsafe("description", 4000);
96                         HTTPUploadedFile uploadedFile = request.getHttpRequest().getUploadedFile("image");
97                         Bucket fileBucket = uploadedFile.getData();
98                         InputStream imageInputStream = null;
99                         ByteArrayOutputStream imageDataOutputStream = null;
100                         try {
101                                 imageInputStream = fileBucket.getInputStream();
102                                 /* TODO - check length */
103                                 imageDataOutputStream = new ByteArrayOutputStream((int) fileBucket.size());
104                                 ByteStreams.copy(imageInputStream, imageDataOutputStream);
105                         } catch (IOException ioe1) {
106                                 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
107                                 return;
108                         } finally {
109                                 fileBucket.free();
110                                 Closer.close(imageInputStream);
111                                 Closer.close(imageDataOutputStream);
112                         }
113                         byte[] imageData = imageDataOutputStream.toByteArray();
114                         ByteArrayInputStream imageDataInputStream = null;
115                         Image uploadedImage = null;
116                         try {
117                                 imageDataInputStream = new ByteArrayInputStream(imageData);
118                                 uploadedImage = ImageIO.read(imageDataInputStream);
119                                 if (uploadedImage == null) {
120                                         templateContext.set("messages", webInterface.getL10n().getString("Page.UploadImage.Error.InvalidImage"));
121                                         return;
122                                 }
123                                 String mimeType = getMimeType(imageData);
124                                 TemporaryImage temporaryImage = webInterface.getCore().createTemporaryImage(mimeType, imageData);
125                                 net.pterodactylus.sone.data.Image image = webInterface.getCore().createImage(currentSone, parent, temporaryImage);
126                                 image.modify().setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).setWidth(uploadedImage.getWidth(null)).setHeight(uploadedImage.getHeight(null)).update();
127                         } catch (IOException ioe1) {
128                                 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
129                                 return;
130                         } catch (ImageTitleMustNotBeEmpty itmnbe) {
131                                 throw new RedirectException("emptyImageTitle.html");
132                         } finally {
133                                 Closer.close(imageDataInputStream);
134                                 Closer.flush(uploadedImage);
135                         }
136                         throw new RedirectException("imageBrowser.html?album=" + parent.getId());
137                 }
138         }
139
140         //
141         // PRIVATE METHODS
142         //
143
144         /**
145          * Tries to detect the MIME type of the encoded image.
146          *
147          * @param imageData
148          *            The encoded image
149          * @return The MIME type of the image, or “application/octet-stream” if the
150          *         image type could not be detected
151          */
152         private static String getMimeType(byte[] imageData) {
153                 ByteArrayInputStream imageDataInputStream = new ByteArrayInputStream(imageData);
154                 try {
155                         ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageDataInputStream);
156                         Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
157                         if (imageReaders.hasNext()) {
158                                 return fromNullable(imageReaders.next().getOriginatingProvider().getMIMETypes())
159                                                 .or(new String[] { UNKNOWN_MIME_TYPE })[0];
160                         }
161                 } catch (IOException ioe1) {
162                         logger.log(Level.FINE, "Could not detect MIME type for image.", ioe1);
163                 }
164                 return UNKNOWN_MIME_TYPE;
165         }
166
167 }