Skip to content

Commit

Permalink
Merge branch 'dev' into companions-on-bus-notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
binh-dam-ibigroup committed Dec 9, 2024
2 parents dcde571 + 65e1d30 commit 93ab1f2
Show file tree
Hide file tree
Showing 20 changed files with 712 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
import org.opentripplanner.middleware.models.MonitoredTrip;
import org.opentripplanner.middleware.models.OtpUser;
import org.opentripplanner.middleware.persistence.Persistence;
import org.opentripplanner.middleware.models.RelatedUser;
import org.opentripplanner.middleware.tripmonitor.jobs.CheckMonitoredTrip;
import org.opentripplanner.middleware.tripmonitor.jobs.MonitoredTripLocks;
import org.opentripplanner.middleware.utils.InvalidItineraryReason;
import org.opentripplanner.middleware.utils.JsonUtils;
import org.opentripplanner.middleware.utils.NotificationUtils;
import org.opentripplanner.middleware.utils.SwaggerUtils;
import spark.Request;
import spark.Response;
Expand All @@ -22,12 +24,17 @@

import static io.github.manusant.ss.descriptor.MethodDescriptor.path;
import static com.mongodb.client.model.Filters.eq;
import static org.opentripplanner.middleware.i18n.Message.TRIP_INVITE_COMPANION;
import static org.opentripplanner.middleware.i18n.Message.TRIP_INVITE_OBSERVER;
import static org.opentripplanner.middleware.i18n.Message.TRIP_INVITE_PRIMARY_TRAVELER;
import static org.opentripplanner.middleware.models.MonitoredTrip.USER_ID_FIELD_NAME;
import static org.opentripplanner.middleware.models.MonitoredTrip.getAddedUsers;
import static org.opentripplanner.middleware.utils.ConfigUtils.getConfigPropertyAsInt;
import static org.opentripplanner.middleware.utils.HttpUtils.JSON_ONLY;
import static org.opentripplanner.middleware.utils.JsonUtils.getPOJOFromRequestBody;
import static org.opentripplanner.middleware.utils.JsonUtils.logMessageAndHalt;


/**
* Implementation of the {@link ApiController} abstract class for managing {@link MonitoredTrip} entities. This
* controller connects with Auth0 services using the hooks provided by {@link ApiController}.
Expand Down Expand Up @@ -90,6 +97,8 @@ MonitoredTrip preCreateHook(MonitoredTrip monitoredTrip, Request req) {
}
}

notifyTripCompanionsAndObservers(monitoredTrip, null);

return monitoredTrip;
}

Expand Down Expand Up @@ -128,6 +137,30 @@ private void preCreateOrUpdateChecks(MonitoredTrip monitoredTrip, Request req) {
processTripQueryParams(monitoredTrip, req);
}

/** Notify users added as companions or observers to a trip. (Removed users won't get notified.) */
private void notifyTripCompanionsAndObservers(MonitoredTrip monitoredTrip, MonitoredTrip originalTrip) {
MonitoredTrip.TripUsers usersToNotify = getAddedUsers(monitoredTrip, originalTrip);
OtpUser tripCreator = Persistence.otpUsers.getById(monitoredTrip.userId);

if (usersToNotify.companion != null) {
OtpUser companionUser = Persistence.otpUsers.getOneFiltered(Filters.eq("email", usersToNotify.companion.email));
NotificationUtils.notifyCompanion(monitoredTrip, tripCreator, companionUser, TRIP_INVITE_COMPANION);
}

if (usersToNotify.primary != null) {
// email could be used too for primary users
OtpUser primaryUser = Persistence.otpUsers.getById(usersToNotify.primary.userId);
NotificationUtils.notifyCompanion(monitoredTrip, tripCreator, primaryUser, TRIP_INVITE_PRIMARY_TRAVELER);
}

if (!usersToNotify.observers.isEmpty()) {
for (RelatedUser observer : usersToNotify.observers) {
OtpUser observerUser = Persistence.otpUsers.getOneFiltered(Filters.eq("email", observer.email));
NotificationUtils.notifyCompanion(monitoredTrip, tripCreator, observerUser, TRIP_INVITE_OBSERVER);
}
}
}

/**
* Processes the {@link MonitoredTrip} query parameters, so the trip's fields match the query parameters.
* If an error occurs regarding the query params, returns a HTTP 400 status.
Expand Down Expand Up @@ -171,6 +204,9 @@ MonitoredTrip preUpdateHook(MonitoredTrip monitoredTrip, MonitoredTrip preExisti
// perform the database update here before releasing the lock to be sure that the record is updated in the
// database before a CheckMonitoredTripJob analyzes the data
Persistence.monitoredTrips.replace(monitoredTrip.id, monitoredTrip);

notifyTripCompanionsAndObservers(monitoredTrip, preExisting);

return runCheckMonitoredTrip(monitoredTrip);
} catch (Exception e) {
// FIXME: an error happened while updating the trip, but the trip might have been saved to the DB, so return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public enum Message {
TRIP_DELAY_EARLY,
TRIP_DELAY_LATE,
TRIP_DELAY_MINUTES,
TRIP_INVITE_COMPANION,
TRIP_INVITE_PRIMARY_TRAVELER,
TRIP_INVITE_OBSERVER,
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,6 +1,7 @@
package org.opentripplanner.middleware.models;

import com.auth0.exception.Auth0Exception;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.opentripplanner.middleware.auth.Auth0Connection;
import org.opentripplanner.middleware.auth.RequestingUser;
import org.opentripplanner.middleware.auth.Permission;
Expand All @@ -19,6 +20,7 @@
* It provides a place to centralize common fields that all users share (e.g., email) and common methods (such as the
* authorization check {@link #canBeManagedBy}.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class AbstractUser extends Model {
private static final Logger LOG = LoggerFactory.getLogger(AbstractUser.class);
private static final long serialVersionUID = 1L;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* A monitored trip represents a trip a user would like to receive notification on if affected by a delay and/or route
Expand Down Expand Up @@ -432,6 +435,69 @@ public boolean isOneTime() {
* @return true if the trip has a (confirmed) companion, false otherwise.
*/
public boolean hasConfirmedCompanion() {
return companion != null && companion.status == RelatedUser.RelatedUserStatus.CONFIRMED;
return companion != null && companion.isConfirmed();
}

/**
* Gets users not previously involved (as primary traveler, companion, or observer) in a trip.
*/
public static TripUsers getAddedUsers(MonitoredTrip monitoredTrip, MonitoredTrip originalTrip) {
RelatedUser addedCompanion = null;
if (monitoredTrip.hasConfirmedCompanion() && (
originalTrip == null ||
originalTrip.companion == null ||
!originalTrip.companion.email.equals(monitoredTrip.companion.email)
)) {
// Include the companion if creating trip or setting companion for the first time,
// or setting a different companion.
addedCompanion = monitoredTrip.companion;
}

MobilityProfileLite addedPrimaryTraveler = null;
if (monitoredTrip.primary != null && (
originalTrip == null ||
originalTrip.primary == null ||
!originalTrip.primary.userId.equals(monitoredTrip.primary.userId)
)) {
// Include the primary traveler if creating trip or setting primary traveler for the first time,
// or setting a different primary traveler.
addedPrimaryTraveler = monitoredTrip.primary;
}

List<RelatedUser> addedObservers = new ArrayList<>();
if (monitoredTrip.observers != null) {
List<RelatedUser> confirmedObservers = monitoredTrip.observers.stream()
.filter(Objects::nonNull)
.filter(RelatedUser::isConfirmed)
.collect(Collectors.toList());
if (originalTrip == null || originalTrip.observers == null) {
// Include all observers if creating trip or setting observers for the first time.
addedObservers.addAll(confirmedObservers);
} else {
// If observers have been set before, include observers not previously present.
Set<String> existingObserverEmails = originalTrip.observers.stream()
.map(obs -> obs.email)
.collect(Collectors.toSet());
confirmedObservers.forEach(obs -> {
if (!existingObserverEmails.contains(obs.email)) {
addedObservers.add(obs);
}
});
}
}

return new TripUsers(addedPrimaryTraveler, addedCompanion, addedObservers);
}

public static class TripUsers {
public final RelatedUser companion;
public final List<RelatedUser> observers;
public final MobilityProfileLite primary;

public TripUsers(MobilityProfileLite primary, RelatedUser companion, List<RelatedUser> observers) {
this.primary = primary;
this.companion = companion;
this.observers = observers;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.opentripplanner.middleware.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.bson.codecs.pojo.annotations.BsonIgnore;

/** A related user is a companion or observer requested by a dependent. */
public class RelatedUser {
public enum RelatedUserStatus {
Expand All @@ -15,6 +18,10 @@ public RelatedUser() {
// Required for JSON deserialization.
}

public RelatedUser(String email, RelatedUserStatus status) {
this(email, status, null);
}

public RelatedUser(String email, RelatedUserStatus status, String nickname) {
this.email = email;
this.status = status;
Expand All @@ -25,5 +32,11 @@ public RelatedUser(String email, RelatedUserStatus status, String nickname, Stri
this (email, status, nickname);
this.acceptKey = acceptKey;
}

@JsonIgnore
@BsonIgnore
public boolean isConfirmed() {
return status == RelatedUserStatus.CONFIRMED;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
Expand Down Expand Up @@ -59,8 +60,6 @@ public class CheckMonitoredTrip implements Runnable {

public static final String ACCOUNT_PATH = "/#/account";

private final String TRIPS_PATH = ACCOUNT_PATH + "/trips";

public static final String SETTINGS_PATH = ACCOUNT_PATH + "/settings";

public final MonitoredTrip trip;
Expand Down Expand Up @@ -529,21 +528,15 @@ private void sendNotifications() {
String tripNameOrReminder = hasInitialReminder ? initialReminderNotification.body : trip.tripName;

Locale locale = getOtpUserLocale();
String tripLinkLabel = Message.TRIP_LINK_TEXT.get(locale);
String tripUrl = getTripUrl();
// A HashMap is needed instead of a Map for template data to be serialized to the template renderer.
Map<String, Object> templateData = new HashMap<>(Map.of(
Map<String, Object> templateData = new HashMap<>();
templateData.putAll(Map.of(
"emailGreeting", Message.TRIP_EMAIL_GREETING.get(locale),
"tripNameOrReminder", tripNameOrReminder,
"tripLinkLabelAndUrl", label(tripLinkLabel, tripUrl, locale),
"tripLinkAnchorLabel", tripLinkLabel,
"tripUrl", tripUrl,
"emailFooter", String.format(Message.TRIP_EMAIL_FOOTER.get(locale), OTP_UI_NAME),
"manageLinkText", Message.TRIP_EMAIL_MANAGE_NOTIFICATIONS.get(locale),
"manageLinkUrl", String.format("%s%s", OTP_UI_URL, SETTINGS_PATH),
"notifications", new ArrayList<>(notifications),
"smsFooter", Message.SMS_STOP_NOTIFICATIONS.get(locale)
));
templateData.putAll(NotificationUtils.getTripNotificationFields(trip, locale));
if (hasInitialReminder) {
templateData.put("initialReminder", initialReminderNotification);
}
Expand Down Expand Up @@ -588,9 +581,7 @@ private boolean sendPush(OtpUser otpUser, Map<String, Object> data) {
*/
private boolean sendEmail(OtpUser otpUser, Map<String, Object> data) {
Locale locale = getOtpUserLocale();
String subject = trip.tripName != null
? String.format(Message.TRIP_EMAIL_SUBJECT.get(locale), trip.tripName)
: String.format(Message.TRIP_EMAIL_SUBJECT_FOR_USER.get(locale), otpUser.email);
String subject = NotificationUtils.getTripEmailSubject(otpUser, locale, trip);
return NotificationUtils.sendEmail(
otpUser,
subject,
Expand Down Expand Up @@ -670,6 +661,18 @@ public boolean shouldSkipMonitoredTripCheck(boolean persist) throws Exception {
return true;
}

// For trips that are snoozed, see if they should be unsnoozed first.
if (trip.snoozed) {
if (shouldUnsnoozeTrip()) {
// Clear previous matching itinerary as we want to start afresh.
// The snoozed state will be updated later in the process.
previousMatchingItinerary = null;
} else {
LOG.info("Skipping: Trip is snoozed.");
return true;
}
}

if (isPrevMatchingItineraryNotConcluded()) {
// Skip checking the trip the rest of the time that it is active if the trip was deemed not possible for the
// next possible time during a previous query to find candidate itinerary matches.
Expand All @@ -678,12 +681,6 @@ public boolean shouldSkipMonitoredTripCheck(boolean persist) throws Exception {
return true;
}

// skip checking the trip if it has been snoozed
if (trip.snoozed) {
LOG.info("Skipping: Trip is snoozed.");
return true;
}

matchingItinerary = previousMatchingItinerary;
targetZonedDateTime = DateTimeUtils.makeOtpZonedDateTime(previousJourneyState.targetDate, trip.tripTime);
} else {
Expand Down Expand Up @@ -926,7 +923,24 @@ private Locale getOtpUserLocale() {
return I18nUtils.getOtpUserLocale(getOtpUser());
}

private String getTripUrl() {
return String.format("%s%s/%s", OTP_UI_URL, TRIPS_PATH, trip.id);
/**
* Whether a trip should be unsnoozed and monitoring should resume.
* @return true if the current time is after the calendar day (on or after midnight)
* after the matching trip start day, false otherwise.
*/
public boolean shouldUnsnoozeTrip() {
ZoneId otpZoneId = DateTimeUtils.getOtpZoneId();
var midnightAfterLastChecked = ZonedDateTime
.ofInstant(
Instant.ofEpochMilli(previousJourneyState.lastCheckedEpochMillis).plus(1, ChronoUnit.DAYS),
otpZoneId
)
.withHour(0)
.withMinute(0)
.withSecond(0);

ZonedDateTime now = DateTimeUtils.nowAsZonedDateTime(otpZoneId);
// Include equal or after midnight as true.
return !now.isBefore(midnightAfterLastChecked);
}
}
Loading

0 comments on commit 93ab1f2

Please sign in to comment.