68 lines
1.9 KiB
Dart
68 lines
1.9 KiB
Dart
import 'package:cloud_firestore/cloud_firestore.dart';
|
|
import 'package:firebase_auth/firebase_auth.dart';
|
|
|
|
import '../../constants.dart';
|
|
import '../../helper.dart';
|
|
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() {
|
|
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,
|
|
);
|
|
|
|
// construct chat room ID for the two users
|
|
String chatRoomID = getCompoundId([currentUserID, receiverID]);
|
|
|
|
// add new message to database
|
|
await _firestore
|
|
.collection(Constants.dbCollectionChatRooms)
|
|
.doc(chatRoomID)
|
|
.collection(Constants.dbCollectionMessages)
|
|
.add(newMessage.toMap());
|
|
}
|
|
|
|
// get messages
|
|
Stream<QuerySnapshot> getMessages(String userID, otherUserID) {
|
|
String chatRoomID = getCompoundId([userID, otherUserID]);
|
|
|
|
return _firestore
|
|
.collection(Constants.dbCollectionChatRooms)
|
|
.doc(chatRoomID)
|
|
.collection(Constants.dbCollectionMessages)
|
|
.orderBy("timestamp", descending: false)
|
|
.snapshots();
|
|
}
|
|
}
|