1
0
mirror of https://github.com/KokaKiwi/BarInsta synced 2024-11-15 19:27:31 +00:00

Convert UserRepository and UserService to kotlin

This commit is contained in:
Ammar Githam 2021-06-06 10:11:30 +09:00
parent 6b24c907dd
commit a2bd2e4b53
7 changed files with 147 additions and 255 deletions

View File

@ -28,13 +28,14 @@ import java.io.File;
import awais.instagrabber.R; import awais.instagrabber.R;
import awais.instagrabber.databinding.DialogProfilepicBinding; 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.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.CoroutineUtilsKt;
import awais.instagrabber.utils.DownloadUtils; import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.TextUtils; import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.webservices.UserService; import awais.instagrabber.webservices.UserService;
import kotlinx.coroutines.Dispatchers;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -129,33 +130,29 @@ public class ProfilePicDialogFragment extends DialogFragment {
private void fetchAvatar() { private void fetchAvatar() {
if (isLoggedIn) { if (isLoggedIn) {
final UserService userService = UserService.getInstance(); final UserService userService = UserService.INSTANCE;
userService.getUserInfo(id, new ServiceCallback<User>() { userService.getUserInfo(id, CoroutineUtilsKt.getContinuation((user, throwable) -> AppExecutors.INSTANCE.getMainThread().execute(() -> {
@Override if (throwable != null) {
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 Context context = getContext(); final Context context = getContext();
if (context == null) { if (context == null) {
dismiss(); dismiss();
return; return;
} }
Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(context, throwable.getMessage(), Toast.LENGTH_SHORT).show();
dismiss(); 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); } else setupPhoto(fallbackUrl);
} }

View File

@ -338,7 +338,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
directMessagesService = isLoggedIn ? DirectMessagesService.getInstance(csrfToken, myId, deviceUuid) : null; directMessagesService = isLoggedIn ? DirectMessagesService.getInstance(csrfToken, myId, deviceUuid) : null;
storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : null; storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : null;
mediaService = isLoggedIn ? MediaService.INSTANCE : null; mediaService = isLoggedIn ? MediaService.INSTANCE : null;
userService = isLoggedIn ? UserService.getInstance() : null; userService = isLoggedIn ? UserService.INSTANCE : null;
graphQLService = isLoggedIn ? null : GraphQLService.getInstance(); graphQLService = isLoggedIn ? null : GraphQLService.getInstance();
final Context context = getContext(); final Context context = getContext();
if (context == null) return; if (context == null) return;
@ -586,44 +586,36 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
return; return;
} }
if (isLoggedIn) { if (isLoggedIn) {
userService.getUsernameInfo(usernameTemp, new ServiceCallback<User>() { userService.getUsernameInfo(
@Override usernameTemp,
public void onSuccess(final User user) { CoroutineUtilsKt.getContinuation((user, throwable) -> AppExecutors.INSTANCE.getMainThread().execute(() -> {
userService.getUserFriendship(user.getPk(), new ServiceCallback<FriendshipStatus>() { if (throwable != null) {
@Override Log.e(TAG, "Error fetching profile", throwable);
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);
final Context context = getContext(); final Context context = getContext();
try { if (context == null) return;
if (t == null) Toast.makeText(context, throwable.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, R.string.error_loading_profile_loggedin, Toast.LENGTH_LONG).show(); return;
else
Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
} catch (final Throwable ignored) {
}
} }
}); userService.getUserFriendship(
} user.getPk(),
CoroutineUtilsKt.getContinuation(
@Override (friendshipStatus, throwable1) -> AppExecutors.INSTANCE.getMainThread().execute(() -> {
public void onFailure(final Throwable t) { if (throwable1 != null) {
Log.e(TAG, "Error fetching profile", t); Log.e(TAG, "Error fetching profile relationship", throwable1);
final Context context = getContext(); final Context context = getContext();
try { if (context == null) return;
if (t == null) Toast.makeText(context, throwable1.getMessage(),
Toast.makeText(context, R.string.error_loading_profile_loggedin, Toast.LENGTH_LONG).show(); Toast.LENGTH_SHORT).show();
else Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show(); return;
} catch (final Throwable ignored) { }
} user.setFriendshipStatus(friendshipStatus);
} profileModel = user;
}); setProfileDetails();
}), Dispatchers.getIO()
)
);
}), Dispatchers.getIO())
);
return; return;
} }
graphQLService.fetchUser(usernameTemp, new ServiceCallback<User>() { graphQLService.fetchUser(usernameTemp, new ServiceCallback<User>() {

View File

@ -36,16 +36,16 @@ import awais.instagrabber.db.entities.Account;
import awais.instagrabber.db.repositories.AccountRepository; import awais.instagrabber.db.repositories.AccountRepository;
import awais.instagrabber.db.repositories.RepositoryCallback; import awais.instagrabber.db.repositories.RepositoryCallback;
import awais.instagrabber.dialogs.AccountSwitcherDialogFragment; import awais.instagrabber.dialogs.AccountSwitcherDialogFragment;
import awais.instagrabber.repositories.responses.User;
import awais.instagrabber.utils.AppExecutors; import awais.instagrabber.utils.AppExecutors;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.CoroutineUtilsKt;
import awais.instagrabber.utils.FlavorTown; import awais.instagrabber.utils.FlavorTown;
import awais.instagrabber.utils.ProcessPhoenix; import awais.instagrabber.utils.ProcessPhoenix;
import awais.instagrabber.utils.TextUtils; import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.webservices.UserService; import awais.instagrabber.webservices.UserService;
import kotlinx.coroutines.Dispatchers;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -288,44 +288,40 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
// adds cookies to database for quick access // adds cookies to database for quick access
final long uid = CookieUtils.getUserIdFromCookie(cookie); final long uid = CookieUtils.getUserIdFromCookie(cookie);
final UserService userService = UserService.getInstance(); final UserService userService = UserService.INSTANCE;
userService.getUserInfo(uid, new ServiceCallback<User>() { userService.getUserInfo(uid, CoroutineUtilsKt.getContinuation((user, throwable) -> AppExecutors.INSTANCE.getMainThread().execute(() -> {
@Override if (throwable != null) {
public void onSuccess(final User result) { Log.e(TAG, "Error fetching user info", throwable);
return;
}
if (user != null) {
// Log.d(TAG, "adding userInfo: " + result); // Log.d(TAG, "adding userInfo: " + result);
if (result != null) { accountRepository.insertOrUpdateAccount(
accountRepository.insertOrUpdateAccount( uid,
uid, user.getUsername(),
result.getUsername(), cookie,
cookie, user.getFullName(),
result.getFullName(), user.getProfilePicUrl(),
result.getProfilePicUrl(), new RepositoryCallback<Account>() {
new RepositoryCallback<Account>() { @Override
@Override public void onSuccess(final Account result) {
public void onSuccess(final Account result) { // final FragmentActivity activity = getActivity();
// final FragmentActivity activity = getActivity(); // if (activity == null) return;
// if (activity == null) return; // activity.recreate();
// activity.recreate(); AppExecutors.INSTANCE.getMainThread().execute(() -> {
AppExecutors.INSTANCE.getMainThread().execute(() -> { final Context context = getContext();
final Context context = getContext(); if (context == null) return;
if (context == null) return; ProcessPhoenix.triggerRebirth(context);
ProcessPhoenix.triggerRebirth(context); }, 200);
}, 200); }
}
@Override @Override
public void onDataNotAvailable() { public void onDataNotAvailable() {
Log.e(TAG, "onDataNotAvailable: insert failed"); Log.e(TAG, "onDataNotAvailable: insert failed");
} }
}); });
}
} }
}), Dispatchers.getIO()));
@Override
public void onFailure(final Throwable t) {
Log.e(TAG, "Error fetching user info", t);
}
});
} }
} }

View File

@ -1,25 +1,25 @@
package awais.instagrabber.repositories; package awais.instagrabber.repositories
import awais.instagrabber.repositories.responses.FriendshipStatus; import awais.instagrabber.repositories.responses.FriendshipStatus
import awais.instagrabber.repositories.responses.UserSearchResponse; import awais.instagrabber.repositories.responses.UserSearchResponse
import awais.instagrabber.repositories.responses.WrappedUser; import awais.instagrabber.repositories.responses.WrappedUser
import retrofit2.Call; import retrofit2.http.GET
import retrofit2.http.GET; import retrofit2.http.Path
import retrofit2.http.Path; import retrofit2.http.Query
import retrofit2.http.Query;
public interface UserRepository {
interface UserRepository {
@GET("/api/v1/users/{uid}/info/") @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/") @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}/") @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/") @GET("/api/v1/users/search/")
Call<UserSearchResponse> search(@Query("timezone_offset") float timezoneOffset, suspend fun search(
@Query("q") String query); @Query("timezone_offset") timezoneOffset: Float,
@Query("q") query: String,
): UserSearchResponse
} }

View File

@ -12,9 +12,10 @@ import androidx.lifecycle.MutableLiveData;
import awais.instagrabber.repositories.responses.User; import awais.instagrabber.repositories.responses.User;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.CoroutineUtilsKt;
import awais.instagrabber.utils.TextUtils; import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.webservices.UserService; import awais.instagrabber.webservices.UserService;
import kotlinx.coroutines.Dispatchers;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -32,7 +33,7 @@ public class AppStateViewModel extends AndroidViewModel {
cookie = settingsHelper.getString(Constants.COOKIE); cookie = settingsHelper.getString(Constants.COOKIE);
final boolean isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != 0; final boolean isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != 0;
if (!isLoggedIn) return; if (!isLoggedIn) return;
userService = UserService.getInstance(); userService = UserService.INSTANCE;
// final AccountRepository accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(application)); // final AccountRepository accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(application));
fetchProfileDetails(); fetchProfileDetails();
} }
@ -49,16 +50,12 @@ public class AppStateViewModel extends AndroidViewModel {
private void fetchProfileDetails() { private void fetchProfileDetails() {
final long uid = CookieUtils.getUserIdFromCookie(cookie); final long uid = CookieUtils.getUserIdFromCookie(cookie);
if (userService == null) return; if (userService == null) return;
userService.getUserInfo(uid, new ServiceCallback<User>() { userService.getUserInfo(uid, CoroutineUtilsKt.getContinuation((user, throwable) -> {
@Override if (throwable != null) {
public void onSuccess(final User user) { Log.e(TAG, "onFailure: ", throwable);
currentUser.postValue(user); return;
} }
currentUser.postValue(user);
@Override }, Dispatchers.getIO()));
public void onFailure(final Throwable t) {
Log.e(TAG, "onFailure: ", t);
}
});
} }
} }

View File

@ -24,7 +24,6 @@ import awais.instagrabber.R;
import awais.instagrabber.fragments.UserSearchFragment; import awais.instagrabber.fragments.UserSearchFragment;
import awais.instagrabber.models.Resource; import awais.instagrabber.models.Resource;
import awais.instagrabber.repositories.responses.User; import awais.instagrabber.repositories.responses.User;
import awais.instagrabber.repositories.responses.UserSearchResponse;
import awais.instagrabber.repositories.responses.directmessages.RankedRecipient; import awais.instagrabber.repositories.responses.directmessages.RankedRecipient;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
@ -37,7 +36,6 @@ import awais.instagrabber.webservices.UserService;
import kotlinx.coroutines.Dispatchers; import kotlinx.coroutines.Dispatchers;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
import static awais.instagrabber.utils.Utils.settingsHelper; 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)) { if (TextUtils.isEmpty(csrfToken) || viewerId <= 0 || TextUtils.isEmpty(deviceUuid)) {
throw new IllegalArgumentException("User is not logged in!"); throw new IllegalArgumentException("User is not logged in!");
} }
userService = UserService.getInstance(); userService = UserService.INSTANCE;
directMessagesService = DirectMessagesService.getInstance(csrfToken, viewerId, deviceUuid); directMessagesService = DirectMessagesService.getInstance(csrfToken, viewerId, deviceUuid);
rankedRecipientsCache = RankedRecipientsCache.INSTANCE; rankedRecipientsCache = RankedRecipientsCache.INSTANCE;
if ((rankedRecipientsCache.isFailed() || rankedRecipientsCache.isExpired()) && !rankedRecipientsCache.isUpdateInitiated()) { if ((rankedRecipientsCache.isFailed() || rankedRecipientsCache.isExpired()) && !rankedRecipientsCache.isUpdateInitiated()) {
@ -170,9 +168,26 @@ public class UserSearchViewModel extends ViewModel {
} }
private void defaultUserSearch() { private void defaultUserSearch() {
searchRequest = userService.search(currentQuery); userService.search(currentQuery, CoroutineUtilsKt.getContinuation((userSearchResponse, throwable) -> {
//noinspection unchecked if (throwable != null) {
handleRequest((Call<UserSearchResponse>) searchRequest); 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() { 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) { private List<RankedRecipient> mergeResponseWithCache(@NonNull final List<RankedRecipient> list) {
final Iterator<RankedRecipient> iterator = list.stream() final Iterator<RankedRecipient> iterator = list.stream()
.filter(Objects::nonNull) .filter(Objects::nonNull)

View File

@ -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; suspend fun getUserInfo(uid: Long): User {
import awais.instagrabber.repositories.responses.FriendshipStatus; val response = repository.getUserInfo(uid)
import awais.instagrabber.repositories.responses.User; return response.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);
} }
public static UserService getInstance() { suspend fun getUsernameInfo(username: String): User {
if (instance == null) { val response = repository.getUsernameInfo(username)
instance = new UserService(); return response.user
}
return instance;
} }
public void getUserInfo(final long uid, final ServiceCallback<User> callback) { suspend fun getUserFriendship(uid: Long): FriendshipStatus = repository.getUserFriendship(uid)
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 suspend fun search(query: String): UserSearchResponse {
public void onFailure(@NonNull final Call<WrappedUser> call, @NonNull final Throwable t) { val timezoneOffset = TimeZone.getDefault().rawOffset.toFloat() / 1000
callback.onFailure(t); return repository.search(timezoneOffset, query)
}
});
}
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);
}
});
}
public Call<UserSearchResponse> search(final String query) {
final float timezoneOffset = (float) TimeZone.getDefault().getRawOffset() / 1000;
return repository.search(timezoneOffset, query);
} }
} }