Skip to content

Commit

Permalink
Merge pull request #169 from les-crepes/159-afficher-les-chats-du-dié…
Browse files Browse the repository at this point in the history
…téticien

159 afficher les chats du diététicien
  • Loading branch information
chloefont authored Sep 5, 2022
2 parents 523a955 + 12e88ba commit 9fc19b6
Show file tree
Hide file tree
Showing 17 changed files with 399 additions and 188 deletions.
32 changes: 22 additions & 10 deletions lib/api/firebase_message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,34 @@ class FirebaseMessage extends FirebaseAPI implements IMessage {

@override
Future<List<Message>?> readConversation(
String firstId, String secondId) async {
List<String> userIds = [firstId, secondId];
final querySnapshot = await collectionReference
.where('fromId', whereIn: userIds)
.where('toId', whereIn: userIds)
String userId1, String userId2) async {
final query = collectionReference
.where('fromId', isEqualTo: userId1)
.where('toId', isEqualTo: userId2)
.withConverter(
fromFirestore: Message.fromFirestore,
toFirestore: (Message msg, _) => msg.toFirestore())
.get();
final messages = querySnapshot.docs.map((doc) => doc.data()).toList();

final query2 = collectionReference
.where('fromId', isEqualTo: userId2)
.where('toId', isEqualTo: userId1)
.withConverter(
fromFirestore: Message.fromFirestore,
toFirestore: (Message msg, _) => msg.toFirestore())
.get();

final querySnapshots = await Future.wait([query, query2]);

final messages = [
...querySnapshots[0].docs.map((doc) => doc.data()).toList(),
...querySnapshots[1].docs.map((doc) => doc.data()).toList(),
];

return messages;
}

Stream<Message> followConversation(
String firstId, String secondId) {
Stream<Message> followConversation(String firstId, String secondId) {
List<String> userIds = [firstId, secondId];
final Stream<QuerySnapshot> msgStream = collectionReference
.where('fromId', whereIn: userIds)
Expand All @@ -67,8 +80,7 @@ class FirebaseMessage extends FirebaseAPI implements IMessage {
.snapshots();

return msgStream
.map((querySnapshot) =>
querySnapshot.docs.map((doc) => doc.data()))
.map((querySnapshot) => querySnapshot.docs.map((doc) => doc.data()))
.cast();
}

Expand Down
6 changes: 3 additions & 3 deletions lib/api/imessage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import 'package:pdg_app/model/message.dart';

abstract class IMessage {
void createMessage(Message message);
Future<dynamic> readMessage(String messageId);
Future<List<dynamic>?> readConversation(String firstId, String secondId);
Future<Message> readMessage(String messageId);
Future<List<Message>?> readConversation(String firstId, String secondId);
void updateMessage(Message message);
void deleteMessage(String messageId);
}
}
2 changes: 2 additions & 0 deletions lib/model/custom_list_tile_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import 'package:flutter/material.dart';
class CustomListTileData {
final Widget? avatar;
final String? title;
final String? subtitle;
final DateTime? date;
final int? badgeCount;
final void Function()? onTap;

CustomListTileData({
this.avatar,
this.title,
this.subtitle,
this.date,
this.badgeCount,
this.onTap,
Expand Down
9 changes: 9 additions & 0 deletions lib/model/user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ class User implements IModel {
firstName = name;
}

@override
bool operator ==(Object other) {
if (other is User && other.uid == uid) return true;
return false;
}

@override
int get hashCode => Object.hash(uid, null);

void addUser(String userId) {
if (clientList == null) {
throw Exception("Client list is null");
Expand Down
81 changes: 81 additions & 0 deletions lib/provider/chat_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import 'dart:collection';
import 'dart:developer';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:pdg_app/api/firebase_message.dart';
import 'package:sorted_list/sorted_list.dart';

import '../api/firebase_user.dart';
import '../api/imessage.dart';
import '../api/iuser.dart';
import '../model/message.dart';
import '../model/user.dart';
import 'auth_provider.dart';

typedef Uid = String;

class ChatProvider extends ChangeNotifier {
/// Getting the instance of the AuthProvider class.
final AuthProvider _auth;
final IMessage _messageApi = FirebaseMessage(FirebaseFirestore.instance);
final IUser _userApi = FirebaseUser(FirebaseFirestore.instance);

/// The list of messages using a [LinkedHashMap] to keep the order of the messages.
final Map<User, SortedList<Message>> _messages = {};

ChatProvider(AuthProvider authProvider) : _auth = authProvider;

Map<User, SortedList<Message>> get messages => UnmodifiableMapView(_messages);

/// Returning an unmodifiable list view of the messages.
UnmodifiableListView<Message> getMessagesWithUid(String uid) {
final messages = _messages[uid];
if (messages != null) {
return UnmodifiableListView(messages);
}
return UnmodifiableListView([]);
}

UnmodifiableListView<MapEntry<User, Message>> getLastMessageOfEachUser() {
final result =
_messages.entries.where((element) => element.value.isNotEmpty).map((e) {
MapEntry<User, Message> entry = MapEntry(e.key, e.value.last);
return entry;
}).toList();
return UnmodifiableListView(result);
}

/// Fetching all the messages from the database.
Future<void> fetchAllMessages() async {
List<User> users = [];

if (_auth.isAdmin) {
final clients = await _userApi.getDietitianClient(_auth.userUid);
users.addAll(clients);
} else {
final diet = await _userApi.readDietitianOfClient(_auth.userUid);
if (diet != null) {
users.add(diet);
}
}
final List<Future<List<Message>?>> functions = [];
for (final user in users) {
functions.add(_messageApi.readConversation(_auth.userUid, user.uid));
}

final futureResult = await Future.wait(functions);

int index = 0;
for (final conv in futureResult) {
final sortedList =
SortedList<Message>((a, b) => a.time.compareTo(b.time));

sortedList.addAll(conv!);

_messages[users[index]] = sortedList;
index++;
}
log(_messages.toString());
}
}
2 changes: 1 addition & 1 deletion lib/router/chat_guard.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ChatGuard extends AutoRouteGuard {
if (isAdmin) {
resolver.next(true);
} else {
router.push(const ChatScreenRoute());
router.push(ChatScreenRoute());
}
}
}
31 changes: 31 additions & 0 deletions lib/router/chat_router_page.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:pdg_app/provider/auth_provider.dart';
import 'package:pdg_app/provider/chat_provider.dart';
import 'package:provider/provider.dart';

class ChatRouterPage extends StatelessWidget {
const ChatRouterPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ChatProvider(GetIt.I.get<AuthProvider>()),
builder: (context, child) {
return FutureBuilder(
future: context.read<ChatProvider>().fetchAllMessages(),
builder: (context, snapshot) =>
snapshot.connectionState == ConnectionState.done
? const AutoRouter()
: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [CircularProgressIndicator()]),
),
);
},
);
}
}
4 changes: 2 additions & 2 deletions lib/router/router.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import '../screens/home.dart';
import '../widgets/register/register_third_page.dart';
import '../screens/update_client_record.dart';
import './auth_gard.dart';
import 'chat_router_page.dart';
import 'home_guard.dart';

@MaterialAutoRouter(
Expand All @@ -32,8 +33,7 @@ import 'home_guard.dart';
initial: true,
children: [
AutoRoute(
page: EmptyRouterPage,
name: 'ChatRouterPage',
page: ChatRouterPage,
path: 'chat',
children: [
AutoRoute(
Expand Down
Loading

0 comments on commit 9fc19b6

Please sign in to comment.