2 * Sone - UploadImagePage.java - Copyright © 2011–2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.web;
20 import java.awt.Dimension;
21 import java.awt.Image;
22 import java.awt.image.ImageObserver;
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.Iterator;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.atomic.AtomicInteger;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32 import javax.imageio.ImageIO;
33 import javax.imageio.ImageReader;
34 import javax.imageio.stream.ImageInputStream;
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.data.TemporaryImage;
39 import net.pterodactylus.sone.text.TextFilter;
40 import net.pterodactylus.sone.web.page.FreenetRequest;
41 import net.pterodactylus.util.io.Closer;
42 import net.pterodactylus.util.logging.Logging;
43 import net.pterodactylus.util.template.Template;
44 import net.pterodactylus.util.template.TemplateContext;
45 import net.pterodactylus.util.web.Method;
47 import freenet.support.api.Bucket;
48 import freenet.support.api.HTTPUploadedFile;
50 import com.google.common.base.Optional;
51 import com.google.common.io.ByteStreams;
54 * Page implementation that lets the user upload an image.
56 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58 public class UploadImagePage extends SoneTemplatePage {
61 private static final Logger logger = Logging.getLogger(UploadImagePage.class);
64 * Creates a new “upload image” page.
67 * The template to render
69 * The Sone web interface
71 public UploadImagePage(Template template, WebInterface webInterface) {
72 super("uploadImage.html", template, "Page.UploadImage.Title", webInterface, true);
76 // SONETEMPLATEPAGE METHODS
80 protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
81 super.processTemplate(request, templateContext);
82 if (request.getMethod() == Method.POST) {
83 Sone currentSone = getCurrentSone(request.getToadletContext());
84 String parentId = request.getHttpRequest().getPartAsStringFailsafe("parent", 36);
85 Optional<Album> parent = webInterface.getCore().getAlbum(parentId);
86 if (!parent.isPresent()) {
87 /* TODO - signal error */
90 if (!currentSone.equals(parent.get().getSone())) {
91 /* TODO - signal error. */
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 net.pterodactylus.sone.data.Image image = null;
102 imageInputStream = fileBucket.getInputStream();
103 /* TODO - check length */
104 imageDataOutputStream = new ByteArrayOutputStream((int) fileBucket.size());
105 ByteStreams.copy(imageInputStream, imageDataOutputStream);
106 } catch (IOException ioe1) {
107 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
111 Closer.close(imageInputStream);
112 Closer.close(imageDataOutputStream);
114 byte[] imageData = imageDataOutputStream.toByteArray();
115 ByteArrayInputStream imageDataInputStream = null;
116 Image uploadedImage = null;
118 imageDataInputStream = new ByteArrayInputStream(imageData);
119 uploadedImage = ImageIO.read(imageDataInputStream);
120 if (uploadedImage == null) {
121 templateContext.set("messages", webInterface.getL10n().getString("Page.UploadImage.Error.InvalidImage"));
124 String mimeType = getMimeType(imageData);
125 Dimension imageSize = getImageDimensions(uploadedImage);
126 TemporaryImage temporaryImage = webInterface.getCore().createTemporaryImage(mimeType, imageData, imageSize.width, imageSize.height);
127 image = webInterface.getCore().createImage(currentSone, parent.get(), temporaryImage);
128 image.modify().setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).update();
129 } catch (IOException ioe1) {
130 logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
133 Closer.close(imageDataInputStream);
134 Closer.flush(uploadedImage);
136 throw new RedirectException("imageBrowser.html?album=" + parent.get().getId());
140 private static Dimension getImageDimensions(Image uploadedImage) {
141 final CountDownLatch widthHeightLatch = new CountDownLatch(2);
142 final AtomicInteger finalWidth = new AtomicInteger();
143 final AtomicInteger finalHeight = new AtomicInteger();
144 ImageObserver imageObserver = new ImageObserver() {
146 public boolean imageUpdate(Image image, int infoFlags, int x, int y, int width, int height) {
147 if ((infoFlags & WIDTH) != 0) {
148 finalWidth.set(width);
149 widthHeightLatch.countDown();
151 if ((infoFlags & HEIGHT) != 0) {
152 finalHeight.set(width);
153 widthHeightLatch.countDown();
155 return (infoFlags & ALLBITS) != 0;
158 finalWidth.set(uploadedImage.getWidth(imageObserver));
159 finalHeight.set(uploadedImage.getHeight(imageObserver));
160 while ((finalWidth.get() == -1) || (finalHeight.get() == -1)) {
162 widthHeightLatch.await();
163 } catch (InterruptedException ie1) {
164 logger.log(Level.WARNING, "Interrupted while waiting for latch...");
167 return new Dimension(finalWidth.get(), finalHeight.get());
175 * Tries to detect the MIME type of the encoded image.
179 * @return The MIME type of the image, or “application/octet-stream” if the
180 * image type could not be detected
182 private static String getMimeType(byte[] imageData) {
183 ByteArrayInputStream imageDataInputStream = new ByteArrayInputStream(imageData);
185 ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageDataInputStream);
186 Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
187 if (imageReaders.hasNext()) {
188 return imageReaders.next().getOriginatingProvider().getMIMETypes()[0];
190 } catch (IOException ioe1) {
191 logger.log(Level.FINE, "Could not detect MIME type for image.", ioe1);
193 return "application/octet-stream";