From 7a22adb9d656240907c9413f50e898d6ae33a9f8 Mon Sep 17 00:00:00 2001 From: Hank Grabowski Date: Fri, 24 Feb 2023 16:36:20 -0500 Subject: [PATCH] Change Auth Service to only handle credentials --- lib/friendica_client/friendica_client.dart | 3 +- lib/screens/image_viewer_screen.dart | 4 +- lib/screens/message_thread_screen.dart | 5 +-- lib/screens/profile_screen.dart | 2 +- lib/screens/user_profile_screen.dart | 2 +- .../direct_message_friendica_extensions.dart | 4 +- .../connection_mastodon_extensions.dart | 2 +- lib/services/auth_service.dart | 16 +++---- lib/services/connections_manager.dart | 44 +++++++++++-------- lib/services/direct_message_service.dart | 32 ++++++++------ lib/services/entry_manager_service.dart | 18 ++++---- lib/services/gallery_service.dart | 11 +++-- lib/services/interactions_manager.dart | 7 ++- lib/services/notifications_manager.dart | 15 ++++--- lib/services/timeline_manager.dart | 5 ++- 15 files changed, 99 insertions(+), 71 deletions(-) diff --git a/lib/friendica_client/friendica_client.dart b/lib/friendica_client/friendica_client.dart index 1de16c0..b05c774 100644 --- a/lib/friendica_client/friendica_client.dart +++ b/lib/friendica_client/friendica_client.dart @@ -39,8 +39,7 @@ class FriendicaClient { Credentials get credentials => _credentials; - FriendicaClient({required Credentials credentials}) - : _credentials = credentials { + FriendicaClient(Credentials credentials) : _credentials = credentials { _networkStatusService = getIt(); } diff --git a/lib/screens/image_viewer_screen.dart b/lib/screens/image_viewer_screen.dart index 0241ce1..0af26f1 100644 --- a/lib/screens/image_viewer_screen.dart +++ b/lib/screens/image_viewer_screen.dart @@ -9,6 +9,7 @@ import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:relatica/utils/clipboard_utils.dart'; +import '../friendica_client/friendica_client.dart'; import '../globals.dart'; import '../models/media_attachment.dart'; import '../services/auth_service.dart'; @@ -45,7 +46,8 @@ class _ImageViewerScreenState extends State { final appsDir = await getApplicationDocumentsDirectory(); final filename = p.basename(attachment.fullFileUri.path); final bytesResult = - await getIt().currentClient.getFileBytes(attachment.uri); + await FriendicaClient(getIt().currentCredentials) + .getFileBytes(attachment.uri); if (bytesResult.isFailure && mounted) { buildSnackbar(context, 'Error getting full size version of file: ${bytesResult.error}'); diff --git a/lib/screens/message_thread_screen.dart b/lib/screens/message_thread_screen.dart index 57dac33..e0a071d 100644 --- a/lib/screens/message_thread_screen.dart +++ b/lib/screens/message_thread_screen.dart @@ -47,9 +47,8 @@ class _MessageThreadScreenState extends State { ) { return result.fold( onSuccess: (thread) { - final yourId = getIt().currentClient.credentials.userId; - final yourAvatarUrl = - getIt().currentClient.credentials.avatar; + final yourId = getIt().currentCredentials.userId; + final yourAvatarUrl = getIt().currentCredentials.avatar; final participants = Map.fromEntries(thread.participants.map((p) => MapEntry(p.id, p))); return Center( diff --git a/lib/screens/profile_screen.dart b/lib/screens/profile_screen.dart index dc79cbd..0b0ce54 100644 --- a/lib/screens/profile_screen.dart +++ b/lib/screens/profile_screen.dart @@ -21,7 +21,7 @@ class _ProfileScreenState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text('Profile: ${authService.currentClient.credentials.handle}'), + Text('Profile: ${authService.currentCredentials.handle}'), ], ), ), diff --git a/lib/screens/user_profile_screen.dart b/lib/screens/user_profile_screen.dart index 9b47ca7..89e936a 100644 --- a/lib/screens/user_profile_screen.dart +++ b/lib/screens/user_profile_screen.dart @@ -43,7 +43,7 @@ class _UserProfileScreenState extends State { final manager = context.watch(); final body = manager.getById(widget.userId).fold(onSuccess: (profile) { final notMyProfile = - getIt().currentClient.credentials.userId != profile.id; + getIt().currentCredentials.userId != profile.id; return RefreshIndicator( onRefresh: () async { diff --git a/lib/serializers/friendica/direct_message_friendica_extensions.dart b/lib/serializers/friendica/direct_message_friendica_extensions.dart index 7fbcb0c..32717af 100644 --- a/lib/serializers/friendica/direct_message_friendica_extensions.dart +++ b/lib/serializers/friendica/direct_message_friendica_extensions.dart @@ -41,14 +41,14 @@ extension DirectMessageFriendicaExtension on DirectMessage { final String parentUri = json['friendica_parent_uri']; final cm = getIt(); - if (getIt().currentClient.credentials.userId != senderId) { + if (getIt().currentCredentials.userId != senderId) { final s = ConnectionFriendicaExtensions.fromJson(json['sender']); if (cm.getById(s.id).isFailure) { cm.addConnection(s); } } - if (getIt().currentClient.credentials.userId != recipientId) { + if (getIt().currentCredentials.userId != recipientId) { final r = ConnectionFriendicaExtensions.fromJson(json['recipient']); if (cm.getById(r.id).isFailure) { cm.addConnection(r); diff --git a/lib/serializers/mastodon/connection_mastodon_extensions.dart b/lib/serializers/mastodon/connection_mastodon_extensions.dart index 87404e6..12b6469 100644 --- a/lib/serializers/mastodon/connection_mastodon_extensions.dart +++ b/lib/serializers/mastodon/connection_mastodon_extensions.dart @@ -20,7 +20,7 @@ extension ConnectionMastodonExtensions on Connection { if (handleFromJson.contains('@')) { handle = handleFromJson; } else { - final server = getIt().currentClient.serverName; + final server = getIt().currentCredentials.serverName; handle = '$handleFromJson@$server'; } diff --git a/lib/services/auth_service.dart b/lib/services/auth_service.dart index 3c921d3..8c5bba0 100644 --- a/lib/services/auth_service.dart +++ b/lib/services/auth_service.dart @@ -10,13 +10,13 @@ import 'secrets_service.dart'; import 'timeline_manager.dart'; class AuthService extends ChangeNotifier { - FriendicaClient? _friendicaClient; + Credentials? _currentCredentials; bool _loggedIn = false; - bool get loggedIn => _loggedIn && _friendicaClient != null; + bool get loggedIn => _loggedIn && _currentCredentials != null; + + Credentials get currentCredentials => _currentCredentials!; - FriendicaClient get currentClient => _friendicaClient!; - Future getStoredLoginState() async { final prefs = await SharedPreferences.getInstance(); return prefs.getBool('logged-in') ?? false; @@ -24,7 +24,7 @@ class AuthService extends ChangeNotifier { FutureResult signIn( Credentials credentials) async { - final client = FriendicaClient(credentials: credentials); + final client = FriendicaClient(credentials); final result = await client.getMyProfile(); if (result.isFailure) { await clearCredentials(); @@ -38,7 +38,7 @@ class AuthService extends ChangeNotifier { ), ); await _setLoginState(true); - _friendicaClient = client; + _currentCredentials = credentials; notifyListeners(); return Result.ok(client); } @@ -46,12 +46,12 @@ class AuthService extends ChangeNotifier { Future signOut() async { await _setLoginState(false); getIt().clear(); - _friendicaClient = null; + _currentCredentials = null; notifyListeners(); } Future clearCredentials() async { - _friendicaClient = null; + _currentCredentials = null; await _setLoginState(false); notifyListeners(); } diff --git a/lib/services/connections_manager.dart b/lib/services/connections_manager.dart index 1cf43e3..e092757 100644 --- a/lib/services/connections_manager.dart +++ b/lib/services/connections_manager.dart @@ -7,6 +7,7 @@ import 'package:result_monad/result_monad.dart'; import '../data/interfaces/connections_repo_intf.dart'; import '../data/interfaces/groups_repo.intf.dart'; +import '../friendica_client/friendica_client.dart'; import '../friendica_client/paging_data.dart'; import '../globals.dart'; import '../models/connection.dart'; @@ -43,7 +44,9 @@ class ConnectionsManager extends ChangeNotifier { Future acceptFollowRequest(Connection connection) async { _logger.finest( 'Attempting to accept follow request ${connection.name}: ${connection.status}'); - await getIt().currentClient.acceptFollow(connection).match( + await FriendicaClient(getIt().currentCredentials) + .acceptFollow(connection) + .match( onSuccess: (update) { _logger .finest('Successfully followed ${update.name}: ${update.status}'); @@ -59,7 +62,9 @@ class ConnectionsManager extends ChangeNotifier { Future rejectFollowRequest(Connection connection) async { _logger.finest( 'Attempting to accept follow request ${connection.name}: ${connection.status}'); - await getIt().currentClient.rejectFollow(connection).match( + await FriendicaClient(getIt().currentCredentials) + .rejectFollow(connection) + .match( onSuccess: (update) { _logger .finest('Successfully followed ${update.name}: ${update.status}'); @@ -75,7 +80,9 @@ class ConnectionsManager extends ChangeNotifier { Future ignoreFollowRequest(Connection connection) async { _logger.finest( 'Attempting to accept follow request ${connection.name}: ${connection.status}'); - await getIt().currentClient.ignoreFollow(connection).match( + await FriendicaClient(getIt().currentCredentials) + .ignoreFollow(connection) + .match( onSuccess: (update) { _logger .finest('Successfully followed ${update.name}: ${update.status}'); @@ -91,7 +98,9 @@ class ConnectionsManager extends ChangeNotifier { Future follow(Connection connection) async { _logger.finest( 'Attempting to follow ${connection.name}: ${connection.status}'); - await getIt().currentClient.followConnection(connection).match( + await FriendicaClient(getIt().currentCredentials) + .followConnection(connection) + .match( onSuccess: (update) { _logger .finest('Successfully followed ${update.name}: ${update.status}'); @@ -107,8 +116,7 @@ class ConnectionsManager extends ChangeNotifier { Future unfollow(Connection connection) async { _logger.finest( 'Attempting to unfollow ${connection.name}: ${connection.status}'); - await getIt() - .currentClient + await FriendicaClient(getIt().currentCredentials) .unFollowConnection(connection) .match( onSuccess: (update) { @@ -129,7 +137,7 @@ class ConnectionsManager extends ChangeNotifier { Future updateAllContacts() async { _logger.fine('Updating all contacts'); - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final results = {}; var moreResults = true; var maxId = -1; @@ -206,9 +214,9 @@ class ConnectionsManager extends ChangeNotifier { FutureResult addUserToGroup( GroupData group, Connection connection) async { _logger.finest('Adding ${connection.name} to group: ${group.name}'); - final result = await getIt() - .currentClient - .addConnectionToGroup(group, connection); + final result = + await FriendicaClient(getIt().currentCredentials) + .addConnectionToGroup(group, connection); result.match( onSuccess: (_) => _refreshGroupListData(connection.id, true), onError: (error) { @@ -223,9 +231,9 @@ class ConnectionsManager extends ChangeNotifier { FutureResult removeUserFromGroup( GroupData group, Connection connection) async { _logger.finest('Removing ${connection.name} from group: ${group.name}'); - final result = await getIt() - .currentClient - .removeConnectionFromGroup(group, connection); + final result = + await FriendicaClient(getIt().currentCredentials) + .removeConnectionFromGroup(group, connection); result.match( onSuccess: (_) => _refreshGroupListData(connection.id, true), onError: (error) { @@ -273,8 +281,7 @@ class ConnectionsManager extends ChangeNotifier { Future _refreshGroupListData(String id, bool withNotification) async { _logger.finest('Refreshing member list data for Connection $id'); - await getIt() - .currentClient + await FriendicaClient(getIt().currentCredentials) .getMemberGroupsForConnection(id) .match( onSuccess: (groups) { @@ -292,8 +299,7 @@ class ConnectionsManager extends ChangeNotifier { Future _refreshConnection( Connection connection, bool withNotification) async { _logger.finest('Refreshing connection data for ${connection.name}'); - await getIt() - .currentClient + await FriendicaClient(getIt().currentCredentials) .getConnectionWithStatus(connection) .match( onSuccess: (update) { @@ -310,7 +316,9 @@ class ConnectionsManager extends ChangeNotifier { Future _updateMyGroups(bool withNotification) async { _logger.finest('Refreshing my groups list'); - await getIt().currentClient.getGroups().match( + await FriendicaClient(getIt().currentCredentials) + .getGroups() + .match( onSuccess: (groups) { _logger.finest('Got updated groups:${groups.map((e) => e.name)}'); groupsRepo.clearGroups(); diff --git a/lib/services/direct_message_service.dart b/lib/services/direct_message_service.dart index dbf0235..2fddc13 100644 --- a/lib/services/direct_message_service.dart +++ b/lib/services/direct_message_service.dart @@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:result_monad/result_monad.dart'; +import '../friendica_client/friendica_client.dart'; import '../friendica_client/paging_data.dart'; import '../globals.dart'; import '../models/connection.dart'; @@ -36,8 +37,7 @@ class DirectMessageService extends ChangeNotifier { } Future updateThreads() async { - await getIt() - .currentClient + await FriendicaClient(getIt().currentCredentials) .getDirectMessages(PagingData()) .match( onSuccess: (update) { @@ -61,11 +61,13 @@ class DirectMessageService extends ChangeNotifier { FutureResult newThread( Connection receiver, String text) async { - final result = await getIt().currentClient.postDirectMessage( - null, - receiver.id, - text, - ); + final result = + await FriendicaClient(getIt().currentCredentials) + .postDirectMessage( + null, + receiver.id, + text, + ); result.match(onSuccess: (newMessage) { DirectMessageThread.createThreads([newMessage]).forEach((thread) { _threads[thread.parentUri] = thread; @@ -99,11 +101,13 @@ class DirectMessageService extends ChangeNotifier { ); } - final result = await getIt().currentClient.postDirectMessage( - original.id, - original.senderId, - text, - ); + final result = + await FriendicaClient(getIt().currentCredentials) + .postDirectMessage( + original.id, + original.senderId, + text, + ); result.match(onSuccess: (newMessage) { thread.messages.add(newMessage); notifyListeners(); @@ -126,7 +130,9 @@ class DirectMessageService extends ChangeNotifier { return; } - await getIt().currentClient.markDirectMessageRead(m).match( + await FriendicaClient(getIt().currentCredentials) + .markDirectMessageRead(m) + .match( onSuccess: (update) { thread.messages.removeAt(oldIndex); thread.messages.insert(oldIndex, update); diff --git a/lib/services/entry_manager_service.dart b/lib/services/entry_manager_service.dart index a4cb8aa..6092e96 100644 --- a/lib/services/entry_manager_service.dart +++ b/lib/services/entry_manager_service.dart @@ -43,7 +43,7 @@ class EntryManagerService extends ChangeNotifier { Result getPostTreeEntryBy(String id) { _logger.finest('Getting post: $id'); - final currentId = getIt().currentClient.credentials.userId; + final currentId = getIt().currentCredentials.userId; final postNode = _getPostRootNode(id); if (postNode == null) { return Result.error(ExecError( @@ -68,7 +68,9 @@ class EntryManagerService extends ChangeNotifier { FutureResult deleteEntryById(String id) async { _logger.finest('Delete entry: $id'); - final result = await getIt().currentClient.deleteEntryById(id); + final result = + await FriendicaClient(getIt().currentCredentials) + .deleteEntryById(id); if (result.isFailure) { return result.errorCast(); } @@ -86,7 +88,7 @@ class EntryManagerService extends ChangeNotifier { required List existingMediaItems, }) async { _logger.finest('Creating new post: $text'); - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final mediaIds = existingMediaItems.map((m) => m.scales.first.id).toList(); for (final item in mediaItems.attachments) { if (item.isExistingServerItem) { @@ -166,7 +168,7 @@ class EntryManagerService extends ChangeNotifier { FutureResult, ExecError> updateTimeline( TimelineIdentifiers type, int maxId, int sinceId) async { _logger.fine(() => 'Updating timeline'); - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final itemsResult = await client.getTimeline( type: type, page: PagingData( @@ -301,7 +303,7 @@ class EntryManagerService extends ChangeNotifier { FutureResult refreshStatusChain(String id) async { _logger.finest('Refreshing post: $id'); - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final result = await client .getPostOrComment(id, fullContext: false) .andThenAsync((rootItems) async => await client @@ -328,7 +330,7 @@ class EntryManagerService extends ChangeNotifier { FutureResult resharePost(String id) async { _logger.finest('Resharing post: $id'); - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final result = await client.resharePost(id).andThenSuccessAsync((item) async { await processNewItems([item], client.credentials.username, null); @@ -350,7 +352,7 @@ class EntryManagerService extends ChangeNotifier { FutureResult unResharePost(String id) async { _logger.finest('Unresharing post: $id'); - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final result = await client.unResharePost(id).andThenSuccessAsync((item) async { await processNewItems([item], client.credentials.username, null); @@ -368,7 +370,7 @@ class EntryManagerService extends ChangeNotifier { FutureResult toggleFavorited( String id, bool newStatus) async { - final client = getIt().currentClient; + final client = FriendicaClient(getIt().currentCredentials); final result = await client.changeFavoriteStatus(id, newStatus); if (result.isFailure) { return result.errorCast(); diff --git a/lib/services/gallery_service.dart b/lib/services/gallery_service.dart index 4c23cdc..1378d13 100644 --- a/lib/services/gallery_service.dart +++ b/lib/services/gallery_service.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:result_monad/result_monad.dart'; +import '../friendica_client/friendica_client.dart'; import '../friendica_client/paging_data.dart'; import '../globals.dart'; import '../models/exec_error.dart'; @@ -39,7 +40,9 @@ class GalleryService extends ChangeNotifier { } FutureResult, ExecError> updateGalleries() async { - final result = await getIt().currentClient.getGalleryData(); + final result = + await FriendicaClient(getIt().currentCredentials) + .getGalleryData(); if (result.isFailure) { return result.errorCast(); } @@ -88,9 +91,9 @@ class GalleryService extends ChangeNotifier { final pagesToUse = nextPageOnly ? [pages.last] : pages; for (final page in pagesToUse) { - final result = await getIt() - .currentClient - .getGalleryImages(galleryName, page); + final result = + await FriendicaClient(getIt().currentCredentials) + .getGalleryImages(galleryName, page); if (result.isFailure) { return result.errorCast(); } diff --git a/lib/services/interactions_manager.dart b/lib/services/interactions_manager.dart index e6761e2..b304585 100644 --- a/lib/services/interactions_manager.dart +++ b/lib/services/interactions_manager.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:result_monad/result_monad.dart'; +import '../friendica_client/friendica_client.dart'; import '../globals.dart'; import '../models/connection.dart'; import '../models/exec_error.dart'; @@ -31,7 +32,8 @@ class InteractionsManager extends ChangeNotifier { FutureResult, ExecError> updateLikesForStatus( String statusId) async { final likesResult = - await getIt().currentClient.getLikes(statusId); + await FriendicaClient(getIt().currentCredentials) + .getLikes(statusId); if (likesResult.isSuccess) { _likesByStatusId[statusId] = likesResult.value; notifyListeners(); @@ -42,7 +44,8 @@ class InteractionsManager extends ChangeNotifier { FutureResult, ExecError> updateResharesForStatus( String statusId) async { final resharesResult = - await getIt().currentClient.getReshares(statusId); + await FriendicaClient(getIt().currentCredentials) + .getReshares(statusId); if (resharesResult.isSuccess) { _resharesByStatusId[statusId] = resharesResult.value; notifyListeners(); diff --git a/lib/services/notifications_manager.dart b/lib/services/notifications_manager.dart index b916276..aa33132 100644 --- a/lib/services/notifications_manager.dart +++ b/lib/services/notifications_manager.dart @@ -4,6 +4,7 @@ import 'package:relatica/services/network_status_service.dart'; import 'package:result_monad/result_monad.dart'; import 'package:uuid/uuid.dart'; +import '../friendica_client/friendica_client.dart'; import '../friendica_client/paged_response.dart'; import '../friendica_client/pages_manager.dart'; import '../friendica_client/paging_data.dart'; @@ -127,9 +128,9 @@ class NotificationsManager extends ChangeNotifier { } FutureResult markSeen(UserNotification notification) async { - final result = await getIt() - .currentClient - .clearNotification(notification); + final result = + await FriendicaClient(getIt().currentCredentials) + .clearNotification(notification); if (result.isSuccess) { notifyListeners(); } @@ -140,7 +141,8 @@ class NotificationsManager extends ChangeNotifier { FutureResult, ExecError> markAllAsRead() async { final result = - await getIt().currentClient.clearNotifications(); + await FriendicaClient(getIt().currentCredentials) + .clearNotifications(); if (result.isFailure) { return result.errorCast(); } @@ -151,7 +153,7 @@ class NotificationsManager extends ChangeNotifier { } List buildUnreadMessageNotifications() { - final myId = getIt().currentClient.credentials.userId; + final myId = getIt().currentCredentials.userId; final result = getIt().getThreads(unreadyOnly: true).map((t) { final fromAccount = t.participants.firstWhere((p) => p.id != myId); @@ -176,7 +178,8 @@ class NotificationsManager extends ChangeNotifier { static FutureResult>, ExecError> _clientGetNotificationsRequest(PagingData page) async { final result = - await getIt().currentClient.getNotifications(page); + await FriendicaClient(getIt().currentCredentials) + .getNotifications(page); return result; } } diff --git a/lib/services/timeline_manager.dart b/lib/services/timeline_manager.dart index 42fb888..6c05cf4 100644 --- a/lib/services/timeline_manager.dart +++ b/lib/services/timeline_manager.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; import 'package:result_monad/result_monad.dart'; +import '../friendica_client/friendica_client.dart'; import '../globals.dart'; import '../models/TimelineIdentifiers.dart'; import '../models/entry_tree_item.dart'; @@ -45,7 +46,9 @@ class TimelineManager extends ChangeNotifier { Future _refreshGroupData() async { _logger.finest('Refreshing member group data '); - await getIt().currentClient.getGroups().match( + await FriendicaClient(getIt().currentCredentials) + .getGroups() + .match( onSuccess: (groups) { _groups.clear(); for (final group in groups) {