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.

76 lines
1.9 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({
  12. int page = 0,
  13. DateTime? acceptedAt
  14. }) async {
  15. RSAPrivateKey privKey = await MyProfile.getPrivateKey();
  16. Map<String, String> params = {};
  17. if (page != 0) {
  18. params['page'] = page.toString();
  19. }
  20. if (acceptedAt != null) {
  21. params['updated_at'] = acceptedAt.toIso8601String();
  22. }
  23. var uri = await MyProfile.getServerUrl('api/v1/auth/friend_requests');
  24. uri = uri.replace(queryParameters: params);
  25. var resp = await http.get(
  26. uri,
  27. headers: {
  28. 'cookie': await getSessionCookie(),
  29. }
  30. );
  31. if (resp.statusCode != 200) {
  32. throw Exception(resp.body);
  33. }
  34. final db = await getDatabaseConnection();
  35. List<dynamic> friendsRequestJson = jsonDecode(resp.body);
  36. for (var i = 0; i < friendsRequestJson.length; i++) {
  37. Friend friend = Friend.fromJson(
  38. friendsRequestJson[i] as Map<String, dynamic>,
  39. privKey,
  40. );
  41. await db.insert(
  42. 'friends',
  43. friend.toMap(),
  44. conflictAlgorithm: ConflictAlgorithm.replace,
  45. );
  46. List<dynamic> tokens = (friendsRequestJson[i]['tokens']);
  47. for (var j = 0; j < tokens.length; j++) {
  48. DeviceToken token = DeviceToken.fromJson(
  49. tokens[j]['device_token'],
  50. friend.friendId,
  51. privKey,
  52. );
  53. await db.insert(
  54. 'device_tokens',
  55. token.toMap(),
  56. conflictAlgorithm: ConflictAlgorithm.replace,
  57. );
  58. }
  59. }
  60. }
  61. }