Add more tests for unfollow Sone page
[Sone.git] / src / main / java / net / pterodactylus / sone / web / pages / UploadImagePage.java
1 /*
2  * Sone - UploadImagePage.java - Copyright © 2011–2016 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.pages;
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.WebInterface;
42 import net.pterodactylus.sone.web.page.FreenetRequest;
43 import net.pterodactylus.util.io.Closer;
44 import net.pterodactylus.util.template.Template;
45 import net.pterodactylus.util.template.TemplateContext;
46 import net.pterodactylus.util.web.Method;
47
48 import com.google.common.io.ByteStreams;
49
50 import freenet.support.api.Bucket;
51 import freenet.support.api.HTTPUploadedFile;
52
53 /**
54  * Page implementation that lets the user upload an image.
55  *
56  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57  */
58 public class UploadImagePage extends SoneTemplatePage {
59
60         private static final Logger logger = getLogger(UploadImagePage.class.getName());
61         private static final String UNKNOWN_MIME_TYPE = "application/octet-stream";
62
63         /**
64          * Creates a new “upload image” page.
65          *
66          * @param template
67          *            The template to render
68          * @param webInterface
69          *            The Sone web interface
70          */
71         public UploadImagePage(Template template, WebInterface webInterface) {
72                 super("uploadImage.html", template, "Page.UploadImage.Title", webInterface, true);
73         }
74
75         //
76         // SONETEMPLATEPAGE METHODS
77         //
78
79         /**
80          * {@inheritDoc}
81          */
82         @Override
83         protected void handleRequest(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
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).trim();
95                         if (name.length() == 0) {
96                                 throw new RedirectException("emptyImageTitle.html");
97                         }
98                         String description = request.getHttpRequest().getPartAsStringFailsafe("description", 4000);
99                         HTTPUploadedFile uploadedFile = request.getHttpRequest().getUploadedFile("image");
100                         Bucket fileBucket = uploadedFile.getData();
101                         InputStream imageInputStream = null;
102                         ByteArrayOutputStream imageDataOutputStream = null;
103                         try {
104                                 imageInputStream = fileBucket.getInputStream();
105                                 /* TODO - check length */
106                                 imageDataOutputStream = new ByteArrayOutputStream((int) fileBucket.size());
107                                 ByteStreams.copy(imageInputStream, imageDataOutputStream);
108                         } catch (IOException ioe1) {
109                                 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
110                                 return;
111                         } finally {
112                                 fileBucket.free();
113                                 Closer.close(imageInputStream);
114                                 Closer.close(imageDataOutputStream);
115                         }
116                         byte[] imageData = imageDataOutputStream.toByteArray();
117                         ByteArrayInputStream imageDataInputStream = null;
118                         Image uploadedImage = null;
119                         try {
120                                 imageDataInputStream = new ByteArrayInputStream(imageData);
121                                 uploadedImage = ImageIO.read(imageDataInputStream);
122                                 if (uploadedImage == null) {
123                                         templateContext.set("messages", webInterface.getL10n().getString("Page.UploadImage.Error.InvalidImage"));
124                                         return;
125                                 }
126                                 String mimeType = getMimeType(imageData);
127                                 TemporaryImage temporaryImage = webInterface.getCore().createTemporaryImage(mimeType, imageData);
128                                 net.pterodactylus.sone.data.Image image = webInterface.getCore().createImage(currentSone, parent, temporaryImage);
129                                 image.modify().setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).setWidth(uploadedImage.getWidth(null)).setHeight(uploadedImage.getHeight(null)).update();
130                         } catch (IOException ioe1) {
131                                 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
132                                 return;
133                         } catch (ImageTitleMustNotBeEmpty itmnbe) {
134                                 throw new RedirectException("emptyImageTitle.html");
135                         } finally {
136                                 Closer.close(imageDataInputStream);
137                                 Closer.flush(uploadedImage);
138                         }
139                         throw new RedirectException("imageBrowser.html?album=" + parent.getId());
140                 }
141         }
142
143         //
144         // PRIVATE METHODS
145         //
146
147         /**
148          * Tries to detect the MIME type of the encoded image.
149          *
150          * @param imageData
151          *            The encoded image
152          * @return The MIME type of the image, or “application/octet-stream” if the
153          *         image type could not be detected
154          */
155         private static String getMimeType(byte[] imageData) {
156                 ByteArrayInputStream imageDataInputStream = new ByteArrayInputStream(imageData);
157                 try {
158                         ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageDataInputStream);
159                         Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
160                         if (imageReaders.hasNext()) {
161                                 return fromNullable(imageReaders.next().getOriginatingProvider().getMIMETypes())
162                                                 .or(new String[] { UNKNOWN_MIME_TYPE })[0];
163                         }
164                 } catch (IOException ioe1) {
165                         logger.log(Level.FINE, "Could not detect MIME type for image.", ioe1);
166                 }
167                 return UNKNOWN_MIME_TYPE;
168         }
169
170 }