basic firebase notification sending + token registration logic

This commit is contained in:
2026-01-13 14:43:36 +01:00
parent ba642d10a5
commit bef418d77d
9 changed files with 173 additions and 14 deletions
@@ -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);
}
}