import 'package:comunic/helpers/database/friends_database_helper.dart'; import 'package:comunic/lists/friends_list.dart'; import 'package:comunic/models/api_request.dart'; import 'package:comunic/models/friend.dart'; import 'package:meta/meta.dart'; /// Friends helper /// /// @author Pierre HUBERT class FriendsHelper { final FriendsDatabaseHelper _friendsDatabaseHelper = FriendsDatabaseHelper(); /// Get the list of friends of the user from the server /// /// Returns the list of friends in case of success, or null if an error /// occurred Future _downloadList() async { final response = await APIRequest( uri: "friends/getList", needLogin: true, args: { "complete": "true", }, ).exec(); if (response.code != 200) return null; // Parse and return the list of friends FriendsList list = FriendsList(); response.getArray().forEach( (f) => list.add( Friend( id: f["ID_friend"], accepted: f["accepted"] == 1, lastActive: f["time_last_activity"], following: f["following"] == 1, canPostTexts: f["canPostTexts"], ), ), ); // Save the list of friends _friendsDatabaseHelper.clearTable(); _friendsDatabaseHelper.insertAll(list); return list; } /// Get the list, either from an online or an offline source Future getList({@required bool online}) async { if (online) return await _downloadList(); else return FriendsList()..addAll(await _friendsDatabaseHelper.getAll()); } /// Respond to friendship request Future respondRequest(int friendID, bool accept) async { final response = await APIRequest( uri: "friends/respondRequest", needLogin: true, args: { "friendID": friendID.toString(), "accept": accept.toString() }).exec(); return response.code == 200; } /// Update following status for a friend Future setFollowing(int friendID, bool follow) async { final response = await APIRequest( uri: "friends/setFollowing", needLogin: true, args: { "friendID": friendID.toString(), "follow": follow.toString() }).exec(); return response.code == 200; } /// Remove a friend from the list Future removeFriend(int friendID) async { final response = await APIRequest( uri: "friends/remove", needLogin: true, args: {"friendID": friendID.toString()}).exec(); return response.code == 200; } /// Get and return the list of friends of an other user /// /// Throws an Exception if could not get the list of friends Future> getOtherUserList(int userID) async { final response = await APIRequest( uri: "friends/get_user_list", needLogin: true, args: {"userID": userID.toString()}, ).exec(); if (response.code != 200) throw new Exception("Could not get the list of friends of this user!"); return Set.from(response.getArray()); } }