readers = ImageIO.getImageReaders(iis);
+
+ String format = StringUtils.EMPTY;
+ while (readers.hasNext()) {
+ ImageReader read = readers.next();
+ format = read.getFormatName();
+ }
+ URLConnection urlConn;
+ try {
+ urlConn = url.openConnection();
+ } catch (IOException e) {
+ logger.error(String.format("Failed open url: %s", url.toString()));
+ throw e;
+ }
+
+ try (InputStream is = new BufferedInputStream(urlConn.getInputStream())) {
+ String attachmentType = attachmentTypeFromFormat(format);
+
+ String attachmentFName = DigestUtils.md5Hex(UUID.randomUUID().toString()) + "." + attachmentType;
+ Files.copy(is, Paths.get(tmpDir, attachmentFName));
+ return URI.create(String.format("juick://%s", attachmentFName));
+ } catch (IOException e) {
+ logger.error(String.format("Failed download image by url: %s", url.toString()), e);
+ throw e;
+ }
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/server/util/ImageUtils.java b/juick-server/src/main/java/com/juick/server/util/ImageUtils.java
new file mode 100644
index 00000000..d16faf8f
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/server/util/ImageUtils.java
@@ -0,0 +1,175 @@
+
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.server.util;
+
+import com.juick.Attachment;
+import org.apache.commons.imaging.ImageReadException;
+import org.apache.commons.imaging.Imaging;
+import org.apache.commons.imaging.common.ImageMetadata;
+import org.apache.commons.imaging.formats.jpeg.JpegImageMetadata;
+import org.apache.commons.imaging.formats.tiff.TiffField;
+import org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.FilenameUtils;
+import org.imgscalr.Scalr;
+import org.imgscalr.Scalr.Rotation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.FileImageInputStream;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.Iterator;
+
+public class ImageUtils {
+ private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
+
+ private String imgDir;
+ private String tmpDir;
+
+ public ImageUtils(String imgDir, String tmpDir) {
+ this.imgDir = imgDir;
+ this.tmpDir = tmpDir;
+ }
+/**
+ * Returns BufferedImage
, same as ImageIO.read()
does.
+ *
+ * JPEG images with EXIF metadata are rotated according to Orientation tag.
+ *
+ * @param imageFile a File
to read from.
+ */
+ private static BufferedImage readImageWithOrientation(File imageFile)
+ throws IOException {
+
+ BufferedImage image = ImageIO.read(imageFile);
+ if (!FilenameUtils.getExtension(imageFile.getName()).equals("jpg")) {
+ return image;
+ }
+
+ try {
+ ImageMetadata metadata = Imaging.getMetadata(imageFile);
+
+ if (metadata instanceof JpegImageMetadata) {
+ JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
+ TiffField orientationField = jpegMetadata.findEXIFValue(TiffTagConstants.TIFF_TAG_ORIENTATION);
+
+ if (orientationField != null) {
+ int orientation = orientationField.getIntValue();
+ switch (orientation) {
+ case TiffTagConstants.ORIENTATION_VALUE_ROTATE_90_CW:
+ image = Scalr.rotate(image, Rotation.CW_90);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_ROTATE_180:
+ image = Scalr.rotate(image, Rotation.CW_180);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_ROTATE_270_CW:
+ image = Scalr.rotate(image, Rotation.CW_270);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_MIRROR_HORIZONTAL:
+ image = Scalr.rotate(image, Rotation.FLIP_HORZ);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_MIRROR_VERTICAL:
+ image = Scalr.rotate(image, Rotation.FLIP_VERT);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_MIRROR_HORIZONTAL_AND_ROTATE_90_CW:
+ image = Scalr.rotate(Scalr.rotate(image, Rotation.FLIP_HORZ), Rotation.CW_90);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_MIRROR_HORIZONTAL_AND_ROTATE_270_CW:
+ image = Scalr.rotate(Scalr.rotate(image, Rotation.FLIP_HORZ), Rotation.CW_270);
+ break;
+ case TiffTagConstants.ORIENTATION_VALUE_HORIZONTAL_NORMAL:
+ default:
+ // do nothing
+ break;
+ }
+ }
+ }
+ } catch (ImageReadException e) {
+ // failed to read metadata.
+ // nothing to do here, return image as is.
+ }
+
+ return image;
+ }
+
+ public void saveImageWithPreviews(String tempFilename, String outputFilename)
+ throws IOException {
+ String ext = FilenameUtils.getExtension(outputFilename);
+
+ Path outputImagePath = Paths.get(imgDir, "p", outputFilename);
+ // this throws strange exceptions
+ // Files.move(Paths.get(tmpDir, tempFilename), outputImagePath);
+ FileUtils.moveFile(Paths.get(tmpDir, tempFilename).toFile(), outputImagePath.toFile());
+ BufferedImage originalImage = readImageWithOrientation(outputImagePath.toFile());
+
+ int width = originalImage.getWidth();
+ int height = originalImage.getHeight();
+ int maxDimension = (width > height) ? width : height;
+ BufferedImage image1024 = (maxDimension > 1024) ? Scalr.resize(originalImage, 1024) : originalImage;
+ BufferedImage image0512 = (maxDimension > 512) ? Scalr.resize(originalImage, 512) : originalImage;
+ BufferedImage image0160 = (maxDimension > 160) ? Scalr.resize(originalImage, 160) : originalImage;
+ ImageIO.write(image1024, ext, Paths.get(imgDir, "photos-1024", outputFilename).toFile());
+ ImageIO.write(image0512, ext, Paths.get(imgDir, "photos-512", outputFilename).toFile());
+ ImageIO.write(image0160, ext, Paths.get(imgDir, "ps", outputFilename).toFile());
+ }
+
+ public void saveAvatar(String tempFilename, int uid)
+ throws IOException {
+ String ext = FilenameUtils.getExtension(tempFilename);
+ String originalName = String.format("%s.%s", uid, ext);
+ Path originalPath = Paths.get(imgDir, "ao", originalName);
+ Files.move(Paths.get(tmpDir, tempFilename), originalPath, StandardCopyOption.REPLACE_EXISTING);
+ BufferedImage originalImage = ImageIO.read(originalPath.toFile());
+
+ String targetExt = "png";
+ String targetName = String.format("%s.%s", uid, targetExt);
+ ImageIO.write(Scalr.resize(originalImage, 96), targetExt, Paths.get(imgDir, "a", targetName).toFile());
+ ImageIO.write(Scalr.resize(originalImage, 32), targetExt, Paths.get(imgDir, "as", targetName).toFile());
+ }
+ public Attachment getAttachment(File imgFile) throws IOException {
+ Attachment attachment = new Attachment();
+ try (ImageInputStream stream = ImageIO.createImageInputStream(imgFile)) {
+ Iterator iter = ImageIO.getImageReaders(stream);
+ while (iter.hasNext()) {
+ ImageReader reader = iter.next();
+ try {
+ reader.setInput(stream);
+ attachment.setWidth(reader.getWidth(reader.getMinIndex()));
+ attachment.setHeight(reader.getHeight(reader.getMinIndex()));
+ return attachment;
+ } catch (Exception e) {
+ logger.debug("Error reading {}, trying next reader", imgFile.getAbsolutePath());
+ } finally {
+ reader.dispose();
+ }
+ }
+ }
+
+ logger.warn("Not a known image file {}", imgFile.getAbsolutePath());
+ return attachment;
+ }
+}
\ No newline at end of file
diff --git a/juick-server/src/main/java/com/juick/server/util/TagUtils.java b/juick-server/src/main/java/com/juick/server/util/TagUtils.java
new file mode 100644
index 00000000..cb828933
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/server/util/TagUtils.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.server.util;
+
+import com.juick.Tag;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Created by aalexeev on 11/13/16.
+ */
+public class TagUtils {
+ private TagUtils() {
+ throw new IllegalStateException();
+ }
+
+ public static String toString(final List tags) {
+ if (CollectionUtils.isEmpty(tags))
+ return StringUtils.EMPTY;
+
+ return tags.stream().map(t -> "*" + t.getName())
+ .collect(Collectors.joining(" "));
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/server/util/UserUtils.java b/juick-server/src/main/java/com/juick/server/util/UserUtils.java
new file mode 100644
index 00000000..1adc85ab
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/server/util/UserUtils.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.server.util;
+
+import com.juick.User;
+import com.juick.model.AnonymousUser;
+import com.juick.service.security.entities.JuickUser;
+import javax.annotation.Nonnull;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+/**
+ * Created by aalexeev on 11/14/16.
+ */
+public class UserUtils {
+ private UserUtils() {
+ throw new IllegalStateException();
+ }
+
+ public static Authentication getAuthentication() {
+ return SecurityContextHolder.getContext().getAuthentication();
+ }
+
+ public static Object getPrincipal(final Authentication authentication) {
+ return authentication == null ? null : authentication.getPrincipal();
+ }
+
+ @Nonnull
+ public static User getCurrentUser() {
+ Object principal = getPrincipal(getAuthentication());
+
+ if (principal instanceof JuickUser)
+ return ((JuickUser) principal).getUser();
+
+ if (principal instanceof User)
+ return (User) principal;
+
+ return AnonymousUser.INSTANCE;
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/server/util/WebUtils.java b/juick-server/src/main/java/com/juick/server/util/WebUtils.java
new file mode 100644
index 00000000..9dd628ee
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/server/util/WebUtils.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.server.util;
+
+import java.util.regex.Pattern;
+
+/**
+ * Created by aalexeev on 11/28/16.
+ */
+public class WebUtils {
+ private WebUtils() {
+ throw new IllegalStateException();
+ }
+
+ private static final Pattern USER_NAME_PATTERN = Pattern.compile("[a-zA-Z-_\\d]{2,16}");
+
+ private static final Pattern POST_NUMBER_PATTERN = Pattern.compile("-?\\d+");
+
+ private static final Pattern JID_PATTERN = Pattern.compile("^[a-zA-Z0-9\\\\-\\\\_\\\\@\\\\.]{6,64}$");
+
+
+ public static boolean isPostNumber(final String aString) {
+ return aString != null && POST_NUMBER_PATTERN.matcher(aString).matches();
+ }
+
+ public static boolean isNotPostNumber(final String aString) {
+ return !isPostNumber(aString);
+ }
+
+ public static boolean isUserName(final String aString) {
+ return aString != null && USER_NAME_PATTERN.matcher(aString).matches();
+ }
+
+ public static boolean isNotUserName(final String aString) {
+ return !isUserName(aString);
+ }
+
+ public static boolean isJid(final String aString) {
+ return aString != null && JID_PATTERN.matcher(aString).matches();
+ }
+
+ public static boolean isNotJid(final String aString) {
+ return !isJid(aString);
+ }
+
+
+}
diff --git a/juick-server/src/main/java/com/juick/server/www/controllers/NewMessage.java b/juick-server/src/main/java/com/juick/server/www/controllers/NewMessage.java
index 9e364ff8..c476e5c2 100644
--- a/juick-server/src/main/java/com/juick/server/www/controllers/NewMessage.java
+++ b/juick-server/src/main/java/com/juick/server/www/controllers/NewMessage.java
@@ -19,8 +19,8 @@ package com.juick.server.www.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juick.Message;
import com.juick.User;
-import com.juick.server.helpers.AnonymousUser;
-import com.juick.server.helpers.CommandResult;
+import com.juick.model.AnonymousUser;
+import com.juick.model.CommandResult;
import com.juick.server.util.*;
import com.juick.server.www.WebApp;
import com.juick.service.*;
diff --git a/juick-server/src/main/java/com/juick/server/www/controllers/Settings.java b/juick-server/src/main/java/com/juick/server/www/controllers/Settings.java
index f2ecccf6..6405b3bd 100644
--- a/juick-server/src/main/java/com/juick/server/www/controllers/Settings.java
+++ b/juick-server/src/main/java/com/juick/server/www/controllers/Settings.java
@@ -16,8 +16,8 @@
*/
package com.juick.server.www.controllers;
-import com.juick.server.helpers.NotifyOpts;
-import com.juick.server.helpers.UserInfo;
+import com.juick.model.NotifyOpts;
+import com.juick.model.UserInfo;
import com.juick.server.util.*;
import com.juick.service.*;
import org.apache.commons.lang3.RandomStringUtils;
@@ -25,7 +25,6 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
@@ -45,7 +44,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
diff --git a/juick-server/src/main/java/com/juick/server/www/controllers/SocialLogin.java b/juick-server/src/main/java/com/juick/server/www/controllers/SocialLogin.java
index 93d3946a..3cea3e34 100644
--- a/juick-server/src/main/java/com/juick/server/www/controllers/SocialLogin.java
+++ b/juick-server/src/main/java/com/juick/server/www/controllers/SocialLogin.java
@@ -24,7 +24,7 @@ import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.*;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.github.scribejava.core.oauth.OAuth20Service;
-import com.juick.facebook.User;
+import com.juick.model.facebook.User;
import com.juick.server.util.HttpBadRequestException;
import com.juick.server.util.UserUtils;
import com.juick.service.CrosspostService;
@@ -32,7 +32,7 @@ import com.juick.service.EmailService;
import com.juick.service.TelegramService;
import com.juick.service.UserService;
import com.juick.server.www.Utils;
-import com.juick.vk.UsersResponse;
+import com.juick.model.vk.UsersResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
@@ -216,8 +216,8 @@ public class SocialLogin {
OAuth1AccessToken accessToken = oAuthService.getAccessToken(requestToken, verifier);
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, TWITTER_VERIFY_URL);
oAuthService.signRequest(accessToken, oAuthRequest);
- com.juick.twitter.User twitterUser = jsonMapper.readValue(oAuthService.execute(oAuthRequest).getBody(),
- com.juick.twitter.User.class);
+ com.juick.model.twitter.User twitterUser = jsonMapper.readValue(oAuthService.execute(oAuthRequest).getBody(),
+ com.juick.model.twitter.User.class);
if (userService.linkTwitterAccount(user, accessToken.getToken(), accessToken.getTokenSecret(),
twitterUser.getScreenName())) {
response.setStatus(HttpServletResponse.SC_FOUND);
@@ -265,7 +265,7 @@ public class SocialLogin {
vkService.signRequest(token, meRequest);
String graph = vkService.execute(meRequest).getBody();
- com.juick.vk.User jsonUser = jsonMapper.readValue(graph, UsersResponse.class).getUsers().get(0);
+ com.juick.model.vk.User jsonUser = jsonMapper.readValue(graph, UsersResponse.class).getUsers().get(0);
String vkName = jsonUser.getFirstName() + " " + jsonUser.getLastName();
String vkLink = jsonUser.getScreenName();
diff --git a/juick-server/src/main/java/com/juick/service/CrosspostServiceImpl.java b/juick-server/src/main/java/com/juick/service/CrosspostServiceImpl.java
index 14bdc7e2..47d1870b 100644
--- a/juick-server/src/main/java/com/juick/service/CrosspostServiceImpl.java
+++ b/juick-server/src/main/java/com/juick/service/CrosspostServiceImpl.java
@@ -18,7 +18,7 @@
package com.juick.service;
import com.juick.ExternalToken;
-import com.juick.server.helpers.ApplicationStatus;
+import com.juick.model.ApplicationStatus;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.dao.EmptyResultDataAccessException;
diff --git a/juick-server/src/main/java/com/juick/service/ImagesServiceImpl.java b/juick-server/src/main/java/com/juick/service/ImagesServiceImpl.java
new file mode 100644
index 00000000..67c8360e
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/ImagesServiceImpl.java
@@ -0,0 +1,82 @@
+package com.juick.service;
+
+import com.juick.Attachment;
+import com.juick.Message;
+import com.juick.Photo;
+import com.juick.server.util.ImageUtils;
+import org.springframework.util.StringUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Paths;
+
+public class ImagesServiceImpl implements ImagesService {
+ private ImageUtils imageUtils;
+ private String imgDir;
+ private String tmpDir;
+ public ImagesServiceImpl(String imgDir, String tmpDir) {
+ this.imgDir = imgDir;
+ this.tmpDir = tmpDir;
+ imageUtils = new ImageUtils(imgDir, tmpDir);
+ }
+ @Override
+ public void setAttachmentMetadata(String baseUrl, Message msg) throws Exception {
+ if (!StringUtils.isEmpty(msg.getAttachmentType())) {
+ Photo photo = new Photo();
+ if (msg.getRid()> 0) {
+ photo.setSmall(String.format("%sphotos-512/%d-%d.%s", baseUrl, msg.getMid(), msg.getRid(), msg.getAttachmentType()));
+ photo.setMedium(String.format("%sphotos-1024/%d-%d.%s", baseUrl, msg.getMid(), msg.getRid(), msg.getAttachmentType()));
+ photo.setThumbnail(String.format("%sps/%d-%d.%s", baseUrl, msg.getMid(), msg.getRid(), msg.getAttachmentType()));
+ } else {
+ photo.setSmall(String.format("%sphotos-512/%d.%s", baseUrl, msg.getMid(), msg.getAttachmentType()));
+ photo.setMedium(String.format("%sphotos-1024/%d.%s", baseUrl, msg.getMid(), msg.getAttachmentType()));
+ photo.setThumbnail(String.format("%sps/%d.%s", baseUrl, msg.getMid(), msg.getAttachmentType()));
+ }
+ msg.setPhoto(photo);
+ String imageName = String.format("%s.%s", msg.getMid(), msg.getAttachmentType());
+ if (msg.getRid() > 0) {
+ imageName = String.format("%s-%s.%s", msg.getMid(), msg.getRid(), msg.getAttachmentType());
+ }
+ File fullImage = Paths.get(imgDir, "p", imageName).toFile();
+ File mediumImage = Paths.get(imgDir, "photos-1024", imageName).toFile();
+ File smallImage = Paths.get(imgDir, "photos-512", imageName).toFile();
+ File thumbnailImage = Paths.get(imgDir, "ps", imageName).toFile();
+ StringBuilder builder = new StringBuilder();
+ builder.append(baseUrl);
+ builder.append(msg.getAttachmentType().equals("mp4") ? "video" : "p");
+ builder.append("/").append(msg.getMid());
+ if (msg.getRid() > 0) {
+ builder.append("-").append(msg.getRid());
+ }
+ builder.append(".").append(msg.getAttachmentType());
+ String originalUrl = builder.toString();
+
+ Attachment original = imageUtils.getAttachment(fullImage);
+ original.setUrl(originalUrl);
+
+ Attachment medium = imageUtils.getAttachment(mediumImage);
+ medium.setUrl(photo.getMedium());
+ original.setMedium(medium);
+
+ Attachment small = imageUtils.getAttachment(smallImage);
+ small.setUrl(photo.getSmall());
+ original.setSmall(small);
+
+ Attachment thumb = imageUtils.getAttachment(thumbnailImage);
+ thumb.setUrl(photo.getMedium());
+ original.setThumbnail(thumb);
+
+ msg.setAttachment(original);
+ }
+ }
+
+ @Override
+ public void saveImageWithPreviews(String tempFilename, String outputFilename) throws IOException {
+ imageUtils.saveImageWithPreviews(tempFilename, outputFilename);
+ }
+
+ @Override
+ public void saveAvatar(String tempFilename, int uid) throws IOException {
+ imageUtils.saveAvatar(tempFilename, uid);
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java b/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java
index 0abe9309..b0707232 100644
--- a/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java
+++ b/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java
@@ -18,10 +18,9 @@
package com.juick.service;
import com.juick.*;
-import com.juick.server.helpers.PrivacyOpts;
-import com.juick.server.helpers.ResponseReply;
+import com.juick.model.PrivacyOpts;
+import com.juick.model.ResponseReply;
import com.juick.server.util.HttpNotFoundException;
-import com.juick.service.security.entities.JuickUser;
import com.juick.util.MessageUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
diff --git a/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java b/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java
index 1dee379f..492fef1c 100644
--- a/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java
+++ b/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java
@@ -20,7 +20,7 @@ package com.juick.service;
import com.juick.Message;
import com.juick.Tag;
import com.juick.User;
-import com.juick.server.helpers.NotifyOpts;
+import com.juick.model.NotifyOpts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
diff --git a/juick-server/src/main/java/com/juick/service/TagServiceImpl.java b/juick-server/src/main/java/com/juick/service/TagServiceImpl.java
index aa6c3713..42159d3b 100644
--- a/juick-server/src/main/java/com/juick/service/TagServiceImpl.java
+++ b/juick-server/src/main/java/com/juick/service/TagServiceImpl.java
@@ -19,7 +19,7 @@ package com.juick.service;
import com.juick.Tag;
import com.juick.User;
-import com.juick.server.helpers.TagStats;
+import com.juick.model.TagStats;
import com.juick.util.StreamUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
diff --git a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java
index bd72bed9..82e9a124 100644
--- a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java
+++ b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java
@@ -19,9 +19,9 @@ package com.juick.service;
import com.juick.Message;
import com.juick.User;
-import com.juick.server.helpers.AnonymousUser;
-import com.juick.server.helpers.Auth;
-import com.juick.server.helpers.UserInfo;
+import com.juick.model.AnonymousUser;
+import com.juick.model.Auth;
+import com.juick.model.UserInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
diff --git a/juick-server/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java b/juick-server/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java
new file mode 100644
index 00000000..9215d09a
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.service.security;
+
+import com.juick.User;
+import com.juick.service.security.entities.JuickUser;
+import com.juick.service.UserService;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
+import org.springframework.security.authentication.RememberMeAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.RememberMeServices;
+import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
+import org.springframework.util.Assert;
+import org.springframework.web.filter.OncePerRequestFilter;
+import org.springframework.web.util.WebUtils;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Created by aalexeev on 4/5/17.
+ */
+public class HashParamAuthenticationFilter extends OncePerRequestFilter {
+ public static final String PARAM_NAME = "hash";
+
+ private final UserService userService;
+ private final RememberMeServices rememberMeServices;
+
+
+ public HashParamAuthenticationFilter(
+ final UserService userService,
+ final RememberMeServices rememberMeServices) {
+ Assert.notNull(userService, "userService should not be null");
+ Assert.notNull(rememberMeServices, "rememberMeServices should not be null");
+
+ this.userService = userService;
+ this.rememberMeServices = rememberMeServices;
+ }
+
+ @Override
+ protected void doFilterInternal(
+ HttpServletRequest request,
+ HttpServletResponse response,
+ FilterChain filterChain) throws ServletException, IOException {
+
+ String hash = getHashFromRequest(request);
+
+ if (hash != null && authenticationIsRequired()) {
+ User user = userService.getUserByHash(hash);
+
+ if (!user.isAnonymous()) {
+ User userWithPassword = userService.getUserByName(user.getName());
+ userWithPassword.setAuthHash(userService.getHashByUID(userWithPassword.getUid()));
+ Authentication authentication = new RememberMeAuthenticationToken(
+ ((AbstractRememberMeServices)rememberMeServices).getKey(), new JuickUser(userWithPassword), JuickUser.USER_AUTHORITY);
+
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+
+ rememberMeServices.loginSuccess(request, response, authentication);
+ }
+ }
+
+ filterChain.doFilter(request, response);
+ }
+
+ private boolean authenticationIsRequired() {
+ Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
+
+ return existingAuth == null ||
+ !existingAuth.isAuthenticated() ||
+ existingAuth instanceof AnonymousAuthenticationToken;
+ }
+
+ private String getHashFromRequest(HttpServletRequest request) {
+ String paramHash = request.getParameter(PARAM_NAME);
+ Cookie cookieHash = WebUtils.getCookie(request, PARAM_NAME);
+
+ if (paramHash == null && cookieHash != null) {
+ return cookieHash.getValue();
+ }
+ return paramHash;
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java b/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java
new file mode 100644
index 00000000..59425fab
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.service.security;
+
+import com.juick.service.UserService;
+import com.juick.service.security.entities.JuickUser;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.util.Assert;
+
+/**
+ * Created by aalexeev on 11/28/16.
+ */
+public class JuickUserDetailsService implements UserDetailsService {
+ private final UserService userService;
+
+ public JuickUserDetailsService(final UserService userService) {
+ Assert.notNull(userService, "UserService must be initialized");
+ this.userService = userService;
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
+ if (StringUtils.isBlank(username))
+ throw new UsernameNotFoundException("Invalid user name " + username);
+
+ com.juick.User user = userService.getUserByName(username);
+
+ if (!user.isAnonymous()) {
+ user.setAuthHash(userService.getHashByUID(user.getUid()));
+ return new JuickUser(user);
+ }
+
+ throw new UsernameNotFoundException("The username " + username + " is not found");
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/service/security/NullUserDetailsService.java b/juick-server/src/main/java/com/juick/service/security/NullUserDetailsService.java
new file mode 100644
index 00000000..91acefa3
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/security/NullUserDetailsService.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.service.security;
+
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+
+/**
+ * Created by aalexeev on 11/28/16.
+ */
+public class NullUserDetailsService implements UserDetailsService {
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ throw new UsernameNotFoundException(
+ "loadUserByUsername called for NullUserDetailsService, user " + username + "can not be found");
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/service/security/deprecated/CookieSimpleHashRememberMeServices.java b/juick-server/src/main/java/com/juick/service/security/deprecated/CookieSimpleHashRememberMeServices.java
new file mode 100644
index 00000000..e385d7dd
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/security/deprecated/CookieSimpleHashRememberMeServices.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.service.security.deprecated;
+
+import com.juick.User;
+import com.juick.service.security.entities.JuickUser;
+import com.juick.service.UserService;
+import com.juick.service.security.NullUserDetailsService;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.env.Environment;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.web.authentication.RememberMeServices;
+import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
+import org.springframework.security.web.authentication.rememberme.InvalidCookieException;
+import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
+import org.springframework.util.Assert;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Optional;
+
+/**
+ * Created by aalexeev on 11/28/16.
+ *
+ * @deprecated not recommended use for secure reasons
+ */
+@Deprecated
+public class CookieSimpleHashRememberMeServices extends AbstractRememberMeServices implements RememberMeServices {
+ private static final Logger logger = LoggerFactory.getLogger(CookieSimpleHashRememberMeServices.class);
+
+ private static final String COOKIE_PARAM_NAME = "hash";
+
+ private final UserService userService;
+
+ public CookieSimpleHashRememberMeServices(
+ final String key, final UserService userService, final Environment environment) {
+ super(key, new NullUserDetailsService());
+
+ Assert.notNull(userService);
+ Assert.notNull(environment);
+
+ this.userService = userService;
+
+ setCookieName(COOKIE_PARAM_NAME);
+ setCookieDomain(environment.getProperty("web_domain", "localhost"));
+ setAlwaysRemember(true);
+ }
+
+ @Override
+ public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
+ super.logout(request, response, authentication);
+ userService.deleteLoginForUser(authentication.getName());
+ }
+
+ @Override
+ protected void onLoginSuccess(
+ HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
+ String username = successfulAuthentication.getName();
+
+ logger.debug("Creating new persistent login for user {}", username);
+
+ try {
+ int uid = userService.getUIDbyName(username);
+
+ Assert.isTrue(uid > 0);
+
+ String hash = RandomStringUtils.randomAlphanumeric(16).toUpperCase();
+
+ userService.setLoginForUser(uid, hash);
+
+ setCookie(new String[]{hash}, getTokenValiditySeconds(), request, response);
+ } catch (Exception e) {
+ logger.error("Failed to save cookies", e);
+ }
+ }
+
+ @Override
+ protected UserDetails processAutoLoginCookie(
+ String[] cookieTokens, HttpServletRequest request, HttpServletResponse response)
+ throws RememberMeAuthenticationException, UsernameNotFoundException {
+ String hash = cookieTokens[0];
+
+ if (StringUtils.isBlank(hash)) {
+ hash = request.getParameter("hash");
+ }
+ if (StringUtils.isBlank(hash)) {
+ throw new InvalidCookieException("Cookie is invalid and hash parameter not found");
+ }
+
+ int uid = userService.getUIDbyHash(hash);
+ if (uid <= 0)
+ throw new UsernameNotFoundException("User not found by hash, cookies" + cookieTokens);
+
+ Optional userOptional = userService.getUserByUID(uid);
+
+ Assert.isTrue(userOptional.isPresent());
+
+ return new JuickUser(userService.getUserByName(userOptional.get().getName()));
+ }
+
+ @Override
+ protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
+ return new String[]{cookieValue};
+ }
+
+ @Override
+ protected String encodeCookie(String[] cookieTokens) {
+ return cookieTokens != null && cookieTokens.length > 0 ? cookieTokens[0] : StringUtils.EMPTY;
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/service/security/deprecated/RequestParamHashRememberMeServices.java b/juick-server/src/main/java/com/juick/service/security/deprecated/RequestParamHashRememberMeServices.java
new file mode 100644
index 00000000..3631e5a4
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/security/deprecated/RequestParamHashRememberMeServices.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.service.security.deprecated;
+
+import com.juick.User;
+import com.juick.service.security.entities.JuickUser;
+import com.juick.service.UserService;
+import com.juick.service.security.NullUserDetailsService;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.web.authentication.RememberMeServices;
+import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
+import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
+import org.springframework.util.Assert;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Created by aalexeev on 11/30/16.
+ *
+ * @deprecated for security reasons
+ */
+@Deprecated
+public class RequestParamHashRememberMeServices extends AbstractRememberMeServices implements RememberMeServices {
+ private static final String PARAM_NAME = "hash";
+
+ private final UserService userService;
+
+ public RequestParamHashRememberMeServices(String key, UserService userService) {
+ super(key, new NullUserDetailsService());
+
+ Assert.notNull(userService);
+ this.userService = userService;
+ setAlwaysRemember(false);
+ }
+
+ @Override
+ protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
+ // do nothing
+ }
+
+ @Override
+ protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
+ return false; // always false
+ }
+
+ @Override
+ protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
+ // do nothing
+ }
+
+ @Override
+ protected String extractRememberMeCookie(HttpServletRequest request) {
+ return PARAM_NAME; // return any not blank value
+ }
+
+ @Override
+ protected UserDetails processAutoLoginCookie(
+ String[] cookieTokens, HttpServletRequest request, HttpServletResponse response)
+ throws RememberMeAuthenticationException, UsernameNotFoundException {
+ String hash = request.getParameter(PARAM_NAME);
+
+ if (StringUtils.isNotBlank(hash)) {
+ User user = userService.getUserByHash(hash);
+ if (!user.isAnonymous())
+ return new JuickUser(userService.getUserByName(user.getName()));
+ }
+ throw new UsernameNotFoundException("User not found by hash " + hash);
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/service/security/entities/JuickUser.java b/juick-server/src/main/java/com/juick/service/security/entities/JuickUser.java
new file mode 100644
index 00000000..c43f112f
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/service/security/entities/JuickUser.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.service.security.entities;
+
+import com.juick.User;
+import com.juick.model.AnonymousUser;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Created by aalexeev on 11/21/16.
+ */
+public class JuickUser implements UserDetails {
+ static final GrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER");
+ static final GrantedAuthority ROLE_ANONYMOUS = new SimpleGrantedAuthority("ROLE_ANONYMOUS");
+
+ public static final List USER_AUTHORITY = Collections.singletonList(ROLE_USER);
+ public static final List ANONYMOUS_AUTHORITY = Collections.singletonList(ROLE_ANONYMOUS);
+
+ public static final JuickUser ANONYMOUS_USER = new JuickUser(AnonymousUser.INSTANCE, ANONYMOUS_AUTHORITY);
+
+ private final com.juick.User user;
+ private final Collection extends GrantedAuthority> authorities;
+
+ public JuickUser(com.juick.User user) {
+ this(user, USER_AUTHORITY);
+ }
+
+ public JuickUser(com.juick.User user, Collection extends GrantedAuthority> authorities) {
+ this.user = user;
+ this.authorities = authorities;
+ }
+
+ @Override
+ public Collection extends GrantedAuthority> getAuthorities() {
+ return authorities;
+ }
+
+ @Override
+ public String getPassword() {
+ return "{noop}" + user.getCredentials();
+ }
+
+ @Override
+ public String getUsername() {
+ return user.getName();
+ }
+
+ @Override
+ public boolean isAccountNonExpired() {
+ return true;
+ }
+
+ @Override
+ public boolean isAccountNonLocked() {
+ return StringUtils.isNotBlank(user.getCredentials());
+ }
+
+ @Override
+ public boolean isCredentialsNonExpired() {
+ return isAccountNonLocked();
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return !user.isBanned() && isCredentialsNonExpired();
+ }
+
+ public User getUser() {
+ return user;
+ }
+}
--
cgit v1.2.3