Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.2 KiB

  1. import 'dart:convert';
  2. import 'package:http/http.dart' as http;
  3. import 'package:pointycastle/export.dart';
  4. import 'package:sqflite/sqflite.dart';
  5. import 'package:flutter_dotenv/flutter_dotenv.dart';
  6. import '/models/friends.dart';
  7. import '/utils/storage/database.dart';
  8. import '/utils/storage/encryption_keys.dart';
  9. import '/utils/storage/session_cookie.dart';
  10. import '/utils/encryption/aes_helper.dart';
  11. Future<void> updateFriends() async {
  12. RSAPrivateKey privKey = await getPrivateKey();
  13. var resp = await http.get(
  14. Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'),
  15. headers: {
  16. 'cookie': await getSessionCookie(),
  17. }
  18. );
  19. if (resp.statusCode != 200) {
  20. throw Exception(resp.body);
  21. }
  22. List<Friend> friends = [];
  23. List<String> friendIds = [];
  24. List<dynamic> friendsRequestJson = jsonDecode(resp.body);
  25. for (var i = 0; i < friendsRequestJson.length; i++) {
  26. friends.add(
  27. Friend.fromJson(
  28. friendsRequestJson[i] as Map<String, dynamic>,
  29. privKey,
  30. )
  31. );
  32. friendIds.add(friends[i].friendId);
  33. }
  34. Map<String, String> params = {};
  35. params['friend_ids'] = friendIds.join(',');
  36. var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friends');
  37. uri = uri.replace(queryParameters: params);
  38. resp = await http.get(
  39. uri,
  40. headers: {
  41. 'cookie': await getSessionCookie(),
  42. }
  43. );
  44. if (resp.statusCode != 200) {
  45. throw Exception(resp.body);
  46. }
  47. final db = await getDatabaseConnection();
  48. List<dynamic> friendsJson = jsonDecode(resp.body);
  49. for (var i = 0; i < friendsJson.length; i++) {
  50. var friendJson = friendsJson[i] as Map<String, dynamic>;
  51. var friend = findFriendByFriendId(friends, friendJson['id']);
  52. friend.username = AesHelper.aesDecrypt(
  53. base64.decode(friend.friendSymmetricKey),
  54. base64.decode(friendJson['username']),
  55. );
  56. await db.insert(
  57. 'friends',
  58. friend.toMap(),
  59. conflictAlgorithm: ConflictAlgorithm.replace,
  60. );
  61. }
  62. }