1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-11-26 06:49:22 +00:00
comunicmobile/lib/helpers/conversations_helper.dart

219 lines
7.3 KiB
Dart
Raw Normal View History

2019-04-27 06:42:27 +00:00
import 'package:comunic/helpers/database/conversation_messages_database_helper.dart';
import 'package:comunic/helpers/database/conversations_database_helper.dart';
2019-04-24 15:46:25 +00:00
import 'package:comunic/helpers/users_helper.dart';
2019-04-25 06:56:16 +00:00
import 'package:comunic/lists/conversation_messages_list.dart';
import 'package:comunic/lists/conversations_list.dart';
import 'package:comunic/lists/users_list.dart';
2019-04-23 12:35:41 +00:00
import 'package:comunic/models/api_request.dart';
2019-04-25 18:14:19 +00:00
import 'package:comunic/models/api_response.dart';
2019-04-23 12:35:41 +00:00
import 'package:comunic/models/conversation.dart';
2019-04-25 06:56:16 +00:00
import 'package:comunic/models/conversation_message.dart';
2019-04-25 07:48:52 +00:00
import 'package:comunic/models/new_conversation_message.dart';
import 'package:comunic/utils/account_utils.dart';
2019-04-27 06:51:58 +00:00
import 'package:meta/meta.dart';
2019-04-23 12:35:41 +00:00
/// Conversation helper
///
/// @author Pierre HUBERT
2019-04-25 07:48:52 +00:00
enum SendMessageResult { SUCCESS, MESSAGE_REJECTED, FAILED }
2019-04-23 12:35:41 +00:00
class ConversationsHelper {
final ConversationsDatabaseHelper _conversationsDatabaseHelper =
ConversationsDatabaseHelper();
2019-04-27 06:42:27 +00:00
final ConversationMessagesDatabaseHelper _conversationMessagesDatabaseHelper =
ConversationMessagesDatabaseHelper();
2019-04-23 12:35:41 +00:00
/// Download the list of conversations from the server
Future<ConversationsList> downloadList() async {
2019-04-23 12:35:41 +00:00
final response =
await APIRequest(uri: "conversations/getList", needLogin: true).exec();
if (response.code != 200) return null;
try {
ConversationsList list = ConversationsList();
2019-04-24 15:46:25 +00:00
response.getArray().forEach((f) => list.add(_apiToConversation(f)));
2019-04-23 12:35:41 +00:00
// Update the database
await _conversationsDatabaseHelper.clearTable();
await _conversationsDatabaseHelper.insertAll(list);
2019-04-23 12:35:41 +00:00
return list;
} on Exception catch (e) {
2019-04-23 12:35:41 +00:00
print(e.toString());
return null;
}
}
/// Get the local list of conversations
Future<ConversationsList> getCachedList() async {
final list = await _conversationsDatabaseHelper.getAll();
list.sort();
return list;
}
2019-04-24 15:46:25 +00:00
/// Get information about a single conversation specified by its [id]
Future<Conversation> _downloadSingle(int id) async {
try {
final response = await APIRequest(
uri: "conversations/getInfoOne",
needLogin: true,
args: {"conversationID": id.toString()}).exec();
if (response.code != 200) return null;
final conversation = _apiToConversation(response.getObject());
_conversationsDatabaseHelper.insertOrUpdate(conversation);
return conversation;
} on Exception catch (e) {
print(e.toString());
print("Could not get information about a single conversation !");
return null;
}
}
/// Get information about a single conversation. If [force] is set to false,
/// cached version of the conversation will be used, else it will always get
/// the information from the server
Future<Conversation> getSingle(int id, {bool force = false}) async {
2019-04-25 06:56:16 +00:00
if (force || !await _conversationsDatabaseHelper.has(id))
2019-04-24 15:46:25 +00:00
return await _downloadSingle(id);
else
return _conversationsDatabaseHelper.get(id);
}
/// Get the name of a [conversation]. This requires information
/// about the users of this conversation
static String getConversationName(
Conversation conversation, UsersList users) {
2019-04-25 09:14:05 +00:00
if (conversation.hasName) return conversation.name;
String name = "";
int count = 0;
for (int i = 0; i < 3 && i < conversation.members.length; i++)
if (conversation.members[i] != userID()) {
name += (count > 0 ? ", " : "") +
users.getUser(conversation.members[i]).fullName;
count++;
}
if (conversation.members.length > 3) name += ", ...";
return name;
}
2019-04-24 15:46:25 +00:00
/// Asynchronously get the name fo the conversation
///
/// Unlike the synchronous method, this method does not need information
/// about the members of the conversation
///
/// Returns null in case of failure
static Future<String> getConversationNameAsync(
Conversation conversation) async {
2019-04-25 09:14:05 +00:00
if (conversation.hasName) return conversation.name;
2019-04-24 15:46:25 +00:00
//Get information about the members of the conversation
final members = await UsersHelper().getUsersInfo(conversation.members);
if (members == null) return null;
return ConversationsHelper.getConversationName(conversation, members);
}
/// Turn an API entry into a [Conversation] object
2019-04-25 06:56:16 +00:00
Conversation _apiToConversation(Map<String, dynamic> map) {
2019-04-24 15:46:25 +00:00
return Conversation(
id: map["ID"],
ownerID: map["ID_owner"],
lastActive: map["last_active"],
name: map["name"] == false ? null : map["name"],
following: map["following"] == 1,
sawLastMessage: map["saw_last_message"] == 1,
members: map["members"].map<int>((f) => int.parse(f)).toList(),
);
}
2019-04-25 06:56:16 +00:00
/// Refresh the list of messages of a conversation
///
/// Set [lastMessageID] to 0 to specify that we do not have any message of the
/// conversation yet or another value else
2019-04-27 06:51:58 +00:00
Future<ConversationMessagesList> _downloadNewMessagesSingle(
int conversationID,
2019-04-25 06:56:16 +00:00
{int lastMessageID = 0}) async {
// Execute the request on the server
final response = await APIRequest(
uri: "conversations/refresh_single",
needLogin: true,
args: {
"conversationID": conversationID.toString(),
"last_message_id": lastMessageID.toString()
}).exec();
if (response.code != 200) return null;
// Parse the response of the server
ConversationMessagesList list = ConversationMessagesList();
response.getArray().forEach((f) {
list.add(ConversationMessage(
id: f["ID"],
2019-04-27 06:42:27 +00:00
conversationID: conversationID,
2019-04-25 06:56:16 +00:00
userID: f["ID_user"],
timeInsert: f["time_insert"],
message: f["message"],
imageURL: f["image_path"]));
});
2019-04-27 06:42:27 +00:00
// Save messages in the cache
_conversationMessagesDatabaseHelper.insertOrUpdateAll(list);
2019-04-25 06:56:16 +00:00
return list;
}
2019-04-25 07:48:52 +00:00
2019-04-27 06:51:58 +00:00
/// Get new messages for a given conversation
///
/// If [lastMessageID] is set to 0 then we retrieve the last messages of
/// the conversation.
/// Otherwise [lastMessageID] contains the ID of the last known message
Future<ConversationMessagesList> getNewMessages(
{@required int conversationID,
int lastMessageID = 0,
bool online = true}) async {
if (online)
return await _downloadNewMessagesSingle(conversationID,
lastMessageID: lastMessageID);
else
return await _conversationMessagesDatabaseHelper
.getAllMessagesConversations(conversationID,
lastMessageID: lastMessageID);
2019-04-27 06:51:58 +00:00
}
2019-04-25 07:48:52 +00:00
/// Send a new message to the server
Future<SendMessageResult> sendMessage(NewConversationMessage message) async {
2019-04-25 18:14:19 +00:00
final request = APIRequest(
2019-04-25 07:48:52 +00:00
uri: "conversations/sendMessage",
needLogin: true,
args: {
"conversationID": message.conversationID.toString(),
2019-04-25 18:14:19 +00:00
"message": message.hasMessage ? message.message : ""
2019-04-25 07:48:52 +00:00
},
2019-04-25 18:14:19 +00:00
);
//Check for image
2019-04-27 06:42:27 +00:00
if (message.hasImage) request.addFile("image", message.image);
2019-04-25 18:14:19 +00:00
//Send the message
APIResponse response;
2019-04-27 06:42:27 +00:00
if (!message.hasImage)
2019-04-25 18:14:19 +00:00
response = await request.exec();
else
response = await request.execWithFiles();
2019-04-25 07:48:52 +00:00
2019-04-27 06:42:27 +00:00
if (response.code == 401)
2019-04-25 07:48:52 +00:00
return SendMessageResult.MESSAGE_REJECTED;
2019-04-27 06:42:27 +00:00
else if (response.code != 200) return SendMessageResult.FAILED;
2019-04-25 07:48:52 +00:00
return SendMessageResult.SUCCESS;
}
2019-04-23 12:35:41 +00:00
}