diff options
Diffstat (limited to 'app/src')
99 files changed, 3581 insertions, 3604 deletions
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java index 9db681e3..9e7ac3aa 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java @@ -62,7 +62,10 @@ import ml.docilealligator.infinityforreddit.fragments.SidebarFragment; import ml.docilealligator.infinityforreddit.fragments.SubredditListingFragment; import ml.docilealligator.infinityforreddit.fragments.SubscribedSubredditsListingFragment; import ml.docilealligator.infinityforreddit.fragments.UserListingFragment; +import ml.docilealligator.infinityforreddit.fragments.ViewImgurImageFragment; import ml.docilealligator.infinityforreddit.fragments.ViewImgurVideoFragment; +import ml.docilealligator.infinityforreddit.fragments.ViewPostDetailFragment; +import ml.docilealligator.infinityforreddit.fragments.ViewRedditGalleryImageOrGifFragment; import ml.docilealligator.infinityforreddit.fragments.ViewRedditGalleryVideoFragment; import ml.docilealligator.infinityforreddit.services.DownloadMediaService; import ml.docilealligator.infinityforreddit.services.DownloadRedditVideoService; @@ -242,4 +245,10 @@ public interface AppComponent { void inject(SearchUsersResultActivity searchUsersResultActivity); void inject(MultiredditSelectionActivity multiredditSelectionActivity); + + void inject(ViewImgurImageFragment viewImgurImageFragment); + + void inject(ViewRedditGalleryImageOrGifFragment viewRedditGalleryImageOrGifFragment); + + void inject(ViewPostDetailFragment viewPostDetailFragment); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FavoriteThing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FavoriteThing.java index 1bc7b002..8a041e3b 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/FavoriteThing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FavoriteThing.java @@ -1,12 +1,15 @@ package ml.docilealligator.infinityforreddit; +import android.os.Handler; + import androidx.annotation.NonNull; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Executor; import ml.docilealligator.infinityforreddit.apis.RedditAPI; -import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThingsAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings; import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData; import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData; import ml.docilealligator.infinityforreddit.utils.APIUtils; @@ -16,7 +19,8 @@ import retrofit2.Response; import retrofit2.Retrofit; public class FavoriteThing { - public static void favoriteSubreddit(Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, + public static void favoriteSubreddit(Executor executor, Handler handler, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, String accessToken, SubscribedSubredditData subscribedSubredditData, FavoriteThingListener favoriteThingListener) { Map<String, String> params = new HashMap<>(); @@ -26,8 +30,8 @@ public class FavoriteThing { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if (response.isSuccessful()) { - new InsertSubscribedThingsAsyncTask(redditDataRoomDatabase, subscribedSubredditData, - favoriteThingListener::success).execute(); + InsertSubscribedThings.insertSubscribedThings(executor, handler, redditDataRoomDatabase, subscribedSubredditData, + favoriteThingListener::success); } else { favoriteThingListener.failed(); } @@ -40,7 +44,8 @@ public class FavoriteThing { }); } - public static void unfavoriteSubreddit(Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, + public static void unfavoriteSubreddit(Executor executor, Handler handler, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, String accessToken, SubscribedSubredditData subscribedSubredditData, FavoriteThingListener favoriteThingListener) { Map<String, String> params = new HashMap<>(); @@ -50,8 +55,8 @@ public class FavoriteThing { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if (response.isSuccessful()) { - new InsertSubscribedThingsAsyncTask(redditDataRoomDatabase, subscribedSubredditData, - favoriteThingListener::success).execute(); + InsertSubscribedThings.insertSubscribedThings(executor, handler, redditDataRoomDatabase, + subscribedSubredditData, favoriteThingListener::success); } else { favoriteThingListener.failed(); } @@ -64,9 +69,10 @@ public class FavoriteThing { }); } - public static void favoriteUser(Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, - String accessToken, SubscribedUserData subscribedUserData, - FavoriteThingListener favoriteThingListener) { + public static void favoriteUser(Executor executor, Handler handler, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, + String accessToken, SubscribedUserData subscribedUserData, + FavoriteThingListener favoriteThingListener) { Map<String, String> params = new HashMap<>(); params.put(APIUtils.SR_NAME_KEY, "u_" + subscribedUserData.getName()); params.put(APIUtils.MAKE_FAVORITE_KEY, "true"); @@ -74,8 +80,8 @@ public class FavoriteThing { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if (response.isSuccessful()) { - new InsertSubscribedThingsAsyncTask(redditDataRoomDatabase, subscribedUserData, - favoriteThingListener::success).execute(); + InsertSubscribedThings.insertSubscribedThings(executor, handler, redditDataRoomDatabase, + subscribedUserData, favoriteThingListener::success); } else { favoriteThingListener.failed(); } @@ -88,9 +94,10 @@ public class FavoriteThing { }); } - public static void unfavoriteUser(Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, - String accessToken, SubscribedUserData subscribedUserData, - FavoriteThingListener favoriteThingListener) { + public static void unfavoriteUser(Executor executor, Handler handler, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, + String accessToken, SubscribedUserData subscribedUserData, + FavoriteThingListener favoriteThingListener) { Map<String, String> params = new HashMap<>(); params.put(APIUtils.SR_NAME_KEY, "u_" + subscribedUserData.getName()); params.put(APIUtils.MAKE_FAVORITE_KEY, "false"); @@ -98,8 +105,8 @@ public class FavoriteThing { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if (response.isSuccessful()) { - new InsertSubscribedThingsAsyncTask(redditDataRoomDatabase, subscribedUserData, - favoriteThingListener::success).execute(); + InsertSubscribedThings.insertSubscribedThings(executor, handler, redditDataRoomDatabase, + subscribedUserData, favoriteThingListener::success); } else { favoriteThingListener.failed(); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java index e121ffcb..fbbf05ed 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java @@ -4,6 +4,7 @@ import android.app.WallpaperManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; +import android.os.Handler; import android.view.WindowManager; import android.widget.Toast; @@ -14,14 +15,16 @@ import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.transition.Transition; -import ml.docilealligator.infinityforreddit.asynctasks.SetAsWallpaperAsyncTask; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.asynctasks.SetAsWallpaper; public class WallpaperSetter { public static final int HOME_SCREEN = 0; public static final int LOCK_SCREEN = 1; public static final int BOTH_SCREENS = 2; - public static void set(String url, int setTo, Context context, SetWallpaperListener setWallpaperListener) { + public static void set(Executor executor, Handler handler, String url, int setTo, Context context, SetWallpaperListener setWallpaperListener) { Toast.makeText(context, R.string.save_image_first, Toast.LENGTH_SHORT).show(); WallpaperManager wallpaperManager = WallpaperManager.getInstance(context); WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); @@ -29,7 +32,8 @@ public class WallpaperSetter { Glide.with(context).asBitmap().load(url).into(new CustomTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { - new SetAsWallpaperAsyncTask(resource, setTo, wallpaperManager, windowManager, setWallpaperListener).execute(); + SetAsWallpaper.setAsWallpaper(executor, handler, resource, setTo, wallpaperManager, + windowManager, setWallpaperListener); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java index 3a8ffae1..9f9207e5 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java @@ -38,8 +38,8 @@ import javax.inject.Named; import butterknife.BindView; import butterknife.ButterKnife; import ml.docilealligator.infinityforreddit.adapters.CustomThemeListingRecyclerViewAdapter; -import ml.docilealligator.infinityforreddit.asynctasks.ChangeThemeNameAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteThemeAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.ChangeThemeName; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteTheme; import ml.docilealligator.infinityforreddit.asynctasks.GetCustomTheme; import ml.docilealligator.infinityforreddit.asynctasks.InsertCustomTheme; import ml.docilealligator.infinityforreddit.bottomsheetfragments.CreateThemeBottomSheetFragment; @@ -175,7 +175,8 @@ public class CustomThemeListingActivity extends BaseActivity implements if (imm != null) { imm.hideSoftInputFromWindow(themeNameEditText.getWindowToken(), 0); } - new ChangeThemeNameAsyncTask(redditDataRoomDatabase, oldThemeName, themeNameEditText.getText().toString()).execute(); + ChangeThemeName.changeThemeName(executor, redditDataRoomDatabase, oldThemeName, + themeNameEditText.getText().toString()); }) .setNegativeButton(R.string.cancel, null) .setOnDismissListener(dialogInterface -> { @@ -212,7 +213,7 @@ public class CustomThemeListingActivity extends BaseActivity implements .setTitle(R.string.delete_theme) .setMessage(getString(R.string.delete_theme_dialog_message, themeName)) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteThemeAsyncTask(redditDataRoomDatabase, themeName, (isLightTheme, isDarkTheme, isAmoledTheme) -> { + -> DeleteTheme.deleteTheme(executor, new Handler(), redditDataRoomDatabase, themeName, (isLightTheme, isDarkTheme, isAmoledTheme) -> { if (isLightTheme) { CustomThemeSharedPreferencesUtils.insertThemeToSharedPreferences( CustomThemeWrapper.getIndigo(CustomThemeListingActivity.this), lightThemeSharedPreferences); @@ -226,7 +227,7 @@ public class CustomThemeListingActivity extends BaseActivity implements CustomThemeWrapper.getIndigoAmoled(CustomThemeListingActivity.this), amoledThemeSharedPreferences); } EventBus.getDefault().post(new RecreateActivityEvent()); - }).execute()) + })) .setNegativeButton(R.string.no, null) .show(); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java index 368d58cc..07c0c2af 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java @@ -52,8 +52,8 @@ public class EditCommentActivity extends BaseActivity { public static final String EXTRA_FULLNAME = "EF"; public static final String EXTRA_POSITION = "EP"; - static final String EXTRA_EDITED_COMMENT_CONTENT = "EECC"; - static final String EXTRA_EDITED_COMMENT_POSITION = "EECP"; + public static final String EXTRA_EDITED_COMMENT_CONTENT = "EECC"; + public static final String EXTRA_EDITED_COMMENT_POSITION = "EECP"; @BindView(R.id.coordinator_layout_edit_comment_activity) CoordinatorLayout coordinatorLayout; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java index 0f40fcc7..5c8ea02f 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java @@ -50,9 +50,9 @@ import retrofit2.Retrofit; public class EditPostActivity extends BaseActivity { - static final String EXTRA_TITLE = "ET"; - static final String EXTRA_CONTENT = "EC"; - static final String EXTRA_FULLNAME = "EF"; + public static final String EXTRA_TITLE = "ET"; + public static final String EXTRA_CONTENT = "EC"; + public static final String EXTRA_FULLNAME = "EF"; @BindView(R.id.coordinator_layout_edit_post_activity) CoordinatorLayout coordinatorLayout; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LoginActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LoginActivity.java index 49455183..21f49973 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LoginActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LoginActivity.java @@ -7,6 +7,7 @@ import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; +import android.os.Handler; import android.util.Log; import android.view.InflateException; import android.view.MenuItem; @@ -32,6 +33,7 @@ import org.json.JSONObject; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -43,7 +45,7 @@ import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.apis.RedditAPI; -import ml.docilealligator.infinityforreddit.asynctasks.ParseAndInsertNewAccountAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.ParseAndInsertNewAccount; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.utils.APIUtils; import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; @@ -85,6 +87,8 @@ public class LoginActivity extends BaseActivity { SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; private String authCode; private boolean enableDom = false; @@ -193,13 +197,13 @@ public class LoginActivity extends BaseActivity { mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, accessToken) .putString(SharedPreferencesUtils.ACCOUNT_NAME, name) .putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, profileImageUrl).apply(); - new ParseAndInsertNewAccountAsyncTask(name, accessToken, refreshToken, profileImageUrl, bannerImageUrl, + ParseAndInsertNewAccount.parseAndInsertNewAccount(mExecutor, new Handler(), name, accessToken, refreshToken, profileImageUrl, bannerImageUrl, karma, authCode, mRedditDataRoomDatabase.accountDao(), () -> { Intent resultIntent = new Intent(); setResult(Activity.RESULT_OK, resultIntent); finish(); - }).execute(); + }); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java index a2d8ac7f..83b8a2c9 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java @@ -80,7 +80,7 @@ import ml.docilealligator.infinityforreddit.SortType; import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback; import ml.docilealligator.infinityforreddit.account.AccountViewModel; import ml.docilealligator.infinityforreddit.adapters.NavigationDrawerRecyclerViewAdapter; -import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThingsAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings; import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount; import ml.docilealligator.infinityforreddit.asynctasks.SwitchToAnonymousMode; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment; @@ -897,13 +897,15 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb public void onFetchSubscribedThingSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData, ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubredditData> subredditData) { - new InsertSubscribedThingsAsyncTask( + InsertSubscribedThings.insertSubscribedThings( + mExecutor, + new Handler(), mRedditDataRoomDatabase, mAccountName, subscribedSubredditData, subscribedUserData, subredditData, - () -> mFetchSubscriptionsSuccess = true).execute(); + () -> mFetchSubscriptionsSuccess = true); } @Override @@ -966,11 +968,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb private void changeSortType() { int currentPostType = sectionsPagerAdapter.getCurrentPostType(); Bundle bundle = new Bundle(); - if (currentPostType != PostDataSource.TYPE_FRONT_PAGE) { - bundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true); - } else { - bundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, false); - } + bundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, currentPostType != PostDataSource.TYPE_FRONT_PAGE); SortTypeBottomSheetFragment sortTypeBottomSheetFragment = new SortTypeBottomSheetFragment(); sortTypeBottomSheetFragment.setArguments(bundle); sortTypeBottomSheetFragment.show(getSupportFragmentManager(), sortTypeBottomSheetFragment.getTag()); @@ -978,43 +976,43 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.action_search_main_activity: - Intent intent = new Intent(this, SearchActivity.class); - startActivity(intent); - return true; - case R.id.action_sort_main_activity: - changeSortType(); - return true; - case R.id.action_refresh_main_activity: - if (mMenu != null) { - mMenu.findItem(R.id.action_lazy_mode_main_activity).setTitle(R.string.action_start_lazy_mode); - } - sectionsPagerAdapter.refresh(); - mFetchUserInfoSuccess = false; - loadUserData(); - return true; - case R.id.action_lazy_mode_main_activity: - MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_main_activity); - if (isInLazyMode) { - sectionsPagerAdapter.stopLazyMode(); - isInLazyMode = false; - lazyModeItem.setTitle(R.string.action_start_lazy_mode); - params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); + int itemId = item.getItemId(); + if (itemId == R.id.action_search_main_activity) { + Intent intent = new Intent(this, SearchActivity.class); + startActivity(intent); + return true; + } else if (itemId == R.id.action_sort_main_activity) { + changeSortType(); + return true; + } else if (itemId == R.id.action_refresh_main_activity) { + if (mMenu != null) { + mMenu.findItem(R.id.action_lazy_mode_main_activity).setTitle(R.string.action_start_lazy_mode); + } + sectionsPagerAdapter.refresh(); + mFetchUserInfoSuccess = false; + loadUserData(); + return true; + } else if (itemId == R.id.action_lazy_mode_main_activity) { + MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_main_activity); + if (isInLazyMode) { + sectionsPagerAdapter.stopLazyMode(); + isInLazyMode = false; + lazyModeItem.setTitle(R.string.action_start_lazy_mode); + params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); + collapsingToolbarLayout.setLayoutParams(params); + } else { + if (sectionsPagerAdapter.startLazyMode()) { + isInLazyMode = true; + lazyModeItem.setTitle(R.string.action_stop_lazy_mode); + params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL); collapsingToolbarLayout.setLayoutParams(params); - } else { - if (sectionsPagerAdapter.startLazyMode()) { - isInLazyMode = true; - lazyModeItem.setTitle(R.string.action_stop_lazy_mode); - params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL); - collapsingToolbarLayout.setLayoutParams(params); - } } - return true; - case R.id.action_change_post_layout_main_activity: - PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment(); - postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag()); - return true; + } + return true; + } else if (itemId == R.id.action_change_post_layout_main_activity) { + PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment(); + postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag()); + return true; } return false; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MultiredditSelectionActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MultiredditSelectionActivity.java index e84534b1..0e189274 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MultiredditSelectionActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MultiredditSelectionActivity.java @@ -5,6 +5,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.MenuItem; import android.view.View; import android.view.Window; @@ -34,7 +35,7 @@ import ml.docilealligator.infinityforreddit.ActivityToolbarInterface; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.InsertMultiRedditAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertMultireddit; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent; import ml.docilealligator.infinityforreddit.fragments.MultiRedditListingFragment; @@ -167,10 +168,11 @@ public class MultiredditSelectionActivity extends BaseActivity implements Activi FetchMyMultiReddits.fetchMyMultiReddits(mOauthRetrofit, mAccessToken, new FetchMyMultiReddits.FetchMyMultiRedditsListener() { @Override public void success(ArrayList<MultiReddit> multiReddits) { - new InsertMultiRedditAsyncTask(mRedditDataRoomDatabase, multiReddits, mAccountName, () -> { + InsertMultireddit.insertMultireddit(mExecutor, new Handler(), mRedditDataRoomDatabase, + multiReddits, mAccountName, () -> { mInsertSuccess = true; ((MultiRedditListingFragment) mFragment).stopRefreshProgressbar(); - }).execute(); + }); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java index 5e0d1d6e..cbab1914 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java @@ -8,6 +8,7 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; +import android.os.Handler; import android.provider.MediaStore; import android.view.Menu; import android.view.MenuItem; @@ -51,7 +52,7 @@ import ml.docilealligator.infinityforreddit.Flair; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SubmitImagePostEvent; @@ -423,11 +424,11 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> { + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); loadSubredditIconSuccessful = true; - }).execute(); + }); } private void promptAlertDialog(int titleResId, int messageResId) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java index 51369282..48e012a4 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java @@ -6,6 +6,7 @@ import android.content.res.ColorStateList; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -42,7 +43,7 @@ import ml.docilealligator.infinityforreddit.Flair; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SubmitTextOrLinkPostEvent; @@ -354,11 +355,12 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> { + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, + mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); loadSubredditIconSuccessful = true; - }).execute(); + }); } private void promptAlertDialog(int titleResId, int messageResId) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java index 131baa39..7d93fef7 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java @@ -6,6 +6,7 @@ import android.content.res.ColorStateList; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -45,7 +46,7 @@ import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.adapters.MarkdownBottomBarRecyclerViewAdapter; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SubmitTextOrLinkPostEvent; @@ -371,11 +372,12 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> { + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, + mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); loadSubredditIconSuccessful = true; - }).execute(); + }); } private void promptAlertDialog(int titleResId, int messageResId) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java index cfb747a4..420477ff 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java @@ -7,6 +7,7 @@ import android.content.res.Resources; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.provider.MediaStore; import android.view.Menu; import android.view.MenuItem; @@ -54,7 +55,7 @@ import ml.docilealligator.infinityforreddit.Flair; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SubmitVideoOrGifPostEvent; @@ -431,11 +432,12 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> { + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, + mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); loadSubredditIconSuccessful = true; - }).execute(); + }); } private void promptAlertDialog(int titleResId, int messageResId) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java index 7e273b09..0c88bcb4 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java @@ -18,7 +18,6 @@ import com.google.android.material.snackbar.Snackbar; import com.r0adkll.slidr.Slidr; import java.util.ArrayList; -import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -68,8 +67,6 @@ public class ReportActivity extends BaseActivity { RedditDataRoomDatabase mRedditDataRoomDatabase; @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; private String mAccessToken; private String mFullname; private String mSubredditName; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java index 44cae730..35d6c66e 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java @@ -35,8 +35,6 @@ import com.r0adkll.slidr.model.SlidrInterface; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; -import java.util.concurrent.Executor; - import javax.inject.Inject; import javax.inject.Named; @@ -110,8 +108,6 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; private String mAccessToken; private String mAccountName; private String mQuery; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchSubredditsResultActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchSubredditsResultActivity.java index 4f417ca0..b6882196 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchSubredditsResultActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchSubredditsResultActivity.java @@ -21,8 +21,6 @@ import com.r0adkll.slidr.Slidr; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; -import java.util.concurrent.Executor; - import javax.inject.Inject; import javax.inject.Named; @@ -31,7 +29,6 @@ import butterknife.ButterKnife; import ml.docilealligator.infinityforreddit.ActivityToolbarInterface; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent; import ml.docilealligator.infinityforreddit.fragments.SubredditListingFragment; @@ -53,8 +50,6 @@ public class SearchSubredditsResultActivity extends BaseActivity implements Acti Toolbar toolbar; Fragment mFragment; @Inject - RedditDataRoomDatabase mRedditDataRoomDatabase; - @Inject @Named("default") SharedPreferences mSharedPreferences; @Inject @@ -62,8 +57,6 @@ public class SearchSubredditsResultActivity extends BaseActivity implements Acti SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; private String mAccessToken; private String mAccountName; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java index 6da07407..84db322c 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java @@ -22,7 +22,6 @@ import com.google.android.material.snackbar.Snackbar; import com.r0adkll.slidr.Slidr; import java.util.ArrayList; -import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -33,7 +32,6 @@ import ml.docilealligator.infinityforreddit.ActivityToolbarInterface; import ml.docilealligator.infinityforreddit.FetchUserFlairs; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.SelectUserFlair; import ml.docilealligator.infinityforreddit.UserFlair; import ml.docilealligator.infinityforreddit.adapters.UserFlairRecyclerViewAdapter; @@ -58,8 +56,6 @@ public class SelectUserFlairActivity extends BaseActivity implements ActivityToo @Named("oauth") Retrofit mOauthRetrofit; @Inject - RedditDataRoomDatabase mRedditDataRoomDatabase; - @Inject @Named("default") SharedPreferences mSharedPreferences; @Inject @@ -67,8 +63,6 @@ public class SelectUserFlairActivity extends BaseActivity implements ActivityToo SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; private LinearLayoutManager mLinearLayoutManager; private boolean mNullAccessToken = false; private String mAccessToken; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SendPrivateMessageActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SendPrivateMessageActivity.java index 61d44645..216dd2ae 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SendPrivateMessageActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SendPrivateMessageActivity.java @@ -16,8 +16,6 @@ import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.snackbar.Snackbar; -import java.util.concurrent.Executor; - import javax.inject.Inject; import javax.inject.Named; @@ -25,7 +23,6 @@ import butterknife.BindView; import butterknife.ButterKnife; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.message.ComposeMessage; import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; @@ -53,8 +50,6 @@ public class SendPrivateMessageActivity extends BaseActivity { @Named("oauth") Retrofit mOauthRetrofit; @Inject - RedditDataRoomDatabase mRedditDataRoomDatabase; - @Inject @Named("default") SharedPreferences mSharedPreferences; @Inject @@ -62,8 +57,6 @@ public class SendPrivateMessageActivity extends BaseActivity { SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; private String mAccessToken; private boolean isSubmitting = false; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SettingsActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SettingsActivity.java index 0831bf44..e19b5fa9 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SettingsActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SettingsActivity.java @@ -17,8 +17,6 @@ import com.google.android.material.appbar.AppBarLayout; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; -import java.util.concurrent.Executor; - import javax.inject.Inject; import javax.inject.Named; @@ -26,7 +24,6 @@ import butterknife.BindView; import butterknife.ButterKnife; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.RecreateActivityEvent; import ml.docilealligator.infinityforreddit.settings.AboutPreferenceFragment; @@ -58,11 +55,7 @@ public class SettingsActivity extends BaseActivity implements @Named("current_account") SharedPreferences mCurrentAccountSharedPreferences; @Inject - RedditDataRoomDatabase mRedditDataRoomDatabase; - @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; @Override protected void onCreate(Bundle savedInstanceState) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java index 366edda0..7e97c0a6 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java @@ -8,6 +8,7 @@ import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -51,7 +52,7 @@ import ml.docilealligator.infinityforreddit.Flair; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SubmitCrosspostEvent; @@ -424,11 +425,12 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> { + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, + mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); loadSubredditIconSuccessful = true; - }).execute(); + }); } private void promptAlertDialog(int titleResId, int messageResId) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java index 32f6f4a0..23efef58 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java @@ -29,7 +29,6 @@ import com.google.android.material.appbar.AppBarLayout; import com.r0adkll.slidr.Slidr; import java.util.ArrayList; -import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -81,8 +80,6 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; - @Inject - Executor mExecutor; public SubscribedSubredditViewModel mSubscribedSubredditViewModel; private String mAccessToken; private String mAccountName; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditSelectionActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditSelectionActivity.java index a28b8903..1029469d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditSelectionActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditSelectionActivity.java @@ -5,6 +5,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -36,7 +37,7 @@ import ml.docilealligator.infinityforreddit.FetchSubscribedThing; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThingsAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent; import ml.docilealligator.infinityforreddit.fragments.SubscribedSubredditsListingFragment; @@ -187,13 +188,15 @@ public class SubredditSelectionActivity extends BaseActivity implements Activity public void onFetchSubscribedThingSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData, ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubredditData> subredditData) { - new InsertSubscribedThingsAsyncTask( + InsertSubscribedThings.insertSubscribedThings( + mExecutor, + new Handler(), mRedditDataRoomDatabase, mAccountName, subscribedSubredditData, subscribedUserData, subredditData, - () -> mInsertSuccess = true).execute(); + () -> mInsertSuccess = true); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java index 775e434c..c4a90904 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java @@ -4,6 +4,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; @@ -43,8 +44,8 @@ import ml.docilealligator.infinityforreddit.FragmentCommunicator; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.asynctasks.InsertMultiRedditAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThingsAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertMultireddit; +import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.GoBackToMainPageEvent; import ml.docilealligator.infinityforreddit.events.RefreshMultiRedditsEvent; @@ -246,7 +247,9 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti public void onFetchSubscribedThingSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData, ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubredditData> subredditData) { - new InsertSubscribedThingsAsyncTask( + InsertSubscribedThings.insertSubscribedThings( + mExecutor, + new Handler(), mRedditDataRoomDatabase, mAccountName, subscribedSubredditData, @@ -255,7 +258,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti () -> { mInsertSuccess = true; sectionsPagerAdapter.stopRefreshProgressbar(); - }).execute(); + }); } @Override @@ -277,10 +280,10 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti FetchMyMultiReddits.fetchMyMultiReddits(mOauthRetrofit, mAccessToken, new FetchMyMultiReddits.FetchMyMultiRedditsListener() { @Override public void success(ArrayList<MultiReddit> multiReddits) { - new InsertMultiRedditAsyncTask(mRedditDataRoomDatabase, multiReddits, mAccountName, () -> { + InsertMultireddit.insertMultireddit(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddits, mAccountName, () -> { mInsertMultiredditSuccess = true; sectionsPagerAdapter.stopMultiRedditRefreshProgressbar(); - }).execute(); + }); } @Override @@ -297,7 +300,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti .setTitle(R.string.delete) .setMessage(R.string.delete_multi_reddit_dialog_message) .setPositiveButton(R.string.delete, (dialogInterface, i) - -> DeleteMultiReddit.deleteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, + -> DeleteMultiReddit.deleteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, mAccountName, multiReddit.getPath(), new DeleteMultiReddit.DeleteMultiRedditListener() { @Override public void success() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java index 1a5a8c38..e82ea47a 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java @@ -10,6 +10,7 @@ import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.text.Html; import android.view.Menu; import android.view.MenuItem; @@ -46,6 +47,7 @@ import com.r0adkll.slidr.model.SlidrConfig; import com.r0adkll.slidr.model.SlidrPosition; import java.io.File; +import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -57,8 +59,8 @@ import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; import ml.docilealligator.infinityforreddit.WallpaperSetter; -import ml.docilealligator.infinityforreddit.asynctasks.SaveBitmapImageToFileAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.SaveGIFToFileAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.SaveBitmapImageToFile; +import ml.docilealligator.infinityforreddit.asynctasks.SaveGIFToFile; import ml.docilealligator.infinityforreddit.bottomsheetfragments.SetAsWallpaperBottomSheetFragment; import ml.docilealligator.infinityforreddit.font.ContentFontFamily; import ml.docilealligator.infinityforreddit.font.ContentFontStyle; @@ -86,6 +88,8 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa @Inject @Named("default") SharedPreferences mSharedPreferences; + @Inject + Executor mExecutor; private boolean isActionBarHidden = false; private boolean isDownloading = false; private RequestManager glide; @@ -273,62 +277,62 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa @Override public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - return true; - case R.id.action_download_view_image_or_gif_activity: - if (isDownloading) { - return false; - } + int itemId = item.getItemId(); + if (itemId == android.R.id.home) { + finish(); + return true; + } else if (itemId == R.id.action_download_view_image_or_gif_activity) { + if (isDownloading) { + return false; + } - isDownloading = true; + isDownloading = true; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (ContextCompat.checkSelfPermission(this, - Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (ContextCompat.checkSelfPermission(this, + Manifest.permission.WRITE_EXTERNAL_STORAGE) + != PackageManager.PERMISSION_GRANTED) { - // Permission is not granted - // No explanation needed; request the permission - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, - PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); - } else { - // Permission has already been granted - download(); - } + // Permission is not granted + // No explanation needed; request the permission + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, + PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); } else { + // Permission has already been granted download(); } + } else { + download(); + } - return true; - case R.id.action_share_view_image_or_gif_activity: - if (isGif) - shareGif(); - else - shareImage(); - return true; - case R.id.action_set_wallpaper_view_image_or_gif_activity: - if (!isGif) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - SetAsWallpaperBottomSheetFragment setAsWallpaperBottomSheetFragment = new SetAsWallpaperBottomSheetFragment(); - setAsWallpaperBottomSheetFragment.show(getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); - } else { - WallpaperSetter.set(mImageUrl, WallpaperSetter.BOTH_SCREENS, this, - new WallpaperSetter.SetWallpaperListener() { - @Override - public void success() { - Toast.makeText(ViewImageOrGifActivity.this, R.string.wallpaper_set, Toast.LENGTH_SHORT).show(); - } - - @Override - public void failed() { - Toast.makeText(ViewImageOrGifActivity.this, R.string.error_set_wallpaper, Toast.LENGTH_SHORT).show(); - } - }); - } + return true; + } else if (itemId == R.id.action_share_view_image_or_gif_activity) { + if (isGif) + shareGif(); + else + shareImage(); + return true; + } else if (itemId == R.id.action_set_wallpaper_view_image_or_gif_activity) { + if (!isGif) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + SetAsWallpaperBottomSheetFragment setAsWallpaperBottomSheetFragment = new SetAsWallpaperBottomSheetFragment(); + setAsWallpaperBottomSheetFragment.show(getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); + } else { + WallpaperSetter.set(mExecutor, new Handler(), mImageUrl, WallpaperSetter.BOTH_SCREENS, this, + new WallpaperSetter.SetWallpaperListener() { + @Override + public void success() { + Toast.makeText(ViewImageOrGifActivity.this, R.string.wallpaper_set, Toast.LENGTH_SHORT).show(); + } + + @Override + public void failed() { + Toast.makeText(ViewImageOrGifActivity.this, R.string.error_set_wallpaper, Toast.LENGTH_SHORT).show(); + } + }); } - return true; + } + return true; } return false; @@ -353,8 +357,9 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { if (getExternalCacheDir() != null) { Toast.makeText(ViewImageOrGifActivity.this, R.string.save_image_first, Toast.LENGTH_SHORT).show(); - new SaveBitmapImageToFileAsyncTask(resource, getExternalCacheDir().getPath(), mImageFileName, - new SaveBitmapImageToFileAsyncTask.SaveBitmapImageToFileAsyncTaskListener() { + SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, new Handler(), resource, + getExternalCacheDir().getPath(), mImageFileName, + new SaveBitmapImageToFile.SaveBitmapImageToFileListener() { @Override public void saveSuccess(File imageFile) { Uri uri = FileProvider.getUriForFile(ViewImageOrGifActivity.this, @@ -372,7 +377,7 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa Toast.makeText(ViewImageOrGifActivity.this, R.string.cannot_save_image, Toast.LENGTH_SHORT).show(); } - }).execute(); + }); } else { Toast.makeText(ViewImageOrGifActivity.this, R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); @@ -397,8 +402,8 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa @Override public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) { if (getExternalCacheDir() != null) { - new SaveGIFToFileAsyncTask(resource, getExternalCacheDir().getPath(), mImageFileName, - new SaveGIFToFileAsyncTask.SaveGIFToFileAsyncTaskListener() { + SaveGIFToFile.saveGifToFile(mExecutor, new Handler(), resource, getExternalCacheDir().getPath(), mImageFileName, + new SaveGIFToFile.SaveGIFToFileAsyncTaskListener() { @Override public void saveSuccess(File imageFile) { Uri uri = FileProvider.getUriForFile(ViewImageOrGifActivity.this, @@ -416,7 +421,7 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa Toast.makeText(ViewImageOrGifActivity.this, R.string.cannot_save_gif, Toast.LENGTH_SHORT).show(); } - }).execute(); + }); } else { Toast.makeText(ViewImageOrGifActivity.this, R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); @@ -440,7 +445,7 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa @Override public void setToHomeScreen(int viewPagerPosition) { - WallpaperSetter.set(mImageUrl, WallpaperSetter.HOME_SCREEN, this, + WallpaperSetter.set(mExecutor, new Handler(), mImageUrl, WallpaperSetter.HOME_SCREEN, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { @@ -456,7 +461,7 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa @Override public void setToLockScreen(int viewPagerPosition) { - WallpaperSetter.set(mImageUrl, WallpaperSetter.LOCK_SCREEN, this, + WallpaperSetter.set(mExecutor, new Handler(), mImageUrl, WallpaperSetter.LOCK_SCREEN, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { @@ -472,7 +477,7 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa @Override public void setToBoth(int viewPagerPosition) { - WallpaperSetter.set(mImageUrl, WallpaperSetter.BOTH_SCREENS, this, + WallpaperSetter.set(mExecutor, new Handler(), mImageUrl, WallpaperSetter.BOTH_SCREENS, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java index 58898098..10866770 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java @@ -5,6 +5,7 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -28,6 +29,7 @@ import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; +import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -81,6 +83,8 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa @Inject @Named("default") SharedPreferences sharedPreferences; + @Inject + Executor executor; @Override protected void onCreate(Bundle savedInstanceState) { @@ -301,7 +305,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa @Override public void setToHomeScreen(int viewPagerPosition) { if (images != null && viewPagerPosition >= 0 && viewPagerPosition < images.size()) { - WallpaperSetter.set(images.get(viewPagerPosition).getLink(), WallpaperSetter.HOME_SCREEN, this, + WallpaperSetter.set(executor, new Handler(), images.get(viewPagerPosition).getLink(), WallpaperSetter.HOME_SCREEN, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { @@ -319,7 +323,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa @Override public void setToLockScreen(int viewPagerPosition) { if (images != null && viewPagerPosition >= 0 && viewPagerPosition < images.size()) { - WallpaperSetter.set(images.get(viewPagerPosition).getLink(), WallpaperSetter.LOCK_SCREEN, this, + WallpaperSetter.set(executor, new Handler(), images.get(viewPagerPosition).getLink(), WallpaperSetter.LOCK_SCREEN, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { @@ -337,7 +341,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa @Override public void setToBoth(int viewPagerPosition) { if (images != null && viewPagerPosition >= 0 && viewPagerPosition < images.size()) { - WallpaperSetter.set(images.get(viewPagerPosition).getLink(), WallpaperSetter.BOTH_SCREENS, this, + WallpaperSetter.set(executor, new Handler(), images.get(viewPagerPosition).getLink(), WallpaperSetter.BOTH_SCREENS, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewMultiRedditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewMultiRedditDetailActivity.java index e1bdf079..4c673726 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewMultiRedditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewMultiRedditDetailActivity.java @@ -4,6 +4,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -264,7 +265,7 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT .setTitle(R.string.delete) .setMessage(R.string.delete_multi_reddit_dialog_message) .setPositiveButton(R.string.delete, (dialogInterface, i) - -> DeleteMultiReddit.deleteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, + -> DeleteMultiReddit.deleteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, mAccountName, multiPath, new DeleteMultiReddit.DeleteMultiRedditListener() { @Override public void success() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java index 145fdadc..3e395af8 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java @@ -1,61 +1,41 @@ package ml.docilealligator.infinityforreddit.activities; +import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; -import android.content.res.Resources; -import android.graphics.Canvas; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; -import android.util.DisplayMetrics; -import android.view.HapticFeedbackConstants; import android.view.KeyEvent; -import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.content.res.ResourcesCompat; -import androidx.core.graphics.drawable.DrawableCompat; -import androidx.recyclerview.widget.ItemTouchHelper; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.LinearSmoothScroller; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import androidx.transition.AutoTransition; -import androidx.transition.TransitionManager; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.RequestManager; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentActivity; +import androidx.fragment.app.FragmentManager; +import androidx.viewpager2.adapter.FragmentStateAdapter; +import androidx.viewpager2.widget.ViewPager2; + import com.evernote.android.state.State; import com.github.piasy.biv.BigImageViewer; import com.github.piasy.biv.loader.glide.GlideImageLoader; import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.livefront.bridge.Bridge; -import com.r0adkll.slidr.Slidr; import com.r0adkll.slidr.model.SlidrInterface; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; import java.util.concurrent.Executor; import javax.inject.Inject; @@ -63,181 +43,71 @@ import javax.inject.Named; import butterknife.BindView; import butterknife.ButterKnife; -import im.ene.toro.exoplayer.ExoCreator; -import im.ene.toro.media.PlaybackInfo; -import im.ene.toro.media.VolumeInfo; import ml.docilealligator.infinityforreddit.ActivityToolbarInterface; -import ml.docilealligator.infinityforreddit.DeleteThing; import ml.docilealligator.infinityforreddit.Flair; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.SaveThing; import ml.docilealligator.infinityforreddit.SortType; import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback; -import ml.docilealligator.infinityforreddit.adapters.CommentAndPostRecyclerViewAdapter; -import ml.docilealligator.infinityforreddit.apis.RedditAPI; import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; -import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostCommentSortTypeBottomSheetFragment; import ml.docilealligator.infinityforreddit.comment.Comment; -import ml.docilealligator.infinityforreddit.comment.FetchComment; -import ml.docilealligator.infinityforreddit.comment.FetchRemovedComment; -import ml.docilealligator.infinityforreddit.comment.ParseComment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; -import ml.docilealligator.infinityforreddit.customviews.CustomToroContainer; -import ml.docilealligator.infinityforreddit.events.ChangeNSFWBlurEvent; -import ml.docilealligator.infinityforreddit.events.ChangeNetworkStatusEvent; -import ml.docilealligator.infinityforreddit.events.ChangeSpoilerBlurEvent; -import ml.docilealligator.infinityforreddit.events.PostUpdateEventToDetailActivity; -import ml.docilealligator.infinityforreddit.events.PostUpdateEventToPostList; import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent; -import ml.docilealligator.infinityforreddit.message.ReadMessage; -import ml.docilealligator.infinityforreddit.post.FetchPost; -import ml.docilealligator.infinityforreddit.post.FetchRemovedPost; -import ml.docilealligator.infinityforreddit.post.HidePost; -import ml.docilealligator.infinityforreddit.post.ParsePost; +import ml.docilealligator.infinityforreddit.fragments.PostFragment; +import ml.docilealligator.infinityforreddit.fragments.ViewPostDetailFragment; import ml.docilealligator.infinityforreddit.post.Post; -import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData; -import ml.docilealligator.infinityforreddit.subreddit.SubredditData; -import ml.docilealligator.infinityforreddit.utils.APIUtils; import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; -import ml.docilealligator.infinityforreddit.utils.Utils; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; -import retrofit2.Retrofit; - -import static im.ene.toro.media.PlaybackInfo.INDEX_UNSET; -import static im.ene.toro.media.PlaybackInfo.TIME_UNSET; -import static ml.docilealligator.infinityforreddit.activities.CommentActivity.RETURN_EXTRA_COMMENT_DATA_KEY; -import static ml.docilealligator.infinityforreddit.activities.CommentActivity.WRITE_COMMENT_REQUEST_CODE; public class ViewPostDetailActivity extends BaseActivity implements FlairBottomSheetFragment.FlairSelectionCallback, SortTypeSelectionCallback, ActivityToolbarInterface { + public static final String EXTRA_POST_LIST = "EPL"; public static final String EXTRA_POST_DATA = "EPD"; - public static final String EXTRA_POST_LIST_POSITION = "EPLI"; public static final String EXTRA_POST_ID = "EPI"; + public static final String EXTRA_POST_LIST_POSITION = "EPLP"; public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI"; public static final String EXTRA_MESSAGE_FULLNAME = "ENI"; public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN"; public static final int EDIT_COMMENT_REQUEST_CODE = 3; public static final int GIVE_AWARD_REQUEST_CODE = 100; - private static final int EDIT_POST_REQUEST_CODE = 2; - String mAccessToken; @State String mAccountName; @State - Post mPost; - @State - boolean isLoadingMoreChildren = false; - @State - boolean isRefreshing = false; - @State - boolean isSingleCommentThreadMode = false; - @State - ArrayList<Comment> comments; - @State - ArrayList<String> children; - @State - int mChildrenStartingIndex = 0; - @State - boolean loadMoreChildrenSuccess = true; - @State - boolean hasMoreChildren; - @State - boolean isFetchingComments = false; - @State - String mMessageFullname; - @State String mNewAccountName; - @State - String sortType; - @State - boolean mRespectSubredditRecommendedSortType; @BindView(R.id.coordinator_layout_view_post_detail) CoordinatorLayout mCoordinatorLayout; @BindView(R.id.appbar_layout_view_post_detail_activity) AppBarLayout mAppBarLayout; @BindView(R.id.toolbar_view_post_detail_activity) Toolbar mToolbar; - @BindView(R.id.swipe_refresh_layout_view_post_detail_activity) - SwipeRefreshLayout mSwipeRefreshLayout; - @BindView(R.id.recycler_view_view_post_detail) - CustomToroContainer mRecyclerView; - @BindView(R.id.fetch_post_info_linear_layout_view_post_detail_activity) - LinearLayout mFetchPostInfoLinearLayout; - @BindView(R.id.fetch_post_info_image_view_view_post_detail_activity) - ImageView mFetchPostInfoImageView; - @BindView(R.id.fetch_post_info_text_view_view_post_detail_activity) - TextView mFetchPostInfoTextView; + @BindView(R.id.view_pager_2_view_post_detail_activity) + ViewPager2 viewPager2; @BindView(R.id.fab_view_post_detail_activity) FloatingActionButton fab; @Inject - @Named("no_oauth") - Retrofit mRetrofit; - @Inject - @Named("pushshift") - Retrofit pushshiftRetrofit; - @Inject - @Named("oauth") - Retrofit mOauthRetrofit; - @Inject - @Named("gfycat") - Retrofit mGfycatRetrofit; - @Inject - @Named("redgifs") - Retrofit mRedgifsRetrofit; - @Inject RedditDataRoomDatabase mRedditDataRoomDatabase; @Inject @Named("default") SharedPreferences mSharedPreferences; @Inject - @Named("sort_type") - SharedPreferences mSortTypeSharedPreferences; - @Inject - @Named("nsfw_and_spoiler") - SharedPreferences mNsfwAndSpoilerSharedPreferences; - @Inject @Named("current_account") SharedPreferences mCurrentAccountSharedPreferences; @Inject CustomThemeWrapper mCustomThemeWrapper; @Inject - ExoCreator mExoCreator; - @Inject Executor mExecutor; - private RequestManager mGlide; - private Locale mLocale; - private Menu mMenu; + @State + ArrayList<Post> posts; + @State + Post post; + private FragmentManager fragmentManager; + private SlidrInterface mSlidrInterface; + private SectionsPagerAdapter sectionsPagerAdapter; private int orientation; - private int postListPosition = -1; - private String mSingleCommentId; - private boolean showToast = false; - private boolean isSortingComments = false; private boolean mVolumeKeysNavigateComments; - private boolean mIsSmoothScrolling = false; - private boolean mLockFab; - private boolean mSwipeUpToHideFab; - private boolean mExpandChildren; - private int mWindowWidth; - private LinearLayoutManager mLinearLayoutManager; - private CommentAndPostRecyclerViewAdapter mAdapter; - private RecyclerView.SmoothScroller mSmoothScroller; - private PostCommentSortTypeBottomSheetFragment mPostCommentSortTypeBottomSheetFragment; - private SlidrInterface mSlidrInterface; - private Drawable mSavedIcon; - private Drawable mUnsavedIcon; - private ColorDrawable backgroundSwipeRight; - private ColorDrawable backgroundSwipeLeft; - private Drawable drawableSwipeRight; - private Drawable drawableSwipeLeft; - private int swipeLeftAction; - private int swipeRightAction; - private float swipeActionThreshold; - private ItemTouchHelper touchHelper; + @Override protected void onCreate(Bundle savedInstanceState) { @@ -257,12 +127,9 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS applyCustomTheme(); - mSavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_toolbar_24dp); - mUnsavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_border_toolbar_24dp); - - if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) { + /*if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) { mSlidrInterface = Slidr.attach(this); - } + }*/ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Window window = getWindow(); @@ -286,288 +153,59 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams(); params.bottomMargin += navBarHeight; fab.setLayoutParams(params); - mRecyclerView.setPadding(0, 0, 0, navBarHeight + mRecyclerView.getPaddingBottom()); - showToast = true; } } } - DisplayMetrics displayMetrics = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); - mWindowWidth = displayMetrics.widthPixels; + fragmentManager = getSupportFragmentManager(); - mToolbar.setTitle(""); - setSupportActionBar(mToolbar); - setToolbarGoToTop(mToolbar); - - mVolumeKeysNavigateComments = mSharedPreferences.getBoolean(SharedPreferencesUtils.VOLUME_KEYS_NAVIGATE_COMMENTS, false); - mLockFab = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_JUMP_TO_NEXT_TOP_LEVEL_COMMENT_BUTTON, false); - mSwipeUpToHideFab = mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_UP_TO_HIDE_JUMP_TO_NEXT_TOP_LEVEL_COMMENT_BUTTON, false); - mExpandChildren = !mSharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_TOP_LEVEL_COMMENTS_FIRST, false); if (savedInstanceState == null) { - mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false); + posts = getIntent().getParcelableArrayListExtra(EXTRA_POST_LIST); + post = getIntent().getParcelableExtra(EXTRA_POST_DATA); } - mGlide = Glide.with(this); - Resources resources = getResources(); - mLocale = getResources().getConfiguration().locale; - - mLinearLayoutManager = new LinearLayoutManager(this); - mRecyclerView.setLayoutManager(mLinearLayoutManager); - - if (children != null && children.size() > 0) { - mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { - @Override - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - if (!mIsSmoothScrolling && !mLockFab) { - if (!recyclerView.canScrollVertically(1)) { - fab.hide(); - } else { - if (dy > 0) { - if (mSwipeUpToHideFab) { - fab.show(); - } else { - fab.hide(); - } - } else { - if (mSwipeUpToHideFab) { - fab.hide(); - } else { - fab.show(); - } - } - } - } - - if (!isLoadingMoreChildren && loadMoreChildrenSuccess) { - int visibleItemCount = mLinearLayoutManager.getChildCount(); - int totalItemCount = mLinearLayoutManager.getItemCount(); - int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); - - if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { - fetchMoreComments(); - } - } - } + orientation = getResources().getConfiguration().orientation; - @Override - public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { - if (newState == RecyclerView.SCROLL_STATE_IDLE) { - mIsSmoothScrolling = false; - } - } - }); - } else { - mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { - @Override - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - if (!mIsSmoothScrolling && !mLockFab) { - if (!recyclerView.canScrollVertically(1)) { - fab.hide(); - } else { - if (dy > 0) { - if (mSwipeUpToHideFab) { - fab.show(); - } else { - fab.hide(); - } - } else { - if (mSwipeUpToHideFab) { - fab.hide(); - } else { - fab.show(); - } - } - } - } - } - - @Override - public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { - if (newState == RecyclerView.SCROLL_STATE_IDLE) { - mIsSmoothScrolling = false; - } - } - }); - } - - boolean enableSwipeAction = mSharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_SWIPE_ACTION, false); - boolean vibrateWhenActionTriggered = mSharedPreferences.getBoolean(SharedPreferencesUtils.VIBRATE_WHEN_ACTION_TRIGGERED, true); - swipeActionThreshold = Float.parseFloat(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_ACTION_THRESHOLD, "0.3")); - swipeRightAction = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_RIGHT_ACTION, "1")); - swipeLeftAction = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_LEFT_ACTION, "0")); - initializeSwipeActionDrawable(); - touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() { - boolean exceedThreshold = false; - - @Override - public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { - if (!(viewHolder instanceof CommentAndPostRecyclerViewAdapter.CommentViewHolder)) { - return makeMovementFlags(0, 0); - } - int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; - return makeMovementFlags(0, swipeFlags); - } - - @Override - public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { - return false; - } - - @Override - public boolean isItemViewSwipeEnabled() { - return true; - } - - @Override - public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { - if (touchHelper != null) { - touchHelper.attachToRecyclerView(null); - touchHelper.attachToRecyclerView(mRecyclerView); - if (mAdapter != null) { - mAdapter.onItemSwipe(viewHolder, direction, swipeLeftAction, swipeRightAction); - } - } - } - - @Override - public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { - super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); - - View itemView = viewHolder.itemView; - int horizontalOffset = (int) Utils.convertDpToPixel(16, ViewPostDetailActivity.this); - if (dX > 0) { - if (dX > (itemView.getRight() - itemView.getLeft()) * swipeActionThreshold) { - if (!exceedThreshold) { - exceedThreshold = true; - if (vibrateWhenActionTriggered) { - viewHolder.itemView.setHapticFeedbackEnabled(true); - viewHolder.itemView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); - } - } - backgroundSwipeRight.setBounds(0, itemView.getTop(), itemView.getRight(), itemView.getBottom()); - } else { - exceedThreshold = false; - backgroundSwipeRight.setBounds(0, 0, 0, 0); - } - - drawableSwipeRight.setBounds(itemView.getLeft() + ((int) dX) - horizontalOffset - drawableSwipeRight.getIntrinsicWidth(), - (itemView.getBottom() + itemView.getTop() - drawableSwipeRight.getIntrinsicHeight()) / 2, - itemView.getLeft() + ((int) dX) - horizontalOffset, - (itemView.getBottom() + itemView.getTop() + drawableSwipeRight.getIntrinsicHeight()) / 2); - backgroundSwipeRight.draw(c); - drawableSwipeRight.draw(c); - } else if (dX < 0) { - if (-dX > (itemView.getRight() - itemView.getLeft()) * swipeActionThreshold) { - if (!exceedThreshold) { - exceedThreshold = true; - if (vibrateWhenActionTriggered) { - viewHolder.itemView.setHapticFeedbackEnabled(true); - viewHolder.itemView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); - } - } - backgroundSwipeLeft.setBounds(0, itemView.getTop(), itemView.getRight(), itemView.getBottom()); - } else { - exceedThreshold = false; - backgroundSwipeLeft.setBounds(0, 0, 0, 0); - } - drawableSwipeLeft.setBounds(itemView.getRight() + ((int) dX) + horizontalOffset, - (itemView.getBottom() + itemView.getTop() - drawableSwipeLeft.getIntrinsicHeight()) / 2, - itemView.getRight() + ((int) dX) + horizontalOffset + drawableSwipeLeft.getIntrinsicWidth(), - (itemView.getBottom() + itemView.getTop() + drawableSwipeLeft.getIntrinsicHeight()) / 2); - backgroundSwipeLeft.draw(c); - drawableSwipeLeft.draw(c); - } - } - - @Override - public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) { - return swipeActionThreshold; - } - }); - - if (enableSwipeAction) { - touchHelper.attachToRecyclerView(mRecyclerView); - } - - mSwipeRefreshLayout.setOnRefreshListener(() -> refresh(true, true)); - - mSmoothScroller = new LinearSmoothScroller(this) { - @Override - protected int getVerticalSnapPreference() { - return LinearSmoothScroller.SNAP_TO_START; - } - }; + mToolbar.setTitle(""); + setSupportActionBar(mToolbar); + setToolbarGoToTop(mToolbar); - mSingleCommentId = getIntent().getStringExtra(EXTRA_SINGLE_COMMENT_ID); if (savedInstanceState == null) { - if (mSingleCommentId != null) { - isSingleCommentThreadMode = true; - } - mMessageFullname = getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME); mNewAccountName = getIntent().getStringExtra(EXTRA_NEW_ACCOUNT_NAME); - - if (!mRespectSubredditRecommendedSortType || isSingleCommentThreadMode) { - sortType = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.BEST.value.toUpperCase()); - if (sortType != null) { - mToolbar.setTitle(new SortType(SortType.Type.valueOf(sortType)).getType().fullName); - sortType = sortType.toLowerCase(); - } - } - } else { - if (sortType != null) { - mToolbar.setTitle(new SortType(SortType.Type.valueOf(sortType.toUpperCase())).getType().fullName); - } } - orientation = resources.getConfiguration().orientation; - - mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null); mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null); - checkNewAccountAndBindView(); + mVolumeKeysNavigateComments = mSharedPreferences.getBoolean(SharedPreferencesUtils.VOLUME_KEYS_NAVIGATE_COMMENTS, false); - if (getIntent().hasExtra(EXTRA_POST_LIST_POSITION)) { - postListPosition = getIntent().getIntExtra(EXTRA_POST_LIST_POSITION, -1); - } + fab.setOnClickListener(view -> { + if (sectionsPagerAdapter != null) { + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.scrollToNextParentComment(); + } + } + }); - mPostCommentSortTypeBottomSheetFragment = new PostCommentSortTypeBottomSheetFragment(); + checkNewAccountAndBindView(savedInstanceState); } - private void initializeSwipeActionDrawable() { - if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) { - backgroundSwipeRight = new ColorDrawable(mCustomThemeWrapper.getDownvoted()); - drawableSwipeRight = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_downward_black_24dp, null); - } else { - backgroundSwipeRight = new ColorDrawable(mCustomThemeWrapper.getUpvoted()); - drawableSwipeRight = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_upward_black_24dp, null); + public void setTitle(String title) { + if (mToolbar != null) { + mToolbar.setTitle(title); } + } - if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) { - backgroundSwipeLeft = new ColorDrawable(mCustomThemeWrapper.getUpvoted()); - drawableSwipeLeft = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_upward_black_24dp, null); - } else { - backgroundSwipeLeft = new ColorDrawable(mCustomThemeWrapper.getDownvoted()); - drawableSwipeLeft = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_downward_black_24dp, null); - } + public void showFab() { + fab.show(); } - @Override - protected void onResume() { - super.onResume(); - if (mAdapter != null && mRecyclerView != null) { - mRecyclerView.onWindowVisibilityChanged(View.VISIBLE); - } + public void hideFab() { + fab.hide(); } - @Override - protected void onPause() { - super.onPause(); - if (mAdapter != null && mRecyclerView != null) { - mRecyclerView.onWindowVisibilityChanged(View.GONE); - } + public void showSnackBar(int resId) { + Snackbar.make(mCoordinatorLayout, resId, Snackbar.LENGTH_SHORT).show(); } @Override @@ -584,13 +222,10 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS protected void applyCustomTheme() { mCoordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor()); applyAppBarLayoutAndToolbarTheme(mAppBarLayout, mToolbar); - mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); - mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); - mFetchPostInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor()); applyFABTheme(fab); } - private void checkNewAccountAndBindView() { + private void checkNewAccountAndBindView(Bundle savedInstanceState) { if (mNewAccountName != null) { if (mAccountName == null || !mAccountName.equals(mNewAccountName)) { SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, @@ -599,823 +234,58 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show(); mNewAccountName = null; - if (newAccount != null) { - mAccessToken = newAccount.getAccessToken(); - mAccountName = newAccount.getAccountName(); - } - bindView(); + bindView(savedInstanceState); }); } else { - bindView(); + bindView(savedInstanceState); } } else { - bindView(); - } - } - - private void bindView() { - if (mAccessToken != null && mMessageFullname != null) { - ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() { - @Override - public void readSuccess() { - mMessageFullname = null; - } - - @Override - public void readFailed() { - - } - }); - } - - if (mPost == null) { - mPost = getIntent().getParcelableExtra(EXTRA_POST_DATA); - } - - if (mPost == null) { - fetchPostAndCommentsById(getIntent().getStringExtra(EXTRA_POST_ID)); - } else { - setupMenu(); - - mAdapter = new CommentAndPostRecyclerViewAdapter(ViewPostDetailActivity.this, - mCustomThemeWrapper, mRetrofit, mOauthRetrofit, mGfycatRetrofit, - mRedgifsRetrofit, mRedditDataRoomDatabase, mGlide, - mWindowWidth, mAccessToken, mAccountName, mPost, mLocale, mSingleCommentId, - isSingleCommentThreadMode, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mExoCreator, - new CommentAndPostRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { - @Override - public void updatePost(Post post) { - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - - @Override - public void retryFetchingComments() { - fetchCommentsRespectRecommendedSort(false); - } - - @Override - public void retryFetchingMoreComments() { - isLoadingMoreChildren = false; - loadMoreChildrenSuccess = true; - - fetchMoreComments(); - } - }); - mRecyclerView.setAdapter(mAdapter); - - if (comments == null) { - fetchCommentsRespectRecommendedSort(false); - } else { - if (isRefreshing) { - isRefreshing = false; - refresh(true, true); - } else if (isFetchingComments) { - fetchCommentsRespectRecommendedSort(false); - } else { - mAdapter.addComments(comments, hasMoreChildren); - if (isLoadingMoreChildren) { - isLoadingMoreChildren = false; - fetchMoreComments(); - } - } - } + bindView(savedInstanceState); } - - mRecyclerView.setCacheManager(mAdapter); - mRecyclerView.setPlayerInitializer(order -> { - VolumeInfo volumeInfo = new VolumeInfo(true, 0f); - return new PlaybackInfo(INDEX_UNSET, TIME_UNSET, volumeInfo); - }); - - fab.setOnClickListener(view -> scrollToNextParentComment()); } - private void setupMenu() { - if (mMenu != null) { - MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_activity); - MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_activity); - - mMenu.findItem(R.id.action_comment_view_post_detail_activity).setVisible(true); - mMenu.findItem(R.id.action_sort_view_post_detail_activity).setVisible(true); - - if (mAccessToken != null) { - if (mPost.isSaved()) { - saveItem.setVisible(true); - saveItem.setIcon(mSavedIcon); - } else { - saveItem.setVisible(true); - saveItem.setIcon(mUnsavedIcon); - } - - if (mPost.isHidden()) { - hideItem.setVisible(true); - hideItem.setTitle(R.string.action_unhide_post); - } else { - hideItem.setVisible(true); - hideItem.setTitle(R.string.action_hide_post); - } - } else { - saveItem.setVisible(false); - hideItem.setVisible(false); - } - - if (mPost.getAuthor().equals(mAccountName)) { - if (mPost.getPostType() == Post.TEXT_TYPE) { - mMenu.findItem(R.id.action_edit_view_post_detail_activity).setVisible(true); - } - mMenu.findItem(R.id.action_delete_view_post_detail_activity).setVisible(true); - - MenuItem nsfwItem = mMenu.findItem(R.id.action_nsfw_view_post_detail_activity); - nsfwItem.setVisible(true); - if (mPost.isNSFW()) { - nsfwItem.setTitle(R.string.action_unmark_nsfw); - } else { - nsfwItem.setTitle(R.string.action_mark_nsfw); - } - - MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_activity); - spoilerItem.setVisible(true); - if (mPost.isSpoiler()) { - spoilerItem.setTitle(R.string.action_unmark_spoiler); - } else { - spoilerItem.setTitle(R.string.action_mark_spoiler); - } - - mMenu.findItem(R.id.action_edit_flair_view_post_detail_activity).setVisible(true); - } - - mMenu.findItem(R.id.action_view_crosspost_parent_view_post_detail_activity).setVisible(mPost.getCrosspostParentId() != null); - - if ("[deleted]".equals(mPost.getAuthor()) || - "[deleted]".equals(mPost.getSelfText()) || - "[removed]".equals(mPost.getSelfText()) - ) { - mMenu.findItem(R.id.action_see_removed_view_post_detail_activity).setVisible(true); - } - } - } - - private Drawable getMenuItemIcon(int drawableId) { - Drawable icon = getDrawable(drawableId); - if (icon != null) { - DrawableCompat.setTint(icon, mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor()); + private void bindView(Bundle savedInstanceState) { + sectionsPagerAdapter = new SectionsPagerAdapter(this); + viewPager2.setAdapter(sectionsPagerAdapter); + if (savedInstanceState == null) { + viewPager2.setCurrentItem(getIntent().getIntExtra(EXTRA_POST_LIST_POSITION, 0), false); } - - return icon; } - private void fetchPostAndCommentsById(String subredditId) { - mFetchPostInfoLinearLayout.setVisibility(View.GONE); - mSwipeRefreshLayout.setRefreshing(true); - mGlide.clear(mFetchPostInfoImageView); - - Call<String> postAndComments; - if (mAccessToken == null) { - if (isSingleCommentThreadMode && mSingleCommentId != null) { - postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadById( - subredditId, mSingleCommentId, sortType); - } else { - postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsById(subredditId, - sortType); - } - } else { - if (isSingleCommentThreadMode && mSingleCommentId != null) { - postAndComments = mOauthRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadByIdOauth(subredditId, - mSingleCommentId, sortType, APIUtils.getOAuthHeader(mAccessToken)); - } else { - postAndComments = mOauthRetrofit.create(RedditAPI.class).getPostAndCommentsByIdOauth(subredditId, - sortType, APIUtils.getOAuthHeader(mAccessToken)); - } - } - postAndComments.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - mSwipeRefreshLayout.setRefreshing(false); - - if (response.isSuccessful()) { - ParsePost.parsePost(response.body(), new ParsePost.ParsePostListener() { - @Override - public void onParsePostSuccess(Post post) { - mPost = post; - - setupMenu(); - - mAdapter = new CommentAndPostRecyclerViewAdapter(ViewPostDetailActivity.this, - mCustomThemeWrapper, mRetrofit, mOauthRetrofit, mGfycatRetrofit, - mRedgifsRetrofit, mRedditDataRoomDatabase, mGlide, - mWindowWidth, mAccessToken, mAccountName, mPost, mLocale, - mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences, - mNsfwAndSpoilerSharedPreferences, mExoCreator, - new CommentAndPostRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { - @Override - public void updatePost(Post post) { - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - - @Override - public void retryFetchingComments() { - fetchCommentsRespectRecommendedSort(false); - } - - @Override - public void retryFetchingMoreComments() { - isLoadingMoreChildren = false; - loadMoreChildrenSuccess = true; - - fetchMoreComments(); - } - }); - mRecyclerView.setAdapter(mAdapter); - - if (mRespectSubredditRecommendedSortType) { - fetchCommentsRespectRecommendedSort(false); - } else { - ParseComment.parseComment(response.body(), new ArrayList<>(), mLocale, - mExpandChildren, new ParseComment.ParseCommentListener() { - @Override - public void onParseCommentSuccess(ArrayList<Comment> expandedComments, String parentId, ArrayList<String> moreChildrenFullnames) { - ViewPostDetailActivity.this.children = moreChildrenFullnames; - - hasMoreChildren = children.size() != 0; - mAdapter.addComments(expandedComments, hasMoreChildren); - - if (children.size() > 0) { - mRecyclerView.clearOnScrollListeners(); - mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { - @Override - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - if (!mIsSmoothScrolling && !mLockFab) { - if (!recyclerView.canScrollVertically(1)) { - fab.hide(); - } else { - if (dy > 0) { - if (mSwipeUpToHideFab) { - fab.show(); - } else { - fab.hide(); - } - } else { - if (mSwipeUpToHideFab) { - fab.hide(); - } else { - fab.show(); - } - } - } - } - - if (!isLoadingMoreChildren && loadMoreChildrenSuccess) { - int visibleItemCount = mLinearLayoutManager.getChildCount(); - int totalItemCount = mLinearLayoutManager.getItemCount(); - int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); - - if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { - fetchMoreComments(); - } - } - } - - @Override - public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { - if (newState == RecyclerView.SCROLL_STATE_IDLE) { - mIsSmoothScrolling = false; - } - } - }); - } - } - - @Override - public void onParseCommentFailed() { - mAdapter.initiallyLoadCommentsFailed(); - } - }); - } - } - - @Override - public void onParsePostFail() { - showErrorView(subredditId); - } - }); - } else { - showErrorView(subredditId); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - showErrorView(subredditId); + private void editComment(String commentAuthor, String commentContentMarkdown, int position) { + if (sectionsPagerAdapter != null) { + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.editComment(commentAuthor, commentContentMarkdown, position); } - }); - } - - private void fetchCommentsRespectRecommendedSort(boolean changeRefreshState, boolean checkSortState, String sortType) { - if (mRespectSubredditRecommendedSortType && mPost != null) { - FetchSubredditData.fetchSubredditData(mRetrofit, mPost.getSubredditName(), - new FetchSubredditData.FetchSubredditDataListener() { - @Override - public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { - if (subredditData.getSuggestedCommentSort() == null || subredditData.getSuggestedCommentSort().equals("null") || subredditData.getSuggestedCommentSort().equals("")) { - mRespectSubredditRecommendedSortType = false; - ViewPostDetailActivity.this.sortType = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.BEST.value.toUpperCase()); - if (ViewPostDetailActivity.this.sortType != null) { - mToolbar.setTitle(new SortType(SortType.Type.valueOf(ViewPostDetailActivity.this.sortType)).getType().fullName); - ViewPostDetailActivity.this.sortType = ViewPostDetailActivity.this.sortType.toLowerCase(); - } - fetchComments(changeRefreshState, checkSortState, ViewPostDetailActivity.this.sortType); - } else { - ViewPostDetailActivity.this.sortType = subredditData.getSuggestedCommentSort(); - String sortTypeTemp = ViewPostDetailActivity.this.sortType.toLowerCase().substring(0, 1).toUpperCase() + ViewPostDetailActivity.this.sortType.substring(1); - mToolbar.setTitle(sortTypeTemp); - fetchComments(changeRefreshState, checkSortState, subredditData.getSuggestedCommentSort()); - } - } - - @Override - public void onFetchSubredditDataFail(boolean isQuarantined) { - mRespectSubredditRecommendedSortType = false; - ViewPostDetailActivity.this.sortType = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.BEST.value.toUpperCase()); - if (ViewPostDetailActivity.this.sortType != null) { - mToolbar.setTitle(new SortType(SortType.Type.valueOf(ViewPostDetailActivity.this.sortType)).getType().fullName); - ViewPostDetailActivity.this.sortType = ViewPostDetailActivity.this.sortType.toLowerCase(); - } - } - }); - } else { - fetchComments(changeRefreshState, checkSortState, sortType); - } - } - - private void fetchComments(boolean changeRefreshState, boolean checkSortState, String sortType) { - isFetchingComments = true; - mAdapter.setSingleComment(mSingleCommentId, isSingleCommentThreadMode); - mAdapter.initiallyLoading(); - String commentId = null; - if (isSingleCommentThreadMode) { - commentId = mSingleCommentId; - } - - Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit; - FetchComment.fetchComments(retrofit, mAccessToken, mPost.getId(), commentId, sortType, mExpandChildren, - mLocale, new FetchComment.FetchCommentListener() { - @Override - public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, - String parentId, ArrayList<String> children) { - if (checkSortState && isSortingComments) { - if (changeRefreshState) { - isRefreshing = false; - } - - return; - } - - ViewPostDetailActivity.this.children = children; - - comments = expandedComments; - hasMoreChildren = children.size() != 0; - mAdapter.addComments(expandedComments, hasMoreChildren); - - if (children.size() > 0) { - mRecyclerView.clearOnScrollListeners(); - mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { - @Override - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - if (!mIsSmoothScrolling && !mLockFab) { - if (!recyclerView.canScrollVertically(1)) { - fab.hide(); - } else { - if (dy > 0) { - if (mSwipeUpToHideFab) { - fab.show(); - } else { - fab.hide(); - } - } else { - if (mSwipeUpToHideFab) { - fab.hide(); - } else { - fab.show(); - } - } - } - } - - if (!isLoadingMoreChildren && loadMoreChildrenSuccess) { - int visibleItemCount = mLinearLayoutManager.getChildCount(); - int totalItemCount = mLinearLayoutManager.getItemCount(); - int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); - - if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { - fetchMoreComments(); - } - } - } - - @Override - public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { - if (newState == RecyclerView.SCROLL_STATE_IDLE) { - mIsSmoothScrolling = false; - } - } - }); - } - if (changeRefreshState) { - isRefreshing = false; - } - - isFetchingComments = false; - } - - @Override - public void onFetchCommentFailed() { - isFetchingComments = false; - if (checkSortState && isSortingComments) { - if (changeRefreshState) { - isRefreshing = false; - } - - return; - } - - mAdapter.initiallyLoadCommentsFailed(); - if (changeRefreshState) { - isRefreshing = false; - } - } - }); - } - - private void fetchCommentsRespectRecommendedSort(boolean changeRefreshState) { - fetchCommentsRespectRecommendedSort(changeRefreshState, true, sortType); - } - - void fetchMoreComments() { - if (isFetchingComments || isLoadingMoreChildren || !loadMoreChildrenSuccess) { - return; } - - isLoadingMoreChildren = true; - - Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit; - FetchComment.fetchMoreComment(retrofit, mAccessToken, children, mChildrenStartingIndex, - 0, mExpandChildren, mLocale, new FetchComment.FetchMoreCommentListener() { - @Override - public void onFetchMoreCommentSuccess(ArrayList<Comment> expandedComments, int childrenStartingIndex) { - hasMoreChildren = childrenStartingIndex < children.size(); - mAdapter.addComments(expandedComments, hasMoreChildren); - mChildrenStartingIndex = childrenStartingIndex; - isLoadingMoreChildren = false; - loadMoreChildrenSuccess = true; - } - - @Override - public void onFetchMoreCommentFailed() { - isLoadingMoreChildren = false; - loadMoreChildrenSuccess = false; - mAdapter.loadMoreCommentsFailed(); - } - }); } - private void refresh(boolean fetchPost, boolean fetchComments) { - if (mAdapter != null && !isRefreshing) { - isRefreshing = true; - mChildrenStartingIndex = 0; - - mFetchPostInfoLinearLayout.setVisibility(View.GONE); - mGlide.clear(mFetchPostInfoImageView); - - if (fetchComments) { - fetchCommentsRespectRecommendedSort(!fetchPost); - } - - if (fetchPost) { - Retrofit retrofit; - if (mAccessToken == null) { - retrofit = mRetrofit; - } else { - retrofit = mOauthRetrofit; - } - FetchPost.fetchPost(retrofit, mPost.getId(), mAccessToken, mLocale, - new FetchPost.FetchPostListener() { - @Override - public void fetchPostSuccess(Post post) { - mPost = post; - mAdapter.updatePost(mPost); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - isRefreshing = false; - setupMenu(); - mSwipeRefreshLayout.setRefreshing(false); - } - - @Override - public void fetchPostFailed() { - showMessage(R.string.refresh_post_failed); - isRefreshing = false; - } - }); + private void awardGiven(String awardsHTML, int awardCount, int position) { + if (sectionsPagerAdapter != null) { + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.awardGiven(awardsHTML, awardCount, position); } } } - private void showErrorView(String subredditId) { - mSwipeRefreshLayout.setRefreshing(false); - mFetchPostInfoLinearLayout.setVisibility(View.VISIBLE); - mFetchPostInfoLinearLayout.setOnClickListener(view -> fetchPostAndCommentsById(subredditId)); - mFetchPostInfoTextView.setText(R.string.load_post_error); - mGlide.load(R.drawable.error_image).into(mFetchPostInfoImageView); - } - - private void showMessage(int resId) { - if (showToast) { - Toast.makeText(ViewPostDetailActivity.this, resId, Toast.LENGTH_SHORT).show(); - } else { - Snackbar.make(mCoordinatorLayout, resId, Snackbar.LENGTH_SHORT).show(); - } - } - - private void markNSFW() { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw); - } - - Map<String, String> params = new HashMap<>(); - params.put(APIUtils.ID_KEY, mPost.getFullName()); - mOauthRetrofit.create(RedditAPI.class).markNSFW(APIUtils.getOAuthHeader(mAccessToken), params) - .enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw); - } - - refresh(true, false); - showMessage(R.string.mark_nsfw_success); - } else { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw); - } - - showMessage(R.string.mark_nsfw_failed); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw); - } - - showMessage(R.string.mark_nsfw_failed); - } - }); - } - - private void unmarkNSFW() { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw); - } - - Map<String, String> params = new HashMap<>(); - params.put(APIUtils.ID_KEY, mPost.getFullName()); - mOauthRetrofit.create(RedditAPI.class).unmarkNSFW(APIUtils.getOAuthHeader(mAccessToken), params) - .enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw); - } - - refresh(true, false); - showMessage(R.string.unmark_nsfw_success); - } else { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw); - } - - showMessage(R.string.unmark_nsfw_failed); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - if (mMenu != null) { - mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw); - } - - showMessage(R.string.unmark_nsfw_failed); - } - }); - } - - private void markSpoiler() { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler); - } - - Map<String, String> params = new HashMap<>(); - params.put(APIUtils.ID_KEY, mPost.getFullName()); - mOauthRetrofit.create(RedditAPI.class).markSpoiler(APIUtils.getOAuthHeader(mAccessToken), params) - .enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler); - } - - refresh(true, false); - showMessage(R.string.mark_spoiler_success); - } else { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler); - } - - showMessage(R.string.mark_spoiler_failed); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler); - } - - showMessage(R.string.mark_spoiler_failed); - } - }); - } - - private void unmarkSpoiler() { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler); - } - - Map<String, String> params = new HashMap<>(); - params.put(APIUtils.ID_KEY, mPost.getFullName()); - mOauthRetrofit.create(RedditAPI.class).unmarkSpoiler(APIUtils.getOAuthHeader(mAccessToken), params) - .enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler); - } - - refresh(true, false); - showMessage(R.string.unmark_spoiler_success); - } else { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler); - } - - showMessage(R.string.unmark_spoiler_failed); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - if (mMenu != null) { - mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler); - } - - showMessage(R.string.unmark_spoiler_failed); - } - }); - } - public void deleteComment(String fullName, int position) { - new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme) - .setTitle(R.string.delete_this_comment) - .setMessage(R.string.are_you_sure) - .setPositiveButton(R.string.delete, (dialogInterface, i) - -> DeleteThing.delete(mOauthRetrofit, fullName, mAccessToken, new DeleteThing.DeleteThingListener() { - @Override - public void deleteSuccess() { - Toast.makeText(ViewPostDetailActivity.this, R.string.delete_post_success, Toast.LENGTH_SHORT).show(); - mAdapter.deleteComment(position); - } - - @Override - public void deleteFailed() { - Toast.makeText(ViewPostDetailActivity.this, R.string.delete_post_failed, Toast.LENGTH_SHORT).show(); - } - })) - .setNegativeButton(R.string.cancel, null) - .show(); - } - - public void showRemovedComment(Comment comment, int position) { - Toast.makeText(ViewPostDetailActivity.this, R.string.fetching_removed_comment, Toast.LENGTH_SHORT).show(); - FetchRemovedComment.fetchRemovedComment( - pushshiftRetrofit, - comment, - new FetchRemovedComment.FetchRemovedCommentListener() { - @Override - public void fetchSuccess(Comment comment) { - mAdapter.editComment(comment.getAuthor(), comment.getCommentMarkdown(), position); - } - - @Override - public void fetchFailed() { - Toast.makeText(ViewPostDetailActivity.this, R.string.show_removed_comment_failed, Toast.LENGTH_SHORT).show(); - } - }); - } - - public void changeToNomalThreadMode() { - isSingleCommentThreadMode = false; - mSingleCommentId = null; - mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false); - refresh(false, true); - } - - public void scrollToNextParentComment() { - if (mLinearLayoutManager != null) { - int currentPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); - if (mAdapter != null) { - int nextParentPosition = mAdapter.getNextParentCommentPosition(currentPosition); - if (nextParentPosition < 0) { - return; - } - mSmoothScroller.setTargetPosition(nextParentPosition); - if (mLinearLayoutManager != null) { - mIsSmoothScrolling = true; - mLinearLayoutManager.startSmoothScroll(mSmoothScroller); - } + if (sectionsPagerAdapter != null) { + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.deleteComment(fullName, position); } } } - public void scrollToPreviousParentComment() { - if (mLinearLayoutManager != null) { - int currentPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); - if (mAdapter != null) { - int nextParentPosition = mAdapter.getPreviousParentCommentPosition(currentPosition); - if (nextParentPosition < 0) { - return; - } - mSmoothScroller.setTargetPosition(nextParentPosition); - if (mLinearLayoutManager != null) { - mIsSmoothScrolling = true; - mLinearLayoutManager.startSmoothScroll(mSmoothScroller); - } - } - } - } - - public void delayTransition() { - TransitionManager.beginDelayedTransition(mRecyclerView, new AutoTransition()); - } - - @Subscribe - public void onPostUpdateEvent(PostUpdateEventToDetailActivity event) { - if (mPost.getId().equals(event.post.getId())) { - mPost.setVoteType(event.post.getVoteType()); - mPost.setSaved(event.post.isSaved()); - if (mMenu != null) { - if (event.post.isSaved()) { - mMenu.findItem(R.id.action_save_view_post_detail_activity).setIcon(mSavedIcon); - } else { - mMenu.findItem(R.id.action_save_view_post_detail_activity).setIcon(mUnsavedIcon); - } + public void showRemovedComment(Comment comment, int position) { + if (sectionsPagerAdapter != null) { + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.showRemovedComment(comment, position); } - mAdapter.updatePost(mPost); - } - } - - @Subscribe - public void onChangeNSFWBlurEvent(ChangeNSFWBlurEvent event) { - mAdapter.setBlurNSFW(event.needBlurNSFW); - refreshAdapter(); - } - - @Subscribe - public void onChangeSpoilerBlurEvent(ChangeSpoilerBlurEvent event) { - mAdapter.setBlurSpoiler(event.needBlurSpoiler); - refreshAdapter(); - } - - private void refreshAdapter() { - int previousPosition = -1; - if (mLinearLayoutManager != null) { - previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); - } - - RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager(); - mRecyclerView.setAdapter(null); - mRecyclerView.setLayoutManager(null); - mRecyclerView.setAdapter(mAdapter); - mRecyclerView.setLayoutManager(layoutManager); - - if (previousPosition > 0) { - mRecyclerView.scrollToPosition(previousPosition); } } @@ -1426,271 +296,11 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS } } - @Subscribe - public void onChangeNetworkStatusEvent(ChangeNetworkStatusEvent changeNetworkStatusEvent) { - if (mAdapter != null) { - String autoplay = mSharedPreferences.getString(SharedPreferencesUtils.VIDEO_AUTOPLAY, SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_NEVER); - String dataSavingMode = mSharedPreferences.getString(SharedPreferencesUtils.DATA_SAVING_MODE, SharedPreferencesUtils.DATA_SAVING_MODE_OFF); - boolean stateChanged = false; - if (autoplay.equals(SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_ON_WIFI)) { - mAdapter.setAutoplay(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_WIFI); - stateChanged = true; - } - if (dataSavingMode.equals(SharedPreferencesUtils.DATA_SAVING_MODE_ONLY_ON_CELLULAR_DATA)) { - mAdapter.setDataSavingMode(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_CELLULAR); - stateChanged = true; - } - - if (stateChanged) { - refreshAdapter(); - } - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.view_post_detail_activity, menu); - applyMenuItemTheme(menu); - mMenu = menu; - if (mPost != null) { - setupMenu(); - } - return true; - } - - public void showRemovedPost() { - Toast.makeText(ViewPostDetailActivity.this, R.string.fetching_removed_post, Toast.LENGTH_SHORT).show(); - FetchRemovedPost.fetchRemovedPost( - pushshiftRetrofit, - mPost, - new FetchRemovedPost.FetchRemovedPostListener() { - @Override - public void fetchSuccess(Post post) { - mPost = post; - mAdapter.updatePost(post); - } - - @Override - public void fetchFailed() { - Toast.makeText(ViewPostDetailActivity.this, R.string.show_removed_post_failed, Toast.LENGTH_SHORT).show(); - } - }); - } - @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.action_refresh_view_post_detail_activity: - refresh(true, true); - return true; - case R.id.action_comment_view_post_detail_activity: - if (mPost != null) { - if (mPost.isArchived()) { - showMessage(R.string.archived_post_reply_unavailable); - return true; - } - - if (mPost.isLocked()) { - showMessage(R.string.locked_post_comment_unavailable); - return true; - } - - if (mAccessToken == null) { - showMessage(R.string.login_first); - return true; - } - - Intent intent = new Intent(this, CommentActivity.class); - intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TEXT_MARKDOWN_KEY, mPost.getTitle()); - intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_BODY_MARKDOWN_KEY, mPost.getSelfText()); - intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_BODY_KEY, mPost.getSelfTextPlain()); - intent.putExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY, mPost.getFullName()); - intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, 0); - intent.putExtra(CommentActivity.EXTRA_IS_REPLYING_KEY, false); - startActivityForResult(intent, WRITE_COMMENT_REQUEST_CODE); - } - return true; - case R.id.action_save_view_post_detail_activity: - if (mPost != null && mAccessToken != null) { - if (mPost.isSaved()) { - item.setIcon(mUnsavedIcon); - SaveThing.unsaveThing(mOauthRetrofit, mAccessToken, mPost.getFullName(), - new SaveThing.SaveThingListener() { - @Override - public void success() { - mPost.setSaved(false); - item.setIcon(mUnsavedIcon); - showMessage(R.string.post_unsaved_success); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - - @Override - public void failed() { - mPost.setSaved(true); - item.setIcon(mSavedIcon); - showMessage(R.string.post_unsaved_failed); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - }); - } else { - item.setIcon(mSavedIcon); - SaveThing.saveThing(mOauthRetrofit, mAccessToken, mPost.getFullName(), - new SaveThing.SaveThingListener() { - @Override - public void success() { - mPost.setSaved(true); - item.setIcon(mSavedIcon); - showMessage(R.string.post_saved_success); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - - @Override - public void failed() { - mPost.setSaved(false); - item.setIcon(mUnsavedIcon); - showMessage(R.string.post_saved_failed); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - }); - } - } - return true; - case R.id.action_sort_view_post_detail_activity: - if (mPost != null) { - mPostCommentSortTypeBottomSheetFragment.show(getSupportFragmentManager(), mPostCommentSortTypeBottomSheetFragment.getTag()); - } - return true; - case R.id.action_view_crosspost_parent_view_post_detail_activity: - Intent crosspostIntent = new Intent(this, ViewPostDetailActivity.class); - crosspostIntent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, mPost.getCrosspostParentId()); - startActivity(crosspostIntent); - return true; - case R.id.action_hide_view_post_detail_activity: - if (mPost != null && mAccessToken != null) { - if (mPost.isHidden()) { - item.setTitle(R.string.action_hide_post); - - HidePost.unhidePost(mOauthRetrofit, mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() { - @Override - public void success() { - mPost.setHidden(false); - item.setTitle(R.string.action_hide_post); - showMessage(R.string.post_unhide_success); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - - @Override - public void failed() { - mPost.setHidden(true); - item.setTitle(R.string.action_unhide_post); - showMessage(R.string.post_unhide_failed); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - }); - } else { - item.setTitle(R.string.action_unhide_post); - - HidePost.hidePost(mOauthRetrofit, mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() { - @Override - public void success() { - mPost.setHidden(true); - item.setTitle(R.string.action_unhide_post); - showMessage(R.string.post_hide_success); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - - @Override - public void failed() { - mPost.setHidden(false); - item.setTitle(R.string.action_hide_post); - showMessage(R.string.post_hide_failed); - EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); - } - }); - } - } - return true; - case R.id.action_edit_view_post_detail_activity: - Intent editPostIntent = new Intent(this, EditPostActivity.class); - editPostIntent.putExtra(EditPostActivity.EXTRA_FULLNAME, mPost.getFullName()); - editPostIntent.putExtra(EditPostActivity.EXTRA_TITLE, mPost.getTitle()); - editPostIntent.putExtra(EditPostActivity.EXTRA_CONTENT, mPost.getSelfText()); - startActivityForResult(editPostIntent, EDIT_POST_REQUEST_CODE); - return true; - case R.id.action_delete_view_post_detail_activity: - new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme) - .setTitle(R.string.delete_this_post) - .setMessage(R.string.are_you_sure) - .setPositiveButton(R.string.delete, (dialogInterface, i) - -> DeleteThing.delete(mOauthRetrofit, mPost.getFullName(), mAccessToken, new DeleteThing.DeleteThingListener() { - @Override - public void deleteSuccess() { - Toast.makeText(ViewPostDetailActivity.this, R.string.delete_post_success, Toast.LENGTH_SHORT).show(); - finish(); - } - - @Override - public void deleteFailed() { - showMessage(R.string.delete_post_failed); - } - })) - .setNegativeButton(R.string.cancel, null) - .show(); - return true; - case R.id.action_nsfw_view_post_detail_activity: - if (mPost.isNSFW()) { - unmarkNSFW(); - } else { - markNSFW(); - } - return true; - case R.id.action_spoiler_view_post_detail_activity: - if (mPost.isSpoiler()) { - unmarkSpoiler(); - } else { - markSpoiler(); - } - return true; - case R.id.action_edit_flair_view_post_detail_activity: - FlairBottomSheetFragment flairBottomSheetFragment = new FlairBottomSheetFragment(); - Bundle bundle = new Bundle(); - bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken); - bundle.putString(FlairBottomSheetFragment.EXTRA_SUBREDDIT_NAME, mPost.getSubredditName()); - flairBottomSheetFragment.setArguments(bundle); - flairBottomSheetFragment.show(getSupportFragmentManager(), flairBottomSheetFragment.getTag()); - return true; - case R.id.action_give_award_view_post_detail_activity: - if (mAccessToken == null) { - Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show(); - return true; - } - - Intent giveAwardIntent = new Intent(this, GiveAwardActivity.class); - giveAwardIntent.putExtra(GiveAwardActivity.EXTRA_THING_FULLNAME, mPost.getFullName()); - giveAwardIntent.putExtra(GiveAwardActivity.EXTRA_ITEM_POSITION, 0); - startActivityForResult(giveAwardIntent, GIVE_AWARD_REQUEST_CODE); - return true; - case R.id.action_report_view_post_detail_activity: - if (mAccessToken == null) { - Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show(); - return true; - } - Intent intent = new Intent(this, ReportActivity.class); - intent.putExtra(ReportActivity.EXTRA_SUBREDDIT_NAME, mPost.getSubredditName()); - intent.putExtra(ReportActivity.EXTRA_THING_FULLNAME, mPost.getFullName()); - startActivity(intent); - return true; - case R.id.action_see_removed_view_post_detail_activity: - showRemovedPost(); - return true; - case R.id.action_crosspost_view_post_detail_activity: - Intent submitCrosspostIntent = new Intent(this, SubmitCrosspostActivity.class); - submitCrosspostIntent.putExtra(SubmitCrosspostActivity.EXTRA_POST, mPost); - startActivity(submitCrosspostIntent); - return true; - case android.R.id.home: - onBackPressed(); - return true; + if (item.getItemId() == android.R.id.home) { + onBackPressed(); + return true; } return false; } @@ -1698,42 +308,19 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); - if (requestCode == WRITE_COMMENT_REQUEST_CODE) { - if (data != null && resultCode == RESULT_OK) { - if (data.hasExtra(RETURN_EXTRA_COMMENT_DATA_KEY)) { - Comment comment = data.getParcelableExtra(RETURN_EXTRA_COMMENT_DATA_KEY); - if (comment != null && comment.getDepth() == 0) { - mAdapter.addComment(comment); - } else { - String parentFullname = data.getStringExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY); - int parentPosition = data.getIntExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, -1); - if (parentFullname != null && parentPosition >= 0) { - mAdapter.addChildComment(comment, parentFullname, parentPosition); - } - } - } else { - Toast.makeText(this, R.string.send_comment_failed, Toast.LENGTH_SHORT).show(); - } - } - } else if (requestCode == EDIT_POST_REQUEST_CODE) { - if (resultCode == RESULT_OK) { - refresh(true, false); - } - } else if (requestCode == EDIT_COMMENT_REQUEST_CODE) { - if (data != null && resultCode == RESULT_OK) { - mAdapter.editComment(null, + if (requestCode == EDIT_COMMENT_REQUEST_CODE) { + if (data != null && resultCode == Activity.RESULT_OK) { + editComment(null, data.getStringExtra(EditCommentActivity.EXTRA_EDITED_COMMENT_CONTENT), data.getExtras().getInt(EditCommentActivity.EXTRA_EDITED_COMMENT_POSITION)); } } else if (requestCode == GIVE_AWARD_REQUEST_CODE) { - if (data != null && resultCode == RESULT_OK) { + if (data != null && resultCode == Activity.RESULT_OK) { Toast.makeText(this, R.string.give_award_success, Toast.LENGTH_SHORT).show(); int position = data.getIntExtra(GiveAwardActivity.EXTRA_RETURN_ITEM_POSITION, 0); String newAwardsHTML = data.getStringExtra(GiveAwardActivity.EXTRA_RETURN_NEW_AWARDS); int newAwardsCount = data.getIntExtra(GiveAwardActivity.EXTRA_RETURN_NEW_AWARDS_COUNT, 0); - if (mAdapter != null) { - mAdapter.giveAward(newAwardsHTML, newAwardsCount, position); - } + awardGiven(newAwardsHTML, newAwardsCount, position); } } } @@ -1741,7 +328,6 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); - comments = mAdapter == null ? null : mAdapter.getVisibleComments(); Bridge.saveInstanceState(this, outState); } @@ -1765,13 +351,16 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mVolumeKeysNavigateComments) { - switch (keyCode) { - case KeyEvent.KEYCODE_VOLUME_UP: - scrollToPreviousParentComment(); - return true; - case KeyEvent.KEYCODE_VOLUME_DOWN: - scrollToNextParentComment(); - return true; + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + switch (keyCode) { + case KeyEvent.KEYCODE_VOLUME_UP: + fragment.scrollToPreviousParentComment(); + return true; + case KeyEvent.KEYCODE_VOLUME_DOWN: + fragment.scrollToNextParentComment(); + return true; + } } } return super.onKeyDown(keyCode, event); @@ -1779,46 +368,19 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS @Override public void flairSelected(Flair flair) { - Map<String, String> params = new HashMap<>(); - params.put(APIUtils.API_TYPE_KEY, APIUtils.API_TYPE_JSON); - params.put(APIUtils.FLAIR_TEMPLATE_ID_KEY, flair.getId()); - params.put(APIUtils.LINK_KEY, mPost.getFullName()); - params.put(APIUtils.TEXT_KEY, flair.getText()); - - mOauthRetrofit.create(RedditAPI.class).selectFlair(mPost.getSubredditNamePrefixed(), - APIUtils.getOAuthHeader(mAccessToken), params).enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - refresh(true, false); - showMessage(R.string.update_flair_success); - } else { - showMessage(R.string.update_flair_failed); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - showMessage(R.string.update_flair_failed); - } - }); + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.changeFlair(flair); + } } @Override public void sortTypeSelected(SortType sortType) { - mFetchPostInfoLinearLayout.setVisibility(View.GONE); - mGlide.clear(mFetchPostInfoImageView); - mChildrenStartingIndex = 0; - if (children != null) { - children.clear(); - } - this.sortType = sortType.getType().value; - if (!mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false)) { - mSortTypeSharedPreferences.edit().putString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, sortType.getType().name()).apply(); + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.changeSortType(sortType); + mToolbar.setTitle(sortType.getType().fullName); } - fetchCommentsRespectRecommendedSort(false, false, sortType.getType().value); - - mToolbar.setTitle(sortType.getType().fullName); } public void lockSwipeRightToGoBack() { @@ -1835,8 +397,51 @@ public class ViewPostDetailActivity extends BaseActivity implements FlairBottomS @Override public void onLongPress() { - if (mLinearLayoutManager != null) { - mLinearLayoutManager.scrollToPositionWithOffset(0, 0); + ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment(); + if (fragment != null) { + fragment.goToTop(); + } + } + + private class SectionsPagerAdapter extends FragmentStateAdapter { + + public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) { + super(fragmentActivity); + } + + @NonNull + @Override + public Fragment createFragment(int position) { + ViewPostDetailFragment fragment = new ViewPostDetailFragment(); + Bundle bundle = new Bundle(); + if (posts != null) { + bundle.putParcelable(ViewPostDetailFragment.EXTRA_POST_DATA, posts.get(position)); + } else { + if (post == null) { + bundle.putString(ViewPostDetailFragment.EXTRA_POST_ID, getIntent().getStringExtra(EXTRA_POST_ID)); + } else { + bundle.putParcelable(ViewPostDetailFragment.EXTRA_POST_DATA, post); + } + } + fragment.setArguments(bundle); + return fragment; + } + + @Override + public int getItemCount() { + return posts == null ? 1 : posts.size(); + } + + @Nullable + ViewPostDetailFragment getCurrentFragment() { + if (viewPager2 == null || fragmentManager == null) { + return null; + } + Fragment fragment = fragmentManager.findFragmentByTag("f" + viewPager2.getCurrentItem()); + if (fragment instanceof PostFragment) { + return (ViewPostDetailFragment) fragment; + } + return null; } } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java index 6867125b..b7f914b9 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java @@ -4,6 +4,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.MenuItem; import android.view.View; import android.widget.EditText; @@ -36,7 +37,7 @@ import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.adapters.PrivateMessagesDetailRecyclerViewAdapter; -import ml.docilealligator.infinityforreddit.asynctasks.LoadUserDataAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadUserData; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.RepliedToPrivateMessageEvent; import ml.docilealligator.infinityforreddit.message.Message; @@ -93,7 +94,7 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit private String mAccountName; private String mUserAvatar; private ArrayList<ProvideUserAvatarCallback> mProvideUserAvatarCallbacks; - private LoadUserDataAsyncTask mLoadUserDataAsyncTask; + private boolean isLoadingUserAvatar = false; private boolean isSendingMessage = false; private int mSecondaryTextColor; private int mSendMessageIconColor; @@ -234,15 +235,16 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit public void fetchUserAvatar(String username, ProvideUserAvatarCallback provideUserAvatarCallback) { if (mUserAvatar == null) { mProvideUserAvatarCallbacks.add(provideUserAvatarCallback); - if (mLoadUserDataAsyncTask == null) { - mLoadUserDataAsyncTask = new LoadUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), username, mRetrofit, iconImageUrl -> { - mUserAvatar = iconImageUrl; + if (!isLoadingUserAvatar) { + LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, + username, mRetrofit, iconImageUrl -> { + isLoadingUserAvatar = false; + mUserAvatar = iconImageUrl == null ? "" : iconImageUrl; for (ProvideUserAvatarCallback provideUserAvatarCallbackInArrayList : mProvideUserAvatarCallbacks) { provideUserAvatarCallbackInArrayList.fetchAvatarSuccess(iconImageUrl); } mProvideUserAvatarCallbacks.clear(); }); - mLoadUserDataAsyncTask.execute(); } } else { provideUserAvatarCallback.fetchAvatarSuccess(mUserAvatar); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java index 0eaa24c9..6bcccfa3 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java @@ -4,6 +4,7 @@ import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; +import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; @@ -20,6 +21,7 @@ import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; import java.util.ArrayList; +import java.util.concurrent.Executor; import javax.inject.Inject; import javax.inject.Named; @@ -56,6 +58,8 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA @Inject @Named("default") SharedPreferences sharedPreferences; + @Inject + Executor executor; @Override protected void onCreate(Bundle savedInstanceState) { @@ -152,7 +156,7 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA @Override public void setToHomeScreen(int viewPagerPosition) { if (gallery != null && viewPagerPosition >= 0 && viewPagerPosition < gallery.size()) { - WallpaperSetter.set(gallery.get(viewPagerPosition).url, WallpaperSetter.HOME_SCREEN, this, + WallpaperSetter.set(executor, new Handler(), gallery.get(viewPagerPosition).url, WallpaperSetter.HOME_SCREEN, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { @@ -170,7 +174,7 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA @Override public void setToLockScreen(int viewPagerPosition) { if (gallery != null && viewPagerPosition >= 0 && viewPagerPosition < gallery.size()) { - WallpaperSetter.set(gallery.get(viewPagerPosition).url, WallpaperSetter.LOCK_SCREEN, this, + WallpaperSetter.set(executor, new Handler(), gallery.get(viewPagerPosition).url, WallpaperSetter.LOCK_SCREEN, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { @@ -188,7 +192,7 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA @Override public void setToBoth(int viewPagerPosition) { if (gallery != null && viewPagerPosition >= 0 && viewPagerPosition < gallery.size()) { - WallpaperSetter.set(gallery.get(viewPagerPosition).url, WallpaperSetter.BOTH_SCREENS, this, + WallpaperSetter.set(executor, new Handler(), gallery.get(viewPagerPosition).url, WallpaperSetter.BOTH_SCREENS, this, new WallpaperSetter.SetWallpaperListener() { @Override public void success() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java index cd514c0f..e076a293 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java @@ -71,8 +71,8 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.SortType; import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback; import ml.docilealligator.infinityforreddit.asynctasks.AddSubredditOrUserToMultiReddit; -import ml.docilealligator.infinityforreddit.asynctasks.CheckIsSubscribedToSubredditAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.InsertSubredditDataAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.CheckIsSubscribedToSubreddit; +import ml.docilealligator.infinityforreddit.asynctasks.InsertSubredditData; import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment; import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostLayoutBottomSheetFragment; @@ -515,7 +515,8 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers; nOnlineSubscribersTextView.setText(getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers)); - new InsertSubredditDataAsyncTask(mRedditDataRoomDatabase, subredditData, () -> mFetchSubredditInfoSuccess = true).execute(); + InsertSubredditData.insertSubredditData(mExecutor, new Handler(), mRedditDataRoomDatabase, + subredditData, () -> mFetchSubredditInfoSuccess = true); } @Override @@ -862,8 +863,9 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp } }); - new CheckIsSubscribedToSubredditAsyncTask(mRedditDataRoomDatabase, subredditName, mAccountName, - new CheckIsSubscribedToSubredditAsyncTask.CheckIsSubscribedToSubredditListener() { + CheckIsSubscribedToSubreddit.checkIsSubscribedToSubreddit(mExecutor, new Handler(), + mRedditDataRoomDatabase, subredditName, mAccountName, + new CheckIsSubscribedToSubreddit.CheckIsSubscribedToSubredditListener() { @Override public void isSubscribed() { subscribeSubredditChip.setText(R.string.unsubscribe); @@ -877,7 +879,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp subscribeSubredditChip.setChipBackgroundColor(ColorStateList.valueOf(unsubscribedColor)); subscriptionReady = true; } - }).execute(); + }); sectionsPagerAdapter = new SectionsPagerAdapter(this); viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java index e3736f1a..c2227455 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java @@ -75,7 +75,7 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.SortType; import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback; import ml.docilealligator.infinityforreddit.asynctasks.AddSubredditOrUserToMultiReddit; -import ml.docilealligator.infinityforreddit.asynctasks.CheckIsFollowingUserAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.CheckIsFollowingUser; import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount; import ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment; import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostLayoutBottomSheetFragment; @@ -94,7 +94,6 @@ import ml.docilealligator.infinityforreddit.multireddit.MultiReddit; import ml.docilealligator.infinityforreddit.post.Post; import ml.docilealligator.infinityforreddit.post.PostDataSource; import ml.docilealligator.infinityforreddit.readpost.InsertReadPost; -import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserDao; import ml.docilealligator.infinityforreddit.user.BlockUser; import ml.docilealligator.infinityforreddit.user.FetchUserData; import ml.docilealligator.infinityforreddit.user.UserDao; @@ -198,7 +197,6 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele public UserViewModel userViewModel; private FragmentManager fragmentManager; private SectionsPagerAdapter sectionsPagerAdapter; - private SubscribedUserDao subscribedUserDao; private RequestManager glide; private Menu mMenu; private AppBarLayout.LayoutParams params; @@ -358,7 +356,6 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, false); lockBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_BOTTOM_APP_BAR, false); - subscribedUserDao = mRedditDataRoomDatabase.subscribedUserDao(); glide = Glide.with(this); Locale locale = getResources().getConfiguration().locale; @@ -412,7 +409,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele subscriptionReady = false; if (resources.getString(R.string.follow).contentEquals(subscribeUserChip.getText())) { UserFollowing.followUser(mOauthRetrofit, mRetrofit, mAccessToken, - username, mAccountName, subscribedUserDao, new UserFollowing.UserFollowingListener() { + username, mAccountName, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() { @Override public void onUserFollowingSuccess() { subscribeUserChip.setText(R.string.unfollow); @@ -429,7 +426,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele }); } else { UserFollowing.unfollowUser(mOauthRetrofit, mRetrofit, mAccessToken, - username, mAccountName, subscribedUserDao, new UserFollowing.UserFollowingListener() { + username, mAccountName, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() { @Override public void onUserFollowingSuccess() { subscribeUserChip.setText(R.string.follow); @@ -448,7 +445,8 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele } }); - new CheckIsFollowingUserAsyncTask(subscribedUserDao, username, mAccountName, new CheckIsFollowingUserAsyncTask.CheckIsFollowingUserListener() { + CheckIsFollowingUser.checkIsFollowingUser(mExecutor, new Handler(), mRedditDataRoomDatabase, + username, mAccountName, new CheckIsFollowingUser.CheckIsFollowingUserListener() { @Override public void isSubscribed() { subscribeUserChip.setText(R.string.unfollow); @@ -462,7 +460,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele subscribeUserChip.setChipBackgroundColor(ColorStateList.valueOf(unsubscribedColor)); subscriptionReady = true; } - }).execute(); + }); } else { subscribeUserChip.setVisibility(View.GONE); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java index 0722da59..11a9df06 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java @@ -11,6 +11,7 @@ import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; +import android.os.Handler; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; @@ -59,6 +60,7 @@ import org.commonmark.ext.gfm.tables.TableBlock; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.concurrent.Executor; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -100,8 +102,8 @@ import ml.docilealligator.infinityforreddit.activities.ViewRedditGalleryActivity import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivity; import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity; import ml.docilealligator.infinityforreddit.activities.ViewVideoActivity; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.LoadUserDataAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; +import ml.docilealligator.infinityforreddit.asynctasks.LoadUserData; import ml.docilealligator.infinityforreddit.bottomsheetfragments.CommentMoreBottomSheetFragment; import ml.docilealligator.infinityforreddit.bottomsheetfragments.CopyTextBottomSheetFragment; import ml.docilealligator.infinityforreddit.bottomsheetfragments.ShareLinkBottomSheetFragment; @@ -111,6 +113,7 @@ import ml.docilealligator.infinityforreddit.comment.FetchComment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.customviews.AspectRatioGifImageView; import ml.docilealligator.infinityforreddit.customviews.MarkwonLinearLayoutManager; +import ml.docilealligator.infinityforreddit.fragments.ViewPostDetailFragment; import ml.docilealligator.infinityforreddit.post.Post; import ml.docilealligator.infinityforreddit.post.PostDataSource; import ml.docilealligator.infinityforreddit.utils.APIUtils; @@ -141,6 +144,8 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy private static final int VIEW_TYPE_VIEW_ALL_COMMENTS = 17; private AppCompatActivity mActivity; + private ViewPostDetailFragment mFragment; + private Executor mExecutor; private Retrofit mRetrofit; private Retrofit mOauthRetrofit; private Retrofit mGfycatRetrofit; @@ -235,7 +240,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy private float mScale; private ExoCreator mExoCreator; - public CommentAndPostRecyclerViewAdapter(AppCompatActivity activity, CustomThemeWrapper customThemeWrapper, + public CommentAndPostRecyclerViewAdapter(AppCompatActivity activity, ViewPostDetailFragment fragment, Executor executor, CustomThemeWrapper customThemeWrapper, Retrofit retrofit, Retrofit oauthRetrofit, Retrofit gfycatRetrofit, Retrofit redgifsRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, RequestManager glide, @@ -246,6 +251,8 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy SharedPreferences nsfwAndSpoilerSharedPreferences, ExoCreator exoCreator, CommentRecyclerViewAdapterCallback commentRecyclerViewAdapterCallback) { mActivity = activity; + mFragment = fragment; + mExecutor = executor; mRetrofit = retrofit; mOauthRetrofit = oauthRetrofit; mGfycatRetrofit = gfycatRetrofit; @@ -731,7 +738,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy if (mPost.getSubredditNamePrefixed().startsWith("u/")) { if (mPost.getAuthorIconUrl() == null) { String authorName = mPost.getAuthor().equals("[deleted]") ? mPost.getSubredditNamePrefixed().substring(2) : mPost.getAuthor(); - new LoadUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), authorName, mOauthRetrofit, iconImageUrl -> { + LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName, mOauthRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -749,7 +756,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy mPost.setAuthorIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!mPost.getAuthorIconUrl().equals("")) { mGlide.load(mPost.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -763,7 +770,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy } } else { if (mPost.getSubredditIconUrl() == null) { - new LoadSubredditIconAsyncTask( + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, mPost.getSubredditNamePrefixed().substring(2), mRetrofit, iconImageUrl -> { if (iconImageUrl == null || iconImageUrl.equals("")) { @@ -779,7 +786,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy } mPost.setSubredditIconUrl(iconImageUrl); - }).execute(); + }); } else if (!mPost.getSubredditIconUrl().equals("")) { mGlide.load(mPost.getSubredditIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -3761,9 +3768,9 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy if (bottomConstraintLayout.getLayoutParams().height == 0) { bottomConstraintLayout.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT; topScoreTextView.setVisibility(View.GONE); - ((ViewPostDetailActivity) mActivity).delayTransition(); + mFragment.delayTransition(); } else { - ((ViewPostDetailActivity) mActivity).delayTransition(); + mFragment.delayTransition(); bottomConstraintLayout.getLayoutParams().height = 0; topScoreTextView.setVisibility(View.VISIBLE); } @@ -3940,7 +3947,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy if (mActivity != null && mActivity instanceof ViewPostDetailActivity) { mIsSingleCommentThreadMode = false; mSingleCommentId = null; - ((ViewPostDetailActivity) mActivity).changeToNomalThreadMode(); + mFragment.changeToNomalThreadMode(); } }); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FollowedUsersRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FollowedUsersRecyclerViewAdapter.java index 40107a03..a077569e 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FollowedUsersRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FollowedUsersRecyclerViewAdapter.java @@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.adapters; import android.content.Context; import android.content.Intent; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -17,16 +18,17 @@ import com.bumptech.glide.RequestManager; import com.bumptech.glide.request.RequestOptions; import java.util.List; +import java.util.concurrent.Executor; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import me.zhanghai.android.fastscroll.PopupTextProvider; -import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity; -import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.FavoriteThing; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity; +import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData; import pl.droidsonroids.gif.GifImageView; import retrofit2.Retrofit; @@ -40,6 +42,7 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc private List<SubscribedUserData> mSubscribedUserData; private List<SubscribedUserData> mFavoriteSubscribedUserData; private Context mContext; + private Executor mExecutor; private Retrofit mOauthRetrofit; private RedditDataRoomDatabase mRedditDataRoomDatabase; private String mAccessToken; @@ -47,11 +50,12 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc private int mPrimaryTextColor; private int mSecondaryTextColor; - public FollowedUsersRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, + public FollowedUsersRecyclerViewAdapter(Context context, Executor executor, Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, CustomThemeWrapper customThemeWrapper, String accessToken) { mContext = context; + mExecutor = executor; mOauthRetrofit = oauthRetrofit; mRedditDataRoomDatabase = redditDataRoomDatabase; mAccessToken = accessToken; @@ -215,7 +219,8 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc if(mFavoriteSubscribedUserData.get(position).isFavorite()) { favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp); mFavoriteSubscribedUserData.get(position).setFavorite(false); - FavoriteThing.unfavoriteUser(mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, + FavoriteThing.unfavoriteUser(mExecutor, new Handler(), mOauthRetrofit, + mRedditDataRoomDatabase, mAccessToken, mFavoriteSubscribedUserData.get(position), new FavoriteThing.FavoriteThingListener() { @Override @@ -240,7 +245,8 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc } else { favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp); mFavoriteSubscribedUserData.get(position).setFavorite(true); - FavoriteThing.favoriteUser(mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, + FavoriteThing.favoriteUser(mExecutor, new Handler(), mOauthRetrofit, + mRedditDataRoomDatabase, mAccessToken, mFavoriteSubscribedUserData.get(position), new FavoriteThing.FavoriteThingListener() { @Override @@ -301,7 +307,8 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc if(mSubscribedUserData.get(position).isFavorite()) { favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp); mSubscribedUserData.get(position).setFavorite(false); - FavoriteThing.unfavoriteUser(mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, + FavoriteThing.unfavoriteUser(mExecutor, new Handler(), mOauthRetrofit, + mRedditDataRoomDatabase, mAccessToken, mSubscribedUserData.get(position), new FavoriteThing.FavoriteThingListener() { @Override @@ -326,7 +333,8 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc } else { favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp); mSubscribedUserData.get(position).setFavorite(true); - FavoriteThing.favoriteUser(mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, + FavoriteThing.favoriteUser(mExecutor, new Handler(), mOauthRetrofit, + mRedditDataRoomDatabase, mAccessToken, mSubscribedUserData.get(position), new FavoriteThing.FavoriteThingListener() { @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MultiRedditListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MultiRedditListingRecyclerViewAdapter.java index 5d2d3ef1..580e7fec 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MultiRedditListingRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MultiRedditListingRecyclerViewAdapter.java @@ -1,5 +1,6 @@ package ml.docilealligator.infinityforreddit.adapters; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -16,6 +17,7 @@ import com.bumptech.glide.RequestManager; import com.bumptech.glide.request.RequestOptions; import java.util.List; +import java.util.concurrent.Executor; import butterknife.BindView; import butterknife.ButterKnife; @@ -37,6 +39,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter< private static final int VIEW_TYPE_MULTI_REDDIT = 3; private AppCompatActivity mActivity; + private Executor mExecutor; private Retrofit mOauthRetrofit; private RedditDataRoomDatabase mRedditDataRoomDatabase; private RequestManager mGlide; @@ -53,11 +56,12 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter< void onLongClick(MultiReddit multiReddit); } - public MultiRedditListingRecyclerViewAdapter(AppCompatActivity activity, Retrofit oauthRetrofit, + public MultiRedditListingRecyclerViewAdapter(AppCompatActivity activity, Executor executor, Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, CustomThemeWrapper customThemeWrapper, String accessToken, OnItemClickListener onItemClickListener) { mActivity = activity; + mExecutor = executor; mGlide = Glide.with(activity); mOauthRetrofit = oauthRetrofit; mRedditDataRoomDatabase = redditDataRoomDatabase; @@ -125,7 +129,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter< if(multiReddit.isFavorite()) { ((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp); multiReddit.setFavorite(false); - FavoriteMultiReddit.favoriteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, + FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, false, multiReddit, new FavoriteMultiReddit.FavoriteMultiRedditListener() { @Override @@ -151,7 +155,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter< } else { ((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp); multiReddit.setFavorite(true); - FavoriteMultiReddit.favoriteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, + FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, true, multiReddit, new FavoriteMultiReddit.FavoriteMultiRedditListener() { @Override @@ -211,7 +215,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter< if(multiReddit.isFavorite()) { ((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp); multiReddit.setFavorite(false); - FavoriteMultiReddit.favoriteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, + FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, false, multiReddit, new FavoriteMultiReddit.FavoriteMultiRedditListener() { @Override @@ -237,7 +241,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter< } else { ((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp); multiReddit.setFavorite(true); - FavoriteMultiReddit.favoriteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, + FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken, true, multiReddit, new FavoriteMultiReddit.FavoriteMultiRedditListener() { @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java index e50aaf1b..60043539 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java @@ -10,6 +10,7 @@ import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -56,6 +57,7 @@ import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.concurrent.Executor; import butterknife.BindView; import butterknife.ButterKnife; @@ -84,12 +86,13 @@ import ml.docilealligator.infinityforreddit.activities.ViewRedditGalleryActivity import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivity; import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity; import ml.docilealligator.infinityforreddit.activities.ViewVideoActivity; -import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIconAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.LoadUserDataAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon; +import ml.docilealligator.infinityforreddit.asynctasks.LoadUserData; import ml.docilealligator.infinityforreddit.bottomsheetfragments.ShareLinkBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.customviews.AspectRatioGifImageView; import ml.docilealligator.infinityforreddit.events.PostUpdateEventToDetailActivity; +import ml.docilealligator.infinityforreddit.fragments.PostFragment; import ml.docilealligator.infinityforreddit.post.Post; import ml.docilealligator.infinityforreddit.post.PostDataSource; import ml.docilealligator.infinityforreddit.user.UserDao; @@ -126,6 +129,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView } }; private AppCompatActivity mActivity; + private PostFragment mFragment; + private Executor mExecutor; private Retrofit mOauthRetrofit; private Retrofit mRetrofit; private Retrofit mGfycatRetrofit; @@ -204,7 +209,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView private ExoCreator mExoCreator; private Callback mCallback; - public PostRecyclerViewAdapter(AppCompatActivity activity, Retrofit oauthRetrofit, Retrofit retrofit, + public PostRecyclerViewAdapter(AppCompatActivity activity, PostFragment fragment, Executor executor, Retrofit oauthRetrofit, Retrofit retrofit, Retrofit gfycatRetrofit, Retrofit redgifsRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, CustomThemeWrapper customThemeWrapper, Locale locale, int imageViewWidth, @@ -215,6 +220,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView super(DIFF_CALLBACK); if (activity != null) { mActivity = activity; + mFragment = fragment; + mExecutor = executor; mOauthRetrofit = oauthRetrofit; mRetrofit = retrofit; mGfycatRetrofit = gfycatRetrofit; @@ -432,7 +439,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView if (mDisplaySubredditName) { if (authorPrefixed.equals(subredditNamePrefixed)) { if (post.getAuthorIconUrl() == null) { - new LoadUserDataAsyncTask(mUserDao, post.getAuthor(), mRetrofit, iconImageUrl -> { + LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, post.getAuthor(), + mRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -450,7 +458,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView post.setAuthorIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!post.getAuthorIconUrl().equals("")) { mGlide.load(post.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -464,7 +472,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView } } else { if (post.getSubredditIconUrl() == null) { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, + subredditName, mRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { @@ -483,7 +492,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView post.setSubredditIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!post.getSubredditIconUrl().equals("")) { mGlide.load(post.getSubredditIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -499,7 +508,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView } else { if (post.getAuthorIconUrl() == null) { String authorName = post.getAuthor().equals("[deleted]") ? post.getSubredditNamePrefixed().substring(2) : post.getAuthor(); - new LoadUserDataAsyncTask(mUserDao, authorName, mRetrofit, iconImageUrl -> { + LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName, mRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -517,7 +526,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView post.setAuthorIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!post.getAuthorIconUrl().equals("")) { mGlide.load(post.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -761,7 +770,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView if (mDisplaySubredditName) { if (authorPrefixed.equals(subredditNamePrefixed)) { if (post.getAuthorIconUrl() == null) { - new LoadUserDataAsyncTask(mUserDao, post.getAuthor(), mRetrofit, iconImageUrl -> { + LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, post.getAuthor(), mRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -779,7 +788,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView post.setAuthorIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!post.getAuthorIconUrl().equals("")) { mGlide.load(post.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -793,7 +802,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView } } else { if (post.getSubredditIconUrl() == null) { - new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit, + LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, + subredditName, mRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { @@ -812,7 +822,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView post.setSubredditIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!post.getSubredditIconUrl().equals("")) { mGlide.load(post.getSubredditIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -831,7 +841,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView } else { if (post.getAuthorIconUrl() == null) { String authorName = post.getAuthor().equals("[deleted]") ? post.getSubredditNamePrefixed().substring(2) : post.getAuthor(); - new LoadUserDataAsyncTask(mUserDao, authorName, mRetrofit, iconImageUrl -> { + LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName, mRetrofit, iconImageUrl -> { if (mActivity != null && getItemCount() > 0) { if (iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -849,7 +859,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView post.setAuthorIconUrl(iconImageUrl); } } - }).execute(); + }); } else if (!post.getAuthorIconUrl().equals("")) { mGlide.load(post.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) @@ -1622,7 +1632,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView canStartActivity = false; Intent intent = new Intent(mActivity, ViewPostDetailActivity.class); - intent.putExtra(ViewPostDetailActivity.EXTRA_POST_DATA, post); + intent.putExtra(ViewPostDetailActivity.EXTRA_POST_LIST, mFragment.getPostList()); intent.putExtra(ViewPostDetailActivity.EXTRA_POST_LIST_POSITION, getAdapterPosition()); mActivity.startActivity(intent); } @@ -2638,7 +2648,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView canStartActivity = false; Intent intent = new Intent(mActivity, ViewPostDetailActivity.class); - intent.putExtra(ViewPostDetailActivity.EXTRA_POST_DATA, post); + intent.putExtra(ViewPostDetailActivity.EXTRA_POST_LIST, mFragment.getPostList()); intent.putExtra(ViewPostDetailActivity.EXTRA_POST_LIST_POSITION, getAdapterPosition()); mActivity.startActivity(intent); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java index cec8041a..1d34c29d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java @@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.adapters; import android.content.Context; import android.content.res.ColorStateList; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -22,10 +23,12 @@ import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.bumptech.glide.request.RequestOptions; +import java.util.concurrent.Executor; + import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; -import ml.docilealligator.infinityforreddit.asynctasks.CheckIsSubscribedToSubredditAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.CheckIsSubscribedToSubreddit; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.NetworkState; import ml.docilealligator.infinityforreddit.R; @@ -52,6 +55,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred }; private RequestManager glide; private Context context; + private Executor executor; private Retrofit oauthRetrofit; private Retrofit retrofit; private String accessToken; @@ -67,13 +71,14 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred private NetworkState networkState; private Callback callback; - public SubredditListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit, + public SubredditListingRecyclerViewAdapter(Context context, Executor executor, Retrofit oauthRetrofit, Retrofit retrofit, CustomThemeWrapper customThemeWrapper, String accessToken, String accountName, RedditDataRoomDatabase redditDataRoomDatabase, Callback callback) { super(DIFF_CALLBACK); this.context = context; + this.executor = executor; this.oauthRetrofit = oauthRetrofit; this.retrofit = retrofit; this.accessToken = accessToken; @@ -125,8 +130,9 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred ((DataViewHolder) holder).subredditNameTextView.setText(subredditData.getName()); - new CheckIsSubscribedToSubredditAsyncTask(redditDataRoomDatabase, subredditData.getName(), accountName, - new CheckIsSubscribedToSubredditAsyncTask.CheckIsSubscribedToSubredditListener() { + CheckIsSubscribedToSubreddit.checkIsSubscribedToSubreddit(executor, new Handler(), + redditDataRoomDatabase, subredditData.getName(), accountName, + new CheckIsSubscribedToSubreddit.CheckIsSubscribedToSubredditListener() { @Override public void isSubscribed() { ((DataViewHolder) holder).subscribeButton.setVisibility(View.GONE); @@ -152,7 +158,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred }); }); } - }).execute(); + }); } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubscribedSubredditsRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubscribedSubredditsRecyclerViewAdapter.java index 9ab3659d..3ca11603 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubscribedSubredditsRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubscribedSubredditsRecyclerViewAdapter.java @@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.adapters; import android.content.Context; import android.content.Intent; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -17,6 +18,7 @@ import com.bumptech.glide.RequestManager; import com.bumptech.glide.request.RequestOptions; import java.util.List; +import java.util.concurrent.Executor; import butterknife.BindView; import butterknife.ButterKnife; @@ -38,6 +40,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte private static final int VIEW_TYPE_SUBREDDIT = 3; private Context mContext; + private Executor mExecutor; private Retrofit mOauthRetrofit; private RedditDataRoomDatabase mRedditDataRoomDatabase; private List<SubscribedSubredditData> mSubscribedSubredditData; @@ -53,11 +56,12 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte private int primaryTextColor; private int secondaryTextColor; - public SubscribedSubredditsRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, + public SubscribedSubredditsRecyclerViewAdapter(Context context, Executor executor, Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, CustomThemeWrapper customThemeWrapper, String accessToken) { mContext = context; + mExecutor = executor; glide = Glide.with(context); mOauthRetrofit = oauthRetrofit; mRedditDataRoomDatabase = redditDataRoomDatabase; @@ -66,12 +70,12 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte secondaryTextColor = customThemeWrapper.getSecondaryTextColor(); } - public SubscribedSubredditsRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, + public SubscribedSubredditsRecyclerViewAdapter(Context context, Executor executor, Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, CustomThemeWrapper customThemeWrapper, String accessToken, boolean hasClearSelectionRow, ItemClickListener itemClickListener) { - this(context, oauthRetrofit, redditDataRoomDatabase, customThemeWrapper, accessToken); + this(context, executor, oauthRetrofit, redditDataRoomDatabase, customThemeWrapper, accessToken); this.hasClearSelectionRow = hasClearSelectionRow; this.itemClickListener = itemClickListener; } @@ -190,7 +194,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte if(mSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset).isFavorite()) { ((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp); mSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset).setFavorite(false); - FavoriteThing.unfavoriteSubreddit(mOauthRetrofit, mRedditDataRoomDatabase, accessToken, + FavoriteThing.unfavoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, accessToken, mSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset), new FavoriteThing.FavoriteThingListener() { @Override @@ -215,7 +219,8 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte } else { ((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp); mSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset).setFavorite(true); - FavoriteThing.favoriteSubreddit(mOauthRetrofit, mRedditDataRoomDatabase, accessToken, + FavoriteThing.favoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, + mRedditDataRoomDatabase, accessToken, mSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset), new FavoriteThing.FavoriteThingListener() { @Override @@ -288,7 +293,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte if(mFavoriteSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset).isFavorite()) { ((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp); mFavoriteSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset).setFavorite(false); - FavoriteThing.unfavoriteSubreddit(mOauthRetrofit, mRedditDataRoomDatabase, accessToken, + FavoriteThing.unfavoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, accessToken, mFavoriteSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset), new FavoriteThing.FavoriteThingListener() { @Override @@ -313,7 +318,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte } else { ((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp); mFavoriteSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset).setFavorite(true); - FavoriteThing.favoriteSubreddit(mOauthRetrofit, mRedditDataRoomDatabase, accessToken, + FavoriteThing.favoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, accessToken, mFavoriteSubscribedSubredditData.get(viewHolder.getAdapterPosition() - offset), new FavoriteThing.FavoriteThingListener() { @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UserListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UserListingRecyclerViewAdapter.java index 2fb83bae..f8c9f993 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UserListingRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UserListingRecyclerViewAdapter.java @@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.adapters; import android.content.Context; import android.content.res.ColorStateList; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -22,14 +23,16 @@ import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.bumptech.glide.request.RequestOptions; +import java.util.concurrent.Executor; + import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import ml.docilealligator.infinityforreddit.NetworkState; import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.asynctasks.CheckIsFollowingUserAsyncTask; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.asynctasks.CheckIsFollowingUser; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; -import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserDao; import ml.docilealligator.infinityforreddit.user.UserData; import ml.docilealligator.infinityforreddit.user.UserFollowing; import pl.droidsonroids.gif.GifImageView; @@ -52,11 +55,12 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R }; private RequestManager glide; private Context context; + private Executor executor; private Retrofit oauthRetrofit; private Retrofit retrofit; private String accessToken; private String accountName; - private SubscribedUserDao subscribedUserDao; + private RedditDataRoomDatabase redditDataRoomDatabase; private int primaryTextColor; private int buttonTextColor; @@ -67,17 +71,18 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R private NetworkState networkState; private final Callback callback; - public UserListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit, + public UserListingRecyclerViewAdapter(Context context, Executor executor, Retrofit oauthRetrofit, Retrofit retrofit, CustomThemeWrapper customThemeWrapper, String accessToken, - String accountName, SubscribedUserDao subscribedUserDao, + String accountName, RedditDataRoomDatabase redditDataRoomDatabase, Callback callback) { super(DIFF_CALLBACK); this.context = context; + this.executor = executor; this.oauthRetrofit = oauthRetrofit; this.retrofit = retrofit; this.accessToken = accessToken; this.accountName = accountName; - this.subscribedUserDao = subscribedUserDao; + this.redditDataRoomDatabase = redditDataRoomDatabase; this.callback = callback; glide = Glide.with(context); primaryTextColor = customThemeWrapper.getPrimaryTextColor(); @@ -125,8 +130,8 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R ((UserListingRecyclerViewAdapter.DataViewHolder) holder).userNameTextView.setText(userData.getName()); - new CheckIsFollowingUserAsyncTask(subscribedUserDao, userData.getName(), accountName, - new CheckIsFollowingUserAsyncTask.CheckIsFollowingUserListener() { + CheckIsFollowingUser.checkIsFollowingUser(executor, new Handler(), redditDataRoomDatabase, + userData.getName(), accountName, new CheckIsFollowingUser.CheckIsFollowingUserListener() { @Override public void isSubscribed() { ((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setVisibility(View.GONE); @@ -137,7 +142,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R ((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setVisibility(View.VISIBLE); ((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setOnClickListener(view -> { UserFollowing.followUser(oauthRetrofit, retrofit, - accessToken, userData.getName(), accountName, subscribedUserDao, + accessToken, userData.getName(), accountName, redditDataRoomDatabase, new UserFollowing.UserFollowingListener() { @Override public void onUserFollowingSuccess() { @@ -152,7 +157,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R }); }); } - }).execute(); + }); } } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ChangeThemeName.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ChangeThemeName.java new file mode 100644 index 00000000..efe81f59 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ChangeThemeName.java @@ -0,0 +1,14 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class ChangeThemeName { + public static void changeThemeName(Executor executor, RedditDataRoomDatabase redditDataRoomDatabase, + String oldName, String newName) { + executor.execute(() -> { + redditDataRoomDatabase.customThemeDao().updateName(oldName, newName); + }); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ChangeThemeNameAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ChangeThemeNameAsyncTask.java deleted file mode 100644 index 4bc3bef4..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ChangeThemeNameAsyncTask.java +++ /dev/null @@ -1,23 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class ChangeThemeNameAsyncTask extends AsyncTask<Void, Void, Void> { - private RedditDataRoomDatabase redditDataRoomDatabase; - private String oldName; - private String newName; - - public ChangeThemeNameAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, String oldName, String newName) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.oldName = oldName; - this.newName = newName; - } - - @Override - protected Void doInBackground(Void... voids) { - redditDataRoomDatabase.customThemeDao().updateName(oldName, newName); - return null; - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsFollowingUser.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsFollowingUser.java new file mode 100644 index 00000000..2bf3657e --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsFollowingUser.java @@ -0,0 +1,31 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData; + +public class CheckIsFollowingUser { + public static void checkIsFollowingUser(Executor executor, Handler handler, + RedditDataRoomDatabase redditDataRoomDatabase, String username, + String accountName, CheckIsFollowingUserListener checkIsFollowingUserListener) { + executor.execute(() -> { + SubscribedUserData subscribedUserData = redditDataRoomDatabase.subscribedUserDao().getSubscribedUser(username, accountName); + handler.post(() -> { + if (subscribedUserData != null) { + checkIsFollowingUserListener.isSubscribed(); + } else { + checkIsFollowingUserListener.isNotSubscribed(); + } + }); + }); + } + + public interface CheckIsFollowingUserListener { + void isSubscribed(); + + void isNotSubscribed(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsFollowingUserAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsFollowingUserAsyncTask.java deleted file mode 100644 index a34bd0a8..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsFollowingUserAsyncTask.java +++ /dev/null @@ -1,44 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserDao; -import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData; - -public class CheckIsFollowingUserAsyncTask extends AsyncTask<Void, Void, Void> { - private SubscribedUserDao subscribedUserDao; - private String username; - private String accountName; - private SubscribedUserData subscribedUserData; - private CheckIsFollowingUserListener checkIsFollowingUserListener; - - public CheckIsFollowingUserAsyncTask(SubscribedUserDao subscribedUserDao, String username, String accountName, - CheckIsFollowingUserListener checkIsFollowingUserListener) { - this.subscribedUserDao = subscribedUserDao; - this.username = username; - this.accountName = accountName; - this.checkIsFollowingUserListener = checkIsFollowingUserListener; - } - - @Override - protected Void doInBackground(Void... voids) { - subscribedUserData = subscribedUserDao.getSubscribedUser(username, accountName); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (subscribedUserData != null) { - checkIsFollowingUserListener.isSubscribed(); - } else { - checkIsFollowingUserListener.isNotSubscribed(); - } - } - - public interface CheckIsFollowingUserListener { - void isSubscribed(); - - void isNotSubscribed(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java new file mode 100644 index 00000000..fed411cc --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java @@ -0,0 +1,32 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData; + +public class CheckIsSubscribedToSubreddit { + + public static void checkIsSubscribedToSubreddit(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + String subredditName, String accountName, + CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) { + executor.execute(() -> { + SubscribedSubredditData subscribedSubredditData = redditDataRoomDatabase.subscribedSubredditDao().getSubscribedSubreddit(subredditName, accountName); + handler.post(() -> { + if (subscribedSubredditData != null) { + checkIsSubscribedToSubredditListener.isSubscribed(); + } else { + checkIsSubscribedToSubredditListener.isNotSubscribed(); + } + }); + }); + } + + public interface CheckIsSubscribedToSubredditListener { + void isSubscribed(); + + void isNotSubscribed(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubredditAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubredditAsyncTask.java deleted file mode 100644 index a7aaddd4..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubredditAsyncTask.java +++ /dev/null @@ -1,46 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData; - -public class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask<Void, Void, Void> { - - private RedditDataRoomDatabase redditDataRoomDatabase; - private String subredditName; - private String accountName; - private SubscribedSubredditData subscribedSubredditData; - private CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener; - - public CheckIsSubscribedToSubredditAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - String subredditName, String accountName, - CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.subredditName = subredditName; - this.accountName = accountName; - this.checkIsSubscribedToSubredditListener = checkIsSubscribedToSubredditListener; - } - - @Override - protected Void doInBackground(Void... voids) { - subscribedSubredditData = redditDataRoomDatabase.subscribedSubredditDao().getSubscribedSubreddit(subredditName, accountName); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (subscribedSubredditData != null) { - checkIsSubscribedToSubredditListener.isSubscribed(); - } else { - checkIsSubscribedToSubredditListener.isNotSubscribed(); - } - } - - public interface CheckIsSubscribedToSubredditListener { - void isSubscribed(); - - void isNotSubscribed(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllPostLayouts.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllPostLayouts.java new file mode 100644 index 00000000..ca20a20d --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllPostLayouts.java @@ -0,0 +1,44 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.content.SharedPreferences; +import android.os.Handler; + +import java.util.Map; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; + +public class DeleteAllPostLayouts { + + public static void deleteAllPostLayouts(Executor executor, Handler handler, SharedPreferences defaultSharedPreferences, + SharedPreferences postLayoutSharedPreferences, + DeleteAllPostLayoutsAsyncTaskListener deleteAllPostLayoutsAsyncTaskListener) { + executor.execute(() -> { + Map<String,?> keys = defaultSharedPreferences.getAll(); + SharedPreferences.Editor editor = defaultSharedPreferences.edit(); + + for(Map.Entry<String,?> entry : keys.entrySet()){ + String key = entry.getKey(); + if (key.startsWith(SharedPreferencesUtils.POST_LAYOUT_SHARED_PREFERENCES_FILE) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_POPULAR_POST_LEGACY) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_ALL_POST_LEGACY) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_SUBREDDIT_POST_BASE) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_MULTI_REDDIT_POST_BASE) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_USER_POST_BASE) + || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_SEARCH_POST)) { + editor.remove(key); + } + } + editor.apply(); + + postLayoutSharedPreferences.edit().clear().apply(); + + handler.post(deleteAllPostLayoutsAsyncTaskListener::success); + }); + } + + public interface DeleteAllPostLayoutsAsyncTaskListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllPostLayoutsAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllPostLayoutsAsyncTask.java deleted file mode 100644 index a4298f10..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllPostLayoutsAsyncTask.java +++ /dev/null @@ -1,57 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.content.SharedPreferences; -import android.os.AsyncTask; - -import java.util.Map; - -import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; - -public class DeleteAllPostLayoutsAsyncTask extends AsyncTask<Void, Void, Void> { - - private SharedPreferences defaultSharedPreferences; - private SharedPreferences postLayoutSharedPreferences; - private DeleteAllPostLayoutsAsyncTaskListener deleteAllPostLayoutsAsyncTaskListener; - - public interface DeleteAllPostLayoutsAsyncTaskListener { - void success(); - } - - public DeleteAllPostLayoutsAsyncTask(SharedPreferences defaultSharedPreferences, - SharedPreferences postLayoutSharedPreferences, - DeleteAllPostLayoutsAsyncTaskListener deleteAllPostLayoutsAsyncTaskListener) { - this.defaultSharedPreferences = defaultSharedPreferences; - this.postLayoutSharedPreferences = postLayoutSharedPreferences; - this.deleteAllPostLayoutsAsyncTaskListener = deleteAllPostLayoutsAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - Map<String,?> keys = defaultSharedPreferences.getAll(); - SharedPreferences.Editor editor = defaultSharedPreferences.edit(); - - for(Map.Entry<String,?> entry : keys.entrySet()){ - String key = entry.getKey(); - if (key.startsWith(SharedPreferencesUtils.POST_LAYOUT_SHARED_PREFERENCES_FILE) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_POPULAR_POST_LEGACY) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_ALL_POST_LEGACY) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_SUBREDDIT_POST_BASE) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_MULTI_REDDIT_POST_BASE) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_USER_POST_BASE) - || key.startsWith(SharedPreferencesUtils.POST_LAYOUT_SEARCH_POST)) { - editor.remove(key); - } - } - editor.apply(); - - postLayoutSharedPreferences.edit().clear().apply(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteAllPostLayoutsAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllReadPosts.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllReadPosts.java new file mode 100644 index 00000000..996f8f39 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllReadPosts.java @@ -0,0 +1,23 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class DeleteAllReadPosts { + + public static void deleteAllReadPosts(Executor executor, Handler handler, + RedditDataRoomDatabase redditDataRoomDatabase, + DeleteAllReadPostsAsyncTaskListener deleteAllReadPostsAsyncTaskListener) { + executor.execute(() -> { + redditDataRoomDatabase.readPostDao().deleteAllReadPosts(); + handler.post(deleteAllReadPostsAsyncTaskListener::success); + }); + } + + public interface DeleteAllReadPostsAsyncTaskListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllReadPostsAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllReadPostsAsyncTask.java deleted file mode 100644 index 34098ef2..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllReadPostsAsyncTask.java +++ /dev/null @@ -1,33 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class DeleteAllReadPostsAsyncTask extends AsyncTask<Void, Void, Void> { - - public interface DeleteAllReadPostsAsyncTaskListener { - void success(); - } - - private RedditDataRoomDatabase redditDataRoomDatabase; - private DeleteAllReadPostsAsyncTaskListener deleteAllReadPostsAsyncTaskListener; - - public DeleteAllReadPostsAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - DeleteAllReadPostsAsyncTaskListener deleteAllReadPostsAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.deleteAllReadPostsAsyncTaskListener = deleteAllReadPostsAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - redditDataRoomDatabase.readPostDao().deleteAllReadPosts(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteAllReadPostsAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSortTypes.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSortTypes.java new file mode 100644 index 00000000..e077871d --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSortTypes.java @@ -0,0 +1,46 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.content.SharedPreferences; +import android.os.Handler; + +import java.util.Map; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; + +public class DeleteAllSortTypes { + + public static void deleteAllSortTypes(Executor executor, Handler handler, SharedPreferences defaultSharedPreferences, + SharedPreferences sortTypeSharedPreferences, + DeleteAllSortTypesAsyncTaskListener deleteAllSortTypesAsyncTaskListener) { + executor.execute(() -> { + Map<String,?> keys = defaultSharedPreferences.getAll(); + SharedPreferences.Editor editor = defaultSharedPreferences.edit(); + + for(Map.Entry<String,?> entry : keys.entrySet()){ + String key = entry.getKey(); + if (key.contains(SharedPreferencesUtils.SORT_TYPE_BEST_POST) || key.contains(SharedPreferencesUtils.SORT_TIME_BEST_POST) + || key.contains(SharedPreferencesUtils.SORT_TYPE_ALL_POST_LEGACY) || key.contains(SharedPreferencesUtils.SORT_TIME_ALL_POST_LEGACY) + || key.contains(SharedPreferencesUtils.SORT_TYPE_POPULAR_POST_LEGACY) || key.contains(SharedPreferencesUtils.SORT_TIME_POPULAR_POST_LEGACY) + || key.contains(SharedPreferencesUtils.SORT_TYPE_SEARCH_POST) || key.contains(SharedPreferencesUtils.SORT_TIME_SEARCH_POST) + || key.contains(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE) || key.contains(SharedPreferencesUtils.SORT_TIME_SUBREDDIT_POST_BASE) + || key.contains(SharedPreferencesUtils.SORT_TYPE_MULTI_REDDIT_POST_BASE) || key.contains(SharedPreferencesUtils.SORT_TIME_MULTI_REDDIT_POST_BASE) + || key.contains(SharedPreferencesUtils.SORT_TYPE_USER_POST_BASE) || key.contains(SharedPreferencesUtils.SORT_TIME_USER_POST_BASE) + || key.contains(SharedPreferencesUtils.SORT_TYPE_USER_COMMENT) || key.contains(SharedPreferencesUtils.SORT_TIME_USER_COMMENT) + || key.contains(SharedPreferencesUtils.SORT_TYPE_SEARCH_SUBREDDIT) || key.contains(SharedPreferencesUtils.SORT_TYPE_SEARCH_USER) + || key.contains(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT)) { + editor.remove(key); + } + } + editor.apply(); + + sortTypeSharedPreferences.edit().clear().apply(); + + handler.post(deleteAllSortTypesAsyncTaskListener::success); + }); + } + + public interface DeleteAllSortTypesAsyncTaskListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSortTypesAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSortTypesAsyncTask.java deleted file mode 100644 index a0d999b5..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSortTypesAsyncTask.java +++ /dev/null @@ -1,58 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.content.SharedPreferences; -import android.os.AsyncTask; - -import java.util.Map; - -import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; - -public class DeleteAllSortTypesAsyncTask extends AsyncTask<Void, Void, Void> { - private SharedPreferences defaultSharedPreferences; - private SharedPreferences sortTypeSharedPreferences; - private DeleteAllSortTypesAsyncTaskListener deleteAllSortTypesAsyncTaskListener; - - public interface DeleteAllSortTypesAsyncTaskListener { - void success(); - } - - public DeleteAllSortTypesAsyncTask(SharedPreferences defaultSharedPreferences, - SharedPreferences sortTypeSharedPreferences, - DeleteAllSortTypesAsyncTaskListener deleteAllSortTypesAsyncTaskListener) { - this.defaultSharedPreferences = defaultSharedPreferences; - this.sortTypeSharedPreferences = sortTypeSharedPreferences; - this.deleteAllSortTypesAsyncTaskListener = deleteAllSortTypesAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - Map<String,?> keys = defaultSharedPreferences.getAll(); - SharedPreferences.Editor editor = defaultSharedPreferences.edit(); - - for(Map.Entry<String,?> entry : keys.entrySet()){ - String key = entry.getKey(); - if (key.contains(SharedPreferencesUtils.SORT_TYPE_BEST_POST) || key.contains(SharedPreferencesUtils.SORT_TIME_BEST_POST) - || key.contains(SharedPreferencesUtils.SORT_TYPE_ALL_POST_LEGACY) || key.contains(SharedPreferencesUtils.SORT_TIME_ALL_POST_LEGACY) - || key.contains(SharedPreferencesUtils.SORT_TYPE_POPULAR_POST_LEGACY) || key.contains(SharedPreferencesUtils.SORT_TIME_POPULAR_POST_LEGACY) - || key.contains(SharedPreferencesUtils.SORT_TYPE_SEARCH_POST) || key.contains(SharedPreferencesUtils.SORT_TIME_SEARCH_POST) - || key.contains(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE) || key.contains(SharedPreferencesUtils.SORT_TIME_SUBREDDIT_POST_BASE) - || key.contains(SharedPreferencesUtils.SORT_TYPE_MULTI_REDDIT_POST_BASE) || key.contains(SharedPreferencesUtils.SORT_TIME_MULTI_REDDIT_POST_BASE) - || key.contains(SharedPreferencesUtils.SORT_TYPE_USER_POST_BASE) || key.contains(SharedPreferencesUtils.SORT_TIME_USER_POST_BASE) - || key.contains(SharedPreferencesUtils.SORT_TYPE_USER_COMMENT) || key.contains(SharedPreferencesUtils.SORT_TIME_USER_COMMENT) - || key.contains(SharedPreferencesUtils.SORT_TYPE_SEARCH_SUBREDDIT) || key.contains(SharedPreferencesUtils.SORT_TYPE_SEARCH_USER) - || key.contains(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT)) { - editor.remove(key); - } - } - editor.apply(); - - sortTypeSharedPreferences.edit().clear().apply(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteAllSortTypesAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSubreddits.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSubreddits.java new file mode 100644 index 00000000..84e6ff60 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSubreddits.java @@ -0,0 +1,22 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class DeleteAllSubreddits { + + public static void deleteAllSubreddits(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + DeleteAllSubredditsAsyncTaskListener deleteAllSubredditsAsyncTaskListener) { + executor.execute(() -> { + redditDataRoomDatabase.subredditDao().deleteAllSubreddits(); + handler.post(deleteAllSubredditsAsyncTaskListener::success); + }); + } + + public interface DeleteAllSubredditsAsyncTaskListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSubredditsAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSubredditsAsyncTask.java deleted file mode 100644 index f5494224..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllSubredditsAsyncTask.java +++ /dev/null @@ -1,33 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class DeleteAllSubredditsAsyncTask extends AsyncTask<Void, Void, Void> { - - private RedditDataRoomDatabase redditDataRoomDatabase; - private DeleteAllSubredditsAsyncTaskListener deleteAllSubredditsAsyncTaskListener; - - public interface DeleteAllSubredditsAsyncTaskListener { - void success(); - } - - public DeleteAllSubredditsAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - DeleteAllSubredditsAsyncTaskListener deleteAllSubredditsAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.deleteAllSubredditsAsyncTaskListener = deleteAllSubredditsAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - redditDataRoomDatabase.subredditDao().deleteAllSubreddits(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteAllSubredditsAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllThemes.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllThemes.java new file mode 100644 index 00000000..8fbc8cb0 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllThemes.java @@ -0,0 +1,30 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.content.SharedPreferences; +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class DeleteAllThemes { + + public static void deleteAllThemes(Executor executor, Handler handler, + RedditDataRoomDatabase redditDataRoomDatabase, + SharedPreferences lightThemeSharedPreferences, + SharedPreferences darkThemeSharedPreferences, + SharedPreferences amoledThemeSharedPreferences, + DeleteAllThemesListener deleteAllThemesListener) { + executor.execute(() -> { + redditDataRoomDatabase.customThemeDao().deleteAllCustomThemes(); + lightThemeSharedPreferences.edit().clear().apply(); + darkThemeSharedPreferences.edit().clear().apply(); + amoledThemeSharedPreferences.edit().clear().apply(); + handler.post(deleteAllThemesListener::success); + }); + } + + public interface DeleteAllThemesListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllThemesAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllThemesAsyncTask.java deleted file mode 100644 index ccf935fb..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllThemesAsyncTask.java +++ /dev/null @@ -1,45 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.content.SharedPreferences; -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class DeleteAllThemesAsyncTask extends AsyncTask<Void, Void, Void> { - private RedditDataRoomDatabase redditDataRoomDatabase; - private SharedPreferences lightThemeSharedPreferences; - private SharedPreferences darkThemeSharedPreferences; - private SharedPreferences amoledThemeSharedPreferences; - private DeleteAllThemesAsyncTaskListener deleteAllThemesAsyncTaskListener; - - public interface DeleteAllThemesAsyncTaskListener { - void success(); - } - - public DeleteAllThemesAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - SharedPreferences lightThemeSharedPreferences, - SharedPreferences darkThemeSharedPreferences, - SharedPreferences amoledThemeSharedPreferences, - DeleteAllThemesAsyncTaskListener deleteAllThemesAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.lightThemeSharedPreferences = lightThemeSharedPreferences; - this.darkThemeSharedPreferences = darkThemeSharedPreferences; - this.amoledThemeSharedPreferences = amoledThemeSharedPreferences; - this.deleteAllThemesAsyncTaskListener = deleteAllThemesAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - redditDataRoomDatabase.customThemeDao().deleteAllCustomThemes(); - lightThemeSharedPreferences.edit().clear().apply(); - darkThemeSharedPreferences.edit().clear().apply(); - amoledThemeSharedPreferences.edit().clear().apply(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteAllThemesAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllUsers.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllUsers.java new file mode 100644 index 00000000..ee233614 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllUsers.java @@ -0,0 +1,22 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class DeleteAllUsers { + + public static void deleteAllUsers(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + DeleteAllUsersListener deleteAllUsersListener) { + executor.execute(() -> { + redditDataRoomDatabase.userDao().deleteAllUsers(); + handler.post(deleteAllUsersListener::success); + }); + } + + public interface DeleteAllUsersListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllUsersAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllUsersAsyncTask.java deleted file mode 100644 index 26c20043..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteAllUsersAsyncTask.java +++ /dev/null @@ -1,33 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class DeleteAllUsersAsyncTask extends AsyncTask<Void, Void, Void> { - - private RedditDataRoomDatabase redditDataRoomDatabase; - private DeleteAllUsersAsyncTaskListener deleteAllUsersAsyncTaskListener; - - public interface DeleteAllUsersAsyncTaskListener { - void success(); - } - - public DeleteAllUsersAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - DeleteAllUsersAsyncTaskListener deleteAllUsersAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.deleteAllUsersAsyncTaskListener = deleteAllUsersAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - redditDataRoomDatabase.userDao().deleteAllUsers(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteAllUsersAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteMultiredditInDatabase.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteMultiredditInDatabase.java new file mode 100644 index 00000000..d6e2522d --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteMultiredditInDatabase.java @@ -0,0 +1,23 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class DeleteMultiredditInDatabase { + + public static void deleteMultiredditInDatabase(Executor executor, Handler handler, + RedditDataRoomDatabase redditDataRoomDatabase, + String accountName, String multipath, + DeleteMultiredditInDatabaseListener deleteMultiredditInDatabaseListener) { + executor.execute(() -> { + redditDataRoomDatabase.multiRedditDao().deleteMultiReddit(multipath, accountName); + handler.post(deleteMultiredditInDatabaseListener::success); + }); + } + public interface DeleteMultiredditInDatabaseListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteMultiredditInDatabaseAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteMultiredditInDatabaseAsyncTask.java deleted file mode 100644 index 61e62244..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteMultiredditInDatabaseAsyncTask.java +++ /dev/null @@ -1,37 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class DeleteMultiredditInDatabaseAsyncTask extends AsyncTask<Void, Void, Void> { - public interface DeleteMultiredditInDatabaseAsyncTaskListener { - void success(); - } - - private RedditDataRoomDatabase redditDataRoomDatabase; - private String accountName; - private String multipath; - private DeleteMultiredditInDatabaseAsyncTaskListener deleteMultiredditInDatabaseAsyncTaskListener; - - public DeleteMultiredditInDatabaseAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - String accountName, String multipath, - DeleteMultiredditInDatabaseAsyncTaskListener deleteMultiredditInDatabaseAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.accountName = accountName; - this.multipath = multipath; - this.deleteMultiredditInDatabaseAsyncTaskListener = deleteMultiredditInDatabaseAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - redditDataRoomDatabase.multiRedditDao().deleteMultiReddit(multipath, accountName); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteMultiredditInDatabaseAsyncTaskListener.success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteTheme.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteTheme.java new file mode 100644 index 00000000..2934e77c --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteTheme.java @@ -0,0 +1,32 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.customtheme.CustomTheme; + +public class DeleteTheme { + + public static void deleteTheme(Executor executor, Handler handler, + RedditDataRoomDatabase redditDataRoomDatabase, String themeName, + DeleteThemeListener deleteThemeListener) { + executor.execute(() -> { + CustomTheme customTheme = redditDataRoomDatabase.customThemeDao().getCustomTheme(themeName); + if (customTheme != null) { + boolean isLightTheme = customTheme.isLightTheme; + boolean isDarkTheme = customTheme.isDarkTheme; + boolean isAmoledTheme = customTheme.isAmoledTheme; + redditDataRoomDatabase.customThemeDao().deleteCustomTheme(themeName); + handler.post(() -> deleteThemeListener.success(isLightTheme, isDarkTheme, isAmoledTheme)); + } else { + handler.post(() -> deleteThemeListener.success(false, false, false)); + } + }); + } + + public interface DeleteThemeListener { + void success(boolean isLightTheme, boolean isDarkTheme, boolean isAmoledTheme); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteThemeAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteThemeAsyncTask.java deleted file mode 100644 index e33cdbf5..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/DeleteThemeAsyncTask.java +++ /dev/null @@ -1,44 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.customtheme.CustomTheme; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class DeleteThemeAsyncTask extends AsyncTask<Void, Void, Void> { - private RedditDataRoomDatabase redditDataRoomDatabase; - private String themeName; - private DeleteThemeAsyncTaskListener deleteThemeAsyncTaskListener; - private boolean isLightTheme = false; - private boolean isDarkTheme = false; - private boolean isAmoledTheme = false; - - public interface DeleteThemeAsyncTaskListener { - void success(boolean isLightTheme, boolean isDarkTheme, boolean isAmoledTheme); - } - - public DeleteThemeAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, String themeName, - DeleteThemeAsyncTaskListener deleteThemeAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.themeName = themeName; - this.deleteThemeAsyncTaskListener = deleteThemeAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - CustomTheme customTheme = redditDataRoomDatabase.customThemeDao().getCustomTheme(themeName); - if (customTheme != null) { - isLightTheme = customTheme.isLightTheme; - isDarkTheme = customTheme.isDarkTheme; - isAmoledTheme = customTheme.isAmoledTheme; - redditDataRoomDatabase.customThemeDao().deleteCustomTheme(themeName); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - deleteThemeAsyncTaskListener.success(isLightTheme, isDarkTheme, isAmoledTheme); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertMultiRedditAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertMultiRedditAsyncTask.java deleted file mode 100644 index b0351966..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertMultiRedditAsyncTask.java +++ /dev/null @@ -1,94 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import ml.docilealligator.infinityforreddit.multireddit.MultiReddit; -import ml.docilealligator.infinityforreddit.multireddit.MultiRedditDao; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; - -public class InsertMultiRedditAsyncTask extends AsyncTask<Void, Void, Void> { - private MultiRedditDao multiRedditDao; - private ArrayList<MultiReddit> multiReddits; - private MultiReddit multiReddit; - private String accountName; - private InsertMultiRedditAsyncTaskListener insertMultiRedditAsyncTaskListener; - - public InsertMultiRedditAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - ArrayList<MultiReddit> multiReddits, String accountName, - InsertMultiRedditAsyncTaskListener insertMultiRedditAsyncTaskListener) { - multiRedditDao = redditDataRoomDatabase.multiRedditDao(); - this.multiReddits = multiReddits; - this.accountName = accountName; - this.insertMultiRedditAsyncTaskListener = insertMultiRedditAsyncTaskListener; - } - - public InsertMultiRedditAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - MultiReddit multiReddit, - InsertMultiRedditAsyncTaskListener insertMultiRedditAsyncTaskListener) { - multiRedditDao = redditDataRoomDatabase.multiRedditDao(); - this.multiReddit = multiReddit; - this.insertMultiRedditAsyncTaskListener = insertMultiRedditAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - if (multiReddit != null) { - multiRedditDao.insert(multiReddit); - return null; - } - - List<MultiReddit> existingMultiReddits = multiRedditDao.getAllMultiRedditsList(accountName); - Collections.sort(multiReddits, (multiReddit, t1) -> multiReddit.getName().compareToIgnoreCase(t1.getName())); - List<String> deletedMultiredditNames = new ArrayList<>(); - compareTwoMultiRedditList(multiReddits, existingMultiReddits, deletedMultiredditNames); - - for (String deleted : deletedMultiredditNames) { - multiRedditDao.deleteMultiReddit(deleted, accountName); - } - - for (MultiReddit multiReddit : multiReddits) { - multiRedditDao.insert(multiReddit); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - insertMultiRedditAsyncTaskListener.success(); - } - - private void compareTwoMultiRedditList(List<MultiReddit> newMultiReddits, - List<MultiReddit> oldMultiReddits, - List<String> deletedMultiReddits) { - int newIndex = 0; - for (int oldIndex = 0; oldIndex < oldMultiReddits.size(); oldIndex++) { - if (newIndex >= newMultiReddits.size()) { - for (; oldIndex < oldMultiReddits.size(); oldIndex++) { - deletedMultiReddits.add(oldMultiReddits.get(oldIndex).getName()); - } - return; - } - - MultiReddit old = oldMultiReddits.get(oldIndex); - for (; newIndex < newMultiReddits.size(); newIndex++) { - if (newMultiReddits.get(newIndex).getName().compareToIgnoreCase(old.getName()) == 0) { - newIndex++; - break; - } - if (newMultiReddits.get(newIndex).getName().compareToIgnoreCase(old.getName()) > 0) { - deletedMultiReddits.add(old.getName()); - break; - } - } - } - } - - public interface InsertMultiRedditAsyncTaskListener { - void success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertMultireddit.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertMultireddit.java new file mode 100644 index 00000000..99d046c9 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertMultireddit.java @@ -0,0 +1,76 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.multireddit.MultiReddit; +import ml.docilealligator.infinityforreddit.multireddit.MultiRedditDao; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + +public class InsertMultireddit { + + public static void insertMultireddit(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + ArrayList<MultiReddit> multiReddits, String accountName, + InsertMultiRedditListener insertMultiRedditListener) { + executor.execute(() -> { + MultiRedditDao multiRedditDao = redditDataRoomDatabase.multiRedditDao(); + List<MultiReddit> existingMultiReddits = multiRedditDao.getAllMultiRedditsList(accountName); + Collections.sort(multiReddits, (multiReddit, t1) -> multiReddit.getName().compareToIgnoreCase(t1.getName())); + List<String> deletedMultiredditNames = new ArrayList<>(); + compareTwoMultiRedditList(multiReddits, existingMultiReddits, deletedMultiredditNames); + + for (String deleted : deletedMultiredditNames) { + multiRedditDao.deleteMultiReddit(deleted, accountName); + } + + for (MultiReddit multiReddit : multiReddits) { + multiRedditDao.insert(multiReddit); + } + + handler.post(insertMultiRedditListener::success); + }); + } + + public static void insertMultireddit(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + MultiReddit multiReddit, + InsertMultiRedditListener insertMultiRedditListener) { + executor.execute(() -> { + redditDataRoomDatabase.multiRedditDao().insert(multiReddit); + handler.post(insertMultiRedditListener::success); + }); + } + + private static void compareTwoMultiRedditList(List<MultiReddit> newMultiReddits, + List<MultiReddit> oldMultiReddits, + List<String> deletedMultiReddits) { + int newIndex = 0; + for (int oldIndex = 0; oldIndex < oldMultiReddits.size(); oldIndex++) { + if (newIndex >= newMultiReddits.size()) { + for (; oldIndex < oldMultiReddits.size(); oldIndex++) { + deletedMultiReddits.add(oldMultiReddits.get(oldIndex).getName()); + } + return; + } + + MultiReddit old = oldMultiReddits.get(oldIndex); + for (; newIndex < newMultiReddits.size(); newIndex++) { + if (newMultiReddits.get(newIndex).getName().compareToIgnoreCase(old.getName()) == 0) { + newIndex++; + break; + } + if (newMultiReddits.get(newIndex).getName().compareToIgnoreCase(old.getName()) > 0) { + deletedMultiReddits.add(old.getName()); + break; + } + } + } + } + + public interface InsertMultiRedditListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubredditData.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubredditData.java new file mode 100644 index 00000000..5ef4ac2c --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubredditData.java @@ -0,0 +1,24 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.subreddit.SubredditData; + +public class InsertSubredditData { + + public static void insertSubredditData(Executor executor, Handler handler, RedditDataRoomDatabase db, + SubredditData subredditData, + InsertSubredditDataAsyncTaskListener insertSubredditDataAsyncTaskListener) { + executor.execute(() -> { + db.subredditDao().insert(subredditData); + handler.post(insertSubredditDataAsyncTaskListener::insertSuccess); + }); + } + + public interface InsertSubredditDataAsyncTaskListener { + void insertSuccess(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubredditDataAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubredditDataAsyncTask.java deleted file mode 100644 index c0085540..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubredditDataAsyncTask.java +++ /dev/null @@ -1,35 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.subreddit.SubredditDao; -import ml.docilealligator.infinityforreddit.subreddit.SubredditData; - -public class InsertSubredditDataAsyncTask extends AsyncTask<Void, Void, Void> { - private SubredditDao mSubredditDao; - private SubredditData subredditData; - private InsertSubredditDataAsyncTaskListener insertSubredditDataAsyncTaskListener; - - public InsertSubredditDataAsyncTask(RedditDataRoomDatabase db, SubredditData subredditData, - InsertSubredditDataAsyncTaskListener insertSubredditDataAsyncTaskListener) { - mSubredditDao = db.subredditDao(); - this.subredditData = subredditData; - this.insertSubredditDataAsyncTaskListener = insertSubredditDataAsyncTaskListener; - } - - @Override - protected Void doInBackground(final Void... params) { - mSubredditDao.insert(subredditData); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - insertSubredditDataAsyncTaskListener.insertSuccess(); - } - - public interface InsertSubredditDataAsyncTaskListener { - void insertSuccess(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubscribedThingsAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubscribedThings.java index 0d67e183..02ad624d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubscribedThingsAsyncTask.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertSubscribedThings.java @@ -1,12 +1,13 @@ package ml.docilealligator.infinityforreddit.asynctasks; -import android.os.AsyncTask; +import android.os.Handler; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.concurrent.Executor; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.subreddit.SubredditDao; @@ -16,117 +17,99 @@ import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubred import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserDao; import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData; -public class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void> { - - private RedditDataRoomDatabase mRedditDataRoomDatabase; - private String mAccountName; - private SubscribedSubredditDao mSubscribedSubredditDao; - private SubscribedUserDao mSubscribedUserDao; - private SubredditDao mSubredditDao; - private SubscribedSubredditData mSingleSubscribedSubredditData; - private SubscribedUserData mSingleSubscribedUserData; - private List<SubscribedSubredditData> subscribedSubredditDataList; - private List<SubscribedUserData> subscribedUserDataList; - private List<SubredditData> subredditDataList; - private InsertSubscribedThingListener mInsertSubscribedThingListener; - - public InsertSubscribedThingsAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, @Nullable String accountName, - List<SubscribedSubredditData> subscribedSubredditDataList, - List<SubscribedUserData> subscribedUserDataList, - List<SubredditData> subredditDataList, - InsertSubscribedThingListener insertSubscribedThingListener) { - mRedditDataRoomDatabase = redditDataRoomDatabase; - mAccountName = accountName; - mSubscribedSubredditDao = redditDataRoomDatabase.subscribedSubredditDao(); - mSubscribedUserDao = redditDataRoomDatabase.subscribedUserDao(); - mSubredditDao = redditDataRoomDatabase.subredditDao(); - - this.subscribedSubredditDataList = subscribedSubredditDataList; - this.subscribedUserDataList = subscribedUserDataList; - this.subredditDataList = subredditDataList; - mInsertSubscribedThingListener = insertSubscribedThingListener; - } - - public InsertSubscribedThingsAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - SubscribedSubredditData subscribedSubredditDataList, - InsertSubscribedThingListener insertSubscribedThingListener) { - mRedditDataRoomDatabase = redditDataRoomDatabase; - mSubscribedSubredditDao = redditDataRoomDatabase.subscribedSubredditDao(); - mAccountName = subscribedSubredditDataList.getUsername(); - mSingleSubscribedSubredditData = subscribedSubredditDataList; - mInsertSubscribedThingListener = insertSubscribedThingListener; - } - - public InsertSubscribedThingsAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, - SubscribedUserData subscribedUserDataList, - InsertSubscribedThingListener insertSubscribedThingListener) { - mRedditDataRoomDatabase = redditDataRoomDatabase; - mSubscribedUserDao = redditDataRoomDatabase.subscribedUserDao(); - mAccountName = subscribedUserDataList.getUsername(); - mSingleSubscribedUserData = subscribedUserDataList; - mInsertSubscribedThingListener = insertSubscribedThingListener; - } +public class InsertSubscribedThings { + + public static void insertSubscribedThings(Executor executor, Handler handler, + RedditDataRoomDatabase redditDataRoomDatabase, @Nullable String accountName, + List<SubscribedSubredditData> subscribedSubredditDataList, + List<SubscribedUserData> subscribedUserDataList, + List<SubredditData> subredditDataList, + InsertSubscribedThingListener insertSubscribedThingListener) { + executor.execute(() -> { + if (accountName != null && redditDataRoomDatabase.accountDao().getAccountData(accountName) == null) { + handler.post(insertSubscribedThingListener::insertSuccess); + return; + } - @Override - protected Void doInBackground(final Void... params) { - if (mAccountName != null && mRedditDataRoomDatabase.accountDao().getAccountData(mAccountName) == null) { - return null; - } + SubscribedSubredditDao subscribedSubredditDao = redditDataRoomDatabase.subscribedSubredditDao(); + SubscribedUserDao subscribedUserDao = redditDataRoomDatabase.subscribedUserDao(); + SubredditDao subredditDao = redditDataRoomDatabase.subredditDao(); - if (mSingleSubscribedSubredditData != null) { - mSubscribedSubredditDao.insert(mSingleSubscribedSubredditData); - } else if (mSingleSubscribedUserData != null) { - mSubscribedUserDao.insert(mSingleSubscribedUserData); - } else { if (subscribedSubredditDataList != null) { List<SubscribedSubredditData> existingSubscribedSubredditDataList = - mSubscribedSubredditDao.getAllSubscribedSubredditsList(mAccountName); + subscribedSubredditDao.getAllSubscribedSubredditsList(accountName); Collections.sort(subscribedSubredditDataList, (subscribedSubredditData, t1) -> subscribedSubredditData.getName().compareToIgnoreCase(t1.getName())); List<String> unsubscribedSubreddits = new ArrayList<>(); compareTwoSubscribedSubredditList(subscribedSubredditDataList, existingSubscribedSubredditDataList, unsubscribedSubreddits); for (String unsubscribed : unsubscribedSubreddits) { - mSubscribedSubredditDao.deleteSubscribedSubreddit(unsubscribed, mAccountName); + subscribedSubredditDao.deleteSubscribedSubreddit(unsubscribed, accountName); } for (SubscribedSubredditData s : subscribedSubredditDataList) { - mSubscribedSubredditDao.insert(s); + subscribedSubredditDao.insert(s); } } if (subscribedUserDataList != null) { List<SubscribedUserData> existingSubscribedUserDataList = - mSubscribedUserDao.getAllSubscribedUsersList(mAccountName); + subscribedUserDao.getAllSubscribedUsersList(accountName); Collections.sort(subscribedUserDataList, (subscribedUserData, t1) -> subscribedUserData.getName().compareToIgnoreCase(t1.getName())); List<String> unsubscribedUsers = new ArrayList<>(); compareTwoSubscribedUserList(subscribedUserDataList, existingSubscribedUserDataList, unsubscribedUsers); for (String unsubscribed : unsubscribedUsers) { - mSubscribedUserDao.deleteSubscribedUser(unsubscribed, mAccountName); + subscribedUserDao.deleteSubscribedUser(unsubscribed, accountName); } for (SubscribedUserData s : subscribedUserDataList) { - mSubscribedUserDao.insert(s); + subscribedUserDao.insert(s); } } if (subredditDataList != null) { for (SubredditData s : subredditDataList) { - mSubredditDao.insert(s); + subredditDao.insert(s); } } - } - return null; + + handler.post(insertSubscribedThingListener::insertSuccess); + }); } - @Override - protected void onPostExecute(Void aVoid) { - mInsertSubscribedThingListener.insertSuccess(); + public static void insertSubscribedThings(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + SubscribedSubredditData singleSubscribedSubredditData, + InsertSubscribedThingListener insertSubscribedThingListener) { + executor.execute(() -> { + String accountName = singleSubscribedSubredditData.getUsername(); + if (accountName != null && redditDataRoomDatabase.accountDao().getAccountData(accountName) == null) { + handler.post(insertSubscribedThingListener::insertSuccess); + return; + } + + redditDataRoomDatabase.subscribedSubredditDao().insert(singleSubscribedSubredditData); + handler.post(insertSubscribedThingListener::insertSuccess); + }); + } + + public static void insertSubscribedThings(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + SubscribedUserData mSingleSubscribedUserData, + InsertSubscribedThingListener insertSubscribedThingListener) { + executor.execute(() -> { + String accountName = mSingleSubscribedUserData.getUsername(); + if (accountName != null && redditDataRoomDatabase.accountDao().getAccountData(accountName) == null) { + handler.post(insertSubscribedThingListener::insertSuccess); + return; + } + + redditDataRoomDatabase.subscribedUserDao().insert(mSingleSubscribedUserData); + handler.post(insertSubscribedThingListener::insertSuccess); + }); } - private void compareTwoSubscribedSubredditList(List<SubscribedSubredditData> newSubscribedSubreddits, + private static void compareTwoSubscribedSubredditList(List<SubscribedSubredditData> newSubscribedSubreddits, List<SubscribedSubredditData> oldSubscribedSubreddits, List<String> unsubscribedSubredditNames) { int newIndex = 0; @@ -152,7 +135,7 @@ public class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void> } } - private void compareTwoSubscribedUserList(List<SubscribedUserData> newSubscribedUsers, + private static void compareTwoSubscribedUserList(List<SubscribedUserData> newSubscribedUsers, List<SubscribedUserData> oldSubscribedUsers, List<String> unsubscribedUserNames) { int newIndex = 0; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertUserData.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertUserData.java new file mode 100644 index 00000000..0e480315 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertUserData.java @@ -0,0 +1,25 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.user.UserData; + +public class InsertUserData { + + public static void insertUserData(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + UserData userData, InsertUserDataListener insertUserDataListener) { + executor.execute(() -> { + redditDataRoomDatabase.userDao().insert(userData); + if (insertUserDataListener != null) { + handler.post(insertUserDataListener::insertSuccess); + } + }); + } + + public interface InsertUserDataListener { + void insertSuccess(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertUserDataAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertUserDataAsyncTask.java deleted file mode 100644 index caf2f7f1..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/InsertUserDataAsyncTask.java +++ /dev/null @@ -1,36 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.user.UserDao; -import ml.docilealligator.infinityforreddit.user.UserData; - -public class InsertUserDataAsyncTask extends AsyncTask<Void, Void, Void> { - private UserDao userDao; - private UserData userData; - private InsertUserDataCallback insertUserDataCallback; - - public InsertUserDataAsyncTask(UserDao userDao, UserData userData, InsertUserDataCallback insertUserDataCallback) { - this.userDao = userDao; - this.userData = userData; - this.insertUserDataCallback = insertUserDataCallback; - } - - @Override - protected Void doInBackground(Void... voids) { - userDao.insert(userData); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (insertUserDataCallback != null) { - insertUserDataCallback.insertSuccess(); - } - } - - public interface InsertUserDataCallback { - void insertSuccess(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadSubredditIcon.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadSubredditIcon.java new file mode 100644 index 00000000..0e1c981c --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadSubredditIcon.java @@ -0,0 +1,48 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.ArrayList; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData; +import ml.docilealligator.infinityforreddit.subreddit.SubredditDao; +import ml.docilealligator.infinityforreddit.subreddit.SubredditData; +import retrofit2.Retrofit; + +public class LoadSubredditIcon { + + public static void loadSubredditIcon(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, + String subredditName, Retrofit retrofit, + LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener) { + executor.execute(() -> { + SubredditDao subredditDao = redditDataRoomDatabase.subredditDao(); + SubredditData subredditData = subredditDao.getSubredditData(subredditName); + if (subredditData != null) { + String iconImageUrl = subredditDao.getSubredditData(subredditName).getIconUrl(); + handler.post(() -> loadSubredditIconAsyncTaskListener.loadIconSuccess(iconImageUrl)); + } else { + handler.post(() -> FetchSubredditData.fetchSubredditData(retrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { + @Override + public void onFetchSubredditDataSuccess(SubredditData subredditData1, int nCurrentOnlineSubscribers) { + ArrayList<SubredditData> singleSubredditDataList = new ArrayList<>(); + singleSubredditDataList.add(subredditData1); + InsertSubscribedThings.insertSubscribedThings(executor, handler, redditDataRoomDatabase, null, + null, null, singleSubredditDataList, + () -> loadSubredditIconAsyncTaskListener.loadIconSuccess(subredditData1.getIconUrl())); + } + + @Override + public void onFetchSubredditDataFail(boolean isQuarantined) { + loadSubredditIconAsyncTaskListener.loadIconSuccess(null); + } + })); + } + }); + } + + public interface LoadSubredditIconAsyncTaskListener { + void loadIconSuccess(String iconImageUrl); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadSubredditIconAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadSubredditIconAsyncTask.java deleted file mode 100644 index 695e4e46..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadSubredditIconAsyncTask.java +++ /dev/null @@ -1,71 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import java.util.ArrayList; - -import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.subreddit.SubredditDao; -import ml.docilealligator.infinityforreddit.subreddit.SubredditData; -import retrofit2.Retrofit; - -public class LoadSubredditIconAsyncTask extends AsyncTask<Void, Void, Void> { - private RedditDataRoomDatabase redditDataRoomDatabase; - private SubredditDao subredditDao; - private String subredditName; - private Retrofit retrofit; - private String iconImageUrl; - private boolean hasSubredditInDb; - private LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener; - public LoadSubredditIconAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, String subredditName, Retrofit retrofit, - LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener) { - this.redditDataRoomDatabase = redditDataRoomDatabase; - this.subredditDao = redditDataRoomDatabase.subredditDao(); - this.subredditName = subredditName; - this.retrofit = retrofit; - this.loadSubredditIconAsyncTaskListener = loadSubredditIconAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - SubredditData subredditData = subredditDao.getSubredditData(subredditName); - if (subredditData != null) { - iconImageUrl = subredditDao.getSubredditData(subredditName).getIconUrl(); - hasSubredditInDb = true; - } else { - hasSubredditInDb = false; - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (!isCancelled()) { - if (hasSubredditInDb) { - loadSubredditIconAsyncTaskListener.loadIconSuccess(iconImageUrl); - } else { - FetchSubredditData.fetchSubredditData(retrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { - @Override - public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { - ArrayList<SubredditData> singleSubredditDataList = new ArrayList<>(); - singleSubredditDataList.add(subredditData); - new InsertSubscribedThingsAsyncTask(redditDataRoomDatabase, null, - null, null, singleSubredditDataList, - () -> loadSubredditIconAsyncTaskListener.loadIconSuccess(subredditData.getIconUrl())).execute(); - } - - @Override - public void onFetchSubredditDataFail(boolean isQuarantined) { - loadSubredditIconAsyncTaskListener.loadIconSuccess(null); - } - }); - } - } - } - - public interface LoadSubredditIconAsyncTaskListener { - void loadIconSuccess(String iconImageUrl); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadUserData.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadUserData.java new file mode 100644 index 00000000..c6ef0ffc --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadUserData.java @@ -0,0 +1,42 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.user.FetchUserData; +import ml.docilealligator.infinityforreddit.user.UserDao; +import ml.docilealligator.infinityforreddit.user.UserData; +import retrofit2.Retrofit; + +public class LoadUserData { + + public static void loadUserData(Executor executor, Handler handler, RedditDataRoomDatabase redditDataRoomDatabase, String userName, + Retrofit retrofit, LoadUserDataAsyncTaskListener loadUserDataAsyncTaskListener) { + executor.execute(() -> { + UserDao userDao = redditDataRoomDatabase.userDao(); + if (userDao.getUserData(userName) != null) { + String iconImageUrl = userDao.getUserData(userName).getIconUrl(); + handler.post(() -> loadUserDataAsyncTaskListener.loadUserDataSuccess(iconImageUrl)); + } else { + handler.post(() -> FetchUserData.fetchUserData(retrofit, userName, new FetchUserData.FetchUserDataListener() { + @Override + public void onFetchUserDataSuccess(UserData userData) { + InsertUserData.insertUserData(executor, handler, redditDataRoomDatabase, userData, + () -> loadUserDataAsyncTaskListener.loadUserDataSuccess(userData.getIconUrl())); + } + + @Override + public void onFetchUserDataFailed() { + loadUserDataAsyncTaskListener.loadUserDataSuccess(null); + } + })); + } + }); + } + + public interface LoadUserDataAsyncTaskListener { + void loadUserDataSuccess(String iconImageUrl); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadUserDataAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadUserDataAsyncTask.java deleted file mode 100644 index 3386965e..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/LoadUserDataAsyncTask.java +++ /dev/null @@ -1,58 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.user.FetchUserData; -import ml.docilealligator.infinityforreddit.user.UserDao; -import ml.docilealligator.infinityforreddit.user.UserData; -import retrofit2.Retrofit; - -public class LoadUserDataAsyncTask extends AsyncTask<Void, Void, Void> { - private UserDao userDao; - private String userName; - private String iconImageUrl; - private boolean hasUserInDb; - private Retrofit retrofit; - private LoadUserDataAsyncTaskListener loadUserDataAsyncTaskListener; - public LoadUserDataAsyncTask(UserDao userDao, String userName, Retrofit retrofit, LoadUserDataAsyncTaskListener loadUserDataAsyncTaskListener) { - this.userDao = userDao; - this.userName = userName; - this.retrofit = retrofit; - this.loadUserDataAsyncTaskListener = loadUserDataAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - if (userDao.getUserData(userName) != null) { - iconImageUrl = userDao.getUserData(userName).getIconUrl(); - hasUserInDb = true; - } else { - hasUserInDb = false; - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (hasUserInDb) { - loadUserDataAsyncTaskListener.loadUserDataSuccess(iconImageUrl); - } else { - FetchUserData.fetchUserData(retrofit, userName, new FetchUserData.FetchUserDataListener() { - @Override - public void onFetchUserDataSuccess(UserData userData) { - new InsertUserDataAsyncTask(userDao, userData, () -> loadUserDataAsyncTaskListener.loadUserDataSuccess(userData.getIconUrl())).execute(); - } - - @Override - public void onFetchUserDataFailed() { - loadUserDataAsyncTaskListener.loadUserDataSuccess(null); - } - }); - } - } - - public interface LoadUserDataAsyncTaskListener { - void loadUserDataSuccess(String iconImageUrl); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ParseAndInsertNewAccount.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ParseAndInsertNewAccount.java new file mode 100644 index 00000000..b742f983 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ParseAndInsertNewAccount.java @@ -0,0 +1,29 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.account.Account; +import ml.docilealligator.infinityforreddit.account.AccountDao; + +public class ParseAndInsertNewAccount { + + public static void parseAndInsertNewAccount(Executor executor, Handler handler, String username, + String accessToken, String refreshToken, String profileImageUrl, + String bannerImageUrl, int karma, String code, AccountDao accountDao, + ParseAndInsertAccountListener parseAndInsertAccountListener) { + executor.execute(() -> { + Account account = new Account(username, accessToken, refreshToken, code, profileImageUrl, + bannerImageUrl, karma, true); + accountDao.markAllAccountsNonCurrent(); + accountDao.insert(account); + + handler.post(parseAndInsertAccountListener::success); + }); + } + + public interface ParseAndInsertAccountListener { + void success(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ParseAndInsertNewAccountAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ParseAndInsertNewAccountAsyncTask.java deleted file mode 100644 index 7563803e..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/ParseAndInsertNewAccountAsyncTask.java +++ /dev/null @@ -1,50 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import ml.docilealligator.infinityforreddit.account.Account; -import ml.docilealligator.infinityforreddit.account.AccountDao; - -public class ParseAndInsertNewAccountAsyncTask extends AsyncTask<Void, Void, Void> { - - private String username; - private String accessToken; - private String refreshToken; - private String profileImageUrl; - private String bannerImageUrl; - private int karma; - private String code; - private AccountDao accountDao; - private ParseAndInsertAccountListener parseAndInsertAccountListener; - public ParseAndInsertNewAccountAsyncTask(String username, String accessToken, String refreshToken, String profileImageUrl, String bannerImageUrl, - int karma, String code, AccountDao accountDao, - ParseAndInsertAccountListener parseAndInsertAccountListener) { - this.username = username; - this.accessToken = accessToken; - this.refreshToken = refreshToken; - this.profileImageUrl = profileImageUrl; - this.bannerImageUrl = bannerImageUrl; - this.karma = karma; - this.code = code; - this.accountDao = accountDao; - this.parseAndInsertAccountListener = parseAndInsertAccountListener; - } - - @Override - protected Void doInBackground(Void... voids) { - Account account = new Account(username, accessToken, refreshToken, code, profileImageUrl, - bannerImageUrl, karma, true); - accountDao.markAllAccountsNonCurrent(); - accountDao.insert(account); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - parseAndInsertAccountListener.success(); - } - - public interface ParseAndInsertAccountListener { - void success(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveBitmapImageToFile.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveBitmapImageToFile.java new file mode 100644 index 00000000..c5388f08 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveBitmapImageToFile.java @@ -0,0 +1,35 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.graphics.Bitmap; +import android.os.Handler; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.concurrent.Executor; + +public class SaveBitmapImageToFile { + + public static void SaveBitmapImageToFile(Executor executor, Handler handler, Bitmap resource, String cacheDirPath, String fileName, + SaveBitmapImageToFileListener saveBitmapImageToFileListener) { + executor.execute(() -> { + try { + File imageFile = new File(cacheDirPath, fileName); + OutputStream outputStream = new FileOutputStream(imageFile); + resource.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); + outputStream.flush(); + outputStream.close(); + + handler.post(() -> saveBitmapImageToFileListener.saveSuccess(imageFile)); + } catch (IOException e) { + handler.post(saveBitmapImageToFileListener::saveFailed); + } + }); + } + + public interface SaveBitmapImageToFileListener { + void saveSuccess(File imageFile); + void saveFailed(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveBitmapImageToFileAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveBitmapImageToFileAsyncTask.java deleted file mode 100644 index 7af3fba4..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveBitmapImageToFileAsyncTask.java +++ /dev/null @@ -1,55 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.graphics.Bitmap; -import android.os.AsyncTask; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class SaveBitmapImageToFileAsyncTask extends AsyncTask<Void, Void, Void> { - private Bitmap resource; - private String cacheDirPath; - private String fileName; - private SaveBitmapImageToFileAsyncTaskListener saveBitmapImageToFileAsyncTaskListener; - private boolean saveSuccess = true; - private File imageFile; - - public SaveBitmapImageToFileAsyncTask(Bitmap resource, String cacheDirPath, String fileName, - SaveBitmapImageToFileAsyncTaskListener saveBitmapImageToFileAsyncTaskListener) { - this.resource = resource; - this.cacheDirPath = cacheDirPath; - this.fileName = fileName; - this.saveBitmapImageToFileAsyncTaskListener = saveBitmapImageToFileAsyncTaskListener; - } - - public interface SaveBitmapImageToFileAsyncTaskListener { - void saveSuccess(File imageFile); - void saveFailed(); - } - - @Override - protected Void doInBackground(Void... voids) { - try { - imageFile = new File(cacheDirPath, fileName); - OutputStream outputStream = new FileOutputStream(imageFile); - resource.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); - outputStream.flush(); - outputStream.close(); - } catch (IOException e) { - saveSuccess = false; - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (saveSuccess) { - saveBitmapImageToFileAsyncTaskListener.saveSuccess(imageFile); - } else { - saveBitmapImageToFileAsyncTaskListener.saveFailed(); - } - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveGIFToFile.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveGIFToFile.java new file mode 100644 index 00000000..e4b61364 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveGIFToFile.java @@ -0,0 +1,40 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.os.Handler; + +import com.bumptech.glide.load.resource.gif.GifDrawable; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.Executor; + +public class SaveGIFToFile { + + public static void saveGifToFile(Executor executor, Handler handler, GifDrawable resource, + String cacheDirPath, String fileName, + SaveGIFToFileAsyncTaskListener saveImageToFileAsyncTaskListener) { + executor.execute(() -> { + try { + File imageFile = new File(cacheDirPath, fileName); + ByteBuffer byteBuffer = resource.getBuffer(); + OutputStream outputStream = new FileOutputStream(imageFile); + byte[] bytes = new byte[byteBuffer.capacity()]; + ((ByteBuffer) byteBuffer.duplicate().clear()).get(bytes); + outputStream.write(bytes, 0, bytes.length); + outputStream.close(); + + handler.post(() -> saveImageToFileAsyncTaskListener.saveSuccess(imageFile)); + } catch (IOException e) { + handler.post(saveImageToFileAsyncTaskListener::saveFailed); + } + }); + } + + public interface SaveGIFToFileAsyncTaskListener { + void saveSuccess(File imageFile); + void saveFailed(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveGIFToFileAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveGIFToFileAsyncTask.java deleted file mode 100644 index 52a86e2c..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SaveGIFToFileAsyncTask.java +++ /dev/null @@ -1,59 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.os.AsyncTask; - -import com.bumptech.glide.load.resource.gif.GifDrawable; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -public class SaveGIFToFileAsyncTask extends AsyncTask<Void, Void, Void> { - private GifDrawable resource; - private String cacheDirPath; - private String fileName; - private SaveGIFToFileAsyncTaskListener saveImageToFileAsyncTaskListener; - private boolean saveSuccess = true; - private File imageFile; - - public SaveGIFToFileAsyncTask(GifDrawable resource, String cacheDirPath, String fileName, - SaveGIFToFileAsyncTaskListener saveImageToFileAsyncTaskListener) { - this.resource = resource; - this.cacheDirPath = cacheDirPath; - this.fileName = fileName; - this.saveImageToFileAsyncTaskListener = saveImageToFileAsyncTaskListener; - } - - public interface SaveGIFToFileAsyncTaskListener { - void saveSuccess(File imageFile); - void saveFailed(); - } - - @Override - protected Void doInBackground(Void... voids) { - try { - imageFile = new File(cacheDirPath, fileName); - ByteBuffer byteBuffer = resource.getBuffer(); - OutputStream outputStream = new FileOutputStream(imageFile); - byte[] bytes = new byte[byteBuffer.capacity()]; - ((ByteBuffer) byteBuffer.duplicate().clear()).get(bytes); - outputStream.write(bytes, 0, bytes.length); - outputStream.close(); - } catch (IOException e) { - saveSuccess = false; - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (saveSuccess) { - saveImageToFileAsyncTaskListener.saveSuccess(imageFile); - } else { - saveImageToFileAsyncTaskListener.saveFailed(); - } - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SetAsWallpaper.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SetAsWallpaper.java new file mode 100644 index 00000000..f19a3cdb --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SetAsWallpaper.java @@ -0,0 +1,77 @@ +package ml.docilealligator.infinityforreddit.asynctasks; + +import android.app.WallpaperManager; +import android.graphics.Bitmap; +import android.graphics.Rect; +import android.media.ThumbnailUtils; +import android.os.Build; +import android.os.Handler; +import android.util.DisplayMetrics; +import android.view.WindowManager; + +import java.io.IOException; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.WallpaperSetter; + +public class SetAsWallpaper { + + public static void setAsWallpaper(Executor executor, Handler handler, Bitmap bitmap, int setTo, + WallpaperManager manager, WindowManager windowManager, + WallpaperSetter.SetWallpaperListener setWallpaperListener) { + executor.execute(new Runnable() { + @Override + public void run() { + DisplayMetrics metrics = new DisplayMetrics(); + Rect rect = null; + Bitmap bitmapFinal = bitmap; + + if (windowManager != null) { + windowManager.getDefaultDisplay().getMetrics(metrics); + int height = metrics.heightPixels; + int width = metrics.widthPixels; + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + bitmapFinal = ThumbnailUtils.extractThumbnail(bitmapFinal, width, height); + } + + float imageAR = (float) bitmapFinal.getWidth() / (float) bitmapFinal.getHeight(); + float screenAR = (float) width / (float) height; + + if (imageAR > screenAR) { + int desiredWidth = (int) (bitmapFinal.getHeight() * screenAR); + rect = new Rect((bitmapFinal.getWidth() - desiredWidth) / 2, 0, bitmapFinal.getWidth(), bitmapFinal.getHeight()); + } else { + int desiredHeight = (int) (bitmapFinal.getWidth() / screenAR); + rect = new Rect(0, (bitmapFinal.getHeight() - desiredHeight) / 2, bitmapFinal.getWidth(), (bitmapFinal.getHeight() + desiredHeight) / 2); + } + } + try { + switch (setTo) { + case WallpaperSetter.HOME_SCREEN: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(bitmapFinal, rect, true, WallpaperManager.FLAG_SYSTEM); + } + break; + case WallpaperSetter.LOCK_SCREEN: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(bitmapFinal, rect, true, WallpaperManager.FLAG_LOCK); + } + break; + case WallpaperSetter.BOTH_SCREENS: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(bitmapFinal, rect, true, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK); + } else { + manager.setBitmap(bitmapFinal); + } + break; + } + + handler.post(setWallpaperListener::success); + } catch (IOException e) { + handler.post(setWallpaperListener::failed); + } + } + }); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SetAsWallpaperAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SetAsWallpaperAsyncTask.java deleted file mode 100644 index c613cb9c..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/SetAsWallpaperAsyncTask.java +++ /dev/null @@ -1,95 +0,0 @@ -package ml.docilealligator.infinityforreddit.asynctasks; - -import android.app.WallpaperManager; -import android.graphics.Bitmap; -import android.graphics.Rect; -import android.media.ThumbnailUtils; -import android.os.AsyncTask; -import android.os.Build; -import android.util.DisplayMetrics; -import android.view.WindowManager; - -import java.io.IOException; - -import ml.docilealligator.infinityforreddit.WallpaperSetter; - -public class SetAsWallpaperAsyncTask extends AsyncTask<Void, Void, Void> { - - private Bitmap bitmap; - private int setTo; - private WallpaperManager manager; - private WindowManager windowManager; - private WallpaperSetter.SetWallpaperListener setWallpaperListener; - private boolean success = true; - - public SetAsWallpaperAsyncTask(Bitmap bitmap, int setTo, WallpaperManager manager, WindowManager windowManager, - WallpaperSetter.SetWallpaperListener setWallpaperListener) { - this.bitmap = bitmap; - this.setTo = setTo; - this.manager = manager; - this.windowManager = windowManager; - this.setWallpaperListener = setWallpaperListener; - } - - @Override - protected Void doInBackground(Void... voids) { - DisplayMetrics metrics = new DisplayMetrics(); - Rect rect = null; - - if (windowManager != null) { - windowManager.getDefaultDisplay().getMetrics(metrics); - int height = metrics.heightPixels; - int width = metrics.widthPixels; - - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height); - } - - float imageAR = (float) bitmap.getWidth() / (float) bitmap.getHeight(); - float screenAR = (float) width / (float) height; - - if (imageAR > screenAR) { - int desiredWidth = (int) (bitmap.getHeight() * screenAR); - rect = new Rect((bitmap.getWidth() - desiredWidth) / 2, 0, bitmap.getWidth(), bitmap.getHeight()); - } else { - int desiredHeight = (int) (bitmap.getWidth() / screenAR); - rect = new Rect(0, (bitmap.getHeight() - desiredHeight) / 2, bitmap.getWidth(), (bitmap.getHeight() + desiredHeight) / 2); - } - } - try { - switch (setTo) { - case WallpaperSetter.HOME_SCREEN: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(bitmap, rect, true, WallpaperManager.FLAG_SYSTEM); - } - break; - case WallpaperSetter.LOCK_SCREEN: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(bitmap, rect, true, WallpaperManager.FLAG_LOCK); - } - break; - case WallpaperSetter.BOTH_SCREENS: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(bitmap, rect, true, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK); - } else { - manager.setBitmap(bitmap); - } - break; - } - } catch (IOException e) { - success = false; - } - - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (success) { - setWallpaperListener.success(); - } else { - setWallpaperListener.failed(); - } - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java index a740116c..38726cd8 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java @@ -24,20 +24,22 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.fastscroll.FastScrollerBuilder; -import ml.docilealligator.infinityforreddit.activities.BaseActivity; -import ml.docilealligator.infinityforreddit.activities.SubscribedThingListingActivity; -import ml.docilealligator.infinityforreddit.adapters.FollowedUsersRecyclerViewAdapter; -import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.FragmentCommunicator; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.activities.BaseActivity; +import ml.docilealligator.infinityforreddit.activities.SubscribedThingListingActivity; +import ml.docilealligator.infinityforreddit.adapters.FollowedUsersRecyclerViewAdapter; +import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserViewModel; import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; import retrofit2.Retrofit; @@ -70,7 +72,9 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo @Inject RedditDataRoomDatabase mRedditDataRoomDatabase; @Inject - CustomThemeWrapper customThemeWrapper; + CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; SubscribedUserViewModel mSubscribedUserViewModel; private Activity mActivity; private RequestManager mGlide; @@ -108,7 +112,7 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo mLinearLayoutManager = new LinearLayoutManager(mActivity); mRecyclerView.setLayoutManager(mLinearLayoutManager); FollowedUsersRecyclerViewAdapter adapter = new FollowedUsersRecyclerViewAdapter(mActivity, - mOauthRetrofit, mRedditDataRoomDatabase, customThemeWrapper, + mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, getArguments().getString(EXTRA_ACCESS_TOKEN)); mRecyclerView.setAdapter(adapter); new FastScrollerBuilder(mRecyclerView).build(); @@ -117,7 +121,7 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo new SubscribedUserViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, getArguments().getString(EXTRA_ACCOUNT_NAME))) .get(SubscribedUserViewModel.class); - mSubscribedUserViewModel.getAllSubscribedUsers().observe(this, subscribedUserData -> { + mSubscribedUserViewModel.getAllSubscribedUsers().observe(getViewLifecycleOwner(), subscribedUserData -> { mSwipeRefreshLayout.setRefreshing(false); if (subscribedUserData == null || subscribedUserData.size() == 0) { mRecyclerView.setVisibility(View.GONE); @@ -131,7 +135,7 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo adapter.setSubscribedUsers(subscribedUserData); }); - mSubscribedUserViewModel.getAllFavoriteSubscribedUsers().observe(this, favoriteSubscribedUserData -> { + mSubscribedUserViewModel.getAllFavoriteSubscribedUsers().observe(getViewLifecycleOwner(), favoriteSubscribedUserData -> { mSwipeRefreshLayout.setRefreshing(false); if (favoriteSubscribedUserData != null && favoriteSubscribedUserData.size() > 0) { mLinearLayout.setVisibility(View.GONE); @@ -159,12 +163,12 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo public void applyTheme() { if (mActivity instanceof SubscribedThingListingActivity) { mSwipeRefreshLayout.setOnRefreshListener(() -> ((SubscribedThingListingActivity) mActivity).loadSubscriptions(true)); - mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(customThemeWrapper.getCircularProgressBarBackground()); - mSwipeRefreshLayout.setColorSchemeColors(customThemeWrapper.getColorAccent()); + mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); + mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); } else { mSwipeRefreshLayout.setEnabled(false); } - mErrorTextView.setTextColor(customThemeWrapper.getSecondaryTextColor()); + mErrorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor()); } public void goBackToTop() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java index 28f9a0bf..9c86135c 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java @@ -24,6 +24,8 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; @@ -72,6 +74,8 @@ public class MultiRedditListingFragment extends Fragment implements FragmentComm Retrofit mOauthRetrofit; @Inject CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; public MultiRedditViewModel mMultiRedditViewModel; private AppCompatActivity mActivity; @@ -113,7 +117,8 @@ public class MultiRedditListingFragment extends Fragment implements FragmentComm mLinearLayoutManager = new LinearLayoutManager(mActivity); mRecyclerView.setLayoutManager(mLinearLayoutManager); MultiRedditListingRecyclerViewAdapter adapter = new MultiRedditListingRecyclerViewAdapter(mActivity, - mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, accessToken, new MultiRedditListingRecyclerViewAdapter.OnItemClickListener() { + mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, accessToken, + new MultiRedditListingRecyclerViewAdapter.OnItemClickListener() { @Override public void onClick(MultiReddit multiReddit) { if (mActivity instanceof MultiredditSelectionActivity) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java index 0f1ee2d8..eb69cbee 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java @@ -437,7 +437,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime)); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SEARCH_POST, defaultPostLayout); - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mGfycatRetrofit, + mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mRetrofit, mGfycatRetrofit, mRedgifsRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, locale, windowWidth, accessToken, accountName, postType, postLayout, true, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, @@ -503,7 +503,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { sortType = new SortType(SortType.Type.valueOf(sort)); } - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mGfycatRetrofit, + mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mRetrofit, mGfycatRetrofit, mRedgifsRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, locale, windowWidth, accessToken, accountName, postType, postLayout, displaySubredditName, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, @@ -567,7 +567,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { sortType = new SortType(SortType.Type.valueOf(sort)); } - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mGfycatRetrofit, + mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mRetrofit, mGfycatRetrofit, mRedgifsRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, locale, windowWidth, accessToken, accountName, postType, postLayout, true, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, @@ -631,7 +631,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { } postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_USER_POST_BASE + username, defaultPostLayout); - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mGfycatRetrofit, + mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mRetrofit, mGfycatRetrofit, mRedgifsRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, locale, windowWidth, accessToken, accountName, postType, postLayout, true, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, @@ -686,7 +686,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { } postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST, defaultPostLayout); - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mGfycatRetrofit, + mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mRetrofit, mGfycatRetrofit, mRedgifsRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, locale, windowWidth, accessToken, accountName, postType, postLayout, true, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, @@ -1061,6 +1061,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator { } } + public ArrayList<Post> getPostList() { + return new ArrayList<>(mPostViewModel.getPosts().getValue()); + } + @Override public void onAttach(@NonNull Context context) { super.onAttach(context); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java index b6fb5795..0e76c543 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java @@ -5,6 +5,7 @@ import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; +import android.os.Handler; import android.text.Spanned; import android.text.style.SuperscriptSpan; import android.text.util.Linkify; @@ -23,6 +24,8 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import org.commonmark.ext.gfm.tables.TableBlock; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; @@ -45,7 +48,7 @@ import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.activities.LinkResolverActivity; import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivity; -import ml.docilealligator.infinityforreddit.asynctasks.InsertSubredditDataAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertSubredditData; import ml.docilealligator.infinityforreddit.bottomsheetfragments.UrlMenuBottomSheetFragment; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData; @@ -72,6 +75,8 @@ public class SidebarFragment extends Fragment { RedditDataRoomDatabase mRedditDataRoomDatabase; @Inject CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; public SidebarFragment() { // Required empty public constructor @@ -189,7 +194,8 @@ public class SidebarFragment extends Fragment { @Override public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { swipeRefreshLayout.setRefreshing(false); - new InsertSubredditDataAsyncTask(mRedditDataRoomDatabase, subredditData, () -> swipeRefreshLayout.setRefreshing(false)).execute(); + InsertSubredditData.insertSubredditData(mExecutor, new Handler(), mRedditDataRoomDatabase, + subredditData, () -> swipeRefreshLayout.setRefreshing(false)); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java index 996739dc..99fc5ec4 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java @@ -25,6 +25,8 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; @@ -88,7 +90,9 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun @Named("nsfw_and_spoiler") SharedPreferences mNsfwAndSpoilerSharedPreferences; @Inject - CustomThemeWrapper customThemeWrapper; + CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; private LinearLayoutManager mLinearLayoutManager; private SubredditListingRecyclerViewAdapter mAdapter; private Activity mActivity; @@ -135,8 +139,8 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun sortType = new SortType(SortType.Type.valueOf(sort.toUpperCase())); boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false); - mAdapter = new SubredditListingRecyclerViewAdapter(mActivity, mOauthRetrofit, mRetrofit, - customThemeWrapper, accessToken, accountName, mRedditDataRoomDatabase, + mAdapter = new SubredditListingRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRetrofit, + mCustomThemeWrapper, accessToken, accountName, mRedditDataRoomDatabase, new SubredditListingRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { @@ -236,9 +240,9 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun @Override public void applyTheme() { - mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(customThemeWrapper.getCircularProgressBarBackground()); - mSwipeRefreshLayout.setColorSchemeColors(customThemeWrapper.getColorAccent()); - mFetchSubredditListingInfoTextView.setTextColor(customThemeWrapper.getSecondaryTextColor()); + mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); + mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); + mFetchSubredditListingInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor()); } public void goBackToTop() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java index 6279bae5..5275cb87 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java @@ -24,6 +24,8 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; @@ -74,7 +76,9 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra @Inject RedditDataRoomDatabase mRedditDataRoomDatabase; @Inject - CustomThemeWrapper customThemeWrapper; + CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; public SubscribedSubredditViewModel mSubscribedSubredditViewModel; private Activity mActivity; private RequestManager mGlide; @@ -116,12 +120,12 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra SubscribedSubredditsRecyclerViewAdapter adapter; if (getArguments().getBoolean(EXTRA_IS_SUBREDDIT_SELECTION)) { - adapter = new SubscribedSubredditsRecyclerViewAdapter(mActivity, mOauthRetrofit, mRedditDataRoomDatabase, - customThemeWrapper, accessToken, getArguments().getBoolean(EXTRA_EXTRA_CLEAR_SELECTION), + adapter = new SubscribedSubredditsRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, + mCustomThemeWrapper, accessToken, getArguments().getBoolean(EXTRA_EXTRA_CLEAR_SELECTION), (name, iconUrl, subredditIsUser) -> ((SubredditSelectionActivity) mActivity).getSelectedSubreddit(name, iconUrl, subredditIsUser)); } else { - adapter = new SubscribedSubredditsRecyclerViewAdapter(mActivity, mOauthRetrofit, mRedditDataRoomDatabase, - customThemeWrapper, accessToken); + adapter = new SubscribedSubredditsRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, + mCustomThemeWrapper, accessToken); } mRecyclerView.setAdapter(adapter); @@ -130,7 +134,7 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra mSubscribedSubredditViewModel = new ViewModelProvider(this, new SubscribedSubredditViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, accountName)) .get(SubscribedSubredditViewModel.class); - mSubscribedSubredditViewModel.getAllSubscribedSubreddits().observe(this, subscribedSubredditData -> { + mSubscribedSubredditViewModel.getAllSubscribedSubreddits().observe(getViewLifecycleOwner(), subscribedSubredditData -> { mSwipeRefreshLayout.setRefreshing(false); if (subscribedSubredditData == null || subscribedSubredditData.size() == 0) { mRecyclerView.setVisibility(View.GONE); @@ -146,7 +150,7 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra adapter.setSubscribedSubreddits(subscribedSubredditData); }); - mSubscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(this, favoriteSubscribedSubredditData -> { + mSubscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(getViewLifecycleOwner(), favoriteSubscribedSubredditData -> { mSwipeRefreshLayout.setRefreshing(false); if (favoriteSubscribedSubredditData != null && favoriteSubscribedSubredditData.size() > 0) { mLinearLayout.setVisibility(View.GONE); @@ -175,12 +179,12 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra public void applyTheme() { if (mActivity instanceof SubscribedThingListingActivity) { mSwipeRefreshLayout.setOnRefreshListener(() -> ((SubscribedThingListingActivity) mActivity).loadSubscriptions(true)); - mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(customThemeWrapper.getCircularProgressBarBackground()); - mSwipeRefreshLayout.setColorSchemeColors(customThemeWrapper.getColorAccent()); + mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); + mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); } else { mSwipeRefreshLayout.setEnabled(false); } - mErrorTextView.setTextColor(customThemeWrapper.getSecondaryTextColor()); + mErrorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor()); } public void goBackToTop() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java index f6d9ceb1..b1c09395 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java @@ -25,6 +25,8 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; @@ -88,7 +90,9 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato @Named("nsfw_and_spoiler") SharedPreferences mNsfwAndSpoilerSharedPreferences; @Inject - CustomThemeWrapper customThemeWrapper; + CustomThemeWrapper mCustomThemeWrapper; + @Inject + Executor mExecutor; private LinearLayoutManager mLinearLayoutManager; private String mQuery; private UserListingRecyclerViewAdapter mAdapter; @@ -135,8 +139,8 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato sortType = new SortType(SortType.Type.valueOf(sort.toUpperCase())); boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false); - mAdapter = new UserListingRecyclerViewAdapter(getActivity(), mOauthRetrofit, mRetrofit, - customThemeWrapper, accessToken, accountName, mRedditDataRoomDatabase.subscribedUserDao(), + mAdapter = new UserListingRecyclerViewAdapter(getActivity(), mExecutor, mOauthRetrofit, mRetrofit, + mCustomThemeWrapper, accessToken, accountName, mRedditDataRoomDatabase, new UserListingRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { @@ -238,9 +242,9 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato @Override public void applyTheme() { - mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(customThemeWrapper.getCircularProgressBarBackground()); - mSwipeRefreshLayout.setColorSchemeColors(customThemeWrapper.getColorAccent()); - mFetchUserListingInfoTextView.setTextColor(customThemeWrapper.getSecondaryTextColor()); + mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); + mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); + mFetchUserListingInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor()); } public void goBackToTop() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java index df4c01cb..0dcf1f01 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java @@ -9,6 +9,7 @@ import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -37,17 +38,21 @@ import com.davemorrissey.labs.subscaleview.ImageSource; import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView; import java.io.File; +import java.util.concurrent.Executor; + +import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; -import ml.docilealligator.infinityforreddit.activities.ViewImgurMediaActivity; -import ml.docilealligator.infinityforreddit.asynctasks.SaveBitmapImageToFileAsyncTask; -import ml.docilealligator.infinityforreddit.bottomsheetfragments.SetAsWallpaperBottomSheetFragment; import ml.docilealligator.infinityforreddit.BuildConfig; import ml.docilealligator.infinityforreddit.ImgurMedia; +import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.services.DownloadMediaService; import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; +import ml.docilealligator.infinityforreddit.activities.ViewImgurMediaActivity; +import ml.docilealligator.infinityforreddit.asynctasks.SaveBitmapImageToFile; +import ml.docilealligator.infinityforreddit.bottomsheetfragments.SetAsWallpaperBottomSheetFragment; +import ml.docilealligator.infinityforreddit.services.DownloadMediaService; public class ViewImgurImageFragment extends Fragment { @@ -60,6 +65,8 @@ public class ViewImgurImageFragment extends Fragment { SubsamplingScaleImageView imageView; @BindView(R.id.load_image_error_linear_layout_view_imgur_image_fragment) LinearLayout errorLinearLayout; + @Inject + Executor mExecutor; private ViewImgurMediaActivity activity; private RequestManager glide; @@ -76,6 +83,8 @@ public class ViewImgurImageFragment extends Fragment { Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_view_imgur_images, container, false); + ((Infinity) activity.getApplication()).getAppComponent().inject(this); + ButterKnife.bind(this, rootView); setHasOptionsMenu(true); @@ -150,83 +159,83 @@ public class ViewImgurImageFragment extends Fragment { @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.action_download_view_imgur_image_fragment: - if (isDownloading) { - return false; - } + int itemId = item.getItemId(); + if (itemId == R.id.action_download_view_imgur_image_fragment) { + if (isDownloading) { + return false; + } - isDownloading = true; + isDownloading = true; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (ContextCompat.checkSelfPermission(activity, - Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (ContextCompat.checkSelfPermission(activity, + Manifest.permission.WRITE_EXTERNAL_STORAGE) + != PackageManager.PERMISSION_GRANTED) { - // Permission is not granted - // No explanation needed; request the permission - requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, - PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); - } else { - // Permission has already been granted - download(); - } + // Permission is not granted + // No explanation needed; request the permission + requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, + PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); } else { + // Permission has already been granted download(); } + } else { + download(); + } - return true; - case R.id.action_share_view_imgur_image_fragment: - glide.asBitmap().load(imgurMedia.getLink()).into(new CustomTarget<Bitmap>() { - - @Override - public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { - if (activity.getExternalCacheDir() != null) { - Toast.makeText(activity, R.string.save_image_first, Toast.LENGTH_SHORT).show(); - new SaveBitmapImageToFileAsyncTask(resource, activity.getExternalCacheDir().getPath(), - imgurMedia.getFileName(), - new SaveBitmapImageToFileAsyncTask.SaveBitmapImageToFileAsyncTaskListener() { - @Override - public void saveSuccess(File imageFile) { - Uri uri = FileProvider.getUriForFile(activity, - BuildConfig.APPLICATION_ID + ".provider", imageFile); - Intent shareIntent = new Intent(); - shareIntent.setAction(Intent.ACTION_SEND); - shareIntent.putExtra(Intent.EXTRA_STREAM, uri); - shareIntent.setType("image/*"); - shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); - } - - @Override - public void saveFailed() { - Toast.makeText(activity, - R.string.cannot_save_image, Toast.LENGTH_SHORT).show(); - } - }).execute(); - } else { - Toast.makeText(activity, - R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); - } + return true; + } else if (itemId == R.id.action_share_view_imgur_image_fragment) { + glide.asBitmap().load(imgurMedia.getLink()).into(new CustomTarget<Bitmap>() { + + @Override + public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { + if (activity.getExternalCacheDir() != null) { + Toast.makeText(activity, R.string.save_image_first, Toast.LENGTH_SHORT).show(); + SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, new Handler(), resource, activity.getExternalCacheDir().getPath(), + imgurMedia.getFileName(), + new SaveBitmapImageToFile.SaveBitmapImageToFileListener() { + @Override + public void saveSuccess(File imageFile) { + Uri uri = FileProvider.getUriForFile(activity, + BuildConfig.APPLICATION_ID + ".provider", imageFile); + Intent shareIntent = new Intent(); + shareIntent.setAction(Intent.ACTION_SEND); + shareIntent.putExtra(Intent.EXTRA_STREAM, uri); + shareIntent.setType("image/*"); + shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); + } + + @Override + public void saveFailed() { + Toast.makeText(activity, + R.string.cannot_save_image, Toast.LENGTH_SHORT).show(); + } + }); + } else { + Toast.makeText(activity, + R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); } + } - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { + @Override + public void onLoadCleared(@Nullable Drawable placeholder) { - } - }); - return true; - case R.id.action_set_wallpaper_view_imgur_image_fragment: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - SetAsWallpaperBottomSheetFragment setAsWallpaperBottomSheetFragment = new SetAsWallpaperBottomSheetFragment(); - Bundle bundle = new Bundle(); - bundle.putInt(SetAsWallpaperBottomSheetFragment.EXTRA_VIEW_PAGER_POSITION, activity.getCurrentPagePosition()); - setAsWallpaperBottomSheetFragment.setArguments(bundle); - setAsWallpaperBottomSheetFragment.show(activity.getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); - } else { - ((SetAsWallpaperCallback) activity).setToBoth(activity.getCurrentPagePosition()); } - return true; + }); + return true; + } else if (itemId == R.id.action_set_wallpaper_view_imgur_image_fragment) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + SetAsWallpaperBottomSheetFragment setAsWallpaperBottomSheetFragment = new SetAsWallpaperBottomSheetFragment(); + Bundle bundle = new Bundle(); + bundle.putInt(SetAsWallpaperBottomSheetFragment.EXTRA_VIEW_PAGER_POSITION, activity.getCurrentPagePosition()); + setAsWallpaperBottomSheetFragment.setArguments(bundle); + setAsWallpaperBottomSheetFragment.show(activity.getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); + } else { + ((SetAsWallpaperCallback) activity).setToBoth(activity.getCurrentPagePosition()); + } + return true; } return false; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java new file mode 100644 index 00000000..f4f6e49c --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java @@ -0,0 +1,1739 @@ +package ml.docilealligator.infinityforreddit.fragments; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.graphics.Canvas; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.util.DisplayMetrics; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.view.menu.MenuItemImpl; +import androidx.core.content.ContextCompat; +import androidx.core.content.res.ResourcesCompat; +import androidx.core.graphics.drawable.DrawableCompat; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.ItemTouchHelper; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.LinearSmoothScroller; +import androidx.recyclerview.widget.RecyclerView; +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; +import androidx.transition.AutoTransition; +import androidx.transition.TransitionManager; + +import com.bumptech.glide.Glide; +import com.bumptech.glide.RequestManager; +import com.evernote.android.state.State; +import com.google.android.material.dialog.MaterialAlertDialogBuilder; +import com.livefront.bridge.Bridge; + +import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.Subscribe; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.Executor; + +import javax.inject.Inject; +import javax.inject.Named; + +import butterknife.BindView; +import butterknife.ButterKnife; +import im.ene.toro.exoplayer.ExoCreator; +import im.ene.toro.media.PlaybackInfo; +import im.ene.toro.media.VolumeInfo; +import ml.docilealligator.infinityforreddit.DeleteThing; +import ml.docilealligator.infinityforreddit.Flair; +import ml.docilealligator.infinityforreddit.FragmentCommunicator; +import ml.docilealligator.infinityforreddit.Infinity; +import ml.docilealligator.infinityforreddit.R; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.SaveThing; +import ml.docilealligator.infinityforreddit.SortType; +import ml.docilealligator.infinityforreddit.activities.CommentActivity; +import ml.docilealligator.infinityforreddit.activities.EditPostActivity; +import ml.docilealligator.infinityforreddit.activities.GiveAwardActivity; +import ml.docilealligator.infinityforreddit.activities.ReportActivity; +import ml.docilealligator.infinityforreddit.activities.SubmitCrosspostActivity; +import ml.docilealligator.infinityforreddit.activities.ViewPostDetailActivity; +import ml.docilealligator.infinityforreddit.adapters.CommentAndPostRecyclerViewAdapter; +import ml.docilealligator.infinityforreddit.apis.RedditAPI; +import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment; +import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostCommentSortTypeBottomSheetFragment; +import ml.docilealligator.infinityforreddit.comment.Comment; +import ml.docilealligator.infinityforreddit.comment.FetchComment; +import ml.docilealligator.infinityforreddit.comment.FetchRemovedComment; +import ml.docilealligator.infinityforreddit.comment.ParseComment; +import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; +import ml.docilealligator.infinityforreddit.customviews.CustomToroContainer; +import ml.docilealligator.infinityforreddit.events.ChangeNSFWBlurEvent; +import ml.docilealligator.infinityforreddit.events.ChangeNetworkStatusEvent; +import ml.docilealligator.infinityforreddit.events.ChangeSpoilerBlurEvent; +import ml.docilealligator.infinityforreddit.events.PostUpdateEventToDetailActivity; +import ml.docilealligator.infinityforreddit.events.PostUpdateEventToPostList; +import ml.docilealligator.infinityforreddit.message.ReadMessage; +import ml.docilealligator.infinityforreddit.post.FetchPost; +import ml.docilealligator.infinityforreddit.post.FetchRemovedPost; +import ml.docilealligator.infinityforreddit.post.HidePost; +import ml.docilealligator.infinityforreddit.post.ParsePost; +import ml.docilealligator.infinityforreddit.post.Post; +import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData; +import ml.docilealligator.infinityforreddit.subreddit.SubredditData; +import ml.docilealligator.infinityforreddit.utils.APIUtils; +import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; +import ml.docilealligator.infinityforreddit.utils.Utils; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; + +import static im.ene.toro.media.PlaybackInfo.INDEX_UNSET; +import static im.ene.toro.media.PlaybackInfo.TIME_UNSET; +import static ml.docilealligator.infinityforreddit.activities.CommentActivity.RETURN_EXTRA_COMMENT_DATA_KEY; +import static ml.docilealligator.infinityforreddit.activities.CommentActivity.WRITE_COMMENT_REQUEST_CODE; + +public class ViewPostDetailFragment extends Fragment implements FragmentCommunicator { + + public static final String EXTRA_POST_DATA = "EPD"; + public static final String EXTRA_POST_ID = "EPI"; + public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI"; + public static final String EXTRA_MESSAGE_FULLNAME = "EMF"; + public static final String EXTRA_POST_LIST_POSITION = "EPLP"; + private static final int EDIT_POST_REQUEST_CODE = 2; + + @BindView(R.id.swipe_refresh_layout_view_post_detail_fragment) + SwipeRefreshLayout mSwipeRefreshLayout; + @BindView(R.id.recycler_view_view_post_detail_fragment) + CustomToroContainer mRecyclerView; + @BindView(R.id.fetch_post_info_linear_layout_view_post_detail_fragment) + LinearLayout mFetchPostInfoLinearLayout; + @BindView(R.id.fetch_post_info_image_view_view_post_detail_fragment) + ImageView mFetchPostInfoImageView; + @BindView(R.id.fetch_post_info_text_view_view_post_detail_fragment) + TextView mFetchPostInfoTextView; + @Inject + @Named("no_oauth") + Retrofit mRetrofit; + @Inject + @Named("pushshift") + Retrofit pushshiftRetrofit; + @Inject + @Named("oauth") + Retrofit mOauthRetrofit; + @Inject + @Named("gfycat") + Retrofit mGfycatRetrofit; + @Inject + @Named("redgifs") + Retrofit mRedgifsRetrofit; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Inject + @Named("default") + SharedPreferences mSharedPreferences; + @Inject + @Named("sort_type") + SharedPreferences mSortTypeSharedPreferences; + @Inject + @Named("nsfw_and_spoiler") + SharedPreferences mNsfwAndSpoilerSharedPreferences; + @Inject + @Named("current_account") + SharedPreferences mCurrentAccountSharedPreferences; + @Inject + CustomThemeWrapper mCustomThemeWrapper; + @Inject + ExoCreator mExoCreator; + @Inject + Executor mExecutor; + @State + Post mPost; + @State + boolean isLoadingMoreChildren = false; + @State + boolean isRefreshing = false; + @State + boolean isSingleCommentThreadMode = false; + @State + ArrayList<Comment> comments; + @State + ArrayList<String> children; + @State + int mChildrenStartingIndex = 0; + @State + boolean loadMoreChildrenSuccess = true; + @State + boolean hasMoreChildren; + @State + boolean isFetchingComments = false; + @State + String mMessageFullname; + @State + String sortType; + @State + boolean mRespectSubredditRecommendedSortType; + private ViewPostDetailActivity activity; + private RequestManager mGlide; + private Locale mLocale; + private Menu mMenu; + private String mAccessToken; + private String mAccountName; + private int postListPosition = -1; + private String mSingleCommentId; + private boolean showToast = false; + private boolean isSortingComments = false; + private boolean mIsSmoothScrolling = false; + private boolean mLockFab; + private boolean mSwipeUpToHideFab; + private boolean mExpandChildren; + private int mWindowWidth; + private LinearLayoutManager mLinearLayoutManager; + private CommentAndPostRecyclerViewAdapter mAdapter; + private RecyclerView.SmoothScroller mSmoothScroller; + private Drawable mSavedIcon; + private Drawable mUnsavedIcon; + private ColorDrawable backgroundSwipeRight; + private ColorDrawable backgroundSwipeLeft; + private Drawable drawableSwipeRight; + private Drawable drawableSwipeLeft; + private int swipeLeftAction; + private int swipeRightAction; + private float swipeActionThreshold; + private ItemTouchHelper touchHelper; + + public ViewPostDetailFragment() { + // Required empty public constructor + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + View rootView = inflater.inflate(R.layout.fragment_view_post_detail, container, false); + + ((Infinity) activity.getApplication()).getAppComponent().inject(this); + + setHasOptionsMenu(true); + + Bridge.restoreInstanceState(this, savedInstanceState); + + ButterKnife.bind(this, rootView); + + EventBus.getDefault().register(this); + + applyTheme(); + + mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null); + mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null); + + mSavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_toolbar_24dp); + mUnsavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_border_toolbar_24dp); + + if (activity != null && activity.isImmersiveInterface()) { + mRecyclerView.setPadding(0, 0, 0, activity.getNavBarHeight() + mRecyclerView.getPaddingBottom()); + showToast = true; + } + + DisplayMetrics displayMetrics = new DisplayMetrics(); + activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); + mWindowWidth = displayMetrics.widthPixels; + + mLockFab = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_JUMP_TO_NEXT_TOP_LEVEL_COMMENT_BUTTON, false); + mSwipeUpToHideFab = mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_UP_TO_HIDE_JUMP_TO_NEXT_TOP_LEVEL_COMMENT_BUTTON, false); + mExpandChildren = !mSharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_TOP_LEVEL_COMMENTS_FIRST, false); + if (savedInstanceState == null) { + mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false); + } + + mGlide = Glide.with(this); + Resources resources = getResources(); + mLocale = getResources().getConfiguration().locale; + + mLinearLayoutManager = new LinearLayoutManager(activity); + mRecyclerView.setLayoutManager(mLinearLayoutManager); + + if (children != null && children.size() > 0) { + mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + if (!mIsSmoothScrolling && !mLockFab) { + if (!recyclerView.canScrollVertically(1)) { + activity.hideFab(); + } else { + if (dy > 0) { + if (mSwipeUpToHideFab) { + activity.showFab(); + } else { + activity.hideFab(); + } + } else { + if (mSwipeUpToHideFab) { + activity.hideFab(); + } else { + activity.showFab(); + } + } + } + } + + if (!isLoadingMoreChildren && loadMoreChildrenSuccess) { + int visibleItemCount = mLinearLayoutManager.getChildCount(); + int totalItemCount = mLinearLayoutManager.getItemCount(); + int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); + + if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { + fetchMoreComments(); + } + } + } + + @Override + public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + mIsSmoothScrolling = false; + } + } + }); + } else { + mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + if (!mIsSmoothScrolling && !mLockFab) { + if (!recyclerView.canScrollVertically(1)) { + activity.hideFab(); + } else { + if (dy > 0) { + if (mSwipeUpToHideFab) { + activity.showFab(); + } else { + activity.hideFab(); + } + } else { + if (mSwipeUpToHideFab) { + activity.hideFab(); + } else { + activity.showFab(); + } + } + } + } + } + + @Override + public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + mIsSmoothScrolling = false; + } + } + }); + } + + boolean enableSwipeAction = mSharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_SWIPE_ACTION, false); + boolean vibrateWhenActionTriggered = mSharedPreferences.getBoolean(SharedPreferencesUtils.VIBRATE_WHEN_ACTION_TRIGGERED, true); + swipeActionThreshold = Float.parseFloat(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_ACTION_THRESHOLD, "0.3")); + swipeRightAction = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_RIGHT_ACTION, "1")); + swipeLeftAction = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.SWIPE_LEFT_ACTION, "0")); + initializeSwipeActionDrawable(); + touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() { + boolean exceedThreshold = false; + + @Override + public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { + if (!(viewHolder instanceof CommentAndPostRecyclerViewAdapter.CommentViewHolder)) { + return makeMovementFlags(0, 0); + } + int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; + return makeMovementFlags(0, swipeFlags); + } + + @Override + public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { + return false; + } + + @Override + public boolean isItemViewSwipeEnabled() { + return true; + } + + @Override + public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { + if (touchHelper != null) { + touchHelper.attachToRecyclerView(null); + touchHelper.attachToRecyclerView(mRecyclerView); + if (mAdapter != null) { + mAdapter.onItemSwipe(viewHolder, direction, swipeLeftAction, swipeRightAction); + } + } + } + + @Override + public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { + super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); + + View itemView = viewHolder.itemView; + int horizontalOffset = (int) Utils.convertDpToPixel(16, activity); + if (dX > 0) { + if (dX > (itemView.getRight() - itemView.getLeft()) * swipeActionThreshold) { + if (!exceedThreshold) { + exceedThreshold = true; + if (vibrateWhenActionTriggered) { + viewHolder.itemView.setHapticFeedbackEnabled(true); + viewHolder.itemView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); + } + } + backgroundSwipeRight.setBounds(0, itemView.getTop(), itemView.getRight(), itemView.getBottom()); + } else { + exceedThreshold = false; + backgroundSwipeRight.setBounds(0, 0, 0, 0); + } + + drawableSwipeRight.setBounds(itemView.getLeft() + ((int) dX) - horizontalOffset - drawableSwipeRight.getIntrinsicWidth(), + (itemView.getBottom() + itemView.getTop() - drawableSwipeRight.getIntrinsicHeight()) / 2, + itemView.getLeft() + ((int) dX) - horizontalOffset, + (itemView.getBottom() + itemView.getTop() + drawableSwipeRight.getIntrinsicHeight()) / 2); + backgroundSwipeRight.draw(c); + drawableSwipeRight.draw(c); + } else if (dX < 0) { + if (-dX > (itemView.getRight() - itemView.getLeft()) * swipeActionThreshold) { + if (!exceedThreshold) { + exceedThreshold = true; + if (vibrateWhenActionTriggered) { + viewHolder.itemView.setHapticFeedbackEnabled(true); + viewHolder.itemView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); + } + } + backgroundSwipeLeft.setBounds(0, itemView.getTop(), itemView.getRight(), itemView.getBottom()); + } else { + exceedThreshold = false; + backgroundSwipeLeft.setBounds(0, 0, 0, 0); + } + drawableSwipeLeft.setBounds(itemView.getRight() + ((int) dX) + horizontalOffset, + (itemView.getBottom() + itemView.getTop() - drawableSwipeLeft.getIntrinsicHeight()) / 2, + itemView.getRight() + ((int) dX) + horizontalOffset + drawableSwipeLeft.getIntrinsicWidth(), + (itemView.getBottom() + itemView.getTop() + drawableSwipeLeft.getIntrinsicHeight()) / 2); + backgroundSwipeLeft.draw(c); + drawableSwipeLeft.draw(c); + } + } + + @Override + public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) { + return swipeActionThreshold; + } + }); + + if (enableSwipeAction) { + touchHelper.attachToRecyclerView(mRecyclerView); + } + + mSwipeRefreshLayout.setOnRefreshListener(() -> refresh(true, true)); + + mSmoothScroller = new LinearSmoothScroller(activity) { + @Override + protected int getVerticalSnapPreference() { + return LinearSmoothScroller.SNAP_TO_START; + } + }; + + mSingleCommentId = getArguments().getString(EXTRA_SINGLE_COMMENT_ID); + if (savedInstanceState == null) { + if (mSingleCommentId != null) { + isSingleCommentThreadMode = true; + } + mMessageFullname = getArguments().getString(EXTRA_MESSAGE_FULLNAME); + + if (!mRespectSubredditRecommendedSortType || isSingleCommentThreadMode) { + sortType = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.BEST.value.toUpperCase()); + if (sortType != null) { + activity.setTitle(new SortType(SortType.Type.valueOf(sortType)).getType().fullName); + sortType = sortType.toLowerCase(); + } + } + } else { + if (sortType != null) { + activity.setTitle(new SortType(SortType.Type.valueOf(sortType.toUpperCase())).getType().fullName); + } + } + + if (getArguments().containsKey(EXTRA_POST_LIST_POSITION)) { + postListPosition = getArguments().getInt(EXTRA_POST_LIST_POSITION, -1); + } + + bindView(); + + return rootView; + } + + private void bindView() { + if (mAccessToken != null && mMessageFullname != null) { + ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() { + @Override + public void readSuccess() { + mMessageFullname = null; + } + + @Override + public void readFailed() { + + } + }); + } + + if (mPost == null) { + mPost = getArguments().getParcelable(EXTRA_POST_DATA); + } + + if (mPost == null) { + fetchPostAndCommentsById(getArguments().getString(EXTRA_POST_ID)); + } else { + setupMenu(); + + mAdapter = new CommentAndPostRecyclerViewAdapter(activity, + this, mExecutor, mCustomThemeWrapper, mRetrofit, mOauthRetrofit, mGfycatRetrofit, + mRedgifsRetrofit, mRedditDataRoomDatabase, mGlide, + mWindowWidth, mAccessToken, mAccountName, mPost, mLocale, mSingleCommentId, + isSingleCommentThreadMode, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mExoCreator, + new CommentAndPostRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { + @Override + public void updatePost(Post post) { + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + + @Override + public void retryFetchingComments() { + fetchCommentsRespectRecommendedSort(false); + } + + @Override + public void retryFetchingMoreComments() { + isLoadingMoreChildren = false; + loadMoreChildrenSuccess = true; + + fetchMoreComments(); + } + }); + mRecyclerView.setAdapter(mAdapter); + + if (comments == null) { + fetchCommentsRespectRecommendedSort(false); + } else { + if (isRefreshing) { + isRefreshing = false; + refresh(true, true); + } else if (isFetchingComments) { + fetchCommentsRespectRecommendedSort(false); + } else { + mAdapter.addComments(comments, hasMoreChildren); + if (isLoadingMoreChildren) { + isLoadingMoreChildren = false; + fetchMoreComments(); + } + } + } + } + + mRecyclerView.setCacheManager(mAdapter); + mRecyclerView.setPlayerInitializer(order -> { + VolumeInfo volumeInfo = new VolumeInfo(true, 0f); + return new PlaybackInfo(INDEX_UNSET, TIME_UNSET, volumeInfo); + }); + } + + private void setupMenu() { + if (mMenu != null) { + MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_fragment); + MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_fragment); + + mMenu.findItem(R.id.action_comment_view_post_detail_fragment).setVisible(true); + mMenu.findItem(R.id.action_sort_view_post_detail_fragment).setVisible(true); + + if (mAccessToken != null) { + if (mPost.isSaved()) { + saveItem.setVisible(true); + saveItem.setIcon(mSavedIcon); + } else { + saveItem.setVisible(true); + saveItem.setIcon(mUnsavedIcon); + } + + if (mPost.isHidden()) { + hideItem.setVisible(true); + hideItem.setTitle(R.string.action_unhide_post); + } else { + hideItem.setVisible(true); + hideItem.setTitle(R.string.action_hide_post); + } + } else { + saveItem.setVisible(false); + hideItem.setVisible(false); + } + + if (mPost.getAuthor().equals(mAccountName)) { + if (mPost.getPostType() == Post.TEXT_TYPE) { + mMenu.findItem(R.id.action_edit_view_post_detail_fragment).setVisible(true); + } + mMenu.findItem(R.id.action_delete_view_post_detail_fragment).setVisible(true); + + MenuItem nsfwItem = mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment); + nsfwItem.setVisible(true); + if (mPost.isNSFW()) { + nsfwItem.setTitle(R.string.action_unmark_nsfw); + } else { + nsfwItem.setTitle(R.string.action_mark_nsfw); + } + + MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment); + spoilerItem.setVisible(true); + if (mPost.isSpoiler()) { + spoilerItem.setTitle(R.string.action_unmark_spoiler); + } else { + spoilerItem.setTitle(R.string.action_mark_spoiler); + } + + mMenu.findItem(R.id.action_edit_flair_view_post_detail_fragment).setVisible(true); + } + + mMenu.findItem(R.id.action_view_crosspost_parent_view_post_detail_fragment).setVisible(mPost.getCrosspostParentId() != null); + + if ("[deleted]".equals(mPost.getAuthor()) || + "[deleted]".equals(mPost.getSelfText()) || + "[removed]".equals(mPost.getSelfText()) + ) { + mMenu.findItem(R.id.action_see_removed_view_post_detail_fragment).setVisible(true); + } + } + } + + private void initializeSwipeActionDrawable() { + if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) { + backgroundSwipeRight = new ColorDrawable(mCustomThemeWrapper.getDownvoted()); + drawableSwipeRight = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_downward_black_24dp, null); + } else { + backgroundSwipeRight = new ColorDrawable(mCustomThemeWrapper.getUpvoted()); + drawableSwipeRight = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_upward_black_24dp, null); + } + + if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) { + backgroundSwipeLeft = new ColorDrawable(mCustomThemeWrapper.getUpvoted()); + drawableSwipeLeft = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_upward_black_24dp, null); + } else { + backgroundSwipeLeft = new ColorDrawable(mCustomThemeWrapper.getDownvoted()); + drawableSwipeLeft = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_arrow_downward_black_24dp, null); + } + } + + private Drawable getMenuItemIcon(int drawableId) { + Drawable icon = ContextCompat.getDrawable(activity, drawableId); + if (icon != null) { + DrawableCompat.setTint(icon, mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor()); + } + + return icon; + } + + public void addComment(Comment comment) { + if (mAdapter != null) { + mAdapter.addComment(comment); + } + } + + public void addChildComment(Comment comment, String parentFullname, int parentPosition) { + if (mAdapter != null) { + mAdapter.addChildComment(comment, parentFullname, parentPosition); + } + } + + public void editComment(String commentAuthor, String commentContentMarkdown, int position) { + if (mAdapter != null) { + mAdapter.editComment(commentAuthor, + commentContentMarkdown, + position); + } + } + + public void awardGiven(String awardsHTML, int awardCount, int position) { + if (mAdapter != null) { + mAdapter.giveAward(awardsHTML, awardCount, position); + } + } + + public void changeFlair(Flair flair) { + Map<String, String> params = new HashMap<>(); + params.put(APIUtils.API_TYPE_KEY, APIUtils.API_TYPE_JSON); + params.put(APIUtils.FLAIR_TEMPLATE_ID_KEY, flair.getId()); + params.put(APIUtils.LINK_KEY, mPost.getFullName()); + params.put(APIUtils.TEXT_KEY, flair.getText()); + + mOauthRetrofit.create(RedditAPI.class).selectFlair(mPost.getSubredditNamePrefixed(), + APIUtils.getOAuthHeader(mAccessToken), params).enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { + if (response.isSuccessful()) { + refresh(true, false); + showMessage(R.string.update_flair_success); + } else { + showMessage(R.string.update_flair_failed); + } + } + + @Override + public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { + showMessage(R.string.update_flair_failed); + } + }); + } + + public void changeSortType(SortType sortType) { + mFetchPostInfoLinearLayout.setVisibility(View.GONE); + mGlide.clear(mFetchPostInfoImageView); + mChildrenStartingIndex = 0; + if (children != null) { + children.clear(); + } + this.sortType = sortType.getType().value; + if (!mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false)) { + mSortTypeSharedPreferences.edit().putString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, sortType.getType().name()).apply(); + } + fetchCommentsRespectRecommendedSort(false, false, sortType.getType().value); + } + + public void goToTop() { + if (mLinearLayoutManager != null) { + mLinearLayoutManager.scrollToPositionWithOffset(0, 0); + } + } + + @Override + public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { + inflater.inflate(R.menu.view_post_detail_fragment, menu); + applyMenuItemTheme(menu); + mMenu = menu; + if (mPost != null) { + setupMenu(); + } + } + + @Override + public boolean onOptionsItemSelected(@NonNull MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_refresh_view_post_detail_fragment) { + refresh(true, true); + return true; + } else if (itemId == R.id.action_comment_view_post_detail_fragment) { + if (mPost != null) { + if (mPost.isArchived()) { + showMessage(R.string.archived_post_reply_unavailable); + return true; + } + + if (mPost.isLocked()) { + showMessage(R.string.locked_post_comment_unavailable); + return true; + } + + if (mAccessToken == null) { + showMessage(R.string.login_first); + return true; + } + + Intent intent = new Intent(activity, CommentActivity.class); + intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TEXT_MARKDOWN_KEY, mPost.getTitle()); + intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_BODY_MARKDOWN_KEY, mPost.getSelfText()); + intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_BODY_KEY, mPost.getSelfTextPlain()); + intent.putExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY, mPost.getFullName()); + intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, 0); + intent.putExtra(CommentActivity.EXTRA_IS_REPLYING_KEY, false); + startActivityForResult(intent, WRITE_COMMENT_REQUEST_CODE); + } + return true; + } else if (itemId == R.id.action_save_view_post_detail_fragment) { + if (mPost != null && mAccessToken != null) { + if (mPost.isSaved()) { + item.setIcon(mUnsavedIcon); + SaveThing.unsaveThing(mOauthRetrofit, mAccessToken, mPost.getFullName(), + new SaveThing.SaveThingListener() { + @Override + public void success() { + mPost.setSaved(false); + item.setIcon(mUnsavedIcon); + showMessage(R.string.post_unsaved_success); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + + @Override + public void failed() { + mPost.setSaved(true); + item.setIcon(mSavedIcon); + showMessage(R.string.post_unsaved_failed); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + }); + } else { + item.setIcon(mSavedIcon); + SaveThing.saveThing(mOauthRetrofit, mAccessToken, mPost.getFullName(), + new SaveThing.SaveThingListener() { + @Override + public void success() { + mPost.setSaved(true); + item.setIcon(mSavedIcon); + showMessage(R.string.post_saved_success); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + + @Override + public void failed() { + mPost.setSaved(false); + item.setIcon(mUnsavedIcon); + showMessage(R.string.post_saved_failed); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + }); + } + } + return true; + } else if (itemId == R.id.action_sort_view_post_detail_fragment) { + if (mPost != null) { + PostCommentSortTypeBottomSheetFragment postCommentSortTypeBottomSheetFragment = new PostCommentSortTypeBottomSheetFragment(); + postCommentSortTypeBottomSheetFragment.show(activity.getSupportFragmentManager(), postCommentSortTypeBottomSheetFragment.getTag()); + } + return true; + } else if (itemId == R.id.action_view_crosspost_parent_view_post_detail_fragment) { + Intent crosspostIntent = new Intent(activity, ViewPostDetailActivity.class); + crosspostIntent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, mPost.getCrosspostParentId()); + startActivity(crosspostIntent); + return true; + } else if (itemId == R.id.action_hide_view_post_detail_fragment) { + if (mPost != null && mAccessToken != null) { + if (mPost.isHidden()) { + item.setTitle(R.string.action_hide_post); + + HidePost.unhidePost(mOauthRetrofit, mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() { + @Override + public void success() { + mPost.setHidden(false); + item.setTitle(R.string.action_hide_post); + showMessage(R.string.post_unhide_success); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + + @Override + public void failed() { + mPost.setHidden(true); + item.setTitle(R.string.action_unhide_post); + showMessage(R.string.post_unhide_failed); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + }); + } else { + item.setTitle(R.string.action_unhide_post); + + HidePost.hidePost(mOauthRetrofit, mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() { + @Override + public void success() { + mPost.setHidden(true); + item.setTitle(R.string.action_unhide_post); + showMessage(R.string.post_hide_success); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + + @Override + public void failed() { + mPost.setHidden(false); + item.setTitle(R.string.action_hide_post); + showMessage(R.string.post_hide_failed); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + }); + } + } + return true; + } else if (itemId == R.id.action_edit_view_post_detail_fragment) { + Intent editPostIntent = new Intent(activity, EditPostActivity.class); + editPostIntent.putExtra(EditPostActivity.EXTRA_FULLNAME, mPost.getFullName()); + editPostIntent.putExtra(EditPostActivity.EXTRA_TITLE, mPost.getTitle()); + editPostIntent.putExtra(EditPostActivity.EXTRA_CONTENT, mPost.getSelfText()); + startActivityForResult(editPostIntent, EDIT_POST_REQUEST_CODE); + return true; + } else if (itemId == R.id.action_delete_view_post_detail_fragment) { + new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) + .setTitle(R.string.delete_this_post) + .setMessage(R.string.are_you_sure) + .setPositiveButton(R.string.delete, (dialogInterface, i) + -> DeleteThing.delete(mOauthRetrofit, mPost.getFullName(), mAccessToken, new DeleteThing.DeleteThingListener() { + @Override + public void deleteSuccess() { + Toast.makeText(activity, R.string.delete_post_success, Toast.LENGTH_SHORT).show(); + activity.finish(); + } + + @Override + public void deleteFailed() { + showMessage(R.string.delete_post_failed); + } + })) + .setNegativeButton(R.string.cancel, null) + .show(); + return true; + } else if (itemId == R.id.action_nsfw_view_post_detail_fragment) { + if (mPost.isNSFW()) { + unmarkNSFW(); + } else { + markNSFW(); + } + return true; + } else if (itemId == R.id.action_spoiler_view_post_detail_fragment) { + if (mPost.isSpoiler()) { + unmarkSpoiler(); + } else { + markSpoiler(); + } + return true; + } else if (itemId == R.id.action_edit_flair_view_post_detail_fragment) { + FlairBottomSheetFragment flairBottomSheetFragment = new FlairBottomSheetFragment(); + Bundle bundle = new Bundle(); + bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken); + bundle.putString(FlairBottomSheetFragment.EXTRA_SUBREDDIT_NAME, mPost.getSubredditName()); + flairBottomSheetFragment.setArguments(bundle); + flairBottomSheetFragment.show(activity.getSupportFragmentManager(), flairBottomSheetFragment.getTag()); + return true; + } else if (itemId == R.id.action_give_award_view_post_detail_fragment) { + if (mAccessToken == null) { + Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show(); + return true; + } + + Intent giveAwardIntent = new Intent(activity, GiveAwardActivity.class); + giveAwardIntent.putExtra(GiveAwardActivity.EXTRA_THING_FULLNAME, mPost.getFullName()); + giveAwardIntent.putExtra(GiveAwardActivity.EXTRA_ITEM_POSITION, 0); + activity.startActivityForResult(giveAwardIntent, ViewPostDetailActivity.GIVE_AWARD_REQUEST_CODE); + return true; + } else if (itemId == R.id.action_report_view_post_detail_fragment) { + if (mAccessToken == null) { + Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show(); + return true; + } + Intent intent = new Intent(activity, ReportActivity.class); + intent.putExtra(ReportActivity.EXTRA_SUBREDDIT_NAME, mPost.getSubredditName()); + intent.putExtra(ReportActivity.EXTRA_THING_FULLNAME, mPost.getFullName()); + startActivity(intent); + return true; + } else if (itemId == R.id.action_see_removed_view_post_detail_fragment) { + showRemovedPost(); + return true; + } else if (itemId == R.id.action_crosspost_view_post_detail_fragment) { + Intent submitCrosspostIntent = new Intent(activity, SubmitCrosspostActivity.class); + submitCrosspostIntent.putExtra(SubmitCrosspostActivity.EXTRA_POST, mPost); + startActivity(submitCrosspostIntent); + return true; + } + return false; + } + + @Override + public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { + if (requestCode == WRITE_COMMENT_REQUEST_CODE) { + if (data != null && resultCode == Activity.RESULT_OK) { + if (data.hasExtra(RETURN_EXTRA_COMMENT_DATA_KEY)) { + Comment comment = data.getParcelableExtra(RETURN_EXTRA_COMMENT_DATA_KEY); + if (comment != null && comment.getDepth() == 0) { + addComment(comment); + } else { + String parentFullname = data.getStringExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY); + int parentPosition = data.getIntExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, -1); + if (parentFullname != null && parentPosition >= 0) { + addChildComment(comment, parentFullname, parentPosition); + } + } + } else { + Toast.makeText(activity, R.string.send_comment_failed, Toast.LENGTH_SHORT).show(); + } + } + } else if (requestCode == EDIT_POST_REQUEST_CODE) { + if (resultCode == Activity.RESULT_OK) { + refresh(true, false); + } + } + } + + @Override + public void onResume() { + super.onResume(); + if (mAdapter != null && mRecyclerView != null) { + mRecyclerView.onWindowVisibilityChanged(View.VISIBLE); + } + } + + @Override + public void onPause() { + super.onPause(); + if (mAdapter != null && mRecyclerView != null) { + mRecyclerView.onWindowVisibilityChanged(View.GONE); + } + } + + @Override + public void onSaveInstanceState(@NonNull Bundle outState) { + super.onSaveInstanceState(outState); + comments = mAdapter == null ? null : mAdapter.getVisibleComments(); + Bridge.saveInstanceState(this, outState); + } + + @Override + public void onDestroyView() { + super.onDestroyView(); + Bridge.clear(this); + } + + @Override + public void onDestroy() { + EventBus.getDefault().unregister(this); + super.onDestroy(); + } + + @SuppressLint("RestrictedApi") + protected boolean applyMenuItemTheme(Menu menu) { + if (mCustomThemeWrapper != null) { + int size = Math.min(menu.size(), 2); + for (int i = 0; i < size; i++) { + MenuItem item = menu.getItem(i); + if (((MenuItemImpl) item).requestsActionButton()) { + Drawable drawable = item.getIcon(); + if (drawable != null) { + DrawableCompat.setTint(drawable, mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor()); + item.setIcon(drawable); + } + } + } + } + return true; + } + + private void fetchPostAndCommentsById(String subredditId) { + mFetchPostInfoLinearLayout.setVisibility(View.GONE); + mSwipeRefreshLayout.setRefreshing(true); + mGlide.clear(mFetchPostInfoImageView); + + Call<String> postAndComments; + if (mAccessToken == null) { + if (isSingleCommentThreadMode && mSingleCommentId != null) { + postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadById( + subredditId, mSingleCommentId, sortType); + } else { + postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsById(subredditId, + sortType); + } + } else { + if (isSingleCommentThreadMode && mSingleCommentId != null) { + postAndComments = mOauthRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadByIdOauth(subredditId, + mSingleCommentId, sortType, APIUtils.getOAuthHeader(mAccessToken)); + } else { + postAndComments = mOauthRetrofit.create(RedditAPI.class).getPostAndCommentsByIdOauth(subredditId, + sortType, APIUtils.getOAuthHeader(mAccessToken)); + } + } + postAndComments.enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { + mSwipeRefreshLayout.setRefreshing(false); + + if (response.isSuccessful()) { + ParsePost.parsePost(response.body(), new ParsePost.ParsePostListener() { + @Override + public void onParsePostSuccess(Post post) { + mPost = post; + + setupMenu(); + + mAdapter = new CommentAndPostRecyclerViewAdapter(activity, + ViewPostDetailFragment.this, mExecutor, mCustomThemeWrapper, mRetrofit, mOauthRetrofit, mGfycatRetrofit, + mRedgifsRetrofit, mRedditDataRoomDatabase, mGlide, + mWindowWidth, mAccessToken, mAccountName, mPost, mLocale, + mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences, + mNsfwAndSpoilerSharedPreferences, mExoCreator, + new CommentAndPostRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { + @Override + public void updatePost(Post post) { + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + } + + @Override + public void retryFetchingComments() { + fetchCommentsRespectRecommendedSort(false); + } + + @Override + public void retryFetchingMoreComments() { + isLoadingMoreChildren = false; + loadMoreChildrenSuccess = true; + + fetchMoreComments(); + } + }); + mRecyclerView.setAdapter(mAdapter); + + if (mRespectSubredditRecommendedSortType) { + fetchCommentsRespectRecommendedSort(false); + } else { + ParseComment.parseComment(response.body(), new ArrayList<>(), mLocale, + mExpandChildren, new ParseComment.ParseCommentListener() { + @Override + public void onParseCommentSuccess(ArrayList<Comment> expandedComments, String parentId, ArrayList<String> moreChildrenFullnames) { + ViewPostDetailFragment.this.children = moreChildrenFullnames; + + hasMoreChildren = children.size() != 0; + mAdapter.addComments(expandedComments, hasMoreChildren); + + if (children.size() > 0) { + mRecyclerView.clearOnScrollListeners(); + mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + if (!mIsSmoothScrolling && !mLockFab) { + if (!recyclerView.canScrollVertically(1)) { + activity.hideFab(); + } else { + if (dy > 0) { + if (mSwipeUpToHideFab) { + activity.showFab(); + } else { + activity.hideFab(); + } + } else { + if (mSwipeUpToHideFab) { + activity.hideFab(); + } else { + activity.showFab(); + } + } + } + } + + if (!isLoadingMoreChildren && loadMoreChildrenSuccess) { + int visibleItemCount = mLinearLayoutManager.getChildCount(); + int totalItemCount = mLinearLayoutManager.getItemCount(); + int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); + + if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { + fetchMoreComments(); + } + } + } + + @Override + public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + mIsSmoothScrolling = false; + } + } + }); + } + } + + @Override + public void onParseCommentFailed() { + mAdapter.initiallyLoadCommentsFailed(); + } + }); + } + } + + @Override + public void onParsePostFail() { + showErrorView(subredditId); + } + }); + } else { + showErrorView(subredditId); + } + } + + @Override + public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { + showErrorView(subredditId); + } + }); + } + + private void fetchCommentsRespectRecommendedSort(boolean changeRefreshState, boolean checkSortState, String sortType) { + if (mRespectSubredditRecommendedSortType && mPost != null) { + FetchSubredditData.fetchSubredditData(mRetrofit, mPost.getSubredditName(), + new FetchSubredditData.FetchSubredditDataListener() { + @Override + public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { + if (subredditData.getSuggestedCommentSort() == null || subredditData.getSuggestedCommentSort().equals("null") || subredditData.getSuggestedCommentSort().equals("")) { + mRespectSubredditRecommendedSortType = false; + ViewPostDetailFragment.this.sortType = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.BEST.value.toUpperCase()); + if (ViewPostDetailFragment.this.sortType != null) { + activity.setTitle(new SortType(SortType.Type.valueOf(ViewPostDetailFragment.this.sortType)).getType().fullName); + ViewPostDetailFragment.this.sortType = ViewPostDetailFragment.this.sortType.toLowerCase(); + } + fetchComments(changeRefreshState, checkSortState, ViewPostDetailFragment.this.sortType); + } else { + ViewPostDetailFragment.this.sortType = subredditData.getSuggestedCommentSort(); + String sortTypeTemp = ViewPostDetailFragment.this.sortType.toLowerCase().substring(0, 1).toUpperCase() + ViewPostDetailFragment.this.sortType.substring(1); + activity.setTitle(sortTypeTemp); + fetchComments(changeRefreshState, checkSortState, subredditData.getSuggestedCommentSort()); + } + } + + @Override + public void onFetchSubredditDataFail(boolean isQuarantined) { + mRespectSubredditRecommendedSortType = false; + ViewPostDetailFragment.this.sortType = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.BEST.value.toUpperCase()); + if (ViewPostDetailFragment.this.sortType != null) { + activity.setTitle(new SortType(SortType.Type.valueOf(ViewPostDetailFragment.this.sortType)).getType().fullName); + ViewPostDetailFragment.this.sortType = ViewPostDetailFragment.this.sortType.toLowerCase(); + } + } + }); + } else { + fetchComments(changeRefreshState, checkSortState, sortType); + } + } + + private void fetchComments(boolean changeRefreshState, boolean checkSortState, String sortType) { + isFetchingComments = true; + mAdapter.setSingleComment(mSingleCommentId, isSingleCommentThreadMode); + mAdapter.initiallyLoading(); + String commentId = null; + if (isSingleCommentThreadMode) { + commentId = mSingleCommentId; + } + + Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit; + FetchComment.fetchComments(retrofit, mAccessToken, mPost.getId(), commentId, sortType, mExpandChildren, + mLocale, new FetchComment.FetchCommentListener() { + @Override + public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, + String parentId, ArrayList<String> children) { + if (checkSortState && isSortingComments) { + if (changeRefreshState) { + isRefreshing = false; + } + + return; + } + + ViewPostDetailFragment.this.children = children; + + comments = expandedComments; + hasMoreChildren = children.size() != 0; + mAdapter.addComments(expandedComments, hasMoreChildren); + + if (children.size() > 0) { + mRecyclerView.clearOnScrollListeners(); + mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + if (!mIsSmoothScrolling && !mLockFab) { + if (!recyclerView.canScrollVertically(1)) { + activity.hideFab(); + } else { + if (dy > 0) { + if (mSwipeUpToHideFab) { + activity.showFab(); + } else { + activity.hideFab(); + } + } else { + if (mSwipeUpToHideFab) { + activity.hideFab(); + } else { + activity.showFab(); + } + } + } + } + + if (!isLoadingMoreChildren && loadMoreChildrenSuccess) { + int visibleItemCount = mLinearLayoutManager.getChildCount(); + int totalItemCount = mLinearLayoutManager.getItemCount(); + int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); + + if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { + fetchMoreComments(); + } + } + } + + @Override + public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + mIsSmoothScrolling = false; + } + } + }); + } + if (changeRefreshState) { + isRefreshing = false; + } + + isFetchingComments = false; + } + + @Override + public void onFetchCommentFailed() { + isFetchingComments = false; + if (checkSortState && isSortingComments) { + if (changeRefreshState) { + isRefreshing = false; + } + + return; + } + + mAdapter.initiallyLoadCommentsFailed(); + if (changeRefreshState) { + isRefreshing = false; + } + } + }); + } + + private void fetchCommentsRespectRecommendedSort(boolean changeRefreshState) { + fetchCommentsRespectRecommendedSort(changeRefreshState, true, sortType); + } + + void fetchMoreComments() { + if (isFetchingComments || isLoadingMoreChildren || !loadMoreChildrenSuccess) { + return; + } + + isLoadingMoreChildren = true; + + Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit; + FetchComment.fetchMoreComment(retrofit, mAccessToken, children, mChildrenStartingIndex, + 0, mExpandChildren, mLocale, new FetchComment.FetchMoreCommentListener() { + @Override + public void onFetchMoreCommentSuccess(ArrayList<Comment> expandedComments, int childrenStartingIndex) { + hasMoreChildren = childrenStartingIndex < children.size(); + mAdapter.addComments(expandedComments, hasMoreChildren); + mChildrenStartingIndex = childrenStartingIndex; + isLoadingMoreChildren = false; + loadMoreChildrenSuccess = true; + } + + @Override + public void onFetchMoreCommentFailed() { + isLoadingMoreChildren = false; + loadMoreChildrenSuccess = false; + mAdapter.loadMoreCommentsFailed(); + } + }); + } + + public void refresh(boolean fetchPost, boolean fetchComments) { + if (mAdapter != null && !isRefreshing) { + isRefreshing = true; + mChildrenStartingIndex = 0; + + mFetchPostInfoLinearLayout.setVisibility(View.GONE); + mGlide.clear(mFetchPostInfoImageView); + + if (fetchComments) { + fetchCommentsRespectRecommendedSort(!fetchPost); + } + + if (fetchPost) { + Retrofit retrofit; + if (mAccessToken == null) { + retrofit = mRetrofit; + } else { + retrofit = mOauthRetrofit; + } + FetchPost.fetchPost(retrofit, mPost.getId(), mAccessToken, mLocale, + new FetchPost.FetchPostListener() { + @Override + public void fetchPostSuccess(Post post) { + mPost = post; + mAdapter.updatePost(mPost); + EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)); + isRefreshing = false; + setupMenu(); + mSwipeRefreshLayout.setRefreshing(false); + } + + @Override + public void fetchPostFailed() { + showMessage(R.string.refresh_post_failed); + isRefreshing = false; + } + }); + } + } + } + + private void showErrorView(String subredditId) { + mSwipeRefreshLayout.setRefreshing(false); + mFetchPostInfoLinearLayout.setVisibility(View.VISIBLE); + mFetchPostInfoLinearLayout.setOnClickListener(view -> fetchPostAndCommentsById(subredditId)); + mFetchPostInfoTextView.setText(R.string.load_post_error); + mGlide.load(R.drawable.error_image).into(mFetchPostInfoImageView); + } + + private void showMessage(int resId) { + if (showToast) { + Toast.makeText(activity, resId, Toast.LENGTH_SHORT).show(); + } else { + activity.showSnackBar(resId); + } + } + + private void markNSFW() { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw); + } + + Map<String, String> params = new HashMap<>(); + params.put(APIUtils.ID_KEY, mPost.getFullName()); + mOauthRetrofit.create(RedditAPI.class).markNSFW(APIUtils.getOAuthHeader(mAccessToken), params) + .enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { + if (response.isSuccessful()) { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw); + } + + refresh(true, false); + showMessage(R.string.mark_nsfw_success); + } else { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw); + } + + showMessage(R.string.mark_nsfw_failed); + } + } + + @Override + public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw); + } + + showMessage(R.string.mark_nsfw_failed); + } + }); + } + + private void unmarkNSFW() { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw); + } + + Map<String, String> params = new HashMap<>(); + params.put(APIUtils.ID_KEY, mPost.getFullName()); + mOauthRetrofit.create(RedditAPI.class).unmarkNSFW(APIUtils.getOAuthHeader(mAccessToken), params) + .enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { + if (response.isSuccessful()) { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_mark_nsfw); + } + + refresh(true, false); + showMessage(R.string.unmark_nsfw_success); + } else { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw); + } + + showMessage(R.string.unmark_nsfw_failed); + } + } + + @Override + public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { + if (mMenu != null) { + mMenu.findItem(R.id.action_nsfw_view_post_detail_fragment).setTitle(R.string.action_unmark_nsfw); + } + + showMessage(R.string.unmark_nsfw_failed); + } + }); + } + + private void markSpoiler() { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_unmark_spoiler); + } + + Map<String, String> params = new HashMap<>(); + params.put(APIUtils.ID_KEY, mPost.getFullName()); + mOauthRetrofit.create(RedditAPI.class).markSpoiler(APIUtils.getOAuthHeader(mAccessToken), params) + .enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { + if (response.isSuccessful()) { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_unmark_spoiler); + } + + refresh(true, false); + showMessage(R.string.mark_spoiler_success); + } else { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_mark_spoiler); + } + + showMessage(R.string.mark_spoiler_failed); + } + } + + @Override + public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_mark_spoiler); + } + + showMessage(R.string.mark_spoiler_failed); + } + }); + } + + private void unmarkSpoiler() { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_mark_spoiler); + } + + Map<String, String> params = new HashMap<>(); + params.put(APIUtils.ID_KEY, mPost.getFullName()); + mOauthRetrofit.create(RedditAPI.class).unmarkSpoiler(APIUtils.getOAuthHeader(mAccessToken), params) + .enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { + if (response.isSuccessful()) { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_mark_spoiler); + } + + refresh(true, false); + showMessage(R.string.unmark_spoiler_success); + } else { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_unmark_spoiler); + } + + showMessage(R.string.unmark_spoiler_failed); + } + } + + @Override + public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { + if (mMenu != null) { + mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment).setTitle(R.string.action_unmark_spoiler); + } + + showMessage(R.string.unmark_spoiler_failed); + } + }); + } + + public void deleteComment(String fullName, int position) { + new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) + .setTitle(R.string.delete_this_comment) + .setMessage(R.string.are_you_sure) + .setPositiveButton(R.string.delete, (dialogInterface, i) + -> DeleteThing.delete(mOauthRetrofit, fullName, mAccessToken, new DeleteThing.DeleteThingListener() { + @Override + public void deleteSuccess() { + Toast.makeText(activity, R.string.delete_post_success, Toast.LENGTH_SHORT).show(); + mAdapter.deleteComment(position); + } + + @Override + public void deleteFailed() { + Toast.makeText(activity, R.string.delete_post_failed, Toast.LENGTH_SHORT).show(); + } + })) + .setNegativeButton(R.string.cancel, null) + .show(); + } + + public void showRemovedComment(Comment comment, int position) { + Toast.makeText(activity, R.string.fetching_removed_comment, Toast.LENGTH_SHORT).show(); + FetchRemovedComment.fetchRemovedComment( + pushshiftRetrofit, + comment, + new FetchRemovedComment.FetchRemovedCommentListener() { + @Override + public void fetchSuccess(Comment comment) { + mAdapter.editComment(comment.getAuthor(), comment.getCommentMarkdown(), position); + } + + @Override + public void fetchFailed() { + Toast.makeText(activity, R.string.show_removed_comment_failed, Toast.LENGTH_SHORT).show(); + } + }); + } + + public void changeToNomalThreadMode() { + isSingleCommentThreadMode = false; + mSingleCommentId = null; + mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false); + refresh(false, true); + } + + public void scrollToNextParentComment() { + if (mLinearLayoutManager != null) { + int currentPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); + if (mAdapter != null) { + int nextParentPosition = mAdapter.getNextParentCommentPosition(currentPosition); + if (nextParentPosition < 0) { + return; + } + mSmoothScroller.setTargetPosition(nextParentPosition); + if (mLinearLayoutManager != null) { + mIsSmoothScrolling = true; + mLinearLayoutManager.startSmoothScroll(mSmoothScroller); + } + } + } + } + + public void scrollToPreviousParentComment() { + if (mLinearLayoutManager != null) { + int currentPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); + if (mAdapter != null) { + int nextParentPosition = mAdapter.getPreviousParentCommentPosition(currentPosition); + if (nextParentPosition < 0) { + return; + } + mSmoothScroller.setTargetPosition(nextParentPosition); + if (mLinearLayoutManager != null) { + mIsSmoothScrolling = true; + mLinearLayoutManager.startSmoothScroll(mSmoothScroller); + } + } + } + } + + public void delayTransition() { + TransitionManager.beginDelayedTransition(mRecyclerView, new AutoTransition()); + } + + public void showRemovedPost() { + Toast.makeText(activity, R.string.fetching_removed_post, Toast.LENGTH_SHORT).show(); + FetchRemovedPost.fetchRemovedPost( + pushshiftRetrofit, + mPost, + new FetchRemovedPost.FetchRemovedPostListener() { + @Override + public void fetchSuccess(Post post) { + mPost = post; + mAdapter.updatePost(post); + } + + @Override + public void fetchFailed() { + Toast.makeText(activity, R.string.show_removed_post_failed, Toast.LENGTH_SHORT).show(); + } + }); + } + + @Subscribe + public void onPostUpdateEvent(PostUpdateEventToDetailActivity event) { + if (mPost.getId().equals(event.post.getId())) { + mPost.setVoteType(event.post.getVoteType()); + mPost.setSaved(event.post.isSaved()); + if (mMenu != null) { + if (event.post.isSaved()) { + mMenu.findItem(R.id.action_save_view_post_detail_fragment).setIcon(mSavedIcon); + } else { + mMenu.findItem(R.id.action_save_view_post_detail_fragment).setIcon(mUnsavedIcon); + } + } + mAdapter.updatePost(mPost); + } + } + + @Subscribe + public void onChangeNSFWBlurEvent(ChangeNSFWBlurEvent event) { + mAdapter.setBlurNSFW(event.needBlurNSFW); + refreshAdapter(); + } + + @Subscribe + public void onChangeSpoilerBlurEvent(ChangeSpoilerBlurEvent event) { + mAdapter.setBlurSpoiler(event.needBlurSpoiler); + refreshAdapter(); + } + + private void refreshAdapter() { + int previousPosition = -1; + if (mLinearLayoutManager != null) { + previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition(); + } + + RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager(); + mRecyclerView.setAdapter(null); + mRecyclerView.setLayoutManager(null); + mRecyclerView.setAdapter(mAdapter); + mRecyclerView.setLayoutManager(layoutManager); + + if (previousPosition > 0) { + mRecyclerView.scrollToPosition(previousPosition); + } + } + + @Subscribe + public void onChangeNetworkStatusEvent(ChangeNetworkStatusEvent changeNetworkStatusEvent) { + if (mAdapter != null) { + String autoplay = mSharedPreferences.getString(SharedPreferencesUtils.VIDEO_AUTOPLAY, SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_NEVER); + String dataSavingMode = mSharedPreferences.getString(SharedPreferencesUtils.DATA_SAVING_MODE, SharedPreferencesUtils.DATA_SAVING_MODE_OFF); + boolean stateChanged = false; + if (autoplay.equals(SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_ON_WIFI)) { + mAdapter.setAutoplay(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_WIFI); + stateChanged = true; + } + if (dataSavingMode.equals(SharedPreferencesUtils.DATA_SAVING_MODE_ONLY_ON_CELLULAR_DATA)) { + mAdapter.setDataSavingMode(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_CELLULAR); + stateChanged = true; + } + + if (stateChanged) { + refreshAdapter(); + } + } + } + + @Override + public void onAttach(@NonNull Context context) { + super.onAttach(context); + activity = (ViewPostDetailActivity) context; + } + + @Override + public void applyTheme() { + mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); + mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); + mFetchPostInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor()); + } +}
\ No newline at end of file diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java index 7373279e..75e3b2c6 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java @@ -9,6 +9,7 @@ import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -42,15 +43,19 @@ import com.github.piasy.biv.view.BigImageView; import com.github.piasy.biv.view.GlideImageViewFactory; import java.io.File; +import java.util.concurrent.Executor; + +import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import ml.docilealligator.infinityforreddit.BuildConfig; +import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; import ml.docilealligator.infinityforreddit.activities.ViewRedditGalleryActivity; -import ml.docilealligator.infinityforreddit.asynctasks.SaveBitmapImageToFileAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.SaveGIFToFileAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.SaveBitmapImageToFile; +import ml.docilealligator.infinityforreddit.asynctasks.SaveGIFToFile; import ml.docilealligator.infinityforreddit.bottomsheetfragments.SetAsWallpaperBottomSheetFragment; import ml.docilealligator.infinityforreddit.post.Post; import ml.docilealligator.infinityforreddit.services.DownloadMediaService; @@ -67,6 +72,8 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment { BigImageView imageView; @BindView(R.id.load_image_error_linear_layout_view_reddit_gallery_image_or_gif_fragment) LinearLayout errorLinearLayout; + @Inject + Executor mExecutor; private ViewRedditGalleryActivity activity; private RequestManager glide; @@ -86,6 +93,8 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment { View rootView = inflater.inflate(R.layout.fragment_view_reddit_gallery_image_or_gif, container, false); + ((Infinity) activity.getApplication()).getAppComponent().inject(this); + ButterKnife.bind(this, rootView); setHasOptionsMenu(true); @@ -283,9 +292,9 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment { public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { if (activity.getExternalCacheDir() != null) { Toast.makeText(activity, R.string.save_image_first, Toast.LENGTH_SHORT).show(); - new SaveBitmapImageToFileAsyncTask(resource, activity.getExternalCacheDir().getPath(), + SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, new Handler(), resource, activity.getExternalCacheDir().getPath(), media.fileName, - new SaveBitmapImageToFileAsyncTask.SaveBitmapImageToFileAsyncTaskListener() { + new SaveBitmapImageToFile.SaveBitmapImageToFileListener() { @Override public void saveSuccess(File imageFile) { Uri uri = FileProvider.getUriForFile(activity, @@ -303,7 +312,7 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment { Toast.makeText(activity, R.string.cannot_save_image, Toast.LENGTH_SHORT).show(); } - }).execute(); + }); } else { Toast.makeText(activity, R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); @@ -328,8 +337,8 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment { @Override public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) { if (activity.getExternalCacheDir() != null) { - new SaveGIFToFileAsyncTask(resource, activity.getExternalCacheDir().getPath(), media.fileName, - new SaveGIFToFileAsyncTask.SaveGIFToFileAsyncTaskListener() { + SaveGIFToFile.saveGifToFile(mExecutor, new Handler(), resource, activity.getExternalCacheDir().getPath(), media.fileName, + new SaveGIFToFile.SaveGIFToFileAsyncTaskListener() { @Override public void saveSuccess(File imageFile) { Uri uri = FileProvider.getUriForFile(activity, @@ -347,7 +356,7 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment { Toast.makeText(activity, R.string.cannot_save_gif, Toast.LENGTH_SHORT).show(); } - }).execute(); + }); } else { Toast.makeText(activity, R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/DeleteMultiReddit.java b/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/DeleteMultiReddit.java index 0d6567a1..7fbb3ab7 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/DeleteMultiReddit.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/DeleteMultiReddit.java @@ -1,8 +1,12 @@ package ml.docilealligator.infinityforreddit.multireddit; +import android.os.Handler; + import androidx.annotation.NonNull; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteMultiredditInDatabaseAsyncTask; +import java.util.concurrent.Executor; + +import ml.docilealligator.infinityforreddit.asynctasks.DeleteMultiredditInDatabase; import ml.docilealligator.infinityforreddit.apis.RedditAPI; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.utils.APIUtils; @@ -12,12 +16,14 @@ import retrofit2.Response; import retrofit2.Retrofit; public class DeleteMultiReddit { + public interface DeleteMultiRedditListener { void success(); void failed(); } - public static void deleteMultiReddit(Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, + public static void deleteMultiReddit(Executor executor, Handler handler, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, String accessToken, String accountName, String multipath, DeleteMultiRedditListener deleteMultiRedditListener) { oauthRetrofit.create(RedditAPI.class).deleteMultiReddit(APIUtils.getOAuthHeader(accessToken), @@ -25,8 +31,8 @@ public class DeleteMultiReddit { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if (response.isSuccessful()) { - new DeleteMultiredditInDatabaseAsyncTask(redditDataRoomDatabase, accountName, multipath, - deleteMultiRedditListener::success).execute(); + DeleteMultiredditInDatabase.deleteMultiredditInDatabase(executor, handler, redditDataRoomDatabase, accountName, multipath, + deleteMultiRedditListener::success); } else { deleteMultiRedditListener.failed(); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/FavoriteMultiReddit.java b/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/FavoriteMultiReddit.java index 5d6c7573..227b7665 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/FavoriteMultiReddit.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/multireddit/FavoriteMultiReddit.java @@ -1,12 +1,15 @@ package ml.docilealligator.infinityforreddit.multireddit; +import android.os.Handler; + import androidx.annotation.NonNull; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Executor; import ml.docilealligator.infinityforreddit.apis.RedditAPI; -import ml.docilealligator.infinityforreddit.asynctasks.InsertMultiRedditAsyncTask; +import ml.docilealligator.infinityforreddit.asynctasks.InsertMultireddit; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.utils.APIUtils; import retrofit2.Call; @@ -20,7 +23,8 @@ public class FavoriteMultiReddit { void failed(); } - public static void favoriteMultiReddit(Retrofit oauthRetrofit, RedditDataRoomDatabase redditDataRoomDatabase, + public static void favoriteMultiReddit(Executor executor, Handler handler, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, String accessToken, boolean makeFavorite, MultiReddit multiReddit, FavoriteMultiRedditListener favoriteMultiRedditListener) { Map<String, String> params = new HashMap<>(); @@ -33,8 +37,8 @@ public class FavoriteMultiReddit { public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if (response.isSuccessful()) { multiReddit.setFavorite(makeFavorite); - new InsertMultiRedditAsyncTask(redditDataRoomDatabase, multiReddit, - favoriteMultiRedditListener::success).execute(); + InsertMultireddit.insertMultireddit(executor, handler, redditDataRoomDatabase, multiReddit, + favoriteMultiRedditListener::success); } else { favoriteMultiRedditListener.failed(); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java b/app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java index 14216298..c31da124 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java @@ -1,9 +1,7 @@ package ml.docilealligator.infinityforreddit.post; import android.graphics.Bitmap; -import android.os.AsyncTask; -import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.json.JSONArray; @@ -21,15 +19,14 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import ml.docilealligator.infinityforreddit.apis.RedditAPI; import ml.docilealligator.infinityforreddit.Flair; +import ml.docilealligator.infinityforreddit.apis.RedditAPI; import ml.docilealligator.infinityforreddit.utils.APIUtils; import ml.docilealligator.infinityforreddit.utils.JSONUtils; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; -import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; @@ -38,33 +35,31 @@ public class SubmitPost { Locale locale, String subredditName, String title, String content, Flair flair, boolean isSpoiler, boolean isNSFW, String kind, SubmitPostListener submitPostListener) { - submitPost(oauthRetrofit, accessToken, locale, subredditName, title, content, + submitPost(oauthRetrofit, accessToken, subredditName, title, content, flair, isSpoiler, isNSFW, kind, null, submitPostListener); } public static void submitImagePost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit, - String accessToken, Locale locale, - String subredditName, String title, Bitmap image, Flair flair, - boolean isSpoiler, boolean isNSFW, SubmitPostListener submitPostListener) { - uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, image, - new UploadImageListener() { - @Override - public void uploaded(String imageUrl) { - submitPost(oauthRetrofit, accessToken, locale, - subredditName, title, imageUrl, flair, isSpoiler, isNSFW, - APIUtils.KIND_IMAGE, null, submitPostListener); - } - - @Override - public void uploadFailed(@Nullable String errorMessage) { - submitPostListener.submitFailed(errorMessage); - } - }); + String accessToken, String subredditName, String title, Bitmap image, + Flair flair, boolean isSpoiler, boolean isNSFW, SubmitPostListener submitPostListener) { + try { + String imageUrlOrError = uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, image); + if (imageUrlOrError != null && !imageUrlOrError.startsWith("Error: ")) { + submitPost(oauthRetrofit, accessToken, + subredditName, title, imageUrlOrError, flair, isSpoiler, isNSFW, + APIUtils.KIND_IMAGE, null, submitPostListener); + } else { + submitPostListener.submitFailed(imageUrlOrError); + } + } catch (IOException | JSONException | XmlPullParserException e) { + e.printStackTrace(); + submitPostListener.submitFailed(e.getMessage()); + } } public static void submitVideoPost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit, Retrofit uploadVideoRetrofit, String accessToken, - Locale locale, String subredditName, String title, File buffer, String mimeType, + String subredditName, String title, File buffer, String mimeType, Bitmap posterBitmap, Flair flair, boolean isSpoiler, boolean isNSFW, SubmitPostListener submitPostListener) { RedditAPI api = oauthRetrofit.create(RedditAPI.class); @@ -76,97 +71,64 @@ public class SubmitPost { uploadImageParams.put(APIUtils.MIMETYPE_KEY, mimeType); Call<String> uploadImageCall = api.uploadImage(APIUtils.getOAuthHeader(accessToken), uploadImageParams); - uploadImageCall.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - new ParseJSONResponseFromAWSAsyncTask(response.body(), new ParseJSONResponseFromAWSAsyncTask.ParseJSONResponseFromAWSListener() { - @Override - public void parseSuccessful(Map<String, RequestBody> nameValuePairsMap) { - RequestBody fileBody = RequestBody.create(buffer, MediaType.parse("application/octet-stream")); - MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_video." + fileType, fileBody); - - RedditAPI uploadVideoToAWSApi; - if (fileType.equals("gif")) { - uploadVideoToAWSApi = uploadMediaRetrofit.create(RedditAPI.class); - } else { - uploadVideoToAWSApi = uploadVideoRetrofit.create(RedditAPI.class); - } - Call<String> uploadMediaToAWS = uploadVideoToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload); - - uploadMediaToAWS.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - new ParseXMLReponseFromAWSAsyncTask(response.body(), new ParseXMLReponseFromAWSAsyncTask.ParseXMLResponseFromAWSListener() { - @Override - public void parseSuccessful(String url) { - uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, - posterBitmap, new UploadImageListener() { - @Override - public void uploaded(String imageUrl) { - if (fileType.equals("gif")) { - submitPost(oauthRetrofit, accessToken, locale, - subredditName, title, url, flair, isSpoiler, isNSFW, - APIUtils.KIND_VIDEOGIF, imageUrl, submitPostListener); - } else { - submitPost(oauthRetrofit, accessToken, locale, - subredditName, title, url, flair, isSpoiler, isNSFW, - APIUtils.KIND_VIDEO, imageUrl, submitPostListener); - } - } - - @Override - public void uploadFailed(@Nullable String errorMessage) { - submitPostListener.submitFailed(errorMessage); - } - }); - } - - @Override - public void parseFailed() { - submitPostListener.submitFailed(null); - } - }).execute(); - } else { - submitPostListener.submitFailed(response.message()); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - submitPostListener.submitFailed(t.getMessage()); - } - }); - } + try { + Response<String> uploadImageResponse = uploadImageCall.execute(); + if (uploadImageResponse.isSuccessful()) { + Map<String, RequestBody> nameValuePairsMap = parseJSONResponseFromAWS(uploadImageResponse.body()); + + RequestBody fileBody = RequestBody.create(buffer, MediaType.parse("application/octet-stream")); + MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_video." + fileType, fileBody); - @Override - public void parseFailed() { - submitPostListener.submitFailed(null); + RedditAPI uploadVideoToAWSApi; + if (fileType.equals("gif")) { + uploadVideoToAWSApi = uploadMediaRetrofit.create(RedditAPI.class); + } else { + uploadVideoToAWSApi = uploadVideoRetrofit.create(RedditAPI.class); + } + Call<String> uploadMediaToAWS = uploadVideoToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload); + Response<String> uploadMediaToAWSResponse = uploadMediaToAWS.execute(); + if (uploadMediaToAWSResponse.isSuccessful()) { + String url = parseXMLResponseFromAWS(uploadMediaToAWSResponse.body()); + if (url == null) { + submitPostListener.submitFailed(null); + return; + } + String imageUrlOrError = uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, posterBitmap); + if (imageUrlOrError != null && !imageUrlOrError.startsWith("Error: ")) { + if (fileType.equals("gif")) { + submitPost(oauthRetrofit, accessToken, + subredditName, title, url, flair, isSpoiler, isNSFW, + APIUtils.KIND_VIDEOGIF, imageUrlOrError, submitPostListener); + } else { + submitPost(oauthRetrofit, accessToken, + subredditName, title, url, flair, isSpoiler, isNSFW, + APIUtils.KIND_VIDEO, imageUrlOrError, submitPostListener); } - }).execute(); + } else { + submitPostListener.submitFailed(imageUrlOrError); + } } else { - submitPostListener.submitFailed(response.message()); + submitPostListener.submitFailed(uploadMediaToAWSResponse.code() + " " + uploadMediaToAWSResponse.message()); } + } else { + submitPostListener.submitFailed(uploadImageResponse.code() + " " + uploadImageResponse.message()); } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - submitPostListener.submitFailed(t.getMessage()); - } - }); + } catch (IOException | XmlPullParserException | JSONException e) { + e.printStackTrace(); + submitPostListener.submitFailed(e.getMessage()); + } } public static void submitCrosspost(Retrofit oauthRetrofit, String accessToken, - Locale locale, String subredditName, String title, String crosspostFullname, + String subredditName, String title, String crosspostFullname, Flair flair, boolean isSpoiler, boolean isNSFW, String kind, SubmitPostListener submitPostListener) { - submitPost(oauthRetrofit, accessToken, locale, subredditName, title, crosspostFullname, + submitPost(oauthRetrofit, accessToken, subredditName, title, crosspostFullname, flair, isSpoiler, isNSFW, kind, null, submitPostListener); } private static void submitPost(Retrofit oauthRetrofit, String accessToken, - Locale locale, String subredditName, String title, String content, + String subredditName, String title, String content, Flair flair, boolean isSpoiler, boolean isNSFW, String kind, @Nullable String posterUrl, SubmitPostListener submitPostListener) { RedditAPI api = oauthRetrofit.create(RedditAPI.class); @@ -206,32 +168,23 @@ public class SubmitPost { params.put(APIUtils.NSFW_KEY, Boolean.toString(isNSFW)); Call<String> submitPostCall = api.submit(APIUtils.getOAuthHeader(accessToken), params); - submitPostCall.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) { - if (response.isSuccessful()) { - try { - getSubmittedPost(response.body(), kind, oauthRetrofit, accessToken, - locale, submitPostListener); - } catch (JSONException e) { - e.printStackTrace(); - submitPostListener.submitFailed(null); - } - } else { - submitPostListener.submitFailed(response.message()); - } - } - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - submitPostListener.submitFailed(t.getMessage()); + try { + Response<String> response = submitPostCall.execute(); + if (response.isSuccessful()) { + getSubmittedPost(response.body(), kind, oauthRetrofit, accessToken, submitPostListener); + } else { + submitPostListener.submitFailed(response.message()); } - }); + } catch (IOException | JSONException e) { + e.printStackTrace(); + submitPostListener.submitFailed(e.getMessage()); + } } - private static void uploadImage(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit, - String accessToken, Bitmap image, - UploadImageListener uploadImageListener) { + @Nullable + private static String uploadImage(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit, + String accessToken, Bitmap image) throws IOException, JSONException, XmlPullParserException { RedditAPI api = oauthRetrofit.create(RedditAPI.class); Map<String, String> uploadImageParams = new HashMap<>(); @@ -239,70 +192,32 @@ public class SubmitPost { uploadImageParams.put(APIUtils.MIMETYPE_KEY, "image/jpeg"); Call<String> uploadImageCall = api.uploadImage(APIUtils.getOAuthHeader(accessToken), uploadImageParams); - uploadImageCall.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - new ParseJSONResponseFromAWSAsyncTask(response.body(), new ParseJSONResponseFromAWSAsyncTask.ParseJSONResponseFromAWSListener() { - @Override - public void parseSuccessful(Map<String, RequestBody> nameValuePairsMap) { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - image.compress(Bitmap.CompressFormat.JPEG, 100, stream); - byte[] byteArray = stream.toByteArray(); - - RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), byteArray); - MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_image.jpg", fileBody); - - RedditAPI uploadMediaToAWSApi = uploadMediaRetrofit.create(RedditAPI.class); - Call<String> uploadMediaToAWS = uploadMediaToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload); - - uploadMediaToAWS.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { - if (response.isSuccessful()) { - new ParseXMLReponseFromAWSAsyncTask(response.body(), new ParseXMLReponseFromAWSAsyncTask.ParseXMLResponseFromAWSListener() { - @Override - public void parseSuccessful(String url) { - uploadImageListener.uploaded(url); - } - - @Override - public void parseFailed() { - uploadImageListener.uploadFailed(null); - } - }).execute(); - } else { - uploadImageListener.uploadFailed("Error: " + response.code()); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - uploadImageListener.uploadFailed(t.getMessage()); - } - }); - } - - @Override - public void parseFailed() { - uploadImageListener.uploadFailed(null); - } - }).execute(); - } else { - uploadImageListener.uploadFailed(response.message()); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - uploadImageListener.uploadFailed(t.getMessage()); + Response<String> uploadImageResponse = uploadImageCall.execute(); + if (uploadImageResponse.isSuccessful()) { + Map<String, RequestBody> nameValuePairsMap = parseJSONResponseFromAWS(uploadImageResponse.body()); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + image.compress(Bitmap.CompressFormat.JPEG, 100, stream); + byte[] byteArray = stream.toByteArray(); + + RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), byteArray); + MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_image.jpg", fileBody); + + RedditAPI uploadMediaToAWSApi = uploadMediaRetrofit.create(RedditAPI.class); + Call<String> uploadMediaToAWS = uploadMediaToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload); + Response<String> uploadMediaToAWSResponse = uploadMediaToAWS.execute(); + if (uploadMediaToAWSResponse.isSuccessful()) { + return parseXMLResponseFromAWS(uploadMediaToAWSResponse.body()); + } else { + return "Error: " + uploadMediaToAWSResponse.code(); } - }); + } else { + return "Error: " + uploadImageResponse.message(); + } } private static void getSubmittedPost(String response, String kind, Retrofit oauthRetrofit, - String accessToken, Locale locale, - SubmitPostListener submitPostListener) throws JSONException { + String accessToken, SubmitPostListener submitPostListener) throws JSONException, IOException { JSONObject responseObject = new JSONObject(response).getJSONObject(JSONUtils.JSON_KEY); if (responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() != 0) { JSONArray error = responseObject.getJSONArray(JSONUtils.ERRORS_KEY) @@ -328,31 +243,22 @@ public class SubmitPost { RedditAPI api = oauthRetrofit.create(RedditAPI.class); Call<String> getPostCall = api.getPostOauth(postId, APIUtils.getOAuthHeader(accessToken)); - getPostCall.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) { - if (response.isSuccessful()) { - ParsePost.parsePost(response.body(), new ParsePost.ParsePostListener() { - @Override - public void onParsePostSuccess(Post post) { - submitPostListener.submitSuccessful(post); - } - - @Override - public void onParsePostFail() { - submitPostListener.submitFailed(null); - } - }); - } else { - submitPostListener.submitFailed(response.message()); + Response<String> getPostCallResponse = getPostCall.execute(); + if (getPostCallResponse.isSuccessful()) { + ParsePost.parsePost(getPostCallResponse.body(), new ParsePost.ParsePostListener() { + @Override + public void onParsePostSuccess(Post post) { + submitPostListener.submitSuccessful(post); } - } - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - submitPostListener.submitFailed(t.getMessage()); - } - }); + @Override + public void onParsePostFail() { + submitPostListener.submitFailed(null); + } + }); + } else { + submitPostListener.submitFailed(getPostCallResponse.message()); + } } else { submitPostListener.submitSuccessful(null); } @@ -364,115 +270,39 @@ public class SubmitPost { void submitFailed(@Nullable String errorMessage); } - private interface UploadImageListener { - void uploaded(String imageUrl); - - void uploadFailed(@Nullable String errorMessage); - } - - private static class ParseJSONResponseFromAWSAsyncTask extends AsyncTask<Void, Void, Void> { - private String response; - private ParseJSONResponseFromAWSListener parseJSONResponseFromAWSListener; - private Map<String, RequestBody> nameValuePairsMap; - private boolean successful; - ParseJSONResponseFromAWSAsyncTask(String response, ParseJSONResponseFromAWSListener parseJSONResponseFromAWSListener) { - this.response = response; - this.parseJSONResponseFromAWSListener = parseJSONResponseFromAWSListener; - nameValuePairsMap = new HashMap<>(); - successful = false; - } - - @Override - protected Void doInBackground(Void... voids) { - try { - JSONObject responseObject = new JSONObject(response); - JSONArray nameValuePairs = responseObject.getJSONObject(JSONUtils.ARGS_KEY).getJSONArray(JSONUtils.FIELDS_KEY); - - nameValuePairsMap = new HashMap<>(); - for (int i = 0; i < nameValuePairs.length(); i++) { - nameValuePairsMap.put(nameValuePairs.getJSONObject(i).getString(JSONUtils.NAME_KEY), - APIUtils.getRequestBody(nameValuePairs.getJSONObject(i).getString(JSONUtils.VALUE_KEY))); - } - - successful = true; - } catch (JSONException e) { - e.printStackTrace(); - successful = false; - } + private static Map<String, RequestBody> parseJSONResponseFromAWS(String response) throws JSONException { + JSONObject responseObject = new JSONObject(response); + JSONArray nameValuePairs = responseObject.getJSONObject(JSONUtils.ARGS_KEY).getJSONArray(JSONUtils.FIELDS_KEY); - return null; + Map<String, RequestBody> nameValuePairsMap = new HashMap<>(); + for (int i = 0; i < nameValuePairs.length(); i++) { + nameValuePairsMap.put(nameValuePairs.getJSONObject(i).getString(JSONUtils.NAME_KEY), + APIUtils.getRequestBody(nameValuePairs.getJSONObject(i).getString(JSONUtils.VALUE_KEY))); } - @Override - protected void onPostExecute(Void aVoid) { - if (successful) { - parseJSONResponseFromAWSListener.parseSuccessful(nameValuePairsMap); - } else { - parseJSONResponseFromAWSListener.parseFailed(); - } - } - - interface ParseJSONResponseFromAWSListener { - void parseSuccessful(Map<String, RequestBody> nameValuePairsMap); - - void parseFailed(); - } + return nameValuePairsMap; } - private static class ParseXMLReponseFromAWSAsyncTask extends AsyncTask<Void, Void, Void> { - private String response; - private ParseXMLResponseFromAWSListener parseXMLResponseFromAWSListener; - private String imageUrl; - private boolean successful; - ParseXMLReponseFromAWSAsyncTask(String response, ParseXMLResponseFromAWSListener parseXMLResponseFromAWSListener) { - this.response = response; - this.parseXMLResponseFromAWSListener = parseXMLResponseFromAWSListener; - successful = false; - } - - @Override - protected Void doInBackground(Void... voids) { - try { - XmlPullParser xmlPullParser = XmlPullParserFactory.newInstance().newPullParser(); - xmlPullParser.setInput(new StringReader(response)); - - boolean isLocationTag = false; - int eventType = xmlPullParser.getEventType(); - while (eventType != XmlPullParser.END_DOCUMENT) { - if (eventType == XmlPullParser.START_TAG) { - if (xmlPullParser.getName().equals("Location")) { - isLocationTag = true; - } - } else if (eventType == XmlPullParser.TEXT) { - if (isLocationTag) { - imageUrl = xmlPullParser.getText(); - successful = true; - return null; - } - } - eventType = xmlPullParser.next(); + @Nullable + private static String parseXMLResponseFromAWS(String response) throws XmlPullParserException, IOException { + XmlPullParser xmlPullParser = XmlPullParserFactory.newInstance().newPullParser(); + xmlPullParser.setInput(new StringReader(response)); + + boolean isLocationTag = false; + int eventType = xmlPullParser.getEventType(); + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { + if (xmlPullParser.getName().equals("Location")) { + isLocationTag = true; + } + } else if (eventType == XmlPullParser.TEXT) { + if (isLocationTag) { + return xmlPullParser.getText(); } - } catch (XmlPullParserException | IOException e) { - e.printStackTrace(); - successful = false; - } - - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - if (successful) { - parseXMLResponseFromAWSListener.parseSuccessful(imageUrl); - } else { - parseXMLResponseFromAWSListener.parseFailed(); } + eventType = xmlPullParser.next(); } - interface ParseXMLResponseFromAWSListener { - void parseSuccessful(String url); - - void parseFailed(); - } + return null; } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java b/app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java index b979a07e..2f313125 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java @@ -6,11 +6,15 @@ import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; import android.net.Uri; -import android.os.AsyncTask; import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.HandlerThread; import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.Process; import android.widget.Toast; import androidx.annotation.NonNull; @@ -19,8 +23,6 @@ import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.bumptech.glide.Glide; -import com.bumptech.glide.request.target.CustomTarget; -import com.bumptech.glide.request.transition.Transition; import org.greenrobot.eventbus.EventBus; @@ -29,22 +31,24 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.Random; +import java.util.concurrent.ExecutionException; import javax.inject.Inject; import javax.inject.Named; +import ml.docilealligator.infinityforreddit.Flair; +import ml.docilealligator.infinityforreddit.Infinity; +import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper; import ml.docilealligator.infinityforreddit.events.SubmitCrosspostEvent; import ml.docilealligator.infinityforreddit.events.SubmitImagePostEvent; import ml.docilealligator.infinityforreddit.events.SubmitTextOrLinkPostEvent; import ml.docilealligator.infinityforreddit.events.SubmitVideoOrGifPostEvent; -import ml.docilealligator.infinityforreddit.Flair; -import ml.docilealligator.infinityforreddit.Infinity; -import ml.docilealligator.infinityforreddit.utils.NotificationUtils; import ml.docilealligator.infinityforreddit.post.Post; import ml.docilealligator.infinityforreddit.post.SubmitPost; -import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.utils.APIUtils; +import ml.docilealligator.infinityforreddit.utils.NotificationUtils; import retrofit2.Retrofit; public class SubmitPostService extends Service { @@ -61,6 +65,7 @@ public class SubmitPostService extends Service { public static final int EXTRA_POST_TYPE_IMAGE = 1; public static final int EXTRA_POST_TYPE_VIDEO = 2; public static final int EXTRA_POST_TYPE_CROSSPOST = 3; + private static final String EXTRA_MEDIA_URI = "EU"; @Inject @Named("oauth") Retrofit mOauthRetrofit; @@ -72,15 +77,7 @@ public class SubmitPostService extends Service { Retrofit mUploadVideoRetrofit; @Inject CustomThemeWrapper mCustomThemeWrapper; - private String mAccessToken; - private String subredditName; - private String title; - private Flair flair; - private boolean isSpoiler; - private boolean isNSFW; - private String content; - private String kind; - private Uri mediaUri; + private ServiceHandler serviceHandler; public SubmitPostService() { } @@ -90,17 +87,59 @@ public class SubmitPostService extends Service { return null; } + // Handler that receives messages from the thread + private final class ServiceHandler extends Handler { + public ServiceHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(@NonNull Message msg) { + super.handleMessage(msg); + Bundle bundle = msg.getData(); + String accessToken = bundle.getString(EXTRA_ACCESS_TOKEN); + String subredditName = bundle.getString(EXTRA_SUBREDDIT_NAME); + String title = bundle.getString(EXTRA_TITLE); + Flair flair = bundle.getParcelable(EXTRA_FLAIR); + boolean isSpoiler = bundle.getBoolean(EXTRA_IS_SPOILER, false); + boolean isNSFW = bundle.getBoolean(EXTRA_IS_NSFW, false); + int postType = bundle.getInt(EXTRA_POST_TYPE, EXTRA_POST_TEXT_OR_LINK); + + if (postType == EXTRA_POST_TEXT_OR_LINK) { + String content = bundle.getString(EXTRA_CONTENT); + String kind = bundle.getString(EXTRA_KIND); + submitTextOrLinkPost(accessToken, subredditName, title, content, flair, isSpoiler, isNSFW, kind); + } else if (postType == EXTRA_POST_TYPE_CROSSPOST) { + String content = bundle.getString(EXTRA_CONTENT); + submitCrosspost(accessToken, subredditName, title, content, flair, isSpoiler, isNSFW); + } else if (postType == EXTRA_POST_TYPE_IMAGE) { + Uri mediaUri = Uri.parse(bundle.getString(EXTRA_MEDIA_URI)); + submitImagePost(accessToken, mediaUri, subredditName, title, flair, isSpoiler, isNSFW); + } else { + Uri mediaUri = Uri.parse(bundle.getString(EXTRA_MEDIA_URI)); + submitVideoPost(accessToken, mediaUri, subredditName, title, flair, isSpoiler, isNSFW); + } + } + } + @Override - public int onStartCommand(Intent intent, int flags, int startId) { + public void onCreate() { ((Infinity) getApplication()).getAppComponent().inject(this); + // Start up the thread running the service. Note that we create a + // separate thread because the service normally runs in the process's + // main thread, which we don't want to block. We also make it + // background priority so CPU-intensive work doesn't disrupt our UI. + HandlerThread thread = new HandlerThread("ServiceStartArguments", + Process.THREAD_PRIORITY_BACKGROUND); + thread.start(); + + // Get the HandlerThread's Looper and use it for our Handler + serviceHandler = new ServiceHandler(thread.getLooper()); + } - mAccessToken = intent.getStringExtra(EXTRA_ACCESS_TOKEN); - subredditName = intent.getStringExtra(EXTRA_SUBREDDIT_NAME); - title = intent.getStringExtra(EXTRA_TITLE); - flair = intent.getParcelableExtra(EXTRA_FLAIR); - isSpoiler = intent.getBooleanExtra(EXTRA_IS_SPOILER, false); - isNSFW = intent.getBooleanExtra(EXTRA_IS_NSFW, false); - int postType = intent.getIntExtra(EXTRA_POST_TYPE, EXTRA_POST_TEXT_OR_LINK); + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + ((Infinity) getApplication()).getAppComponent().inject(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel serviceChannel = new NotificationChannel( @@ -113,25 +152,26 @@ public class SubmitPostService extends Service { manager.createNotificationChannel(serviceChannel); } + int randomNotificationIdOffset = new Random().nextInt(10000); + int postType = intent.getIntExtra(EXTRA_POST_TYPE, EXTRA_POST_TEXT_OR_LINK); + Bundle bundle = intent.getExtras(); + if (postType == EXTRA_POST_TEXT_OR_LINK) { - content = intent.getStringExtra(EXTRA_CONTENT); - kind = intent.getStringExtra(EXTRA_KIND); - startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting)); - submitTextOrLinkPost(); + startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting)); } else if (postType == EXTRA_POST_TYPE_CROSSPOST) { - content = intent.getStringExtra(EXTRA_CONTENT); - startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting)); - submitCrosspost(); + startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting)); } else if (postType == EXTRA_POST_TYPE_IMAGE) { - mediaUri = intent.getData(); - startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting_image)); - submitImagePost(); + bundle.putString(EXTRA_MEDIA_URI, intent.getData().toString()); + startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting_image)); } else { - mediaUri = intent.getData(); - startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting_video)); - submitVideoPost(); + bundle.putString(EXTRA_MEDIA_URI, intent.getData().toString()); + startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting_video)); } + Message msg = serviceHandler.obtainMessage(); + msg.setData(bundle); + serviceHandler.sendMessage(msg); + return START_NOT_STICKY; } @@ -144,8 +184,8 @@ public class SubmitPostService extends Service { .build(); } - private void submitTextOrLinkPost() { - SubmitPost.submitTextOrLinkPost(mOauthRetrofit, mAccessToken, getResources().getConfiguration().locale, + private void submitTextOrLinkPost(String accessToken, String subredditName, String title, String content, Flair flair, boolean isSpoiler, boolean isNSFW, String kind) { + SubmitPost.submitTextOrLinkPost(mOauthRetrofit, accessToken, getResources().getConfiguration().locale, subredditName, title, content, flair, isSpoiler, isNSFW, kind, new SubmitPost.SubmitPostListener() { @Override public void submitSuccessful(Post post) { @@ -163,9 +203,9 @@ public class SubmitPostService extends Service { }); } - private void submitCrosspost() { - SubmitPost.submitCrosspost(mOauthRetrofit, mAccessToken, getResources().getConfiguration().locale, - subredditName, title, content, flair, isSpoiler, isNSFW, APIUtils.KIND_CROSSPOST, new SubmitPost.SubmitPostListener() { + private void submitCrosspost(String accessToken, String subredditName, String title, String content, Flair flair, boolean isSpoiler, boolean isNSFW) { + SubmitPost.submitCrosspost(mOauthRetrofit, accessToken, subredditName, title, content, flair, isSpoiler, + isNSFW, APIUtils.KIND_CROSSPOST, new SubmitPost.SubmitPostListener() { @Override public void submitSuccessful(Post post) { EventBus.getDefault().post(new SubmitCrosspostEvent(true, post, null)); @@ -182,49 +222,35 @@ public class SubmitPostService extends Service { }); } - private void submitImagePost() { - Glide.with(this) - .asBitmap() - .load(mediaUri) - .into(new CustomTarget<Bitmap>() { - - @Override - public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { - SubmitPost.submitImagePost(mOauthRetrofit, mUploadMediaRetrofit, mAccessToken, - getResources().getConfiguration().locale, subredditName, title, resource, - flair, isSpoiler, isNSFW, new SubmitPost.SubmitPostListener() { - @Override - public void submitSuccessful(Post post) { - EventBus.getDefault().post(new SubmitImagePostEvent(true, null)); - Toast.makeText(SubmitPostService.this, R.string.image_is_processing, Toast.LENGTH_SHORT).show(); - - stopService(); - } - - @Override - public void submitFailed(@Nullable String errorMessage) { - EventBus.getDefault().post(new SubmitImagePostEvent(false, errorMessage)); - - stopService(); - } - }); - } - - @Override - public void onLoadFailed(@Nullable Drawable errorDrawable) { - EventBus.getDefault().post(new SubmitImagePostEvent(false, getString(R.string.error_processing_image))); + private void submitImagePost(String accessToken, Uri mediaUri, String subredditName, String title, Flair flair, boolean isSpoiler, boolean isNSFW) { + try { + Bitmap resource = Glide.with(this).asBitmap().load(mediaUri).submit().get(); + SubmitPost.submitImagePost(mOauthRetrofit, mUploadMediaRetrofit, accessToken, subredditName, title, resource, + flair, isSpoiler, isNSFW, new SubmitPost.SubmitPostListener() { + @Override + public void submitSuccessful(Post post) { + EventBus.getDefault().post(new SubmitImagePostEvent(true, null)); + Toast.makeText(SubmitPostService.this, R.string.image_is_processing, Toast.LENGTH_SHORT).show(); - stopService(); - } + stopService(); + } - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { + @Override + public void submitFailed(@Nullable String errorMessage) { + EventBus.getDefault().post(new SubmitImagePostEvent(false, errorMessage)); - } - }); + stopService(); + } + }); + } catch (ExecutionException | InterruptedException e) { + e.printStackTrace(); + EventBus.getDefault().post(new SubmitImagePostEvent(false, getString(R.string.error_processing_image))); + stopService(); + } } - private void submitVideoPost() { + private void submitVideoPost(String accessToken, Uri mediaUri, String subredditName, String title, + Flair flair, boolean isSpoiler, boolean isNSFW) { try { InputStream in = getContentResolver().openInputStream(mediaUri); String type = getContentResolver().getType(mediaUri); @@ -235,67 +261,39 @@ public class SubmitPostService extends Service { cacheFilePath = getExternalCacheDir() + "/" + mediaUri.getLastPathSegment() + ".mp4"; } - new CopyFileToCacheAsyncTask(in, cacheFilePath, - new CopyFileToCacheAsyncTask.CopyFileToCacheAsyncTaskListener() { - @Override - public void success() { - Glide.with(SubmitPostService.this) - .asBitmap() - .load(mediaUri) - .into(new CustomTarget<Bitmap>() { - @Override - public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { - if (type != null) { - SubmitPost.submitVideoPost(mOauthRetrofit, mUploadMediaRetrofit, mUploadVideoRetrofit, - mAccessToken, getResources().getConfiguration().locale, subredditName, title, - new File(cacheFilePath), type, resource, flair, isSpoiler, isNSFW, - new SubmitPost.SubmitPostListener() { - @Override - public void submitSuccessful(Post post) { - EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(true, false, null)); - if (type.contains("gif")) { - Toast.makeText(SubmitPostService.this, R.string.gif_is_processing, Toast.LENGTH_SHORT).show(); - } else { - Toast.makeText(SubmitPostService.this, R.string.video_is_processing, Toast.LENGTH_SHORT).show(); - } - - stopService(); - } - - @Override - public void submitFailed(@Nullable String errorMessage) { - EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, false, errorMessage)); - - stopService(); - } - }); - } else { - EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)); - } - } - - @Override - public void onLoadFailed(@Nullable Drawable errorDrawable) { - EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)); - - stopService(); - } - - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { - - } - }); - } - - @Override - public void failed() { - EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)); + copyFileToCache(in, cacheFilePath); + + Bitmap resource = Glide.with(this).asBitmap().load(mediaUri).submit().get(); + + if (type != null) { + SubmitPost.submitVideoPost(mOauthRetrofit, mUploadMediaRetrofit, mUploadVideoRetrofit, + accessToken, subredditName, title, new File(cacheFilePath), type, resource, flair, + isSpoiler, isNSFW, new SubmitPost.SubmitPostListener() { + @Override + public void submitSuccessful(Post post) { + EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(true, false, null)); + if (type.contains("gif")) { + Toast.makeText(SubmitPostService.this, R.string.gif_is_processing, Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(SubmitPostService.this, R.string.video_is_processing, Toast.LENGTH_SHORT).show(); + } + + stopService(); + } + + @Override + public void submitFailed(@Nullable String errorMessage) { + EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, false, errorMessage)); + + stopService(); + } + }); + } else { + EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)); - stopService(); - } - }).execute(); - } catch (IOException e) { + stopService(); + } + } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)); @@ -303,47 +301,12 @@ public class SubmitPostService extends Service { } } - private static class CopyFileToCacheAsyncTask extends AsyncTask<Void, Void, Void> { - - private InputStream fileInputStream; - private String destinationFilePath; - private CopyFileToCacheAsyncTaskListener copyFileToCacheAsyncTaskListener; - private boolean parseFailed = false; - - interface CopyFileToCacheAsyncTaskListener { - void success(); - void failed(); - } - - public CopyFileToCacheAsyncTask(InputStream fileInputStream, String destinationFilePath, CopyFileToCacheAsyncTaskListener copyFileToCacheAsyncTaskListener) { - this.fileInputStream = fileInputStream; - this.destinationFilePath = destinationFilePath; - this.copyFileToCacheAsyncTaskListener = copyFileToCacheAsyncTaskListener; - } - - @Override - protected Void doInBackground(Void... voids) { - try (OutputStream out = new FileOutputStream(destinationFilePath)) { - byte[] buf = new byte[2048]; - int len; - while ((len = fileInputStream.read(buf)) > 0) { - out.write(buf, 0, len); - } - } catch (IOException e) { - e.printStackTrace(); - parseFailed = true; - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (parseFailed) { - copyFileToCacheAsyncTaskListener.failed(); - } else { - copyFileToCacheAsyncTaskListener.success(); - } + private static void copyFileToCache(InputStream fileInputStream, String destinationFilePath) throws IOException { + OutputStream out = new FileOutputStream(destinationFilePath); + byte[] buf = new byte[2048]; + int len; + while ((len = fileInputStream.read(buf)) > 0) { + out.write(buf, 0, len); } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AdvancedPreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AdvancedPreferenceFragment.java index 7b586b5c..cbb6669f 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AdvancedPreferenceFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AdvancedPreferenceFragment.java @@ -4,6 +4,7 @@ import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; +import android.os.Handler; import android.widget.Toast; import androidx.annotation.NonNull; @@ -16,19 +17,21 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder; import org.greenrobot.eventbus.EventBus; +import java.util.concurrent.Executor; + import javax.inject.Inject; import javax.inject.Named; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllPostLayoutsAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllReadPostsAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllSortTypesAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllSubredditsAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllThemesAsyncTask; -import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllUsersAsyncTask; -import ml.docilealligator.infinityforreddit.events.RecreateActivityEvent; import ml.docilealligator.infinityforreddit.Infinity; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllPostLayouts; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllReadPosts; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllSortTypes; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllSubreddits; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllThemes; +import ml.docilealligator.infinityforreddit.asynctasks.DeleteAllUsers; +import ml.docilealligator.infinityforreddit.events.RecreateActivityEvent; import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils; /** @@ -65,6 +68,8 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { @Inject @Named("nsfw_and_spoiler") SharedPreferences nsfwAndBlurringSharedPreferences; + @Inject + Executor executor; private Activity activity; @Override @@ -88,8 +93,8 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) .setTitle(R.string.are_you_sure) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteAllSubredditsAsyncTask(mRedditDataRoomDatabase, - () -> Toast.makeText(activity, R.string.delete_all_subreddits_success, Toast.LENGTH_SHORT).show()).execute()) + -> DeleteAllSubreddits.deleteAllSubreddits(executor, new Handler(), mRedditDataRoomDatabase, + () -> Toast.makeText(activity, R.string.delete_all_subreddits_success, Toast.LENGTH_SHORT).show())) .setNegativeButton(R.string.no, null) .show(); return true; @@ -101,8 +106,8 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) .setTitle(R.string.are_you_sure) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteAllUsersAsyncTask(mRedditDataRoomDatabase, - () -> Toast.makeText(activity, R.string.delete_all_users_success, Toast.LENGTH_SHORT).show()).execute()) + -> DeleteAllUsers.deleteAllUsers(executor, new Handler(), mRedditDataRoomDatabase, + () -> Toast.makeText(activity, R.string.delete_all_users_success, Toast.LENGTH_SHORT).show())) .setNegativeButton(R.string.no, null) .show(); return true; @@ -114,10 +119,11 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) .setTitle(R.string.are_you_sure) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteAllSortTypesAsyncTask(mSharedPreferences, mSortTypeSharedPreferences, () -> { + -> DeleteAllSortTypes.deleteAllSortTypes(executor, new Handler(), + mSharedPreferences, mSortTypeSharedPreferences, () -> { Toast.makeText(activity, R.string.delete_all_sort_types_success, Toast.LENGTH_SHORT).show(); EventBus.getDefault().post(new RecreateActivityEvent()); - }).execute()) + })) .setNegativeButton(R.string.no, null) .show(); return true; @@ -129,10 +135,11 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) .setTitle(R.string.are_you_sure) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteAllPostLayoutsAsyncTask(mSharedPreferences, mPostLayoutSharedPreferences, () -> { + -> DeleteAllPostLayouts.deleteAllPostLayouts(executor, new Handler(), + mSharedPreferences, mPostLayoutSharedPreferences, () -> { Toast.makeText(activity, R.string.delete_all_post_layouts_success, Toast.LENGTH_SHORT).show(); EventBus.getDefault().post(new RecreateActivityEvent()); - }).execute()) + })) .setNegativeButton(R.string.no, null) .show(); return true; @@ -144,11 +151,12 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) .setTitle(R.string.are_you_sure) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteAllThemesAsyncTask(mRedditDataRoomDatabase, lightThemeSharedPreferences, + -> DeleteAllThemes.deleteAllThemes(executor, new Handler(), + mRedditDataRoomDatabase, lightThemeSharedPreferences, darkThemeSharedPreferences, amoledThemeSharedPreferences, () -> { Toast.makeText(activity, R.string.delete_all_themes_success, Toast.LENGTH_SHORT).show(); EventBus.getDefault().post(new RecreateActivityEvent()); - }).execute()) + })) .setNegativeButton(R.string.no, null) .show(); return true; @@ -175,9 +183,10 @@ public class AdvancedPreferenceFragment extends PreferenceFragmentCompat { new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme) .setTitle(R.string.are_you_sure) .setPositiveButton(R.string.yes, (dialogInterface, i) - -> new DeleteAllReadPostsAsyncTask(mRedditDataRoomDatabase, () -> { + -> DeleteAllReadPosts.deleteAllReadPosts(executor, new Handler(), + mRedditDataRoomDatabase, () -> { Toast.makeText(activity, R.string.delete_all_read_posts_success, Toast.LENGTH_SHORT).show(); - }).execute()) + })) .setNegativeButton(R.string.no, null) .show(); return true; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/user/UserFollowing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/user/UserFollowing.java index 170ec7ed..6edbcf6d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/user/UserFollowing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/user/UserFollowing.java @@ -7,6 +7,7 @@ import androidx.annotation.NonNull; import java.util.HashMap; import java.util.Map; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; import ml.docilealligator.infinityforreddit.apis.RedditAPI; import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserDao; import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData; @@ -18,18 +19,18 @@ import retrofit2.Retrofit; public class UserFollowing { public static void followUser(Retrofit oauthRetrofit, Retrofit retrofit, String accessToken, String username, String accountName, - SubscribedUserDao subscribedUserDao, + RedditDataRoomDatabase redditDataRoomDatabase, UserFollowingListener userFollowingListener) { userFollowing(oauthRetrofit, retrofit, accessToken, username, accountName, "sub", - subscribedUserDao, userFollowingListener); + redditDataRoomDatabase.subscribedUserDao(), userFollowingListener); } public static void unfollowUser(Retrofit oauthRetrofit, Retrofit retrofit, String accessToken, String username, String accountName, - SubscribedUserDao subscribedUserDao, + RedditDataRoomDatabase redditDataRoomDatabase, UserFollowingListener userFollowingListener) { userFollowing(oauthRetrofit, retrofit, accessToken, username, accountName, "unsub", - subscribedUserDao, userFollowingListener); + redditDataRoomDatabase.subscribedUserDao(), userFollowingListener); } private static void userFollowing(Retrofit oauthRetrofit, Retrofit retrofit, String accessToken, diff --git a/app/src/main/res/layout/activity_view_post_detail.xml b/app/src/main/res/layout/activity_view_post_detail.xml index 2e3479d0..d16899f3 100644 --- a/app/src/main/res/layout/activity_view_post_detail.xml +++ b/app/src/main/res/layout/activity_view_post_detail.xml @@ -32,44 +32,11 @@ </com.google.android.material.appbar.AppBarLayout> - <androidx.swiperefreshlayout.widget.SwipeRefreshLayout - android:id="@+id/swipe_refresh_layout_view_post_detail_activity" + <androidx.viewpager2.widget.ViewPager2 + android:id="@+id/view_pager_2_view_post_detail_activity" android:layout_width="match_parent" android:layout_height="match_parent" - app:layout_behavior="@string/appbar_scrolling_view_behavior"> - - <ml.docilealligator.infinityforreddit.customviews.CustomToroContainer - android:id="@+id/recycler_view_view_post_detail" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:paddingBottom="144dp" - android:clipToPadding="false" /> - - </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> - - <LinearLayout - android:id="@+id/fetch_post_info_linear_layout_view_post_detail_activity" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:gravity="center" - android:orientation="vertical" - android:visibility="gone"> - - <ImageView - android:id="@+id/fetch_post_info_image_view_view_post_detail_activity" - android:layout_width="150dp" - android:layout_height="wrap_content" /> - - <TextView - android:id="@+id/fetch_post_info_text_view_view_post_detail_activity" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_marginTop="16dp" - android:gravity="center" - android:textSize="?attr/font_default" - android:fontFamily="?attr/font_family" /> - - </LinearLayout> + app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_view_post_detail_activity" diff --git a/app/src/main/res/layout/fragment_view_post_detail.xml b/app/src/main/res/layout/fragment_view_post_detail.xml new file mode 100644 index 00000000..7b2c314a --- /dev/null +++ b/app/src/main/res/layout/fragment_view_post_detail.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="utf-8"?> +<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="match_parent" + xmlns:app="http://schemas.android.com/apk/res-auto" + tools:context=".fragments.ViewPostDetailFragment"> + + <androidx.swiperefreshlayout.widget.SwipeRefreshLayout + android:id="@+id/swipe_refresh_layout_view_post_detail_fragment" + android:layout_width="match_parent" + android:layout_height="match_parent" + app:layout_behavior="@string/appbar_scrolling_view_behavior"> + + <ml.docilealligator.infinityforreddit.customviews.CustomToroContainer + android:id="@+id/recycler_view_view_post_detail_fragment" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:paddingBottom="144dp" + android:clipToPadding="false" /> + + </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> + + <LinearLayout + android:id="@+id/fetch_post_info_linear_layout_view_post_detail_fragment" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:gravity="center" + android:orientation="vertical" + android:visibility="gone"> + + <ImageView + android:id="@+id/fetch_post_info_image_view_view_post_detail_fragment" + android:layout_width="150dp" + android:layout_height="wrap_content" /> + + <TextView + android:id="@+id/fetch_post_info_text_view_view_post_detail_fragment" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginTop="16dp" + android:gravity="center" + android:textSize="?attr/font_default" + android:fontFamily="?attr/font_family" /> + + </LinearLayout> + +</FrameLayout>
\ No newline at end of file diff --git a/app/src/main/res/menu/view_post_detail_activity.xml b/app/src/main/res/menu/view_post_detail_fragment.xml index 454603aa..d9e66bd6 100644 --- a/app/src/main/res/menu/view_post_detail_activity.xml +++ b/app/src/main/res/menu/view_post_detail_fragment.xml @@ -2,7 +2,7 @@ <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item - android:id="@+id/action_comment_view_post_detail_activity" + android:id="@+id/action_comment_view_post_detail_fragment" android:orderInCategory="1" android:title="@string/action_add_comment" android:icon="@drawable/ic_comment_toolbar_24dp" @@ -10,92 +10,92 @@ android:visible="false" /> <item - android:id="@+id/action_save_view_post_detail_activity" + android:id="@+id/action_save_view_post_detail_fragment" android:orderInCategory="2" android:title="@string/action_save_post" app:showAsAction="ifRoom" android:visible="false" /> <item - android:id="@+id/action_sort_view_post_detail_activity" + android:id="@+id/action_sort_view_post_detail_fragment" android:orderInCategory="3" android:title="@string/action_sort" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_refresh_view_post_detail_activity" + android:id="@+id/action_refresh_view_post_detail_fragment" android:orderInCategory="4" android:title="@string/action_refresh" app:showAsAction="never" /> <item - android:id="@+id/action_view_crosspost_parent_view_post_detail_activity" + android:id="@+id/action_view_crosspost_parent_view_post_detail_fragment" android:orderInCategory="5" android:title="@string/action_view_crosspost_parent" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_hide_view_post_detail_activity" + android:id="@+id/action_hide_view_post_detail_fragment" android:orderInCategory="6" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_edit_view_post_detail_activity" + android:id="@+id/action_edit_view_post_detail_fragment" android:orderInCategory="7" android:title="@string/action_edit_post" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_delete_view_post_detail_activity" + android:id="@+id/action_delete_view_post_detail_fragment" android:orderInCategory="8" android:title="@string/action_delete_post" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_nsfw_view_post_detail_activity" + android:id="@+id/action_nsfw_view_post_detail_fragment" android:orderInCategory="9" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_spoiler_view_post_detail_activity" + android:id="@+id/action_spoiler_view_post_detail_fragment" android:orderInCategory="10" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_edit_flair_view_post_detail_activity" + android:id="@+id/action_edit_flair_view_post_detail_fragment" android:orderInCategory="11" android:title="@string/action_edit_flair" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_give_award_view_post_detail_activity" + android:id="@+id/action_give_award_view_post_detail_fragment" android:orderInCategory="12" android:title="@string/action_give_award" app:showAsAction="never" /> <item - android:id="@+id/action_report_view_post_detail_activity" + android:id="@+id/action_report_view_post_detail_fragment" android:orderInCategory="13" android:title="@string/action_report" app:showAsAction="never" /> <item - android:id="@+id/action_see_removed_view_post_detail_activity" + android:id="@+id/action_see_removed_view_post_detail_fragment" android:orderInCategory="14" android:title="@string/action_see_removed" app:showAsAction="never" android:visible="false" /> <item - android:id="@+id/action_crosspost_view_post_detail_activity" + android:id="@+id/action_crosspost_view_post_detail_fragment" android:orderInCategory="15" android:title="@string/action_crosspost" app:showAsAction="never" /> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 71bf3538..85441699 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -24,8 +24,8 @@ <string name="edit_multi_reddit_activity_label">"编辑版块聚合"</string> <string name="selected_subeddits_activity_label">"被选中的版块"</string> <string name="report_activity_label">"报告"</string> - <string name="view_imgur_media_activity_image_label">"图片"</string> - <string name="view_imgur_media_activity_video_label">"视频"</string> + <string name="view_imgur_media_activity_image_label">"图片 %1$d/%2$d"</string> + <string name="view_imgur_media_activity_video_label">"视频 %1$d/%2$d"</string> <string name="send_private_message_activity_label">"私信"</string> <string name="view_reddit_gallery_activity_image_label">"图片 %1$d/%2$d "</string> |