FCM уведомления

This commit is contained in:
RoyceDa
2026-02-25 18:38:14 +02:00
parent 0e240d1eeb
commit d6890c95e4
7 changed files with 151 additions and 1 deletions

View File

@@ -0,0 +1,93 @@
package im.rosetta.service.dispatch;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import im.rosetta.database.repository.UserRepository;
import im.rosetta.service.services.UserService;
/**
* Класс для отправки push-уведомлений пользователям через Firebase Cloud Messaging (FCM).
*/
public class FirebaseDispatcher {
private UserRepository userRepository = new UserRepository();
private UserService userService = new UserService(userRepository);
public FirebaseDispatcher() {
initializeFirebase();
}
/**
* Инициализация Firebase Admin SDK
*/
private void initializeFirebase() {
if (FirebaseApp.getApps().isEmpty()) {
try {
String firebaseCredentialsPath = System.getenv("FIREBASE_CREDENTIALS_PATH");
if (firebaseCredentialsPath == null || firebaseCredentialsPath.isEmpty()) {
throw new IllegalStateException("FIREBASE_CREDENTIALS_PATH environment variable is not set");
}
FileInputStream serviceAccount = new FileInputStream(firebaseCredentialsPath);
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
throw new RuntimeException("Failed to initialize Firebase", e);
}
}
}
/**
* Отправляет push-уведомление пользователю с данным публичным ключом
* @param publicKey публичный ключ пользователя
* @param title заголовок уведомления
* @param message текст уведомления
*/
public void sendPushNotification(String publicKey, String title, String messageText) {
List<String> tokens = userService.getNotificationsTokens(publicKey);
if (tokens == null || tokens.isEmpty()) {
return;
}
for (String token : tokens) {
try {
Message message = Message.builder()
.setNotification(Notification.builder()
.setTitle(title)
.setBody(messageText)
.build())
.setToken(token)
.build();
String response = FirebaseMessaging.getInstance().send(message);
System.out.println("Successfully sent message: " + response);
} catch (Exception e) {
System.err.println("Failed to send notification to token: " + token + ", error: " + e.getMessage());
}
}
}
/**
* Отправляет push-уведомление нескольким пользователям
* @param publicKeys список публичных ключей пользователей
* @param title заголовок уведомления
* @param messageText текст уведомления
*/
public void sendPushNotification(List<String> publicKeys, String title, String messageText) {
for (String publicKey : publicKeys) {
sendPushNotification(publicKey, title, messageText);
}
}
}