Browse Source

Convert UserRepository and UserService to kotlin

renovate/org.robolectric-robolectric-4.x
Ammar Githam 4 years ago
parent
commit
a2bd2e4b53
  1. 41
      app/src/main/java/awais/instagrabber/dialogs/ProfilePicDialogFragment.java
  2. 66
      app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java
  3. 72
      app/src/main/java/awais/instagrabber/fragments/settings/MorePreferencesFragment.java
  4. 30
      app/src/main/java/awais/instagrabber/repositories/UserRepository.kt
  5. 21
      app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java
  6. 60
      app/src/main/java/awais/instagrabber/viewmodels/UserSearchViewModel.java
  7. 110
      app/src/main/java/awais/instagrabber/webservices/UserService.kt

41
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<User>() {
@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);
}

66
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<User>() {
@Override
public void onSuccess(final User user) {
userService.getUserFriendship(user.getPk(), new ServiceCallback<FriendshipStatus>() {
@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<User>() {

72
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<User>() {
@Override
public void onSuccess(final User result) {
// Log.d(TAG, "adding userInfo: " + result);
if (result != null) {
accountRepository.insertOrUpdateAccount(
uid,
result.getUsername(),
cookie,
result.getFullName(),
result.getProfilePicUrl(),
new RepositoryCallback<Account>() {
@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");
}
});
}
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;
}
@Override
public void onFailure(final Throwable t) {
Log.e(TAG, "Error fetching user info", t);
if (user != null) {
// Log.d(TAG, "adding userInfo: " + result);
accountRepository.insertOrUpdateAccount(
uid,
user.getUsername(),
cookie,
user.getFullName(),
user.getProfilePicUrl(),
new RepositoryCallback<Account>() {
@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");
}
});
}
});
}), Dispatchers.getIO()));
}
}

30
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<WrappedUser> getUserInfo(@Path("uid") final long uid);
suspend fun getUserInfo(@Path("uid") uid: Long): WrappedUser
@GET("/api/v1/users/{username}/usernameinfo/")
Call<WrappedUser> getUsernameInfo(@Path("username") final String username);
suspend fun getUsernameInfo(@Path("username") username: String): WrappedUser
@GET("/api/v1/friendships/show/{uid}/")
Call<FriendshipStatus> getUserFriendship(@Path("uid") final long uid);
suspend fun getUserFriendship(@Path("uid") uid: Long): FriendshipStatus
@GET("/api/v1/users/search/")
Call<UserSearchResponse> search(@Query("timezone_offset") float timezoneOffset,
@Query("q") String query);
suspend fun search(
@Query("timezone_offset") timezoneOffset: Float,
@Query("q") query: String,
): UserSearchResponse
}

21
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<User>() {
@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()));
}
}

60
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<UserSearchResponse>) 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<RankedRecipient> 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<UserSearchResponse> request) {
request.enqueue(new Callback<UserSearchResponse>() {
@Override
public void onResponse(@NonNull final Call<UserSearchResponse> call, @NonNull final Response<UserSearchResponse> 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<RankedRecipient> 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<UserSearchResponse> call, @NonNull final Throwable t) {
Log.e(TAG, "onFailure: ", t);
recipients.postValue(Resource.error(t.getMessage(), getCachedRecipients()));
searchRequest = null;
}
});
}
private List<RankedRecipient> mergeResponseWithCache(@NonNull final List<RankedRecipient> list) {
final Iterator<RankedRecipient> iterator = list.stream()
.filter(Objects::nonNull)

110
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;
}
public void getUserInfo(final long uid, final ServiceCallback<User> callback) {
final Call<WrappedUser> request = repository.getUserInfo(uid);
request.enqueue(new Callback<WrappedUser>() {
@Override
public void onResponse(@NonNull final Call<WrappedUser> call, @NonNull final Response<WrappedUser> response) {
final WrappedUser user = response.body();
if (user == null) {
callback.onSuccess(null);
return;
}
callback.onSuccess(user.getUser());
}
@Override
public void onFailure(@NonNull final Call<WrappedUser> call, @NonNull final Throwable t) {
callback.onFailure(t);
}
});
}
public void getUsernameInfo(final String username, final ServiceCallback<User> callback) {
final Call<WrappedUser> request = repository.getUsernameInfo(username);
request.enqueue(new Callback<WrappedUser>() {
@Override
public void onResponse(@NonNull final Call<WrappedUser> call, @NonNull final Response<WrappedUser> response) {
final WrappedUser user = response.body();
if (user == null) {
callback.onFailure(null);
return;
}
callback.onSuccess(user.getUser());
}
@Override
public void onFailure(@NonNull final Call<WrappedUser> call, @NonNull final Throwable t) {
callback.onFailure(t);
}
});
}
public void getUserFriendship(final long uid, final ServiceCallback<FriendshipStatus> callback) {
final Call<FriendshipStatus> request = repository.getUserFriendship(uid);
request.enqueue(new Callback<FriendshipStatus>() {
@Override
public void onResponse(@NonNull final Call<FriendshipStatus> call, @NonNull final Response<FriendshipStatus> response) {
final FriendshipStatus status = response.body();
if (status == null) {
callback.onSuccess(null);
return;
}
callback.onSuccess(status);
}
@Override
public void onFailure(@NonNull final Call<FriendshipStatus> call, @NonNull final Throwable t) {
callback.onFailure(t);
}
});
suspend fun getUsernameInfo(username: String): User {
val response = repository.getUsernameInfo(username)
return response.user
}
suspend fun getUserFriendship(uid: Long): FriendshipStatus = repository.getUserFriendship(uid)
public Call<UserSearchResponse> search(final String query) {
final float timezoneOffset = (float) TimeZone.getDefault().getRawOffset() / 1000;
return repository.search(timezoneOffset, query);
suspend fun search(query: String): UserSearchResponse {
val timezoneOffset = TimeZone.getDefault().rawOffset.toFloat() / 1000
return repository.search(timezoneOffset, query)
}
}
Loading…
Cancel
Save