Browse Source

better handling for own profile

renovate/org.robolectric-robolectric-4.x
Austin Huang 4 years ago
parent
commit
383ffce89f
No known key found for this signature in database GPG Key ID: 84C23AA04587A91F
  1. 19
      app/src/main/java/awais/instagrabber/asyncs/ProfileFetcher.java
  2. 55
      app/src/main/java/awais/instagrabber/asyncs/UsernameFetcher.java
  3. 119
      app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java
  4. 43
      app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java

19
app/src/main/java/awais/instagrabber/asyncs/ProfileFetcher.java

@ -18,13 +18,16 @@ public final class ProfileFetcher extends AsyncTask<Void, Void, Void> {
private final GraphQLService graphQLService; private final GraphQLService graphQLService;
private final FetchListener<User> fetchListener; private final FetchListener<User> fetchListener;
private final long myId;
private final boolean isLoggedIn; private final boolean isLoggedIn;
private final String userName; private final String userName;
public ProfileFetcher(final String userName, public ProfileFetcher(final String userName,
final long myId,
final boolean isLoggedIn, final boolean isLoggedIn,
final FetchListener<User> fetchListener) { final FetchListener<User> fetchListener) {
this.userName = userName; this.userName = userName;
this.myId = myId;
this.isLoggedIn = isLoggedIn; this.isLoggedIn = isLoggedIn;
this.fetchListener = fetchListener; this.fetchListener = fetchListener;
userService = isLoggedIn ? UserService.getInstance() : null; userService = isLoggedIn ? UserService.getInstance() : null;
@ -34,7 +37,7 @@ public final class ProfileFetcher extends AsyncTask<Void, Void, Void> {
@Nullable @Nullable
@Override @Override
protected Void doInBackground(final Void... voids) { protected Void doInBackground(final Void... voids) {
if (isLoggedIn) {
if (isLoggedIn && userName != null) {
userService.getUsernameInfo(userName, new ServiceCallback<User>() { userService.getUsernameInfo(userName, new ServiceCallback<User>() {
@Override @Override
public void onSuccess(final User user) { public void onSuccess(final User user) {
@ -60,6 +63,20 @@ public final class ProfileFetcher extends AsyncTask<Void, Void, Void> {
} }
}); });
} }
else if (isLoggedIn) {
userService.getUserInfo(myId, new ServiceCallback<User>() {
@Override
public void onSuccess(final User user) {
fetchListener.onResult(user);
}
@Override
public void onFailure(final Throwable t) {
Log.e(TAG, "Error", t);
fetchListener.onFailure(t);
}
});
}
else { else {
graphQLService.fetchUser(userName, new ServiceCallback<User>() { graphQLService.fetchUser(userName, new ServiceCallback<User>() {
@Override @Override

55
app/src/main/java/awais/instagrabber/asyncs/UsernameFetcher.java

@ -1,55 +0,0 @@
package awais.instagrabber.asyncs;
import android.os.AsyncTask;
import android.util.Log;
import androidx.annotation.Nullable;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import java.net.URL;
import awais.instagrabber.BuildConfig;
import awais.instagrabber.interfaces.FetchListener;
import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.NetworkUtils;
import awais.instagrabber.utils.Utils;
public final class UsernameFetcher extends AsyncTask<Void, Void, String> {
private final FetchListener<String> fetchListener;
private final long uid;
public UsernameFetcher(final long uid, final FetchListener<String> fetchListener) {
this.uid = uid;
this.fetchListener = fetchListener;
}
@Nullable
@Override
protected String doInBackground(final Void... voids) {
String result = null;
try {
final HttpURLConnection conn = (HttpURLConnection) new URL("https://i.instagram.com/api/v1/users/" + uid + "/info/").openConnection();
conn.setRequestProperty("User-Agent", Utils.settingsHelper.getString(Constants.BROWSER_UA));
conn.setUseCaches(true);
final JSONObject user;
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK &&
(user = new JSONObject(NetworkUtils.readFromConnection(conn)).optJSONObject(Constants.EXTRAS_USER)) != null)
result = user.getString(Constants.EXTRAS_USERNAME);
conn.disconnect();
} catch (final Exception e) {
if (BuildConfig.DEBUG) Log.e("AWAISKING_APP", "", e);
}
return result;
}
@Override
protected void onPostExecute(final String result) {
if (fetchListener != null) fetchListener.onResult(result);
}
}

119
app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java

@ -59,7 +59,6 @@ import awais.instagrabber.adapters.HighlightsAdapter;
import awais.instagrabber.asyncs.CreateThreadAction; import awais.instagrabber.asyncs.CreateThreadAction;
import awais.instagrabber.asyncs.ProfileFetcher; import awais.instagrabber.asyncs.ProfileFetcher;
import awais.instagrabber.asyncs.ProfilePostFetchService; import awais.instagrabber.asyncs.ProfilePostFetchService;
import awais.instagrabber.asyncs.UsernameFetcher;
import awais.instagrabber.customviews.PrimaryActionModeCallback; import awais.instagrabber.customviews.PrimaryActionModeCallback;
import awais.instagrabber.customviews.PrimaryActionModeCallback.CallbacksHelper; import awais.instagrabber.customviews.PrimaryActionModeCallback.CallbacksHelper;
import awais.instagrabber.databinding.FragmentProfileBinding; import awais.instagrabber.databinding.FragmentProfileBinding;
@ -125,11 +124,12 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
private HighlightsViewModel highlightsViewModel; private HighlightsViewModel highlightsViewModel;
private MenuItem blockMenuItem, restrictMenuItem, chainingMenuItem; private MenuItem blockMenuItem, restrictMenuItem, chainingMenuItem;
private MenuItem muteStoriesMenuItem, mutePostsMenuItem; private MenuItem muteStoriesMenuItem, mutePostsMenuItem;
private boolean highlightsFetching;
private boolean accountIsUpdated = false;
private boolean postsSetupDone = false; private boolean postsSetupDone = false;
private Set<Media> selectedFeedModels; private Set<Media> selectedFeedModels;
private Media downloadFeedModel; private Media downloadFeedModel;
private int downloadChildPosition = -1; private int downloadChildPosition = -1;
private long myId;
private PostsLayoutPreferences layoutPreferences = Utils.getPostsLayoutPreferences(Constants.PREF_PROFILE_POSTS_LAYOUT); private PostsLayoutPreferences layoutPreferences = Utils.getPostsLayoutPreferences(Constants.PREF_PROFILE_POSTS_LAYOUT);
private final Runnable usernameSettingRunnable = () -> { private final Runnable usernameSettingRunnable = () -> {
@ -303,11 +303,11 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
cookie = Utils.settingsHelper.getString(Constants.COOKIE); cookie = Utils.settingsHelper.getString(Constants.COOKIE);
isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) > 0; isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) > 0;
final long userId = CookieUtils.getUserIdFromCookie(cookie);
myId = CookieUtils.getUserIdFromCookie(cookie);
final String deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID); final String deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID);
final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie);
fragmentActivity = (MainActivity) requireActivity(); fragmentActivity = (MainActivity) requireActivity();
friendshipService = isLoggedIn ? FriendshipService.getInstance(deviceUuid, csrfToken, userId) : null;
friendshipService = isLoggedIn ? FriendshipService.getInstance(deviceUuid, csrfToken, myId) : null;
storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : null; storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : null;
mediaService = isLoggedIn ? MediaService.getInstance(null, null, 0) : null; mediaService = isLoggedIn ? MediaService.getInstance(null, null, 0) : null;
accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(getContext())); accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(getContext()));
@ -363,9 +363,10 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
public void onCreateOptionsMenu(@NonNull final Menu menu, @NonNull final MenuInflater inflater) { public void onCreateOptionsMenu(@NonNull final Menu menu, @NonNull final MenuInflater inflater) {
inflater.inflate(R.menu.profile_menu, menu); inflater.inflate(R.menu.profile_menu, menu);
blockMenuItem = menu.findItem(R.id.block); blockMenuItem = menu.findItem(R.id.block);
final boolean isNotMe = profileModel != null && !Objects.equals(profileModel.getPk(), CookieUtils.getUserIdFromCookie(cookie));
if (blockMenuItem != null) { if (blockMenuItem != null) {
if (profileModel != null) {
blockMenuItem.setVisible(!Objects.equals(profileModel.getPk(), CookieUtils.getUserIdFromCookie(cookie)));
if (isNotMe) {
blockMenuItem.setVisible(true);
blockMenuItem.setTitle(profileModel.getFriendshipStatus().isBlocking() ? R.string.unblock : R.string.block); blockMenuItem.setTitle(profileModel.getFriendshipStatus().isBlocking() ? R.string.unblock : R.string.block);
} else { } else {
blockMenuItem.setVisible(false); blockMenuItem.setVisible(false);
@ -373,8 +374,8 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
restrictMenuItem = menu.findItem(R.id.restrict); restrictMenuItem = menu.findItem(R.id.restrict);
if (restrictMenuItem != null) { if (restrictMenuItem != null) {
if (profileModel != null) {
restrictMenuItem.setVisible(!Objects.equals(profileModel.getPk(), CookieUtils.getUserIdFromCookie(cookie)));
if (isNotMe) {
restrictMenuItem.setVisible(true);
restrictMenuItem.setTitle(profileModel.getFriendshipStatus().isRestricted() ? R.string.unrestrict : R.string.restrict); restrictMenuItem.setTitle(profileModel.getFriendshipStatus().isRestricted() ? R.string.unrestrict : R.string.restrict);
} else { } else {
restrictMenuItem.setVisible(false); restrictMenuItem.setVisible(false);
@ -382,8 +383,8 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
muteStoriesMenuItem = menu.findItem(R.id.mute_stories); muteStoriesMenuItem = menu.findItem(R.id.mute_stories);
if (muteStoriesMenuItem != null) { if (muteStoriesMenuItem != null) {
if (profileModel != null) {
muteStoriesMenuItem.setVisible(!Objects.equals(profileModel.getPk(), CookieUtils.getUserIdFromCookie(cookie)));
if (isNotMe) {
muteStoriesMenuItem.setVisible(true);
muteStoriesMenuItem.setTitle(profileModel.getFriendshipStatus().isMutingReel() ? R.string.mute_stories : R.string.unmute_stories); muteStoriesMenuItem.setTitle(profileModel.getFriendshipStatus().isMutingReel() ? R.string.mute_stories : R.string.unmute_stories);
} else { } else {
muteStoriesMenuItem.setVisible(false); muteStoriesMenuItem.setVisible(false);
@ -391,8 +392,8 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
mutePostsMenuItem = menu.findItem(R.id.mute_posts); mutePostsMenuItem = menu.findItem(R.id.mute_posts);
if (mutePostsMenuItem != null) { if (mutePostsMenuItem != null) {
if (profileModel != null) {
mutePostsMenuItem.setVisible(!Objects.equals(profileModel.getPk(), CookieUtils.getUserIdFromCookie(cookie)));
if (isNotMe) {
mutePostsMenuItem.setVisible(true);
mutePostsMenuItem.setTitle(profileModel.getFriendshipStatus().isMuting() ? R.string.mute_posts : R.string.unmute_posts); mutePostsMenuItem.setTitle(profileModel.getFriendshipStatus().isMuting() ? R.string.mute_posts : R.string.unmute_posts);
} else { } else {
mutePostsMenuItem.setVisible(false); mutePostsMenuItem.setVisible(false);
@ -400,11 +401,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
chainingMenuItem = menu.findItem(R.id.chaining); chainingMenuItem = menu.findItem(R.id.chaining);
if (chainingMenuItem != null) { if (chainingMenuItem != null) {
if (profileModel != null) {
chainingMenuItem.setVisible(!Objects.equals(profileModel.getPk(), CookieUtils.getUserIdFromCookie(cookie)));
} else {
chainingMenuItem.setVisible(false);
}
chainingMenuItem.setVisible(isNotMe);
} }
} }
@ -588,49 +585,20 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
binding.swipeRefreshLayout.setEnabled(true); binding.swipeRefreshLayout.setEnabled(true);
setupHighlights(); setupHighlights();
setupCommonListeners(); setupCommonListeners();
fetchUsername();
}
private void fetchUsername() {
final long uid = CookieUtils.getUserIdFromCookie(cookie);
if (TextUtils.isEmpty(username) && uid > 0) {
final FetchListener<String> fetchListener = username -> {
if (TextUtils.isEmpty(username)) return;
this.username = username;
setUsernameDelayed();
fetchProfileDetails();
};
accountRepository.getAccount(uid, new RepositoryCallback<Account>() {
@Override
public void onSuccess(final Account account) {
boolean found = false;
if (account != null) {
final String username = account.getUsername();
if (!TextUtils.isEmpty(username)) {
found = true;
fetchListener.onResult("@" + username);
}
}
if (!found) {
// if not in database, fetch info from instagram
new UsernameFetcher(uid, fetchListener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
@Override
public void onDataNotAvailable() {}
});
return;
}
fetchProfileDetails(); fetchProfileDetails();
} }
private void fetchProfileDetails() { private void fetchProfileDetails() {
if (TextUtils.isEmpty(username)) return;
new ProfileFetcher(username.trim().substring(1), isLoggedIn, new FetchListener<User>() {
accountIsUpdated = false;
new ProfileFetcher(TextUtils.isEmpty(username) ? null : username.trim().substring(1),
myId, isLoggedIn, new FetchListener<User>() {
@Override @Override
public void onResult(final User user) { public void onResult(final User user) {
if (getContext() == null) return; if (getContext() == null) return;
if (TextUtils.isEmpty(username)) {
username = user.getUsername();
setUsernameDelayed();
}
profileModel = user; profileModel = user;
setProfileDetails(); setProfileDetails();
} }
@ -665,11 +633,10 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
profileDetailsBinding.isVerified.setVisibility(profileModel.isVerified() ? View.VISIBLE : View.GONE); profileDetailsBinding.isVerified.setVisibility(profileModel.isVerified() ? View.VISIBLE : View.GONE);
final long profileId = profileModel.getPk(); final long profileId = profileModel.getPk();
final long myId = CookieUtils.getUserIdFromCookie(cookie);
if (isLoggedIn) { if (isLoggedIn) {
fetchStoryAndHighlights(profileId); fetchStoryAndHighlights(profileId);
} }
setupButtons(profileId, myId);
setupButtons(profileId);
profileDetailsBinding.favChip.setVisibility(View.VISIBLE); profileDetailsBinding.favChip.setVisibility(View.VISIBLE);
final FavoriteRepository favoriteRepository = FavoriteRepository.getInstance(FavoriteDataSource.getInstance(getContext())); final FavoriteRepository favoriteRepository = FavoriteRepository.getInstance(FavoriteDataSource.getInstance(getContext()));
favoriteRepository.getFavorite(profileModel.getUsername(), FavoriteType.USER, new RepositoryCallback<Favorite>() { favoriteRepository.getFavorite(profileModel.getUsername(), FavoriteType.USER, new RepositoryCallback<Favorite>() {
@ -895,13 +862,10 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
profileDetailsBinding.mainFollowers.setOnClickListener(followersCount > 0 ? followClickListener : null); profileDetailsBinding.mainFollowers.setOnClickListener(followersCount > 0 ? followClickListener : null);
profileDetailsBinding.mainFollowing.setOnClickListener(followingCount > 0 ? followClickListener : null); profileDetailsBinding.mainFollowing.setOnClickListener(followingCount > 0 ? followClickListener : null);
} }
binding.swipeRefreshLayout.setRefreshing(true);
binding.postsRecyclerView.setVisibility(View.VISIBLE); binding.postsRecyclerView.setVisibility(View.VISIBLE);
fetchPosts();
} else { } else {
profileDetailsBinding.mainFollowers.setClickable(false); profileDetailsBinding.mainFollowers.setClickable(false);
profileDetailsBinding.mainFollowing.setClickable(false); profileDetailsBinding.mainFollowing.setClickable(false);
binding.swipeRefreshLayout.setRefreshing(false);
// error // error
binding.privatePage1.setImageResource(R.drawable.lock); binding.privatePage1.setImageResource(R.drawable.lock);
binding.privatePage2.setText(R.string.priv_acc); binding.privatePage2.setText(R.string.priv_acc);
@ -910,7 +874,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
} }
private void setupButtons(final long profileId, final long myId) {
private void setupButtons(final long profileId) {
profileDetailsBinding.btnTagged.setVisibility(isReallyPrivate() ? View.GONE : View.VISIBLE); profileDetailsBinding.btnTagged.setVisibility(isReallyPrivate() ? View.GONE : View.VISIBLE);
if (isLoggedIn) { if (isLoggedIn) {
if (Objects.equals(profileId, myId)) { if (Objects.equals(profileId, myId)) {
@ -919,6 +883,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
profileDetailsBinding.btnLiked.setVisibility(View.VISIBLE); profileDetailsBinding.btnLiked.setVisibility(View.VISIBLE);
profileDetailsBinding.btnDM.setVisibility(View.GONE); profileDetailsBinding.btnDM.setVisibility(View.GONE);
profileDetailsBinding.btnSaved.setText(R.string.saved); profileDetailsBinding.btnSaved.setText(R.string.saved);
if (!accountIsUpdated) updateAccountInfo();
return; return;
} }
profileDetailsBinding.btnSaved.setVisibility(View.GONE); profileDetailsBinding.btnSaved.setVisibility(View.GONE);
@ -973,6 +938,26 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
} }
private void updateAccountInfo() {
accountRepository.insertOrUpdateAccount(
profileModel.getPk(),
profileModel.getUsername(),
cookie,
profileModel.getFullName(),
profileModel.getProfilePicUrl(),
new RepositoryCallback<Account>() {
@Override
public void onSuccess(final Account result) {
accountIsUpdated = true;
}
@Override
public void onDataNotAvailable() {
Log.e(TAG, "onDataNotAvailable: insert failed");
}
});
}
private void fetchStoryAndHighlights(final long profileId) { private void fetchStoryAndHighlights(final long profileId) {
storiesService.getUserStory( storiesService.getUserStory(
StoryViewerOptions.forUser(profileId, profileModel.getFullName()), StoryViewerOptions.forUser(profileId, profileModel.getFullName()),
@ -994,7 +979,6 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
new ServiceCallback<List<HighlightModel>>() { new ServiceCallback<List<HighlightModel>>() {
@Override @Override
public void onSuccess(final List<HighlightModel> result) { public void onSuccess(final List<HighlightModel> result) {
highlightsFetching = false;
if (result != null) { if (result != null) {
profileDetailsBinding.highlightsList.setVisibility(View.VISIBLE); profileDetailsBinding.highlightsList.setVisibility(View.VISIBLE);
highlightsViewModel.getList().postValue(result); highlightsViewModel.getList().postValue(result);
@ -1166,7 +1150,8 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
private void updateSwipeRefreshState() { private void updateSwipeRefreshState() {
binding.swipeRefreshLayout.setRefreshing(binding.postsRecyclerView.isFetching() || highlightsFetching);
Log.d("austin_debug", "usrs: "+binding.postsRecyclerView.isFetching());
binding.swipeRefreshLayout.setRefreshing(binding.postsRecyclerView.isFetching());
} }
private void setupHighlights() { private void setupHighlights() {
@ -1185,14 +1170,6 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
highlightsViewModel.getList().observe(getViewLifecycleOwner(), highlightModels -> highlightsAdapter.submitList(highlightModels)); highlightsViewModel.getList().observe(getViewLifecycleOwner(), highlightModels -> highlightsAdapter.submitList(highlightModels));
} }
private void fetchPosts() {
// stopCurrentExecutor();
binding.swipeRefreshLayout.setRefreshing(true);
// currentlyExecuting = new PostsFetcher(profileModel.getId(), PostItemType.MAIN, endCursor, postsFetchListener)
// .setUsername(profileModel.getUsername())
// .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void navigateToProfile(final String username) { private void navigateToProfile(final String username) {
final NavController navController = NavHostFragment.findNavController(this); final NavController navController = NavHostFragment.findNavController(this);
final Bundle bundle = new Bundle(); final Bundle bundle = new Bundle();
@ -1211,8 +1188,8 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
private boolean isReallyPrivate() { private boolean isReallyPrivate() {
final long myId = CookieUtils.getUserIdFromCookie(cookie);
if (profileModel.getPk() == myId) return false;
final FriendshipStatus friendshipStatus = profileModel.getFriendshipStatus(); final FriendshipStatus friendshipStatus = profileModel.getFriendshipStatus();
return !friendshipStatus.isFollowing() && (profileModel.getPk() != myId) && profileModel.isPrivate();
return !friendshipStatus.isFollowing() && profileModel.isPrivate();
} }
} }

43
app/src/main/java/awais/instagrabber/viewmodels/AppStateViewModel.java

@ -7,7 +7,6 @@ import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.AndroidViewModel;
import awais.instagrabber.asyncs.ProfileFetcher; import awais.instagrabber.asyncs.ProfileFetcher;
import awais.instagrabber.asyncs.UsernameFetcher;
import awais.instagrabber.db.datasources.AccountDataSource; import awais.instagrabber.db.datasources.AccountDataSource;
import awais.instagrabber.db.entities.Account; import awais.instagrabber.db.entities.Account;
import awais.instagrabber.db.repositories.AccountRepository; import awais.instagrabber.db.repositories.AccountRepository;
@ -28,7 +27,6 @@ public class AppStateViewModel extends AndroidViewModel {
private User currentUser; private User currentUser;
private AccountRepository accountRepository; private AccountRepository accountRepository;
private String username;
public AppStateViewModel(@NonNull final Application application) { public AppStateViewModel(@NonNull final Application application) {
super(application); super(application);
@ -37,52 +35,15 @@ public class AppStateViewModel extends AndroidViewModel {
isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) > 0; isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) > 0;
if (!isLoggedIn) return; if (!isLoggedIn) return;
accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(application)); accountRepository = AccountRepository.getInstance(AccountDataSource.getInstance(application));
setCurrentUser();
}
private void setCurrentUser() {
if (!isLoggedIn) return;
final FetchListener<String> usernameListener = username -> {
if (TextUtils.isEmpty(username)) return;
this.username = username;
fetchProfileDetails(); fetchProfileDetails();
};
fetchUsername(usernameListener);
} }
public User getCurrentUser() { public User getCurrentUser() {
return currentUser; return currentUser;
} }
private void fetchUsername(final FetchListener<String> usernameListener) {
if (!TextUtils.isEmpty(username)) {
usernameListener.onResult(username);
return;
}
final long uid = CookieUtils.getUserIdFromCookie(cookie);
if (uid <= 0) return;
accountRepository.getAccount(uid, new RepositoryCallback<Account>() {
@Override
public void onSuccess(@NonNull final Account account) {
final String username = account.getUsername();
if (TextUtils.isEmpty(username)) return;
usernameListener.onResult("@" + username);
}
@Override
public void onDataNotAvailable() {
// if not in database, fetch info
new UsernameFetcher(uid, usernameListener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
}
private void fetchProfileDetails() { private void fetchProfileDetails() {
if (TextUtils.isEmpty(username)) return;
new ProfileFetcher(
username.trim().substring(1),
true,
user -> this.currentUser = user
).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final long uid = CookieUtils.getUserIdFromCookie(cookie);
new ProfileFetcher(null, uid, true, user -> this.currentUser = user).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} }
} }
Loading…
Cancel
Save