diff options
Diffstat (limited to 'juick-server')
4 files changed, 133 insertions, 79 deletions
diff --git a/juick-server/src/main/java/com/juick/server/CommandsManager.java b/juick-server/src/main/java/com/juick/server/CommandsManager.java index 6b6b3e53..a6a3a6e1 100644 --- a/juick-server/src/main/java/com/juick/server/CommandsManager.java +++ b/juick-server/src/main/java/com/juick/server/CommandsManager.java @@ -25,12 +25,15 @@ import com.juick.server.component.MessageEvent; import com.juick.server.component.PingEvent; import com.juick.server.component.SubscribeEvent; import com.juick.server.helpers.TagStats; +import com.juick.server.util.HttpUtils; +import com.juick.server.util.ImageUtils; import com.juick.server.xmpp.helpers.annotation.UserCommand; import com.juick.service.*; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.ocpsoft.prettytime.PrettyTime; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import rocks.xmpp.addr.Jid; @@ -39,6 +42,9 @@ import javax.annotation.PostConstruct; import javax.inject.Inject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URI; +import java.nio.file.Paths; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -65,6 +71,10 @@ public class CommandsManager { private PrivacyQueriesService privacyQueriesService; @Inject private SubscriptionService subscriptionService; + @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}") + private String tmpDir; + @Value("${img_path:#{systemEnvironment['TEMP'] ?: '/tmp'}}") + private String imgDir; @Inject private ApplicationEventPublisher applicationEventPublisher; @@ -74,7 +84,7 @@ public class CommandsManager { } - public Optional<String> processCommand(User user, Jid from, String input) throws InvocationTargetException, + public Optional<String> processCommand(User user, Jid from, String input, URI attachment) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { Optional<Method> cmd = MethodUtils.getMethodsListWithAnnotation(getClass(), UserCommand.class).stream() .filter(m -> Pattern.compile(m.getAnnotation(UserCommand.class).pattern(), @@ -89,22 +99,22 @@ public class CommandsManager { groups.add(matcher.group(i)); } } - return Optional.of((String) getClass().getMethod(cmd.get().getName(), User.class, Jid.class, String[].class) - .invoke(this, user, from, groups.toArray(new String[groups.size()]))); + return Optional.of((String) getClass().getMethod(cmd.get().getName(), User.class, Jid.class, URI.class, String[].class) + .invoke(this, user, from, attachment, groups.toArray(new String[groups.size()]))); } return Optional.empty(); } @UserCommand(pattern = "^ping$", patternFlags = Pattern.CASE_INSENSITIVE, help = "PING - returns you a PONG") - public String commandPing(User user, Jid from, String[] input) { + public String commandPing(User user, Jid from, URI attachment, String[] input) { applicationEventPublisher.publishEvent(new PingEvent(this, user)); return "PONG"; } @UserCommand(pattern = "^help$", patternFlags = Pattern.CASE_INSENSITIVE, help = "HELP - returns this help message") - public String commandHelp(User user, Jid from, String[] input) { + public String commandHelp(User user, Jid from, URI attachment, String[] input) { return Arrays.stream(getClass().getDeclaredMethods()) .filter(m -> m.isAnnotationPresent(UserCommand.class)) .map(m -> m.getAnnotation(UserCommand.class).help()) @@ -113,11 +123,11 @@ public class CommandsManager { @UserCommand(pattern = "^login$", patternFlags = Pattern.CASE_INSENSITIVE, help = "LOGIN - log in to Juick website") - public String commandLogin(User user_from, Jid from, String[] input) { + public String commandLogin(User user_from, Jid from, URI attachment, String[] input) { return "http://juick.com/login?hash=" + userService.getHashByUID(user_from.getUid()); } @UserCommand(pattern = "^\\@(\\S+)\\s+([\\s\\S]+)$", help = "@username message - send PM to username") - public String commandPM(User user_from, Jid from, String... arguments) { + public String commandPM(User user_from, Jid from, URI attachment, String... arguments) { String body = arguments[1]; User user_to = userService.getUserByName(arguments[0]); @@ -138,7 +148,7 @@ public class CommandsManager { } @UserCommand(pattern = "^bl$", patternFlags = Pattern.CASE_INSENSITIVE, help = "BL - Show your blacklist") - public String commandBLShow(User user_from, Jid from, String... arguments) { + public String commandBLShow(User user_from, Jid from, URI attachment, String... arguments) { List<User> blusers = userService.getUserBLUsers(user_from.getUid()); List<String> bltags = tagService.getUserBLTags(user_from.getUid()); @@ -165,13 +175,13 @@ public class CommandsManager { } @UserCommand(pattern = "^#\\+$", help = "#+ - Show last Juick messages") - public String commandLast(User user_from, Jid from, String... arguments) { + public String commandLast(User user_from, Jid from, URI attachment, String... arguments) { return "Last messages:\n" + printMessages(messagesService.getAll(user_from.getUid(), 0), true); } @UserCommand(pattern = "@", help = "@ - Show recommendations and popular personal blogs") - public String commandUsers(User user_from, Jid from, String... arguments) { + public String commandUsers(User user_from, Jid from, URI attachment, String... arguments) { StringBuilder msg = new StringBuilder(); msg.append("Recommended blogs"); List<String> recommendedUsers = showQueriesService.getRecommendedUsers(user_from); @@ -195,7 +205,7 @@ public class CommandsManager { } @UserCommand(pattern = "^bl\\s+@([^\\s\\n\\+]+)", patternFlags = Pattern.CASE_INSENSITIVE, help = "BL @username - add @username to your blacklist") - public String blacklistUser(User user_from, Jid from, String... arguments) { + public String blacklistUser(User user_from, Jid from, URI attachment, String... arguments) { User blUser = userService.getUserByName(arguments[0]); if (blUser != null) { PrivacyQueriesService.PrivacyResult result = privacyQueriesService.blacklistUser(user_from, blUser); @@ -209,7 +219,7 @@ public class CommandsManager { } @UserCommand(pattern = "^bl\\s\\*(\\S+)$", patternFlags = Pattern.CASE_INSENSITIVE, help = "BL *tag - add *tag to your blacklist") - public String blacklistTag(User user_from, Jid from, String... arguments) { + public String blacklistTag(User user_from, Jid from, URI attachment, String... arguments) { User blUser = userService.getUserByName(arguments[0]); if (blUser != null) { Tag tag = tagService.getTag(arguments[0], false); @@ -225,7 +235,7 @@ public class CommandsManager { return "Tag not found"; } @UserCommand(pattern = "\\*", help = "* - Show your tags") - public String commandTags(User currentUser, Jid from, String... args) { + public String commandTags(User currentUser, Jid from, URI attachment, String... args) { List<TagStats> tags = tagService.getUserTagStats(currentUser.getUid()); String msg = "Your tags: (tag - messages)\n" + tags.stream() @@ -233,7 +243,7 @@ public class CommandsManager { return msg; } @UserCommand(pattern = "S", help = "S - Show your subscriptions") - public String commandSubscriptions(User currentUser, Jid from, String... args) { + public String commandSubscriptions(User currentUser, Jid from, URI attachment, String... args) { List<User> friends = userService.getUserFriends(currentUser.getUid()); List<String> tags = subscriptionService.getSubscribedTags(currentUser); String msg = friends.size() > 0 ? "You are subscribed to users:" + friends.stream().map(u -> "\n@" + u.getName()) @@ -245,7 +255,7 @@ public class CommandsManager { return msg; } @UserCommand(pattern = "!", help = "! - Show your favorite messages") - public String commandFavorites(User currentUser, Jid from, String... args) { + public String commandFavorites(User currentUser, Jid from, URI attachment, String... args) { List<Integer> mids = messagesService.getUserRecommendations(currentUser.getUid(), 0); if (mids.size() > 0) { return "Favorite messages: \n" + printMessages(mids, false); @@ -253,7 +263,7 @@ public class CommandsManager { return "No favorite messages, try to \"like\" something ;)"; } @UserCommand(pattern = "^\\!\\s+#(\\d+)", help = "! #12345 - recommend message") - public String commandRecommend(User user, Jid from, String... arguments) { + public String commandRecommend(User user, Jid from, URI attachment, String... arguments) { int mid = NumberUtils.toInt(arguments[0], 0); if (mid > 0) { com.juick.Message msg = messagesService.getMessage(mid); @@ -277,7 +287,7 @@ public class CommandsManager { // TODO: target notification @UserCommand(pattern = "^(s|u)\\s+\\@(\\S+)$", help = "S @username - subscribe to user" + "\nU @username - unsubscribe from user", patternFlags = Pattern.CASE_INSENSITIVE) - public String commandSubscribeUser(User user, Jid from, String... args) { + public String commandSubscribeUser(User user, Jid from, URI attachment, String... args) { boolean subscribe = args[0].equalsIgnoreCase("s"); User toUser = userService.getUserByName(args[1]); if (subscribe) { @@ -296,7 +306,7 @@ public class CommandsManager { } @UserCommand(pattern = "^(s|u)\\s+\\*(\\S+)$", help = "S *tag - subscribe to tag" + "\nU *tag - unsubscribe from tag", patternFlags = Pattern.CASE_INSENSITIVE) - public String commandSubscribeTag(User user, Jid from, String... args) { + public String commandSubscribeTag(User user, Jid from, URI attachment, String... args) { boolean subscribe = args[0].equalsIgnoreCase("s"); Tag tag = tagService.getTag(args[1], true); if (subscribe) { @@ -313,7 +323,7 @@ public class CommandsManager { } @UserCommand(pattern = "^(s|u)\\s+#(\\d+)$", help = "S #1234 - subscribe to comments" + "\nU #1234 - unsubscribe from comments", patternFlags = Pattern.CASE_INSENSITIVE) - public String commandSubscribeMessage(User user, Jid from, String... args) { + public String commandSubscribeMessage(User user, Jid from, URI attachment, String... args) { boolean subscribe = args[0].equalsIgnoreCase("s"); int mid = NumberUtils.toInt(args[1], 0); if (messagesService.getMessage(mid) != null) { @@ -332,7 +342,7 @@ public class CommandsManager { } @UserCommand(pattern = "^(on|off)$", patternFlags = Pattern.CASE_INSENSITIVE, help = "ON/OFF - Enable/disable subscriptions delivery") - public String commandOnOff(User user, Jid from, String[] input) { + public String commandOnOff(User user, Jid from, URI attachment, String[] input) { UserService.ActiveStatus newStatus; String retValUpdated; if (input[0].toLowerCase().equals("on")) { @@ -351,7 +361,7 @@ public class CommandsManager { } @UserCommand(pattern = "^\\@([^\\s\\n\\+]+)(\\+?)$", help = "@username+ - Show user's info and last 20 messages") - public String commandUser(User user, Jid from, String... arguments) { + public String commandUser(User user, Jid from, URI attachment, String... arguments) { User blogUser = userService.getUserByName(arguments[0]); int page = arguments[1].length(); if (blogUser.getUid() > 0) { @@ -362,7 +372,7 @@ public class CommandsManager { return "User not found"; } @UserCommand(pattern = "^#(\\d+)(\\+?)$", help = "#1234 - Show message (#1234+ - message with replies)") - public String commandShow(User user, Jid from, String... arguments) { + public String commandShow(User user, Jid from, URI attachment, String... arguments) { boolean showReplies = arguments[1].length() > 0; int mid = NumberUtils.toInt(arguments[0], 0); if (mid == 0) { @@ -381,7 +391,7 @@ public class CommandsManager { return "Message not found"; } @UserCommand(pattern = "^#(\\d+)\\/(\\d+)$", help = "#1234/5 - Show reply") - public String commandShowReply(User user, Jid from, String... arguments) { + public String commandShowReply(User user, Jid from, URI attachment, String... arguments) { int mid = NumberUtils.toInt(arguments[0], 0); int rid = NumberUtils.toInt(arguments[1], 0); com.juick.Message reply = messagesService.getReply(mid, rid); @@ -391,7 +401,7 @@ public class CommandsManager { return "Reply not found"; } @UserCommand(pattern = "^\\*(\\S+)(\\+?)$", help = "*tag - Show last messages with tag") - public String commandShowTag(User user, Jid from, String... arguments) { + public String commandShowTag(User user, Jid from, URI attachment, String... arguments) { Tag tag = tagService.getTag(arguments[0], false); if (tag != null) { // TODO: synonims @@ -401,7 +411,7 @@ public class CommandsManager { return "Tag not found"; } @UserCommand(pattern = "^D #(\\d+)$", help = "D #1234 - Delete post", patternFlags = Pattern.CASE_INSENSITIVE) - public String commandDeletePost(User user, Jid from, String... args) { + public String commandDeletePost(User user, Jid from, URI attachment, String... args) { int mid = Integer.valueOf(args[0]); if (messagesService.deleteMessage(user.getUid(), mid)) { return "Message deleted"; @@ -409,7 +419,7 @@ public class CommandsManager { return "This is not your message"; } @UserCommand(pattern = "^D #(\\d+)(\\.|\\-|\\/)(\\d+)$", help = "D #1234/5 - Delete comment", patternFlags = Pattern.CASE_INSENSITIVE) - public String commandDeleteReply(User user, Jid from, String... args) { + public String commandDeleteReply(User user, Jid from, URI attachment, String... args) { int mid = Integer.valueOf(args[0]); int rid = Integer.valueOf(args[2]); if (messagesService.deleteReply(user.getUid(), mid, rid)) { @@ -419,19 +429,19 @@ public class CommandsManager { } } @UserCommand(pattern = "^(D L|DL|D LAST)$", help = "D L - Delete last message", patternFlags = Pattern.CASE_INSENSITIVE) - public String commandDeleteLast(User user, Jid from, String... args) { + public String commandDeleteLast(User user, Jid from, URI attachment, String... args) { return "Temporarily unavailable"; } @UserCommand(pattern = "^\\?\\s+\\@([a-zA-Z0-9\\-\\.\\@]+)\\s+([\\s\\S]+)$", help = "? @user string - search in user messages") - public String commandSearch(User user, Jid from, String... args) { + public String commandSearch(User user, Jid from, URI attachment, String... args) { return "Temporarily unavailable"; } @UserCommand(pattern = "^\\?\\s+([\\s\\S]+)$", help = "? string - search in all messages") - public String commandSearchAll(User user, Jid from, String... args) { + public String commandSearchAll(User user, Jid from, URI attachment, String... args) { return "Temporarily unavailable"; } @UserCommand(pattern = "^(#+)$", help = "# - Show last messages from your feed (## - second page, ...)") - public String commandMyFeed(User user, Jid from, String... arguments) { + public String commandMyFeed(User user, Jid from, URI attachment, String... arguments) { // number of # is the page count int page = arguments[0].length() - 1; List<Integer> mids = messagesService.getMyFeed(user.getUid(), page, false); @@ -442,7 +452,7 @@ public class CommandsManager { } @UserCommand(pattern = "^(#|\\.)(\\d+)((\\.|\\-|\\/)(\\d+))?\\s([\\s\\S]+)", help = "#1234 *tag *tag2 - edit tags\n#1234 text - reply to message") - public String EditOrReply(User user, Jid from, String... args) { + public String EditOrReply(User user, Jid from, URI attachment, String... args) throws Exception { int mid = NumberUtils.toInt(args[1]); int rid = NumberUtils.toInt(args[4], 0); String txt = args[5]; @@ -454,7 +464,14 @@ public class CommandsManager { tagService.updateTags(mid, messageTags); return "Tags are updated"; } else { - int newrid = messagesService.createReply(mid, rid, user.getUid(), txt, null); + String attachmentType = attachment != null ? attachment.toString().substring(attachment.toString().length() - 3) : null; + int newrid = messagesService.createReply(mid, rid, user.getUid(), txt, attachmentType); + if (StringUtils.isNotEmpty(attachmentType)) { + String attachmentFName = attachment.getScheme().equals("juick") ? attachment.getHost() + : HttpUtils.downloadImage(attachment.toURL(), tmpDir); + String fname = String.format("%d-%d.%s", mid, newrid, attachmentType); + ImageUtils.saveImageWithPreviews(attachmentFName, fname, tmpDir, imgDir); + } applicationEventPublisher.publishEvent(new MessageEvent(this, messagesService.getReply(mid, newrid))); return "Reply posted.\n#" + mid + "/" + newrid + " " + "https://juick.com/" + mid + "#" + newrid; diff --git a/juick-server/src/main/java/com/juick/server/XMPPConnection.java b/juick-server/src/main/java/com/juick/server/XMPPConnection.java index 87164755..942b4787 100644 --- a/juick-server/src/main/java/com/juick/server/XMPPConnection.java +++ b/juick-server/src/main/java/com/juick/server/XMPPConnection.java @@ -23,9 +23,11 @@ import com.juick.server.component.LikeEvent; import com.juick.server.component.MessageEvent; import com.juick.server.component.PingEvent; import com.juick.server.component.SubscribeEvent; +import com.juick.server.helpers.UserInfo; +import com.juick.server.util.HttpUtils; +import com.juick.server.util.ImageUtils; import com.juick.server.util.TagUtils; import com.juick.server.xmpp.s2s.BasicXmppSession; -import com.juick.server.helpers.UserInfo; import com.juick.server.xmpp.s2s.StanzaListener; import com.juick.service.*; import com.juick.util.MessageUtils; @@ -65,7 +67,6 @@ import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.IOException; import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; @@ -104,6 +105,8 @@ public class XMPPConnection implements StanzaListener, NotificationListener { private boolean isXmppDisabled; @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}") private String tmpDir; + @Value("${img_path:#{systemEnvironment['TEMP'] ?: '/tmp'}}") + private String imgDir; @Inject private MessagesService messagesService; @@ -570,20 +573,20 @@ public class XMPPConnection implements StanzaListener, NotificationListener { } } - public boolean incomingMessage(Message msg) { + public void incomingMessage(Message msg) { if (msg.getType() != null && msg.getType().equals(Message.Type.ERROR)) { StanzaError error = msg.getError(); if (error != null && error.getCondition().equals(Condition.RESOURCE_CONSTRAINT)) { // offline query is full, deactivating this jid if (userService.setActiveStatusForJID(msg.getFrom().toEscapedString(), UserService.ActiveStatus.Inactive)) { logger.info("{} is inactive now", msg.getFrom()); - return true; + return; } } - return false; + return; } if (StringUtils.isBlank(msg.getBody())) { - return false; + return; } String username = msg.getTo().getLocal(); @@ -601,14 +604,15 @@ public class XMPPConnection implements StanzaListener, NotificationListener { reply.setType(Message.Type.CHAT); reply.setBody("Для того, чтобы начать пользоваться сервисом, пожалуйста пройдите быструю регистрацию: http://juick.com/signup?type=xmpp&hash=" + signuphash + "\nЕсли у вас уже есть учетная запись на Juick, вы сможете присоединить этот JabberID к ней.\n\nTo start using Juick, please sign up: http://juick.com/signup?type=xmpp&hash=" + signuphash + "\nIf you already have an account on Juick, you will be proposed to attach this JabberID to your existing account."); s2s(ClientMessage.from(reply)); - return true; + return; } if (username.equals(jid.getLocal())) { try { - return incomingMessageJuick(user_from, msg.getFrom(), msg.getBody().trim()); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - return false; + OobX oobX = msg.getExtension(OobX.class); + incomingMessageJuick(user_from, msg.getFrom(), msg.getBody().trim(), oobX.getUri()); + } catch (Exception e) { + return; } } @@ -622,7 +626,7 @@ public class XMPPConnection implements StanzaListener, NotificationListener { reply.setId(msg.getId()); reply.setError(new StanzaError(StanzaError.Type.CANCEL, Condition.ITEM_NOT_FOUND)); s2s(ClientMessage.from(reply)); - return true; + return; } boolean success = false; @@ -646,9 +650,9 @@ public class XMPPConnection implements StanzaListener, NotificationListener { s2s(ClientMessage.from(reply)); } - return false; + return; } - public boolean incomingMessageJuick(User user_from, Jid from, String command) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { + public com.juick.Message incomingMessageJuick(User user_from, Jid from, String command, URI attachment) throws Exception { int commandlen = command.length(); // COMPATIBILITY @@ -656,18 +660,29 @@ public class XMPPConnection implements StanzaListener, NotificationListener { command = command.substring(3).trim(); } - Optional<String> result = commandsManager.processCommand(user_from, from, command); + Optional<String> result = commandsManager.processCommand(user_from, from, command, attachment); if (result.isPresent()) { sendReply(from, result.get()); + com.juick.Message msg = new com.juick.Message(); + msg.setText(result.get()); + return msg; } else { // new message List<Tag> tags = tagService.fromString(command, false); String body = command.substring(TagUtils.toString(tags).length()); - int mid = messagesService.createMessage(user_from.getUid(), body, null, tags); + String attachmentType = attachment != null ? attachment.toString().substring(attachment.toString().length() - 3) : null; + int mid = messagesService.createMessage(user_from.getUid(), body, attachmentType, tags); subscriptionService.subscribeMessage(mid, user_from.getUid()); - applicationEventPublisher.publishEvent(new MessageEvent(this, messagesService.getMessage(mid))); + if (StringUtils.isNotEmpty(attachmentType)) { + String attachmentFName = attachment.getScheme().equals("juick") ? attachment.getPath() + : HttpUtils.downloadImage(attachment.toURL(), tmpDir); + String fname = String.format("%d.%s", mid, attachmentType); + ImageUtils.saveImageWithPreviews(attachmentFName, fname, tmpDir, imgDir); + } + com.juick.Message msg = messagesService.getMessage(mid); + applicationEventPublisher.publishEvent(new MessageEvent(this, msg)); + return msg; } - return true; } @Override @@ -679,9 +694,7 @@ public class XMPPConnection implements StanzaListener, NotificationListener { } } else if (xmlValue instanceof Message) { Message msg = (Message) xmlValue; - if (!incomingMessage(msg)) { - router.send(msg); - } + incomingMessage(msg); } else if (xmlValue instanceof IQ) { IQ iq = (IQ) xmlValue; router.send(iq); diff --git a/juick-server/src/main/java/com/juick/server/api/Post.java b/juick-server/src/main/java/com/juick/server/api/Post.java index 301f6e37..6bab5b41 100644 --- a/juick-server/src/main/java/com/juick/server/api/Post.java +++ b/juick-server/src/main/java/com/juick/server/api/Post.java @@ -303,7 +303,7 @@ public class Post { if (msg.getUser().getUid() == visitor.getUid()) { throw new HttpForbiddenException(); } - String status = commandsManager.commandRecommend(visitor, null, String.valueOf(mid)); + String status = commandsManager.commandRecommend(visitor, null, null, String.valueOf(mid)); return Status.getStatus(status); } } diff --git a/juick-server/src/test/java/com/juick/server/tests/ServerTests.java b/juick-server/src/test/java/com/juick/server/tests/ServerTests.java index 6c232167..92d05828 100644 --- a/juick-server/src/test/java/com/juick/server/tests/ServerTests.java +++ b/juick-server/src/test/java/com/juick/server/tests/ServerTests.java @@ -23,16 +23,18 @@ import com.juick.ExternalToken; import com.juick.Message; import com.juick.Tag; import com.juick.User; -import com.juick.server.EmailManager; import com.juick.server.CommandsManager; +import com.juick.server.EmailManager; import com.juick.server.XMPPConnection; import com.juick.server.XMPPServer; import com.juick.server.helpers.AnonymousUser; import com.juick.server.helpers.TagStats; +import com.juick.server.util.HttpUtils; import com.juick.service.*; import com.juick.util.DateFormattersHolder; import com.juick.util.MessageUtils; import org.apache.commons.lang3.StringUtils; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -49,6 +51,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.util.FileSystemUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; @@ -57,7 +60,11 @@ import rocks.xmpp.core.stanza.model.Stanza; import rocks.xmpp.core.stanza.model.server.ServerMessage; import javax.inject.Inject; +import java.io.IOException; import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; import java.sql.Timestamp; import java.time.Instant; import java.util.*; @@ -116,6 +123,10 @@ public class ServerTests { private ImagesService imagesService; @Value("${hostname:localhost}") private Jid jid; + @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}") + private String tmpDir; + @Value("${img_path:#{systemEnvironment['TEMP'] ?: '/tmp'}}") + private String imgDir; private static User ugnich, freefd, juick; static String ugnichName, ugnichPassword, freefdName, freefdPassword, juickName, juickPassword; @@ -125,7 +136,11 @@ public class ServerTests { private static boolean isSetUp = false; @Before - public void setUp() { + public void setUp() throws IOException { + Files.createDirectory(Paths.get(imgDir, "p")); + Files.createDirectory(Paths.get(imgDir, "photos-1024")); + Files.createDirectory(Paths.get(imgDir, "photos-512")); + Files.createDirectory(Paths.get(imgDir, "ps")); if (!isSetUp) { ugnichName = "ugnich"; ugnichPassword = "secret"; @@ -149,6 +164,13 @@ public class ServerTests { isSetUp = true; } } + @After + public void teardown() throws IOException { + FileSystemUtils.deleteRecursively(Paths.get(imgDir, "p")); + FileSystemUtils.deleteRecursively(Paths.get(imgDir, "photos-1024")); + FileSystemUtils.deleteRecursively(Paths.get(imgDir, "photos-512")); + FileSystemUtils.deleteRecursively(Paths.get(imgDir, "ps")); + } @Test public void getMyFeed() { int mid0 = messagesService.createMessage(ugnich.getUid(), "test", null, null); @@ -242,7 +264,7 @@ public class ServerTests { int reply_id = messagesService.createReply(msg.getMid(), 0, ugnich_id, "comment", null); assertEquals(1, subscriptionService.getUsersSubscribedToComments(msg, messagesService.getReply(msg.getMid(), reply_id)).size()); - assertThat(messagesService.getDiscussions(ugnich.getUid(), Instant.now().toEpochMilli()).get(0), + assertThat(messagesService.getDiscussions(ugnich.getUid(), 0L).get(0), equalTo(msg.getMid())); messagesService.deleteMessage(user_id, mid); messagesService.deleteMessage(user_id, mid2); @@ -518,21 +540,23 @@ public class ServerTests { } @Test public void botCommandsTests() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { - assertThat(commandsManager.processCommand(new User(), Jid.of("test@localhost"), "PING").get(), is("PONG")); + assertThat(commandsManager.processCommand(new User(), Jid.of("test@localhost"), "PING", null).get(), is("PONG")); // subscription commands have two lines, others have 1 - assertThat(commandsManager.processCommand(new User(), Jid.of("test@localhost"), "help").get().split("\n").length, is(32)); + assertThat(commandsManager.processCommand(new User(), Jid.of("test@localhost"), "help", null).get().split("\n").length, is(32)); } @Test - public void protocolTests() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { + public void protocolTests() throws Exception { int uid = userService.createUser("me", "secret"); User user = userService.getUserByUID(uid).orElse(new User()); Tag yo = tagService.getTag("yo", true); - router.incomingMessageJuick(user, Jid.of("test@localhost"), "*yo yoyo"); + Message msg = router.incomingMessageJuick(user, Jid.of("test@localhost"), "*yo yoyo", URI.create("http://static.juick.com/settings/facebook.png")); + assertThat(msg.getAttachmentType(), is("png")); + Message msgreply = router.incomingMessageJuick(user, Jid.of("test@localhost"), "#" + msg.getMid() + " yyy", URI.create("juick://" + HttpUtils.downloadImage(URI.create("http://static.juick.com/settings/xmpp.png").toURL(), tmpDir))); + assertThat(messagesService.getReply(msg.getMid(), 1).getAttachmentType(), equalTo("png")); int mid = messagesService.createMessage(uid, "yoyo", null, Collections.singletonList(yo)); assertEquals("should be message", true, - commandsManager.processCommand(user, Jid.of("test@localhost"), String.format("#%d", mid)).get().startsWith("@me")); - mid = messagesService.getUserBlog(user.getUid(), -1, 0).stream().reduce((first, second) -> second).get(); + commandsManager.processCommand(user, Jid.of("test@localhost"), String.format("#%d", mid), null).get().startsWith("@me")); assertEquals("text should match", "yoyo", messagesService.getMessage(mid).getText()); assertEquals("tag should match", "yo", @@ -541,9 +565,9 @@ public class ServerTests { User readerUser = userService.getUserByUID(readerUid).orElse(new User()); Jid dummyJid = Jid.of("dummy@localhost"); assertEquals("should be subscribed", "Subscribed", - commandsManager.processCommand(readerUser, dummyJid, "S #" + mid).get()); + commandsManager.processCommand(readerUser, dummyJid, "S #" + mid, null).get()); assertEquals("should be favorited", "Message is added to your recommendations", - commandsManager.processCommand(readerUser, dummyJid, "! #" + mid).get()); + commandsManager.processCommand(readerUser, dummyJid, "! #" + mid, null).get()); int rid = messagesService.createReply(mid, 0, uid, "comment", null); assertEquals("number of subscribed users should match", 1, subscriptionService.getUsersSubscribedToComments( @@ -555,7 +579,7 @@ public class ServerTests { messagesService.getMessage(mid), messagesService.getReply(mid, rid)).size()); assertEquals("should be subscribed", "Subscribed to @" + user.getName(), - commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "S @" + user.getName()).get()); + commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "S @" + user.getName(), null).get()); List<User> friends = userService.getUserFriends(readerUid); assertEquals("number of friend users should match", 2, friends.size()); @@ -566,57 +590,57 @@ public class ServerTests { String expectedThirdReply = "Reply posted.\n#" + mid + "/3 " + "https://juick.com/" + mid + "#3"; assertEquals("should be second reply", expectedSecondReply, - commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + " yoyo").get()); + commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + " yoyo", null).get()); assertEquals("should be third reply", expectedThirdReply, - commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + "/2 yoyo").get()); + commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + "/2 yoyo", null).get()); Message reply = messagesService.getReplies(mid).stream().filter(m -> m.getRid() == 3).findFirst() .orElse(new Message()); assertEquals("should be reply to second comment", 2, reply.getReplyto()); assertEquals("tags should NOT be updated", "It is not your message", - commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "#" + mid + " *yo *there").get()); + commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "#" + mid + " *yo *there", null).get()); assertEquals("tags should be updated", "Tags are updated", - commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + " *there").get()); + commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + " *there", null).get()); assertEquals("number of tags should match", 2, tagService.getMessageTags(mid).size()); assertEquals("should be blacklisted", "Tag added to your blacklist", - commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "BL *there").get()); + commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "BL *there", null).get()); assertEquals("number of subscribed users should match", 0, subscriptionService.getSubscribedUsers(uid, mid).size()); assertEquals("tags should be updated", "Tags are updated", - commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + " *there").get()); + commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid + " *there", null).get()); assertEquals("number of tags should match", 1, tagService.getMessageTags(mid).size()); int taggerUid = userService.createUser("dummyTagger", "dummySecret"); User taggerUser = userService.getUserByUID(taggerUid).orElse(new User()); assertEquals("should be subscribed", "Subscribed", - commandsManager.processCommand(taggerUser, Jid.of("tagger@localhost"), "S *yo").get()); + commandsManager.processCommand(taggerUser, Jid.of("tagger@localhost"), "S *yo", null).get()); assertEquals("number of subscribed users should match", 2, subscriptionService.getSubscribedUsers(uid, mid).size()); assertEquals("should be unsubscribed", "Unsubscribed from yo", - commandsManager.processCommand(taggerUser, Jid.of("tagger@localhost"), "U *yo").get()); + commandsManager.processCommand(taggerUser, Jid.of("tagger@localhost"), "U *yo", null).get()); assertEquals("number of subscribed users should match", 1, subscriptionService.getSubscribedUsers(uid, mid).size()); assertEquals("number of readers should match", 1, userService.getUserReaders(uid).size()); - String readerFeed = commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "#").get(); + String readerFeed = commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "#", null).get(); assertEquals("description should match", true, readerFeed.startsWith("Your feed")); assertEquals("should be unsubscribed", "Unsubscribed from @" + user.getName(), - commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "U @" + user.getName()).get()); + commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "U @" + user.getName(), null).get()); assertEquals("number of readers should match", 0, userService.getUserReaders(uid).size()); assertEquals("number of friends should match", 1, userService.getUserFriends(uid).size()); assertEquals("should be unsubscribed", "Unsubscribed from #" + mid, - commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "u #" + mid).get()); + commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "u #" + mid, null).get()); assertEquals("number of subscribed users should match", 0, subscriptionService.getUsersSubscribedToComments(messagesService.getMessage(mid), messagesService.getReply(mid, rid)).size()); assertNotEquals("should NOT be deleted", String.format("Message %s deleted", mid), - commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "D #" + mid).get()); + commandsManager.processCommand(readerUser, Jid.of("dummy@localhost"), "D #" + mid, null).get()); assertEquals("should be deleted", "Message deleted", - commandsManager.processCommand(user, Jid.of("test@localhost"), "D #" + mid).get()); + commandsManager.processCommand(user, Jid.of("test@localhost"), "D #" + mid, null).get()); assertEquals("should be not found", "Message not found", - commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid).get()); + commandsManager.processCommand(user, Jid.of("test@localhost"), "#" + mid, null).get()); } @Test public void mailParserTest() throws Exception { |