From 5f3e74559144da2b659773a29f73211e2347dd16 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 25 Dec 2017 11:44:32 +0300 Subject: email notifications --- .../src/main/java/com/juick/api/EmailManager.java | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 juick-api/src/main/java/com/juick/api/EmailManager.java (limited to 'juick-api/src') diff --git a/juick-api/src/main/java/com/juick/api/EmailManager.java b/juick-api/src/main/java/com/juick/api/EmailManager.java new file mode 100644 index 00000000..8e868ca0 --- /dev/null +++ b/juick-api/src/main/java/com/juick/api/EmailManager.java @@ -0,0 +1,56 @@ +package com.juick.api; + +import com.juick.Message; +import com.juick.server.component.MessageEvent; +import com.juick.server.util.HttpBadRequestException; +import com.juick.service.EmailService; +import com.juick.service.SubscriptionService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import static com.juick.formatters.PlainTextFormatter.formatPost; + +@Component +public class EmailManager implements ApplicationListener { + private static final Logger logger = LoggerFactory.getLogger(EmailManager.class); + @Inject + EmailService emailService; + @Inject + SubscriptionService subscriptionService; + @Override + public void onApplicationEvent(MessageEvent event) { + Message msg = event.getMessage(); + if (msg.getRid() == 0) { + subscriptionService.getSubscribedUsers(msg.getUser().getUid(), msg.getMid()) + .forEach(user -> emailService.getEmails(user.getUid()) + .forEach(email -> emailNotify(email, msg))); + } else { + subscriptionService.getUsersSubscribedToComments(msg.getMid(), msg.getUser().getUid()) + .forEach(user -> emailService.getEmails(user.getUid()) + .forEach(email -> emailNotify(email, msg))); + } + } + + void emailNotify(String email, Message msg) { + Session session = Session.getDefaultInstance(System.getProperties()); + try { + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress("noreply@mail.juick.com")); + message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(email)); + message.setSubject(String.format("New message from %s", msg.getUser().getName())); + message.setText(formatPost(msg)); + Transport.send(message); + } catch (MessagingException ex) { + logger.error("mail exception", ex); + } + } +} -- cgit v1.2.3