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<void> 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<Friend> friends = [];
|
|
List<String> friendIds = [];
|
|
|
|
List<dynamic> friendsRequestJson = jsonDecode(resp.body);
|
|
|
|
for (var i = 0; i < friendsRequestJson.length; i++) {
|
|
friends.add(
|
|
Friend.fromJson(
|
|
friendsRequestJson[i] as Map<String, dynamic>,
|
|
privKey,
|
|
)
|
|
);
|
|
|
|
friendIds.add(friends[i].friendId);
|
|
}
|
|
|
|
Map<String, String> 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<dynamic> friendsJson = jsonDecode(resp.body);
|
|
for (var i = 0; i < friendsJson.length; i++) {
|
|
var friendJson = friendsJson[i] as Map<String, dynamic>;
|
|
var friend = findFriendByFriendId(friends, friendJson['id']);
|
|
|
|
friend.username = AesHelper.aesDecrypt(
|
|
base64.decode(friend.friendSymmetricKey),
|
|
base64.decode(friendJson['username']),
|
|
);
|
|
|
|
friend.asymmetricPublicKey = friendJson['asymmetric_public_key'];
|
|
|
|
await db.insert(
|
|
'friends',
|
|
friend.toMap(),
|
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
|
);
|
|
}
|
|
}
|
|
|