import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import '/models/friends.dart'; import '/utils/storage/database.dart'; import '/utils/storage/encryption_keys.dart'; import '/utils/storage/session_cookie.dart'; import '/utils/encryption/aes_helper.dart'; Future updateFriends() async { RSAPrivateKey privKey = await getPrivateKey(); var resp = await http.get( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'), headers: { 'cookie': await getSessionCookie(), } ); if (resp.statusCode != 200) { throw Exception(resp.body); } List friends = []; List friendIds = []; List friendsRequestJson = jsonDecode(resp.body); for (var i = 0; i < friendsRequestJson.length; i++) { friends.add( Friend.fromJson( friendsRequestJson[i] as Map, privKey, ) ); friendIds.add(friends[i].friendId); } Map params = {}; params['friend_ids'] = friendIds.join(','); var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friends'); uri = uri.replace(queryParameters: params); resp = await http.get( uri, headers: { 'cookie': await getSessionCookie(), } ); if (resp.statusCode != 200) { throw Exception(resp.body); } final db = await getDatabaseConnection(); List friendsJson = jsonDecode(resp.body); for (var i = 0; i < friendsJson.length; i++) { var friendJson = friendsJson[i] as Map; var friend = findFriendByFriendId(friends, friendJson['id']); friend.username = AesHelper.aesDecrypt( base64.decode(friend.friendSymmetricKey), base64.decode(friendJson['username']), ); await db.insert( 'friends', friend.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); } }