Compare commits
126
Commits
cachingAndPP
...
deploy
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab9b930bcc | ||
|
|
7eed50f17b | ||
|
|
91d9be1c98 | ||
|
|
bfcb1597ba | ||
|
|
85b427f0d5 | ||
|
|
7344ed7f17 | ||
|
|
31ea7ab80e | ||
|
|
ade57e384e | ||
|
|
7862029773 | ||
|
|
bba0b73adf | ||
|
|
04e17e7995 | ||
|
|
aabb036de9 | ||
|
|
2df20aa374 | ||
|
|
2e60ed3153 | ||
|
|
ad7dd4693c | ||
|
|
2b267400c4 | ||
|
|
b817cf216e | ||
|
|
58ccbdc01a | ||
|
|
f277e8b8b0 | ||
|
|
4063160133 | ||
|
|
427267c4bf | ||
|
|
82b9ae15d9 | ||
|
|
29e4096e95 | ||
|
|
1d2c04d95c | ||
|
|
29956d0b92 | ||
|
|
932fc88b2e | ||
|
|
d7cb3c0e8e | ||
|
|
7c347caea9 | ||
|
|
29fb04d6ec | ||
|
|
82014b1d9c | ||
|
|
57e9beb33f | ||
|
|
30de34b47a | ||
|
|
05a8252d65 | ||
|
|
a57115a6d6 | ||
|
|
ce9dbf4a79 | ||
|
|
007680fccf | ||
|
|
cf7d847993 | ||
|
|
dad0077279 | ||
|
|
0bc692d64a | ||
|
|
16bf41beaa | ||
|
|
98cb2536a2 | ||
|
|
776b8857b6 | ||
|
|
b6ce9a73ce | ||
|
|
906050ad89 | ||
|
|
46a6b2fb7a | ||
|
|
e333b3b9ce | ||
|
|
b64eff7ae6 | ||
|
|
f04e5d7c06 | ||
|
|
4fb02a3f69 | ||
|
|
e1f8cf123b | ||
|
|
cc6028bab5 | ||
|
|
80ba4c33b6 | ||
|
|
3d4f6a4d26 | ||
|
|
2c0dfaf77b | ||
|
|
3051bda1e4 | ||
|
|
a2acdd88f8 | ||
|
|
9e41239ef8 | ||
|
|
8d65e35f88 | ||
|
|
8f62d853e4 | ||
|
|
d5c8342729 | ||
|
|
9d5ad0ca6d | ||
|
|
a2aa22a34a | ||
|
|
82ddcb193c | ||
|
|
8b2de7b9c3 | ||
|
|
c165fce833 | ||
|
|
20d948bcdf | ||
|
|
1b549cc5fc | ||
|
|
18e8d10f6b | ||
|
|
e84269390e | ||
|
|
5eb157b435 | ||
|
|
b95355c10f | ||
|
|
f7d7f6bc53 | ||
|
|
a401b9a6c1 | ||
|
|
cc6990a2a1 | ||
|
|
f88f5a03ef | ||
|
|
d5ef781162 | ||
|
|
1c6caa71ce | ||
|
|
b1ac1619d2 | ||
|
|
6f9f7c1ba0 | ||
|
|
f961b3c2b3 | ||
|
|
2d39c0bef8 | ||
|
|
1a8961831f | ||
|
|
82017e3c50 | ||
|
|
f0dd32c22f | ||
|
|
99b5882c82 | ||
|
|
b60e900e24 | ||
|
|
fb41f80061 | ||
|
|
e2a6b5919a | ||
|
|
60d335f16d | ||
|
|
4fe86b6845 | ||
|
|
c43101e5dc | ||
|
|
d882c8e3b3 | ||
|
|
14cb4f4f88 | ||
|
|
e5e6dc9e2a | ||
|
|
8eaea03b47 | ||
|
|
ff4d352e08 | ||
|
|
657acbc736 | ||
|
|
6393a4a650 | ||
|
|
cb397e7e63 | ||
|
|
69347f8f56 | ||
|
|
e68e163214 | ||
|
|
5e16591913 | ||
|
|
6aaff14c0d | ||
|
|
1b39185454 | ||
|
|
43ab63f77d | ||
|
|
d72a12d089 | ||
|
|
39e385cac3 | ||
|
|
e41fff0840 | ||
|
|
256145f65b | ||
|
|
c636d04fea | ||
|
|
5490958d6e | ||
|
|
06b35c13b6 | ||
|
|
48063d442c | ||
|
|
29b6ac052f | ||
|
|
c3f291a08b | ||
|
|
30fe944387 | ||
|
|
43cf5239fc | ||
|
|
a8f95b680a | ||
|
|
f051efa9eb | ||
|
|
7bbbf903de | ||
|
|
a691e911a2 | ||
|
|
0564733c39 | ||
|
|
9aed0a2703 | ||
|
|
23e5affa71 | ||
|
|
00cbff062e | ||
|
|
75af061871 |
Vendored
+15
-3
@@ -2,6 +2,13 @@
|
||||
|
||||
// this groovy script is executed by jenkins
|
||||
node('built-in') {
|
||||
def DEPLOYMENT_LOCKED = false // Set to false to re-enable deployments
|
||||
def RESET_DB = false // change to reset DB on redeploy
|
||||
|
||||
if (DEPLOYMENT_LOCKED) {
|
||||
echo "⚠️ Deployment is currently locked for testing. Skipping pipeline."
|
||||
return
|
||||
}
|
||||
|
||||
// checkout code from scm
|
||||
stage('Checkout') {
|
||||
@@ -26,9 +33,14 @@ node('built-in') {
|
||||
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
|
||||
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
||||
echo "Resetting database..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
||||
// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
|
||||
// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
||||
if (RESET_DB) {
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
||||
} else {
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down"'
|
||||
|
||||
}
|
||||
echo "Load docker images on server ..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
||||
echo "Restarting docker containers on server ..."
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ services:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
restart: always
|
||||
restart: unless-stopped
|
||||
|
||||
# nominatim:
|
||||
# image: mediagis/nominatim:5.2
|
||||
|
||||
+804
-81
File diff suppressed because it is too large
Load Diff
@@ -149,6 +149,14 @@
|
||||
<artifactId>h3</artifactId>
|
||||
<version>4.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package SuMoC.backend.carrousel.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sumoc.alternative-carrousel")
|
||||
public class CarrouselProperties {
|
||||
/**
|
||||
* Maximum number of alternative suggestions to show in the carrousel.
|
||||
*/
|
||||
private int maxCarrouselItems = 5;
|
||||
|
||||
/**
|
||||
* Time window in days to consider recent suggestions for a user.
|
||||
*/
|
||||
private int recentSuggestionWindowDays = 7;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package SuMoC.backend.carrousel.controller;
|
||||
|
||||
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
|
||||
import SuMoC.backend.carrousel.service.CarrouselService;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Controller for providing a carrousel of alternative routes for displaying on the app startpage.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/routing/alternative/carrousel")
|
||||
@RequiredArgsConstructor
|
||||
public class RoutingAlternativeCarrouselController {
|
||||
|
||||
private final CarrouselService carrouselService;
|
||||
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@GetMapping("/request")
|
||||
@Schema(description = "Provides a carrousel of alternative routes for displaying on the app startpage.")
|
||||
public ResponseEntity<AlternativeCarrouselDTO> getAlternativeCarrousel() {
|
||||
return ResponseEntity.ok(carrouselService.getCarrouselForUser(currentUserService.get().getId()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package SuMoC.backend.carrousel.dto;
|
||||
|
||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "Context for the alternative carrousel for a ad-hoc alternative suggestion.")
|
||||
public class AdHocAlternativeContext extends RouteAlternativeContext {
|
||||
|
||||
@Schema(description = "The trip id associated with this alternative route suggestion.")
|
||||
private Long tripId;
|
||||
|
||||
public AdHocAlternativeContext(RouteDTO alternative, Long tripId) {
|
||||
super(alternative, CarrouselCandidateType.ADHOC_ALTERNATIVE);
|
||||
this.tripId = tripId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package SuMoC.backend.carrousel.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class AlternativeCarrouselDTO {
|
||||
|
||||
private List<RouteAlternativeContext> alternatives;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package SuMoC.backend.carrousel.dto;
|
||||
|
||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class RegularTripAlternativeContext extends RouteAlternativeContext {
|
||||
|
||||
private final MinimalDetectedRegularTripDTO detectedRegularTrip;
|
||||
|
||||
public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip) {
|
||||
super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE);
|
||||
this.detectedRegularTrip = detectedRegularTrip;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package SuMoC.backend.carrousel.dto;
|
||||
|
||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "Wrapper for alternative routes in the carousel.")
|
||||
@NoArgsConstructor
|
||||
public abstract class RouteAlternativeContext {
|
||||
|
||||
protected CarrouselCandidateType carrouselCandidateType;
|
||||
|
||||
protected RouteDTO alternative;
|
||||
|
||||
protected RouteAlternativeContext(RouteDTO alternative, CarrouselCandidateType carrouselCandidateType) {
|
||||
this.carrouselCandidateType = carrouselCandidateType;
|
||||
this.alternative = alternative;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package SuMoC.backend.carrousel.enums;
|
||||
|
||||
public enum CarrouselCandidateType {
|
||||
ADHOC_ALTERNATIVE,
|
||||
REGULAR_TRIP_ALTERNATIVE,
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package SuMoC.backend.carrousel.models;
|
||||
|
||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Entity representing a candidate for the alternatives carrousel. We use this to keep track of alternatives we have
|
||||
* suggested the user via notifications earlier, so that wen can also show them in the carrousel.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "carrousel_candidates")
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class CarrouselCandidate {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false)
|
||||
private CarrouselCandidateType candidateType;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Long userId;
|
||||
|
||||
private Long adHocTripId;
|
||||
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private MinimalDetectedRegularTripDTO detectedRegularTrip;
|
||||
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private RouteDTO suggestedAlternative;
|
||||
|
||||
private Instant suggestedAt;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.carrousel.repository;
|
||||
|
||||
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public interface CarrouselCandidateRepository extends JpaRepository<CarrouselCandidate, Long> {
|
||||
|
||||
@Query("""
|
||||
SELECT c
|
||||
FROM CarrouselCandidate c
|
||||
WHERE c.userId = :userId
|
||||
AND c.suggestedAt >= :cutOff
|
||||
ORDER BY c.suggestedAt DESC
|
||||
""")
|
||||
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
|
||||
|
||||
void deleteAllByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package SuMoC.backend.carrousel.service;
|
||||
|
||||
import SuMoC.backend.carrousel.config.CarrouselProperties;
|
||||
import SuMoC.backend.carrousel.dto.AdHocAlternativeContext;
|
||||
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
|
||||
import SuMoC.backend.carrousel.dto.RegularTripAlternativeContext;
|
||||
import SuMoC.backend.carrousel.dto.RouteAlternativeContext;
|
||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
||||
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CarrouselService {
|
||||
|
||||
private final CarrouselCandidateRepository carrouselCandidateRepository;
|
||||
|
||||
private final CarrouselProperties carrouselProperties;
|
||||
|
||||
public void addAdHocTripCandidates(Trip trip, List<RouteDTO> suggestedAlternatives) {
|
||||
for (var alternative : suggestedAlternatives) {
|
||||
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
||||
.userId(trip.getUser().getId())
|
||||
.adHocTripId(trip.getId())
|
||||
.suggestedAlternative(alternative)
|
||||
.suggestedAt(Instant.now())
|
||||
.candidateType(CarrouselCandidateType.ADHOC_ALTERNATIVE)
|
||||
.build();
|
||||
|
||||
carrouselCandidateRepository.save(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
public List<CarrouselCandidate> getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
|
||||
List<CarrouselCandidate> candidates = new ArrayList<>();
|
||||
|
||||
for (var alternative : suggestedAlternatives) {
|
||||
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
||||
.userId(userId)
|
||||
.detectedRegularTrip(MinimalDetectedRegularTripDTO.fromDetectedRegularTripDTO(detectedRegularTrip))
|
||||
.suggestedAlternative(alternative)
|
||||
.suggestedAt(Instant.now())
|
||||
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
|
||||
.build();
|
||||
candidates.add(candidate);
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
|
||||
var candidates = carrouselCandidateRepository.findByUserIdDesc(userId, Instant.now().minus(Duration.ofDays(carrouselProperties.getRecentSuggestionWindowDays())));
|
||||
|
||||
if (candidates.isEmpty()) {
|
||||
return new AlternativeCarrouselDTO(List.of());
|
||||
}
|
||||
|
||||
var alternativeEntries = candidates.stream()
|
||||
.limit(carrouselProperties.getMaxCarrouselItems())
|
||||
.map(this::mapToCarrouselAlternativeEntry)
|
||||
.toList();
|
||||
|
||||
return new AlternativeCarrouselDTO(alternativeEntries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a CarrouselCandidate to a RouteAlternativeContext, which is the format expected by the frontend carousel.
|
||||
*
|
||||
* @param candidate
|
||||
* @return
|
||||
*/
|
||||
private RouteAlternativeContext mapToCarrouselAlternativeEntry(CarrouselCandidate candidate) {
|
||||
switch (candidate.getCandidateType()) {
|
||||
case ADHOC_ALTERNATIVE -> {
|
||||
return fromAdHocCandidate(candidate);
|
||||
}
|
||||
case REGULAR_TRIP_ALTERNATIVE -> {
|
||||
return fromRegularTripCandidate(candidate);
|
||||
}
|
||||
default -> throw new IllegalStateException("Unimplemented candidate type: " + candidate.getCandidateType());
|
||||
}
|
||||
}
|
||||
|
||||
private RouteAlternativeContext fromAdHocCandidate(CarrouselCandidate candidate) {
|
||||
return new AdHocAlternativeContext(candidate.getSuggestedAlternative(), candidate.getAdHocTripId());
|
||||
}
|
||||
|
||||
private RouteAlternativeContext fromRegularTripCandidate(CarrouselCandidate candidate) {
|
||||
var minRegularTrip = candidate.getDetectedRegularTrip();
|
||||
|
||||
return new RegularTripAlternativeContext(
|
||||
candidate.getSuggestedAlternative(),
|
||||
minRegularTrip
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public class CartaClient {
|
||||
origin,
|
||||
destination,
|
||||
mode.toLowerCase(), // possible values: walking, driving, cycling
|
||||
arrivalTime.getEpochSecond(),
|
||||
arrivalTime != null ? arrivalTime.getEpochSecond() : null,
|
||||
departureTime != null ? departureTime.getEpochSecond() : null,
|
||||
alternatives,
|
||||
walkingSpeed,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
public interface DirectionsRequest {
|
||||
|
||||
Double getOriginLat();
|
||||
|
||||
void setOriginLat(Double originLat);
|
||||
|
||||
Double getOriginLon();
|
||||
|
||||
void setOriginLon(Double originLon);
|
||||
|
||||
Double getDestinationLat();
|
||||
|
||||
void setDestinationLat(Double destinationLat);
|
||||
|
||||
Double getDestinationLon();
|
||||
|
||||
void setDestinationLon(Double destinationLon);
|
||||
|
||||
java.time.Instant getArrivalTime();
|
||||
|
||||
void setArrivalTime(java.time.Instant arrivalTime);
|
||||
|
||||
java.time.Instant getDepartureTime();
|
||||
|
||||
void setDepartureTime(java.time.Instant departureTime);
|
||||
|
||||
SuMoC.backend.routing.dtos.RoutingPreferencesDTO getRoutingPreferencesDTO();
|
||||
|
||||
void setRoutingPreferencesDTO(SuMoC.backend.routing.dtos.RoutingPreferencesDTO routingPreferencesDTO);
|
||||
}
|
||||
+228
-206
@@ -1,15 +1,12 @@
|
||||
package SuMoC.backend.routing.services;
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
import SuMoC.backend.carta.CartaClient;
|
||||
import SuMoC.backend.geocoding.AddressDTO;
|
||||
import SuMoC.backend.geocoding.GeoCodingService;
|
||||
import SuMoC.backend.routing.config.AdHocRoutingProperties;
|
||||
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.dtos.StepDTO;
|
||||
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
|
||||
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
|
||||
import SuMoC.backend.routing.services.CartaTransitRouteProcessor;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -17,48 +14,210 @@ import reactor.core.publisher.Mono;
|
||||
import sumoc.backend.carta.client.model.Direction;
|
||||
import sumoc.backend.carta.client.model.Route;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static SuMoC.backend.trip.Modality.BICYCLE;
|
||||
import static SuMoC.backend.trip.Modality.CAR;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RoutingService {
|
||||
|
||||
private final GeoCodingService geoCodingService;
|
||||
public class DirectionsService {
|
||||
|
||||
private final CartaClient cartaClient;
|
||||
|
||||
private final AlternativeFilterService alternativeFilterService;
|
||||
private final GeoCodingService geoCodingService;
|
||||
|
||||
private final OnCallRoutingProperties onCallRoutingProperties;
|
||||
|
||||
private final AdHocRoutingProperties adHocRoutingProperties;
|
||||
public List<RouteDTO> getPossibleAlternativeRoutes(DirectionsRequest requestDTO) {
|
||||
return getPossibleRoutes(requestDTO, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes an individual call to the CARTA API and returns a direction future.
|
||||
* Returns possible routes for the request - no sanity filtering regarding travel times etc. is applied.
|
||||
* TODO this does not handle the case where origin/destination is provided as address only -> geocoding call to carta needed -> do in directions controller
|
||||
*/
|
||||
private CompletableFuture<Direction> getCartaFuture(
|
||||
RoutingAlternativeRequestDTO requestDTO,
|
||||
String mode,
|
||||
String types,
|
||||
int alternatives
|
||||
) {
|
||||
return cartaClient.asyncGetRoute(
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
|
||||
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
|
||||
mode,
|
||||
requestDTO.getArrivalTime(),
|
||||
null,
|
||||
alternatives, // alternatives
|
||||
null, // walkingSpeed
|
||||
null, // transferTime TODO what is default? adapt?
|
||||
types,
|
||||
null, // range
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
|
||||
public List<RouteDTO> getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
|
||||
ArrayList<RouteDTO> suggestedRoutes = new ArrayList<>();
|
||||
|
||||
// TODO derive origin/destination either from address or coordinates
|
||||
|
||||
// Fetch origin and destination addresses concurrently
|
||||
var addressesMono = Mono.zip(
|
||||
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
|
||||
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
|
||||
);
|
||||
var addressesTuple = addressesMono.block();
|
||||
AddressDTO originAddress = addressesTuple.getT1();
|
||||
AddressDTO destinationAddress = addressesTuple.getT2();
|
||||
|
||||
// Setting up car data for baseline
|
||||
Route carRoute;
|
||||
try {
|
||||
carRoute = directionMap.get("car").getRoutes().getFirst();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarRouteFoundException("No car route to compare to was found.");
|
||||
}
|
||||
double carCarbondDioxide;
|
||||
try {
|
||||
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
|
||||
}
|
||||
double carDuration = carRoute.getDuration();
|
||||
|
||||
// Creating RouteDTOs for all available modes
|
||||
if (includeCarRoute) {
|
||||
Direction carDirection = directionMap.get("car");
|
||||
if (carDirection.getRoutes() != null && !carDirection.getRoutes().isEmpty()) {
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
carRoute,
|
||||
List.of(new StepDTO(CAR, carRoute.getDistance())),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
null,
|
||||
null,
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("bike")) {
|
||||
Direction bikeDirection = directionMap.get("bike");
|
||||
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
|
||||
Route bikeRoute = bikeDirection.getRoutes().getFirst();
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
bikeRoute,
|
||||
List.of(new StepDTO(BICYCLE, bikeRoute.getDistance())),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
null,
|
||||
null,
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("walk")) {
|
||||
Direction walkDirection = directionMap.get("walk");
|
||||
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
|
||||
Route walkRoute = walkDirection.getRoutes().getFirst();
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
walkRoute,
|
||||
List.of(new StepDTO(Modality.WALKING, walkRoute.getDistance())),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
null,
|
||||
null,
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("transit")) {
|
||||
Direction transitDirection = directionMap.get("transit");
|
||||
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
|
||||
for (Route route : transitDirection.getRoutes()) {
|
||||
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
route,
|
||||
routeProcessor.getSteps(),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
routeProcessor.getFirstStopName(),
|
||||
routeProcessor.getLastStopName(),
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
true
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return suggestedRoutes;
|
||||
}
|
||||
|
||||
private RouteDTO createRouteDTO(
|
||||
DirectionsRequest requestDTO,
|
||||
Route route,
|
||||
List<StepDTO> steps,
|
||||
AddressDTO originAddress,
|
||||
AddressDTO destinationAddress,
|
||||
String firstStopName,
|
||||
String lastStopName,
|
||||
double carVariantco2Emission,
|
||||
double carVariantTimeSeconds,
|
||||
boolean isTransit
|
||||
) {
|
||||
|
||||
Instant arrivalTime;
|
||||
Instant departureTime;
|
||||
// Baseline is comparing with car version, except for alternative route requests
|
||||
double timeDifferenceSeconds = route.getDuration() - carVariantTimeSeconds;
|
||||
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
|
||||
// Case 1: both arrival and departure time provided -> must be alternative route request
|
||||
if (isTransit) { // for transit routes, we need to look up the exact arrival time at the last stop
|
||||
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
|
||||
} else {
|
||||
arrivalTime = requestDTO.getArrivalTime();
|
||||
}
|
||||
departureTime = arrivalTime.minusSeconds(route.getDuration());
|
||||
timeDifferenceSeconds = route.getDuration() - (requestDTO.getArrivalTime().getEpochSecond() - requestDTO.getDepartureTime().getEpochSecond());
|
||||
} else if (requestDTO.getArrivalTime() != null) {
|
||||
// Case 2: only arrival time provided
|
||||
if (isTransit) {
|
||||
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
|
||||
} else {
|
||||
arrivalTime = requestDTO.getArrivalTime();
|
||||
}
|
||||
departureTime = arrivalTime.minusSeconds(route.getDuration());
|
||||
} else {
|
||||
// Case 3: only departure time provided
|
||||
if (isTransit) {
|
||||
departureTime = cartaTimeToInstant(route.getSteps().getFirst().getStartTime(), requestDTO.getDepartureTime());
|
||||
} else {
|
||||
departureTime = requestDTO.getDepartureTime();
|
||||
}
|
||||
arrivalTime = departureTime.plusSeconds(route.getDuration());
|
||||
}
|
||||
|
||||
double co2savings = carVariantco2Emission - route.getEmission().getCarbonDioxide();
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
firstStopName,
|
||||
route.getSourceCoordinate().getLatitude(),
|
||||
route.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
lastStopName,
|
||||
route.getTargetCoordinate().getLatitude(),
|
||||
route.getTargetCoordinate().getLongitude(),
|
||||
departureTime,
|
||||
arrivalTime,
|
||||
steps,
|
||||
co2savings,
|
||||
timeDifferenceSeconds,
|
||||
route.getEmission().getCarbonDioxide()
|
||||
);
|
||||
return routeDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +228,7 @@ public class RoutingService {
|
||||
* - bike (optional)
|
||||
* - transit (optional)
|
||||
*/
|
||||
private HashMap<String, Direction> getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) {
|
||||
private HashMap<String, Direction> getPossibleDirections(DirectionsRequest requestDTO) {
|
||||
Map<String, CompletableFuture<Direction>> futuresByMode = new HashMap<>();
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
@@ -113,188 +272,51 @@ public class RoutingService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time.
|
||||
* This is the public method for alternatives explicitly asked for by the client.
|
||||
* Converts a Carta time (seconds since midnight of current day) to an Instant.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
|
||||
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
|
||||
|
||||
return routes;
|
||||
private Instant cartaTimeToInstant(Integer secondsSinceMidnight, Instant instantOfReferenceDay) {
|
||||
LocalDate date = instantOfReferenceDay.atZone(ZoneId.systemDefault()).toLocalDate();
|
||||
LocalDateTime startOfDay = date.atStartOfDay();
|
||||
LocalDateTime resultDateTime = startOfDay.plusSeconds(secondsSinceMidnight);
|
||||
return resultDateTime.atZone(ZoneId.systemDefault()).toInstant();
|
||||
}
|
||||
|
||||
/**
|
||||
* Public alternative retrieval method which is used to check for alternatives we suggest to user via notification
|
||||
* right after user finished the trip.
|
||||
* Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives
|
||||
* and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres.
|
||||
* Makes an individual call to the CARTA API and returns a direction future.
|
||||
*/
|
||||
public List<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
|
||||
|
||||
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
|
||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||
private CompletableFuture<Direction> getCartaFuture(
|
||||
DirectionsRequest requestDTO,
|
||||
String mode,
|
||||
String types,
|
||||
int alternatives
|
||||
) {
|
||||
Instant departureTime = null;
|
||||
Instant arrivalTime = null;
|
||||
if (requestDTO.getArrivalTime() != null) {
|
||||
arrivalTime = requestDTO.getArrivalTime();
|
||||
} else if (requestDTO.getDepartureTime() != null) {
|
||||
departureTime = requestDTO.getDepartureTime();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
|
||||
}
|
||||
|
||||
return routes;
|
||||
}
|
||||
// TODO derive origin either from address or coordinates
|
||||
|
||||
public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
// TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives
|
||||
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
|
||||
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
|
||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||
}
|
||||
|
||||
RouteDTO bestRoute = null;
|
||||
// if users wants physical activity, we pick the fastest physical activity route, if any
|
||||
if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
||||
bestRoute = routes.stream()
|
||||
.filter(RouteDTO::isPhysicalActivity)
|
||||
.min((r1, r2) -> Long.compare(
|
||||
r1.getDurationSeconds(),
|
||||
r2.getDurationSeconds()
|
||||
)).orElse(null);
|
||||
if (bestRoute != null) {
|
||||
return bestRoute;
|
||||
}
|
||||
}
|
||||
// else we pick the fastest route overall
|
||||
bestRoute = routes.stream()
|
||||
.min((r1, r2) -> Long.compare(
|
||||
r1.getDurationSeconds(),
|
||||
r2.getDurationSeconds()
|
||||
)).orElse(null);
|
||||
return bestRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied.
|
||||
*/
|
||||
private List<RouteDTO> getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
|
||||
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
|
||||
|
||||
// Fetch origin and destination addresses concurrently
|
||||
var addressesMono = Mono.zip(
|
||||
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
|
||||
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
|
||||
return cartaClient.asyncGetRoute(
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
|
||||
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
|
||||
mode,
|
||||
arrivalTime,
|
||||
departureTime,
|
||||
alternatives, // alternatives
|
||||
null, // walkingSpeed
|
||||
null, // transferTime TODO what is default? adapt?
|
||||
types,
|
||||
null, // range
|
||||
// TODO only if coordinates are provided directly
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
|
||||
);
|
||||
var addressesTuple = addressesMono.block();
|
||||
AddressDTO originAddress = addressesTuple.getT1();
|
||||
AddressDTO destinationAddress = addressesTuple.getT2();
|
||||
|
||||
// Setting up car data for baseline
|
||||
Route carRoute;
|
||||
try {
|
||||
carRoute = directionMap.get("car").getRoutes().getFirst();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarRouteFoundException("No car route to compare to was found.");
|
||||
}
|
||||
double carCarbondDioxide;
|
||||
try {
|
||||
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("bike")) {
|
||||
Direction bikeDirection = directionMap.get("bike");
|
||||
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
|
||||
Route bikeRoute = bikeDirection.getRoutes().getFirst();
|
||||
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||
steps.add(new StepDTO(
|
||||
Modality.BICYCLE,
|
||||
null,
|
||||
bikeRoute.getDistance()
|
||||
)
|
||||
);
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
null,
|
||||
bikeRoute.getSourceCoordinate().getLatitude(),
|
||||
bikeRoute.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
null,
|
||||
bikeRoute.getTargetCoordinate().getLatitude(),
|
||||
bikeRoute.getTargetCoordinate().getLongitude(),
|
||||
requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()),
|
||||
requestDTO.getArrivalTime(),
|
||||
steps,
|
||||
carCarbondDioxide,
|
||||
bikeRoute.getDuration() - carRoute.getDuration(),
|
||||
0.0
|
||||
);
|
||||
suggestedAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("walk")) {
|
||||
Direction walkDirection = directionMap.get("walk");
|
||||
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
|
||||
Route walkRoute = walkDirection.getRoutes().getFirst();
|
||||
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||
steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
walkRoute.getDistance()
|
||||
));
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
null,
|
||||
walkRoute.getSourceCoordinate().getLatitude(),
|
||||
walkRoute.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
null,
|
||||
walkRoute.getTargetCoordinate().getLatitude(),
|
||||
walkRoute.getTargetCoordinate().getLongitude(),
|
||||
requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
|
||||
requestDTO.getArrivalTime(),
|
||||
steps,
|
||||
carCarbondDioxide,
|
||||
walkRoute.getDuration() - carRoute.getDuration(),
|
||||
0.0
|
||||
);
|
||||
suggestedAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("transit")) {
|
||||
Direction transitDirection = directionMap.get("transit");
|
||||
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
|
||||
for (Route route : transitDirection.getRoutes()) {
|
||||
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
routeProcessor.getFirstStopName(),
|
||||
route.getSourceCoordinate().getLatitude(),
|
||||
route.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
routeProcessor.getLastStopName(),
|
||||
route.getTargetCoordinate().getLatitude(),
|
||||
route.getTargetCoordinate().getLongitude(),
|
||||
requestDTO.getArrivalTime().minusSeconds(route.getDuration()),
|
||||
requestDTO.getArrivalTime(),
|
||||
routeProcessor.getSteps(),
|
||||
carCarbondDioxide - route.getEmission().getCarbonDioxide(),
|
||||
route.getDuration() - carRoute.getDuration(),
|
||||
route.getEmission().getCarbonDioxide()
|
||||
);
|
||||
suggestedAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return suggestedAlternatives;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@ package SuMoC.backend.common.converter;
|
||||
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
/**
|
||||
* This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation.
|
||||
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 1 (Sunday) to 7 (Saturday).
|
||||
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 0 (Sunday) to 6 (Saturday).
|
||||
*/
|
||||
@Converter(autoApply = true)
|
||||
public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer> {
|
||||
@@ -16,8 +17,8 @@ public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert Java DayOfWeek (1=Monday) to SQL format (1=Sunday)
|
||||
return (attribute.getValue() % 7) + 1;
|
||||
// Convert Java DayOfWeek (1=Monday, ..., 7=Sunday) to SQL DOW (0=Sunday, ..., 6=Saturday)
|
||||
return attribute.getValue() % 7;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -25,10 +26,7 @@ public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer
|
||||
if (dbData == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert SQL format (1=Sunday) back to Java DayOfWeek (1=Monday)
|
||||
// Example: SQL 1 (Sunday) -> Java 7
|
||||
// SQL 7 (Saturday) -> Java 6
|
||||
// SQL 2 (Monday) -> Java 1
|
||||
return DayOfWeek.of(((dbData + 5) % 7) + 1);
|
||||
// Convert SQL DOW (0=Sunday, ..., 6=Saturday) to Java DayOfWeek (1=Monday, ..., 7=Sunday)
|
||||
return DayOfWeek.of(dbData == 0 ? 7 : dbData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package SuMoC.backend.config;
|
||||
|
||||
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
@RequiredArgsConstructor
|
||||
public class AsyncConfiguration {
|
||||
|
||||
private final RegularTripSuggestionProperties regularTripSuggestionProperties;
|
||||
|
||||
/**
|
||||
* Custom thread pool executor for parallel processing of regular trip suggestions.
|
||||
* Configured with parallelism setting from application properties.
|
||||
*/
|
||||
@Bean(name = "regularTripSuggestionExecutor")
|
||||
public Executor regularTripSuggestionExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
int parallelism = regularTripSuggestionProperties.getParallelism();
|
||||
|
||||
executor.setCorePoolSize(parallelism);
|
||||
executor.setMaxPoolSize(parallelism);
|
||||
executor.setQueueCapacity(500); // Queue capacity for pending tasks
|
||||
executor.setThreadNamePrefix("regular-trip-");
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.setAwaitTerminationSeconds(60);
|
||||
executor.initialize();
|
||||
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import SuMoC.backend.scheduling.ScheduledTasks;
|
||||
import SuMoC.backend.suggestion.services.RegularTripSuggestionService;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||
import SuMoC.backend.user.dtos.FriendshipDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import SuMoC.backend.user.mapper.UserMapper;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
@@ -28,8 +31,9 @@ import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -158,6 +162,37 @@ public class DevController {
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase-friendship-request-notification/{fcm_token}")
|
||||
@Operation(description = "Immediately sends a test notification of type FRIENDSHIP_REQUEST_RECEIVED to the provided FCM token.")
|
||||
public ResponseEntity<String> SendTestRFriendshipRequestReceivedNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
Notification notification = new Notification();
|
||||
notification.setType(NotificationType.FRIENDSHIP_REQUEST_RECEIVED);
|
||||
FriendshipDTO friendshipDTO = new FriendshipDTO(
|
||||
1L,
|
||||
2L,
|
||||
new MinimalUserDTO(
|
||||
2L,
|
||||
"request_public_name"
|
||||
),
|
||||
FriendShipStatus.PENDING,
|
||||
Instant.now()
|
||||
);
|
||||
notification.setData(objectMapper.writeValueAsString(friendshipDTO));
|
||||
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||
String message = firebaseMessaging.sendAsync(
|
||||
mockRegularTripMessage
|
||||
).get();
|
||||
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-notification-from-detected-regular-trip")
|
||||
@Operation(description = "Testing endpoint that mocks the detection of regular trips and then tests the alternative calculation and notification scheduling.")
|
||||
public ResponseEntity<String> testNotificationFromDetectedRegularTrip() {
|
||||
@@ -204,7 +239,7 @@ public class DevController {
|
||||
.data(objectMapper.writeValueAsString(mockDTO))
|
||||
.user(user)
|
||||
.earliestTimeOfDayToSend(LocalTime.now())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.createdAt(Instant.now())
|
||||
.status(NotificationStatus.PENDING)
|
||||
.build();
|
||||
|
||||
@@ -226,7 +261,7 @@ public class DevController {
|
||||
.data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()))
|
||||
.user(user)
|
||||
.earliestTimeOfDayToSend(LocalTime.now())
|
||||
.createdAt(LocalDateTime.now().minusDays(60))
|
||||
.createdAt(Instant.now().minus(Duration.ofDays(60)))
|
||||
.status(NotificationStatus.SENT)
|
||||
.build();
|
||||
|
||||
@@ -251,4 +286,9 @@ public class DevController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/test-detection-and-notification-regular-trips")
|
||||
public void testDetectionAndNotificationOfRegularTrips() {
|
||||
regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package SuMoC.backend.firebase;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import com.google.firebase.messaging.ApnsConfig;
|
||||
import com.google.firebase.messaging.Aps;
|
||||
import com.google.firebase.messaging.ApsAlert;
|
||||
import com.google.firebase.messaging.Message;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -11,6 +14,21 @@ public class FirebaseMessageBuilder {
|
||||
var builder = Message.builder().setToken(token);
|
||||
builder.putData("type", notification.getType().toString());
|
||||
builder.putData("data", notification.getData());
|
||||
|
||||
//Setup, so iOS can receive and intercept Push Notifications
|
||||
builder.setNotification(com.google.firebase.messaging.Notification.builder()
|
||||
.setTitle("Sumoc Update")
|
||||
.setBody("Deine Nachricht ist da!")
|
||||
.build())
|
||||
.setApnsConfig(ApnsConfig.builder()
|
||||
.setAps(Aps.builder()
|
||||
.setMutableContent(true)
|
||||
.setSound("default") // WICHTIG: Ohne Sound oft keine Anzeige
|
||||
.setBadge(1)
|
||||
.build())
|
||||
.build());
|
||||
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
@@ -21,6 +22,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class BadgeService {
|
||||
|
||||
private final CurrentUserService currentUser;
|
||||
|
||||
@@ -16,7 +16,7 @@ public class Badge {
|
||||
private String description;
|
||||
private BadgeCategory category;
|
||||
|
||||
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private BadgeImageEntity image;
|
||||
|
||||
@ElementCollection
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package SuMoC.backend.gamification.challenges;
|
||||
|
||||
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.ArraySchema;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/challenges")
|
||||
class ChallengeController {
|
||||
|
||||
private ChallengeService challengeService;
|
||||
|
||||
@Autowired
|
||||
public ChallengeController(ChallengeService challengeService) {
|
||||
this.challengeService = challengeService;
|
||||
}
|
||||
|
||||
|
||||
// Admin Endpoints
|
||||
@Operation(summary = "Create a new challenge")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "201", description = "Challenge created successfully",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid input data"),
|
||||
})
|
||||
@PostMapping("/createChallenge")
|
||||
public ResponseEntity<ChallengeDTO> createChallenge(@RequestBody @Valid ChallengeDTO challengeDTO) {
|
||||
ChallengeDTO createdChallenge = challengeService.createChallenge(challengeDTO);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(createdChallenge);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Delete a challenge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Challenge deleted successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Challenge not found")
|
||||
})
|
||||
@DeleteMapping("/deleteChallenge/{challengeId}")
|
||||
public ResponseEntity<Void> deleteChallengeById(@PathVariable Long challengeId) {
|
||||
challengeService.deleteChallenge(challengeId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Modify a challenge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Challenge modified successfully",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
|
||||
@ApiResponse(responseCode = "404", description = "Challenge not found"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid input data")
|
||||
})
|
||||
@PutMapping("/modifyChallenge")
|
||||
public ResponseEntity<ChallengeDTO> modifyChallengeById(
|
||||
@RequestBody @Valid ChallengeDTO challengeDTO) {
|
||||
ChallengeDTO modifiedChallenge = challengeService.modifyChallenge(challengeDTO);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(modifiedChallenge);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Get a challenge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Challenge retrieved successfully",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
|
||||
@ApiResponse(responseCode = "404", description = "Challenge not found")
|
||||
})
|
||||
@GetMapping("/getChallenge/{challengeId}")
|
||||
public ResponseEntity<ChallengeDTO> getChallengeById(@PathVariable Long challengeId) {
|
||||
ChallengeDTO challengeDTO = challengeService.getChallengeById(challengeId);
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(356, TimeUnit.DAYS))
|
||||
.body(challengeDTO);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Get all challenges")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Challenges retrieved successfully",
|
||||
content = @Content(mediaType = "application/json",
|
||||
array = @ArraySchema(schema = @Schema(implementation = ChallengeDTO.class))
|
||||
)),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
|
||||
@ApiResponse(responseCode = "404", description = "No challenges found")
|
||||
})
|
||||
@GetMapping("/getAllChallenges")
|
||||
public ResponseEntity<List<ChallengeDTO>> getAllChallenges(){
|
||||
List<ChallengeDTO> challenges = challengeService.getAllChallenges();
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
||||
.body(challenges);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Activate a challenge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Challenge activated successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Challenge not found")
|
||||
})
|
||||
@PutMapping("/activateChallenge/{challengeId}")
|
||||
public ResponseEntity<Void> activateChallengeById(@PathVariable Long challengeId) {
|
||||
challengeService.activateChallenge(challengeId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Deactivate a challenge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Challenge deactivated successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Challenge not found")
|
||||
})
|
||||
@PutMapping("/deactivateChallenge/{challengeId}")
|
||||
public ResponseEntity<Void> deactivateChallengeById(@PathVariable Long challengeId) {
|
||||
challengeService.deactivateChallenge(challengeId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
// User Endpoints
|
||||
@Operation(summary = "Get all available challenges")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Available challenges retrieved successfully",
|
||||
content = @Content(mediaType = "application/json",
|
||||
array = @ArraySchema(schema = @Schema(implementation = ChallengeDTO.class))
|
||||
)),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
|
||||
@ApiResponse(responseCode = "404", description = "No available challenges found")
|
||||
})
|
||||
@GetMapping("/getAvailableChallenges")
|
||||
public ResponseEntity<List<ChallengeDTO>> getAvailableChallenges() {
|
||||
List<ChallengeDTO> challenges = challengeService.getAvailableChallenges();
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS))
|
||||
.body(challenges);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package SuMoC.backend.gamification.challenges;
|
||||
|
||||
|
||||
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
||||
import SuMoC.backend.images.ImageEntity;
|
||||
import jakarta.persistence.DiscriminatorValue;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
@DiscriminatorValue("CHALLENGE")
|
||||
public class ChallengeImageEntity extends ImageEntity {
|
||||
|
||||
@OneToOne
|
||||
@JoinColumn(name = "challenge_id")
|
||||
private Challenge challenge;
|
||||
|
||||
public ChallengeImageEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ChallengeImageEntity(Challenge challenge, byte[] imageData) {
|
||||
super(imageData);
|
||||
}
|
||||
|
||||
public Challenge getChallenge() {
|
||||
return challenge;
|
||||
}
|
||||
|
||||
public void setChallenge(Challenge challenge) {
|
||||
this.challenge = challenge;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package SuMoC.backend.gamification.challenges;
|
||||
|
||||
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
||||
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
|
||||
import SuMoC.backend.images.ImageBase64Util;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Mapper
|
||||
public interface ChallengeMapper {
|
||||
|
||||
static ChallengeDTO toDTO(Challenge challenge) {
|
||||
ChallengeDTO dto = new ChallengeDTO();
|
||||
dto.setId(challenge.getId());
|
||||
dto.setName(challenge.getName());
|
||||
dto.setDescription(challenge.getDescription());
|
||||
dto.setCriteria(challenge.getCriteria());
|
||||
dto.setReward(challenge.getReward());
|
||||
dto.setBase64image(
|
||||
Optional.ofNullable(challenge.getImage())
|
||||
.map(ChallengeImageEntity::getImageData)
|
||||
.map(ImageBase64Util::encode)
|
||||
.orElse(null)
|
||||
);
|
||||
return dto;
|
||||
}
|
||||
|
||||
static Challenge toEntity(ChallengeDTO dto) {
|
||||
Challenge challenge = new Challenge();
|
||||
challenge.setId(dto.getId());
|
||||
challenge.setName(dto.getName());
|
||||
challenge.setDescription(dto.getDescription());
|
||||
challenge.setCriteria(dto.getCriteria());
|
||||
challenge.setReward(dto.getReward());
|
||||
|
||||
if (dto.getBase64image() != null && !dto.getBase64image().isBlank()) {
|
||||
byte[] bytes = ImageBase64Util.decode(dto.getBase64image());
|
||||
ChallengeImageEntity img = new ChallengeImageEntity();
|
||||
img.setImageData(bytes);
|
||||
challenge.setImage(img);
|
||||
}
|
||||
|
||||
return challenge;
|
||||
}
|
||||
|
||||
static void updateEntityFromDTO(Challenge challenge, ChallengeDTO dto) {
|
||||
challenge.setName(dto.getName());
|
||||
challenge.setDescription(dto.getDescription());
|
||||
challenge.setCriteria(dto.getCriteria());
|
||||
challenge.setReward(dto.getReward());
|
||||
|
||||
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
|
||||
byte[] imageData = ImageBase64Util.decode(dto.getBase64image());
|
||||
if (challenge.getImage() == null) {
|
||||
challenge.setImage(new ChallengeImageEntity(challenge, imageData));
|
||||
} else {
|
||||
challenge.getImage().setImageData(imageData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package SuMoC.backend.gamification.challenges;
|
||||
|
||||
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface ChallengeRepository extends JpaRepository<Challenge, Long> {
|
||||
List<Challenge> findAllByActiveIs(Boolean active);
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT c FROM Challenge c
|
||||
JOIN c.criteria crit
|
||||
WHERE KEY(crit) IS NOT NULL
|
||||
AND VALUE(crit) IS NOT NULL
|
||||
""")
|
||||
List<Challenge> findAllWithValidCriteria();
|
||||
|
||||
Optional<Challenge> findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package SuMoC.backend.gamification.challenges;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
||||
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.Math.min;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class ChallengeService {
|
||||
|
||||
private final CurrentUserService currentUser;
|
||||
private final ChallengeRepository challengeRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public ChallengeService(CurrentUserService currentUser, ChallengeRepository challengeRepository, UserRepository userRepository) {
|
||||
this.currentUser = currentUser;
|
||||
this.challengeRepository = challengeRepository;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
|
||||
// Management of Challenges
|
||||
public ChallengeDTO createChallenge(ChallengeDTO challengeDTO) {
|
||||
Challenge challenge = ChallengeMapper.toEntity(challengeDTO);
|
||||
Challenge savedChallenge = challengeRepository.save(challenge);
|
||||
return ChallengeMapper.toDTO(savedChallenge);
|
||||
}
|
||||
|
||||
public ChallengeDTO getChallengeById(Long id) {
|
||||
Challenge challenge = challengeRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
|
||||
return ChallengeMapper.toDTO(challenge);
|
||||
}
|
||||
|
||||
public List<ChallengeDTO> getAllChallenges() {
|
||||
List<Challenge> challenges = challengeRepository.findAll();
|
||||
return challenges.stream()
|
||||
.map(ChallengeMapper::toDTO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public ChallengeDTO modifyChallenge(ChallengeDTO challengeDTO) {
|
||||
Challenge existingChallenge = challengeRepository.findById(challengeDTO.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
|
||||
|
||||
ChallengeMapper.updateEntityFromDTO(existingChallenge, challengeDTO);
|
||||
Challenge updatedChallenge = challengeRepository.save(existingChallenge);
|
||||
return ChallengeMapper.toDTO(updatedChallenge);
|
||||
}
|
||||
|
||||
public void deleteChallenge(Long id) {
|
||||
Challenge challenge = challengeRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
|
||||
challengeRepository.delete(challenge);
|
||||
}
|
||||
|
||||
public void deactivateChallenge(Long id) {
|
||||
Challenge challenge = challengeRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
|
||||
challenge.setActive(false);
|
||||
challengeRepository.save(challenge);
|
||||
}
|
||||
|
||||
public void activateChallenge(Long id) {
|
||||
Challenge challenge = challengeRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
|
||||
challenge.setActive(true);
|
||||
challengeRepository.save(challenge);
|
||||
}
|
||||
|
||||
|
||||
// User Requests
|
||||
public List<ChallengeDTO> getAvailableChallenges() {
|
||||
List<Challenge> challenges = challengeRepository.findAllByActiveIs(true);
|
||||
return challenges.stream()
|
||||
.map(ChallengeMapper::toDTO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
|
||||
public void checkAndAwardChallenges(String field, Long value) {
|
||||
User user = currentUser.get();
|
||||
Long currentStat = user.getStats().getStatValue(Timeframe.WEEKLY, field);
|
||||
Long newStat = currentStat + value;
|
||||
List<Challenge> activeChallenges = challengeRepository.findAllByActiveIs(true);
|
||||
|
||||
for (Challenge challenge : activeChallenges) {
|
||||
Integer target = challenge.getCriteria().get(field);
|
||||
|
||||
if (target != null && currentStat < target && newStat >= target) {
|
||||
|
||||
user.getStats().addToAllStats("XP", challenge.getReward());
|
||||
userRepository.save(user);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Additional Methods
|
||||
|
||||
@Transactional
|
||||
public void setActiveById(Long challengeId, Boolean active) {
|
||||
Challenge challenge = challengeRepository.findById(challengeId)
|
||||
.orElseThrow();
|
||||
challenge.setActive(active);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Scheduled(cron = "0 0 0 ? * MON")
|
||||
public void weeklyChallengeScheduler() {
|
||||
List<Challenge> activeChallenges = challengeRepository.findAllByActiveIs(true);
|
||||
activeChallenges.forEach(challenge -> {
|
||||
setActiveById(challenge.getId(), false);
|
||||
});
|
||||
|
||||
List<Challenge> allChallenges = challengeRepository.findAllWithValidCriteria();
|
||||
int limit = min(allChallenges.size(), 3);
|
||||
|
||||
if (limit == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Collections.shuffle(allChallenges);
|
||||
|
||||
allChallenges.stream()
|
||||
.limit(limit)
|
||||
.forEach(challenge -> setActiveById(challenge.getId(), true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package SuMoC.backend.gamification.challenges.Models;
|
||||
|
||||
import SuMoC.backend.gamification.challenges.ChallengeImageEntity;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Entity
|
||||
public class Challenge {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
|
||||
@OneToOne(mappedBy = "challenge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private ChallengeImageEntity image;
|
||||
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "challenge_criteria", joinColumns = @JoinColumn(name = "challenge_id"))
|
||||
@MapKeyColumn(name = "criteria_name")
|
||||
@Column(name = "criteria_value")
|
||||
private Map<String, Integer> criteria = new HashMap<>();
|
||||
|
||||
private Integer reward;
|
||||
|
||||
private Boolean active;
|
||||
|
||||
|
||||
// Constructors
|
||||
public Challenge(String name, String description) {
|
||||
this(name, description, null, 0);
|
||||
}
|
||||
|
||||
public Challenge(String name, String description, Map<String, Integer> criteria, Integer reward) {
|
||||
this(name, description, criteria, reward, new ChallengeImageEntity(null, null));
|
||||
}
|
||||
|
||||
public Challenge(String name, String description, Map<String, Integer> criteria, Integer reward, ChallengeImageEntity image) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.criteria = criteria;
|
||||
this.reward = reward;
|
||||
this.image = image;
|
||||
this.active = false;
|
||||
}
|
||||
|
||||
public Challenge() {
|
||||
|
||||
}
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public ChallengeImageEntity getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(ChallengeImageEntity image) {
|
||||
this.image = image;
|
||||
if (image != null) {
|
||||
image.setChallenge(this);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Integer> getCriteria() {
|
||||
return criteria;
|
||||
}
|
||||
|
||||
public void setCriteria(Map<String, Integer> criteria) {
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public Integer getReward() {
|
||||
return reward;
|
||||
}
|
||||
|
||||
public void setReward(Integer reward) {
|
||||
this.reward = reward;
|
||||
}
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(Boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package SuMoC.backend.gamification.challenges.Models;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class ChallengeDTO {
|
||||
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String base64image;
|
||||
private Map<String, Integer> criteria;
|
||||
private Integer reward;
|
||||
|
||||
// Constructors
|
||||
|
||||
public ChallengeDTO() {}
|
||||
|
||||
public ChallengeDTO(Long id, String name, String description, String base64image, Map<String, Integer> criteria, Integer reward) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.base64image = base64image;
|
||||
this.criteria = criteria;
|
||||
this.reward = reward;
|
||||
}
|
||||
|
||||
public ChallengeDTO(Long id, String name, String description, Map<String, Integer> criteria, Integer reward) {
|
||||
this(id, name, description, null, criteria, reward);
|
||||
}
|
||||
|
||||
public ChallengeDTO(Long id , String name, String description) {
|
||||
this(id, name, description, null, 0);
|
||||
}
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getBase64image() {
|
||||
return base64image;
|
||||
}
|
||||
|
||||
public void setBase64image(String base64image) {
|
||||
this.base64image = base64image;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getCriteria() {
|
||||
return criteria;
|
||||
}
|
||||
|
||||
public void setCriteria(Map<String, Integer> criteria) {
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public Integer getReward() {
|
||||
return reward;
|
||||
}
|
||||
|
||||
public void setReward(Integer reward) {
|
||||
this.reward = reward;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.FriendshipService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import SuMoC.backend.user.stats.*;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -20,6 +21,7 @@ import java.util.List;
|
||||
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class LeaderboardService {
|
||||
private final FriendshipService friendshipService;
|
||||
private final StatsListRepository statsListRepository;
|
||||
|
||||
@@ -10,8 +10,9 @@ public class ImageEntity {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
|
||||
@Lob
|
||||
//@Column(columnDefinition = "BYTEA")
|
||||
//@Lob
|
||||
@Basic(fetch = FetchType.EAGER)
|
||||
@Column(columnDefinition = "bytea")
|
||||
//@Column(columnDefinition = "BLOB")
|
||||
private byte[] imageData;
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package SuMoC.backend.images;
|
||||
|
||||
public class ImageRequestDTO {
|
||||
|
||||
private String base64ProfilePicture;
|
||||
|
||||
public ImageRequestDTO(String base64ProfilePicture) {
|
||||
this.base64ProfilePicture = base64ProfilePicture;
|
||||
}
|
||||
|
||||
public ImageRequestDTO() {}
|
||||
|
||||
public String getBase64ProfilePicture() {
|
||||
return base64ProfilePicture;
|
||||
}
|
||||
|
||||
public void setBase64ProfilePicture(String base64ProfilePicture) {
|
||||
this.base64ProfilePicture = base64ProfilePicture;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -37,6 +37,14 @@ public class NotificationController {
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@PutMapping("/unregister-device-token")
|
||||
@Operation(description = "Unregisters the device token for push notifications for the authenticated user.")
|
||||
public ResponseEntity<Void> unregisterDeviceToken() {
|
||||
User user = getAuthenticatedUser();
|
||||
notificationTokenService.unregisterDeviceToken(user);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
// Simple record for request body
|
||||
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Notification System Overview
|
||||
|
||||
This document provides an overview of the notification system for client developers integrating with the backend. It
|
||||
explains notification types, expected payloads, and device token registration.
|
||||
|
||||
## Notification Types
|
||||
|
||||
Notifications sent to clients are categorized by `NotificationType`:
|
||||
|
||||
- **TREND**: Informs users about changes in their mobility trends (e.g., reduced car usage). See
|
||||
`TrendNotificationService`.
|
||||
- **ADHOC_ALTERNATIVE**: Suggests a more sustainable alternative after a recent trip upload. See
|
||||
`AdHocSuggestionService`.
|
||||
- **REGULAR_TRIP_ALTERNATIVE**: Suggests an alternative for a detected regular trip (e.g., weekly commute). See
|
||||
`RegularTripSuggestionService`.
|
||||
- **FRIENDSHIP_REQUEST_RECEIVED**: Notifies about a new pending friendship request.
|
||||
|
||||
See `NotificationType.java` for the full enum.
|
||||
|
||||
## Notification Payloads
|
||||
|
||||
Each notification type includes a data payload. The main DTOs in the notification body are:
|
||||
|
||||
- **TREND**: Contains a list of `TrendDetectionDTO` objects, each describing a detected trend for the user. The
|
||||
structure includes fields such as `userId`, `timespan`, `type`, `attribute`, `deltaType`, `changeValue`, and
|
||||
`trendConnotation`. See `TrendDetectionDTO.java` for details.
|
||||
- **ADHOC_ALTERNATIVE**: Contains a list of `RouteDTO` objects representing the best alternative(s) for a recent trip (
|
||||
see `AdHocSuggestionService`).
|
||||
- **REGULAR_TRIP_ALTERNATIVE**: Contains a list of 1 or 2 `RouteDTO` objects for the best alternative(s) to a detected
|
||||
regular trip, depending on user preferences (e.g., if `preferPhysicalActivity` is set, two alternatives may be
|
||||
included). See `RegularTripSuggestionService` and `RegularTripDetectionService` for details.
|
||||
- **FRIENDSHIP_REQUEST_RECEIVED**: Contains a `friendshipDTO` where `friend` is the user who sent the request. See
|
||||
`FriendshipDTO.java`.
|
||||
|
||||
## Device Token Registration
|
||||
|
||||
To receive push notifications, clients must register their device token. Token registration is handled in the
|
||||
`NotificationController`. The backend stores or updates the token for the authenticated user.
|
||||
|
||||
### Unregistering Device Token
|
||||
|
||||
When a user logs out, the client should call the device token unregistration endpoint to remove the device token from
|
||||
the backend. This ensures the user will no longer receive push notifications on that device after logout.
|
||||
|
||||
- **Endpoint:** `PUT /notifications/unregister-device-token`
|
||||
|
||||
---
|
||||
|
||||
## For Backend Developers
|
||||
|
||||
To queue notifications for users, use the `NotificationSchedulerService` as the main entry point. This service provides
|
||||
methods to schedule notifications with the appropriate type and payload. See `NotificationSchedulerService.java` for
|
||||
usage details.
|
||||
|
||||
---
|
||||
For further details, refer to the respective service and DTO classes in the codebase.
|
||||
@@ -1,9 +1,13 @@
|
||||
package SuMoC.backend.notification.config;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sumoc.notification")
|
||||
@@ -12,4 +16,14 @@ public class NotificationProperties {
|
||||
* Maximum number of failed send attempts before giving up on a notification.
|
||||
*/
|
||||
private int maxFailedSendAttempts = 3;
|
||||
|
||||
/**
|
||||
* Maximum number of notifications to send to a user per hour per notification type.
|
||||
*/
|
||||
private Map<NotificationType, Integer> maxNotificationsPerHourPerType = new HashMap<>(Map.of(
|
||||
NotificationType.TREND, 1,
|
||||
NotificationType.ADHOC_ALTERNATIVE, 1,
|
||||
NotificationType.REGULAR_TRIP_ALTERNATIVE, 1,
|
||||
NotificationType.FRIENDSHIP_REQUEST_RECEIVED, 3
|
||||
));
|
||||
}
|
||||
|
||||
@@ -16,5 +16,9 @@ public enum NotificationType {
|
||||
* An alternative suggestion that refers to a detected regular trip.
|
||||
* E.g. user drives by car every monday at 8 am and there is a sustainable alternative.
|
||||
*/
|
||||
REGULAR_TRIP_ALTERNATIVE
|
||||
REGULAR_TRIP_ALTERNATIVE,
|
||||
/**
|
||||
* A notification informing the user about a new pending friendship request.
|
||||
*/
|
||||
FRIENDSHIP_REQUEST_RECEIVED,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
public interface NotifieableWithTime {
|
||||
Long getUserId();
|
||||
|
||||
LocalTime getEarliestTimeOfDayToSend();
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import SuMoC.backend.user.models.User;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Entity
|
||||
@@ -54,8 +54,10 @@ public class Notification {
|
||||
private String lastFailureReason;
|
||||
|
||||
@Column(nullable = false)
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(nullable = true)
|
||||
private Instant sentAt = null;
|
||||
|
||||
public void incrementFailedSendAttempts() {
|
||||
this.failedSendAttempts++;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package SuMoC.backend.notification.repositories;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -20,11 +21,22 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
|
||||
""")
|
||||
List<Notification> findPendingNotificationsToSend(LocalTime currentTime);
|
||||
|
||||
@Query("""
|
||||
SELECT n
|
||||
FROM Notification n
|
||||
WHERE n.user.id = :userId
|
||||
AND n.status = 'SENT'
|
||||
AND n.createdAt >= :since
|
||||
""")
|
||||
List<Notification> getSentToUserSince(Long userId, Instant since);
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
DELETE
|
||||
FROM Notification n
|
||||
WHERE n.createdAt < :cutOff
|
||||
""")
|
||||
void deleteNotificationsOlder(LocalDateTime cutOff);
|
||||
void deleteNotificationsOlder(Instant cutOff);
|
||||
|
||||
void deleteAllByUser(User user);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.security.dtos.PasswordResetDTO;
|
||||
import SuMoC.backend.security.models.PasswordResetToken;
|
||||
import SuMoC.backend.security.services.AuthenticationService;
|
||||
import jdk.dynalink.linker.support.SimpleLinkRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class EmailService {
|
||||
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Async
|
||||
public void sendPasswordResetEmail(String email, String otp_code) throws MailException {
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
|
||||
message.setFrom("SuMoC@outlook.de");
|
||||
message.setTo(email);
|
||||
message.setSubject("Dein Passwort-Reset Code");
|
||||
message.setText("Hallo!\n\nDein OTP Code lautet: " + otp_code +
|
||||
"\nDieser Code ist für " + String.valueOf(PasswordResetToken.EXPIRY_TIME_MINUTES) + " Minuten gültig.");
|
||||
|
||||
mailSender.send(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.config.NotificationProperties;
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
class NotificationLimiter {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final NotificationProperties notificationProperties;
|
||||
|
||||
/**
|
||||
* Filters the given list of notifications to ensure that no user exceeds the hourly limit.
|
||||
* Notifications exceeding the limit are excluded and set to FAILED status.
|
||||
*
|
||||
* @param notifications
|
||||
* @return
|
||||
*/
|
||||
public List<Notification> enforceHourlyLimits(List<Notification> notifications) {
|
||||
List<Notification> safeToSend = new java.util.ArrayList<>();
|
||||
|
||||
// Avoid multiple queries if user has multiple notifications in the list
|
||||
HashMap<Long, List<Notification>> notificationsByUser = new HashMap<>();
|
||||
|
||||
for (var notification : notifications) {
|
||||
var userId = notification.getUser().getId();
|
||||
|
||||
notificationsByUser
|
||||
.computeIfAbsent(userId,
|
||||
k -> notificationRepository.getSentToUserSince(k, Instant.now().minus(Duration.ofHours(1L))));
|
||||
|
||||
var numberSent = getNumberSentPerType(notificationsByUser.get(userId), notification.getType());
|
||||
|
||||
if (numberSent < notificationProperties.getMaxNotificationsPerHourPerType().getOrDefault(notification.getType(), Integer.MAX_VALUE)) {
|
||||
safeToSend.add(notification);
|
||||
notificationsByUser.get(userId).add(notification); // Consider this one as sent for further checks
|
||||
} else {
|
||||
// Exceeded limit, mark as FAILED
|
||||
notification.setStatus(NotificationStatus.FAILED);
|
||||
notification.setLastFailureReason("Hourly limit exceeded for notification type");
|
||||
notificationRepository.save(notification);
|
||||
}
|
||||
}
|
||||
|
||||
return safeToSend;
|
||||
}
|
||||
|
||||
private Integer getNumberSentPerType(List<Notification> sentNotifications, NotificationType type) {
|
||||
return (int) sentNotifications.stream()
|
||||
.filter(n -> n.getType() == type)
|
||||
.count();
|
||||
}
|
||||
}
|
||||
+58
-5
@@ -3,6 +3,7 @@ package SuMoC.backend.notification.services;
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.interfaces.Notifieable;
|
||||
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.user.models.User;
|
||||
@@ -11,10 +12,14 @@ import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This service is the main entry point to schedule notifications to be sent to a users' mobile device.
|
||||
* It creates Notification entities in the database with status PENDING which are then later processed by the notification worker.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationSchedulerService {
|
||||
@@ -25,6 +30,14 @@ public class NotificationSchedulerService {
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
/**
|
||||
* Can be used to schedule multiple notifications at once. Notifieable interface allows sending to multiple users.
|
||||
* dataBodies need to be serializable to JSON.
|
||||
*
|
||||
* @param dataBodies
|
||||
* @param notificationType
|
||||
* @param earliestTimeOfDayToSend
|
||||
*/
|
||||
public void scheduleAll(List<Notifieable> dataBodies,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
@@ -45,7 +58,7 @@ public class NotificationSchedulerService {
|
||||
.data(dataBodyJson)
|
||||
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
|
||||
.status(NotificationStatus.PENDING)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.createdAt(Instant.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
}).toList();
|
||||
@@ -53,11 +66,47 @@ public class NotificationSchedulerService {
|
||||
notificationRepository.saveAll(notifications);
|
||||
}
|
||||
|
||||
public void scheduleAll(List<NotifieableWithTime> dataBodies,
|
||||
NotificationType notificationType
|
||||
) {
|
||||
List<Notification> notifications = dataBodies.stream().map(dataBody -> {
|
||||
String dataBodyJson;
|
||||
try {
|
||||
dataBodyJson = objectMapper.writeValueAsString(dataBody);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize notification data body", e);
|
||||
}
|
||||
|
||||
User userProxy = entityManager.getReference(User.class, dataBody.getUserId());
|
||||
|
||||
return Notification.builder()
|
||||
.user(userProxy)
|
||||
.type(notificationType)
|
||||
.data(dataBodyJson)
|
||||
.earliestTimeOfDayToSend(dataBody.getEarliestTimeOfDayToSend())
|
||||
.status(NotificationStatus.PENDING)
|
||||
.createdAt(Instant.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
}).toList();
|
||||
|
||||
notificationRepository.saveAll(notifications);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a notification to be sent to the specified user.
|
||||
* Data body needs to be serializable to JSON.
|
||||
*
|
||||
* @param userId
|
||||
* @param dataBody
|
||||
* @param notificationType
|
||||
* @param earliestTimeOfDayToSend TOD from which on the notification can be sent. If null, send as soon as possible.
|
||||
*/
|
||||
public void schedule(
|
||||
Long userId,
|
||||
Object dataBody,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
) {
|
||||
String dataBodyJson;
|
||||
try {
|
||||
@@ -66,6 +115,10 @@ public class NotificationSchedulerService {
|
||||
throw new RuntimeException("Failed to serialize notification data body", e);
|
||||
}
|
||||
|
||||
if (earliestTimeOfDayToSend == null) {
|
||||
earliestTimeOfDayToSend = LocalTime.now();
|
||||
}
|
||||
|
||||
User userProxy = entityManager.getReference(User.class, userId);
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
@@ -74,7 +127,7 @@ public class NotificationSchedulerService {
|
||||
.data(dataBodyJson)
|
||||
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
|
||||
.status(NotificationStatus.PENDING)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.createdAt(Instant.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.google.firebase.messaging.Message;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Service
|
||||
@@ -45,6 +46,8 @@ public class NotificationSender {
|
||||
if (token == null) {
|
||||
logger.warning("No notification token found notification id: " + notification.getId());
|
||||
notification.incrementFailedSendAttempts();
|
||||
notification.setLastFailureReason("No notification token found for user");
|
||||
setFailedIfLimitExceeded(notification);
|
||||
notificationRepository.save(notification);
|
||||
return;
|
||||
}
|
||||
@@ -67,6 +70,7 @@ public class NotificationSender {
|
||||
@Override
|
||||
public void onSuccess(String messageId) {
|
||||
notification.setStatus(NotificationStatus.SENT);
|
||||
notification.setSentAt(Instant.now());
|
||||
notificationRepository.save(notification);
|
||||
logger.info("Notification sent successfully to user: " + notification.getUser().getId());
|
||||
}
|
||||
@@ -75,13 +79,17 @@ public class NotificationSender {
|
||||
public void onFailure(Throwable t) {
|
||||
notification.incrementFailedSendAttempts();
|
||||
notification.setLastFailureReason(t.getMessage());
|
||||
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
||||
notification.setStatus(NotificationStatus.FAILED);
|
||||
}
|
||||
setFailedIfLimitExceeded(notification);
|
||||
notificationRepository.save(notification);
|
||||
logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage());
|
||||
}
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
}
|
||||
|
||||
private void setFailedIfLimitExceeded(Notification notification) {
|
||||
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
||||
notification.setStatus(NotificationStatus.FAILED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -27,4 +28,13 @@ public class NotificationTokenService {
|
||||
notificationTokenRepository.save(newToken);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void unregisterDeviceToken(User user) {
|
||||
var existingToken = notificationTokenRepository.findByUserId(user.getId());
|
||||
existingToken.ifPresent(token -> {
|
||||
user.setNotificationToken(null);
|
||||
notificationTokenRepository.delete(token);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -19,15 +20,18 @@ public class NotificationWorker {
|
||||
|
||||
private final NotificationSender notificationSender;
|
||||
|
||||
private final NotificationLimiter notificationLimiter;
|
||||
|
||||
/**
|
||||
* Process all pending notifications.
|
||||
*/
|
||||
public void run() {
|
||||
// Get all pending notifications where earliest send time has passed and status is pending
|
||||
List<Notification> pendingNotifications =
|
||||
notificationRepository.findPendingNotificationsToSend(LocalTime.now());
|
||||
// Send them
|
||||
for (Notification notification : pendingNotifications) {
|
||||
|
||||
var notificationSafeToSend = notificationLimiter.enforceHourlyLimits(pendingNotifications);
|
||||
|
||||
for (Notification notification : notificationSafeToSend) {
|
||||
notificationSender.sendNotification(notification);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +41,6 @@ public class NotificationWorker {
|
||||
*/
|
||||
public void cleanUpOldNotifications() {
|
||||
// Delete notifications older than 30 days
|
||||
notificationRepository.deleteNotificationsOlder(LocalDateTime.now().minusDays(30));
|
||||
notificationRepository.deleteNotificationsOlder(Instant.now().minus(Duration.ofDays(30)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,7 @@ import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.*;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -68,13 +65,13 @@ public class DetectedRegularTripDTO {
|
||||
.build();
|
||||
}
|
||||
|
||||
public LocalTime getAverageArrivalTime() {
|
||||
int totalSeconds = 0;
|
||||
public Instant getAverageArrivalTime() {
|
||||
long totalSeconds = 0;
|
||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||
totalSeconds += trip.getEndTime().atOffset(ZoneOffset.UTC).toLocalTime().toSecondOfDay();
|
||||
totalSeconds += trip.getEndTime().getEpochSecond();
|
||||
}
|
||||
int averageSeconds = totalSeconds / supportingTrips.size();
|
||||
return LocalTime.ofSecondOfDay(averageSeconds);
|
||||
long averageSeconds = totalSeconds / supportingTrips.size();
|
||||
return Instant.ofEpochSecond(averageSeconds);
|
||||
}
|
||||
|
||||
public int getAverageDurationMinutes() {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package SuMoC.backend.regulartrip.dtos;
|
||||
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Minimal version of the DetectedRegularTripDTO for the purpose of storing in the database and showing in the carousel.
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
public class MinimalDetectedRegularTripDTO {
|
||||
private Modality modality;
|
||||
private DayOfWeek dayOfWeek;
|
||||
@Schema(description = "Earliest departure time among the supporting trips, in the user's local time")
|
||||
private LocalTime departureWindowStart;
|
||||
@Schema(description = "Latest departure time among the supporting trips, in the user's local time")
|
||||
private LocalTime departureWindowEnd;
|
||||
@Schema(description = "Earliest arrival time among the supporting trips, in the user's local time")
|
||||
private LocalTime arrivalWindowStart;
|
||||
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
|
||||
private LocalTime arrivalWindowEnd;
|
||||
@Schema(description = "Backend trip ids of the trips that support this detected regular trip.")
|
||||
private List<Long> supportingTripIds;
|
||||
private String startH3Center;
|
||||
private String endH3Center;
|
||||
|
||||
public static MinimalDetectedRegularTripDTO fromDetectedRegularTripDTO(DetectedRegularTripDTO regularTrip) {
|
||||
MinimalDetectedRegularTripDTO minimalDTO = new MinimalDetectedRegularTripDTO();
|
||||
minimalDTO.modality = regularTrip.getModality();
|
||||
minimalDTO.dayOfWeek = regularTrip.getDayOfWeek();
|
||||
minimalDTO.departureWindowStart = getEarliestDeparture(regularTrip.getSupportingTrips());
|
||||
minimalDTO.departureWindowEnd = getLatestDeparture(regularTrip.getSupportingTrips());
|
||||
minimalDTO.arrivalWindowStart = getEarliestArrival(regularTrip.getSupportingTrips());
|
||||
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
|
||||
minimalDTO.startH3Center = regularTrip.getStartH3Center();
|
||||
minimalDTO.endH3Center = regularTrip.getEndH3Center();
|
||||
minimalDTO.supportingTripIds = regularTrip.getSupportingTrips().stream()
|
||||
.map(RegularTripDetectionDTO::getTripId)
|
||||
.toList();
|
||||
return minimalDTO;
|
||||
}
|
||||
|
||||
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var earliest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getEndTime)
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var latest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getEndTime)
|
||||
.max(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var earliest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getStartTime)
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var latest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getStartTime)
|
||||
.max(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.TripMapper;
|
||||
import SuMoC.backend.trip.TripRepository;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
@@ -16,15 +17,16 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RegularTripDetectionService {
|
||||
|
||||
RegularTripDetectionProperties properties;
|
||||
private final RegularTripDetectionProperties properties;
|
||||
|
||||
TripRepository tripRepository;
|
||||
private final TripRepository tripRepository;
|
||||
|
||||
TripMapper tripMapper;
|
||||
private final TripMapper tripMapper;
|
||||
|
||||
Detector tripDetector;
|
||||
private final Detector tripDetector;
|
||||
|
||||
/**
|
||||
* Detects regular trips for the current day of the week for all users based on saved trip data and RegularTripDetectionProperties.
|
||||
|
||||
@@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties {
|
||||
|
||||
public AdHocRoutingProperties() {
|
||||
super();
|
||||
setAcceptableAdditionalMultiplierRegular(1.30);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
|
||||
setAcceptableAdditionalMultiplierRegular(2.0);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(2.0);
|
||||
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
|
||||
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
|
||||
}
|
||||
|
||||
+9
-5
@@ -2,8 +2,9 @@ package SuMoC.backend.routing.controller;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.routing.services.RoutingService;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -21,24 +22,27 @@ import java.util.logging.Logger;
|
||||
@RestController
|
||||
@RequestMapping("/routing/alternative")
|
||||
@RequiredArgsConstructor
|
||||
public class RoutingController {
|
||||
class RoutingAlternativeController {
|
||||
|
||||
private final Logger logger = Logger.getLogger(RoutingController.class.getName());
|
||||
private final Logger logger = Logger.getLogger(RoutingAlternativeController.class.getName());
|
||||
|
||||
private final RoutingService routingService;
|
||||
private final AlternativeRoutingService alternativeRoutingService;
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@PostMapping("/request")
|
||||
@Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.")
|
||||
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
|
||||
try {
|
||||
|
||||
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) {
|
||||
// This automatically uses default preferences for unauthenticated users
|
||||
routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
|
||||
}
|
||||
|
||||
var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
|
||||
var routeDTOs = alternativeRoutingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
|
||||
return ResponseEntity.ok(routeDTOs);
|
||||
} catch (WebClientRequestException e) {
|
||||
// nominatim container is not up yet, we return mock
|
||||
@@ -0,0 +1,54 @@
|
||||
package SuMoC.backend.routing.controller;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO;
|
||||
import SuMoC.backend.routing.services.DirectionsRoutingService;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/routing/directions")
|
||||
@RequiredArgsConstructor
|
||||
class RoutingDirectionsController {
|
||||
|
||||
private final DirectionsRoutingService directionsRoutingService;
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
@PostMapping("/request")
|
||||
@Schema(description = "Endpoint to request routes from point A to B, also see RoutingDirectionsRequestDTO.")
|
||||
public ResponseEntity<List<RouteDTO>> requestDirections(@Valid @RequestBody RoutingDirectionsRequestDTO directionsRequestDTO) {
|
||||
validateRequestDTO(directionsRequestDTO);
|
||||
|
||||
// if routing preferences are not provided, get stored preferences or default
|
||||
if (directionsRequestDTO.getRoutingPreferencesDTO() == null) {
|
||||
directionsRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(directionsRoutingService.getDirections(directionsRequestDTO));
|
||||
}
|
||||
|
||||
private void validateRequestDTO(RoutingDirectionsRequestDTO requestDTO) {
|
||||
if (requestDTO.getArrivalTime() == null && requestDTO.getDepartureTime() == null) {
|
||||
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
|
||||
}
|
||||
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
|
||||
throw new IllegalArgumentException("Only one of arrivalTime or departureTime should be provided.");
|
||||
}
|
||||
if (requestDTO.getOriginAddress() == null && (requestDTO.getOriginLat() == 0.0 || requestDTO.getOriginLon() == 0.0)) {
|
||||
throw new IllegalArgumentException("Origin must be specified either by address or coordinates.");
|
||||
}
|
||||
if (requestDTO.getDestinationAddress() == null && (requestDTO.getDestinationLat() == 0.0 || requestDTO.getDestinationLon() == 0.0)) {
|
||||
throw new IllegalArgumentException("Destination must be specified either by address or coordinates.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package SuMoC.backend.routing.dtos;
|
||||
|
||||
import SuMoC.backend.geocoding.AddressDTO;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.annotation.Nullable;
|
||||
import lombok.Getter;
|
||||
@@ -17,6 +18,7 @@ import java.util.List;
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Schema(description = "This DTO represents a suggested route as a response to a requested alternative route.")
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class RouteDTO {
|
||||
@Schema(description = "The actual address of the start location.")
|
||||
private AddressDTO startAddress;
|
||||
@@ -46,10 +48,25 @@ public class RouteDTO {
|
||||
private double co2Savings;
|
||||
@Schema(description = "CO2e emission of this route.")
|
||||
private double co2Emissions;
|
||||
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
|
||||
@Schema(description = "The temporal difference in minutes compared to the original route (in case alternative was requested) / the car route (when simply directions requested) .")
|
||||
private double timeDifferenceSeconds;
|
||||
|
||||
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds, double co2Emissions) {
|
||||
public RouteDTO(
|
||||
AddressDTO startAddress,
|
||||
@Nullable String firstStopName,
|
||||
double startLat,
|
||||
double startLon,
|
||||
AddressDTO endAddress,
|
||||
@Nullable String lastStopName,
|
||||
double endLat,
|
||||
double endLon,
|
||||
Instant startDateTime,
|
||||
Instant endDateTime,
|
||||
List<StepDTO> steps,
|
||||
double co2Savings,
|
||||
double timeDifferenceSeconds,
|
||||
double co2Emissions
|
||||
) {
|
||||
this.startAddress = startAddress;
|
||||
this.firstStopName = firstStopName;
|
||||
this.startLat = startLat;
|
||||
@@ -114,17 +131,18 @@ public class RouteDTO {
|
||||
);
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
400f
|
||||
));
|
||||
dto.steps.add(new StepDTO(
|
||||
dto.steps.add(new TransitStepDTO(
|
||||
Modality.TRAM,
|
||||
5000f,
|
||||
"106",
|
||||
5000f
|
||||
"Ich bin eine Testlinie",
|
||||
"Ich bin ein Teststartbahnhof",
|
||||
"Ich bin ein Testendbahnhof"
|
||||
));
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
300f
|
||||
));
|
||||
return dto;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
import SuMoC.backend.carta.DirectionsRequest;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.annotation.Nullable;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -13,7 +14,7 @@ import java.time.Instant;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Schema(description = "This DTO represents a request for alternative routes between an origin and a destination.")
|
||||
public class RoutingAlternativeRequestDTO {
|
||||
public class RoutingAlternativeRequestDTO implements DirectionsRequest {
|
||||
@NotNull
|
||||
private Double originLat;
|
||||
@NotNull
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
import SuMoC.backend.carta.DirectionsRequest;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.annotation.Nullable;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "DTO representing a request for routing directions between two points. Points can be specified either by coordinates or addresses." +
|
||||
"If both provided, coordinates are preferred.")
|
||||
public class RoutingDirectionsRequestDTO implements DirectionsRequest {
|
||||
private Double originLat;
|
||||
private Double originLon;
|
||||
private Double destinationLat;
|
||||
private Double destinationLon;
|
||||
private String originAddress;
|
||||
private String destinationAddress;
|
||||
private Instant arrivalTime;
|
||||
private Instant departureTime;
|
||||
@Nullable
|
||||
@Schema(description = "Routing preferences to customize the routing behavior. If null, will search for stored user preferences, if not found, use default.")
|
||||
private RoutingPreferencesDTO routingPreferencesDTO;
|
||||
}
|
||||
@@ -12,7 +12,9 @@ import java.util.List;
|
||||
@Setter
|
||||
@Schema(description = "This DTO represents the user preferences for routing / alternative route suggestions.")
|
||||
public class RoutingPreferencesDTO {
|
||||
@Schema(description = "Whether to prefer alternative routes that involve physical activity (walking, cycling) when suggestin alternative routes.")
|
||||
private boolean preferPhysicalActivity = false;
|
||||
@Schema(description = "Whether to consider current weather conditions when suggesting alternative routes.")
|
||||
private boolean considerWeatherConditions = true;
|
||||
private List<Modality> modalitiesToConsider = new ArrayList<>(
|
||||
List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
@@ -11,9 +13,13 @@ import lombok.Setter;
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = TransitStepDTO.class, name = "transit"),
|
||||
@JsonSubTypes.Type(value = StepDTO.class, name = "step")
|
||||
})
|
||||
@Schema(description = "A single step within a suggested alternative route.")
|
||||
public class StepDTO {
|
||||
private Modality modality;
|
||||
private String lineNumber;
|
||||
private double distanceMeters;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "A single transit step within a suggested alternative route.")
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TransitStepDTO extends StepDTO {
|
||||
private String lineNumber;
|
||||
private String lineHeadsign;
|
||||
private String startStop;
|
||||
private String endStop;
|
||||
|
||||
public TransitStepDTO(Modality modality, double distanceMeters, String lineNumber, String lineHeadsign, String startStop, String endStop) {
|
||||
super(modality, distanceMeters);
|
||||
this.lineNumber = lineNumber;
|
||||
this.lineHeadsign = lineHeadsign;
|
||||
this.startStop = startStop;
|
||||
this.endStop = endStop;
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ public class RoutingPreferences {
|
||||
preferences.setPreferPhysicalActivity(false);
|
||||
preferences.setConsiderWeatherConditions(true);
|
||||
preferences.setModalitiesToConsider(new ArrayList<>(List.of(
|
||||
Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER,
|
||||
Modality.WALKING,
|
||||
Modality.BUS, Modality.TRAM, Modality.TRAIN
|
||||
)));
|
||||
return preferences;
|
||||
|
||||
@@ -6,6 +6,8 @@ import SuMoC.backend.meteo.WeatherCondition;
|
||||
import SuMoC.backend.routing.config.RoutingProperties;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.dtos.StepDTO;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -50,12 +52,12 @@ public class AlternativeFilterService {
|
||||
|
||||
if (routeDTO.isPhysicalActivity() && alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
||||
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()
|
||||
|| (long) travelTimeDeltaSeconds < toleratedMaximumPhysical) {
|
||||
|| travelTimeDeltaSeconds < toleratedMaximumPhysical) {
|
||||
filteredAlternatives.add(routeDTO);
|
||||
}
|
||||
} else {
|
||||
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular()
|
||||
|| (long) travelTimeDeltaSeconds < toleratedMaximumRegular) {
|
||||
|| travelTimeDeltaSeconds < toleratedMaximumRegular) {
|
||||
filteredAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
@@ -80,14 +82,16 @@ public class AlternativeFilterService {
|
||||
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
|
||||
for (RouteDTO route : alternatives) {
|
||||
if (route.isPhysicalActivity()) {
|
||||
if (!route.isCyclingRoute() && !route.isWalkingRoute()) {
|
||||
throw new RuntimeException("Unexpected case of a physical activity route that is not pure cycling or walking");
|
||||
}
|
||||
var weatherConditions = forecast.getWeatherConditionsBetween(route.getStartDateTime(), route.getEndDateTime());
|
||||
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
|
||||
filteredAlternatives.add(route);
|
||||
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
|
||||
filteredAlternatives.add(route);
|
||||
} else {
|
||||
throw new RuntimeException("Unexpected case of a physical activity route that is not pure cycling or walking");
|
||||
}
|
||||
// else: weather conditions not acceptable, route is silently dropped
|
||||
} else {
|
||||
filteredAlternatives.add(route);
|
||||
}
|
||||
@@ -100,6 +104,49 @@ public class AlternativeFilterService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is meant to filter out transit routes that would make no sense from the user perspective.
|
||||
*
|
||||
* @param alternatives
|
||||
* @return
|
||||
*/
|
||||
public List<RouteDTO> filterForInefficientTransitRoutes(
|
||||
List<RouteDTO> alternatives
|
||||
) {
|
||||
List<RouteDTO> filteredAlternatives = new ArrayList<>();
|
||||
|
||||
var directWalkingRoute = findDirectWalkingRoute(alternatives);
|
||||
for (var alternative : alternatives) {
|
||||
// Case 1: Sum of walking is greater than direct walking route
|
||||
if (directWalkingRoute != null) {
|
||||
double alternativeWalkingDistance = alternative.getSteps().stream()
|
||||
.filter(step -> step.getModality() == Modality.WALKING)
|
||||
.map(StepDTO::getDistanceMeters)
|
||||
.reduce(0d, Double::sum);
|
||||
double directWalkingDistance = directWalkingRoute.getSteps().stream()
|
||||
.filter(step -> step.getModality() == Modality.WALKING)
|
||||
.map(StepDTO::getDistanceMeters)
|
||||
.reduce(0d, Double::sum);
|
||||
if (directWalkingDistance < alternativeWalkingDistance) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
filteredAlternatives.add(alternative);
|
||||
}
|
||||
|
||||
return filteredAlternatives;
|
||||
}
|
||||
|
||||
private RouteDTO findDirectWalkingRoute(List<RouteDTO> alternatives) {
|
||||
return alternatives.stream()
|
||||
.filter(RouteDTO::isWalkingRoute)
|
||||
.min((r1, r2) -> Long.compare(
|
||||
r1.getDurationSeconds(),
|
||||
r2.getDurationSeconds()
|
||||
)).orElse(null);
|
||||
}
|
||||
|
||||
private boolean allConditionsAcceptable(List<WeatherCondition> conditions, List<WeatherCondition> acceptableConditions) {
|
||||
return new HashSet<>(acceptableConditions).containsAll(conditions);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package SuMoC.backend.routing.services;
|
||||
|
||||
import SuMoC.backend.carta.DirectionsService;
|
||||
import SuMoC.backend.routing.config.AdHocRoutingProperties;
|
||||
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Service to determine alternative routes for a given routing request.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AlternativeRoutingService {
|
||||
|
||||
private final AlternativeFilterService alternativeFilterService;
|
||||
|
||||
private final OnCallRoutingProperties onCallRoutingProperties;
|
||||
|
||||
private final AdHocRoutingProperties adHocRoutingProperties;
|
||||
|
||||
private final DirectionsService directionsService;
|
||||
|
||||
/**
|
||||
* Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time.
|
||||
* This is the public method for alternatives explicitly asked for by the client.
|
||||
*/
|
||||
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
|
||||
List<RouteDTO> routes = directionsService.getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
|
||||
routes = alternativeFilterService.filterForInefficientTransitRoutes(routes);
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public alternative retrieval method which is used to check for alternatives we suggest to user via notification
|
||||
* right after user finished the trip.
|
||||
* Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives
|
||||
* and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres.
|
||||
*/
|
||||
public List<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
List<RouteDTO> routes = directionsService.getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
|
||||
|
||||
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
|
||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||
}
|
||||
|
||||
routes = alternativeFilterService.filterForInefficientTransitRoutes(routes);
|
||||
return routes;
|
||||
}
|
||||
|
||||
public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
// TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives
|
||||
List<RouteDTO> routes = directionsService.getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
|
||||
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
|
||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||
}
|
||||
|
||||
routes = alternativeFilterService.filterForInefficientTransitRoutes(routes);
|
||||
|
||||
RouteDTO bestRoute = null;
|
||||
// if users wants physical activity, we pick the fastest physical activity route, if any
|
||||
if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
||||
bestRoute = routes.stream()
|
||||
.filter(RouteDTO::isPhysicalActivity)
|
||||
.min((r1, r2) -> Long.compare(
|
||||
r1.getDurationSeconds(),
|
||||
r2.getDurationSeconds()
|
||||
)).orElse(null);
|
||||
if (bestRoute != null) {
|
||||
return bestRoute;
|
||||
}
|
||||
}
|
||||
// else we pick the fastest route overall
|
||||
bestRoute = routes.stream()
|
||||
.min((r1, r2) -> Long.compare(
|
||||
r1.getDurationSeconds(),
|
||||
r2.getDurationSeconds()
|
||||
)).orElse(null);
|
||||
return bestRoute;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package SuMoC.backend.routing.services;
|
||||
|
||||
import SuMoC.backend.routing.dtos.StepDTO;
|
||||
import SuMoC.backend.routing.dtos.TransitStepDTO;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import sumoc.backend.carta.client.model.Route;
|
||||
import sumoc.backend.carta.client.model.Step;
|
||||
@@ -28,7 +29,7 @@ public class CartaTransitRouteProcessor {
|
||||
/**
|
||||
* Extracts information from the route.
|
||||
*/
|
||||
public void process() {
|
||||
private void process() {
|
||||
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||
|
||||
assert cartaRoute.getSteps() != null;
|
||||
@@ -46,11 +47,21 @@ public class CartaTransitRouteProcessor {
|
||||
? Modality.fromCartaString(step.getLine().getType().toString())
|
||||
: Modality.fromCartaString(step.getType());
|
||||
|
||||
steps.add(new StepDTO(
|
||||
stepModality,
|
||||
step.getType().equals("TransitStep") ? step.getLine().getCode() : null,
|
||||
step.getDistance()
|
||||
));
|
||||
if (step.getType().equals("TransitStep")) {
|
||||
steps.add(new TransitStepDTO(
|
||||
stepModality,
|
||||
step.getDistance(),
|
||||
step.getLine().getCode(),
|
||||
step.getLine().getHeadsign(),
|
||||
step.getStops().getFirst().getName(),
|
||||
step.getStops().getLast().getName()
|
||||
));
|
||||
} else {
|
||||
steps.add(new StepDTO(
|
||||
stepModality,
|
||||
step.getDistance()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
this.steps = steps;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package SuMoC.backend.routing.services;
|
||||
|
||||
import SuMoC.backend.carta.DirectionsService;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Service for getting directions between two given points.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DirectionsRoutingService {
|
||||
|
||||
private final DirectionsService directionsService;
|
||||
|
||||
public List<RouteDTO> getDirections(RoutingDirectionsRequestDTO requestDTO) {
|
||||
// TODO make geocoding call if address is provided instead of coordinates
|
||||
return directionsService.getPossibleRoutes(requestDTO, true);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ public class RoutingPreferencesService {
|
||||
* Gets routing preferences for the current user, if user is logged in returns his preferences, if not logged in returns default preferences.
|
||||
*/
|
||||
public RoutingPreferencesDTO getRoutingPreferencesForCurrentUser() {
|
||||
if (currentUserService.isAuthenticated()) {
|
||||
if (currentUserService.isLoggedInUser()) {
|
||||
var currentUser = currentUserService.get();
|
||||
return getUserRoutingPreferences(currentUser.getId());
|
||||
} else {
|
||||
|
||||
@@ -81,4 +81,6 @@ public class ScheduledTasks {
|
||||
logger.error("Error notifying regular route alternatives.", e);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO clean up task for carrousel candidates
|
||||
}
|
||||
|
||||
@@ -92,18 +92,21 @@ public class SecurityConfiguration {
|
||||
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
|
||||
auth.requestMatchers("/dev/**").permitAll();
|
||||
auth.requestMatchers("/logs").permitAll();
|
||||
auth.requestMatchers("/routing/alternative/**").permitAll();
|
||||
auth.requestMatchers("/auth/user/**").permitAll();
|
||||
auth.requestMatchers("/routing/directions/**").permitAll();
|
||||
auth.requestMatchers("/routing/alternative/**").permitAll();
|
||||
auth.requestMatchers("/geocoding/**").permitAll();
|
||||
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
|
||||
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
|
||||
auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN");
|
||||
auth.requestMatchers("/routing/alternative/carrousel/**").hasAnyRole("USER", "ADMIN");
|
||||
auth.requestMatchers("/routing/preferences/**").hasAnyRole("USER", "ADMIN");
|
||||
|
||||
// gamification
|
||||
auth.requestMatchers("/badges/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers("/leaderboard/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers("/challenges/**").hasAnyRole("ADMIN", "USER");
|
||||
|
||||
auth.requestMatchers("/notifications/**").hasAnyRole("USER", "ADMIN");
|
||||
//auth.requestMatchers("/error").permitAll();
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
package SuMoC.backend.security.controller;
|
||||
|
||||
|
||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
|
||||
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||
import SuMoC.backend.security.dtos.*;
|
||||
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
||||
import SuMoC.backend.security.services.AuthenticationService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
@@ -14,6 +12,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -74,4 +74,39 @@ public class UserAuthenticationController {
|
||||
|
||||
return new ResponseEntity<>(responseDTO, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Operation(summary = "OTP Code zur änderung des Passworts", description = "Erstellt bei Anfrage einen neuen 6-stelligen OTP Code, " +
|
||||
"mit welchem das Passwort des Accounts mit der zugehörigen Email einmalig verändert werden kann." +
|
||||
" Dieser wird per Mail an den Nutzer gesendet.")
|
||||
@PostMapping("/request-otp-for-password-reset")
|
||||
public ResponseEntity<String> requestOtpForPasswordReset(@RequestBody OtpRequestDTO otpRequestDTO) {
|
||||
|
||||
try{
|
||||
authenticationService.generateNewPasswordResetTokenForUser(otpRequestDTO.getEmail());
|
||||
return ResponseEntity.ok("OTP erstellt");
|
||||
} catch (UsernameNotFoundException e) {
|
||||
return ResponseEntity.badRequest().body(e.getMessage());
|
||||
} catch(MailException e){
|
||||
System.out.println(" ## MAIL EXCEPTION \n" +e.getMessage());
|
||||
return ResponseEntity.internalServerError().body("Fehler beim versenden der Email, versuche es später erneut");
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.internalServerError().body("Fehler beim erstellen des OTP");
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "Veränderung des Passworts eines Profils ", description = "Durch Eingabe eines Validen OTP Codes " +
|
||||
"zu einer zugehörigen Email kann das Passwort des Profils geändert werden.")
|
||||
@PostMapping("/reset-password")
|
||||
public ResponseEntity<String> resetPassword(@RequestBody PasswordResetDTO passwordResetDTO){
|
||||
try {
|
||||
authenticationService.resetPassword(passwordResetDTO);
|
||||
return ResponseEntity.ok("Passwort erfolgreich geändert");
|
||||
} catch (InvalidTokenException | UsernameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.badRequest().body(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package SuMoC.backend.security.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class OtpRequestDTO {
|
||||
String email;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package SuMoC.backend.security.dtos;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class PasswordResetDTO {
|
||||
@JsonAlias({"otp_code", "otpCode"})
|
||||
String otpCode;
|
||||
String email;
|
||||
@JsonAlias({"new_password", "newPassword"})
|
||||
String newPassword;
|
||||
}
|
||||
@@ -6,5 +6,6 @@ public enum RegistrationStatus {
|
||||
EMAIL_INVALID,
|
||||
PUBLIC_NAME_EXISTS,
|
||||
PUBLIC_NAME_FORBIDDEN,
|
||||
PASSWORD_INVALID,
|
||||
UNKNOWN_ERROR
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.security.exceptions;
|
||||
|
||||
public class InvalidTokenException extends RuntimeException {
|
||||
public InvalidTokenException(String message) { super(message); }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.security.models;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "OneTimePasswordTokens")
|
||||
@Getter
|
||||
public class PasswordResetToken{
|
||||
|
||||
public static int EXPIRY_TIME_MINUTES = 30;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
private String otpCode;
|
||||
private LocalDateTime expiryDate;
|
||||
|
||||
public PasswordResetToken(String email, String code) {
|
||||
this.email = email;
|
||||
this.otpCode = code;
|
||||
this.expiryDate = LocalDateTime.now().plusMinutes(EXPIRY_TIME_MINUTES);
|
||||
}
|
||||
|
||||
public PasswordResetToken() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package SuMoC.backend.security.repository;
|
||||
|
||||
import SuMoC.backend.security.models.PasswordResetToken;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {
|
||||
Boolean existsByEmail(String email);
|
||||
|
||||
Optional<PasswordResetToken> findByEmail(String email);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
package SuMoC.backend.security.services;
|
||||
|
||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
|
||||
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||
import SuMoC.backend.notification.services.EmailService;
|
||||
import SuMoC.backend.security.dtos.*;
|
||||
import SuMoC.backend.security.enums.RegistrationStatus;
|
||||
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
||||
import SuMoC.backend.security.models.PasswordResetToken;
|
||||
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
|
||||
import SuMoC.backend.user.dtos.UserDTO;
|
||||
import SuMoC.backend.user.enums.RoleName;
|
||||
import SuMoC.backend.user.mapper.UserMapper;
|
||||
@@ -12,14 +13,19 @@ import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@@ -35,21 +41,33 @@ public class AuthenticationService {
|
||||
|
||||
private UserMapper userMapper;
|
||||
|
||||
private PasswordResetTokenRepository passwordResetTokenRepository;
|
||||
private EmailService emailService;
|
||||
|
||||
@Autowired
|
||||
public AuthenticationService(UserRepository userRepository, PasswordEncoder passwordEncoder,
|
||||
AuthenticationManager authenticationManager, TokenService tokenService,
|
||||
UserMapper userMapper) {
|
||||
UserMapper userMapper, PasswordResetTokenRepository passwordResetTokenRepository, EmailService emailService) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.tokenService = tokenService;
|
||||
this.userMapper = userMapper;
|
||||
this.passwordResetTokenRepository = passwordResetTokenRepository;
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
private boolean isPasswordFormatCorrect(String password) {
|
||||
//insert other check ups for passwords
|
||||
if(password.length() < 8) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public RegistrationResponseDTO registerUser(UserRegistrationDTO registrationDTO) {
|
||||
try {
|
||||
// check if mail is already in use
|
||||
if (userRepository.existsByEmail(registrationDTO.getEmail())) {
|
||||
if (userRepository.existsByEmail(registrationDTO.getEmail().toLowerCase())) {
|
||||
return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_EXISTS);
|
||||
}
|
||||
|
||||
@@ -60,15 +78,18 @@ public class AuthenticationService {
|
||||
|
||||
// Validate Email
|
||||
String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
|
||||
if (!registrationDTO.getEmail().matches(emailRegex)) {
|
||||
if (!registrationDTO.getEmail().toLowerCase().matches(emailRegex)) {
|
||||
return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_INVALID);
|
||||
}
|
||||
|
||||
//validate Password
|
||||
if(!isPasswordFormatCorrect(registrationDTO.getPassword())) return new RegistrationResponseDTO(null, null, RegistrationStatus.PASSWORD_INVALID);
|
||||
|
||||
// encode password
|
||||
String encodedPassword = passwordEncoder.encode(registrationDTO.getPassword());
|
||||
|
||||
// create and save user
|
||||
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail(), encodedPassword);
|
||||
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail().toLowerCase(), encodedPassword);
|
||||
|
||||
// Sicherheitshalber nochmal explizit setzen
|
||||
if (user.getRoles() == null || user.getRoles().isEmpty()) {
|
||||
@@ -78,7 +99,7 @@ public class AuthenticationService {
|
||||
|
||||
userRepository.save(user);
|
||||
// We generate the login dto to get the token right after registration
|
||||
LoginResponseDTO loginResponseDTO = login(new UserAuthenticationPairDTO(registrationDTO.getEmail(), registrationDTO.getPassword()));
|
||||
LoginResponseDTO loginResponseDTO = login(new UserAuthenticationPairDTO(registrationDTO.getEmail().toLowerCase(), registrationDTO.getPassword()));
|
||||
// But now we return RegistrationResponseDTO for better status handling
|
||||
return new RegistrationResponseDTO(loginResponseDTO.getUserDTO(), loginResponseDTO.getJwt(), RegistrationStatus.SUCCESS);
|
||||
|
||||
@@ -96,10 +117,10 @@ public class AuthenticationService {
|
||||
try {
|
||||
|
||||
Authentication auth = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(authPairDTO.getEmail(), authPairDTO.getPassword())
|
||||
new UsernamePasswordAuthenticationToken(authPairDTO.getEmail().toLowerCase(), authPairDTO.getPassword())
|
||||
);
|
||||
|
||||
User user = userRepository.findByEmail(authPairDTO.getEmail())
|
||||
User user = userRepository.findByEmail(authPairDTO.getEmail().toLowerCase())
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
|
||||
UserDTO userDTO = userMapper.toUserDTO(user);
|
||||
@@ -114,4 +135,60 @@ public class AuthenticationService {
|
||||
return new LoginResponseDTO(null, "");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param email the account for which a OTP shall be created to reset the password
|
||||
*
|
||||
* NOTE: OTP Code gets hashed by passwordEncoder
|
||||
*/
|
||||
@Transactional
|
||||
public void generateNewPasswordResetTokenForUser(String email) throws UsernameNotFoundException, MailException{
|
||||
if (!userRepository.existsByEmail(email)) throw new UsernameNotFoundException("Es existiert kein Account mit dieser Email") ;
|
||||
|
||||
Optional<PasswordResetToken> token = passwordResetTokenRepository.findByEmail(email);
|
||||
token.ifPresent(passwordResetToken -> {
|
||||
System.out.println("Found token for this account...Deleting token...");
|
||||
passwordResetTokenRepository.delete(passwordResetToken);
|
||||
});
|
||||
|
||||
String otp = generate_six_digit_OTP();
|
||||
passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp
|
||||
emailService.sendPasswordResetEmail(email, otp);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void resetPassword(PasswordResetDTO passwordResetDTO) throws InvalidTokenException, UsernameNotFoundException {
|
||||
|
||||
PasswordResetToken token = passwordResetTokenRepository.findByEmail(passwordResetDTO.getEmail())
|
||||
.orElseThrow(() -> new InvalidTokenException("Token nicht gefunden"));
|
||||
|
||||
if (LocalDateTime.now().isAfter(token.getExpiryDate())) {
|
||||
throw new InvalidTokenException("Code ist abgelaufen");
|
||||
}
|
||||
|
||||
//use .matches() so compare raw otp to (salted!) encoded otp
|
||||
if(!passwordEncoder.matches(passwordResetDTO.getOtpCode(),token.getOtpCode())){
|
||||
throw new InvalidTokenException("Code ist ungültig");
|
||||
}
|
||||
|
||||
if(!isPasswordFormatCorrect(passwordResetDTO.getNewPassword())) {
|
||||
throw new InvalidTokenException("Passwortformat ist nicht korrekt");
|
||||
}
|
||||
|
||||
User user = userRepository.findByEmail(passwordResetDTO.getEmail())
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User existiert nicht"));
|
||||
user.setPassword(passwordEncoder.encode(passwordResetDTO.getNewPassword()));
|
||||
userRepository.save(user);
|
||||
passwordResetTokenRepository.delete(token);
|
||||
}
|
||||
|
||||
private String generate_six_digit_OTP(){
|
||||
SecureRandom random = new SecureRandom();
|
||||
// Generiert eine Zahl von 0 bis 999.999
|
||||
int code = random.nextInt(1000000);
|
||||
// Formatiert die Zahl auf 6 Stellen und füllt links mit 0 auf
|
||||
return String.format("%06d", code);
|
||||
}
|
||||
|
||||
}
|
||||
+4
-4
@@ -1,11 +1,11 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
package SuMoC.backend.seed;
|
||||
|
||||
import SuMoC.backend.gamification.badges.BadgeRepository;
|
||||
import SuMoC.backend.gamification.badges.BadgeService;
|
||||
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||
import jakarta.transaction.Transactional;
|
||||
import kotlin.collections.ArrayDeque;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
@@ -16,7 +16,7 @@ import java.util.*;
|
||||
|
||||
@Component
|
||||
@Profile("dev")
|
||||
@Order(3)
|
||||
@Order(2)
|
||||
public class DevBadgeSeeder implements CommandLineRunner {
|
||||
|
||||
private final BadgeService badgeService;
|
||||
@@ -0,0 +1,178 @@
|
||||
package SuMoC.backend.seed;
|
||||
|
||||
import SuMoC.backend.gamification.challenges.ChallengeMapper;
|
||||
import SuMoC.backend.gamification.challenges.ChallengeRepository;
|
||||
import SuMoC.backend.gamification.challenges.ChallengeService;
|
||||
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.*;
|
||||
|
||||
@Component
|
||||
@Profile("dev")
|
||||
@Order(3)
|
||||
public class DevChallengeSeeder implements CommandLineRunner {
|
||||
|
||||
private final ChallengeService challengeService;
|
||||
private final ChallengeRepository challengeRepository;
|
||||
|
||||
public DevChallengeSeeder(
|
||||
ChallengeService challengeService,
|
||||
ChallengeRepository challengeRepository
|
||||
) {
|
||||
this.challengeService = challengeService;
|
||||
this.challengeRepository = challengeRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) {
|
||||
final String dummyImageBase64 = loadBase64FromClasspath("images/ChallengeDummy.png");
|
||||
List<Seed> seeds = generateSeeds();
|
||||
|
||||
for (Seed seed : seeds) {
|
||||
challengeRepository.findByName(seed.name())
|
||||
.map(ChallengeMapper::toDTO)
|
||||
.ifPresentOrElse(
|
||||
existingChallenge -> {
|
||||
existingChallenge.setName(seed.name());
|
||||
existingChallenge.setDescription(seed.description());
|
||||
existingChallenge.setCriteria(seed.criteria());
|
||||
existingChallenge.setReward(seed.reward());
|
||||
existingChallenge.setBase64image(dummyImageBase64);
|
||||
challengeService.modifyChallenge(existingChallenge);
|
||||
},
|
||||
() -> {
|
||||
ChallengeDTO newChallenge = new ChallengeDTO();
|
||||
newChallenge.setName(seed.name());
|
||||
newChallenge.setDescription(seed.description());
|
||||
newChallenge.setCriteria(seed.criteria());
|
||||
newChallenge.setReward(seed.reward());
|
||||
newChallenge.setBase64image(dummyImageBase64);
|
||||
challengeService.createChallenge(newChallenge);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
challengeService.weeklyChallengeScheduler();
|
||||
}
|
||||
|
||||
private String loadBase64FromClasspath(String classpathLocation) {
|
||||
try (InputStream in = new ClassPathResource(classpathLocation).getInputStream()) {
|
||||
byte[] bytes = in.readAllBytes();
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not load image from classpath: " + classpathLocation, e);
|
||||
}
|
||||
}
|
||||
|
||||
private record Seed(String name, String description, Map<String, Integer> criteria, Integer reward) {}
|
||||
|
||||
private static Seed seed(
|
||||
String name,
|
||||
String description,
|
||||
Map<String, Integer> criteria,
|
||||
Integer reward
|
||||
) {
|
||||
return new Seed(name, description, criteria, reward);
|
||||
}
|
||||
|
||||
private List<Seed> generateSeeds() {
|
||||
List<Seed> seeds = new ArrayList<>();
|
||||
|
||||
seeds.add(seed(
|
||||
"Feierabendrunde",
|
||||
"Lege diese Woche 10 km mit dem Fahrrad zurück",
|
||||
new HashMap<>(Map.of("KM_CYCLED", 10)),
|
||||
80
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"Fahrrad-Fokus",
|
||||
"Lege diese Woche 25 km mit dem Fahrrad zurück",
|
||||
new HashMap<>(Map.of("KM_CYCLED", 25)),
|
||||
150
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"Rad-Marathon",
|
||||
"Lege diese Woche 60 km mit dem Fahrrad zurück",
|
||||
new HashMap<>(Map.of("KM_CYCLED", 60)),
|
||||
320
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"ÖPNV-Snack",
|
||||
"Fahre diese Woche 10 km mit öffentlichen Verkehrsmitteln",
|
||||
new HashMap<>(Map.of("KM_PUBLIC_TRANSPORT", 10)),
|
||||
80
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"ÖPNV-Woche",
|
||||
"Fahre diese Woche 20 km mit öffentlichen Verkehrsmitteln",
|
||||
new HashMap<>(Map.of("KM_PUBLIC_TRANSPORT", 20)),
|
||||
150
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"ÖPNV-Poweruser",
|
||||
"Fahre diese Woche 50 km mit öffentlichen Verkehrsmitteln",
|
||||
new HashMap<>(Map.of("KM_PUBLIC_TRANSPORT", 50)),
|
||||
300
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"Spaziergänger",
|
||||
"Gehe diese Woche 5 km zu Fuß",
|
||||
new HashMap<>(Map.of("KM_WALKED", 5)),
|
||||
60
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"Stadtläufer",
|
||||
"Gehe diese Woche 15 km zu Fuß",
|
||||
new HashMap<>(Map.of("KM_WALKED", 15)),
|
||||
140
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"Weitwanderer",
|
||||
"Gehe diese Woche 30 km zu Fuß",
|
||||
new HashMap<>(Map.of("KM_WALKED", 30)),
|
||||
280
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"XP-Booster",
|
||||
"Sammle diese Woche 250 XP",
|
||||
new HashMap<>(Map.of("XP", 250)),
|
||||
200
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"XP-Grinder",
|
||||
"Sammle diese Woche 500 XP",
|
||||
new HashMap<>(Map.of("XP", 500)),
|
||||
350
|
||||
));
|
||||
|
||||
seeds.add(seed(
|
||||
"XP-Overkill",
|
||||
"Sammle diese Woche 1000 XP",
|
||||
new HashMap<>(Map.of("XP", 1000)),
|
||||
600
|
||||
));
|
||||
|
||||
|
||||
|
||||
|
||||
return seeds;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package SuMoC.backend.seed.trip;
|
||||
|
||||
import SuMoC.backend.trip.TripFactory;
|
||||
import SuMoC.backend.trip.TripService;
|
||||
import SuMoC.backend.trip.dtos.NewTripDTO;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Profile("dev")
|
||||
@Order(2)
|
||||
public class DevTripSeeder implements CommandLineRunner {
|
||||
|
||||
private final TripService tripService;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
|
||||
@Autowired
|
||||
public DevTripSeeder(TripService tripService, UserRepository userRepository) {
|
||||
this.tripService = tripService;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
// Iterate over all users and create 5 random trips for each of the last 5 weeks
|
||||
userRepository.findAll().forEach(user -> {
|
||||
for (int week = 0; week < 5; week++) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
// Create trips within each week's time range
|
||||
long daysAgo = week * 7 + (long) (Math.random() * 7);
|
||||
NewTripDTO newTrip = TripFactory.randomNewTripDTO(
|
||||
java.time.Instant.now().minus(java.time.Duration.ofDays((long) (Math.random() * 30))));
|
||||
tripService.addTrip(user, newTrip);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package SuMoC.backend.seed.user;
|
||||
|
||||
import SuMoC.backend.dev.DevProperties;
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import SuMoC.backend.notification.services.NotificationTokenService;
|
||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||
@@ -12,6 +13,10 @@ import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@Profile("dev")
|
||||
@@ -35,7 +40,53 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) throws Exception {
|
||||
List<User> pgMembers = seedPgMembers();
|
||||
List<User> defaultTestUsers = seedDefaultTestUsers();
|
||||
|
||||
Long positionIndex = 1L;
|
||||
for (var user : pgMembers) {
|
||||
addDummyStats(user);
|
||||
positionIndex++;
|
||||
}
|
||||
for (var user : defaultTestUsers) {
|
||||
addDummyStats(user);
|
||||
positionIndex++;
|
||||
}
|
||||
//List<User> nTestUsers = seedNtestUsers(10);
|
||||
// Now you can do more stuff with the created users if needed
|
||||
}
|
||||
|
||||
/**
|
||||
* Useful for stress testing with a larger number of users. Seeds the specified number of users dummy users.
|
||||
*
|
||||
* @param numberOfUsers
|
||||
* @return List of created User objects
|
||||
*/
|
||||
private List<User> seedNtestUsers(int numberOfUsers) {
|
||||
List<User> createdUsers = new ArrayList<>();
|
||||
for (int i = 1; i <= numberOfUsers; i++) {
|
||||
UserRegistrationDTO userDto = UserRegistrationDTO.builder()
|
||||
.email("testuser" + i + "@email.com")
|
||||
.publicName("Test User " + i)
|
||||
.privateName("Test User " + i)
|
||||
.password("password" + i)
|
||||
.build();
|
||||
authenticationService.registerUser(userDto);
|
||||
User user = userRepository.findByEmail("testuser" + i + "@email.com").orElseThrow();
|
||||
notificationTokenService.registerDeviceToken(
|
||||
user,
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user);
|
||||
}
|
||||
return createdUsers;
|
||||
}
|
||||
|
||||
private List<User> seedDefaultTestUsers() {
|
||||
List<User> createdUsers = new ArrayList<>();
|
||||
UserRegistrationDTO user1dto = UserRegistrationDTO.builder()
|
||||
.email("user1@email.com")
|
||||
.publicName("Nutzer 1 Public")
|
||||
@@ -49,6 +100,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user1);
|
||||
UserRegistrationDTO user2dto = UserRegistrationDTO.builder()
|
||||
.email("user2@email.com")
|
||||
.publicName("Nutzer 2 Public")
|
||||
@@ -62,6 +114,12 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user2);
|
||||
return createdUsers;
|
||||
}
|
||||
|
||||
private List<User> seedPgMembers() {
|
||||
List<User> createdUsers = new ArrayList<>();
|
||||
UserRegistrationDTO user3dto = UserRegistrationDTO.builder()
|
||||
.email("david@test.com")
|
||||
.publicName("David N. Public")
|
||||
@@ -75,6 +133,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user3);
|
||||
UserRegistrationDTO user4dto = UserRegistrationDTO.builder()
|
||||
.email("davidm@test.com")
|
||||
.publicName("David M Public")
|
||||
@@ -88,6 +147,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user4);
|
||||
UserRegistrationDTO user5dto = UserRegistrationDTO.builder()
|
||||
.email("freddie@test.com")
|
||||
.publicName("Freddie Public")
|
||||
@@ -101,6 +161,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user5);
|
||||
UserRegistrationDTO user6dto = UserRegistrationDTO.builder()
|
||||
.email("elias@test.com")
|
||||
.publicName("Elias Public")
|
||||
@@ -114,6 +175,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user6);
|
||||
UserRegistrationDTO user7dto = UserRegistrationDTO.builder()
|
||||
.email("ibrahim@test.com")
|
||||
.publicName("Ibrahim Public")
|
||||
@@ -127,6 +189,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user7);
|
||||
UserRegistrationDTO user8dto = UserRegistrationDTO.builder()
|
||||
.email("lukas@test.com")
|
||||
.publicName("Lukas Public")
|
||||
@@ -140,6 +203,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user8);
|
||||
UserRegistrationDTO user9dto = UserRegistrationDTO.builder()
|
||||
.email("dennis@test.com")
|
||||
.publicName("Dennis Public")
|
||||
@@ -153,6 +217,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user9);
|
||||
UserRegistrationDTO user10dto = UserRegistrationDTO.builder()
|
||||
.email("daniel@test.com")
|
||||
.publicName("Daniel Public")
|
||||
@@ -166,6 +231,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user10);
|
||||
UserRegistrationDTO user11dto = UserRegistrationDTO.builder()
|
||||
.email("markus@test.com")
|
||||
.publicName("Markus Public")
|
||||
@@ -179,6 +245,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user11);
|
||||
UserRegistrationDTO user12dto = UserRegistrationDTO.builder()
|
||||
.email("piet@test.com")
|
||||
.publicName("Piet Public")
|
||||
@@ -192,5 +259,36 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
createdUsers.add(user12);
|
||||
return createdUsers;
|
||||
}
|
||||
|
||||
private void addDummyStats(User user) {
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"XP",
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"CO2_SAVED",
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"KM_CYCLED",
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"KM_WALKED",
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"KM_PUBLIC_TRANSPORT",
|
||||
0
|
||||
);
|
||||
userRepository.save(user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,5 +14,5 @@ public class AdHocSuggestionProperties {
|
||||
* Maximum time after which an uploaded trip is considered recent enough to send
|
||||
* an alternative routing suggestion for if available.
|
||||
*/
|
||||
private Integer recentTripThresholdSeconds = 60 * 60;
|
||||
private Integer recentTripThresholdSeconds = 60 * 60 * 6;
|
||||
}
|
||||
|
||||
@@ -14,4 +14,11 @@ public class RegularTripSuggestionProperties {
|
||||
* We keep it relatively short since regular trips have a time window.
|
||||
*/
|
||||
private Integer notifyBeforeMinutes = 15;
|
||||
|
||||
/**
|
||||
* Number of parallel threads to use for processing users concurrently when checking
|
||||
* for regular trip alternatives. Higher values increase throughput but consume more
|
||||
* resources (database connections, API rate limits, memory).
|
||||
*/
|
||||
private Integer parallelism = 10;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package SuMoC.backend.suggestion.dtos;
|
||||
|
||||
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
/**
|
||||
* This DTO extends RouteDTO and implements Notifieable to be used as the data body for notifications about route suggestions.
|
||||
* This allows us to use the saveAll method in NotificationSchedulerService for better performance when scheduling multiple notifications at once.
|
||||
*/
|
||||
public class RouteDTOtoBeNotified extends RouteDTO implements NotifieableWithTime {
|
||||
private Long userId;
|
||||
@Getter
|
||||
private LocalTime earliestTimeOfDayToSend;
|
||||
|
||||
public RouteDTOtoBeNotified(RouteDTO routeDTO, Long userId, LocalTime earliestTimeOfDayToSend) {
|
||||
super(
|
||||
routeDTO.getStartAddress(),
|
||||
routeDTO.getFirstStopName(),
|
||||
routeDTO.getStartLat(),
|
||||
routeDTO.getStartLon(),
|
||||
routeDTO.getEndAddress(),
|
||||
routeDTO.getLastStopName(),
|
||||
routeDTO.getEndLat(),
|
||||
routeDTO.getEndLon(),
|
||||
routeDTO.getStartDateTime(),
|
||||
routeDTO.getEndDateTime(),
|
||||
routeDTO.getSteps(),
|
||||
routeDTO.getCo2Savings(),
|
||||
routeDTO.getTimeDifferenceSeconds(),
|
||||
routeDTO.getCo2Emissions()
|
||||
);
|
||||
this.userId = userId;
|
||||
this.earliestTimeOfDayToSend = earliestTimeOfDayToSend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
package SuMoC.backend.suggestion.services;
|
||||
|
||||
|
||||
import SuMoC.backend.carrousel.service.CarrouselService;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.routing.services.RoutingService;
|
||||
import SuMoC.backend.suggestion.config.AdHocSuggestionProperties;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
@@ -23,7 +24,7 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class AdHocSuggestionService {
|
||||
|
||||
private final RoutingService routingService;
|
||||
private final AlternativeRoutingService alternativeRoutingService;
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
@@ -31,6 +32,8 @@ public class AdHocSuggestionService {
|
||||
|
||||
private final NotificationSchedulerService notificationSchedulerService;
|
||||
|
||||
private final CarrouselService carrouselService;
|
||||
|
||||
/**
|
||||
* Receives a trip a user has just uploaded, if it is a recent trip and there is a more sustainable alternative,
|
||||
* schedules a notification to push to the user.
|
||||
@@ -42,13 +45,16 @@ public class AdHocSuggestionService {
|
||||
return; // only suggest alternatives for trips mainly done by car, motorcycle or taxi
|
||||
}
|
||||
|
||||
var viableAlternatives = routingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip));
|
||||
var viableAlternatives = alternativeRoutingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip));
|
||||
|
||||
if (!viableAlternatives.isEmpty()) {
|
||||
// Since notification bodies have a size limit, we only send the best alternative
|
||||
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(newTrip.getUser().getId());
|
||||
List<RouteDTO> bestAlternatives = pickBestAlternatives(viableAlternatives, preferencesDTO);
|
||||
|
||||
// add all viable alternatives to carrousel candidates, so that they can be accessed in the app even after the notification is sent
|
||||
carrouselService.addAdHocTripCandidates(newTrip, bestAlternatives);
|
||||
|
||||
notificationSchedulerService.schedule(
|
||||
newTrip.getUser().getId(),
|
||||
bestAlternatives,
|
||||
|
||||
@@ -1,31 +1,45 @@
|
||||
package SuMoC.backend.suggestion.services;
|
||||
|
||||
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
||||
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
||||
import SuMoC.backend.carrousel.service.CarrouselService;
|
||||
import SuMoC.backend.h3.H3Service;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.routing.services.RoutingService;
|
||||
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
|
||||
import SuMoC.backend.suggestion.dtos.RouteDTOtoBeNotified;
|
||||
import com.uber.h3core.util.LatLng;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.LocalTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RegularTripSuggestionService {
|
||||
|
||||
private final RoutingService routingService;
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegularTripSuggestionService.class);
|
||||
|
||||
private final AlternativeRoutingService alternativeRoutingService;
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
@@ -37,6 +51,13 @@ public class RegularTripSuggestionService {
|
||||
|
||||
private final H3Service h3Service;
|
||||
|
||||
private final CarrouselService carrouselService;
|
||||
|
||||
private final CarrouselCandidateRepository carrouselCandidateRepository;
|
||||
|
||||
@Qualifier("regularTripSuggestionExecutor")
|
||||
private final Executor executor;
|
||||
|
||||
public void detectAndNotifyRegularTripsForTodaysDayOfWeek() {
|
||||
// detect
|
||||
DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
|
||||
@@ -47,37 +68,73 @@ public class RegularTripSuggestionService {
|
||||
}
|
||||
|
||||
public void checkAlternativesAndNotify(HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser) {
|
||||
logger.info("Processing {} users for regular trip alternatives in parallel", detectedRegularTripsByUser.size());
|
||||
|
||||
// Use thread-safe collections for parallel processing
|
||||
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist = new ConcurrentLinkedQueue<>();
|
||||
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify = new ConcurrentLinkedQueue<>();
|
||||
|
||||
// Create a CompletableFuture for each user to process in parallel
|
||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
||||
|
||||
for (Long userId : detectedRegularTripsByUser.keySet()) {
|
||||
var detectedRegularTrips = detectedRegularTripsByUser.get(userId);
|
||||
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
|
||||
|
||||
// For each detected regular trip, determine alternatives and notify the user if applicable
|
||||
for (var detectedRegularTrip : detectedRegularTrips) {
|
||||
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
|
||||
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
|
||||
|
||||
var bestAlternative = routingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
|
||||
// if present, schedule notification
|
||||
if (bestAlternative != null) {
|
||||
notificationSchedulerService.schedule(
|
||||
userId,
|
||||
bestAlternative,
|
||||
NotificationType.REGULAR_TRIP_ALTERNATIVE,
|
||||
detectedRegularTrip.getArrivalWindowEnd().minusMinutes(properties.getNotifyBeforeMinutes())
|
||||
);
|
||||
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
processUserTrips(userId, detectedRegularTrips, candidatesToPersist, alternativesToNotify);
|
||||
} catch (Exception e) {
|
||||
logger.error("Error processing regular trips for user {}: {}", userId, e.getMessage(), e);
|
||||
}
|
||||
}, executor);
|
||||
|
||||
futures.add(future);
|
||||
}
|
||||
|
||||
// Wait for all user processing tasks to complete
|
||||
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
|
||||
allFutures.join();
|
||||
|
||||
logger.info("Parallel processing completed. Persisting {} carrousel candidates and scheduling {} notifications",
|
||||
candidatesToPersist.size(), alternativesToNotify.size());
|
||||
|
||||
// Batch save all results
|
||||
carrouselCandidateRepository.saveAll(candidatesToPersist);
|
||||
notificationSchedulerService.scheduleAll(new ArrayList<>(alternativesToNotify), NotificationType.REGULAR_TRIP_ALTERNATIVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process all detected regular trips for a single user.
|
||||
* This method is designed to be called in parallel for multiple users.
|
||||
*/
|
||||
private void processUserTrips(Long userId, List<DetectedRegularTripDTO> detectedRegularTrips,
|
||||
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist,
|
||||
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify) {
|
||||
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
|
||||
|
||||
// For each detected regular trip, determine alternatives and notify the user if applicable
|
||||
for (var detectedRegularTrip : detectedRegularTrips) {
|
||||
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
|
||||
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
|
||||
|
||||
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
|
||||
// if present, schedule notification
|
||||
if (bestAlternative != null) {
|
||||
// save the alternative in the carrousel candidates so that it can be shown in the carrousel as well
|
||||
candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative)));
|
||||
|
||||
LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes());
|
||||
alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) {
|
||||
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
|
||||
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
|
||||
// we plan the trip to arrive at the average arrival time of the regular trip
|
||||
Instant arrivalTime = LocalDateTime.now()
|
||||
.with(trip.getAverageArrivalTime())
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toInstant();
|
||||
Instant arrivalTime = trip.getAverageArrivalTime();
|
||||
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
|
||||
|
||||
return RoutingAlternativeRequestDTO.builder()
|
||||
|
||||
@@ -2,6 +2,7 @@ package SuMoC.backend.trend;
|
||||
|
||||
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
||||
import SuMoC.backend.trend.models.WeeklyMobilityStatsId;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -13,4 +14,6 @@ public interface WeeklyMobilityStatsRepository extends JpaRepository<WeeklyMobil
|
||||
@Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
|
||||
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
|
||||
|
||||
void deleteAllByUser(User user);
|
||||
|
||||
}
|
||||
|
||||
@@ -10,9 +10,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -39,7 +37,12 @@ public class StatTableUpdateService {
|
||||
LocalDate weekEnd = weekStart.plusWeeks(1);
|
||||
LocalDateTime startDateTime = weekStart.atStartOfDay();
|
||||
LocalDateTime endDateTime = weekEnd.atStartOfDay();
|
||||
List<Trip> trips = tripRepository.findValidTripsInWeek(startDateTime, endDateTime);
|
||||
|
||||
// Convert LocalDateTime to Instant
|
||||
Instant startInstant = startDateTime.atZone(ZoneId.systemDefault()).toInstant();
|
||||
Instant endInstant = endDateTime.atZone(ZoneId.systemDefault()).toInstant();
|
||||
|
||||
List<Trip> trips = tripRepository.findValidTripsInWeek(startInstant, endInstant);
|
||||
|
||||
// Groupy trips by userId
|
||||
// TODO verify that we correctly set up the repository find method to avoid querying each trip's user separately (N+1 problem)
|
||||
|
||||
@@ -6,14 +6,12 @@ import SuMoC.backend.trip.dtos.NewTripDTO;
|
||||
import SuMoC.backend.trip.dtos.TripDTO;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -25,20 +23,14 @@ public class TripController {
|
||||
|
||||
private final TripService tripService;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final CurrentUserService currentUser;
|
||||
|
||||
private final AdHocSuggestionService adHocSuggestionService;
|
||||
|
||||
// TODO extend security context with user id to avoid unnecessary db query
|
||||
private User getAuthenticatedUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return userRepository.findByEmail(authentication.getName()).orElseThrow(() -> new RuntimeException("User not found"));
|
||||
}
|
||||
|
||||
@Operation(summary = "User uploads a new trip from the App.")
|
||||
@PostMapping("/uploadTrip")
|
||||
public ResponseEntity<Long> uploadTrip(@Valid @RequestBody NewTripDTO newTripDTO) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUser.get();
|
||||
Trip savedTrip = tripService.addTrip(user, newTripDTO);
|
||||
|
||||
// let the ad hoc service suggest an alternative more ecofriendly route if appropriate
|
||||
@@ -50,7 +42,7 @@ public class TripController {
|
||||
@Operation(summary = "Retrieve all trips of the authenticated user.")
|
||||
@GetMapping("/getAllUserTrips")
|
||||
public ResponseEntity<List<TripDTO>> getAllUserTrips() {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUser.get();
|
||||
|
||||
List<TripDTO> userTrips = tripService.getAllTripsOfUser(user);
|
||||
return ResponseEntity.ok(userTrips);
|
||||
@@ -59,7 +51,7 @@ public class TripController {
|
||||
@Operation(summary = "Validate a trip for the authenticated user.")
|
||||
@PutMapping("/validateTrip/{tripId}")
|
||||
public ResponseEntity<Void> validateTrip(@PathVariable Long tripId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUser.get();
|
||||
|
||||
tripService.validateTrip(user, tripId);
|
||||
return ResponseEntity.ok().build();
|
||||
@@ -68,10 +60,28 @@ public class TripController {
|
||||
@Operation(summary = "Invalidate a trip for the authenticated user.")
|
||||
@PutMapping("/invalidateTrip/{tripId}")
|
||||
public ResponseEntity<Void> invalidateTrip(@PathVariable Long tripId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUser.get();
|
||||
|
||||
tripService.invalidateTrip(user, tripId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete a trip for the authenticated user.")
|
||||
@DeleteMapping("/deleteTrip/{tripId}")
|
||||
public ResponseEntity<Void> deleteTrip(@PathVariable Long tripId) {
|
||||
User user = currentUser.get();
|
||||
|
||||
tripService.deleteTrip(user, tripId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete all trips of the authenticated user.")
|
||||
@DeleteMapping("/deleteAllTrips")
|
||||
public ResponseEntity<Void> deleteAllTrips() {
|
||||
User user = currentUser.get();
|
||||
|
||||
tripService.deleteAllTripsOfUser(user);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,6 +23,68 @@ public class TripFactory {
|
||||
return modalities[ThreadLocalRandom.current().nextInt(modalities.length)];
|
||||
}
|
||||
|
||||
/**
|
||||
* A dto for a car route for there have to be better sustainable alternatives available.
|
||||
*
|
||||
* @param startTime
|
||||
* @return
|
||||
*/
|
||||
public static NewTripDTO newTriggeringCarMock(Instant startTime) {
|
||||
String startPlace = "Essen Schuetzenbahn";
|
||||
String endPlace = "Essen Hbf";
|
||||
|
||||
Set<NewTripSegmentDTO> segments = Set.of(
|
||||
NewTripSegmentDTO.builder()
|
||||
.modality(Modality.CAR)
|
||||
.startTime(startTime)
|
||||
.distanceMeters(5000)
|
||||
.build()
|
||||
);
|
||||
|
||||
return NewTripDTO.builder()
|
||||
.startPlace(startPlace)
|
||||
.endPlace(endPlace)
|
||||
// Actual coordinates
|
||||
.startLatitude(51.45916748046875)
|
||||
.startLongitude(7.014928340911865)
|
||||
.endLatitude(51.451515197753906)
|
||||
.endLongitude(7.01484489440918)
|
||||
.co2Emissions(20.0)
|
||||
.startTime(startTime)
|
||||
.endTime(startTime.plus(Duration.ofMinutes(60)))
|
||||
.mobilityScore(50.0f)
|
||||
.tripSegments(segments)
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
public static NewTripDTO newCarTripDTO(Instant startTime) {
|
||||
String startPlace = "Cologne";
|
||||
String endPlace = "Düsseldorf";
|
||||
|
||||
Set<NewTripSegmentDTO> segments = Set.of(
|
||||
NewTripSegmentDTO.builder()
|
||||
.modality(Modality.CAR)
|
||||
.startTime(startTime)
|
||||
.distanceMeters(50000)
|
||||
.build()
|
||||
);
|
||||
|
||||
return NewTripDTO.builder()
|
||||
.startPlace(startPlace)
|
||||
.endPlace(endPlace)
|
||||
.startLatitude(51.4617108)
|
||||
.startLongitude(7.0170745)
|
||||
.endLatitude(51.2277411)
|
||||
.endLongitude(6.7734556)
|
||||
.co2Emissions(120.0)
|
||||
.startTime(startTime)
|
||||
.endTime(startTime.plus(Duration.ofMinutes(45)))
|
||||
.mobilityScore(75.0f)
|
||||
.tripSegments(segments)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a random NewTripDTO that always consists of two random segments that start at the given startTime,
|
||||
* take 2 hours in total, and have random start and end places from a predefined list of NRW cities.
|
||||
|
||||
@@ -9,7 +9,6 @@ import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -18,11 +17,13 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
|
||||
|
||||
Optional<List<Trip>> findAllByUser(User user);
|
||||
|
||||
void deleteAllByUser(User user);
|
||||
|
||||
@Query("SELECT trip FROM Trip trip " +
|
||||
"JOIN FETCH trip.user " +
|
||||
"JOIN FETCH trip.tripSegments " +
|
||||
"WHERE trip.invalidated = false AND trip.startTime >= :start AND trip.startTime < :end")
|
||||
List<Trip> findValidTripsInWeek(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
|
||||
List<Trip> findValidTripsInWeek(@Param("start") Instant start, @Param("end") Instant end);
|
||||
|
||||
default List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekday(
|
||||
Instant fromDate,
|
||||
@@ -32,12 +33,15 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
|
||||
DayOfWeekConverter converter = new DayOfWeekConverter();
|
||||
return findAllValidFromDateWithMainModalityOnCertainWeekdayInt(
|
||||
fromDate,
|
||||
modality,
|
||||
modality.toString(),
|
||||
converter.convertToDatabaseColumn(dayOfWeek)
|
||||
);
|
||||
}
|
||||
|
||||
@Query("SELECT t FROM Trip t WHERE t.invalidated = false AND t.startTime >= :fromDate AND t.mainModality = :modality AND FUNCTION('day_of_week', t.startTime) = :dayOfWeek")
|
||||
List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, Modality modality, int dayOfWeek);
|
||||
@Query(
|
||||
value = "SELECT * FROM trips t WHERE t.invalidated = false AND t.start_time >= :fromDate AND t.main_modality = :modality AND EXTRACT(DOW from t.start_time) = :dayOfWeek",
|
||||
nativeQuery = true
|
||||
)
|
||||
List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, String modality, int dayOfWeek);
|
||||
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -26,18 +28,20 @@ public class TripService {
|
||||
}
|
||||
|
||||
public void invalidateTrip(User user, Long tripId) {
|
||||
Trip trip = tripRepository.findById(tripId).orElseThrow();
|
||||
Trip trip = tripRepository.findById(tripId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
||||
if (!trip.getUser().equals(user)) {
|
||||
throw new RuntimeException("Trip does not belong to user");
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
||||
}
|
||||
trip.setInvalidated(true);
|
||||
tripRepository.save(trip);
|
||||
}
|
||||
|
||||
public void validateTrip(User user, Long tripId) {
|
||||
Trip trip = tripRepository.findById(tripId).orElseThrow();
|
||||
Trip trip = tripRepository.findById(tripId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
||||
if (!trip.getUser().equals(user)) {
|
||||
throw new RuntimeException("Trip does not belong to user");
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
||||
}
|
||||
trip.setInvalidated(false);
|
||||
tripRepository.save(trip);
|
||||
@@ -55,4 +59,17 @@ public class TripService {
|
||||
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
|
||||
return tripMapper.toTripDTOs(trips);
|
||||
}
|
||||
|
||||
public void deleteTrip(User user, Long tripId) {
|
||||
Trip trip = tripRepository.findById(tripId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
||||
if (!trip.getUser().equals(user)) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
||||
}
|
||||
tripRepository.delete(trip);
|
||||
}
|
||||
|
||||
public void deleteAllTripsOfUser(User user) {
|
||||
tripRepository.deleteAllByUser(user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package SuMoC.backend.trip.models;
|
||||
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -27,6 +29,7 @@ public class Trip {
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
@JsonBackReference("user-trips")
|
||||
private User user;
|
||||
|
||||
@Column(nullable = false)
|
||||
@@ -80,5 +83,6 @@ public class Trip {
|
||||
private Modality mainModality;
|
||||
|
||||
@OneToMany(mappedBy = "trip", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonManagedReference("trip-segments")
|
||||
private Set<TripSegment> tripSegments = new HashSet<>();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package SuMoC.backend.trip.models;
|
||||
|
||||
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -19,6 +20,7 @@ public class TripSegment {
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "trip_id", nullable = false)
|
||||
@JsonBackReference("trip-segments")
|
||||
private Trip trip;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
|
||||
@@ -6,13 +6,10 @@ import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.FriendshipService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -23,18 +20,13 @@ import java.util.concurrent.TimeUnit;
|
||||
public class FriendshipController {
|
||||
private final UserRepository userRepository;
|
||||
private final FriendshipService friendshipService;
|
||||
private final CurrentUserService currentUser;
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@Autowired
|
||||
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUser) {
|
||||
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUserService) {
|
||||
this.userRepository = userRepository;
|
||||
this.friendshipService = friendshipService;
|
||||
this.currentUser = currentUser;
|
||||
}
|
||||
|
||||
// TODO extend security context with user id to avoid unnecessary db query
|
||||
private User getAuthenticatedUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return userRepository.findByEmail(authentication.getName()).get();
|
||||
this.currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
@Operation(summary = "Return all friendships of the logged in user.",
|
||||
@@ -51,7 +43,7 @@ public class FriendshipController {
|
||||
""")
|
||||
@GetMapping("/all")
|
||||
public ResponseEntity<List<FriendshipDTO>> getFriendships() {
|
||||
User user = currentUser.get();
|
||||
User user = currentUserService.get();
|
||||
List<FriendshipDTO> friendships = friendshipService.getFriendships(user.getId());
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
|
||||
@@ -61,7 +53,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Return all accepted friends of the logged in user.", description = "Returns all friends with accepted status.")
|
||||
@GetMapping("/accepted")
|
||||
public ResponseEntity<List<FriendshipDTO>> getAcceptedFriendships() {
|
||||
User user = currentUser.get();
|
||||
User user = currentUserService.get();
|
||||
List<FriendshipDTO> friendships = friendshipService.getAcceptedFriendships(user.getId());
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
|
||||
@@ -71,7 +63,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Request a friendship with another user.", description = "Sends a friendship request to another user from the logged in user.")
|
||||
@PostMapping("/request/{friendId}")
|
||||
public ResponseEntity<Void> requestFriendship(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
checkSelfAction(user.getId(), friendId);
|
||||
friendshipService.requestFriendship(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
@@ -80,17 +72,15 @@ public class FriendshipController {
|
||||
@Operation(summary = "Request a friendship with another user by friend code.", description = "Sends a friendship request to another user identified by their friend code from the logged in user.")
|
||||
@PostMapping("/request/by-friendcode/{friendCode}")
|
||||
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
||||
User user = getAuthenticatedUser();
|
||||
User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow();
|
||||
checkSelfAction(user.getId(), requestedFriend.getId());
|
||||
friendshipService.requestFriendship(user, requestedFriend.getId());
|
||||
User user = currentUserService.get();
|
||||
friendshipService.requestFriendshipByFriendcode(user, friendCode);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Accept a friendship request.", description = "Accepts a pending friendship request for the logged in user from user with friendId.")
|
||||
@PostMapping("/accept/{friendId}")
|
||||
public ResponseEntity<Void> acceptFriendship(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.acceptFriendship(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -98,7 +88,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Reject a friendship request.", description = "Rejects a pending friendship request for the logged in user from user with friendId.")
|
||||
@PostMapping("/reject/{friendId}")
|
||||
public ResponseEntity<Void> rejectFriendship(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.rejectFriendship(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -106,7 +96,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Unfriend a user.", description = "Removes an accepted friendship between the logged in user and user with friendId.")
|
||||
@DeleteMapping("/unfriend/{friendId}")
|
||||
public ResponseEntity<Void> unfriend(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.unfriend(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -114,7 +104,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Block a user.", description = "Blocks the user with friendId for the logged in user.")
|
||||
@PostMapping("/block/{friendId}")
|
||||
public ResponseEntity<Void> blockUser(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
checkSelfAction(user.getId(), friendId);
|
||||
friendshipService.blockUser(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
@@ -123,7 +113,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Unblock a user.", description = "Unblocks the user with friendId for the logged in user.")
|
||||
@PostMapping("/unblock/{friendId}")
|
||||
public ResponseEntity<Void> unblockUser(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.unblockUser(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -131,7 +121,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Get all users the logged in user has blocked.", description = "Returns a list of all users that have been blocked by the logged in user.")
|
||||
@GetMapping("/blocked")
|
||||
public ResponseEntity<List<MinimalUserDTO>> blockedUsers() {
|
||||
User user = currentUser.get();
|
||||
User user = currentUserService.get();
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
|
||||
.body(friendshipService.getBlockedUsers(user.getId()));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.user.controller;
|
||||
|
||||
import SuMoC.backend.images.ImageRequestDTO;
|
||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||
import SuMoC.backend.user.dtos.AddStatRequestDTO;
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
@@ -7,6 +8,7 @@ import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.dtos.StatScope;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.service.UserService;
|
||||
import SuMoC.backend.user.stats.StatsList;
|
||||
import SuMoC.backend.user.stats.StatsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
@@ -103,7 +105,7 @@ public class UserController {
|
||||
})
|
||||
@PutMapping("/setPrivateName/{id}")
|
||||
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPrivateName) {
|
||||
@RequestParam @NotBlank String newPrivateName) {
|
||||
this.userService.setPrivateName(id, newPrivateName);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -121,7 +123,7 @@ public class UserController {
|
||||
})
|
||||
@PutMapping("/setPassword/{id}")
|
||||
public ResponseEntity<LoginResponseDTO> setPassword(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPassword) {
|
||||
@RequestParam @NotBlank String newPassword) {
|
||||
return new ResponseEntity<>(this.userService.setPassword(id, newPassword), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@@ -140,7 +142,7 @@ public class UserController {
|
||||
})
|
||||
@PutMapping("/setEmail/{id}")
|
||||
public ResponseEntity<LoginResponseDTO> setEmail(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newEmail) {
|
||||
@RequestParam @NotBlank String newEmail) {
|
||||
return new ResponseEntity<>(this.userService.setEmail(id, newEmail), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@@ -176,17 +178,33 @@ public class UserController {
|
||||
|
||||
StatScope scope = body.getScope();
|
||||
boolean awardBadges = body.getAwardBadges() == null || body.getAwardBadges();
|
||||
boolean awardChallenges = body.getAwardChallenges() == null || body.getAwardChallenges();
|
||||
|
||||
this.statsService.addStatsToCurrentUser(
|
||||
body.getStat(),
|
||||
body.getValue(),
|
||||
scope,
|
||||
awardBadges
|
||||
awardBadges,
|
||||
awardChallenges
|
||||
);
|
||||
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "get stats of current user",
|
||||
description = "Returns all stats of a user")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Stats were found",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = StatsList.class))),
|
||||
@ApiResponse(responseCode = "403", description = "Not authorized",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@RolesAllowed({"USER", "ADMIN"})
|
||||
@GetMapping("/stats")
|
||||
public ResponseEntity<StatsList> getStats() {
|
||||
StatsList stats = this.statsService.getStats();
|
||||
return ResponseEntity.ok().body(stats);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Add a profile Picture to the user.", description = "A user can add or update a profile picture to be displayed on his profile.")
|
||||
@@ -201,27 +219,54 @@ public class UserController {
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setProfilePicture/{id}")
|
||||
public ResponseEntity<Void> setProfilePicture(@RequestParam String base64ProfilePicture,
|
||||
public ResponseEntity<Void> setProfilePicture(@RequestBody ImageRequestDTO base64ProfilePicture,
|
||||
@PathVariable @NotNull Long id) {
|
||||
this.userService.setProfilePicture(id, base64ProfilePicture);
|
||||
this.userService.setProfilePicture(id, base64ProfilePicture.getBase64ProfilePicture());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get the profile Picture of the user.", description = "A user can get their displayed profile picture.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Profile picture successfully retrieved",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ImageRequestDTO.class))),
|
||||
@ApiResponse(responseCode = "304", description = "Profile picture not modified since last request"),
|
||||
@ApiResponse(responseCode = "403", description = "Only authorized persons may see the profiles picture"),
|
||||
@ApiResponse(responseCode = "404", description = "The user does not exist")
|
||||
})
|
||||
@GetMapping("/getProfilePicture/{id}")
|
||||
public ResponseEntity<String> getProfilePicture(@PathVariable @NotNull Long id) {
|
||||
String imageData = userService.getProfilePicture(id);
|
||||
@GetMapping(value = "/getProfilePicture/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
|
||||
ImageRequestDTO imageData = userService.getProfilePicture(id);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.IMAGE_JPEG)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
||||
.body(imageData);
|
||||
}
|
||||
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Long.class))),
|
||||
@ApiResponse(responseCode = "403", description = "Not authorized",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "The user does not exist",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@GetMapping("/getTotalXP")
|
||||
public ResponseEntity<Long> getTotalXP() {
|
||||
Long xp = userService.getTotalXP();
|
||||
return ResponseEntity.ok().body(xp);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete all mobility data of the authenticated user",
|
||||
description = "Deletes all trips (including trip segments), notifications, weekly mobility stats and carrousel candidates belonging to the current user.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "204", description = "Mobility data successfully deleted"),
|
||||
@ApiResponse(responseCode = "403", description = "Not authorized",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@DeleteMapping("/deleteMobilityData")
|
||||
public ResponseEntity<Void> deleteMobilityData() {
|
||||
this.userService.deleteMobilityData();
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ public class AddStatRequestDTO {
|
||||
|
||||
private Boolean awardBadges;
|
||||
|
||||
private Boolean awardChallenges;
|
||||
|
||||
public String getStat() { return stat; }
|
||||
public void setStat(String stat) { this.stat = stat; }
|
||||
|
||||
@@ -28,5 +30,8 @@ public class AddStatRequestDTO {
|
||||
public void setAwardBadges(Boolean awardBadges) { this.awardBadges = awardBadges; }
|
||||
public StatScope getScope() { return scope; }
|
||||
public void setScope(StatScope scope) { this.scope = scope; }
|
||||
|
||||
public Boolean getAwardChallenges() { return awardChallenges; }
|
||||
public void setAwardChallenges(Boolean awardChallenges) { this.awardChallenges = awardChallenges; }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package SuMoC.backend.user.dtos;
|
||||
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@@ -11,6 +13,8 @@ import java.time.Instant;
|
||||
* The MinimalUserDTO of the friend represents the friend depending on the relationship.
|
||||
* So only if friendship is accepted the private name of the friend is used as displayname.
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class FriendshipDTO {
|
||||
private Long friendshipId;
|
||||
private Long userId;
|
||||
@@ -29,43 +33,4 @@ public class FriendshipDTO {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Long getFriendshipId() {
|
||||
return friendshipId;
|
||||
}
|
||||
|
||||
public void setFriendshipId(Long friendshipId) {
|
||||
this.friendshipId = friendshipId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public MinimalUserDTO getFriend() {
|
||||
return friend;
|
||||
}
|
||||
|
||||
public void setFriend(MinimalUserDTO friend) {
|
||||
this.friend = friend;
|
||||
}
|
||||
|
||||
public FriendShipStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(FriendShipStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,20 @@ public class MaximalUserDTO {
|
||||
private Set<Friendship> friendships;
|
||||
private String base64ProfilePicture;
|
||||
|
||||
public String getFriendCode() {
|
||||
return friendCode;
|
||||
}
|
||||
|
||||
public void setFriendCode(String friendCode) {
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
private String friendCode;
|
||||
|
||||
public MaximalUserDTO() {
|
||||
}
|
||||
|
||||
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships, String base64ProfilePicture) {
|
||||
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships, String friendCode,String base64ProfilePicture) {
|
||||
this.id = id;
|
||||
this.publicName = publicName;
|
||||
this.privateName = privateName;
|
||||
@@ -35,6 +45,7 @@ public class MaximalUserDTO {
|
||||
this.trips = trips;
|
||||
this.friendships = friendships;
|
||||
this.base64ProfilePicture = base64ProfilePicture;
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -9,14 +9,14 @@ public class UserDTO {
|
||||
private String privateName;
|
||||
private String publicName;
|
||||
private Set<RoleName> roles;
|
||||
private String friendCode;
|
||||
|
||||
|
||||
|
||||
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles){
|
||||
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles, String friendCode) {
|
||||
this.userId = userId;
|
||||
this.privateName = privateName;
|
||||
this.publicName = publicName;
|
||||
this.roles = roles;
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
public UserDTO(){}
|
||||
@@ -57,4 +57,13 @@ public class UserDTO {
|
||||
public void setPublicName(String publicName) {
|
||||
this.publicName = publicName;
|
||||
}
|
||||
|
||||
public String getFriendCode() {
|
||||
return friendCode;
|
||||
}
|
||||
|
||||
public void setFriendCode(String friendCode) {
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,7 +15,16 @@ public interface UserMapper {
|
||||
User toUser(UserDTO userDTO);
|
||||
|
||||
static MaximalUserDTO toMaximalUserDTO(User user) {
|
||||
MaximalUserDTO maximalUserDTO = new MaximalUserDTO(
|
||||
// Force-initialize lazy collections while session is still open
|
||||
user.getTrips().size();
|
||||
user.getFriendships().size();
|
||||
|
||||
String base64Image = null;
|
||||
if (user.getProfileImage() != null && user.getProfileImage().getImageData() != null) {
|
||||
base64Image = ImageBase64Util.encode(user.getProfileImage().getImageData());
|
||||
}
|
||||
|
||||
return new MaximalUserDTO(
|
||||
user.getId(),
|
||||
user.getPublicName(),
|
||||
user.getPrivateName(),
|
||||
@@ -23,9 +32,9 @@ public interface UserMapper {
|
||||
user.getVisibilityPrivacy(),
|
||||
user.getTrips(),
|
||||
user.getFriendships(),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
user.getFriendCode(),
|
||||
base64Image
|
||||
);
|
||||
return maximalUserDTO;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package SuMoC.backend.user.models;
|
||||
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -26,10 +27,12 @@ public class Friendship {
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
@JsonBackReference("user-friendships")
|
||||
private User user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "friend_id", nullable = false)
|
||||
@JsonBackReference("friend-friendships")
|
||||
private User friend;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
|
||||
@@ -7,6 +7,7 @@ import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.enums.RoleName;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.stats.StatsList;
|
||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Setter;
|
||||
|
||||
@@ -43,10 +44,11 @@ public class User {
|
||||
@Column(nullable = false)
|
||||
private VisibilityPrivacy visibilityPrivacy;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 36)
|
||||
@Column(nullable = false, unique = true, length = 24)
|
||||
private String friendCode;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonManagedReference("user-trips")
|
||||
private Set<Trip> trips = new HashSet<>();
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@@ -59,24 +61,25 @@ public class User {
|
||||
@Column(name = "role")
|
||||
private Set<RoleName> roles = new HashSet<>();
|
||||
|
||||
@OneToOne
|
||||
@OneToOne(cascade = CascadeType.REMOVE, orphanRemoval = true)
|
||||
@JoinColumn(name = "id", referencedColumnName = "user_id")
|
||||
private NotificationToken notificationToken;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
private Set<UserBadge> badges = new HashSet<>();
|
||||
|
||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private StatsList statsList;
|
||||
|
||||
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JoinColumn(name = "routing_preferences_id", unique = true)
|
||||
private RoutingPreferences routingPreferences;
|
||||
|
||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private ProfileImageEntity profileImage;
|
||||
|
||||
public User() {}
|
||||
public User() {
|
||||
}
|
||||
|
||||
// public User(Long id, String publicName, String privateName, String email, String password, VisibilityPrivacy visibilityPrivacy, String friendCode, Set<Trip> trips, Set<Friendship> friendships, Set<RoleName> roles) {
|
||||
// this.id = id;
|
||||
@@ -97,18 +100,19 @@ public class User {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.visibilityPrivacy = VisibilityPrivacy.NONE;
|
||||
this.friendCode = java.util.UUID.randomUUID().toString(); // generate unique friend code
|
||||
this.friendCode = generateFriendCode(); // generate unique friend code
|
||||
this.routingPreferences = RoutingPreferences.getDefaultPreferences(); // Init with default routing preferences
|
||||
this.roles.add(RoleName.USER);
|
||||
this.statsList = new StatsList(this);
|
||||
|
||||
this.profileImage = new ProfileImageEntity();
|
||||
this.profileImage.setUser(this); }
|
||||
this.profileImage.setUser(this);
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
private void ensureFriendCode() {
|
||||
if (this.friendCode == null) {
|
||||
this.friendCode = UUID.randomUUID().toString();
|
||||
this.friendCode = generateFriendCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,4 +231,25 @@ public class User {
|
||||
public void setProfileImage(ProfileImageEntity profileImage) {
|
||||
this.profileImage = profileImage;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Friendcode generator
|
||||
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final java.security.SecureRandom RANDOM = new java.security.SecureRandom();
|
||||
|
||||
private String generateFriendCode() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (int group = 0; group < 5; group++) {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
sb.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
|
||||
}
|
||||
if (group < 4) {
|
||||
sb.append("-");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user