1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-11-24 22:09:21 +00:00
comunicmobile/lib/helpers/groups_helper.dart

424 lines
14 KiB
Dart
Raw Permalink Normal View History

2020-05-02 06:51:34 +00:00
import 'dart:typed_data';
2021-04-06 15:40:13 +00:00
import 'package:comunic/helpers/conversations_helper.dart';
2020-05-02 09:18:03 +00:00
import 'package:comunic/lists/group_members_list.dart';
2019-06-10 07:47:02 +00:00
import 'package:comunic/lists/groups_list.dart';
2020-04-15 16:06:20 +00:00
import 'package:comunic/models/advanced_group_info.dart';
2019-06-10 07:47:02 +00:00
import 'package:comunic/models/api_request.dart';
2021-04-06 15:40:13 +00:00
import 'package:comunic/models/conversation.dart';
2019-06-10 07:47:02 +00:00
import 'package:comunic/models/group.dart';
2020-05-02 09:18:03 +00:00
import 'package:comunic/models/group_membership.dart';
2021-04-06 15:04:55 +00:00
import 'package:comunic/models/new_group_conversation.dart';
2020-04-15 10:04:19 +00:00
import 'package:comunic/utils/api_utils.dart';
2020-05-01 13:39:54 +00:00
import 'package:comunic/utils/map_utils.dart';
2019-06-10 07:47:02 +00:00
/// Groups helper
///
/// @author Pierre HUBERT
2021-04-06 15:04:55 +00:00
const APIGroupsMembershipLevelsMap = {
2019-06-10 07:47:02 +00:00
"administrator": GroupMembershipLevel.ADMINISTRATOR,
"moderator": GroupMembershipLevel.MODERATOR,
"member": GroupMembershipLevel.MEMBER,
"invited": GroupMembershipLevel.INVITED,
"pending": GroupMembershipLevel.PENDING,
"visitor": GroupMembershipLevel.VISITOR
};
const _APIGroupsVisibilityLevelsMap = {
"open": GroupVisibilityLevel.OPEN,
"private": GroupVisibilityLevel.PRIVATE,
"secrete": GroupVisibilityLevel.SECRETE
};
const _APIGroupsRegistrationLevelsMap = {
"open": GroupRegistrationLevel.OPEN,
"moderated": GroupRegistrationLevel.MODERATED,
"closed": GroupRegistrationLevel.CLOSED
};
const _APIGroupsPostsCreationLevelsMap = {
"moderators": GroupPostCreationLevel.MODERATORS,
"members": GroupPostCreationLevel.MEMBERS
};
2019-06-10 07:57:42 +00:00
final _groupsListCache = GroupsList();
2019-06-10 07:47:02 +00:00
2020-04-15 16:06:20 +00:00
/// Callback for getting advanced user information
enum GetAdvancedInfoStatus { SUCCESS, ACCESS_DENIED }
class GetAdvancedInfoResult {
final GetAdvancedInfoStatus status;
final AdvancedGroupInfo? info;
2020-04-15 16:06:20 +00:00
2022-03-11 15:27:01 +00:00
GetAdvancedInfoResult(this.status, this.info);
2020-04-15 16:06:20 +00:00
}
/// Groups helper
2019-06-10 07:57:42 +00:00
class GroupsHelper {
/// Download a list of groups information from the server
Future<GroupsList?> _downloadList(Set<int?> groups) async {
2019-06-10 07:47:02 +00:00
final response = await APIRequest(
uri: "groups/get_multiple_info",
needLogin: true,
args: {"list": groups.join(",")},
).exec();
if (response.code != 200) return null;
final list = GroupsList();
response
2022-03-10 19:36:55 +00:00
.getObject()
2021-04-23 16:46:35 +00:00
.forEach((k, d) => list[int.parse(k)] = getGroupFromAPI(d));
2019-06-10 07:47:02 +00:00
return list;
}
/// Get a list of groups from the server. In case of error, this method throws
/// an exception
Future<GroupsList> getListOrThrow(Set<int?> groups,
{bool force = false}) async {
final list = await getList(groups, force: force);
if (list == null) throw Exception("Could not get the list of groups!");
return list;
}
2019-06-10 07:57:42 +00:00
/// Get a list of groups from the server
Future<GroupsList?> getList(Set<int?> groups, {bool force = false}) async {
2019-06-10 07:57:42 +00:00
final list = GroupsList();
// Check which groups information to download
final toDownload = Set<int?>();
2019-06-10 07:57:42 +00:00
groups.forEach((groupID) {
if (!force && _groupsListCache.containsKey(groupID))
2019-06-10 07:57:42 +00:00
list[groupID] = _groupsListCache[groupID];
else
toDownload.add(groupID);
});
// Download required groups information
if (toDownload.length > 0) {
final downloaded = await _downloadList(toDownload);
if (downloaded == null) return null;
list.addAll(downloaded);
_groupsListCache.addAll(downloaded);
}
return list;
}
2020-04-15 16:06:20 +00:00
/// Get information about a single group
///
/// Throws in case of failure
Future<Group> getSingle(int groupID, {bool force = false}) async {
return (await getListOrThrow(Set<int>()..add(groupID), force: force))
.values
.first;
}
2020-04-15 10:04:19 +00:00
/// Get the list of groups of a user
Future<Set<int?>> getListUser() async =>
2020-04-15 10:04:19 +00:00
(await APIRequest(uri: "groups/get_my_list", needLogin: true).exec())
.assertOk()
.getArray()!
2020-04-15 10:04:19 +00:00
.map((f) => cast<int>(f))
.toSet();
2020-05-02 16:15:55 +00:00
/// Create a new group
///
/// Throws in case of failure
static Future<int> create(String name) async {
final result = await APIRequest.withLogin("groups/create")
.addString("name", name)
.execWithThrow();
return result.getObject()["id"];
}
2020-04-15 11:56:59 +00:00
/// Perform a simple membership request
2021-04-23 17:32:34 +00:00
static Future<bool> _simpleMembershipRequest(int groupID, String uri,
{Map<String, String>? args}) async =>
2021-04-23 17:32:34 +00:00
(await (APIRequest.withLogin(uri)
..addInt("id", groupID)
..addArgs(args == null ? Map() : args))
2020-04-15 11:25:55 +00:00
.exec())
.isOK;
2020-04-15 11:56:59 +00:00
/// Remove group membership
Future<bool> removeMembership(int groupID) async =>
_simpleMembershipRequest(groupID, "groups/remove_membership");
/// Cancel membership request
Future<bool> cancelRequest(int groupID) async =>
_simpleMembershipRequest(groupID, "groups/cancel_request");
2020-04-15 12:04:47 +00:00
/// Send a new membership request
2021-04-23 17:32:34 +00:00
static Future<bool> sendRequest(int groupID) async =>
2020-04-15 12:04:47 +00:00
_simpleMembershipRequest(groupID, "groups/send_request");
/// Respond to a group membership invitation
2021-04-23 17:32:34 +00:00
static Future<bool> respondInvitation(int groupID, bool accept) async =>
_simpleMembershipRequest(groupID, "groups/respond_invitation", args: {
"accept": accept ? "true" : "false",
});
2020-04-15 16:39:07 +00:00
/// Update group following status
Future<bool> setFollowing(int groupID, bool follow) async =>
(await (APIRequest(uri: "groups/set_following", needLogin: true)
..addInt("groupID", groupID)
..addBool("follow", follow))
.exec())
.isOK;
2020-04-15 16:06:20 +00:00
/// Get advanced information about the user
Future<GetAdvancedInfoResult> getAdvancedInfo(int? groupID) async {
2020-04-15 16:06:20 +00:00
// Get advanced information about the user
final result =
await (APIRequest(uri: "groups/get_advanced_info", needLogin: true)
..addInt("id", groupID))
.exec();
switch (result.code) {
case 401:
return GetAdvancedInfoResult(GetAdvancedInfoStatus.ACCESS_DENIED, null);
case 200:
return GetAdvancedInfoResult(GetAdvancedInfoStatus.SUCCESS,
2022-03-10 19:36:55 +00:00
_getAdvancedGroupInfoFromAPI(result.getObject()));
2020-04-15 16:06:20 +00:00
default:
throw Exception("Could not get advanced group information!");
}
}
2020-05-01 13:12:55 +00:00
/// Get group settings
///
/// This function is currently a kind of alias, but it might
/// change in the future
///
/// Throws in case of error
Future<AdvancedGroupInfo?> getSettings(int groupID) async {
2020-05-01 13:12:55 +00:00
final groupInfo = await getAdvancedInfo(groupID);
if (groupInfo.status != GetAdvancedInfoStatus.SUCCESS)
throw Exception("Could not get group information!");
return groupInfo.info;
}
2020-05-01 18:10:25 +00:00
/// Check the availability of a virtual directory
///
/// Throws in case of error
static Future<void> checkVirtualDirectoryAvailability(
int groupID, String dir) async =>
await APIRequest(uri: "groups/checkVirtualDirectory", needLogin: true)
.addInt("groupID", groupID)
.addString("directory", dir)
.execWithThrow();
2020-05-01 13:39:54 +00:00
/// Update (set) new group settings
///
/// Throws in case of error
static Future<void> setSettings(AdvancedGroupInfo settings) async {
await APIRequest(uri: "groups/set_settings", needLogin: true)
.addInt("id", settings.id)
.addString("name", settings.name)
.addString("virtual_directory", settings.virtualDirectory)
.addString("visibility",
invertMap(_APIGroupsVisibilityLevelsMap)[settings.visibilityLevel])
.addString(
"registration_level",
invertMap(
_APIGroupsRegistrationLevelsMap)[settings.registrationLevel])
.addString(
"posts_level",
invertMap(
_APIGroupsPostsCreationLevelsMap)[settings.postCreationLevel])
.addBool("is_members_list_public", settings.isMembersListPublic!)
2020-05-01 13:39:54 +00:00
.addString("description", settings.description)
.addString("url", settings.url)
.execWithThrow();
}
2020-05-02 06:51:34 +00:00
/// Upload a new logo
///
/// Throws in case of failure
static Future<void> uploadNewLogo(int groupID, Uint8List? bytes) async =>
2020-05-02 06:51:34 +00:00
await APIRequest(uri: "groups/upload_logo", needLogin: true)
.addInt("id", groupID)
.addBytesFile("logo", BytesFile("logo.png", bytes))
.execWithFilesAndThrow();
2020-05-02 07:15:02 +00:00
/// Delete group logo
2020-05-02 07:45:03 +00:00
///
/// Throws in case of error
2020-05-02 07:15:02 +00:00
static Future<void> deleteLogo(int groupID) async =>
await APIRequest(uri: "groups/delete_logo", needLogin: true)
.addInt("id", groupID)
.execWithThrow();
2020-05-02 07:45:03 +00:00
/// Delete a group
///
/// Throws in case of error
static Future<void> deleteGroup(int groupID, String password) async =>
await APIRequest(uri: "groups/delete", needLogin: true)
.addInt("groupID", groupID)
.addString("password", password)
.execWithThrow();
2020-05-02 09:18:03 +00:00
/// Get the list of members of the group
///
/// Throws in case of failure
static Future<GroupMembersList> getMembersList(int groupID) async =>
GroupMembersList()
..addAll((await APIRequest(uri: "groups/get_members", needLogin: true)
.addInt("id", groupID)
.execWithThrow())
.getArray()!
2020-05-02 09:18:03 +00:00
.map((f) => _apiToGroupMembership(f))
.toList());
2020-05-02 13:38:02 +00:00
/// Invite a user to join a group
///
/// Throws an exception in case of failure
static Future<void> sendInvitation(int groupID, int userID) async =>
APIRequest.withLogin("groups/invite")
.addInt("group_id", groupID)
.addInt("userID", userID)
.execWithThrow();
/// Cancel a group membership invitation
///
/// Throws an exception in case of failure
static Future<void> cancelInvitation(int groupID, int? userID) async =>
await APIRequest.withLogin("groups/cancel_invitation")
.addInt("groupID", groupID)
.addInt("userID", userID)
.execWithThrow();
/// Respond to a group membership request
///
/// Throws an exception in case of failure
static Future<void> respondRequest(
int groupID, int? userID, bool accept) async =>
await APIRequest.withLogin("groups/respond_request")
.addInt("groupID", groupID)
.addInt("userID", userID)
.addBool("accept", accept)
.execWithThrow();
2020-05-02 15:05:18 +00:00
/// Remove a member from a group
///
/// Throws an exception in case of failure
static Future<void> removeMemberFromGroup(int groupID, int userID) async =>
APIRequest.withLogin("groups/delete_member")
.addInt("groupID", groupID)
.addInt("userID", userID)
.execWithThrow();
2020-05-02 15:26:03 +00:00
/// Change the membership level of a member of a group
///
/// Throws an exception in case of failure
static Future<void> setNewLevel(
int groupID, int userID, GroupMembershipLevel level) async =>
await APIRequest.withLogin("groups/update_membership_level")
.addInt("groupID", groupID)
.addInt("userID", userID)
2021-04-06 15:04:55 +00:00
.addString("level", invertMap(APIGroupsMembershipLevelsMap)[level])
.execWithThrow();
/// Create a new group conversation
///
/// Throws in case of failure
static Future<void> createGroupConversation(
NewGroupConversation conv) async =>
await APIRequest.withLogin("groups/create_conversation")
.addInt("group_id", conv.groupID)
.addString(
"min_membership_level",
APIGroupsMembershipLevelsMap.entries
.firstWhere((e) => e.value == conv.minMembershipLevel)
.key)
.addString("name", conv.name)
2020-05-02 15:26:03 +00:00
.execWithThrow();
2021-04-06 15:40:13 +00:00
/// Set new conversation visibility level
///
/// Throws in case of failure
static Future<void> setConversationVisibility(
int? convID, GroupMembershipLevel? newLevel) async =>
2021-04-06 15:40:13 +00:00
await APIRequest.withLogin("groups/set_conversation_visibility")
.addInt("conv_id", convID)
.addString(
"min_membership_level",
APIGroupsMembershipLevelsMap.entries
.firstWhere((e) => e.value == newLevel)
.key)
.execWithThrow();
2021-04-06 15:46:05 +00:00
/// Delete a group's conversation
///
/// Throws in case of failure
static Future<void> deleteConversation(int? convID) async =>
2021-04-06 15:46:05 +00:00
await APIRequest.withLogin("groups/delete_conversation")
.addInt("conv_id", convID)
.execWithThrow();
2019-06-10 07:47:02 +00:00
/// Turn an API entry into a group object
2021-04-23 16:46:35 +00:00
static Group getGroupFromAPI(Map<String, dynamic> map) {
2019-06-10 07:47:02 +00:00
return Group(
id: map["id"],
name: map["name"],
2020-04-15 10:04:19 +00:00
iconURL: map["icon_url"],
2019-06-10 07:47:02 +00:00
numberMembers: map["number_members"],
membershipLevel: APIGroupsMembershipLevelsMap[map["membership"]]!,
visibilityLevel: _APIGroupsVisibilityLevelsMap[map["visibility"]]!,
2019-06-10 07:47:02 +00:00
registrationLevel:
_APIGroupsRegistrationLevelsMap[map["registration_level"]]!,
postCreationLevel: _APIGroupsPostsCreationLevelsMap[map["posts_level"]]!,
2020-05-01 18:15:28 +00:00
virtualDirectory: nullToEmpty(map["virtual_directory"]),
2019-06-10 07:47:02 +00:00
following: map["following"]);
}
2020-04-15 16:06:20 +00:00
/// Get advanced group information
AdvancedGroupInfo _getAdvancedGroupInfoFromAPI(Map<String, dynamic> map) =>
AdvancedGroupInfo(
id: map["id"],
name: map["name"],
iconURL: map["icon_url"],
numberMembers: map["number_members"],
membershipLevel: APIGroupsMembershipLevelsMap[map["membership"]]!,
visibilityLevel: _APIGroupsVisibilityLevelsMap[map["visibility"]]!,
2020-04-15 16:06:20 +00:00
registrationLevel:
_APIGroupsRegistrationLevelsMap[map["registration_level"]]!,
postCreationLevel: _APIGroupsPostsCreationLevelsMap[map["posts_level"]]!,
isMembersListPublic: map["is_members_list_public"],
2020-05-01 18:15:28 +00:00
virtualDirectory: nullToEmpty(map["virtual_directory"]),
2020-04-15 16:06:20 +00:00
following: map["following"],
timeCreate: map["time_create"],
2020-05-01 18:30:26 +00:00
description: nullToEmpty(map["description"]),
2020-05-01 18:15:28 +00:00
url: nullToEmpty(map["url"]),
2020-04-15 17:23:08 +00:00
likes: map["number_likes"],
userLike: map["is_liking"],
2021-04-06 15:40:13 +00:00
conversations: map["conversations"]
.map((s) => ConversationsHelper.apiToConversation(s))
.cast<Conversation>()
.toList(),
2021-04-22 13:15:40 +00:00
isForezGroup: map["is_forez_group"],
2020-04-15 16:06:20 +00:00
);
2020-05-02 09:18:03 +00:00
/// Create [GroupMembership] object from API entry
static GroupMembership _apiToGroupMembership(Map<String, dynamic> row) =>
GroupMembership(
userID: row["user_id"],
groupID: row["group_id"],
timeCreate: row["time_create"],
level: APIGroupsMembershipLevelsMap[row["level"]]!,
2020-05-02 09:18:03 +00:00
);
2019-06-10 07:47:02 +00:00
}