2024-04-30 19:25:16 +02:00
|
|
|
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';
|
2024-05-27 14:40:46 +02:00
|
|
|
import '../../utils/helper.dart';
|
2024-05-25 13:56:45 +02:00
|
|
|
import '../../models/message.dart';
|
|
|
|
|
2024-04-30 19:25:16 +02:00
|
|
|
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) {
|
2024-04-30 19:25:16 +02:00
|
|
|
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-04-30 19:25:16 +02:00
|
|
|
|
2024-05-05 10:26:49 +02:00
|
|
|
// add new message to database
|
2024-04-30 19:25:16 +02:00
|
|
|
await _firestore
|
2024-05-05 10:26:49 +02:00
|
|
|
.collection(Constants.dbCollectionChatRooms)
|
2024-04-30 19:25:16 +02:00
|
|
|
.doc(chatRoomID)
|
2024-05-05 10:26:49 +02:00
|
|
|
.collection(Constants.dbCollectionMessages)
|
2024-04-30 19:25:16 +02:00
|
|
|
.add(newMessage.toMap());
|
|
|
|
}
|
|
|
|
|
|
|
|
// get messages
|
|
|
|
Stream<QuerySnapshot> getMessages(String userID, otherUserID) {
|
2024-05-25 13:56:45 +02:00
|
|
|
String chatRoomID = getCompoundId([userID, otherUserID]);
|
2024-04-30 19:25:16 +02:00
|
|
|
|
|
|
|
return _firestore
|
2024-05-05 10:26:49 +02:00
|
|
|
.collection(Constants.dbCollectionChatRooms)
|
2024-04-30 19:25:16 +02:00
|
|
|
.doc(chatRoomID)
|
2024-05-05 10:26:49 +02:00
|
|
|
.collection(Constants.dbCollectionMessages)
|
2024-04-30 19:25:16 +02:00
|
|
|
.orderBy("timestamp", descending: false)
|
|
|
|
.snapshots();
|
|
|
|
}
|
|
|
|
}
|