Don’t save Sones directly, only touch the configuration.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / UploadImagePage.java
1 /*
2  * Sone - UploadImagePage.java - Copyright © 2011–2012 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 java.awt.Image;
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Iterator;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import javax.imageio.ImageIO;
30 import javax.imageio.ImageReader;
31 import javax.imageio.stream.ImageInputStream;
32
33 import net.pterodactylus.sone.data.Album;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.data.TemporaryImage;
36 import net.pterodactylus.sone.text.TextFilter;
37 import net.pterodactylus.sone.web.page.FreenetRequest;
38 import net.pterodactylus.util.io.Closer;
39 import net.pterodactylus.util.io.StreamCopier;
40 import net.pterodactylus.util.logging.Logging;
41 import net.pterodactylus.util.template.Template;
42 import net.pterodactylus.util.template.TemplateContext;
43 import net.pterodactylus.util.web.Method;
44 import freenet.support.api.Bucket;
45 import freenet.support.api.HTTPUploadedFile;
46
47 /**
48  * Page implementation that lets the user upload an image.
49  *
50  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51  */
52 public class UploadImagePage extends SoneTemplatePage {
53
54         /** The logger. */
55         private static final Logger logger = Logging.getLogger(UploadImagePage.class);
56
57         /**
58          * Creates a new “upload image” page.
59          *
60          * @param template
61          *            The template to render
62          * @param webInterface
63          *            The Sone web interface
64          */
65         public UploadImagePage(Template template, WebInterface webInterface) {
66                 super("uploadImage.html", template, "Page.UploadImage.Title", webInterface, true);
67         }
68
69         //
70         // SONETEMPLATEPAGE METHODS
71         //
72
73         /**
74          * {@inheritDoc}
75          */
76         @Override
77         protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
78                 super.processTemplate(request, templateContext);
79                 if (request.getMethod() == Method.POST) {
80                         Sone currentSone = getCurrentSone(request.getToadletContext());
81                         String parentId = request.getHttpRequest().getPartAsStringFailsafe("parent", 36);
82                         Album parent = webInterface.getCore().getAlbum(parentId, false);
83                         if (parent == null) {
84                                 /* TODO - signal error */
85                                 return;
86                         }
87                         if (!currentSone.equals(parent.getSone())) {
88                                 /* TODO - signal error. */
89                                 return;
90                         }
91                         String name = request.getHttpRequest().getPartAsStringFailsafe("title", 200);
92                         String description = request.getHttpRequest().getPartAsStringFailsafe("description", 4000);
93                         HTTPUploadedFile uploadedFile = request.getHttpRequest().getUploadedFile("image");
94                         Bucket fileBucket = uploadedFile.getData();
95                         InputStream imageInputStream = null;
96                         ByteArrayOutputStream imageDataOutputStream = null;
97                         net.pterodactylus.sone.data.Image image = null;
98                         try {
99                                 imageInputStream = fileBucket.getInputStream();
100                                 /* TODO - check length */
101                                 imageDataOutputStream = new ByteArrayOutputStream((int) fileBucket.size());
102                                 StreamCopier.copy(imageInputStream, imageDataOutputStream);
103                         } catch (IOException ioe1) {
104                                 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
105                                 return;
106                         } finally {
107                                 fileBucket.free();
108                                 Closer.close(imageInputStream);
109                                 Closer.close(imageDataOutputStream);
110                         }
111                         byte[] imageData = imageDataOutputStream.toByteArray();
112                         ByteArrayInputStream imageDataInputStream = null;
113                         Image uploadedImage = null;
114                         try {
115                                 imageDataInputStream = new ByteArrayInputStream(imageData);
116                                 uploadedImage = ImageIO.read(imageDataInputStream);
117                                 if (uploadedImage == null) {
118                                         templateContext.set("messages", webInterface.getL10n().getString("Page.UploadImage.Error.InvalidImage"));
119                                         return;
120                                 }
121                                 String mimeType = getMimeType(imageData);
122                                 TemporaryImage temporaryImage = webInterface.getCore().createTemporaryImage(mimeType, imageData);
123                                 image = webInterface.getCore().createImage(currentSone, parent, temporaryImage);
124                                 image.setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).setWidth(uploadedImage.getWidth(null)).setHeight(uploadedImage.getHeight(null));
125                         } catch (IOException ioe1) {
126                                 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
127                                 return;
128                         } finally {
129                                 Closer.close(imageDataInputStream);
130                                 Closer.flush(uploadedImage);
131                         }
132                         throw new RedirectException("imageBrowser.html?album=" + parent.getId());
133                 }
134         }
135
136         //
137         // PRIVATE METHODS
138         //
139
140         /**
141          * Tries to detect the MIME type of the encoded image.
142          *
143          * @param imageData
144          *            The encoded image
145          * @return The MIME type of the image, or “application/octet-stream” if the
146          *         image type could not be detected
147          */
148         private String getMimeType(byte[] imageData) {
149                 ByteArrayInputStream imageDataInputStream = new ByteArrayInputStream(imageData);
150                 try {
151                         ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageDataInputStream);
152                         Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
153                         if (imageReaders.hasNext()) {
154                                 return imageReaders.next().getOriginatingProvider().getMIMETypes()[0];
155                         }
156                 } catch (IOException ioe1) {
157                         logger.log(Level.FINE, "Could not detect MIME type for image.", ioe1);
158                 }
159                 return "application/octet-stream";
160         }
161
162 }