basic firebase notification sending + token registration logic
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
package SuMoC.backend.dev;
|
||||
|
||||
import SuMoC.backend.firebase.MessageBuilder;
|
||||
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
||||
import SuMoC.backend.meteo.ForecastService;
|
||||
import SuMoC.backend.meteo.MeteoClient;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
@@ -29,7 +29,7 @@ public class DevController {
|
||||
private final FirebaseMessaging firebaseMessaging;
|
||||
private final MeteoClient meteoClient;
|
||||
private final ForecastService forecastService;
|
||||
private final MessageBuilder messageBuilder;
|
||||
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public DevController(
|
||||
@@ -38,7 +38,7 @@ public class DevController {
|
||||
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
|
||||
MeteoClient meteoClient,
|
||||
ForecastService forecastService,
|
||||
MessageBuilder messageBuilder,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
ObjectMapper objectMapper
|
||||
) {
|
||||
this.scheduledTasks = scheduledTasks;
|
||||
@@ -46,7 +46,7 @@ public class DevController {
|
||||
this.firebaseMessaging = firebaseMessaging;
|
||||
this.meteoClient = meteoClient;
|
||||
this.forecastService = forecastService;
|
||||
this.messageBuilder = messageBuilder;
|
||||
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class DevController {
|
||||
notification.setType(NotificationType.TREND);
|
||||
notification.setData(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()));
|
||||
|
||||
Message mockTrendMessage = messageBuilder.generateMessage(notification, fcmToken);
|
||||
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||
|
||||
// Send to a topic (no device registration needed)
|
||||
String message = firebaseMessaging.sendAsync(
|
||||
|
||||
+2
-9
@@ -5,16 +5,9 @@ import com.google.firebase.messaging.Message;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class MessageBuilder {
|
||||
|
||||
public Message generateMessage(Notification notification, String overrideToken) {
|
||||
// TODO get users token from database
|
||||
String token = "fEfi8Ao_SQiqURpniIT5cF:APA91bHdfhPIpoSC4Bw7HHr4LzszBWvkyJ4sX0jkAr03gG1XTfRkVxJvLEmV0DiiYzRHN-l2LZVgHicxeWGQek-qYvAkJylfXHxn902nGZOgQ5jyNYqN58M";
|
||||
|
||||
if (overrideToken != null && !overrideToken.isEmpty()) {
|
||||
token = overrideToken;
|
||||
}
|
||||
public class FirebaseMessageBuilder {
|
||||
|
||||
public Message generateMessage(Notification notification, String token) {
|
||||
var builder = Message.builder().setToken(token);
|
||||
builder.putData("type", notification.getType().toString());
|
||||
builder.putData("data", notification.getData());
|
||||
@@ -1,9 +1,43 @@
|
||||
package SuMoC.backend.notification;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import SuMoC.backend.notification.services.NotificationTokenService;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/notifications")
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationController {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final NotificationTokenService notificationTokenService;
|
||||
|
||||
// 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"));
|
||||
}
|
||||
|
||||
@PutMapping("/register-device-token")
|
||||
@Operation(summary = "Registers a device token for push notifications for the authenticated user.")
|
||||
public ResponseEntity<Void> registerDeviceToken(@RequestBody RegisterDeviceTokenRequest request) {
|
||||
User user = getAuthenticatedUser();
|
||||
notificationTokenService.registerDeviceToken(user, request.provider(), request.token());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
// Simple record for request body
|
||||
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.notification.enums;
|
||||
|
||||
public enum NotificationProvider {
|
||||
FIREBASE,
|
||||
}
|
||||
@@ -26,6 +26,7 @@ public class Notification {
|
||||
private User user;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationType type;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
@@ -40,6 +41,7 @@ public class Notification {
|
||||
private LocalTime earliestTimeOfDayToSend;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationStatus status;
|
||||
|
||||
@Column(nullable = false)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package SuMoC.backend.notification.models;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
public class NotificationToken {
|
||||
|
||||
@Id
|
||||
@Column(nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationProvider provider;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 512)
|
||||
private String token;
|
||||
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package SuMoC.backend.notification.repositories;
|
||||
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface NotificationTokenRepository extends JpaRepository<NotificationToken, Long> {
|
||||
Optional<NotificationToken> findByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
import com.google.firebase.messaging.Message;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Service
|
||||
public class NotificationSender {
|
||||
|
||||
private final NotificationTokenRepository notificationTokenRepository;
|
||||
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
||||
private final Logger logger = Logger.getLogger(NotificationSender.class.getName());
|
||||
private final FirebaseMessaging firebaseMessaging;
|
||||
|
||||
public NotificationSender(
|
||||
NotificationTokenRepository notificationTokenRepository,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
@Autowired(required = false) FirebaseMessaging firebaseMessaging
|
||||
) {
|
||||
this.notificationTokenRepository = notificationTokenRepository;
|
||||
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
||||
this.firebaseMessaging = firebaseMessaging;
|
||||
}
|
||||
|
||||
public void sendNotification(User user, Notification notification) {
|
||||
// get users notification token
|
||||
NotificationToken token;
|
||||
try {
|
||||
token = notificationTokenRepository.findByUserId(user.getId()).orElseThrow();
|
||||
} catch (NoSuchElementException e) {
|
||||
logger.warning("No notification token found for user id, skipping send: " + user.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
switch (token.getProvider()) {
|
||||
case FIREBASE -> sendViaFirebase(token, notification);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendViaFirebase(NotificationToken token, Notification notification) {
|
||||
if (firebaseMessaging == null) {
|
||||
logger.warning("FirebaseMessaging not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken());
|
||||
|
||||
firebaseMessaging.sendAsync(message)
|
||||
.addListener(() -> logger.info("Notification sent to user"), Runnable::run);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
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 lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationTokenService {
|
||||
|
||||
private final NotificationTokenRepository notificationTokenRepository;
|
||||
|
||||
public void registerDeviceToken(User user, NotificationProvider provider, String token) {
|
||||
var existingToken = notificationTokenRepository.findByUserId(user.getId());
|
||||
if (existingToken.isPresent()) {
|
||||
var notificationToken = existingToken.get();
|
||||
notificationToken.setToken(token);
|
||||
notificationTokenRepository.save(notificationToken);
|
||||
} else {
|
||||
var newToken = new NotificationToken();
|
||||
newToken.setUserId(user.getId());
|
||||
newToken.setProvider(provider);
|
||||
newToken.setToken(token);
|
||||
notificationTokenRepository.save(newToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user