Skip to content

Commit

Permalink
refactor(Fixed merge conflicts):
Browse files Browse the repository at this point in the history
  • Loading branch information
br648 committed Dec 10, 2024
2 parents 926f994 + 13c2676 commit 128fb32
Show file tree
Hide file tree
Showing 22 changed files with 700 additions and 59 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 @@ -47,6 +47,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 @@ -427,4 +430,74 @@ public int tripTimeMinute() {
public boolean isOneTime() {
return !monday && !tuesday && !wednesday && !thursday && !friday && !saturday && !sunday;
}

/**
* @return true if the trip has a (confirmed) companion, false otherwise.
*/
public boolean hasConfirmedCompanion() {
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 @@ -65,8 +65,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 @@ -559,21 +557,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 @@ -618,9 +610,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 @@ -962,10 +952,6 @@ 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.opentripplanner.middleware.otp.response.Step;
import org.opentripplanner.middleware.tripmonitor.jobs.CheckMonitoredTrip;
import org.opentripplanner.middleware.tripmonitor.jobs.NotificationType;
import org.opentripplanner.middleware.triptracker.instruction.ContinueInstruction;
import org.opentripplanner.middleware.triptracker.instruction.DeviatedInstruction;
import org.opentripplanner.middleware.triptracker.instruction.GetOffHereTransitInstruction;
import org.opentripplanner.middleware.triptracker.instruction.GetOffNextStopTransitInstruction;
Expand All @@ -32,6 +33,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.opentripplanner.middleware.tripmonitor.jobs.NotificationType.ARRIVED_NOTIFICATION;
import static org.opentripplanner.middleware.tripmonitor.jobs.NotificationType.MODE_CHANGE_NOTIFICATION;
Expand Down Expand Up @@ -69,7 +71,7 @@ public static String getInstruction(
) {
if (hasRequiredWalkLeg(travelerPosition)) {
if (hasRequiredTripStatus(tripStatus)) {
TripInstruction tripInstruction = alignTravelerToTrip(travelerPosition, isStartOfTrip);
TripInstruction tripInstruction = alignTravelerToTrip(travelerPosition, isStartOfTrip, false);
if (tripInstruction != null) {
return tripInstruction.build();
}
Expand Down Expand Up @@ -174,7 +176,7 @@ private static TripInstruction getBackOnTrack(
TravelerPosition travelerPosition,
boolean isStartOfTrip
) {
TripInstruction instruction = alignTravelerToTrip(travelerPosition, isStartOfTrip);
TripInstruction instruction = alignTravelerToTrip(travelerPosition, isStartOfTrip, true);
if (instruction != null && instruction.hasInstruction()) {
return instruction;
}
Expand Down Expand Up @@ -219,7 +221,8 @@ private static String getBusStopName(Leg busLeg) {
@Nullable
public static TripInstruction alignTravelerToTrip(
TravelerPosition travelerPosition,
boolean isStartOfTrip
boolean isStartOfTrip,
boolean travelerHasDeviated
) {
Locale locale = travelerPosition.locale;

Expand All @@ -232,16 +235,72 @@ public static TripInstruction alignTravelerToTrip(
}

Step nextStep = snapToWaypoint(travelerPosition, travelerPosition.expectedLeg.steps);
TripInstruction tripInstruction = null;
if (nextStep != null && (!isPositionPastStep(travelerPosition, nextStep) || isStartOfTrip)) {
return new OnTrackInstruction(
tripInstruction = new OnTrackInstruction(
getDistance(travelerPosition.currentPosition, new Coordinates(nextStep)),
nextStep,
locale
);
}
return (travelerHasDeviated || (tripInstruction != null && tripInstruction.hasInstruction()))
? tripInstruction
: getContinueInstruction(travelerPosition, nextStep, locale);
}

/**
* Traveler is on track, but no immediate instruction is available. Provide a "continue on street" reassurance
* instruction if the traveler is on a walk leg. This will be based on the next or previous step depending on the
* traveler's relative position to both.
*/
private static ContinueInstruction getContinueInstruction(
TravelerPosition travelerPosition,
Step nextStep,
Locale locale
) {
if (
Boolean.TRUE.equals(!travelerPosition.expectedLeg.transitLeg) &&
travelerPosition.expectedLeg.steps != null &&
!travelerPosition.expectedLeg.steps.isEmpty()
) {
Step previousStep = getPreviousStep(travelerPosition.expectedLeg.steps, nextStep);
if (previousStep != null) {
boolean travelerBetweenSteps = isPointBetween(previousStep.toCoordinates(), nextStep.toCoordinates(), travelerPosition.currentPosition);
if (travelerBetweenSteps) {
return new ContinueInstruction(previousStep, locale);
} else if (isWithinStepRange(travelerPosition, previousStep)) {
return new ContinueInstruction(previousStep, locale);
} else if (isWithinStepRange(travelerPosition, nextStep)) {
return new ContinueInstruction(nextStep, locale);
}
}
}
return null;
}

/**
* The traveler is still with the provided step range.
*/
private static boolean isWithinStepRange(TravelerPosition travelerPosition, Step step) {
double distanceFromTravelerToStep = getDistance(travelerPosition.currentPosition, step.toCoordinates());
return distanceFromTravelerToStep < step.distance;
}

/**
* Get the step prior to the next step provided.
*/
private static Step getPreviousStep(List<Step> steps, Step nextStep) {
if (steps.get(0).equals(nextStep)) {
return null;
}
Optional<Step> previousStep = IntStream
.range(0, steps.size())
.filter(i -> steps.get(i).equals(nextStep))
.mapToObj(i -> steps.get(i - 1))
.findFirst();
return previousStep.orElse(null);
}

/**
* Send bus notification if the first leg is a bus leg or approaching a bus leg and within the notify window.
*/
Expand Down
Loading

0 comments on commit 128fb32

Please sign in to comment.