cofounderella/lib/services/swipe_stream_service.dart

98 lines
3.0 KiB
Dart
Raw Normal View History

import 'dart:async';
import 'package:flutter/foundation.dart' show debugPrint, kDebugMode;
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../constants.dart';
import 'user_service.dart';
class SwipeStreamService {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final List<String> _matchesInDB = [];
StreamSubscription<List<DocumentSnapshot>>? _subscription;
late String userId;
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
late bool matchesRead = false;
// Singleton instance
static final SwipeStreamService _instance = SwipeStreamService._internal();
// Private constructor
SwipeStreamService._internal();
// Factory constructor
factory SwipeStreamService() {
return _instance;
}
// Initialization method
void initialize(String userId, FlutterLocalNotificationsPlugin plugin) {
_instance.userId = userId;
_instance.flutterLocalNotificationsPlugin = plugin;
// Reset old data
_matchesInDB.clear();
matchesRead = false;
}
Stream<List<DocumentSnapshot>> get swipesStream {
return _firestore
.collection(Constants.dbCollectionUsers)
.doc(userId)
.collection(Constants.dbCollectionMatches)
.snapshots()
.map((snapshot) => snapshot.docs);
}
void _showNotification(String swipeId) async {
String matchName = await UserService.getUserName(swipeId);
const AndroidNotificationDetails androidPlatformChannelSpecifics =
2024-07-12 22:32:07 +02:00
AndroidNotificationDetails('new_matches_channel_id', 'new_match_info',
channelShowBadge: true,
visibility: NotificationVisibility.private,
priority: Priority.high,
showWhen: true);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(0, 'New Match',
2024-07-12 22:32:07 +02:00
'You have a new match with $matchName', platformChannelSpecifics,
payload: swipeId);
}
void listenToSwipes() {
_subscription = swipesStream.listen(
2024-07-12 22:32:07 +02:00
(swipes) {
if (!matchesRead) {
for (var swipe in swipes) {
2024-07-12 22:32:07 +02:00
if (kDebugMode) debugPrint('Init Match Notify --> ${swipe.id}');
_matchesInDB.add(swipe.id);
}
matchesRead = true;
} else {
for (var swipe in swipes) {
if (!_matchesInDB.contains(swipe.id)) {
2024-07-12 22:32:07 +02:00
if (kDebugMode) debugPrint('NEW Match Notify --> ${swipe.id}');
_matchesInDB.add(swipe.id);
_showNotification(swipe.id);
} else {
2024-07-12 22:32:07 +02:00
if (kDebugMode) debugPrint('Old Match Notify --> ${swipe.id}');
}
}
}
},
);
}
void stopListening() {
_subscription?.cancel();
_subscription = null;
}
void addUser(String userId) {
if (!_matchesInDB.contains(userId)) {
2024-07-12 22:32:07 +02:00
if (kDebugMode) debugPrint('Notify: SKIP Match Notify for --> $userId');
_matchesInDB.add(userId);
}
}
}