diff options
author | Vitaly Takmazov | 2018-03-30 12:47:51 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2018-03-30 12:47:51 +0300 |
commit | 42e2a727c2bc15ac15c9a3af66f126dbefe508a2 (patch) | |
tree | fd704fda59b8814919bbd32ca2f43d13ef22a05f /juick-server/src/main/java/com/juick/server | |
parent | 42af9310f0c195a68212cd9d06f2a3f06a402891 (diff) |
server: process attachments correctly
Diffstat (limited to 'juick-server/src/main/java/com/juick/server')
3 files changed, 83 insertions, 53 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 6b6b3e536..a6a3a6e1a 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 871647550..942b4787c 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 301f6e374..6bab5b418 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); } } |