/*
* Copyright (c) 2014 Jacob D. Parr
*
* This software may not be used without permission.
*/
package com.cosmicpush.app.resources.api.userevent;
import com.amazonaws.auth.*;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.*;
import com.cosmicpush.app.domain.accounts.Account;
import com.cosmicpush.app.domain.clients.ApiClient;
import com.cosmicpush.app.domain.clients.config.*;
import com.cosmicpush.app.domain.requests.*;
import com.cosmicpush.app.resources.api.*;
import com.cosmicpush.app.resources.api.jabber.JabberFactory;
import com.cosmicpush.app.resources.manage.client.userevents.*;
import com.cosmicpush.app.system.CpServerObjectMapper;
import com.cosmicpush.pub.common.*;
import com.cosmicpush.pub.push.UserEventPush;
import java.util.List;
import org.crazyyak.dev.common.*;
import org.crazyyak.dev.common.exceptions.*;
import org.crazyyak.dev.domain.comm.AuthenticationMethod;
import org.crazyyak.dev.net.email.EmailMessage;
public class UserEventDelegate extends AbstractDelegate {
private final Account account;
private final ApiClient apiClient;
private final UserEventPush userEvent;
public UserEventDelegate(CpServerObjectMapper objectMapper, ApiRequestStore apiRequestStore, Account account, ApiClient apiClient, ApiRequest apiRequest, UserEventPush userEvent) {
super(objectMapper, apiRequest, apiRequestStore);
this.userEvent = ExceptionUtils.assertNotNull(userEvent, "userEvent");
this.account = ExceptionUtils.assertNotNull(account, "account");
this.apiClient = ExceptionUtils.assertNotNull(apiClient, "apiClient");
}
@Override
public synchronized RequestStatus processRequest() throws Exception {
String reasonNotPermitted = account.getReasonNotPermitted(userEvent);
if (StringUtils.isNotBlank(reasonNotPermitted)) {
return apiRequest.denyRequest(reasonNotPermitted);
} else if (userEvent.isSendStory()) {
return sendEmail(); // This is the "last" event so we can send the email.
}
if (userEvent.containsTrait("priority", "urgent")) {
sendMessage(); // THIS is an "urgent" request so send the message now.
}
return apiRequest.processed();
}
private RequestStatus sendEmail() {
String sessionId = userEvent.getSessionId();
List<ApiRequest> requests = apiRequestStore.getByClientAndSession(apiClient, sessionId);
String deviceId = null;
for (ApiRequest request : requests) {
if (request.getUserEventPush().getDeviceId() != null) {
deviceId = request.getUserEventPush().getDeviceId();
break;
}
}
if (deviceId == null) {
// We never found a device ID, we have an "invalid" request.
return apiRequest.processed();
}
requests = apiRequestStore.getByClientAndDevice(apiClient, deviceId);
UserEventGroup group = new UserEventGroup(requests);
if (group.getBotName() != null || requests.size() == 1) {
// not interested in sending an email.
return apiRequest.processed();
}
UserEventSession session = group.findSession(userEvent);
String userName = group.getUserName();
if (StringUtils.isBlank(userName)) {
userName = "Anonymous";
}
String story = String.format("<h1 style='margin:0'>New Story for %s</h1>\n", userName);
story += "<fieldset style='margin-top:1em'>";
story += "<legend>Request</legend><table>";
story += tableRow("Bot", group.getBotName());
story += tableRow("User Name", userName);
story += tableRow("IP Address", session.getIpAddress());
story += tableRow("Host Address", session.getHostAddress());
story += tableRow("Session ID", session.getSessionId());
story += "</table></fieldset>";
UserAgent userAgent = session.getUserAgent();
if (userAgent != null) {
story += "<fieldset style='margin-top:1em'>";
story += "<legend>User-Agent</legend><table>";
story += tableRow(userAgent.getAgentType(), userAgent.getAgent());
story += tableRow(userAgent.getOsType(), userAgent.getOs());
story += "</table></fieldset>";
}
story += "<fieldset style='margin-top:1em'>";
story += "<legend>Events</legend><table>";
for (ApiRequest request : session.getApiRequests()) {
String msg = request.getUserEventPush().getMessage();
String time = Formats.defaultTime(request.getUserEventPush().getCreatedAt().toDate());
story += tableRow(time, msg);
}
story += "</table></fieldset>";
story += String.format("<p><a href='https://www.cosmicpush.com/manage/api-client/%s/user-events/%s'>More Information...</a></p>", apiClient.getClientName(), deviceId);
story = String.format("<html>\n<body>\n%s</body>\n</html>\n", story);
sendEmail(userName, story);
return apiRequest.processed();
}
private String tableRow(String label, String value) {
if (StringUtils.isBlank(value)) return "";
return String.format("<tr><td style='white-space:nowrap'>%s: </td><td>%s</td></tr>\n",
StringUtils.escapeHtml(label),
StringUtils.escapeHtml(value));
}
private void sendEmail(String userName, String htmlContent) {
if (apiClient.getAwsEmailConfig() != null) {
sendAwsEmail(userName, htmlContent);
} else if (apiClient.getSmtpEmailConfig() != null) {
sendSmtpEmail(userName, htmlContent);
} else {
String msg = String.format("An email configuration was not specified.");
throw ApiException.internalServerError(msg);
}
}
private void sendSmtpEmail(String userName, String htmlContent) {
try {
SmtpEmailConfig config = apiClient.getSmtpEmailConfig();
if (config == null) {
throw new UnsupportedOperationException("AWS e-mail configuration was not specified.");
}
EmailMessage message = new EmailMessage(config.getServerName(), config.getPortNumber(), "jacob.parr@gmail.com");
if (config.getAuthType().isTls()) {
message.setAuthentication(AuthenticationMethod.TLS, config.getUserName(), config.getPassword());
} else if (config.getAuthType().isSsl()) {
message.setAuthentication(AuthenticationMethod.SSL, config.getUserName(), config.getPassword());
} else {
message.setAuthentication(AuthenticationMethod.NONE, config.getUserName(), config.getPassword());
}
message.setFrom("Munchie Monster Support <support@munchiemonster.com>");
String subject = "New Story for " + userName;
message.send(subject, null, htmlContent);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void sendAwsEmail(String userName, String htmlContent) {
try {
AwsEmailConfig config = apiClient.getAwsEmailConfig();
if (config == null) {
throw new UnsupportedOperationException("AWS e-mail configuration was not specified.");
}
Body body = new Body();
body.withHtml(new Content().withCharset("UTF-8").withData(htmlContent));
SendEmailRequest sendEmailRequest = new SendEmailRequest();
String fromAddress = "Munchie Monster Support <support@munchiemonster.com>";
sendEmailRequest.withSource(fromAddress);
sendEmailRequest.withReturnPath(fromAddress);
sendEmailRequest.withReplyToAddresses(fromAddress);
sendEmailRequest.setDestination(new Destination().withToAddresses("jacob.parr@gmail.com"));
Content subject = new Content().withCharset("UTF-8").withData("New Story for " + userName);
sendEmailRequest.setMessage(new Message(subject, body));
AWSCredentials awsCredentials = new BasicAWSCredentials(config.getAccessKeyId(), config.getSecretKey());
new AmazonSimpleEmailServiceClient(awsCredentials).sendEmail(sendEmailRequest);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void sendMessage() {
try {
GoogleTalkConfig config = apiClient.getGoogleTalkConfig();
if (config == null) {
throw new UnsupportedOperationException("Google Talk configuration was not specified.");
}
JabberFactory factory = new JabberFactory(config.getUserName(), config.getPassword());
String id = apiRequest.getApiRequestId();
id = id.substring(id.indexOf(":")+1);
String message = userEvent.getMessage();
message += "\nhttps://www.cosmicpush.com/q/" + id;
factory.sendTo("jacob.parr@gmail.com", message);
} catch (Throwable e) {
e.printStackTrace();
}
}
}