Compare commits
44
Commits
| 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 |
Vendored
+15
-3
@@ -2,6 +2,13 @@
|
|||||||
|
|
||||||
// this groovy script is executed by jenkins
|
// this groovy script is executed by jenkins
|
||||||
node('built-in') {
|
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
|
// checkout code from scm
|
||||||
stage('Checkout') {
|
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 docker-load.sh pg-sumoc@apps-dev.nes:~'
|
||||||
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
||||||
echo "Resetting database..."
|
echo "Resetting database..."
|
||||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
if (RESET_DB) {
|
||||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
|
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
||||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
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 ..."
|
echo "Load docker images on server ..."
|
||||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
||||||
echo "Restarting docker containers on server ..."
|
echo "Restarting docker containers on server ..."
|
||||||
|
|||||||
+1
-1
@@ -44,7 +44,7 @@ services:
|
|||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
restart: always
|
restart: unless-stopped
|
||||||
|
|
||||||
# nominatim:
|
# nominatim:
|
||||||
# image: mediagis/nominatim:5.2
|
# image: mediagis/nominatim:5.2
|
||||||
|
|||||||
+62
-17
@@ -650,7 +650,7 @@ paths:
|
|||||||
summary: 'Veränderung des Passworts eines Profils '
|
summary: 'Veränderung des Passworts eines Profils '
|
||||||
description: Durch Eingabe eines Validen OTP Codes zu einer zugehörigen Email
|
description: Durch Eingabe eines Validen OTP Codes zu einer zugehörigen Email
|
||||||
kann das Passwort des Profils geändert werden.
|
kann das Passwort des Profils geändert werden.
|
||||||
operationId: handlePasswordResetRequest
|
operationId: resetPassword
|
||||||
requestBody:
|
requestBody:
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
@@ -664,7 +664,7 @@ paths:
|
|||||||
'*/*':
|
'*/*':
|
||||||
schema:
|
schema:
|
||||||
type: string
|
type: string
|
||||||
/auth/user/request-password-reset:
|
/auth/user/request-otp-for-password-reset:
|
||||||
post:
|
post:
|
||||||
tags:
|
tags:
|
||||||
- user-authentication-controller
|
- user-authentication-controller
|
||||||
@@ -672,12 +672,12 @@ paths:
|
|||||||
description: "Erstellt bei Anfrage einen neuen 6-stelligen OTP Code, mit welchem\
|
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\
|
\ das Passwort des Accounts mit der zugehörigen Email einmalig verändert werden\
|
||||||
\ kann. Dieser wird per Mail an den Nutzer gesendet."
|
\ kann. Dieser wird per Mail an den Nutzer gesendet."
|
||||||
operationId: handleForgotPasswordRequest
|
operationId: requestOtpForPasswordReset
|
||||||
requestBody:
|
requestBody:
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
type: string
|
$ref: "#/components/schemas/OtpRequestDTO"
|
||||||
required: true
|
required: true
|
||||||
responses:
|
responses:
|
||||||
"200":
|
"200":
|
||||||
@@ -852,19 +852,19 @@ paths:
|
|||||||
"304":
|
"304":
|
||||||
description: Profile picture not modified since last request
|
description: Profile picture not modified since last request
|
||||||
content:
|
content:
|
||||||
'*/*':
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
$ref: "#/components/schemas/ImageRequestDTO"
|
||||||
"403":
|
"403":
|
||||||
description: Only authorized persons may see the profiles picture
|
description: Only authorized persons may see the profiles picture
|
||||||
content:
|
content:
|
||||||
'*/*':
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
$ref: "#/components/schemas/ImageRequestDTO"
|
||||||
"404":
|
"404":
|
||||||
description: The user does not exist
|
description: The user does not exist
|
||||||
content:
|
content:
|
||||||
'*/*':
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
$ref: "#/components/schemas/ImageRequestDTO"
|
||||||
/trip/getAllUserTrips:
|
/trip/getAllUserTrips:
|
||||||
@@ -1384,6 +1384,21 @@ paths:
|
|||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
$ref: "#/components/schemas/BadgeDTO"
|
$ref: "#/components/schemas/BadgeDTO"
|
||||||
|
/user/deleteMobilityData:
|
||||||
|
delete:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
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."
|
||||||
|
operationId: deleteMobilityData
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: Mobility data successfully deleted
|
||||||
|
"403":
|
||||||
|
description: Not authorized
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
/user/delete/{id}:
|
/user/delete/{id}:
|
||||||
delete:
|
delete:
|
||||||
tags:
|
tags:
|
||||||
@@ -1418,6 +1433,31 @@ paths:
|
|||||||
'*/*':
|
'*/*':
|
||||||
schema:
|
schema:
|
||||||
type: object
|
type: object
|
||||||
|
/trip/deleteTrip/{tripId}:
|
||||||
|
delete:
|
||||||
|
tags:
|
||||||
|
- trip-controller
|
||||||
|
summary: Delete a trip for the authenticated user.
|
||||||
|
operationId: deleteTrip
|
||||||
|
parameters:
|
||||||
|
- name: tripId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/trip/deleteAllTrips:
|
||||||
|
delete:
|
||||||
|
tags:
|
||||||
|
- trip-controller
|
||||||
|
summary: Delete all trips of the authenticated user.
|
||||||
|
operationId: deleteAllTrips
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
/friendship/unfriend/{friendId}:
|
/friendship/unfriend/{friendId}:
|
||||||
delete:
|
delete:
|
||||||
tags:
|
tags:
|
||||||
@@ -1810,14 +1850,14 @@ components:
|
|||||||
description: The temporal difference in minutes compared to the original
|
description: The temporal difference in minutes compared to the original
|
||||||
route (in case alternative was requested) / the car route (when simply
|
route (in case alternative was requested) / the car route (when simply
|
||||||
directions requested) .
|
directions requested) .
|
||||||
|
physicalActivity:
|
||||||
|
type: boolean
|
||||||
durationSeconds:
|
durationSeconds:
|
||||||
type: integer
|
type: integer
|
||||||
format: int64
|
format: int64
|
||||||
walkingRoute:
|
|
||||||
type: boolean
|
|
||||||
cyclingRoute:
|
cyclingRoute:
|
||||||
type: boolean
|
type: boolean
|
||||||
physicalActivity:
|
walkingRoute:
|
||||||
type: boolean
|
type: boolean
|
||||||
StepDTO:
|
StepDTO:
|
||||||
type: object
|
type: object
|
||||||
@@ -1894,11 +1934,16 @@ components:
|
|||||||
PasswordResetDTO:
|
PasswordResetDTO:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
otp_code:
|
otpCode:
|
||||||
type: string
|
type: string
|
||||||
email:
|
email:
|
||||||
type: string
|
type: string
|
||||||
new_password:
|
newPassword:
|
||||||
|
type: string
|
||||||
|
OtpRequestDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
email:
|
||||||
type: string
|
type: string
|
||||||
UserRegistrationDTO:
|
UserRegistrationDTO:
|
||||||
type: object
|
type: object
|
||||||
@@ -1949,7 +1994,10 @@ components:
|
|||||||
km_PUBLIC_TRANSPORT:
|
km_PUBLIC_TRANSPORT:
|
||||||
type: integer
|
type: integer
|
||||||
format: int64
|
format: int64
|
||||||
xp:
|
mobility_SCORE:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
co2_SAVED:
|
||||||
type: integer
|
type: integer
|
||||||
format: int64
|
format: int64
|
||||||
km_CYCLED:
|
km_CYCLED:
|
||||||
@@ -1961,10 +2009,7 @@ components:
|
|||||||
km_DRIVEN:
|
km_DRIVEN:
|
||||||
type: integer
|
type: integer
|
||||||
format: int64
|
format: int64
|
||||||
mobility_SCORE:
|
xp:
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
co2_SAVED:
|
|
||||||
type: integer
|
type: integer
|
||||||
format: int64
|
format: int64
|
||||||
StatsList:
|
StatsList:
|
||||||
|
|||||||
@@ -149,6 +149,14 @@
|
|||||||
<artifactId>h3</artifactId>
|
<artifactId>h3</artifactId>
|
||||||
<version>4.4.0</version>
|
<version>4.4.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-core</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-database-postgresql</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -17,4 +17,6 @@ public interface CarrouselCandidateRepository extends JpaRepository<CarrouselCan
|
|||||||
ORDER BY c.suggestedAt DESC
|
ORDER BY c.suggestedAt DESC
|
||||||
""")
|
""")
|
||||||
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
|
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
|
||||||
|
|
||||||
|
void deleteAllByUserId(Long userId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package SuMoC.backend.firebase;
|
package SuMoC.backend.firebase;
|
||||||
|
|
||||||
import SuMoC.backend.notification.models.Notification;
|
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 com.google.firebase.messaging.Message;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -11,6 +14,21 @@ public class FirebaseMessageBuilder {
|
|||||||
var builder = Message.builder().setToken(token);
|
var builder = Message.builder().setToken(token);
|
||||||
builder.putData("type", notification.getType().toString());
|
builder.putData("type", notification.getType().toString());
|
||||||
builder.putData("data", notification.getData());
|
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();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,11 +34,11 @@ public interface ChallengeMapper {
|
|||||||
challenge.setCriteria(dto.getCriteria());
|
challenge.setCriteria(dto.getCriteria());
|
||||||
challenge.setReward(dto.getReward());
|
challenge.setReward(dto.getReward());
|
||||||
|
|
||||||
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
|
if (dto.getBase64image() != null && !dto.getBase64image().isBlank()) {
|
||||||
challenge.setImage(new ChallengeImageEntity(
|
byte[] bytes = ImageBase64Util.decode(dto.getBase64image());
|
||||||
challenge,
|
ChallengeImageEntity img = new ChallengeImageEntity();
|
||||||
ImageBase64Util.decode(dto.getBase64image())
|
img.setImageData(bytes);
|
||||||
));
|
challenge.setImage(img);
|
||||||
}
|
}
|
||||||
|
|
||||||
return challenge;
|
return challenge;
|
||||||
|
|||||||
@@ -85,6 +85,9 @@ public class Challenge {
|
|||||||
|
|
||||||
public void setImage(ChallengeImageEntity image) {
|
public void setImage(ChallengeImageEntity image) {
|
||||||
this.image = image;
|
this.image = image;
|
||||||
|
if (image != null) {
|
||||||
|
image.setChallenge(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getCriteria() {
|
public Map<String, Integer> getCriteria() {
|
||||||
|
|||||||
@@ -10,8 +10,9 @@ public class ImageEntity {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private int id;
|
private int id;
|
||||||
|
|
||||||
@Lob
|
//@Lob
|
||||||
//@Column(columnDefinition = "BYTEA")
|
@Basic(fetch = FetchType.EAGER)
|
||||||
|
@Column(columnDefinition = "bytea")
|
||||||
//@Column(columnDefinition = "BLOB")
|
//@Column(columnDefinition = "BLOB")
|
||||||
private byte[] imageData;
|
private byte[] imageData;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package SuMoC.backend.notification.repositories;
|
package SuMoC.backend.notification.repositories;
|
||||||
|
|
||||||
import SuMoC.backend.notification.models.Notification;
|
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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Modifying;
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
@@ -36,4 +37,6 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
|
|||||||
WHERE n.createdAt < :cutOff
|
WHERE n.createdAt < :cutOff
|
||||||
""")
|
""")
|
||||||
void deleteNotificationsOlder(Instant cutOff);
|
void deleteNotificationsOlder(Instant cutOff);
|
||||||
|
|
||||||
|
void deleteAllByUser(User user);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,7 @@ import SuMoC.backend.trip.Modality;
|
|||||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
import java.time.DayOfWeek;
|
import java.time.*;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.LocalTime;
|
|
||||||
import java.time.ZoneOffset;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -68,13 +65,13 @@ public class DetectedRegularTripDTO {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getAverageArrivalTime() {
|
public Instant getAverageArrivalTime() {
|
||||||
int totalSeconds = 0;
|
long totalSeconds = 0;
|
||||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||||
totalSeconds += trip.getEndTime().atOffset(ZoneOffset.UTC).toLocalTime().toSecondOfDay();
|
totalSeconds += trip.getEndTime().getEpochSecond();
|
||||||
}
|
}
|
||||||
int averageSeconds = totalSeconds / supportingTrips.size();
|
long averageSeconds = totalSeconds / supportingTrips.size();
|
||||||
return LocalTime.ofSecondOfDay(averageSeconds);
|
return Instant.ofEpochSecond(averageSeconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getAverageDurationMinutes() {
|
public int getAverageDurationMinutes() {
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
private LocalTime arrivalWindowStart;
|
private LocalTime arrivalWindowStart;
|
||||||
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
|
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
|
||||||
private LocalTime arrivalWindowEnd;
|
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 startH3Center;
|
||||||
private String endH3Center;
|
private String endH3Center;
|
||||||
|
|
||||||
@@ -41,12 +43,15 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
|
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
|
||||||
minimalDTO.startH3Center = regularTrip.getStartH3Center();
|
minimalDTO.startH3Center = regularTrip.getStartH3Center();
|
||||||
minimalDTO.endH3Center = regularTrip.getEndH3Center();
|
minimalDTO.endH3Center = regularTrip.getEndH3Center();
|
||||||
|
minimalDTO.supportingTripIds = regularTrip.getSupportingTrips().stream()
|
||||||
|
.map(RegularTripDetectionDTO::getTripId)
|
||||||
|
.toList();
|
||||||
return minimalDTO;
|
return minimalDTO;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var earliest = supportingTrips.stream()
|
var earliest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getStartTime)
|
.map(RegularTripDetectionDTO::getEndTime)
|
||||||
.min(Comparator.naturalOrder())
|
.min(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||||
@@ -54,7 +59,7 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
|
|
||||||
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var latest = supportingTrips.stream()
|
var latest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getStartTime)
|
.map(RegularTripDetectionDTO::getEndTime)
|
||||||
.max(Comparator.naturalOrder())
|
.max(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||||
@@ -62,7 +67,7 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
|
|
||||||
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var earliest = supportingTrips.stream()
|
var earliest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getEndTime)
|
.map(RegularTripDetectionDTO::getStartTime)
|
||||||
.min(Comparator.naturalOrder())
|
.min(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||||
@@ -70,7 +75,7 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
|
|
||||||
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var latest = supportingTrips.stream()
|
var latest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getEndTime)
|
.map(RegularTripDetectionDTO::getStartTime)
|
||||||
.max(Comparator.naturalOrder())
|
.max(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||||
|
|||||||
@@ -82,14 +82,16 @@ public class AlternativeFilterService {
|
|||||||
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
|
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
|
||||||
for (RouteDTO route : alternatives) {
|
for (RouteDTO route : alternatives) {
|
||||||
if (route.isPhysicalActivity()) {
|
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());
|
var weatherConditions = forecast.getWeatherConditionsBetween(route.getStartDateTime(), route.getEndDateTime());
|
||||||
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
|
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
|
||||||
filteredAlternatives.add(route);
|
filteredAlternatives.add(route);
|
||||||
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
|
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
|
||||||
filteredAlternatives.add(route);
|
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 {
|
} else {
|
||||||
filteredAlternatives.add(route);
|
filteredAlternatives.add(route);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,9 +102,11 @@ public class UserAuthenticationController {
|
|||||||
authenticationService.resetPassword(passwordResetDTO);
|
authenticationService.resetPassword(passwordResetDTO);
|
||||||
return ResponseEntity.ok("Passwort erfolgreich geändert");
|
return ResponseEntity.ok("Passwort erfolgreich geändert");
|
||||||
} catch (InvalidTokenException | UsernameNotFoundException e) {
|
} catch (InvalidTokenException | UsernameNotFoundException e) {
|
||||||
|
e.printStackTrace();
|
||||||
return ResponseEntity.badRequest().body(e.getMessage());
|
return ResponseEntity.badRequest().body(e.getMessage());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Fehler beim Zurücksetzen des Passworts");
|
e.printStackTrace();
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package SuMoC.backend.security.dtos;
|
package SuMoC.backend.security.dtos;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -8,7 +9,9 @@ import lombok.Setter;
|
|||||||
@Setter
|
@Setter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class PasswordResetDTO {
|
public class PasswordResetDTO {
|
||||||
String otp_code;
|
@JsonAlias({"otp_code", "otpCode"})
|
||||||
|
String otpCode;
|
||||||
String email;
|
String email;
|
||||||
String new_password;
|
@JsonAlias({"new_password", "newPassword"})
|
||||||
|
String newPassword;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,12 +17,12 @@ public class PasswordResetToken{
|
|||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
private String email;
|
private String email;
|
||||||
private String otp_code;
|
private String otpCode;
|
||||||
private LocalDateTime expiryDate;
|
private LocalDateTime expiryDate;
|
||||||
|
|
||||||
public PasswordResetToken(String email, String code) {
|
public PasswordResetToken(String email, String code) {
|
||||||
this.email = email;
|
this.email = email;
|
||||||
this.otp_code = code;
|
this.otpCode = code;
|
||||||
this.expiryDate = LocalDateTime.now().plusMinutes(EXPIRY_TIME_MINUTES);
|
this.expiryDate = LocalDateTime.now().plusMinutes(EXPIRY_TIME_MINUTES);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ import SuMoC.backend.user.models.User;
|
|||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
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.mail.MailException;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
@@ -155,7 +153,6 @@ public class AuthenticationService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
String otp = generate_six_digit_OTP();
|
String otp = generate_six_digit_OTP();
|
||||||
|
|
||||||
passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp
|
passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp
|
||||||
emailService.sendPasswordResetEmail(email, otp);
|
emailService.sendPasswordResetEmail(email, otp);
|
||||||
}
|
}
|
||||||
@@ -171,18 +168,17 @@ public class AuthenticationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//use .matches() so compare raw otp to (salted!) encoded otp
|
//use .matches() so compare raw otp to (salted!) encoded otp
|
||||||
if(!passwordEncoder.matches(passwordResetDTO.getOtp_code(),token.getOtp_code())){
|
if(!passwordEncoder.matches(passwordResetDTO.getOtpCode(),token.getOtpCode())){
|
||||||
throw new InvalidTokenException("Code ist ungültig");
|
throw new InvalidTokenException("Code ist ungültig");
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!isPasswordFormatCorrect(passwordResetDTO.getNew_password())) {
|
if(!isPasswordFormatCorrect(passwordResetDTO.getNewPassword())) {
|
||||||
throw new InvalidTokenException("Passwortformat ist nicht korrekt");
|
throw new InvalidTokenException("Passwortformat ist nicht korrekt");
|
||||||
}
|
}
|
||||||
|
|
||||||
User user = userRepository.findByEmail(passwordResetDTO.getEmail())
|
User user = userRepository.findByEmail(passwordResetDTO.getEmail())
|
||||||
.orElseThrow(() -> new UsernameNotFoundException("User existiert nicht"));
|
.orElseThrow(() -> new UsernameNotFoundException("User existiert nicht"));
|
||||||
|
user.setPassword(passwordEncoder.encode(passwordResetDTO.getNewPassword()));
|
||||||
user.setPassword(passwordEncoder.encode(passwordResetDTO.getNew_password()));
|
|
||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
passwordResetTokenRepository.delete(token);
|
passwordResetTokenRepository.delete(token);
|
||||||
}
|
}
|
||||||
|
|||||||
+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.mapper.BadgeMapper;
|
||||||
import SuMoC.backend.gamification.badges.models.Badge;
|
|
||||||
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
||||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import kotlin.collections.ArrayDeque;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.CommandLineRunner;
|
import org.springframework.boot.CommandLineRunner;
|
||||||
import org.springframework.context.annotation.Profile;
|
import org.springframework.context.annotation.Profile;
|
||||||
@@ -16,7 +16,7 @@ import java.util.*;
|
|||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Profile("dev")
|
@Profile("dev")
|
||||||
@Order(3)
|
@Order(2)
|
||||||
public class DevBadgeSeeder implements CommandLineRunner {
|
public class DevBadgeSeeder implements CommandLineRunner {
|
||||||
|
|
||||||
private final BadgeService badgeService;
|
private final BadgeService badgeService;
|
||||||
@@ -8,13 +8,15 @@ import jakarta.transaction.Transactional;
|
|||||||
import org.springframework.boot.CommandLineRunner;
|
import org.springframework.boot.CommandLineRunner;
|
||||||
import org.springframework.context.annotation.Profile;
|
import org.springframework.context.annotation.Profile;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.core.io.ClassPathResource;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Profile("dev")
|
@Profile("dev")
|
||||||
@Order(4)
|
@Order(3)
|
||||||
public class DevChallengeSeeder implements CommandLineRunner {
|
public class DevChallengeSeeder implements CommandLineRunner {
|
||||||
|
|
||||||
private final ChallengeService challengeService;
|
private final ChallengeService challengeService;
|
||||||
@@ -31,6 +33,7 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public void run(String... args) {
|
public void run(String... args) {
|
||||||
|
final String dummyImageBase64 = loadBase64FromClasspath("images/ChallengeDummy.png");
|
||||||
List<Seed> seeds = generateSeeds();
|
List<Seed> seeds = generateSeeds();
|
||||||
|
|
||||||
for (Seed seed : seeds) {
|
for (Seed seed : seeds) {
|
||||||
@@ -38,20 +41,20 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
.map(ChallengeMapper::toDTO)
|
.map(ChallengeMapper::toDTO)
|
||||||
.ifPresentOrElse(
|
.ifPresentOrElse(
|
||||||
existingChallenge -> {
|
existingChallenge -> {
|
||||||
// Update existing challenge
|
|
||||||
existingChallenge.setName(seed.name());
|
existingChallenge.setName(seed.name());
|
||||||
existingChallenge.setDescription(seed.description());
|
existingChallenge.setDescription(seed.description());
|
||||||
existingChallenge.setCriteria(seed.criteria());
|
existingChallenge.setCriteria(seed.criteria());
|
||||||
existingChallenge.setReward(seed.reward());
|
existingChallenge.setReward(seed.reward());
|
||||||
|
existingChallenge.setBase64image(dummyImageBase64);
|
||||||
challengeService.modifyChallenge(existingChallenge);
|
challengeService.modifyChallenge(existingChallenge);
|
||||||
},
|
},
|
||||||
() -> {
|
() -> {
|
||||||
// Create new challenge
|
|
||||||
ChallengeDTO newChallenge = new ChallengeDTO();
|
ChallengeDTO newChallenge = new ChallengeDTO();
|
||||||
newChallenge.setName(seed.name());
|
newChallenge.setName(seed.name());
|
||||||
newChallenge.setDescription(seed.description());
|
newChallenge.setDescription(seed.description());
|
||||||
newChallenge.setCriteria(seed.criteria());
|
newChallenge.setCriteria(seed.criteria());
|
||||||
newChallenge.setReward(seed.reward());
|
newChallenge.setReward(seed.reward());
|
||||||
|
newChallenge.setBase64image(dummyImageBase64);
|
||||||
challengeService.createChallenge(newChallenge);
|
challengeService.createChallenge(newChallenge);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -60,6 +63,15 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
challengeService.weeklyChallengeScheduler();
|
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 record Seed(String name, String description, Map<String, Integer> criteria, Integer reward) {}
|
||||||
|
|
||||||
private static Seed seed(
|
private static Seed seed(
|
||||||
|
|||||||
@@ -1,57 +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 + adds car trips for every day at same time
|
|
||||||
userRepository.findAll().forEach(user -> {
|
|
||||||
for (int week = 0; week < 5; week++) {
|
|
||||||
for (int day = 0; day < 7; day++) {
|
|
||||||
// NewTripDTO carTrip = TripFactory.newCarTripDTO(
|
|
||||||
// Instant.now()
|
|
||||||
// .minus(Duration.ofDays(week * 7 + day)).atZone(ZoneId.systemDefault()).toInstant()
|
|
||||||
// );
|
|
||||||
// This should definitly trigger regularTripDetection
|
|
||||||
NewTripDTO triggerCarTrip = TripFactory.newTriggeringCarMock(
|
|
||||||
java.time.Instant.now().minus(java.time.Duration.ofDays(week * 7 + day))
|
|
||||||
);
|
|
||||||
tripService.addTrip(user, triggerCarTrip);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create 5 trips per 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);
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -13,6 +13,7 @@ import org.springframework.boot.CommandLineRunner;
|
|||||||
import org.springframework.context.annotation.Profile;
|
import org.springframework.context.annotation.Profile;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -39,17 +40,18 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@Transactional
|
||||||
public void run(String... args) throws Exception {
|
public void run(String... args) throws Exception {
|
||||||
List<User> pgMembers = seedPgMembers();
|
List<User> pgMembers = seedPgMembers();
|
||||||
List<User> defaultTestUsers = seedDefaultTestUsers();
|
List<User> defaultTestUsers = seedDefaultTestUsers();
|
||||||
|
|
||||||
Long positionIndex = 1L;
|
Long positionIndex = 1L;
|
||||||
for (var user : pgMembers) {
|
for (var user : pgMembers) {
|
||||||
addDummyStats(user, positionIndex);
|
addDummyStats(user);
|
||||||
positionIndex++;
|
positionIndex++;
|
||||||
}
|
}
|
||||||
for (var user : defaultTestUsers) {
|
for (var user : defaultTestUsers) {
|
||||||
addDummyStats(user, positionIndex);
|
addDummyStats(user);
|
||||||
positionIndex++;
|
positionIndex++;
|
||||||
}
|
}
|
||||||
//List<User> nTestUsers = seedNtestUsers(10);
|
//List<User> nTestUsers = seedNtestUsers(10);
|
||||||
@@ -261,31 +263,31 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
return createdUsers;
|
return createdUsers;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addDummyStats(User user, Long positionIndex) {
|
private void addDummyStats(User user) {
|
||||||
user.getStats().addToStat(
|
user.getStats().addToStat(
|
||||||
Timeframe.WEEKLY,
|
Timeframe.WEEKLY,
|
||||||
"XP",
|
"XP",
|
||||||
100L * positionIndex
|
0
|
||||||
);
|
);
|
||||||
user.getStats().addToStat(
|
user.getStats().addToStat(
|
||||||
Timeframe.WEEKLY,
|
Timeframe.WEEKLY,
|
||||||
"CO2_SAVED",
|
"CO2_SAVED",
|
||||||
500L * positionIndex
|
0
|
||||||
);
|
);
|
||||||
user.getStats().addToStat(
|
user.getStats().addToStat(
|
||||||
Timeframe.WEEKLY,
|
Timeframe.WEEKLY,
|
||||||
"KM_CYCLED",
|
"KM_CYCLED",
|
||||||
20L * positionIndex
|
0
|
||||||
);
|
);
|
||||||
user.getStats().addToStat(
|
user.getStats().addToStat(
|
||||||
Timeframe.WEEKLY,
|
Timeframe.WEEKLY,
|
||||||
"KM_WALKED",
|
"KM_WALKED",
|
||||||
10L * positionIndex
|
0
|
||||||
);
|
);
|
||||||
user.getStats().addToStat(
|
user.getStats().addToStat(
|
||||||
Timeframe.WEEKLY,
|
Timeframe.WEEKLY,
|
||||||
"KM_PUBLIC_TRANSPORT",
|
"KM_PUBLIC_TRANSPORT",
|
||||||
15L * positionIndex
|
0
|
||||||
);
|
);
|
||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,10 @@ import org.slf4j.LoggerFactory;
|
|||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.time.*;
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -131,10 +134,7 @@ public class RegularTripSuggestionService {
|
|||||||
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
|
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
|
||||||
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
|
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
|
||||||
// we plan the trip to arrive at the average arrival time of the regular trip
|
// we plan the trip to arrive at the average arrival time of the regular trip
|
||||||
Instant arrivalTime = LocalDateTime.now()
|
Instant arrivalTime = trip.getAverageArrivalTime();
|
||||||
.with(trip.getAverageArrivalTime())
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toInstant();
|
|
||||||
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
|
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
|
||||||
|
|
||||||
return RoutingAlternativeRequestDTO.builder()
|
return RoutingAlternativeRequestDTO.builder()
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package SuMoC.backend.trend;
|
|||||||
|
|
||||||
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
||||||
import SuMoC.backend.trend.models.WeeklyMobilityStatsId;
|
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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
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")
|
@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);
|
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
|
||||||
|
|
||||||
|
void deleteAllByUser(User user);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import jakarta.validation.Valid;
|
|||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -67,4 +66,22 @@ public class TripController {
|
|||||||
return ResponseEntity.ok().build();
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
|
|||||||
|
|
||||||
Optional<List<Trip>> findAllByUser(User user);
|
Optional<List<Trip>> findAllByUser(User user);
|
||||||
|
|
||||||
|
void deleteAllByUser(User user);
|
||||||
|
|
||||||
@Query("SELECT trip FROM Trip trip " +
|
@Query("SELECT trip FROM Trip trip " +
|
||||||
"JOIN FETCH trip.user " +
|
"JOIN FETCH trip.user " +
|
||||||
"JOIN FETCH trip.tripSegments " +
|
"JOIN FETCH trip.tripSegments " +
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import SuMoC.backend.trip.models.Trip;
|
|||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -26,18 +28,20 @@ public class TripService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void invalidateTrip(User user, Long tripId) {
|
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)) {
|
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);
|
trip.setInvalidated(true);
|
||||||
tripRepository.save(trip);
|
tripRepository.save(trip);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void validateTrip(User user, Long tripId) {
|
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)) {
|
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);
|
trip.setInvalidated(false);
|
||||||
tripRepository.save(trip);
|
tripRepository.save(trip);
|
||||||
@@ -55,4 +59,17 @@ public class TripService {
|
|||||||
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
|
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
|
||||||
return tripMapper.toTripDTOs(trips);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,9 +73,7 @@ public class FriendshipController {
|
|||||||
@PostMapping("/request/by-friendcode/{friendCode}")
|
@PostMapping("/request/by-friendcode/{friendCode}")
|
||||||
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
||||||
User user = currentUserService.get();
|
User user = currentUserService.get();
|
||||||
User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow();
|
friendshipService.requestFriendshipByFriendcode(user, friendCode);
|
||||||
checkSelfAction(user.getId(), requestedFriend.getId());
|
|
||||||
friendshipService.requestFriendship(user, requestedFriend.getId());
|
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ package SuMoC.backend.user.controller;
|
|||||||
|
|
||||||
import SuMoC.backend.images.ImageRequestDTO;
|
import SuMoC.backend.images.ImageRequestDTO;
|
||||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.user.dtos.*;
|
import SuMoC.backend.user.dtos.AddStatRequestDTO;
|
||||||
|
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||||
|
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||||
|
import SuMoC.backend.user.dtos.StatScope;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.service.UserService;
|
import SuMoC.backend.user.service.UserService;
|
||||||
import SuMoC.backend.user.stats.StatsList;
|
import SuMoC.backend.user.stats.StatsList;
|
||||||
@@ -23,6 +26,7 @@ import org.springframework.http.MediaType;
|
|||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
@Validated
|
@Validated
|
||||||
@@ -101,7 +105,7 @@ public class UserController {
|
|||||||
})
|
})
|
||||||
@PutMapping("/setPrivateName/{id}")
|
@PutMapping("/setPrivateName/{id}")
|
||||||
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
||||||
@RequestParam @NotBlank String newPrivateName) {
|
@RequestParam @NotBlank String newPrivateName) {
|
||||||
this.userService.setPrivateName(id, newPrivateName);
|
this.userService.setPrivateName(id, newPrivateName);
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
@@ -119,7 +123,7 @@ public class UserController {
|
|||||||
})
|
})
|
||||||
@PutMapping("/setPassword/{id}")
|
@PutMapping("/setPassword/{id}")
|
||||||
public ResponseEntity<LoginResponseDTO> setPassword(@PathVariable @NotNull Long 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);
|
return new ResponseEntity<>(this.userService.setPassword(id, newPassword), HttpStatus.OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +142,7 @@ public class UserController {
|
|||||||
})
|
})
|
||||||
@PutMapping("/setEmail/{id}")
|
@PutMapping("/setEmail/{id}")
|
||||||
public ResponseEntity<LoginResponseDTO> setEmail(@PathVariable @NotNull Long 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);
|
return new ResponseEntity<>(this.userService.setEmail(id, newEmail), HttpStatus.OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,16 +233,15 @@ public class UserController {
|
|||||||
@ApiResponse(responseCode = "403", description = "Only authorized persons may see the profiles picture"),
|
@ApiResponse(responseCode = "403", description = "Only authorized persons may see the profiles picture"),
|
||||||
@ApiResponse(responseCode = "404", description = "The user does not exist")
|
@ApiResponse(responseCode = "404", description = "The user does not exist")
|
||||||
})
|
})
|
||||||
@GetMapping("/getProfilePicture/{id}")
|
@GetMapping(value = "/getProfilePicture/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
|
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
|
||||||
ImageRequestDTO imageData = userService.getProfilePicture(id);
|
ImageRequestDTO imageData = userService.getProfilePicture(id);
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.IMAGE_JPEG)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
||||||
.body(imageData);
|
.body(imageData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
|
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
|
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
|
||||||
@@ -253,4 +256,17 @@ public class UserController {
|
|||||||
Long xp = userService.getTotalXP();
|
Long xp = userService.getTotalXP();
|
||||||
return ResponseEntity.ok().body(xp);
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,16 @@ public interface UserMapper {
|
|||||||
User toUser(UserDTO userDTO);
|
User toUser(UserDTO userDTO);
|
||||||
|
|
||||||
static MaximalUserDTO toMaximalUserDTO(User user) {
|
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.getId(),
|
||||||
user.getPublicName(),
|
user.getPublicName(),
|
||||||
user.getPrivateName(),
|
user.getPrivateName(),
|
||||||
@@ -24,9 +33,8 @@ public interface UserMapper {
|
|||||||
user.getTrips(),
|
user.getTrips(),
|
||||||
user.getFriendships(),
|
user.getFriendships(),
|
||||||
user.getFriendCode(),
|
user.getFriendCode(),
|
||||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
base64Image
|
||||||
);
|
);
|
||||||
return maximalUserDTO;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package SuMoC.backend.user.models;
|
package SuMoC.backend.user.models;
|
||||||
|
|
||||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
@@ -26,10 +27,12 @@ public class Friendship {
|
|||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JoinColumn(name = "user_id", nullable = false)
|
@JoinColumn(name = "user_id", nullable = false)
|
||||||
|
@JsonBackReference("user-friendships")
|
||||||
private User user;
|
private User user;
|
||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JoinColumn(name = "friend_id", nullable = false)
|
@JoinColumn(name = "friend_id", nullable = false)
|
||||||
|
@JsonBackReference("friend-friendships")
|
||||||
private User friend;
|
private User friend;
|
||||||
|
|
||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ import SuMoC.backend.user.repository.UserRepository;
|
|||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.jspecify.annotations.NonNull;
|
import org.jspecify.annotations.NonNull;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -344,6 +346,17 @@ public class FriendshipService {
|
|||||||
return friends;
|
return friends;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void requestFriendshipByFriendcode(User sender, String friendCode) {
|
||||||
|
User requestedFriend = userRepository.findByFriendCode(friendCode)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
|
||||||
|
|
||||||
|
if (sender.getId().equals(requestedFriend.getId())) {
|
||||||
|
throw new IllegalArgumentException("Action cannot be performed on oneself.");
|
||||||
|
}
|
||||||
|
|
||||||
|
requestFriendship(sender, requestedFriend.getId());
|
||||||
|
}
|
||||||
|
|
||||||
public record NameWithFriendship(
|
public record NameWithFriendship(
|
||||||
Long id,
|
Long id,
|
||||||
String name,
|
String name,
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
package SuMoC.backend.user.service;
|
package SuMoC.backend.user.service;
|
||||||
|
|
||||||
|
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
||||||
import SuMoC.backend.gamification.Timeframe;
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
import SuMoC.backend.images.ImageBase64Util;
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
import SuMoC.backend.images.ImageRequestDTO;
|
import SuMoC.backend.images.ImageRequestDTO;
|
||||||
|
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.security.services.TokenService;
|
import SuMoC.backend.security.services.TokenService;
|
||||||
import SuMoC.backend.trip.TripMapper;
|
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
|
||||||
|
import SuMoC.backend.trip.TripService;
|
||||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||||
import SuMoC.backend.user.enums.RoleName;
|
import SuMoC.backend.user.enums.RoleName;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.mapper.FriendshipMapper;
|
|
||||||
import SuMoC.backend.user.mapper.UserMapper;
|
import SuMoC.backend.user.mapper.UserMapper;
|
||||||
import SuMoC.backend.user.models.ProfileImageEntity;
|
import SuMoC.backend.user.models.ProfileImageEntity;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
@@ -22,7 +24,6 @@ import org.springframework.security.core.Authentication;
|
|||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
|
||||||
@@ -33,15 +34,18 @@ public class UserService {
|
|||||||
private final CurrentUserService currentUser;
|
private final CurrentUserService currentUser;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
private final UserMapper userMapper;
|
private final UserMapper userMapper;
|
||||||
|
private final TokenService tokenService;
|
||||||
private final TokenService tokenService;;
|
;
|
||||||
private final PrivacyService privacyService;
|
private final PrivacyService privacyService;
|
||||||
private final FriendshipService friendshipService;
|
private final FriendshipService friendshipService;
|
||||||
|
private final TripService tripService;
|
||||||
|
private final NotificationRepository notificationRepository;
|
||||||
|
private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
||||||
|
private final CarrouselCandidateRepository carrouselCandidateRepository;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService) {
|
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService, TripService tripService, NotificationRepository notificationRepository, WeeklyMobilityStatsRepository weeklyMobilityStatsRepository, CarrouselCandidateRepository carrouselCandidateRepository) {
|
||||||
this.currentUser = currentUser;
|
this.currentUser = currentUser;
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
@@ -49,6 +53,10 @@ public class UserService {
|
|||||||
this.tokenService = tokenService;
|
this.tokenService = tokenService;
|
||||||
this.privacyService = privacyService;
|
this.privacyService = privacyService;
|
||||||
this.friendshipService = friendshipService;
|
this.friendshipService = friendshipService;
|
||||||
|
this.tripService = tripService;
|
||||||
|
this.notificationRepository = notificationRepository;
|
||||||
|
this.weeklyMobilityStatsRepository = weeklyMobilityStatsRepository;
|
||||||
|
this.carrouselCandidateRepository = carrouselCandidateRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -60,7 +68,7 @@ public class UserService {
|
|||||||
));
|
));
|
||||||
// TODO: Check tomorrow if this makes sense
|
// TODO: Check tomorrow if this makes sense
|
||||||
// TODO: Can Users see the minimalDTO if they are blocked?
|
// TODO: Can Users see the minimalDTO if they are blocked?
|
||||||
if(friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(requested.getId()))) {
|
if (friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(requested.getId()))) {
|
||||||
throw new ResponseStatusException(
|
throw new ResponseStatusException(
|
||||||
HttpStatus.FORBIDDEN,
|
HttpStatus.FORBIDDEN,
|
||||||
"Der Nutzer hat dich blockiert."
|
"Der Nutzer hat dich blockiert."
|
||||||
@@ -97,7 +105,13 @@ public class UserService {
|
|||||||
userRepository.deleteById(id);
|
userRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void deleteMobilityData() {
|
||||||
|
User user = currentUser.get();
|
||||||
|
tripService.deleteAllTripsOfUser(user);
|
||||||
|
notificationRepository.deleteAllByUser(user);
|
||||||
|
weeklyMobilityStatsRepository.deleteAllByUser(user);
|
||||||
|
carrouselCandidateRepository.deleteAllByUserId(user.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public LoginResponseDTO setPassword(Long id, String newPassword) {
|
public LoginResponseDTO setPassword(Long id, String newPassword) {
|
||||||
@@ -178,7 +192,7 @@ public class UserService {
|
|||||||
));
|
));
|
||||||
System.out.println("################# Returning LoginResponse ################");
|
System.out.println("################# Returning LoginResponse ################");
|
||||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
|
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
|
||||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
|
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||||
@@ -196,15 +210,15 @@ public class UserService {
|
|||||||
}
|
}
|
||||||
User userToChange = userRepository.findById(id)
|
User userToChange = userRepository.findById(id)
|
||||||
.orElseThrow(() -> new ResponseStatusException(
|
.orElseThrow(() -> new ResponseStatusException(
|
||||||
HttpStatus.NOT_FOUND,
|
HttpStatus.NOT_FOUND,
|
||||||
"Der Nutzer Existitert nicht."));
|
"Der Nutzer Existitert nicht."));
|
||||||
|
|
||||||
// TODO: Add String Validator
|
// TODO: Add String Validator
|
||||||
userToChange.setPrivateName(newPrivateName);
|
userToChange.setPrivateName(newPrivateName);
|
||||||
userRepository.save(userToChange);
|
userRepository.save(userToChange);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public MaximalUserDTO getSelf() {
|
public MaximalUserDTO getSelf() {
|
||||||
User sender = currentUser.get();
|
User sender = currentUser.get();
|
||||||
return UserMapper.toMaximalUserDTO(sender);
|
return UserMapper.toMaximalUserDTO(sender);
|
||||||
@@ -258,7 +272,7 @@ public class UserService {
|
|||||||
|
|
||||||
public Long getTotalXP() {
|
public Long getTotalXP() {
|
||||||
User sender = currentUser.get();
|
User sender = currentUser.get();
|
||||||
return sender.getStats().getStatValue(Timeframe.TOTAL,"XP");
|
return sender.getStats().getStatValue(Timeframe.TOTAL, "XP");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/sumoc
|
|||||||
spring.datasource.username=postgres
|
spring.datasource.username=postgres
|
||||||
spring.datasource.password=admin
|
spring.datasource.password=admin
|
||||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||||
spring.jpa.hibernate.ddl-auto=update
|
spring.flyway.enabled=true
|
||||||
|
spring.jpa.hibernate.ddl-auto=validate
|
||||||
|
spring.flyway.baseline-on-migrate=true
|
||||||
|
spring.flyway.baseline-version=0
|
||||||
spring.jpa.show-sql=true
|
spring.jpa.show-sql=true
|
||||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||||
logging.level.org.springframework.security=Trace
|
logging.level.org.springframework.security=Trace
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE image_entity
|
||||||
|
ALTER COLUMN image_data TYPE bytea
|
||||||
|
USING lo_get(image_data);
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
Reference in New Issue
Block a user