diff options
author | Vitaly Takmazov | 2018-03-22 12:09:35 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2018-03-22 12:09:35 +0300 |
commit | 17e72bb8c612e34ec3aac56dd906bd9fefc2bc7c (patch) | |
tree | f84400450dea9a77ef741062ddf71bbb0535d6b4 /juick-server/src | |
parent | 679731ebbea77a7d361a53bb8280d1869c2a95d3 (diff) |
server: event listeners are beans
Diffstat (limited to 'juick-server/src')
5 files changed, 107 insertions, 56 deletions
diff --git a/juick-server/src/main/java/com/juick/server/TelegramBotManager.java b/juick-server/src/main/java/com/juick/server/TelegramBotManager.java index 9e056476..6987fa27 100644 --- a/juick-server/src/main/java/com/juick/server/TelegramBotManager.java +++ b/juick-server/src/main/java/com/juick/server/TelegramBotManager.java @@ -86,10 +86,6 @@ public class TelegramBotManager { private static final String MSG_LINK = "🔗"; - private ApplicationListener<LikeEvent> onLike; - private ApplicationListener<SubscribeEvent> onSubscribe; - private ApplicationListener<MessageEvent> onMessage; - @PostConstruct public void init() { if (StringUtils.isBlank(telegramToken)) { @@ -105,41 +101,6 @@ public class TelegramBotManager { } catch (Exception e) { logger.warn("couldn't initialize telegram bot", e); } - onMessage = event -> { - com.juick.Message jmsg = event.getMessage(); - String msgUrl = formatUrl(jmsg); - if (jmsg.getMid() > 0 && jmsg.getRid() == 0) { - String msg = String.format("[%s](%s) %s", MSG_LINK, msgUrl, formatPost(jmsg, true)); - - List<Long> users = telegramService.getTelegramIdentifiers(subscriptionService.getSubscribedUsers(jmsg.getUser().getUid(), jmsg.getMid())); - List<Long> chats = telegramService.getChats(); - // registered subscribed users - - users.forEach(c -> telegramNotify(c, msg, MessageUtils.attachmentUrl(jmsg))); - // anonymous - chats.stream().filter(u -> telegramService.getUser(u) == 0).forEach(c -> telegramNotify(c, msg, MessageUtils.attachmentUrl(jmsg))); - } else if (jmsg.getRid() > 0) { - com.juick.Message op = messagesService.getMessage(jmsg.getMid()); - String fmsg = String.format("[%s](%s) %s", MSG_LINK, msgUrl, formatPost(jmsg, true)); - telegramService.getTelegramIdentifiers( - subscriptionService.getUsersSubscribedToComments(op, jmsg) - ).forEach(c -> telegramNotify(c, fmsg, MessageUtils.attachmentUrl(jmsg))); - } - }; - onLike = event -> { - User liker = event.getUser(); - com.juick.Message message = event.getMessage(); - telegramService.getTelegramIdentifiers(Collections.singletonList(message.getUser())) - .forEach(c -> telegramNotify(c, String.format("%s recommends your post", - MessageUtils.getMarkdownUser(liker)),null)); - }; - onSubscribe = event -> { - User subscriber = event.getUser(); - User target = event.getToUser(); - telegramService.getTelegramIdentifiers(Collections.singletonList(target)) - .forEach(c -> telegramNotify(c, String.format("%s subscribed to your blog", - MessageUtils.getMarkdownUser(subscriber)), null)); - }; } public void processUpdate(String data) throws Exception { @@ -338,4 +299,34 @@ public class TelegramBotManager { } }); } + public void processMessage(com.juick.Message jmsg) { + String msgUrl = formatUrl(jmsg); + if (jmsg.getMid() > 0 && jmsg.getRid() == 0) { + String msg = String.format("[%s](%s) %s", MSG_LINK, msgUrl, formatPost(jmsg, true)); + + List<Long> users = telegramService.getTelegramIdentifiers(subscriptionService.getSubscribedUsers(jmsg.getUser().getUid(), jmsg.getMid())); + List<Long> chats = telegramService.getChats(); + // registered subscribed users + + users.forEach(c -> telegramNotify(c, msg, MessageUtils.attachmentUrl(jmsg))); + // anonymous + chats.stream().filter(u -> telegramService.getUser(u) == 0).forEach(c -> telegramNotify(c, msg, MessageUtils.attachmentUrl(jmsg))); + } else if (jmsg.getRid() > 0) { + com.juick.Message op = messagesService.getMessage(jmsg.getMid()); + String fmsg = String.format("[%s](%s) %s", MSG_LINK, msgUrl, formatPost(jmsg, true)); + telegramService.getTelegramIdentifiers( + subscriptionService.getUsersSubscribedToComments(op, jmsg) + ).forEach(c -> telegramNotify(c, fmsg, MessageUtils.attachmentUrl(jmsg))); + } + }; + public void processLike(User liker, com.juick.Message message) { + telegramService.getTelegramIdentifiers(Collections.singletonList(message.getUser())) + .forEach(c -> telegramNotify(c, String.format("%s recommends your post", + MessageUtils.getMarkdownUser(liker)),null)); + }; + public void processSubscribe(User subscriber, User target) { + telegramService.getTelegramIdentifiers(Collections.singletonList(target)) + .forEach(c -> telegramNotify(c, String.format("%s subscribed to your blog", + MessageUtils.getMarkdownUser(subscriber)), null)); + }; } diff --git a/juick-server/src/main/java/com/juick/server/XMPPBot.java b/juick-server/src/main/java/com/juick/server/XMPPBot.java index e9eacdd7..f9cdf9c8 100644 --- a/juick-server/src/main/java/com/juick/server/XMPPBot.java +++ b/juick-server/src/main/java/com/juick/server/XMPPBot.java @@ -88,21 +88,11 @@ public class XMPPBot implements StanzaListener, AutoCloseable { @Inject private ApplicationEventPublisher applicationEventPublisher; - private ApplicationListener<MessageEvent> onMessage; - @PostConstruct public void init() { xmpp.addStanzaListener(this); broadcastPresence(null); pt = new PrettyTime(new Locale("ru")); - onMessage = event -> { - com.juick.Message msg = event.getMessage(); - if (msg.getRid() == 0 && msg.getMid() > 0) { - String notify = "New message posted.\n#" + msg.getMid() + " https://juick.com/" + msg.getMid(); - userService.getJIDsbyUID(msg.getUser().getUid()) - .forEach(jid -> sendReply(Jid.of(jid), notify)); - } - }; } public Jid getJid() { @@ -239,7 +229,7 @@ public class XMPPBot implements StanzaListener, AutoCloseable { if (username.equals(jid.getLocal())) { try { - return incomingMessageJuick(user_from, msg); + return incomingMessageJuick(user_from, msg.getFrom(), msg.getBody().trim()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { return false; } @@ -324,8 +314,7 @@ public class XMPPBot implements StanzaListener, AutoCloseable { } return Optional.empty(); } - public boolean incomingMessageJuick(User user_from, Message msg) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { - String command = msg.getBody().trim(); + public boolean incomingMessageJuick(User user_from, Jid from, String command) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { int commandlen = command.length(); // COMPATIBILITY @@ -333,9 +322,9 @@ public class XMPPBot implements StanzaListener, AutoCloseable { command = command.substring(3).trim(); } - Optional<String> result = processCommand(user_from, msg.getFrom(), command); + Optional<String> result = processCommand(user_from, from, command); if (result.isPresent()) { - sendReply(msg.getFrom(), result.get()); + sendReply(from, result.get()); } else { // new message List<Tag> tags = tagService.fromString(command, false); @@ -347,6 +336,14 @@ public class XMPPBot implements StanzaListener, AutoCloseable { return true; } + public void processMessage(com.juick.Message msg) { + if (msg.getRid() == 0 && msg.getMid() > 0) { + String notify = "New message posted.\n#" + msg.getMid() + " https://juick.com/" + msg.getMid(); + userService.getJIDsbyUID(msg.getUser().getUid()) + .forEach(jid -> sendReply(Jid.of(jid), notify)); + } + } + @UserCommand(pattern = "^ping$", patternFlags = Pattern.CASE_INSENSITIVE, help = "PING - returns you a PONG") public String commandPing(User user, Jid from, String[] input) { diff --git a/juick-server/src/main/java/com/juick/server/configuration/ApiAppConfiguration.java b/juick-server/src/main/java/com/juick/server/configuration/ApiAppConfiguration.java index 1ca0130f..8d533f05 100644 --- a/juick-server/src/main/java/com/juick/server/configuration/ApiAppConfiguration.java +++ b/juick-server/src/main/java/com/juick/server/configuration/ApiAppConfiguration.java @@ -53,7 +53,8 @@ import java.util.Collections; @EnableSwagger2 @EnableScheduling @EnableWebSocket -@Import({ApiSecurityConfig.class, BaseWebConfiguration.class, DataConfiguration.class, StorageConfiguration.class}) +@Import({ApiSecurityConfig.class, BaseWebConfiguration.class, DataConfiguration.class, StorageConfiguration.class, +EventsConfiguration.class}) @ComponentScan(basePackages = "com.juick.server") public class ApiAppConfiguration implements WebMvcConfigurer, WebSocketConfigurer { @Inject diff --git a/juick-server/src/main/java/com/juick/server/configuration/EventsConfiguration.java b/juick-server/src/main/java/com/juick/server/configuration/EventsConfiguration.java new file mode 100644 index 00000000..4edc9dde --- /dev/null +++ b/juick-server/src/main/java/com/juick/server/configuration/EventsConfiguration.java @@ -0,0 +1,39 @@ +package com.juick.server.configuration; + +import com.juick.server.TelegramBotManager; +import com.juick.server.XMPPBot; +import com.juick.server.component.LikeEvent; +import com.juick.server.component.MessageEvent; +import com.juick.server.component.SubscribeEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.inject.Inject; + +@Configuration +public class EventsConfiguration { + @Inject + private TelegramBotManager telegramBotManager; + @Inject + private XMPPBot bot; + @Bean + ApplicationListener<MessageEvent> messageListener() { + return event -> { + telegramBotManager.processMessage(event.getMessage()); + bot.processMessage(event.getMessage()); + }; + } + @Bean + ApplicationListener<LikeEvent> likeListener() { + return event -> { + telegramBotManager.processLike(event.getUser(), event.getMessage()); + }; + } + @Bean + ApplicationListener<SubscribeEvent> subscribeListener() { + return event -> { + telegramBotManager.processSubscribe(event.getUser(), event.getToUser()); + }; + } +} 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 0aa1e3ca..fcc0a422 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 @@ -24,9 +24,11 @@ import com.juick.ExternalToken; import com.juick.Message; import com.juick.Tag; import com.juick.User; +import com.juick.configuration.DataConfiguration; import com.juick.server.EmailManager; import com.juick.server.XMPPBot; import com.juick.server.XMPPServer; +import com.juick.server.configuration.ApiAppConfiguration; import com.juick.server.helpers.TagStats; import com.juick.service.*; import com.juick.util.DateFormattersHolder; @@ -39,7 +41,13 @@ import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoCon import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.server.ServletWebServerFactory; +import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestPropertySource; @@ -51,9 +59,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import rocks.xmpp.addr.Jid; +import rocks.xmpp.core.stanza.MessageEvent; import rocks.xmpp.core.stanza.model.Stanza; import rocks.xmpp.core.stanza.model.server.ServerMessage; +import javax.annotation.Nonnull; import javax.inject.Inject; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; @@ -61,6 +71,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; +import java.util.concurrent.CountDownLatch; import java.util.stream.IntStream; import static org.hamcrest.MatcherAssert.assertThat; @@ -78,7 +89,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @TestPropertySource(properties = {"broken_ssl_hosts=localhost,serverstorageisfull.tld", "xmpp_disabled=true"}) @AutoConfigureMockMvc -public class ServerTests extends AbstractJUnit4SpringContextTests { +public class ServerTests { @Inject private MockMvc mockMvc; @@ -114,6 +125,14 @@ public class ServerTests extends AbstractJUnit4SpringContextTests { private static boolean isSetUp = false; + @Import({ApiAppConfiguration.class, DataConfiguration.class}) + @Configuration + static class TestConfig { + @Bean + ApplicationListener<com.juick.server.component.MessageEvent> listener() { + return event -> latch.countDown(); + } + } @Before public void setUp() { @@ -380,6 +399,7 @@ public class ServerTests extends AbstractJUnit4SpringContextTests { int uid = userService.createUser("me", "secret"); User user = userService.getUserByUID(uid).orElse(new User()); Tag yo = tagService.getTag("yo", true); + bot.incomingMessageJuick(user, Jid.of("test@localhost"), "*yo yoyo"); int mid = messagesService.createMessage(uid, "yoyo", null, Collections.singletonList(yo)); assertEquals("should be message", true, bot.processCommand(user, Jid.of("test@localhost"), String.format("#%d", mid)).get().startsWith("@me")); @@ -468,6 +488,7 @@ public class ServerTests extends AbstractJUnit4SpringContextTests { bot.processCommand(user, Jid.of("test@localhost"), "D #" + mid).get()); assertEquals("should be not found", "Message not found", bot.processCommand(user, Jid.of("test@localhost"), "#" + mid).get()); + assertThat(latch.getCount(), equalTo(0L)); } @Test public void mailParserTest() throws Exception { @@ -507,4 +528,6 @@ public class ServerTests extends AbstractJUnit4SpringContextTests { Assert.assertThat(count, equalTo(0L)); mockMvc.perform(get("/ws/_all")).andExpect(status().isBadRequest()); } + + private static CountDownLatch latch = new CountDownLatch(1); } |