aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick/server/MessengerManager.java
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2018-02-08 22:06:08 +0300
committerGravatar Vitaly Takmazov2018-02-08 22:06:08 +0300
commit7414f1034d32c249294a081f1e176a9266fc92ac (patch)
treec780ea6f8a4a4d4db22147b1eea151317765abce /juick-server/src/main/java/com/juick/server/MessengerManager.java
parentc97d1475dc0faa0e791257ca6c6a8561df2ffa90 (diff)
reorganize project structure
Diffstat (limited to 'juick-server/src/main/java/com/juick/server/MessengerManager.java')
-rw-r--r--juick-server/src/main/java/com/juick/server/MessengerManager.java143
1 files changed, 143 insertions, 0 deletions
diff --git a/juick-server/src/main/java/com/juick/server/MessengerManager.java b/juick-server/src/main/java/com/juick/server/MessengerManager.java
new file mode 100644
index 00000000..2979fa28
--- /dev/null
+++ b/juick-server/src/main/java/com/juick/server/MessengerManager.java
@@ -0,0 +1,143 @@
+package com.juick.server;
+
+import com.github.messenger4j.Messenger;
+import com.github.messenger4j.exception.MessengerApiException;
+import com.github.messenger4j.exception.MessengerIOException;
+import com.github.messenger4j.exception.MessengerVerificationException;
+import com.github.messenger4j.send.MessagePayload;
+import com.github.messenger4j.send.message.TemplateMessage;
+import com.github.messenger4j.send.message.TextMessage;
+import com.github.messenger4j.send.message.template.ButtonTemplate;
+import com.github.messenger4j.send.message.template.button.UrlButton;
+import com.github.messenger4j.userprofile.UserProfile;
+import com.github.messenger4j.webhook.event.TextMessageEvent;
+import com.juick.Message;
+import com.juick.User;
+import com.juick.server.component.MessageEvent;
+import com.juick.service.MessagesService;
+import com.juick.service.MessengerService;
+import com.juick.service.SubscriptionService;
+import com.juick.service.UserService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationListener;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Nonnull;
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.Optional;
+
+import static com.juick.formatters.PlainTextFormatter.formatPost;
+import static com.juick.formatters.PlainTextFormatter.formatUrl;
+
+@Component
+public class MessengerManager implements ApplicationListener<MessageEvent> {
+ private static final Logger logger = LoggerFactory.getLogger(MessengerManager.class);
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private SubscriptionService subscriptionService;
+ @Inject
+ private UserService userService;
+ @Inject
+ private MessengerService messengerService;
+ @Inject
+ private ServerManager serverManager;
+
+ @Value("${fb_page_access_token:12345678}")
+ private String facebookPageAccessToken;
+ @Value("${fb_verify_token:12345678}")
+ private String facebookVerifyToken;
+ @Value("${fb_secret:12345678}")
+ private String facebookSecret;
+
+ private Messenger messenger;
+
+ @PostConstruct
+ public void init() {
+ messenger = Messenger.create(facebookPageAccessToken, facebookSecret, facebookVerifyToken);
+ }
+
+ public String getFacebookVerifyToken() {
+ return facebookVerifyToken;
+ }
+
+ public void processUpdate(String signature , String data) throws MessengerVerificationException {
+ messenger.onReceiveEvents(data, Optional.of(signature), event -> {
+ final String senderId = event.senderId();
+ final Instant timestamp = event.timestamp();
+
+ User user_from = userService.getUserByUID(messengerService.getUserId(senderId)).orElse(new User());
+ logger.info("Found juick user {}", user_from.getUid());
+ if (user_from.getUid() == 0) {
+ try {
+ UserProfile profile = messenger.queryUserProfile(senderId);
+ signupNotify(senderId, messengerService.getSignUpHash(senderId, profile.firstName()));
+ } catch (MessengerApiException | MessengerIOException | MalformedURLException e) {
+ logger.warn("messenger profile error", e);
+ try {
+ signupNotify(senderId, messengerService.getSignUpHash(senderId, "anonymous"));
+ } catch (MalformedURLException | MessengerApiException | MessengerIOException e1) {
+ logger.warn("signup error", e1);
+ }
+ }
+ } else {
+ if (event.isTextMessageEvent()) {
+ final TextMessageEvent textMessageEvent = event.asTextMessageEvent();
+ final String messageId = textMessageEvent.messageId();
+ final String text = textMessageEvent.text();
+ logger.info("Received text message from '{}' at '{}' with content: {} (mid: {})",
+ senderId, timestamp, text, messageId);
+ serverManager.processMessage(user_from, text, null);
+ messengerNotify(senderId, "Message sent", null);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onApplicationEvent(@Nonnull MessageEvent event) {
+ Message msg = event.getMessage();
+ if (msg.getMid() > 0 && msg.getRid() == 0) {
+ String subject = formatPost(msg);
+ subscriptionService.getSubscribedUsers(msg.getUser().getUid(), msg.getMid())
+ .forEach(user -> messengerService.getSenderId(user)
+ .ifPresent(t -> messengerNotify(t, subject, formatUrl(msg))));
+ } else if (msg.getRid() > 0) {
+ // get quote
+ com.juick.Message jmsg = messagesService.getReply(msg.getMid(), msg.getRid());
+ String subject = formatPost(jmsg);
+ subscriptionService.getUsersSubscribedToComments(msg.getMid(), msg.getUser().getUid())
+ .forEach(user -> messengerService.getSenderId(user)
+ .ifPresent(t -> messengerNotify(t, subject, formatUrl(jmsg))));
+ }
+ }
+
+ private void messengerNotify(String messengerUser, String text, String url) {
+ try {
+ if (!StringUtils.isEmpty(url)) {
+ final UrlButton showMessage = UrlButton.create("VIEW MESSAGE", new URL(url));
+ ButtonTemplate template = ButtonTemplate.create(text, Collections.singletonList(showMessage));
+ messenger.send(MessagePayload.create(messengerUser, TemplateMessage.create(template)));
+ } else {
+ messenger.send(MessagePayload.create(messengerUser, TextMessage.create(text)));
+ }
+ } catch (MessengerApiException | MessengerIOException | MalformedURLException e) {
+ logger.warn("messenger error", e);
+ }
+ }
+ private void signupNotify(String messengerUser, String hash) throws MalformedURLException, MessengerApiException, MessengerIOException {
+ final UrlButton urlButton = UrlButton.create("LOGIN",
+ new URL("https://juick.com/signup?type=messenger&hash=" + hash));
+ ButtonTemplate template = ButtonTemplate.create("Login to receive notifications",
+ Collections.singletonList(urlButton));
+ messenger.send(MessagePayload.create(messengerUser, TemplateMessage.create(template)));
+ }
+}