From a2bd2e4b53cbab15db600f9afbf8bb6e0cef416f Mon Sep 17 00:00:00 2001 From: Ammar Githam Date: Sun, 6 Jun 2021 10:11:30 +0900 Subject: [PATCH] Convert UserRepository and UserService to kotlin --- .../dialogs/ProfilePicDialogFragment.java | 41 +++---- .../fragments/main/ProfileFragment.java | 66 +++++------ .../settings/MorePreferencesFragment.java | 70 ++++++----- .../repositories/UserRepository.kt | 32 ++--- .../viewmodels/AppStateViewModel.java | 21 ++-- .../viewmodels/UserSearchViewModel.java | 60 ++++------ .../instagrabber/webservices/UserService.kt | 112 ++++-------------- 7 files changed, 147 insertions(+), 255 deletions(-) diff --git a/app/src/main/java/awais/instagrabber/dialogs/ProfilePicDialogFragment.java b/app/src/main/java/awais/instagrabber/dialogs/ProfilePicDialogFragment.java index 84a829cb..e1915f8d 100644 --- a/app/src/main/java/awais/instagrabber/dialogs/ProfilePicDialogFragment.java +++ b/app/src/main/java/awais/instagrabber/dialogs/ProfilePicDialogFragment.java @@ -28,13 +28,14 @@ import java.io.File; import awais.instagrabber.R; import awais.instagrabber.databinding.DialogProfilepicBinding; -import awais.instagrabber.repositories.responses.User; +import awais.instagrabber.utils.AppExecutors; import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.CookieUtils; +import awais.instagrabber.utils.CoroutineUtilsKt; import awais.instagrabber.utils.DownloadUtils; import awais.instagrabber.utils.TextUtils; -import awais.instagrabber.webservices.ServiceCallback; import awais.instagrabber.webservices.UserService; +import kotlinx.coroutines.Dispatchers; import static awais.instagrabber.utils.Utils.settingsHelper; @@ -129,33 +130,29 @@ public class ProfilePicDialogFragment extends DialogFragment { private void fetchAvatar() { if (isLoggedIn) { - final UserService userService = UserService.getInstance(); - userService.getUserInfo(id, new ServiceCallback() { - @Override - public void onSuccess(final User result) { - if (result != null) { - final String url = result.getHDProfilePicUrl(); - if (url == null) { - final Context context = getContext(); - if (context == null) return; - Toast.makeText(context, R.string.no_profile_pic_found, Toast.LENGTH_LONG).show(); - return; - } - setupPhoto(url); - } - } - - @Override - public void onFailure(final Throwable t) { + final UserService userService = UserService.INSTANCE; + userService.getUserInfo(id, CoroutineUtilsKt.getContinuation((user, throwable) -> AppExecutors.INSTANCE.getMainThread().execute(() -> { + if (throwable != null) { final Context context = getContext(); if (context == null) { dismiss(); return; } - Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show(); + Toast.makeText(context, throwable.getMessage(), Toast.LENGTH_SHORT).show(); dismiss(); + return; } - }); + if (user != null) { + final String url = user.getHDProfilePicUrl(); + if (TextUtils.isEmpty(url)) { + final Context context = getContext(); + if (context == null) return; + Toast.makeText(context, R.string.no_profile_pic_found, Toast.LENGTH_LONG).show(); + return; + } + setupPhoto(url); + } + }), Dispatchers.getIO())); } else setupPhoto(fallbackUrl); } diff --git a/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java b/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java index 8b4186a8..f6028715 100644 --- a/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java @@ -338,7 +338,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe directMessagesService = isLoggedIn ? DirectMessagesService.getInstance(csrfToken, myId, deviceUuid) : null; storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : null; mediaService = isLoggedIn ? MediaService.INSTANCE : null; - userService = isLoggedIn ? UserService.getInstance() : null; + userService = isLoggedIn ? UserService.INSTANCE : null; graphQLService = isLoggedIn ? null : GraphQLService.getInstance(); final Context context = getContext(); if (context == null) return; @@ -586,44 +586,36 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe return; } if (isLoggedIn) { - userService.getUsernameInfo(usernameTemp, new ServiceCallback() { - @Override - public void onSuccess(final User user) { - userService.getUserFriendship(user.getPk(), new ServiceCallback() { - @Override - public void onSuccess(final FriendshipStatus status) { - user.setFriendshipStatus(status); - profileModel = user; - setProfileDetails(); - } - - @Override - public void onFailure(final Throwable t) { - Log.e(TAG, "Error fetching profile relationship", t); + userService.getUsernameInfo( + usernameTemp, + CoroutineUtilsKt.getContinuation((user, throwable) -> AppExecutors.INSTANCE.getMainThread().execute(() -> { + if (throwable != null) { + Log.e(TAG, "Error fetching profile", throwable); final Context context = getContext(); - try { - if (t == null) - Toast.makeText(context, R.string.error_loading_profile_loggedin, Toast.LENGTH_LONG).show(); - else - Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show(); - } catch (final Throwable ignored) { - } + if (context == null) return; + Toast.makeText(context, throwable.getMessage(), Toast.LENGTH_SHORT).show(); + return; } - }); - } - - @Override - public void onFailure(final Throwable t) { - Log.e(TAG, "Error fetching profile", t); - final Context context = getContext(); - try { - if (t == null) - Toast.makeText(context, R.string.error_loading_profile_loggedin, Toast.LENGTH_LONG).show(); - else Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show(); - } catch (final Throwable ignored) { - } - } - }); + userService.getUserFriendship( + user.getPk(), + CoroutineUtilsKt.getContinuation( + (friendshipStatus, throwable1) -> AppExecutors.INSTANCE.getMainThread().execute(() -> { + if (throwable1 != null) { + Log.e(TAG, "Error fetching profile relationship", throwable1); + final Context context = getContext(); + if (context == null) return; + Toast.makeText(context, throwable1.getMessage(), + Toast.LENGTH_SHORT).show(); + return; + } + user.setFriendshipStatus(friendshipStatus); + profileModel = user; + setProfileDetails(); + }), Dispatchers.getIO() + ) + ); + }), Dispatchers.getIO()) + ); return; } graphQLService.fetchUser(usernameTemp, new ServiceCallback() { diff --git a/app/src/main/java/awais/instagrabber/fragments/settings/MorePreferencesFragment.java b/app/src/main/java/awais/instagrabber/fragments/settings/MorePreferencesFragment.java index dc8861db..c98a6c06 100644 --- a/app/src/main/java/awais/instagrabber/fragments/settings/MorePreferencesFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/settings/MorePreferencesFragment.java @@ -36,16 +36,16 @@ import awais.instagrabber.db.entities.Account; import awais.instagrabber.db.repositories.AccountRepository; import awais.instagrabber.db.repositories.RepositoryCallback; import awais.instagrabber.dialogs.AccountSwitcherDialogFragment; -import awais.instagrabber.repositories.responses.User; import awais.instagrabber.utils.AppExecutors; import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.CookieUtils; +import awais.instagrabber.utils.CoroutineUtilsKt; import awais.instagrabber.utils.FlavorTown; import awais.instagrabber.utils.ProcessPhoenix; import awais.instagrabber.utils.TextUtils; import awais.instagrabber.utils.Utils; -import awais.instagrabber.webservices.ServiceCallback; import awais.instagrabber.webservices.UserService; +import kotlinx.coroutines.Dispatchers; import static awais.instagrabber.utils.Utils.settingsHelper; @@ -288,44 +288,40 @@ public class MorePreferencesFragment extends BasePreferencesFragment { // adds cookies to database for quick access final long uid = CookieUtils.getUserIdFromCookie(cookie); - final UserService userService = UserService.getInstance(); - userService.getUserInfo(uid, new ServiceCallback() { - @Override - public void onSuccess(final User result) { + final UserService userService = UserService.INSTANCE; + userService.getUserInfo(uid, CoroutineUtilsKt.getContinuation((user, throwable) -> AppExecutors.INSTANCE.getMainThread().execute(() -> { + if (throwable != null) { + Log.e(TAG, "Error fetching user info", throwable); + return; + } + if (user != null) { // Log.d(TAG, "adding userInfo: " + result); - if (result != null) { - accountRepository.insertOrUpdateAccount( - uid, - result.getUsername(), - cookie, - result.getFullName(), - result.getProfilePicUrl(), - new RepositoryCallback() { - @Override - public void onSuccess(final Account result) { - // final FragmentActivity activity = getActivity(); - // if (activity == null) return; - // activity.recreate(); - AppExecutors.INSTANCE.getMainThread().execute(() -> { - final Context context = getContext(); - if (context == null) return; - ProcessPhoenix.triggerRebirth(context); - }, 200); - } + accountRepository.insertOrUpdateAccount( + uid, + user.getUsername(), + cookie, + user.getFullName(), + user.getProfilePicUrl(), + new RepositoryCallback() { + @Override + public void onSuccess(final Account result) { + // final FragmentActivity activity = getActivity(); + // if (activity == null) return; + // activity.recreate(); + AppExecutors.INSTANCE.getMainThread().execute(() -> { + final Context context = getContext(); + if (context == null) return; + ProcessPhoenix.triggerRebirth(context); + }, 200); + } - @Override - public void onDataNotAvailable() { - Log.e(TAG, "onDataNotAvailable: insert failed"); - } - }); - } + @Override + public void onDataNotAvailable() { + Log.e(TAG, "onDataNotAvailable: insert failed"); + } + }); } - - @Override - public void onFailure(final Throwable t) { - Log.e(TAG, "Error fetching user info", t); - } - }); + }), Dispatchers.getIO())); } } diff --git a/app/src/main/java/awais/instagrabber/repositories/UserRepository.kt b/app/src/main/java/awais/instagrabber/repositories/UserRepository.kt index 4b14034b..7264505b 100644 --- a/app/src/main/java/awais/instagrabber/repositories/UserRepository.kt +++ b/app/src/main/java/awais/instagrabber/repositories/UserRepository.kt @@ -1,25 +1,25 @@ -package awais.instagrabber.repositories; +package awais.instagrabber.repositories -import awais.instagrabber.repositories.responses.FriendshipStatus; -import awais.instagrabber.repositories.responses.UserSearchResponse; -import awais.instagrabber.repositories.responses.WrappedUser; -import retrofit2.Call; -import retrofit2.http.GET; -import retrofit2.http.Path; -import retrofit2.http.Query; - -public interface UserRepository { +import awais.instagrabber.repositories.responses.FriendshipStatus +import awais.instagrabber.repositories.responses.UserSearchResponse +import awais.instagrabber.repositories.responses.WrappedUser +import retrofit2.http.GET +import retrofit2.http.Path +import retrofit2.http.Query +interface UserRepository { @GET("/api/v1/users/{uid}/info/") - Call getUserInfo(@Path("uid") final long uid); + suspend fun getUserInfo(@Path("uid") uid: Long): WrappedUser @GET("/api/v1/users/{username}/usernameinfo/") - Call getUsernameInfo(@Path("username") final String username); + suspend fun getUsernameInfo(@Path("username") username: String): WrappedUser @GET("/api/v1/friendships/show/{uid}/") - Call getUserFriendship(@Path("uid") final long uid); + suspend fun getUserFriendship(@Path("uid") uid: Long): FriendshipStatus @GET("/api/v1/users/search/") - Call search(@Query("timezone_offset") float timezoneOffset, - @Query("q") String query); -} + suspend fun search( + @Query("timezone_offset") timezoneOffset: Float, + @Query("q") query: String, + ): UserSearchResponse +} \ No newline at end of file diff --git a/app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java b/app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java index 5b5bb54e..f7e4c1e9 100644 --- a/app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java +++ b/app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java @@ -12,9 +12,10 @@ import androidx.lifecycle.MutableLiveData; import awais.instagrabber.repositories.responses.User; import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.CookieUtils; +import awais.instagrabber.utils.CoroutineUtilsKt; import awais.instagrabber.utils.TextUtils; -import awais.instagrabber.webservices.ServiceCallback; import awais.instagrabber.webservices.UserService; +import kotlinx.coroutines.Dispatchers; import static awais.instagrabber.utils.Utils.settingsHelper; @@ -32,7 +33,7 @@ public class AppStateViewModel extends AndroidViewModel { cookie = settingsHelper.getString(Constants.COOKIE); final boolean isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != 0; if (!isLoggedIn) return; - userService = UserService.getInstance(); + userService = UserService.INSTANCE; // final AccountRepository accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(application)); fetchProfileDetails(); } @@ -49,16 +50,12 @@ public class AppStateViewModel extends AndroidViewModel { private void fetchProfileDetails() { final long uid = CookieUtils.getUserIdFromCookie(cookie); if (userService == null) return; - userService.getUserInfo(uid, new ServiceCallback() { - @Override - public void onSuccess(final User user) { - currentUser.postValue(user); + userService.getUserInfo(uid, CoroutineUtilsKt.getContinuation((user, throwable) -> { + if (throwable != null) { + Log.e(TAG, "onFailure: ", throwable); + return; } - - @Override - public void onFailure(final Throwable t) { - Log.e(TAG, "onFailure: ", t); - } - }); + currentUser.postValue(user); + }, Dispatchers.getIO())); } } diff --git a/app/src/main/java/awais/instagrabber/viewmodels/UserSearchViewModel.java b/app/src/main/java/awais/instagrabber/viewmodels/UserSearchViewModel.java index 51ab0e9b..aef2d8ca 100644 --- a/app/src/main/java/awais/instagrabber/viewmodels/UserSearchViewModel.java +++ b/app/src/main/java/awais/instagrabber/viewmodels/UserSearchViewModel.java @@ -24,7 +24,6 @@ import awais.instagrabber.R; import awais.instagrabber.fragments.UserSearchFragment; import awais.instagrabber.models.Resource; import awais.instagrabber.repositories.responses.User; -import awais.instagrabber.repositories.responses.UserSearchResponse; import awais.instagrabber.repositories.responses.directmessages.RankedRecipient; import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.CookieUtils; @@ -37,7 +36,6 @@ import awais.instagrabber.webservices.UserService; import kotlinx.coroutines.Dispatchers; import okhttp3.ResponseBody; import retrofit2.Call; -import retrofit2.Callback; import retrofit2.Response; import static awais.instagrabber.utils.Utils.settingsHelper; @@ -72,7 +70,7 @@ public class UserSearchViewModel extends ViewModel { if (TextUtils.isEmpty(csrfToken) || viewerId <= 0 || TextUtils.isEmpty(deviceUuid)) { throw new IllegalArgumentException("User is not logged in!"); } - userService = UserService.getInstance(); + userService = UserService.INSTANCE; directMessagesService = DirectMessagesService.getInstance(csrfToken, viewerId, deviceUuid); rankedRecipientsCache = RankedRecipientsCache.INSTANCE; if ((rankedRecipientsCache.isFailed() || rankedRecipientsCache.isExpired()) && !rankedRecipientsCache.isUpdateInitiated()) { @@ -170,9 +168,26 @@ public class UserSearchViewModel extends ViewModel { } private void defaultUserSearch() { - searchRequest = userService.search(currentQuery); - //noinspection unchecked - handleRequest((Call) searchRequest); + userService.search(currentQuery, CoroutineUtilsKt.getContinuation((userSearchResponse, throwable) -> { + if (throwable != null) { + Log.e(TAG, "onFailure: ", throwable); + recipients.postValue(Resource.error(throwable.getMessage(), getCachedRecipients())); + searchRequest = null; + return; + } + if (userSearchResponse == null) { + recipients.postValue(Resource.error(R.string.generic_null_response, getCachedRecipients())); + searchRequest = null; + return; + } + final List list = userSearchResponse + .getUsers() + .stream() + .map(RankedRecipient::of) + .collect(Collectors.toList()); + recipients.postValue(Resource.success(mergeResponseWithCache(list))); + searchRequest = null; + })); } private void rankedRecipientSearch() { @@ -194,39 +209,6 @@ public class UserSearchViewModel extends ViewModel { ); } - private void handleRequest(@NonNull final Call request) { - request.enqueue(new Callback() { - @Override - public void onResponse(@NonNull final Call call, @NonNull final Response response) { - if (!response.isSuccessful()) { - handleErrorResponse(response, true); - searchRequest = null; - return; - } - final UserSearchResponse userSearchResponse = response.body(); - if (userSearchResponse == null) { - recipients.postValue(Resource.error(R.string.generic_null_response, getCachedRecipients())); - searchRequest = null; - return; - } - final List list = userSearchResponse - .getUsers() - .stream() - .map(RankedRecipient::of) - .collect(Collectors.toList()); - recipients.postValue(Resource.success(mergeResponseWithCache(list))); - searchRequest = null; - } - - @Override - public void onFailure(@NonNull final Call call, @NonNull final Throwable t) { - Log.e(TAG, "onFailure: ", t); - recipients.postValue(Resource.error(t.getMessage(), getCachedRecipients())); - searchRequest = null; - } - }); - } - private List mergeResponseWithCache(@NonNull final List list) { final Iterator iterator = list.stream() .filter(Objects::nonNull) diff --git a/app/src/main/java/awais/instagrabber/webservices/UserService.kt b/app/src/main/java/awais/instagrabber/webservices/UserService.kt index 2537e6ee..708f1d8b 100644 --- a/app/src/main/java/awais/instagrabber/webservices/UserService.kt +++ b/app/src/main/java/awais/instagrabber/webservices/UserService.kt @@ -1,101 +1,29 @@ -package awais.instagrabber.webservices; +package awais.instagrabber.webservices -import androidx.annotation.NonNull; +import awais.instagrabber.repositories.UserRepository +import awais.instagrabber.repositories.responses.FriendshipStatus +import awais.instagrabber.repositories.responses.User +import awais.instagrabber.repositories.responses.UserSearchResponse +import awais.instagrabber.webservices.RetrofitFactory.retrofit +import java.util.* -import java.util.TimeZone; +object UserService : BaseService() { + private val repository: UserRepository = retrofit.create(UserRepository::class.java) -import awais.instagrabber.repositories.UserRepository; -import awais.instagrabber.repositories.responses.FriendshipStatus; -import awais.instagrabber.repositories.responses.User; -import awais.instagrabber.repositories.responses.UserSearchResponse; -import awais.instagrabber.repositories.responses.WrappedUser; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; - -public class UserService extends BaseService { - private static final String TAG = UserService.class.getSimpleName(); - - private final UserRepository repository; - - private static UserService instance; - - private UserService() { - repository = RetrofitFactory.INSTANCE - .getRetrofit() - .create(UserRepository.class); + suspend fun getUserInfo(uid: Long): User { + val response = repository.getUserInfo(uid) + return response.user } - public static UserService getInstance() { - if (instance == null) { - instance = new UserService(); - } - return instance; + suspend fun getUsernameInfo(username: String): User { + val response = repository.getUsernameInfo(username) + return response.user } - public void getUserInfo(final long uid, final ServiceCallback callback) { - final Call request = repository.getUserInfo(uid); - request.enqueue(new Callback() { - @Override - public void onResponse(@NonNull final Call call, @NonNull final Response response) { - final WrappedUser user = response.body(); - if (user == null) { - callback.onSuccess(null); - return; - } - callback.onSuccess(user.getUser()); - } + suspend fun getUserFriendship(uid: Long): FriendshipStatus = repository.getUserFriendship(uid) - @Override - public void onFailure(@NonNull final Call call, @NonNull final Throwable t) { - callback.onFailure(t); - } - }); + suspend fun search(query: String): UserSearchResponse { + val timezoneOffset = TimeZone.getDefault().rawOffset.toFloat() / 1000 + return repository.search(timezoneOffset, query) } - - public void getUsernameInfo(final String username, final ServiceCallback callback) { - final Call request = repository.getUsernameInfo(username); - request.enqueue(new Callback() { - @Override - public void onResponse(@NonNull final Call call, @NonNull final Response response) { - final WrappedUser user = response.body(); - if (user == null) { - callback.onFailure(null); - return; - } - callback.onSuccess(user.getUser()); - } - - @Override - public void onFailure(@NonNull final Call call, @NonNull final Throwable t) { - callback.onFailure(t); - } - }); - } - - public void getUserFriendship(final long uid, final ServiceCallback callback) { - final Call request = repository.getUserFriendship(uid); - request.enqueue(new Callback() { - @Override - public void onResponse(@NonNull final Call call, @NonNull final Response response) { - final FriendshipStatus status = response.body(); - if (status == null) { - callback.onSuccess(null); - return; - } - callback.onSuccess(status); - } - - @Override - public void onFailure(@NonNull final Call call, @NonNull final Throwable t) { - callback.onFailure(t); - } - }); - } - - - public Call search(final String query) { - final float timezoneOffset = (float) TimeZone.getDefault().getRawOffset() / 1000; - return repository.search(timezoneOffset, query); - } -} +} \ No newline at end of file