lastMessageStream method
Returns a stream of the last message in a room, checking if it's deleted
Implementation
Stream<mm.Message?> lastMessageStream(String roomId) {
return getFirebaseFirestore
.collection('${FireChatConst.roomsCollectionName}/$roomId/messages')
.orderBy('createdAt', descending: true)
.limit(1)
.snapshots()
.asyncMap(
(snapshot) async {
if (snapshot.docs.isEmpty) return null;
final doc = snapshot.docs.first;
final data = doc.data();
// Skip if message is deleted
// if (data['isDeleted'] == true) return null;
// Get room to resolve author info
final roomDoc = await getFirebaseFirestore
.collection(FireChatConst.roomsCollectionName)
.doc(roomId)
.get();
if (!roomDoc.exists) return null;
final room = await processRoomDocument(
roomDoc,
firebaseUser!,
getFirebaseFirestore,
FireChatConst.usersCollectionName,
);
final author = room.users.firstWhere(
(u) => u.id == data['authorId'],
orElse: () => mm.User(id: data['authorId'] as String),
);
data['author'] = author.toJson();
data['createdAt'] = data['createdAt']?.millisecondsSinceEpoch;
data['id'] = doc.id;
data['updatedAt'] = data['updatedAt']?.millisecondsSinceEpoch;
data['isDeleted'] = data['isDeleted'];
// Check if the message has been seen by all users
final seenBy = data['seenBy'] as Map<String, dynamic>? ?? {};
final allUsersHaveSeen =
room.users.every((user) => seenBy.containsKey(user.id));
return mm.Message.fromJson(data).copyWith(
metadata: {
...data['metadata'] ?? {},
'seen': allUsersHaveSeen,
},
);
},
);
}