aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick/server/protocol
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2017-06-29 14:03:04 +0300
committerGravatar Vitaly Takmazov2017-06-29 14:03:04 +0300
commit02723131139806c761539a42a5fa80b68ecadee8 (patch)
treeca66f22993908758385f708eb2da4e4aeb20510a /juick-server/src/main/java/com/juick/server/protocol
parent4cc4b08f4377b7db697abdb533c625da608eb3d3 (diff)
project structure: split server into jdbc + web
Diffstat (limited to 'juick-server/src/main/java/com/juick/server/protocol')
-rw-r--r--juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java426
-rw-r--r--juick-server/src/main/java/com/juick/server/protocol/ProtocolListener.java13
-rw-r--r--juick-server/src/main/java/com/juick/server/protocol/annotation/UserCommand.java33
3 files changed, 0 insertions, 472 deletions
diff --git a/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java b/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java
deleted file mode 100644
index ef8641f8..00000000
--- a/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java
+++ /dev/null
@@ -1,426 +0,0 @@
-package com.juick.server.protocol;
-
-import com.juick.Message;
-import com.juick.Tag;
-import com.juick.User;
-import com.juick.formatters.PlainTextFormatter;
-import com.juick.server.helpers.TagStats;
-import com.juick.server.protocol.annotation.UserCommand;
-import com.juick.service.*;
-import com.juick.util.TagUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.math.NumberUtils;
-import org.apache.commons.lang3.reflect.MethodUtils;
-
-import javax.inject.Inject;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-/**
- * Created by oxpa on 22.03.16.
- */
-
-public class JuickProtocol {
-
- private String baseUri;
- private ProtocolListener listener;
-
- @Inject
- UserService userService;
- @Inject
- TagService tagService;
- @Inject
- MessagesService messagesService;
- @Inject
- SubscriptionService subscriptionService;
- @Inject
- PMQueriesService pmQueriesService;
- @Inject
- PrivacyQueriesService privacyQueriesService;
- @Inject
- ShowQueriesService showQueriesService;
-
- public JuickProtocol(String baseUri) {
- this.baseUri = baseUri;
- }
-
- /**
- * find command by pattern and invoke
- * @param user who send command
- * @param userInput given by user
- * @return command result
- * @throws InvocationTargetException
- * @throws IllegalAccessException
- * @throws NoSuchMethodException
- */
- public String getReply(User user, String userInput) throws InvocationTargetException,
- IllegalAccessException, NoSuchMethodException {
- Optional<Method> cmd = MethodUtils.getMethodsListWithAnnotation(getClass(), UserCommand.class).stream()
- .filter(m -> Pattern.compile(m.getAnnotation(UserCommand.class).pattern(),
- m.getAnnotation(UserCommand.class).patternFlags()).matcher(userInput).matches())
- .findFirst();
- if (!cmd.isPresent()) {
- // default command - post as new message
- return postMessage(user, userInput.trim());
- } else {
- Matcher matcher = Pattern.compile(cmd.get().getAnnotation(UserCommand.class).pattern(),
- cmd.get().getAnnotation(UserCommand.class).patternFlags()).matcher(userInput.trim());
- List<String> groups = new ArrayList<>();
- while (matcher.find()) {
- for (int i = 1; i <= matcher.groupCount(); i++) {
- groups.add(matcher.group(i));
- }
- }
- return (String) getClass().getMethod(cmd.get().getName(), User.class, String[].class)
- .invoke(this, user, groups.toArray(new String[groups.size()]));
- }
- }
-
- public String postMessage(User user, String input) {
- List<Tag> tags = tagService.fromString(input, false);
- String body = input.substring(TagUtils.toString(tags).length());
- int mid = messagesService.createMessage(user.getUid(), body, null, tags);
- subscriptionService.subscribeMessage(mid, user.getUid());
- listener.messagePosted(messagesService.getMessage(mid));
- return "New message posted.\n#" + mid + " " + baseUri + mid;
- }
-
- @UserCommand(pattern = "^#\\+$", help = "#+ - Show last Juick messages")
- public String commandLast(User user, String... arguments) {
- List<Integer> mids = messagesService.getAll(user.getUid(), 0);
- List<Message> messages = messagesService.getMessages(mids);
- return "Last messages: \n"
- + messages.stream().sorted(Collections.reverseOrder()).map(PlainTextFormatter::formatPostSummary)
- .collect(Collectors.joining("\n\n"));
- }
-
- @UserCommand(pattern = "^bl$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "BL - Show your blacklist")
- public String commandBL(User user_from, String... arguments) {
- List<User> blusers;
- List<String> bltags;
-
- blusers = userService.getUserBLUsers(user_from.getUid());
- bltags = tagService.getUserBLTags(user_from.getUid());
-
-
- String txt = StringUtils.EMPTY;
- if (bltags.size() > 0) {
- for (String bltag : bltags) {
- txt += "*" + bltag + "\n";
- }
-
- if (blusers.size() > 0) {
- txt += "\n";
- }
- }
- if (blusers.size() > 0) {
- for (User bluser : blusers) {
- txt += "@" + bluser.getName() + "\n";
- }
- }
- if (txt.isEmpty()) {
- txt = "You don't have any users or tags in your blacklist.";
- }
- return txt;
- }
-
- @UserCommand(pattern = "^bl\\s+@([^\\s\\n\\+]+)", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "BL @username - add @username to your blacklist")
- public String blacklistUser(User from, String... arguments) {
- User blUser = userService.getUserByName(arguments[0]);
- if (blUser != null) {
- PrivacyQueriesService.PrivacyResult result = privacyQueriesService.blacklistUser(from, blUser);
- if (result == PrivacyQueriesService.PrivacyResult.Added) {
- return "User added to your blacklist";
- } else {
- return "User removed from your blacklist";
- }
- }
- return "User not found";
- }
-
- @UserCommand(pattern = "^bl\\s\\*(\\S+)$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "BL *tag - add *tag to your blacklist")
- public String blacklistTag(User from, String... arguments) {
- User blUser = userService.getUserByName(arguments[0]);
- if (blUser != null) {
- Tag tag = tagService.getTag(arguments[0], false);
- if (tag != null) {
- PrivacyQueriesService.PrivacyResult result = privacyQueriesService.blacklistTag(from, tag);
- if (result == PrivacyQueriesService.PrivacyResult.Added) {
- return "Tag added to your blacklist";
- } else {
- return "Tag removed from your blacklist";
- }
- }
- }
- return "Tag not found";
- }
-
- @UserCommand(pattern = "@", help = "@ - Show recommendations and popular personal blogs")
- public String commandUsers(User currentUser, String... args) {
- StringBuilder msg = new StringBuilder();
- msg.append("Recommended blogs");
- List<String> recommendedUsers = showQueriesService.getRecommendedUsers(currentUser);
- if (recommendedUsers.size() > 0) {
- for (String user : recommendedUsers) {
- msg.append("\n@").append(user);
- }
- } else {
- msg.append("\nNo recommendations now. Subscribe to more blogs. ;)");
- }
- msg.append("\n\nTop 10 personal blogs:");
- List<String> topUsers = showQueriesService.getTopUsers();
- if (topUsers.size() > 0) {
- for (String user : topUsers) {
- msg.append("\n@").append(user);
- }
- } else {
- msg.append("\nNo top users. Empty DB? ;)");
- }
- return msg.toString();
- }
-
- @UserCommand(pattern = "\\*", help = "* - Show your tags")
- public String commandTags(User currentUser, String... args) {
- List<TagStats> tags = tagService.getUserTagStats(currentUser.getUid());
- String msg = "Your tags: (tag - messages)\n" +
- tags.stream()
- .map(t -> String.format("\n*%s - %d", t.getTag().getName(), t.getUsageCount())).collect(Collectors.joining());
- return msg;
- }
-
- @UserCommand(pattern = "S", help = "S - Show your subscriptions")
- public String commandSubscriptions(User currentUser, 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())
- .collect(Collectors.joining())
- : "You are not subscribed to any user.";
- msg += tags.size() > 0 ? "\nYou are subscribed to tags:" + tags.stream().map(t -> "\n*" + t)
- .collect(Collectors.joining())
- : "\nYou are not subscribed to any tag.";
- return msg;
- }
-
- @UserCommand(pattern = "!", help = "! - Show your favorite messages")
- public String commandFavorites(User currentUser, String... args) {
- List<Integer> mids = messagesService.getUserRecommendations(currentUser.getUid(), 0);
- if (mids.size() > 0) {
- List<Message> messages = messagesService.getMessages(mids);
- return "Favorite messages: \n" + String.join("\n", messages.stream().map(PlainTextFormatter::formatPost)
- .collect(Collectors.toList()));
- }
- return "No favorite messages, try to \"like\" something ;)";
- }
-
- @UserCommand(pattern = "^\\@([^\\s\\n\\+]+)(\\+?)$",
- help = "@username+ - Show user's info and last 10 messages (@username++ - second page, ..)")
- public String commandUser(User user, String... arguments) {
- User blogUser = userService.getUserByName(arguments[0]);
- int page = arguments[1].length();
- if (blogUser.getUid() > 0) {
- List<Integer> mids = messagesService.getUserBlog(blogUser.getUid(), 0, page);
- List<Message> messages = messagesService.getMessages(mids);
- return String.format("Last messages from @%s:\n%s", arguments[0],
- String.join("\n", messages.stream()
- .map(PlainTextFormatter::formatPost).collect(Collectors.toList())));
- }
- return "User not found";
- }
-
- @UserCommand(pattern = "^d\\s*\\#([0-9]+)$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "D #12345 - delete the message")
- public String commandDel(User user, String... args) {
- int mid = NumberUtils.toInt(args[0], 0);
- if (messagesService.deleteMessage(user.getUid(), mid)) {
- return String.format("Message %s deleted", mid);
- }
- return "Error";
- }
-
- @UserCommand(pattern = "^login$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "LOGIN - log in to Juick website")
- public String commandLogin(User user, String... arguments) {
- return baseUri + "?" + userService.getHashByUID(user.getUid());
- }
-
- @UserCommand(pattern = "^(#+)$", help = "# - Show last messages from your feed (## - second page, ...)")
- public String commandMyFeed(User user, String... arguments) {
- // number of # is the page count
- int page = arguments[0].length() - 1;
- List<Integer> mids = messagesService.getMyFeed(user.getUid(), page);
- List<Message> messages = messagesService.getMessages(mids);
- // TODO: add instructions for empty feed
- return "Your feed: \n" + String.join("\n",
- messages.stream().map(PlainTextFormatter::formatPost).collect(Collectors.toList()));
- }
-
- @UserCommand(pattern = "^(on|off)$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "ON/OFF - Enable/disable subscriptions delivery")
- public String commandOnOff(User user, String[] input) {
- UserService.ActiveStatus newStatus;
- String retValUpdated;
- if (input[0].toLowerCase().equals("on")) {
- newStatus = UserService.ActiveStatus.Active;
- retValUpdated = "Notifications are activated for " + user.getJid();
- } else {
- newStatus = UserService.ActiveStatus.Inactive;
- retValUpdated = "Notifications are disabled for " + user.getJid();
- }
-
- if (userService.setActiveStatusForJID(user.getJid(), newStatus)) {
- return retValUpdated;
- } else {
- return String.format("Subscriptions status for %s was not changed", user.getJid());
- }
- }
-
- @UserCommand(pattern = "^ping$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "PING - returns you a PONG")
- public String commandPing(User user, String[] input) {
- return "PONG";
- }
-
- @UserCommand(pattern = "^\\@(\\S+)\\s+([\\s\\S]+)$", help = "@username message - send PM to username")
- public String commandPM(User user_from, String... arguments) {
- String user_to = arguments[0];
- String body = arguments[1];
-
- User toUser = userService.getUserByName(user_to);
-
- if (toUser.getUid() > 0) {
- if (!userService.isInBLAny(toUser.getUid(), user_from.getUid())) {
- if (pmQueriesService.createPM(user_from.getUid(), toUser.getUid(), body)) {
- listener.privateMessage(user_from, toUser, body);
- return "Private message sent";
- }
- }
- }
- return "Error";
- }
-
- @UserCommand(pattern = "^#(\\d+)(\\+?)$", help = "#1234 - Show message (#1234+ - message with replies)")
- public String commandShow(User user, String... arguments) {
- boolean showReplies = arguments[1].length() > 0;
- int mid = NumberUtils.toInt(arguments[0], 0);
- if (mid == 0) {
- return "Error";
- }
- Message msg = messagesService.getMessage(mid);
- if (msg != null) {
- if (showReplies) {
- List<Message> replies = messagesService.getReplies(mid);
- replies.add(0, msg);
- return String.join("\n",
- replies.stream().map(PlainTextFormatter::formatPost).collect(Collectors.toList()));
- }
- return PlainTextFormatter.formatPost(msg);
- }
- return "Message not found";
- }
- @UserCommand(pattern = "^(#|\\.)(\\d+)((\\.|\\-|\\/)(\\d+))?\\s([\\s\\S]+)",
- help = "#1234 *tag *tag2 - edit tags\n#1234 text - reply to message")
- public String EditOrReply(User user, String... args) {
- int mid = NumberUtils.toInt(args[1]);
- int rid = NumberUtils.toInt(args[4], 0);
- String txt = args[5];
- List<Tag> messageTags = tagService.fromString(txt, true);
- if (messageTags.size() > 0) {
- if (user.getUid() != messagesService.getMessageAuthor(mid).getUid()) {
- return "It is not your message";
- }
- tagService.updateTags(mid, messageTags);
- return "Tags are updated";
- } else {
- int newrid = messagesService.createReply(mid, rid, user.getUid(), txt, null);
- listener.messagePosted(messagesService.getReply(mid, newrid));
- return "Reply posted.\n#" + mid + "/" + newrid + " "
- + baseUri + mid + "#" + newrid;
- }
- }
-
- @UserCommand(pattern = "^(s|u)\\s+#(\\d+)$", help = "S #1234 - subscribe to comments",
- patternFlags = Pattern.CASE_INSENSITIVE)
- public String commandSubscribeMessage(User user, String... args) {
- boolean subscribe = args[0].equalsIgnoreCase("s");
- int mid = NumberUtils.toInt(args[1], 0);
- if (messagesService.getMessage(mid) != null) {
- if (subscribe) {
- if (subscriptionService.subscribeMessage(mid, user.getUid())) {
- return "Subscribed";
- }
- } else {
- if (subscriptionService.unSubscribeMessage(mid, user.getUid())) {
- return "Unsubscribed from #" + mid;
- }
- return "You was not subscribed to #" + mid;
- }
- }
- return "Error";
- }
- @UserCommand(pattern = "^(s|u)\\s+\\@(\\S+)$", help = "S @user - subscribe to user's posts",
- patternFlags = Pattern.CASE_INSENSITIVE)
- public String commandSubscribeUser(User user, String... args) {
- boolean subscribe = args[0].equalsIgnoreCase("s");
- User toUser = userService.getUserByName(args[1]);
- if (toUser.getUid() > 0) {
- if (subscribe) {
- if (subscriptionService.subscribeUser(user, toUser)) {
- listener.userSubscribed(user, toUser);
- return "Subscribed";
- // TODO: already subscribed case
- }
- } else {
- if (subscriptionService.unSubscribeUser(user, toUser)) {
- return "Unsubscribed from @" + toUser.getName();
- }
- return "You was not subscribed to @" + toUser.getName();
- }
- }
- return "Error";
- }
- @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, String... args) {
- boolean subscribe = args[0].equalsIgnoreCase("s");
- Tag tag = tagService.getTag(args[1], true);
- if (subscribe) {
- if (subscriptionService.subscribeTag(user, tag)) {
- return "Subscribed";
- }
- } else {
- if (subscriptionService.unSubscribeTag(user, tag)) {
- return "Unsubscribed from " + tag.getName();
- }
- return "You was not subscribed to " + tag.getName();
- }
- return "Error";
- }
-
- @UserCommand(pattern = "^help$", patternFlags = Pattern.CASE_INSENSITIVE,
- help = "HELP - returns this help message")
- public String commandHelp(User user, String[] input) {
- return Arrays.stream(getClass().getDeclaredMethods())
- .filter(m -> m.isAnnotationPresent(UserCommand.class))
- .map(m -> m.getAnnotation(UserCommand.class).help())
- .collect(Collectors.joining("\n"));
- }
-
- public String getBaseUri() {
- return baseUri;
- }
-
- public ProtocolListener getListener() {
- return listener;
- }
-
- public void setListener(ProtocolListener listener) {
- this.listener = listener;
- }
-}
diff --git a/juick-server/src/main/java/com/juick/server/protocol/ProtocolListener.java b/juick-server/src/main/java/com/juick/server/protocol/ProtocolListener.java
deleted file mode 100644
index 11231e04..00000000
--- a/juick-server/src/main/java/com/juick/server/protocol/ProtocolListener.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.juick.server.protocol;
-
-import com.juick.Message;
-import com.juick.User;
-
-/**
- * Created by vitalyster on 19.12.2016.
- */
-public interface ProtocolListener {
- void privateMessage(User from, User to, String body);
- void userSubscribed(User from, User to);
- void messagePosted(Message msg);
-}
diff --git a/juick-server/src/main/java/com/juick/server/protocol/annotation/UserCommand.java b/juick-server/src/main/java/com/juick/server/protocol/annotation/UserCommand.java
deleted file mode 100644
index 42a9bb59..00000000
--- a/juick-server/src/main/java/com/juick/server/protocol/annotation/UserCommand.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.juick.server.protocol.annotation;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Created by oxpa on 22.03.16.
- */
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface UserCommand {
- /**
- *
- * @return a command pattern
- */
- String pattern() default StringUtils.EMPTY;
-
- /**
- *
- * @return pattern flags
- */
- int patternFlags() default 0;
-
- /**
- *
- * @return a string used in HELP command output. Basically, only 1 string
- */
- String help() default StringUtils.EMPTY;
-}