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.

69 lines
1.8 KiB

  1. import 'dart:convert';
  2. import 'package:Envelope/database/models/device_tokens.dart';
  3. import 'package:http/http.dart' as http;
  4. import 'package:pointycastle/export.dart';
  5. import 'package:sqflite/sqflite.dart';
  6. import '/database/models/friends.dart';
  7. import '/database/models/my_profile.dart';
  8. import '/utils/storage/database.dart';
  9. import '/utils/storage/session_cookie.dart';
  10. class FriendsService {
  11. static Future<void> updateFriends({DateTime? acceptedAt}) async {
  12. RSAPrivateKey privKey = await MyProfile.getPrivateKey();
  13. Map<String, String> params = {};
  14. if (acceptedAt != null) {
  15. params['updated_at'] = acceptedAt.toIso8601String();
  16. }
  17. var uri = await MyProfile.getServerUrl('api/v1/auth/friend_requests');
  18. uri = uri.replace(queryParameters: params);
  19. var resp = await http.get(
  20. uri,
  21. headers: {
  22. 'cookie': await getSessionCookie(),
  23. }
  24. );
  25. if (resp.statusCode != 200) {
  26. throw Exception(resp.body);
  27. }
  28. final db = await getDatabaseConnection();
  29. List<dynamic> friendsRequestJson = jsonDecode(resp.body);
  30. for (var i = 0; i < friendsRequestJson.length; i++) {
  31. Friend friend = Friend.fromJson(
  32. friendsRequestJson[i] as Map<String, dynamic>,
  33. privKey,
  34. );
  35. await db.insert(
  36. 'friends',
  37. friend.toMap(),
  38. conflictAlgorithm: ConflictAlgorithm.replace,
  39. );
  40. List<dynamic> tokens = (friendsRequestJson[i]['tokens']);
  41. for (var j = 0; j < tokens.length; j++) {
  42. DeviceToken token = DeviceToken.fromJson(
  43. tokens[j]['device_token'],
  44. friend.friendId,
  45. privKey,
  46. );
  47. await db.insert(
  48. 'device_tokens',
  49. token.toMap(),
  50. conflictAlgorithm: ConflictAlgorithm.replace,
  51. );
  52. }
  53. }
  54. }
  55. }