diff options
author | Vitaly Takmazov | 2017-12-27 16:23:28 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2018-01-12 09:12:09 +0300 |
commit | bf5f2142d73a5745124d03f6b6f06c59873e47de (patch) | |
tree | 969d43a3bf6d39197313e16080b8b8472975cbe2 /juick-api/src/main/java/com/juick/api/MessengerManager.java | |
parent | 0c78bc5c08632718eb94c0021cf3ee47fb8ddb82 (diff) |
Messenger bot
Diffstat (limited to 'juick-api/src/main/java/com/juick/api/MessengerManager.java')
-rw-r--r-- | juick-api/src/main/java/com/juick/api/MessengerManager.java | 143 |
1 files changed, 143 insertions, 0 deletions
diff --git a/juick-api/src/main/java/com/juick/api/MessengerManager.java b/juick-api/src/main/java/com/juick/api/MessengerManager.java new file mode 100644 index 00000000..9587dc11 --- /dev/null +++ b/juick-api/src/main/java/com/juick/api/MessengerManager.java @@ -0,0 +1,143 @@ +package com.juick.api; + +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 ApiServer apiServer; + + @Value("${fb_page_access_token}") + private String facebookPageAccessToken; + @Value("${fb_verify_token}") + private String facebookVerifyToken; + @Value("${fb_secret}") + 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); + apiServer.processMessage(user_from, text, null); + messengerNotify(senderId, "Message sent", null); + } + } + }); + } + + @Override + public void onApplicationEvent(@Nonnull MessageEvent event) { + Message msg = event.getMessage(); + if (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 { + // 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)))); + } + } + + 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); + } + } + 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))); + } +} |