Skip to content

Commit

Permalink
refactor(Addressed PR feedback.):
Browse files Browse the repository at this point in the history
  • Loading branch information
br648 committed Dec 13, 2024
1 parent 91d6619 commit c5582e1
Show file tree
Hide file tree
Showing 15 changed files with 289 additions and 231 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ public enum Message {
ACCEPT_DEPENDENT_EMAIL_SUBJECT,
ACCEPT_DEPENDENT_EMAIL_MANAGE,
ACCEPT_DEPENDENT_ERROR,
ARRIVED_AND_MODE_CHANGE_NOTIFICATION,
ARRIVED_NOTIFICATION,
DEPARTED_NOTIFICATION,
LABEL_AND_CONTENT,
MODE_CHANGE_NOTIFICATION,
SMS_STOP_NOTIFICATIONS,
TRIP_EMAIL_SUBJECT,
TRIP_EMAIL_SUBJECT_FOR_USER,
Expand Down Expand Up @@ -51,7 +51,6 @@ public enum Message {
TRIP_INVITE_PRIMARY_TRAVELER,
TRIP_INVITE_OBSERVER,
TRIP_NAME_UNDEFINED,
TRIP_TRAVELER_GENERIC_NAME,
TRIP_NOT_FOUND_NOTIFICATION,
TRIP_NO_LONGER_POSSIBLE_NOTIFICATION,
TRIP_REMINDER_NOTIFICATION,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package org.opentripplanner.middleware.models;

import org.opentripplanner.middleware.i18n.Message;
import org.opentripplanner.middleware.persistence.Persistence;
import org.opentripplanner.middleware.tripmonitor.jobs.NotificationType;
import org.opentripplanner.middleware.triptracker.TravelerPosition;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import static com.mongodb.client.model.Filters.eq;

public class LegTransitionNotification {

Expand All @@ -34,28 +37,27 @@ public LegTransitionNotification(
* Create {@link TripMonitorNotification} for leg transition based on notification type.
*/
@Nullable
public TripMonitorNotification createTripMonitorNotification(NotificationType notificationType) {
private TripMonitorNotification createTripMonitorNotification(NotificationType notificationType) {
String body;
switch (notificationType) {
case MODE_CHANGE_NOTIFICATION:
case ARRIVED_AND_MODE_CHANGE_NOTIFICATION:
body = String.format(
Message.MODE_CHANGE_NOTIFICATION.get(travelerPosition.locale),
getTravelerName(),
travelerPosition.expectedLeg.mode,
travelerPosition.nextLeg.mode
Message.ARRIVED_AND_MODE_CHANGE_NOTIFICATION.get(observerLocale),
travelerName,
travelerPosition.expectedLeg.to.name
);
break;
case DEPARTED_NOTIFICATION:
body = String.format(
Message.DEPARTED_NOTIFICATION.get(observerLocale),
getTravelerName(),
travelerName,
travelerPosition.expectedLeg.from.name
);
break;
case ARRIVED_NOTIFICATION:
body = String.format(
Message.ARRIVED_NOTIFICATION.get(travelerPosition.locale),
getTravelerName(),
Message.ARRIVED_NOTIFICATION.get(observerLocale),
travelerName,
travelerPosition.expectedLeg.to.name
);
break;
Expand All @@ -66,38 +68,23 @@ public TripMonitorNotification createTripMonitorNotification(NotificationType no
}

/**
* Get the traveler's name if available, if not provide a generic traveler name.
* Get a list of users that should be notified of a traveler's leg transition.
*/
private String getTravelerName() {
if (travelerName != null) {
return travelerName;
} else {
return Message.TRIP_TRAVELER_GENERIC_NAME.get(observerLocale);
public static Set<OtpUser> getLegTransitionNotifyUsers(MonitoredTrip trip) {
Set<OtpUser> notifyUsers = new HashSet<>();

if (trip.ownedByPrimary() && trip.companion != null) {
notifyUsers.add(Persistence.otpUsers.getOneFiltered(eq("email", trip.companion.email)));
} else if (trip.ownedByCompanion() && trip.primary != null) {
notifyUsers.add(Persistence.otpUsers.getById(trip.primary.userId));
}
}

/**
* Create locale specific notifications.
*/
public static TripMonitorNotification[] createLegTransitionNotifications(
List<NotificationType> legTransitionTypes,
String travelerName,
TravelerPosition travelerPosition,
Locale observerLocale
) {
List<TripMonitorNotification> tripMonitorNotifications = new ArrayList<>();
// Create locale specific notifications.
for (NotificationType legTransitionType : legTransitionTypes) {
LegTransitionNotification legTransitionNotification = new LegTransitionNotification(
travelerName,
legTransitionType,
travelerPosition,
observerLocale
);
if (legTransitionNotification.tripMonitorNotification != null) {
tripMonitorNotifications.add(legTransitionNotification.tripMonitorNotification);
trip.observers.forEach(observer -> {
if (observer.isConfirmed()) {
notifyUsers.add(Persistence.otpUsers.getOneFiltered(eq("email", observer.email)));
}
}
return tripMonitorNotifications.toArray(new TripMonitorNotification[0]);
});

return notifyUsers;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.mongodb.client.model.Filters.eq;

/**
* A monitored trip represents a trip a user would like to receive notification on if affected by a delay and/or route
* change.
Expand Down Expand Up @@ -500,4 +502,19 @@ public TripUsers(MobilityProfileLite primary, RelatedUser companion, List<Relate
this.observers = observers;
}
}

/**
* Trip created by primary user.
*/
public boolean ownedByPrimary() {
return primary != null && primary.userId.equalsIgnoreCase(userId);
}

/**
* Trip created by companion user.
*/
public boolean ownedByCompanion() {
OtpUser tripOwner = Persistence.otpUsers.getById(userId);
return tripOwner != null && companion != null && companion.email.equalsIgnoreCase(tripOwner.email);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSetter;
import org.apache.logging.log4j.util.Strings;
import org.opentripplanner.middleware.auth.Auth0Users;
import org.opentripplanner.middleware.auth.RequestingUser;
import org.opentripplanner.middleware.persistence.Persistence;
Expand Down Expand Up @@ -210,4 +211,11 @@ public Optional<TripSurveyNotification> findLastTripSurveyNotificationSent() {
if (tripSurveyNotifications == null) return Optional.empty();
return tripSurveyNotifications.stream().max(Comparator.comparingLong(n -> n.timeSent.getTime()));
}

/**
* Use name if available, if not fallback on their email (which is a required field).
*/
public String getAddressee() {
return Strings.isBlank(name) ? email : name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import java.util.Date;
import java.util.Locale;
import java.util.Objects;

/**
* Contains information about the type and details of messages to be sent to users about their {@link MonitoredTrip}s.
Expand Down Expand Up @@ -110,4 +111,17 @@ public static TripMonitorNotification createInitialReminderNotification(
)
);
}

@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
TripMonitorNotification that = (TripMonitorNotification) o;
return type == that.type && Objects.equals(body, that.body);
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), type, body);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public class JourneyState implements Cloneable {

/**
* The notifications already sent.
* FIXME this is never set, so it has no effect.
*/
public Set<TripMonitorNotification> lastNotifications = new HashSet<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,6 @@ private static boolean sendAcceptDependentEmail(OtpUser dependentUser, OtpUser r

String acceptDependentLinkLabel = Message.ACCEPT_DEPENDENT_EMAIL_LINK_TEXT.get(locale);
String acceptDependentUrl = getAcceptDependentUrl(acceptKey, locale);
String addressee = (Strings.isBlank(dependentUser.name)) ? dependentUser.email : dependentUser.name;

// A HashMap is needed instead of a Map for template data to be serialized to the template renderer.
Map<String, Object> templateData = new HashMap<>(
Expand All @@ -193,7 +192,7 @@ private static boolean sendAcceptDependentEmail(OtpUser dependentUser, OtpUser r
"acceptDependentLinkLabelAndUrl", label(acceptDependentLinkLabel, acceptDependentUrl, locale),
"acceptDependentUrl", acceptDependentUrl,
"emailFooter", Message.ACCEPT_DEPENDENT_EMAIL_FOOTER.get(locale),
"emailGreeting", String.format(Message.ACCEPT_DEPENDENT_EMAIL_GREETING.get(locale), addressee),
"emailGreeting", String.format(Message.ACCEPT_DEPENDENT_EMAIL_GREETING.get(locale), dependentUser.getAddressee()),
"manageLinkUrl", String.format("%s%s", OTP_UI_URL, SETTINGS_PATH),
"manageLinkText", Message.ACCEPT_DEPENDENT_EMAIL_MANAGE.get(locale)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import static com.mongodb.client.model.Filters.eq;
import static org.opentripplanner.middleware.models.LegTransitionNotification.getLegTransitionNotifyUsers;

/**
* This job handles the primary functions for checking a {@link MonitoredTrip}, including:
Expand Down Expand Up @@ -251,28 +251,24 @@ private boolean isTrackingOngoing() {
}

/**
* Process leg transition notifications.
* Process leg transition notification.
*/
public void processLegTransition(List<NotificationType> legTransitionTypes, TravelerPosition travelerPosition) {
OtpUser otpUser = getOtpUser();
if (otpUser != null) {
otpUser.relatedUsers.forEach(relatedUser -> {
if (relatedUser.isConfirmed()) {
OtpUser observer = Persistence.otpUsers.getOneFiltered(eq("email", relatedUser.email));
if (observer != null) {
enqueueNotification(
LegTransitionNotification.createLegTransitionNotifications(
legTransitionTypes,
otpUser.name,
travelerPosition,
I18nUtils.getOtpUserLocale(observer)
)
);
sendNotifications(observer);
}
}
});
}
public void processLegTransition(NotificationType notificationType, TravelerPosition travelerPosition) {
OtpUser tripOwner = getOtpUser();
Set<OtpUser> notifyUsers = getLegTransitionNotifyUsers(trip);
notifyUsers.forEach(observer -> {
if (observer != null) {
enqueueNotification(
new LegTransitionNotification(
tripOwner.getAddressee(),
notificationType,
travelerPosition,
I18nUtils.getOtpUserLocale(observer)
).tripMonitorNotification
);
sendNotifications(observer);
}
});
}

/**
Expand Down Expand Up @@ -560,7 +556,7 @@ private void sendNotifications(OtpUser otpUser) {
return;
}

Locale locale = getOtpUserLocale();
Locale locale = I18nUtils.getOtpUserLocale(otpUser);
String tripNameOrReminder = hasInitialReminder ? initialReminderNotification.body : trip.tripName;
if (tripNameOrReminder == null) {
tripNameOrReminder = Message.TRIP_NAME_UNDEFINED.get(locale);
Expand All @@ -585,7 +581,7 @@ private void sendNotifications(OtpUser otpUser) {
boolean successSms = false;

if (otpUser.notificationChannel.contains(OtpUser.Notification.EMAIL)) {
successEmail = sendEmail(otpUser, templateData);
successEmail = sendEmail(otpUser, templateData, locale);
}
if (otpUser.notificationChannel.contains(OtpUser.Notification.PUSH)) {
successPush = sendPush(otpUser, templateData);
Expand All @@ -597,6 +593,9 @@ private void sendNotifications(OtpUser otpUser) {
// TODO: better handle below when one of the following fails
if (successEmail || successPush || successSms) {
notificationTimestampMillis = DateTimeUtils.currentTimeMillis();
// Prevent repeated notifications by saving successfully sent notifications.
trip.journeyState.lastNotifications.addAll(notifications);
Persistence.monitoredTrips.replace(trip.id, trip);
}
}

Expand All @@ -617,8 +616,7 @@ private boolean sendPush(OtpUser otpUser, Map<String, Object> data) {
/**
* Send notification email in MonitoredTrip template.
*/
private boolean sendEmail(OtpUser otpUser, Map<String, Object> data) {
Locale locale = getOtpUserLocale();
private boolean sendEmail(OtpUser otpUser, Map<String, Object> data, Locale locale) {
String subject = NotificationUtils.getTripEmailSubject(otpUser, locale, trip);
return NotificationUtils.sendEmail(
otpUser,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public enum NotificationType {
ALERT_FOUND,
ITINERARY_NOT_FOUND,
INITIAL_REMINDER,
MODE_CHANGE_NOTIFICATION,
ARRIVED_AND_MODE_CHANGE_NOTIFICATION,
DEPARTED_NOTIFICATION,
ARRIVED_NOTIFICATION
}
Loading

0 comments on commit c5582e1

Please sign in to comment.