cofounderella/lib/services/chat/chat_service.dart

68 lines
1.9 KiB
Dart
Raw Normal View History

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
2024-05-25 13:56:45 +02:00
import '../../constants.dart';
import '../../utils/helper.dart';
2024-05-25 13:56:45 +02:00
import '../../models/message.dart';
class ChatService {
// get instance of firestore and auth
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
// get user stream
Stream<List<Map<String, dynamic>>> getUsersStream() {
2024-05-05 10:26:49 +02:00
return _firestore
.collection(Constants.dbCollectionUsers)
.snapshots()
.map((snapshot) {
return snapshot.docs.map((doc) {
// iterate each user
final user = doc.data();
//return user
return user;
}).toList();
});
}
// send message
Future<void> sendMessage(String receiverID, message) async {
// get current user info
final String currentUserID = _auth.currentUser!.uid;
final String currentUserEmail = _auth.currentUser!.email!;
final Timestamp timestamp = Timestamp.now();
// create new message
Message newMessage = Message(
senderID: currentUserID,
senderEmail: currentUserEmail,
receiverID: receiverID,
message: message,
timestamp: timestamp,
);
2024-05-25 13:56:45 +02:00
// construct chat room ID for the two users
String chatRoomID = getCompoundId([currentUserID, receiverID]);
2024-05-05 10:26:49 +02:00
// add new message to database
await _firestore
2024-05-05 10:26:49 +02:00
.collection(Constants.dbCollectionChatRooms)
.doc(chatRoomID)
2024-05-05 10:26:49 +02:00
.collection(Constants.dbCollectionMessages)
.add(newMessage.toMap());
}
// get messages
Stream<QuerySnapshot> getMessages(String userID, otherUserID) {
2024-05-25 13:56:45 +02:00
String chatRoomID = getCompoundId([userID, otherUserID]);
return _firestore
2024-05-05 10:26:49 +02:00
.collection(Constants.dbCollectionChatRooms)
.doc(chatRoomID)
2024-05-05 10:26:49 +02:00
.collection(Constants.dbCollectionMessages)
.orderBy("timestamp", descending: false)
.snapshots();
}
}