aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/main/java')
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java25
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java42
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/FetchGfycatOrRedgifsVideoLinks.java89
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/FetchRules.java50
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/Infinity.java89
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/RPANBroadcast.java236
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/RPANComment.java15
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/RedditGalleryPayload.java96
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/TrendingSearch.java54
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/UploadImageEnabledActivity.java7
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/UploadedImage.java42
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/account/Account.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/account/AccountDao.java3
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/CommentActivity.java211
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java12
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemePreviewActivity.java17
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomizeThemeActivity.java3
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java208
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java191
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/FetchRandomSubredditOrPostActivity.java7
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/FilteredPostsActivity.java148
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/FullMarkdownActivity.java46
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/GiveAwardActivity.java4
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/InboxActivity.java145
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/LinkResolverActivity.java24
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/LockScreenActivity.java83
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java242
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostFilterPreferenceActivity.java42
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostGalleryActivity.java709
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java153
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java31
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java209
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java126
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/RPANActivity.java412
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java8
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/RulesActivity.java97
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchActivity.java86
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java120
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectedSubredditsAndUsersActivity.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java128
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java5
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/TrendingActivity.java328
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java148
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java68
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java94
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java58
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java172
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java118
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewVideoActivity.java266
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/activities/WikiActivity.java370
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsListingRecyclerViewAdapter.java5
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsRecyclerViewAdapter.java1715
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FlairBottomSheetRecyclerViewAdapter.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MarkdownBottomBarRecyclerViewAdapter.java14
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/NavigationDrawerRecyclerViewAdapter.java150
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostDetailRecyclerViewAdapter.java (renamed from app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java)1900
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java305
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RPANCommentStreamRecyclerViewAdapter.java83
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RedditGallerySubmissionRecyclerViewAdapter.java231
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditAutocompleteRecyclerViewAdapter.java103
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/TrendingSearchRecyclerViewAdapter.java228
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UploadedImagesRecyclerViewAdapter.java61
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/apis/RedditAPI.java26
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/apis/Strapi.java13
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java7
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/CopyTextBottomSheetFragment.java27
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/FlairBottomSheetFragment.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/PostTypeBottomSheetFragment.java8
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/SelectOrCaptureImageBottomSheetFragment.java52
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/UploadedImagesBottomSheetFragment.java67
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/broadcastreceivers/WallpaperChangeReceiver.java18
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/comment/Comment.java1
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/comment/FetchComment.java17
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/comment/ParseComment.java196
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/comment/SendComment.java12
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/customtheme/CustomThemeWrapper.java278
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ClickableMotionLayout.java39
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/customviews/CommentIndentationView.java25
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/customviews/LinearLayoutManagerBugFixed.java25
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/customviews/MarkwonLinearLayoutManager.java4
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ViewPagerBugFixed.java37
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeDefaultLinkPostLayoutEvent.java9
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeHidePostFlairEvent.java9
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeRememberMutingOptionInPostFeedEvent.java9
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/events/SubmitGalleryPostEvent.java13
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/events/ToggleSecureModeEvent.java9
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/CommentsListingFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/InboxFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java130
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java25
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java6
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java189
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurVideoFragment.java64
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java383
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRPANBroadcastFragment.java404
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java159
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryVideoFragment.java66
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/post/FetchPost.java34
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/post/ParsePost.java293
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSource.java69
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSourceFactory.java40
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/post/PostViewModel.java76
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java149
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadMediaService.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadRedditVideoService.java3
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/services/MaterialYouService.java98
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java149
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/AcknowledgementFragment.java4
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/CrashReportsFragment.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/CustomizeMainPageTabsFragment.java30
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/GesturesAndButtonsPreferenceFragment.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostDetailsPreferenceFragment.java18
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostPreferenceFragment.java18
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/SecurityPreferenceFragment.java17
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/ThemePreferenceFragment.java64
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/Translation.java25
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/TranslationFragment.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/settings/VideoPreferenceFragment.java9
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/ParseSubredditData.java8
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/SubredditSubscription.java5
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/APIUtils.java2
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/JSONUtils.java36
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/MaterialYouUtils.java155
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/NotificationUtils.java3
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/SharedPreferencesUtils.java17
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/UploadImageUtils.java107
-rw-r--r--app/src/main/java/ml/docilealligator/infinityforreddit/utils/Utils.java103
136 files changed, 10668 insertions, 3905 deletions
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java
index b0506a82..2fc08bd9 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java
@@ -21,15 +21,18 @@ import ml.docilealligator.infinityforreddit.activities.FullMarkdownActivity;
import ml.docilealligator.infinityforreddit.activities.GiveAwardActivity;
import ml.docilealligator.infinityforreddit.activities.InboxActivity;
import ml.docilealligator.infinityforreddit.activities.LinkResolverActivity;
+import ml.docilealligator.infinityforreddit.activities.LockScreenActivity;
import ml.docilealligator.infinityforreddit.activities.LoginActivity;
import ml.docilealligator.infinityforreddit.activities.MainActivity;
import ml.docilealligator.infinityforreddit.activities.MultiredditSelectionActivity;
-import ml.docilealligator.infinityforreddit.activities.PostFilterUsageListingActivity;
import ml.docilealligator.infinityforreddit.activities.PostFilterPreferenceActivity;
+import ml.docilealligator.infinityforreddit.activities.PostFilterUsageListingActivity;
+import ml.docilealligator.infinityforreddit.activities.PostGalleryActivity;
import ml.docilealligator.infinityforreddit.activities.PostImageActivity;
import ml.docilealligator.infinityforreddit.activities.PostLinkActivity;
import ml.docilealligator.infinityforreddit.activities.PostTextActivity;
import ml.docilealligator.infinityforreddit.activities.PostVideoActivity;
+import ml.docilealligator.infinityforreddit.activities.RPANActivity;
import ml.docilealligator.infinityforreddit.activities.ReportActivity;
import ml.docilealligator.infinityforreddit.activities.RulesActivity;
import ml.docilealligator.infinityforreddit.activities.SearchActivity;
@@ -45,6 +48,7 @@ import ml.docilealligator.infinityforreddit.activities.SubredditMultiselectionAc
import ml.docilealligator.infinityforreddit.activities.SubredditSelectionActivity;
import ml.docilealligator.infinityforreddit.activities.SubscribedThingListingActivity;
import ml.docilealligator.infinityforreddit.activities.SuicidePreventionActivity;
+import ml.docilealligator.infinityforreddit.activities.TrendingActivity;
import ml.docilealligator.infinityforreddit.activities.ViewImageOrGifActivity;
import ml.docilealligator.infinityforreddit.activities.ViewImgurMediaActivity;
import ml.docilealligator.infinityforreddit.activities.ViewMultiRedditDetailActivity;
@@ -55,6 +59,7 @@ import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivi
import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity;
import ml.docilealligator.infinityforreddit.activities.ViewVideoActivity;
import ml.docilealligator.infinityforreddit.activities.WebViewActivity;
+import ml.docilealligator.infinityforreddit.activities.WikiActivity;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment;
import ml.docilealligator.infinityforreddit.fragments.CommentsListingFragment;
import ml.docilealligator.infinityforreddit.fragments.FollowedUsersListingFragment;
@@ -68,10 +73,12 @@ 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.ViewRPANBroadcastFragment;
import ml.docilealligator.infinityforreddit.fragments.ViewRedditGalleryImageOrGifFragment;
import ml.docilealligator.infinityforreddit.fragments.ViewRedditGalleryVideoFragment;
import ml.docilealligator.infinityforreddit.services.DownloadMediaService;
import ml.docilealligator.infinityforreddit.services.DownloadRedditVideoService;
+import ml.docilealligator.infinityforreddit.services.MaterialYouService;
import ml.docilealligator.infinityforreddit.services.SubmitPostService;
import ml.docilealligator.infinityforreddit.settings.AdvancedPreferenceFragment;
import ml.docilealligator.infinityforreddit.settings.CrashReportsFragment;
@@ -263,4 +270,20 @@ public interface AppComponent {
void inject(CrashReportsFragment crashReportsFragment);
void inject(AnonymousSubscriptionsActivity anonymousSubscriptionsActivity);
+
+ void inject(LockScreenActivity lockScreenActivity);
+
+ void inject(MaterialYouService materialYouService);
+
+ void inject(RPANActivity rpanActivity);
+
+ void inject(ViewRPANBroadcastFragment viewRPANBroadcastFragment);
+
+ void inject(PostGalleryActivity postGalleryActivity);
+
+ void inject(TrendingActivity trendingActivity);
+
+ void inject(WikiActivity wikiActivity);
+
+ void inject(Infinity infinity);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java
index 845f1b49..49120eca 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java
@@ -44,7 +44,7 @@ class AppModule {
@Provides
@Named("oauth")
@Singleton
- Retrofit provideOauthRetrofit(OkHttpClient okHttpClient) {
+ Retrofit provideOauthRetrofit(@Named("default") OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl(APIUtils.OAUTH_API_BASE_URI)
.client(okHttpClient)
@@ -153,6 +153,18 @@ class AppModule {
}
@Provides
+ @Named("strapi")
+ @Singleton
+ Retrofit providestrapiRetrofit(@Named("default") OkHttpClient okHttpClient) {
+ return new Retrofit.Builder()
+ .baseUrl(APIUtils.STRAPI_BASE_URI)
+ .client(okHttpClient)
+ .addConverterFactory(ScalarsConverterFactory.create())
+ .build();
+ }
+
+ @Provides
+ @Named("default")
@Singleton
OkHttpClient provideOkHttpClient(@Named("no_oauth") Retrofit retrofit, RedditDataRoomDatabase accountRoomDatabase,
@Named("current_account") SharedPreferences currentAccountSharedPreferences) {
@@ -166,6 +178,17 @@ class AppModule {
}
@Provides
+ @Named("rpan")
+ @Singleton
+ OkHttpClient provideRPANOkHttpClient() {
+ return new OkHttpClient.Builder()
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .build();
+ }
+
+ @Provides
@Singleton
RedditDataRoomDatabase provideRedditDataRoomDatabase() {
return RedditDataRoomDatabase.getDatabase(mApplication);
@@ -254,6 +277,12 @@ class AppModule {
}
@Provides
+ @Named("post_details")
+ SharedPreferences providePostDetailsSharedPreferences() {
+ return mApplication.getSharedPreferences(SharedPreferencesUtils.POST_DETAILS_SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
+ }
+
+ @Provides
@Singleton
CustomThemeWrapper provideCustomThemeWrapper(@Named("light_theme") SharedPreferences lightThemeSharedPreferences,
@Named("dark_theme") SharedPreferences darkThemeSharedPreferences,
@@ -263,10 +292,15 @@ class AppModule {
@Provides
@Singleton
- ExoCreator provideExoCreator() {
- SimpleCache cache = new SimpleCache(new File(mApplication.getCacheDir(), "/toro_cache"),
+ SimpleCache provideSimpleCache() {
+ return new SimpleCache(new File(mApplication.getCacheDir(), "/exoplayer"),
new LeastRecentlyUsedCacheEvictor(200 * 1024 * 1024), new ExoDatabaseProvider(mApplication));
- Config config = new Config.Builder(mApplication).setMediaSourceBuilder(MediaSourceBuilder.LOOPING).setCache(cache)
+ }
+
+ @Provides
+ @Singleton
+ ExoCreator provideExoCreator(SimpleCache simpleCache) {
+ Config config = new Config.Builder(mApplication).setMediaSourceBuilder(MediaSourceBuilder.LOOPING).setCache(simpleCache)
.build();
return ToroExo.with(mApplication).getCreator(config);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchGfycatOrRedgifsVideoLinks.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchGfycatOrRedgifsVideoLinks.java
index 1fc8960c..19dc8a9c 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchGfycatOrRedgifsVideoLinks.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchGfycatOrRedgifsVideoLinks.java
@@ -1,12 +1,14 @@
package ml.docilealligator.infinityforreddit;
-import android.os.AsyncTask;
+import android.os.Handler;
import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
+import java.util.concurrent.Executor;
+
import ml.docilealligator.infinityforreddit.apis.GfycatAPI;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
import retrofit2.Call;
@@ -16,8 +18,6 @@ import retrofit2.Retrofit;
public class FetchGfycatOrRedgifsVideoLinks {
private FetchGfycatOrRedgifsVideoLinksListener fetchGfycatOrRedgifsVideoLinksListener;
- private ParseGfycatVideoLinksAsyncTask parseGfycatVideoLinksAsyncTask;
- Retrofit gfycatRetrofit;
Call<String> gfycatCall;
public interface FetchGfycatOrRedgifsVideoLinksListener {
@@ -29,13 +29,14 @@ public class FetchGfycatOrRedgifsVideoLinks {
this.fetchGfycatOrRedgifsVideoLinksListener = fetchGfycatOrRedgifsVideoLinksListener;
}
- public static void fetchGfycatOrRedgifsVideoLinks(Retrofit gfycatRetrofit, String gfycatId,
+ public static void fetchGfycatOrRedgifsVideoLinks(Executor executor, Handler handler, Retrofit gfycatRetrofit,
+ String gfycatId,
FetchGfycatOrRedgifsVideoLinksListener fetchGfycatOrRedgifsVideoLinksListener) {
gfycatRetrofit.create(GfycatAPI.class).getGfycatData(gfycatId).enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- new ParseGfycatVideoLinksAsyncTask(response.body(), fetchGfycatOrRedgifsVideoLinksListener).execute();
+ parseGfycatVideoLinks(executor, handler, response.body(), fetchGfycatOrRedgifsVideoLinksListener);
} else {
fetchGfycatOrRedgifsVideoLinksListener.failed(response.code());
}
@@ -48,7 +49,8 @@ public class FetchGfycatOrRedgifsVideoLinks {
});
}
- public void fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(Retrofit gfycatRetrofit, Retrofit redgifsRetrofit,
+ public void fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(Executor executor, Handler handler,
+ Retrofit gfycatRetrofit, Retrofit redgifsRetrofit,
String gfycatId, boolean isGfycatVideo,
boolean automaticallyTryRedgifs) {
gfycatCall = (isGfycatVideo ? gfycatRetrofit : redgifsRetrofit).create(GfycatAPI.class).getGfycatData(gfycatId);
@@ -56,11 +58,11 @@ public class FetchGfycatOrRedgifsVideoLinks {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- parseGfycatVideoLinksAsyncTask = new ParseGfycatVideoLinksAsyncTask(response.body(), fetchGfycatOrRedgifsVideoLinksListener);
- parseGfycatVideoLinksAsyncTask.execute();
+ parseGfycatVideoLinks(executor, handler, response.body(), fetchGfycatOrRedgifsVideoLinksListener);
} else {
if (response.code() == 404 && isGfycatVideo && automaticallyTryRedgifs) {
- fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(gfycatRetrofit, redgifsRetrofit, gfycatId, false, false);
+ fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(executor, handler, gfycatRetrofit,
+ redgifsRetrofit, gfycatId, false, false);
} else {
fetchGfycatOrRedgifsVideoLinksListener.failed(response.code());
}
@@ -78,60 +80,33 @@ public class FetchGfycatOrRedgifsVideoLinks {
if (gfycatCall != null && !gfycatCall.isCanceled()) {
gfycatCall.cancel();
}
- if (parseGfycatVideoLinksAsyncTask != null && !parseGfycatVideoLinksAsyncTask.isCancelled()) {
- parseGfycatVideoLinksAsyncTask.cancel(true);
- }
}
- private static class ParseGfycatVideoLinksAsyncTask extends AsyncTask<Void, Void, Void> {
-
- private String response;
- private String webm;
- private String mp4;
- private boolean parseFailed = false;
- private FetchGfycatOrRedgifsVideoLinksListener fetchGfycatOrRedgifsVideoLinksListener;
-
- ParseGfycatVideoLinksAsyncTask(String response, FetchGfycatOrRedgifsVideoLinksListener fetchGfycatOrRedgifsVideoLinksListener) {
- this.response = response;
- this.fetchGfycatOrRedgifsVideoLinksListener = fetchGfycatOrRedgifsVideoLinksListener;
- }
-
- @Override
- protected Void doInBackground(Void... voids) {
- try {
- JSONObject jsonObject = new JSONObject(response);
- mp4 = jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).has(JSONUtils.MP4_URL_KEY) ?
- jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).getString(JSONUtils.MP4_URL_KEY)
- : jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY)
+ private static void parseGfycatVideoLinks(Executor executor, Handler handler, String response,
+ FetchGfycatOrRedgifsVideoLinksListener fetchGfycatOrRedgifsVideoLinksListener) {
+ try {
+ JSONObject jsonObject = new JSONObject(response);
+ String mp4 = jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).has(JSONUtils.MP4_URL_KEY) ?
+ jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).getString(JSONUtils.MP4_URL_KEY)
+ : jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY)
+ .getJSONObject(JSONUtils.CONTENT_URLS_KEY)
+ .getJSONObject(JSONUtils.MP4_KEY)
+ .getString(JSONUtils.URL_KEY);
+ String webm;
+ if (jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).has(JSONUtils.WEBM_URL_KEY)) {
+ webm = jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).getString(JSONUtils.WEBM_URL_KEY);
+ } else if (jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).getJSONObject(JSONUtils.CONTENT_URLS_KEY).has(JSONUtils.WEBM_KEY)) {
+ webm = jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY)
.getJSONObject(JSONUtils.CONTENT_URLS_KEY)
- .getJSONObject(JSONUtils.MP4_KEY)
+ .getJSONObject(JSONUtils.WEBM_KEY)
.getString(JSONUtils.URL_KEY);
- if (jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).has(JSONUtils.WEBM_URL_KEY)) {
- webm = jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).getString(JSONUtils.WEBM_URL_KEY);
- } else if (jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY).getJSONObject(JSONUtils.CONTENT_URLS_KEY).has(JSONUtils.WEBM_KEY)) {
- webm = jsonObject.getJSONObject(JSONUtils.GFY_ITEM_KEY)
- .getJSONObject(JSONUtils.CONTENT_URLS_KEY)
- .getJSONObject(JSONUtils.WEBM_KEY)
- .getString(JSONUtils.URL_KEY);
- } else {
- webm = mp4;
- }
- } catch (JSONException e) {
- e.printStackTrace();
- parseFailed = true;
- }
-
- return null;
- }
-
- @Override
- protected void onPostExecute(Void aVoid) {
- super.onPostExecute(aVoid);
- if (parseFailed) {
- fetchGfycatOrRedgifsVideoLinksListener.failed(-1);
} else {
- fetchGfycatOrRedgifsVideoLinksListener.success(webm, mp4);
+ webm = mp4;
}
+ handler.post(() -> fetchGfycatOrRedgifsVideoLinksListener.success(webm, mp4));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(() -> fetchGfycatOrRedgifsVideoLinksListener.failed(-1));
}
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchRules.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchRules.java
index 69f0fa58..e1f9c5e7 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchRules.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchRules.java
@@ -1,6 +1,6 @@
package ml.docilealligator.infinityforreddit;
-import android.os.AsyncTask;
+import android.os.Handler;
import androidx.annotation.NonNull;
@@ -9,6 +9,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
@@ -24,25 +25,25 @@ public class FetchRules {
void failed();
}
- public static void fetchRules(Retrofit retrofit, String subredditName, FetchRulesListener fetchRulesListener) {
-
+ public static void fetchRules(Executor executor, Handler handler, Retrofit retrofit, String subredditName,
+ FetchRulesListener fetchRulesListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> rulesCall = api.getRules(subredditName);
rulesCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- new ParseRulesAsyncTask(response.body(), new ParseRulesAsyncTask.ParseRulesAsyncTaskListener() {
+ parseRules(executor, handler, response.body(), new FetchRulesListener() {
@Override
- public void parseSuccessful(ArrayList<Rule> rules) {
+ public void success(ArrayList<Rule> rules) {
fetchRulesListener.success(rules);
}
@Override
- public void parseFailed() {
+ public void failed() {
fetchRulesListener.failed();
}
- }).execute();
+ });
} else {
fetchRulesListener.failed();
}
@@ -55,17 +56,9 @@ public class FetchRules {
});
}
- private static class ParseRulesAsyncTask extends AsyncTask<Void, ArrayList<Rule>, ArrayList<Rule>> {
- private String response;
- private ParseRulesAsyncTask.ParseRulesAsyncTaskListener parseRulesAsyncTaskListener;
-
- ParseRulesAsyncTask(String response, ParseRulesAsyncTask.ParseRulesAsyncTaskListener parseRulesAsyncTaskListener) {
- this.response = response;
- this.parseRulesAsyncTaskListener = parseRulesAsyncTaskListener;
- }
-
- @Override
- protected ArrayList<Rule> doInBackground(Void... voids) {
+ private static void parseRules(Executor executor, Handler handler, String response,
+ FetchRulesListener fetchRulesListener) {
+ executor.execute(() -> {
try {
JSONArray rulesArray = new JSONObject(response).getJSONArray(JSONUtils.RULES_KEY);
ArrayList<Rule> rules = new ArrayList<>();
@@ -77,26 +70,11 @@ public class FetchRules {
}
rules.add(new Rule(shortName, description));
}
- return rules;
+ handler.post(() -> fetchRulesListener.success(rules));
} catch (JSONException e) {
e.printStackTrace();
+ handler.post(fetchRulesListener::failed);
}
- return null;
- }
-
- @Override
- protected void onPostExecute(ArrayList<Rule> rules) {
- if (rules != null) {
- parseRulesAsyncTaskListener.parseSuccessful(rules);
- } else {
- parseRulesAsyncTaskListener.parseFailed();
- }
- }
-
- interface ParseRulesAsyncTaskListener {
- void parseSuccessful(ArrayList<Rule> rules);
-
- void parseFailed();
- }
+ });
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Infinity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Infinity.java
index 274d1ad7..1c7c7649 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/Infinity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Infinity.java
@@ -1,37 +1,101 @@
package ml.docilealligator.infinityforreddit;
+import android.app.Activity;
import android.app.Application;
+import android.content.Intent;
import android.content.IntentFilter;
+import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
+import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import androidx.lifecycle.LifecycleObserver;
import com.evernote.android.state.StateSaver;
import com.livefront.bridge.Bridge;
import com.livefront.bridge.SavedStateHandler;
import org.greenrobot.eventbus.EventBus;
+import org.greenrobot.eventbus.Subscribe;
+
+import javax.inject.Inject;
+import javax.inject.Named;
import ml.docilealligator.infinityforreddit.broadcastreceivers.NetworkWifiStatusReceiver;
+import ml.docilealligator.infinityforreddit.broadcastreceivers.WallpaperChangeReceiver;
import ml.docilealligator.infinityforreddit.events.ChangeNetworkStatusEvent;
+import ml.docilealligator.infinityforreddit.events.ToggleSecureModeEvent;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
-public class Infinity extends Application {
+public class Infinity extends Application implements LifecycleObserver {
private AppComponent mAppComponent;
private NetworkWifiStatusReceiver mNetworkWifiStatusReceiver;
+ //private boolean lock = false;
+ private boolean isSecureMode;
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
@Override
public void onCreate() {
super.onCreate();
- //RedScreenOfDeath.init(this);
-
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
+ mAppComponent.inject(this);
+
+ isSecureMode = mSharedPreferences.getBoolean(SharedPreferencesUtils.SECURE_MODE, false);
+
+ registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
+ @Override
+ public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
+ if (isSecureMode) {
+ activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
+ }
+ }
+
+ @Override
+ public void onActivityStarted(@NonNull Activity activity) {
+
+ }
+
+ @Override
+ public void onActivityResumed(@NonNull Activity activity) {
+ /*if (lock && !(activity instanceof LockScreenActivity)) {
+ lock = false;
+ Intent intent = new Intent(activity, LockScreenActivity.class);
+ activity.startActivity(intent);
+ }*/
+ }
+
+ @Override
+ public void onActivityPaused(@NonNull Activity activity) {
+
+ }
+
+ @Override
+ public void onActivityStopped(@NonNull Activity activity) {
+
+ }
+
+ @Override
+ public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
+
+ }
+
+ @Override
+ public void onActivityDestroyed(@NonNull Activity activity) {
+
+ }
+ });
+
+ //ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
+
Bridge.initialize(getApplicationContext(), new SavedStateHandler() {
@Override
public void saveInstanceState(@NonNull Object target, @NonNull Bundle state) {
@@ -46,12 +110,31 @@ public class Infinity extends Application {
EventBus.builder().addIndex(new EventBusIndex()).installDefaultEventBus();
+ EventBus.getDefault().register(this);
+
mNetworkWifiStatusReceiver =
new NetworkWifiStatusReceiver(() -> EventBus.getDefault().post(new ChangeNetworkStatusEvent(Utils.getConnectedNetwork(getApplicationContext()))));
registerReceiver(mNetworkWifiStatusReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
+
+ registerReceiver(new WallpaperChangeReceiver(), new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED));
+ }
+
+ /*@OnLifecycleEvent(Lifecycle.Event.ON_START)
+ public void appInForeground() {
+ lock = true;
}
+ @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
+ public void appInBackground(){
+
+ }*/
+
public AppComponent getAppComponent() {
return mAppComponent;
}
+
+ @Subscribe
+ public void onToggleSecureModeEvent(ToggleSecureModeEvent secureModeEvent) {
+ isSecureMode = secureModeEvent.isSecureMode;
+ }
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RPANBroadcast.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RPANBroadcast.java
new file mode 100644
index 00000000..d7c936c2
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RPANBroadcast.java
@@ -0,0 +1,236 @@
+package ml.docilealligator.infinityforreddit;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
+
+public class RPANBroadcast implements Parcelable {
+
+ public int upvotes;
+ public int downvotes;
+ public int uniqueWatchers;
+ public int continuousWatchers;
+ public int totalContinuousWatchers;
+ public boolean chatDisabled;
+ public double broadcastTime;
+ public double estimatedRemainingTime;
+
+ public RPANPost rpanPost;
+ public RPANStream rpanStream;
+
+ public RPANBroadcast(int upvotes, int downvotes, int uniqueWatchers, int continuousWatchers,
+ int totalContinuousWatchers, boolean chatDisabled, double broadcastTime,
+ double estimatedRemainingTime, RPANPost rpanPost, RPANStream rpanStream) {
+ this.upvotes = upvotes;
+ this.downvotes = downvotes;
+ this.uniqueWatchers = uniqueWatchers;
+ this.continuousWatchers = continuousWatchers;
+ this.totalContinuousWatchers = totalContinuousWatchers;
+ this.chatDisabled = chatDisabled;
+ this.broadcastTime = broadcastTime;
+ this.estimatedRemainingTime = estimatedRemainingTime;
+ this.rpanPost = rpanPost;
+ this.rpanStream = rpanStream;
+ }
+
+ protected RPANBroadcast(Parcel in) {
+ upvotes = in.readInt();
+ downvotes = in.readInt();
+ uniqueWatchers = in.readInt();
+ continuousWatchers = in.readInt();
+ totalContinuousWatchers = in.readInt();
+ chatDisabled = in.readByte() != 0;
+ broadcastTime = in.readDouble();
+ estimatedRemainingTime = in.readDouble();
+ rpanPost = in.readParcelable(RPANPost.class.getClassLoader());
+ rpanStream = in.readParcelable(RPANStream.class.getClassLoader());
+ }
+
+ public static final Creator<RPANBroadcast> CREATOR = new Creator<RPANBroadcast>() {
+ @Override
+ public RPANBroadcast createFromParcel(Parcel in) {
+ return new RPANBroadcast(in);
+ }
+
+ @Override
+ public RPANBroadcast[] newArray(int size) {
+ return new RPANBroadcast[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeInt(upvotes);
+ parcel.writeInt(downvotes);
+ parcel.writeInt(uniqueWatchers);
+ parcel.writeInt(continuousWatchers);
+ parcel.writeInt(totalContinuousWatchers);
+ parcel.writeByte((byte) (chatDisabled ? 1 : 0));
+ parcel.writeDouble(broadcastTime);
+ parcel.writeDouble(estimatedRemainingTime);
+ parcel.writeParcelable(rpanPost, i);
+ parcel.writeParcelable(rpanStream, i);
+ }
+
+ public static class RPANPost implements Parcelable {
+ public String fullname;
+ public String title;
+ public String subredditName;
+ public String subredditIconUrl;
+ public String username;
+ public int postScore;
+ public String voteState;
+ public double upvoteRatio;
+ public String postPermalink;
+ public String rpanUrl;
+ public boolean isNsfw;
+ public boolean isLocked;
+ public boolean isArchived;
+ public boolean isSpoiler;
+ public String suggestedCommentSort;
+ public String liveCommentsWebsocketUrl;
+
+ public RPANPost(String fullname, String title, String subredditName, String subredditIconUrl, String username,
+ int postScore, String voteState, double upvoteRatio, String postPermalink, String rpanUrl,
+ boolean isNsfw, boolean isLocked, boolean isArchived, boolean isSpoiler,
+ String suggestedCommentSort, String liveCommentsWebsocketUrl) {
+ this.fullname = fullname;
+ this.title = title;
+ this.subredditName = subredditName;
+ this.subredditIconUrl = subredditIconUrl;
+ this.username = username;
+ this.postScore = postScore;
+ this.voteState = voteState;
+ this.upvoteRatio = upvoteRatio;
+ this.postPermalink = APIUtils.API_BASE_URI + postPermalink;
+ this.rpanUrl = rpanUrl;
+ this.isNsfw = isNsfw;
+ this.isLocked = isLocked;
+ this.isArchived = isArchived;
+ this.isSpoiler = isSpoiler;
+ this.suggestedCommentSort = suggestedCommentSort;
+ this.liveCommentsWebsocketUrl = liveCommentsWebsocketUrl;
+ }
+
+ protected RPANPost(Parcel in) {
+ fullname = in.readString();
+ title = in.readString();
+ subredditName = in.readString();
+ subredditIconUrl = in.readString();
+ username = in.readString();
+ postScore = in.readInt();
+ voteState = in.readString();
+ upvoteRatio = in.readDouble();
+ postPermalink = in.readString();
+ rpanUrl = in.readString();
+ isNsfw = in.readByte() != 0;
+ isLocked = in.readByte() != 0;
+ isArchived = in.readByte() != 0;
+ isSpoiler = in.readByte() != 0;
+ suggestedCommentSort = in.readString();
+ liveCommentsWebsocketUrl = in.readString();
+ }
+
+ public static final Creator<RPANPost> CREATOR = new Creator<RPANPost>() {
+ @Override
+ public RPANPost createFromParcel(Parcel in) {
+ return new RPANPost(in);
+ }
+
+ @Override
+ public RPANPost[] newArray(int size) {
+ return new RPANPost[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeString(fullname);
+ parcel.writeString(title);
+ parcel.writeString(subredditName);
+ parcel.writeString(subredditIconUrl);
+ parcel.writeString(username);
+ parcel.writeInt(postScore);
+ parcel.writeString(voteState);
+ parcel.writeDouble(upvoteRatio);
+ parcel.writeString(postPermalink);
+ parcel.writeString(rpanUrl);
+ parcel.writeByte((byte) (isNsfw ? 1 : 0));
+ parcel.writeByte((byte) (isLocked ? 1 : 0));
+ parcel.writeByte((byte) (isArchived ? 1 : 0));
+ parcel.writeByte((byte) (isSpoiler ? 1 : 0));
+ parcel.writeString(suggestedCommentSort);
+ parcel.writeString(liveCommentsWebsocketUrl);
+ }
+ }
+
+ public static class RPANStream implements Parcelable {
+ public String streamId;
+ public String hlsUrl;
+ public String thumbnail;
+ public int width;
+ public int height;
+ public long publishAt;
+ public String state;
+
+ public RPANStream(String streamId, String hlsUrl, String thumbnail, int width, int height, long publishAt,
+ String state) {
+ this.streamId = streamId;
+ this.hlsUrl = hlsUrl;
+ this.thumbnail = thumbnail;
+ this.width = width;
+ this.height = height;
+ this.publishAt = publishAt;
+ this.state = state;
+ }
+
+ protected RPANStream(Parcel in) {
+ streamId = in.readString();
+ hlsUrl = in.readString();
+ thumbnail = in.readString();
+ width = in.readInt();
+ height = in.readInt();
+ publishAt = in.readLong();
+ state = in.readString();
+ }
+
+ public static final Creator<RPANStream> CREATOR = new Creator<RPANStream>() {
+ @Override
+ public RPANStream createFromParcel(Parcel in) {
+ return new RPANStream(in);
+ }
+
+ @Override
+ public RPANStream[] newArray(int size) {
+ return new RPANStream[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeString(streamId);
+ parcel.writeString(hlsUrl);
+ parcel.writeString(thumbnail);
+ parcel.writeInt(width);
+ parcel.writeInt(height);
+ parcel.writeLong(publishAt);
+ parcel.writeString(state);
+ }
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RPANComment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RPANComment.java
new file mode 100644
index 00000000..077031bf
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RPANComment.java
@@ -0,0 +1,15 @@
+package ml.docilealligator.infinityforreddit;
+
+public class RPANComment {
+ public String author;
+ public String authorIconImage;
+ public String content;
+ public long createdUTC;
+
+ public RPANComment(String author, String authorIconImage, String content, long createdUTC) {
+ this.author = author;
+ this.authorIconImage = authorIconImage;
+ this.content = content;
+ this.createdUTC = createdUTC;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java
index f190a9fb..480adf81 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java
@@ -211,7 +211,7 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE custom_themes"
- + " ADD COLUMN link_color INTEGER DEFAULT " + Color.parseColor("#FF4081") + " NOT NULL");
+ + " ADD COLUMN link_color INTEGER DEFAULT " + Color.parseColor("#FF1868") + " NOT NULL");
database.execSQL("ALTER TABLE custom_themes"
+ " ADD COLUMN received_message_text_color INTEGER DEFAULT " + Color.parseColor("#FFFFFF") + " NOT NULL");
database.execSQL("ALTER TABLE custom_themes"
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditGalleryPayload.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditGalleryPayload.java
new file mode 100644
index 00000000..ef91d6d9
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditGalleryPayload.java
@@ -0,0 +1,96 @@
+package ml.docilealligator.infinityforreddit;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.google.gson.annotations.SerializedName;
+
+import java.util.ArrayList;
+
+public class RedditGalleryPayload {
+ @SerializedName("sr")
+ public String subredditName;
+ @SerializedName("submit_type")
+ public String submitType;
+ @SerializedName("api_type")
+ public String apiType = "json";
+ @SerializedName("show_error_list")
+ public boolean showErrorList = true;
+ public String title;
+ @SerializedName("spoiler")
+ public boolean isSpoiler;
+ @SerializedName("nsfw")
+ public boolean isNSFW;
+ public String kind = "self";
+ @SerializedName("original_content")
+ public boolean originalContent = false;
+ @SerializedName("post_to_twitter")
+ public boolean postToTwitter = false;
+ public boolean sendReplies;
+ @SerializedName("validate_on_submit")
+ public boolean validateOnSubmit = true;
+ @SerializedName("flair_id")
+ public String flairId;
+ @SerializedName("flair_text")
+ public String flairText;
+ public ArrayList<Item> items;
+
+ public RedditGalleryPayload(String subredditName, String submitType, String title,
+ boolean isSpoiler, boolean isNSFW, boolean sendReplies, Flair flair, ArrayList<Item> items) {
+ this.subredditName = subredditName;
+ this.submitType = submitType;
+ this.title = title;
+ this.isSpoiler = isSpoiler;
+ this.isNSFW = isNSFW;
+ this.sendReplies = sendReplies;
+ if (flair != null) {
+ flairId = flair.getId();
+ flairText = flair.getText();
+ }
+ this.items = items;
+ }
+
+ public static class Item implements Parcelable {
+ public String caption;
+ @SerializedName("outbound_url")
+ public String outboundUrl;
+ @SerializedName("media_id")
+ public String mediaId;
+
+ public Item(String caption, String outboundUrl, String mediaId) {
+ this.caption = caption;
+ this.outboundUrl = outboundUrl;
+ this.mediaId = mediaId;
+ }
+
+ protected Item(Parcel in) {
+ caption = in.readString();
+ outboundUrl = in.readString();
+ mediaId = in.readString();
+ }
+
+ public static final Creator<Item> CREATOR = new Creator<Item>() {
+ @Override
+ public Item createFromParcel(Parcel in) {
+ return new Item(in);
+ }
+
+ @Override
+ public Item[] newArray(int size) {
+ return new Item[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeString(caption);
+ parcel.writeString(outboundUrl);
+ parcel.writeString(mediaId);
+ }
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/TrendingSearch.java b/app/src/main/java/ml/docilealligator/infinityforreddit/TrendingSearch.java
new file mode 100644
index 00000000..f0afc541
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/TrendingSearch.java
@@ -0,0 +1,54 @@
+package ml.docilealligator.infinityforreddit;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.ArrayList;
+
+import ml.docilealligator.infinityforreddit.post.Post;
+
+public class TrendingSearch implements Parcelable {
+ public String queryString;
+ public String displayString;
+ public String title;
+ public ArrayList<Post.Preview> previews;
+
+ public TrendingSearch(String queryString, String displayString, String title, ArrayList<Post.Preview> previews) {
+ this.queryString = queryString;
+ this.displayString = displayString;
+ this.title = title;
+ this.previews = previews;
+ }
+
+ protected TrendingSearch(Parcel in) {
+ queryString = in.readString();
+ displayString = in.readString();
+ title = in.readString();
+ previews = in.createTypedArrayList(Post.Preview.CREATOR);
+ }
+
+ public static final Creator<TrendingSearch> CREATOR = new Creator<TrendingSearch>() {
+ @Override
+ public TrendingSearch createFromParcel(Parcel in) {
+ return new TrendingSearch(in);
+ }
+
+ @Override
+ public TrendingSearch[] newArray(int size) {
+ return new TrendingSearch[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeString(queryString);
+ parcel.writeString(displayString);
+ parcel.writeString(title);
+ parcel.writeTypedList(previews);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/UploadImageEnabledActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/UploadImageEnabledActivity.java
new file mode 100644
index 00000000..aecde88f
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/UploadImageEnabledActivity.java
@@ -0,0 +1,7 @@
+package ml.docilealligator.infinityforreddit;
+
+public interface UploadImageEnabledActivity {
+ void uploadImage();
+ void captureImage();
+ void insertImageUrl(UploadedImage uploadedImage);
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/UploadedImage.java b/app/src/main/java/ml/docilealligator/infinityforreddit/UploadedImage.java
new file mode 100644
index 00000000..e3d28734
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/UploadedImage.java
@@ -0,0 +1,42 @@
+package ml.docilealligator.infinityforreddit;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class UploadedImage implements Parcelable {
+ public String imageName;
+ public String imageUrl;
+
+ public UploadedImage(String imageName, String imageUrl) {
+ this.imageName = imageName;
+ this.imageUrl = imageUrl;
+ }
+
+ protected UploadedImage(Parcel in) {
+ imageName = in.readString();
+ imageUrl = in.readString();
+ }
+
+ public static final Creator<UploadedImage> CREATOR = new Creator<UploadedImage>() {
+ @Override
+ public UploadedImage createFromParcel(Parcel in) {
+ return new UploadedImage(in);
+ }
+
+ @Override
+ public UploadedImage[] newArray(int size) {
+ return new UploadedImage[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeString(imageName);
+ parcel.writeString(imageUrl);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/account/Account.java b/app/src/main/java/ml/docilealligator/infinityforreddit/account/Account.java
index 6232c94d..246c3c05 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/account/Account.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/account/Account.java
@@ -3,6 +3,7 @@ package ml.docilealligator.infinityforreddit.account;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
+import androidx.room.Ignore;
import androidx.room.PrimaryKey;
@Entity(tableName = "accounts")
@@ -26,6 +27,11 @@ public class Account {
@ColumnInfo(name = "is_current_user")
private boolean isCurrentUser;
+ @Ignore
+ public static Account getAnonymousAccount() {
+ return new Account("-", null, null, null, null, null, 0, false);
+ }
+
public Account(@NonNull String accountName, String accessToken, String refreshToken, String code,
String profileImageUrl, String bannerImageUrl, int karma, boolean isCurrentUser) {
this.accountName = accountName;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/account/AccountDao.java b/app/src/main/java/ml/docilealligator/infinityforreddit/account/AccountDao.java
index 721dea6f..fcd824a1 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/account/AccountDao.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/account/AccountDao.java
@@ -16,9 +16,6 @@ public interface AccountDao {
@Query("SELECT EXISTS (SELECT 1 FROM accounts WHERE username = '-')")
boolean isAnonymousAccountInserted();
- @Query("INSERT INTO accounts(username, karma, is_current_user) VALUES('-', 0, 0)")
- void insertAnonymousAccount();
-
@Query("SELECT * FROM accounts WHERE username != '-'")
List<Account> getAllAccounts();
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CommentActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CommentActivity.java
index 74dbe822..a244fafe 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CommentActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CommentActivity.java
@@ -1,11 +1,15 @@
package ml.docilealligator.infinityforreddit.activities;
+import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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.text.Spanned;
import android.text.util.Linkify;
import android.view.Menu;
@@ -20,7 +24,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -31,6 +35,11 @@ import org.commonmark.ext.gfm.tables.TableBlock;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.concurrent.Executor;
+
import javax.inject.Inject;
import javax.inject.Named;
@@ -48,17 +57,21 @@ import io.noties.markwon.recycler.table.TableEntry;
import io.noties.markwon.recycler.table.TableEntryPlugin;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.UploadImageEnabledActivity;
+import ml.docilealligator.infinityforreddit.UploadedImage;
import ml.docilealligator.infinityforreddit.adapters.MarkdownBottomBarRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.CopyTextBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.UploadedImagesBottomSheetFragment;
import ml.docilealligator.infinityforreddit.comment.Comment;
import ml.docilealligator.infinityforreddit.comment.SendComment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import retrofit2.Retrofit;
-public class CommentActivity extends BaseActivity {
+public class CommentActivity extends BaseActivity implements UploadImageEnabledActivity {
public static final String EXTRA_COMMENT_PARENT_TEXT_KEY = "ECPTK";
public static final String EXTRA_COMMENT_PARENT_TEXT_MARKDOWN_KEY = "ECPTMK";
@@ -70,6 +83,10 @@ public class CommentActivity extends BaseActivity {
public static final String EXTRA_IS_REPLYING_KEY = "EIRK";
public static final String RETURN_EXTRA_COMMENT_DATA_KEY = "RECDK";
public static final int WRITE_COMMENT_REQUEST_CODE = 1;
+ private static final int PICK_IMAGE_REQUEST_CODE = 100;
+ private static final int CAPTURE_IMAGE_REQUEST_CODE = 200;
+ private static final int MARKDOWN_PREVIEW_REQUEST_CODE = 300;
+ private static final String UPLOADED_IMAGES_STATE = "UIS";
@BindView(R.id.coordinator_layout_comment_activity)
CoordinatorLayout coordinatorLayout;
@@ -91,6 +108,9 @@ public class CommentActivity extends BaseActivity {
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
+ @Named("upload_media")
+ Retrofit mUploadMediaRetrofit;
+ @Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
@@ -98,6 +118,8 @@ public class CommentActivity extends BaseActivity {
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
private String mAccessToken;
private String parentFullname;
private int parentDepth;
@@ -105,6 +127,9 @@ public class CommentActivity extends BaseActivity {
private boolean isSubmitting = false;
private boolean isReplying;
private int markdownColor;
+ private Uri capturedImageUri;
+ private ArrayList<UploadedImage> uploadedImages = new ArrayList<>();
+ private Menu mMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -216,7 +241,7 @@ public class CommentActivity extends BaseActivity {
.tableLayout(R.layout.adapter_table_block, R.id.table_layout)
.textLayoutIsRoot(R.layout.view_table_entry_cell)))
.build();
- contentMarkdownRecyclerView.setLayoutManager(new LinearLayoutManager(this));
+ contentMarkdownRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this));
contentMarkdownRecyclerView.setAdapter(markwonAdapter);
markwonAdapter.setMarkdown(postBodyMarkwon, parentBodyMarkdown);
markwonAdapter.notifyDataSetChanged();
@@ -231,12 +256,32 @@ public class CommentActivity extends BaseActivity {
setSupportActionBar(toolbar);
- MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(mCustomThemeWrapper, item -> {
- MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(this, commentEditText, item);
+ if (savedInstanceState != null) {
+ uploadedImages = savedInstanceState.getParcelableArrayList(UPLOADED_IMAGES_STATE);
+ }
+
+ MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(
+ mCustomThemeWrapper, new MarkdownBottomBarRecyclerViewAdapter.ItemClickListener() {
+ @Override
+ public void onClick(int item) {
+ MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(
+ CommentActivity.this, commentEditText, item);
+ }
+
+ @Override
+ public void onUploadImage() {
+ Utils.hideKeyboard(CommentActivity.this);
+ UploadedImagesBottomSheetFragment fragment = new UploadedImagesBottomSheetFragment();
+ Bundle arguments = new Bundle();
+ arguments.putParcelableArrayList(UploadedImagesBottomSheetFragment.EXTRA_UPLOADED_IMAGES,
+ uploadedImages);
+ fragment.setArguments(arguments);
+ fragment.show(getSupportFragmentManager(), fragment.getTag());
+ }
});
- markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManager(this,
- LinearLayoutManager.HORIZONTAL, false));
+ markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this,
+ LinearLayoutManagerBugFixed.HORIZONTAL, false));
markdownBottomBarRecyclerView.setAdapter(adapter);
commentEditText.requestFocus();
@@ -247,6 +292,12 @@ public class CommentActivity extends BaseActivity {
}
@Override
+ protected void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putParcelableArrayList(UPLOADED_IMAGES_STATE, uploadedImages);
+ }
+
+ @Override
public SharedPreferences getDefaultSharedPreferences() {
return mSharedPreferences;
}
@@ -280,6 +331,7 @@ public class CommentActivity extends BaseActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.comment_activity, menu);
+ mMenu = menu;
applyMenuItemTheme(menu);
return true;
}
@@ -293,60 +345,70 @@ public class CommentActivity extends BaseActivity {
} else if (itemId == R.id.action_preview_comment_activity) {
Intent intent = new Intent(this, FullMarkdownActivity.class);
intent.putExtra(FullMarkdownActivity.EXTRA_COMMENT_MARKDOWN, commentEditText.getText().toString());
- startActivity(intent);
+ intent.putExtra(FullMarkdownActivity.EXTRA_SUBMIT_POST, true);
+ startActivityForResult(intent, MARKDOWN_PREVIEW_REQUEST_CODE);
} else if (itemId == R.id.action_send_comment_activity) {
- if (!isSubmitting) {
- isSubmitting = true;
- if (commentEditText.getText() == null || commentEditText.getText().toString().equals("")) {
- isSubmitting = false;
- Snackbar.make(coordinatorLayout, R.string.comment_content_required, Snackbar.LENGTH_SHORT).show();
- return true;
- }
+ sendComment(item);
+ return true;
+ }
+
+ return false;
+ }
+
+ public void sendComment(@Nullable MenuItem item) {
+ if (!isSubmitting) {
+ isSubmitting = true;
+ if (commentEditText.getText() == null || commentEditText.getText().toString().equals("")) {
+ isSubmitting = false;
+ Snackbar.make(coordinatorLayout, R.string.comment_content_required, Snackbar.LENGTH_SHORT).show();
+ return;
+ }
+ if (item != null) {
item.setEnabled(false);
item.getIcon().setAlpha(130);
- Snackbar sendingSnackbar = Snackbar.make(coordinatorLayout, R.string.sending_comment, Snackbar.LENGTH_INDEFINITE);
- sendingSnackbar.show();
-
- SendComment.sendComment(commentEditText.getText().toString(), parentFullname, parentDepth,
- getResources().getConfiguration().locale, mOauthRetrofit,
- mAccessToken,
- new SendComment.SendCommentListener() {
- @Override
- public void sendCommentSuccess(Comment comment) {
- isSubmitting = false;
+ }
+ Snackbar sendingSnackbar = Snackbar.make(coordinatorLayout, R.string.sending_comment, Snackbar.LENGTH_INDEFINITE);
+ sendingSnackbar.show();
+
+ SendComment.sendComment(mExecutor, new Handler(), commentEditText.getText().toString(),
+ parentFullname, parentDepth, mOauthRetrofit, mAccessToken,
+ new SendComment.SendCommentListener() {
+ @Override
+ public void sendCommentSuccess(Comment comment) {
+ isSubmitting = false;
+ if (item != null) {
item.setEnabled(true);
item.getIcon().setAlpha(255);
- Toast.makeText(CommentActivity.this, R.string.send_comment_success, Toast.LENGTH_SHORT).show();
- Intent returnIntent = new Intent();
- returnIntent.putExtra(RETURN_EXTRA_COMMENT_DATA_KEY, comment);
- returnIntent.putExtra(EXTRA_PARENT_FULLNAME_KEY, parentFullname);
- if (isReplying) {
- returnIntent.putExtra(EXTRA_PARENT_POSITION_KEY, parentPosition);
- }
- setResult(RESULT_OK, returnIntent);
- finish();
}
+ Toast.makeText(CommentActivity.this, R.string.send_comment_success, Toast.LENGTH_SHORT).show();
+ Intent returnIntent = new Intent();
+ returnIntent.putExtra(RETURN_EXTRA_COMMENT_DATA_KEY, comment);
+ returnIntent.putExtra(EXTRA_PARENT_FULLNAME_KEY, parentFullname);
+ if (isReplying) {
+ returnIntent.putExtra(EXTRA_PARENT_POSITION_KEY, parentPosition);
+ }
+ setResult(RESULT_OK, returnIntent);
+ finish();
+ }
- @Override
- public void sendCommentFailed(@Nullable String errorMessage) {
- isSubmitting = false;
- sendingSnackbar.dismiss();
+ @Override
+ public void sendCommentFailed(@Nullable String errorMessage) {
+ isSubmitting = false;
+ sendingSnackbar.dismiss();
+ if (item != null) {
item.setEnabled(true);
item.getIcon().setAlpha(255);
+ }
- if (errorMessage == null || !errorMessage.equals("")) {
- Snackbar.make(coordinatorLayout, R.string.send_comment_failed, Snackbar.LENGTH_SHORT).show();
- } else {
- Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_SHORT).show();
- }
+ if (errorMessage == null || !errorMessage.equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.send_comment_failed, Snackbar.LENGTH_SHORT).show();
+ } else {
+ Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_SHORT).show();
}
- });
- }
- return true;
+ }
+ });
}
-
- return false;
}
private void promptAlertDialog(int titleResId, int messageResId) {
@@ -360,6 +422,26 @@ public class CommentActivity extends BaseActivity {
}
@Override
+ protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (resultCode == RESULT_OK) {
+ if (requestCode == PICK_IMAGE_REQUEST_CODE) {
+ if (data == null) {
+ Toast.makeText(CommentActivity.this, R.string.error_getting_image, Toast.LENGTH_LONG).show();
+ return;
+ }
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, commentEditText, coordinatorLayout, data.getData(), uploadedImages);
+ } else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, commentEditText, coordinatorLayout, capturedImageUri, uploadedImages);
+ } else if (requestCode == MARKDOWN_PREVIEW_REQUEST_CODE) {
+ sendComment(mMenu == null ? null : mMenu.findItem(R.id.action_send_comment_activity));
+ }
+ }
+ }
+
+ @Override
public void onBackPressed() {
if (isSubmitting) {
promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_edit_comment_detail);
@@ -382,4 +464,37 @@ public class CommentActivity extends BaseActivity {
public void onAccountSwitchEvent(SwitchAccountEvent event) {
finish();
}
+
+ @Override
+ public void uploadImage() {
+ Intent intent = new Intent();
+ intent.setType("image/*");
+ intent.setAction(Intent.ACTION_GET_CONTENT);
+ startActivityForResult(Intent.createChooser(intent,
+ getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
+ }
+
+ @Override
+ public void captureImage() {
+ Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ try {
+ capturedImageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
+ File.createTempFile("captured_image", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
+ pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
+ startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
+ } catch (IOException ex) {
+ Toast.makeText(this, R.string.error_creating_temp_file, Toast.LENGTH_SHORT).show();
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.no_camera_available, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ @Override
+ public void insertImageUrl(UploadedImage uploadedImage) {
+ int start = Math.max(commentEditText.getSelectionStart(), 0);
+ int end = Math.max(commentEditText.getSelectionEnd(), 0);
+ commentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
+ "[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
+ 0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
+ }
}
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 9f9207e5..144898bb 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemeListingActivity.java
@@ -1,5 +1,7 @@
package ml.docilealligator.infinityforreddit.activities;
+import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN;
+
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
@@ -17,7 +19,6 @@ import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -37,6 +38,9 @@ import javax.inject.Named;
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.adapters.CustomThemeListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.asynctasks.ChangeThemeName;
import ml.docilealligator.infinityforreddit.asynctasks.DeleteTheme;
@@ -48,13 +52,8 @@ import ml.docilealligator.infinityforreddit.customtheme.CustomTheme;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeViewModel;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
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.utils.CustomThemeSharedPreferencesUtils;
-import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN;
-
public class CustomThemeListingActivity extends BaseActivity implements
CustomThemeOptionsBottomSheetFragment.CustomThemeOptionsBottomSheetFragmentListener,
CreateThemeBottomSheetFragment.SelectBaseThemeBottomSheetFragmentListener {
@@ -110,7 +109,6 @@ public class CustomThemeListingActivity extends BaseActivity implements
CustomThemeListingRecyclerViewAdapter adapter = new CustomThemeListingRecyclerViewAdapter(this,
CustomThemeWrapper.getPredefinedThemes(this));
recyclerView.setAdapter(adapter);
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemePreviewActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemePreviewActivity.java
index dbd40c31..e3d232e6 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemePreviewActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomThemePreviewActivity.java
@@ -1,5 +1,10 @@
package ml.docilealligator.infinityforreddit.activities;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
+
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
@@ -43,22 +48,18 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.customtheme.CustomTheme;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeSettingsItem;
+import ml.docilealligator.infinityforreddit.customviews.ViewPagerBugFixed;
import ml.docilealligator.infinityforreddit.font.ContentFontStyle;
import ml.docilealligator.infinityforreddit.font.FontStyle;
import ml.docilealligator.infinityforreddit.font.TitleFontStyle;
import ml.docilealligator.infinityforreddit.fragments.ThemePreviewCommentsFragment;
import ml.docilealligator.infinityforreddit.fragments.ThemePreviewPostsFragment;
-import ml.docilealligator.infinityforreddit.Infinity;
-import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
-
public class CustomThemePreviewActivity extends AppCompatActivity {
public static final String EXTRA_CUSTOM_THEME_SETTINGS_ITEMS = "ECTSI";
@@ -66,7 +67,7 @@ public class CustomThemePreviewActivity extends AppCompatActivity {
@BindView(R.id.coordinator_layout_theme_preview_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.view_pager_theme_preview_activity)
- ViewPager viewPager;
+ ViewPagerBugFixed viewPager;
@BindView(R.id.appbar_layout_theme_preview_activity)
AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_theme_preview_activity)
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomizeThemeActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomizeThemeActivity.java
index fc238c34..989eb34f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomizeThemeActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/CustomizeThemeActivity.java
@@ -12,7 +12,6 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -104,8 +103,6 @@ public class CustomizeThemeActivity extends BaseActivity {
setTitle(R.string.customize_theme_activity_create_theme_label);
}
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
-
if (savedInstanceState != null) {
customThemeSettingsItems = savedInstanceState.getParcelableArrayList(CUSTOM_THEME_SETTINGS_ITEMS_STATE);
themeName = savedInstanceState.getString(THEME_NAME_STATE);
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 07c0c2af..e46f581b 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditCommentActivity.java
@@ -1,10 +1,14 @@
package ml.docilealligator.infinityforreddit.activities;
+import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
+import android.os.Environment;
+import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
@@ -12,8 +16,10 @@ import android.widget.EditText;
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.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@@ -24,20 +30,28 @@ import com.google.android.material.snackbar.Snackbar;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
-import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.UploadImageEnabledActivity;
+import ml.docilealligator.infinityforreddit.UploadedImage;
import ml.docilealligator.infinityforreddit.adapters.MarkdownBottomBarRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.UploadedImagesBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
-import ml.docilealligator.infinityforreddit.Infinity;
-import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
@@ -46,15 +60,20 @@ import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
-public class EditCommentActivity extends BaseActivity {
+public class EditCommentActivity extends BaseActivity implements UploadImageEnabledActivity {
public static final String EXTRA_CONTENT = "EC";
public static final String EXTRA_FULLNAME = "EF";
public static final String EXTRA_POSITION = "EP";
-
public static final String EXTRA_EDITED_COMMENT_CONTENT = "EECC";
public static final String EXTRA_EDITED_COMMENT_POSITION = "EECP";
+ private static final int PICK_IMAGE_REQUEST_CODE = 100;
+ private static final int CAPTURE_IMAGE_REQUEST_CODE = 200;
+ private static final int MARKDOWN_PREVIEW_REQUEST_CODE = 300;
+
+ private static final String UPLOADED_IMAGES_STATE = "UIS";
+
@BindView(R.id.coordinator_layout_edit_comment_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_edit_comment_activity)
@@ -69,6 +88,9 @@ public class EditCommentActivity extends BaseActivity {
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
+ @Named("upload_media")
+ Retrofit mUploadMediaRetrofit;
+ @Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
@@ -76,10 +98,14 @@ public class EditCommentActivity extends BaseActivity {
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
private String mFullName;
private String mAccessToken;
private String mCommentContent;
private boolean isSubmitting = false;
+ private Uri capturedImageUri;
+ private ArrayList<UploadedImage> uploadedImages = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -109,11 +135,31 @@ public class EditCommentActivity extends BaseActivity {
mCommentContent = getIntent().getStringExtra(EXTRA_CONTENT);
contentEditText.setText(mCommentContent);
- MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(mCustomThemeWrapper, item -> {
- MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(this, contentEditText, item);
+ if (savedInstanceState != null) {
+ uploadedImages = savedInstanceState.getParcelableArrayList(UPLOADED_IMAGES_STATE);
+ }
+
+ MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(
+ mCustomThemeWrapper, new MarkdownBottomBarRecyclerViewAdapter.ItemClickListener() {
+ @Override
+ public void onClick(int item) {
+ MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(
+ EditCommentActivity.this, contentEditText, item);
+ }
+
+ @Override
+ public void onUploadImage() {
+ Utils.hideKeyboard(EditCommentActivity.this);
+ UploadedImagesBottomSheetFragment fragment = new UploadedImagesBottomSheetFragment();
+ Bundle arguments = new Bundle();
+ arguments.putParcelableArrayList(UploadedImagesBottomSheetFragment.EXTRA_UPLOADED_IMAGES,
+ uploadedImages);
+ fragment.setArguments(arguments);
+ fragment.show(getSupportFragmentManager(), fragment.getTag());
+ }
});
- markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManager(this,
+ markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this,
LinearLayoutManager.HORIZONTAL, false));
markdownBottomBarRecyclerView.setAdapter(adapter);
@@ -162,47 +208,10 @@ public class EditCommentActivity extends BaseActivity {
if (item.getItemId() == R.id.action_preview_edit_comment_activity) {
Intent intent = new Intent(this, FullMarkdownActivity.class);
intent.putExtra(FullMarkdownActivity.EXTRA_COMMENT_MARKDOWN, contentEditText.getText().toString());
- startActivity(intent);
+ intent.putExtra(FullMarkdownActivity.EXTRA_SUBMIT_POST, true);
+ startActivityForResult(intent, MARKDOWN_PREVIEW_REQUEST_CODE);
} else if (item.getItemId() == R.id.action_send_edit_comment_activity) {
- if (!isSubmitting) {
- isSubmitting = true;
-
- Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
-
- String content = contentEditText.getText().toString();
-
- Map<String, String> params = new HashMap<>();
- params.put(APIUtils.THING_ID_KEY, mFullName);
- params.put(APIUtils.TEXT_KEY, content);
-
- mOauthRetrofit.create(RedditAPI.class)
- .editPostOrComment(APIUtils.getOAuthHeader(mAccessToken), params)
- .enqueue(new Callback<String>() {
- @Override
- public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
- isSubmitting = false;
- if (response.isSuccessful()) {
- Toast.makeText(EditCommentActivity.this, R.string.edit_success, Toast.LENGTH_SHORT).show();
-
- Intent returnIntent = new Intent();
- returnIntent.putExtra(EXTRA_EDITED_COMMENT_CONTENT, Utils.modifyMarkdown(content));
- returnIntent.putExtra(EXTRA_EDITED_COMMENT_POSITION, getIntent().getExtras().getInt(EXTRA_POSITION));
- setResult(RESULT_OK, returnIntent);
-
- finish();
- } else {
- Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
- }
- }
-
- @Override
- public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
- isSubmitting = false;
- Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
- }
- });
-
- }
+ editComment();
return true;
} else if (item.getItemId() == android.R.id.home) {
onBackPressed();
@@ -211,17 +220,85 @@ public class EditCommentActivity extends BaseActivity {
return false;
}
+ private void editComment() {
+ if (!isSubmitting) {
+ isSubmitting = true;
+
+ Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
+
+ String content = contentEditText.getText().toString();
+
+ Map<String, String> params = new HashMap<>();
+ params.put(APIUtils.THING_ID_KEY, mFullName);
+ params.put(APIUtils.TEXT_KEY, content);
+
+ mOauthRetrofit.create(RedditAPI.class)
+ .editPostOrComment(APIUtils.getOAuthHeader(mAccessToken), params)
+ .enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ isSubmitting = false;
+ if (response.isSuccessful()) {
+ Toast.makeText(EditCommentActivity.this, R.string.edit_success, Toast.LENGTH_SHORT).show();
+
+ Intent returnIntent = new Intent();
+ returnIntent.putExtra(EXTRA_EDITED_COMMENT_CONTENT, Utils.modifyMarkdown(content));
+ returnIntent.putExtra(EXTRA_EDITED_COMMENT_POSITION, getIntent().getExtras().getInt(EXTRA_POSITION));
+ setResult(RESULT_OK, returnIntent);
+
+ finish();
+ } else {
+ Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+ isSubmitting = false;
+ Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
+ }
+ });
+
+ }
+ }
+
private void promptAlertDialog(int titleResId, int messageResId) {
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(titleResId)
.setMessage(messageResId)
- .setPositiveButton(R.string.yes, (dialogInterface, i)
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i)
-> finish())
.setNegativeButton(R.string.no, null)
.show();
}
@Override
+ protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (resultCode == RESULT_OK) {
+ if (requestCode == PICK_IMAGE_REQUEST_CODE) {
+ if (data == null) {
+ Toast.makeText(EditCommentActivity.this, R.string.error_getting_image, Toast.LENGTH_LONG).show();
+ return;
+ }
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, contentEditText, coordinatorLayout, data.getData(), uploadedImages);
+ } else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, contentEditText, coordinatorLayout, capturedImageUri, uploadedImages);
+ } else if (requestCode == MARKDOWN_PREVIEW_REQUEST_CODE) {
+ editComment();
+ }
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putParcelableArrayList(UPLOADED_IMAGES_STATE, uploadedImages);
+ }
+
+ @Override
public void onBackPressed() {
if (isSubmitting) {
promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_edit_comment_detail);
@@ -244,4 +321,37 @@ public class EditCommentActivity extends BaseActivity {
public void onAccountSwitchEvent(SwitchAccountEvent event) {
finish();
}
+
+ @Override
+ public void uploadImage() {
+ Intent intent = new Intent();
+ intent.setType("image/*");
+ intent.setAction(Intent.ACTION_GET_CONTENT);
+ startActivityForResult(Intent.createChooser(intent,
+ getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
+ }
+
+ @Override
+ public void captureImage() {
+ Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ try {
+ capturedImageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
+ File.createTempFile("captured_image", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
+ pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
+ startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
+ } catch (IOException ex) {
+ Toast.makeText(this, R.string.error_creating_temp_file, Toast.LENGTH_SHORT).show();
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.no_camera_available, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ @Override
+ public void insertImageUrl(UploadedImage uploadedImage) {
+ int start = Math.max(contentEditText.getSelectionStart(), 0);
+ int end = Math.max(contentEditText.getSelectionEnd(), 0);
+ contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
+ "[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
+ 0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
+ }
}
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 5c8ea02f..21e1418d 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/EditPostActivity.java
@@ -1,10 +1,14 @@
package ml.docilealligator.infinityforreddit.activities;
+import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
+import android.os.Environment;
+import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@@ -14,9 +18,10 @@ 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.recyclerview.widget.LinearLayoutManager;
+import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -27,33 +32,48 @@ import com.r0adkll.slidr.Slidr;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
-import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.UploadImageEnabledActivity;
+import ml.docilealligator.infinityforreddit.UploadedImage;
import ml.docilealligator.infinityforreddit.adapters.MarkdownBottomBarRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.UploadedImagesBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
-import ml.docilealligator.infinityforreddit.Infinity;
-import ml.docilealligator.infinityforreddit.R;
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;
-public class EditPostActivity extends BaseActivity {
+public class EditPostActivity extends BaseActivity implements UploadImageEnabledActivity {
public static final String EXTRA_TITLE = "ET";
public static final String EXTRA_CONTENT = "EC";
public static final String EXTRA_FULLNAME = "EF";
+ private static final int PICK_IMAGE_REQUEST_CODE = 100;
+ private static final int CAPTURE_IMAGE_REQUEST_CODE = 200;
+ private static final int MARKDOWN_PREVIEW_REQUEST_CODE = 300;
+
+ private static final String UPLOADED_IMAGES_STATE = "UIS";
+
@BindView(R.id.coordinator_layout_edit_post_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_edit_post_activity)
@@ -72,6 +92,9 @@ public class EditPostActivity extends BaseActivity {
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
+ @Named("upload_media")
+ Retrofit mUploadMediaRetrofit;
+ @Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
@@ -79,10 +102,14 @@ public class EditPostActivity extends BaseActivity {
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
private String mFullName;
private String mAccessToken;
private String mPostContent;
private boolean isSubmitting = false;
+ private Uri capturedImageUri;
+ private ArrayList<UploadedImage> uploadedImages = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -117,12 +144,32 @@ public class EditPostActivity extends BaseActivity {
mPostContent = getIntent().getStringExtra(EXTRA_CONTENT);
contentEditText.setText(mPostContent);
- MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(mCustomThemeWrapper, item -> {
- MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(this, contentEditText, item);
+ if (savedInstanceState != null) {
+ uploadedImages = savedInstanceState.getParcelableArrayList(UPLOADED_IMAGES_STATE);
+ }
+
+ MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(
+ mCustomThemeWrapper, new MarkdownBottomBarRecyclerViewAdapter.ItemClickListener() {
+ @Override
+ public void onClick(int item) {
+ MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(
+ EditPostActivity.this, contentEditText, item);
+ }
+
+ @Override
+ public void onUploadImage() {
+ Utils.hideKeyboard(EditPostActivity.this);
+ UploadedImagesBottomSheetFragment fragment = new UploadedImagesBottomSheetFragment();
+ Bundle arguments = new Bundle();
+ arguments.putParcelableArrayList(UploadedImagesBottomSheetFragment.EXTRA_UPLOADED_IMAGES,
+ uploadedImages);
+ fragment.setArguments(arguments);
+ fragment.show(getSupportFragmentManager(), fragment.getTag());
+ }
});
- markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManager(this,
- LinearLayoutManager.HORIZONTAL, false));
+ markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this,
+ LinearLayoutManagerBugFixed.HORIZONTAL, false));
markdownBottomBarRecyclerView.setAdapter(adapter);
contentEditText.requestFocus();
@@ -172,37 +219,10 @@ public class EditPostActivity extends BaseActivity {
if (item.getItemId() == R.id.action_preview_edit_post_activity) {
Intent intent = new Intent(this, FullMarkdownActivity.class);
intent.putExtra(FullMarkdownActivity.EXTRA_COMMENT_MARKDOWN, contentEditText.getText().toString());
- startActivity(intent);
+ intent.putExtra(FullMarkdownActivity.EXTRA_SUBMIT_POST, true);
+ startActivityForResult(intent, MARKDOWN_PREVIEW_REQUEST_CODE);
} else if (item.getItemId() == R.id.action_send_edit_post_activity) {
- if (!isSubmitting) {
- isSubmitting = true;
-
- Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
-
- Map<String, String> params = new HashMap<>();
- params.put(APIUtils.THING_ID_KEY, mFullName);
- params.put(APIUtils.TEXT_KEY, contentEditText.getText().toString());
-
- mOauthRetrofit.create(RedditAPI.class)
- .editPostOrComment(APIUtils.getOAuthHeader(mAccessToken), params)
- .enqueue(new Callback<String>() {
- @Override
- public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
- isSubmitting = false;
- Toast.makeText(EditPostActivity.this, R.string.edit_success, Toast.LENGTH_SHORT).show();
- Intent returnIntent = new Intent();
- setResult(RESULT_OK, returnIntent);
- finish();
- }
-
- @Override
- public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
- isSubmitting = false;
- Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
- }
- });
-
- }
+ editPost();
return true;
} else if (item.getItemId() == android.R.id.home) {
onBackPressed();
@@ -211,11 +231,69 @@ public class EditPostActivity extends BaseActivity {
return false;
}
+ private void editPost() {
+ if (!isSubmitting) {
+ isSubmitting = true;
+
+ Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
+
+ Map<String, String> params = new HashMap<>();
+ params.put(APIUtils.THING_ID_KEY, mFullName);
+ params.put(APIUtils.TEXT_KEY, contentEditText.getText().toString());
+
+ mOauthRetrofit.create(RedditAPI.class)
+ .editPostOrComment(APIUtils.getOAuthHeader(mAccessToken), params)
+ .enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ isSubmitting = false;
+ Toast.makeText(EditPostActivity.this, R.string.edit_success, Toast.LENGTH_SHORT).show();
+ Intent returnIntent = new Intent();
+ setResult(RESULT_OK, returnIntent);
+ finish();
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+ isSubmitting = false;
+ Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
+ }
+ });
+
+ }
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (resultCode == RESULT_OK) {
+ if (requestCode == PICK_IMAGE_REQUEST_CODE) {
+ if (data == null) {
+ Toast.makeText(EditPostActivity.this, R.string.error_getting_image, Toast.LENGTH_LONG).show();
+ return;
+ }
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, contentEditText, coordinatorLayout, data.getData(), uploadedImages);
+ } else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, contentEditText, coordinatorLayout, capturedImageUri, uploadedImages);
+ } else if (requestCode == MARKDOWN_PREVIEW_REQUEST_CODE) {
+ editPost();
+ }
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putParcelableArrayList(UPLOADED_IMAGES_STATE, uploadedImages);
+ }
+
private void promptAlertDialog(int titleResId, int messageResId) {
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(titleResId)
.setMessage(messageResId)
- .setPositiveButton(R.string.yes, (dialogInterface, i)
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i)
-> finish())
.setNegativeButton(R.string.no, null)
.show();
@@ -244,4 +322,37 @@ public class EditPostActivity extends BaseActivity {
public void onAccountSwitchEvent(SwitchAccountEvent event) {
finish();
}
+
+ @Override
+ public void uploadImage() {
+ Intent intent = new Intent();
+ intent.setType("image/*");
+ intent.setAction(Intent.ACTION_GET_CONTENT);
+ startActivityForResult(Intent.createChooser(intent,
+ getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
+ }
+
+ @Override
+ public void captureImage() {
+ Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ try {
+ capturedImageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
+ File.createTempFile("captured_image", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
+ pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
+ startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
+ } catch (IOException ex) {
+ Toast.makeText(this, R.string.error_creating_temp_file, Toast.LENGTH_SHORT).show();
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.no_camera_available, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ @Override
+ public void insertImageUrl(UploadedImage uploadedImage) {
+ int start = Math.max(contentEditText.getSelectionStart(), 0);
+ int end = Math.max(contentEditText.getSelectionEnd(), 0);
+ contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
+ "[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
+ 0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
+ }
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FetchRandomSubredditOrPostActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FetchRandomSubredditOrPostActivity.java
index d73e195c..365209b1 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FetchRandomSubredditOrPostActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FetchRandomSubredditOrPostActivity.java
@@ -3,9 +3,12 @@ package ml.docilealligator.infinityforreddit.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
+import android.os.Handler;
import android.widget.RelativeLayout;
import android.widget.Toast;
+import java.util.concurrent.Executor;
+
import javax.inject.Inject;
import javax.inject.Named;
@@ -32,6 +35,8 @@ public class FetchRandomSubredditOrPostActivity extends BaseActivity {
SharedPreferences mSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
private boolean isCanceled = false;
@Override
@@ -44,7 +49,7 @@ public class FetchRandomSubredditOrPostActivity extends BaseActivity {
int option = getIntent().getIntExtra(EXTRA_RANDOM_OPTION, RandomBottomSheetFragment.RANDOM_SUBREDDIT);
- FetchPost.fetchRandomPost(mRetrofit, option == RandomBottomSheetFragment.RANDOM_NSFW_SUBREDDIT
+ FetchPost.fetchRandomPost(mExecutor, new Handler(), mRetrofit, option == RandomBottomSheetFragment.RANDOM_NSFW_SUBREDDIT
|| option == RandomBottomSheetFragment.RANDOM_NSFW_POST, new FetchPost.FetchRandomPostListener() {
@Override
public void fetchRandomPostSuccess(String postId, String subredditName) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FilteredPostsActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FilteredPostsActivity.java
index e14e8499..4d2ff01f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FilteredPostsActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FilteredPostsActivity.java
@@ -62,6 +62,7 @@ public class FilteredPostsActivity extends BaseActivity implements SortTypeSelec
public static final String EXTRA_NAME = "ESN";
public static final String EXTRA_QUERY = "EQ";
+ public static final String EXTRA_TRENDING_SOURCE = "ETS";
public static final String EXTRA_FILTER = "EF";
public static final String EXTRA_CONTAIN_FLAIR = "ECF";
public static final String EXTRA_POST_TYPE = "EPT";
@@ -312,6 +313,7 @@ public class FilteredPostsActivity extends BaseActivity implements SortTypeSelec
} else if (postType == PostDataSource.TYPE_SEARCH) {
bundle.putString(PostFragment.EXTRA_NAME, name);
bundle.putString(PostFragment.EXTRA_QUERY, getIntent().getStringExtra(EXTRA_QUERY));
+ bundle.putString(PostFragment.EXTRA_TRENDING_SOURCE, getIntent().getStringExtra(EXTRA_TRENDING_SOURCE));
}
mFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_filtered_posts_activity, mFragment).commit();
@@ -359,81 +361,81 @@ public class FilteredPostsActivity extends BaseActivity implements SortTypeSelec
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
- switch (item.getItemId()) {
- case android.R.id.home:
- finish();
- return true;
- case R.id.action_sort_filtered_thing_activity:
- switch (postType) {
- case PostDataSource.TYPE_FRONT_PAGE:
- SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
- Bundle bestBundle = new Bundle();
- bestBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, false);
- bestSortTypeBottomSheetFragment.setArguments(bestBundle);
- bestSortTypeBottomSheetFragment.show(getSupportFragmentManager(), bestSortTypeBottomSheetFragment.getTag());
- break;
- case PostDataSource.TYPE_SEARCH:
- SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment = new SearchPostSortTypeBottomSheetFragment();
- Bundle searchBundle = new Bundle();
- searchPostSortTypeBottomSheetFragment.setArguments(searchBundle);
- searchPostSortTypeBottomSheetFragment.show(getSupportFragmentManager(), searchPostSortTypeBottomSheetFragment.getTag());
- break;
- case PostDataSource.TYPE_SUBREDDIT:
- if (name.equals("popular") || name.equals("all")) {
- SortTypeBottomSheetFragment popularAndAllSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
- Bundle popularBundle = new Bundle();
- popularBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true);
- popularAndAllSortTypeBottomSheetFragment.setArguments(popularBundle);
- popularAndAllSortTypeBottomSheetFragment.show(getSupportFragmentManager(), popularAndAllSortTypeBottomSheetFragment.getTag());
- } else {
- SortTypeBottomSheetFragment subredditSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
- Bundle subredditSheetBundle = new Bundle();
- subredditSheetBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true);
- subredditSortTypeBottomSheetFragment.setArguments(subredditSheetBundle);
- subredditSortTypeBottomSheetFragment.show(getSupportFragmentManager(), subredditSortTypeBottomSheetFragment.getTag());
- }
- break;
- case PostDataSource.TYPE_MULTI_REDDIT:
- SortTypeBottomSheetFragment multiRedditSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
- Bundle multiRedditBundle = new Bundle();
- multiRedditBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true);
- multiRedditSortTypeBottomSheetFragment.setArguments(multiRedditBundle);
- multiRedditSortTypeBottomSheetFragment.show(getSupportFragmentManager(), multiRedditSortTypeBottomSheetFragment.getTag());
- break;
- case PostDataSource.TYPE_USER:
- UserThingSortTypeBottomSheetFragment userThingSortTypeBottomSheetFragment = new UserThingSortTypeBottomSheetFragment();
- userThingSortTypeBottomSheetFragment.show(getSupportFragmentManager(), userThingSortTypeBottomSheetFragment.getTag());
- }
- return true;
- case R.id.action_refresh_filtered_thing_activity:
- if (mMenu != null) {
- mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity).setTitle(R.string.action_start_lazy_mode);
- }
- if (mFragment instanceof FragmentCommunicator) {
- ((FragmentCommunicator) mFragment).refresh();
- }
- return true;
- case R.id.action_lazy_mode_filtered_thing_activity:
- MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity);
- if (isInLazyMode) {
- ((FragmentCommunicator) mFragment).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 (((FragmentCommunicator) mFragment).startLazyMode()) {
- isInLazyMode = true;
- lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
- params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
- collapsingToolbarLayout.setLayoutParams(params);
+ int itemId = item.getItemId();
+ if (itemId == android.R.id.home) {
+ finish();
+ return true;
+ } else if (itemId == R.id.action_sort_filtered_thing_activity) {
+ switch (postType) {
+ case PostDataSource.TYPE_FRONT_PAGE:
+ SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
+ Bundle bestBundle = new Bundle();
+ bestBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, false);
+ bestSortTypeBottomSheetFragment.setArguments(bestBundle);
+ bestSortTypeBottomSheetFragment.show(getSupportFragmentManager(), bestSortTypeBottomSheetFragment.getTag());
+ break;
+ case PostDataSource.TYPE_SEARCH:
+ SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment = new SearchPostSortTypeBottomSheetFragment();
+ Bundle searchBundle = new Bundle();
+ searchPostSortTypeBottomSheetFragment.setArguments(searchBundle);
+ searchPostSortTypeBottomSheetFragment.show(getSupportFragmentManager(), searchPostSortTypeBottomSheetFragment.getTag());
+ break;
+ case PostDataSource.TYPE_SUBREDDIT:
+ if (name.equals("popular") || name.equals("all")) {
+ SortTypeBottomSheetFragment popularAndAllSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
+ Bundle popularBundle = new Bundle();
+ popularBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true);
+ popularAndAllSortTypeBottomSheetFragment.setArguments(popularBundle);
+ popularAndAllSortTypeBottomSheetFragment.show(getSupportFragmentManager(), popularAndAllSortTypeBottomSheetFragment.getTag());
+ } else {
+ SortTypeBottomSheetFragment subredditSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
+ Bundle subredditSheetBundle = new Bundle();
+ subredditSheetBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true);
+ subredditSortTypeBottomSheetFragment.setArguments(subredditSheetBundle);
+ subredditSortTypeBottomSheetFragment.show(getSupportFragmentManager(), subredditSortTypeBottomSheetFragment.getTag());
}
+ break;
+ case PostDataSource.TYPE_MULTI_REDDIT:
+ SortTypeBottomSheetFragment multiRedditSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
+ Bundle multiRedditBundle = new Bundle();
+ multiRedditBundle.putBoolean(SortTypeBottomSheetFragment.EXTRA_NO_BEST_TYPE, true);
+ multiRedditSortTypeBottomSheetFragment.setArguments(multiRedditBundle);
+ multiRedditSortTypeBottomSheetFragment.show(getSupportFragmentManager(), multiRedditSortTypeBottomSheetFragment.getTag());
+ break;
+ case PostDataSource.TYPE_USER:
+ UserThingSortTypeBottomSheetFragment userThingSortTypeBottomSheetFragment = new UserThingSortTypeBottomSheetFragment();
+ userThingSortTypeBottomSheetFragment.show(getSupportFragmentManager(), userThingSortTypeBottomSheetFragment.getTag());
+ }
+ return true;
+ } else if (itemId == R.id.action_refresh_filtered_thing_activity) {
+ if (mMenu != null) {
+ mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity).setTitle(R.string.action_start_lazy_mode);
+ }
+ if (mFragment != null) {
+ ((FragmentCommunicator) mFragment).refresh();
+ }
+ return true;
+ } else if (itemId == R.id.action_lazy_mode_filtered_thing_activity) {
+ MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity);
+ if (isInLazyMode) {
+ ((FragmentCommunicator) mFragment).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 (((FragmentCommunicator) mFragment).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_filtered_post_activity:
- PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment();
- postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag());
- return true;
+ }
+ return true;
+ } else if (itemId == R.id.action_change_post_layout_filtered_post_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/FullMarkdownActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FullMarkdownActivity.java
index 312fe6cd..9eb9fb86 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FullMarkdownActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/FullMarkdownActivity.java
@@ -1,5 +1,6 @@
package ml.docilealligator.infinityforreddit.activities;
+import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
@@ -11,6 +12,7 @@ import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.util.Linkify;
+import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
@@ -20,15 +22,15 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
-import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrInterface;
import org.commonmark.ext.gfm.tables.TableBlock;
+import org.greenrobot.eventbus.EventBus;
+import org.greenrobot.eventbus.Subscribe;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -51,20 +53,21 @@ import io.noties.markwon.recycler.table.TableEntryPlugin;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.customviews.MarkwonLinearLayoutManager;
+import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
public class FullMarkdownActivity extends BaseActivity {
public static final String EXTRA_COMMENT_MARKDOWN = "ECM";
public static final String EXTRA_IS_NSFW = "EIN";
+ public static final String EXTRA_SUBMIT_POST = "ESP";
@BindView(R.id.coordinator_layout_comment_full_markdown_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_comment_full_markdown_activity)
AppBarLayout appBarLayout;
- @BindView(R.id.collapsing_toolbar_layout_comment_full_markdown_activity)
- CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar_comment_full_markdown_activity)
Toolbar toolbar;
@BindView(R.id.content_markdown_view_comment_full_markdown_activity)
@@ -85,6 +88,8 @@ public class FullMarkdownActivity extends BaseActivity {
ButterKnife.bind(this);
+ EventBus.getDefault().register(this);
+
applyCustomTheme();
setSupportActionBar(toolbar);
@@ -112,7 +117,7 @@ public class FullMarkdownActivity extends BaseActivity {
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
adjustToolbar(toolbar);
- markdownRecyclerView.setPadding(0, 0, 0, getNavBarHeight());
+ markdownRecyclerView.setPadding(markdownRecyclerView.getPaddingLeft(), 0, markdownRecyclerView.getPaddingRight(), getNavBarHeight());
}
}
@@ -212,7 +217,7 @@ public class FullMarkdownActivity extends BaseActivity {
.tableLayout(R.layout.adapter_table_block, R.id.table_layout)
.textLayoutIsRoot(R.layout.view_table_entry_cell)))
.build();
- LinearLayoutManager linearLayoutManager = new MarkwonLinearLayoutManager(this, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
+ LinearLayoutManagerBugFixed linearLayoutManager = new MarkwonLinearLayoutManager(this, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
@Override
public void onScrolledLeft() {
if (mSlidrInterface != null) {
@@ -234,10 +239,26 @@ public class FullMarkdownActivity extends BaseActivity {
}
@Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ if (getIntent().getBooleanExtra(EXTRA_SUBMIT_POST, false)) {
+ getMenuInflater().inflate(R.menu.full_markdown_activity, menu);
+ applyMenuItemTheme(menu);
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
+ } else if (item.getItemId() == R.id.action_send_full_markdown_activity) {
+ Intent returnIntent = new Intent();
+ setResult(Activity.RESULT_OK, returnIntent);
+ finish();
+ return true;
}
return false;
@@ -258,4 +279,17 @@ public class FullMarkdownActivity extends BaseActivity {
coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
applyAppBarLayoutAndToolbarTheme(appBarLayout, toolbar);
}
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ EventBus.getDefault().unregister(this);
+ }
+
+ @Subscribe
+ public void onAccountSwitchEvent(SwitchAccountEvent event) {
+ if (!getClass().getName().equals(event.excludeActivityClassName)) {
+ finish();
+ }
+ }
} \ No newline at end of file
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/GiveAwardActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/GiveAwardActivity.java
index a3cc4cdb..98e1b604 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/GiveAwardActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/GiveAwardActivity.java
@@ -17,7 +17,6 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
@@ -39,6 +38,7 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.adapters.AwardRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.award.GiveAward;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
@@ -162,7 +162,7 @@ public class GiveAwardActivity extends BaseActivity {
.setNegativeButton(R.string.no, null)
.show();
});
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
+ recyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this));
recyclerView.setAdapter(adapter);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/InboxActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/InboxActivity.java
index 78fdc00f..2437103f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/InboxActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/InboxActivity.java
@@ -9,9 +9,9 @@ import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
-import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
+import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
@@ -20,15 +20,17 @@ import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
-import androidx.fragment.app.FragmentPagerAdapter;
-import androidx.viewpager.widget.ViewPager;
+import androidx.viewpager2.adapter.FragmentStateAdapter;
+import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
+import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.textfield.TextInputEditText;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrInterface;
@@ -80,7 +82,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
@BindView(R.id.tab_layout_inbox_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_inbox_activity)
- ViewPager viewPager;
+ ViewPager2 viewPager2;
@BindView(R.id.fab_inbox_activity)
FloatingActionButton fab;
@Inject
@@ -100,6 +102,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
Executor mExecutor;
private SlidrInterface mSlidrInterface;
private SectionsPagerAdapter sectionsPagerAdapter;
+ private FragmentManager fragmentManager;
private String mAccessToken;
private String mAccountName;
private String mNewAccountName;
@@ -152,6 +155,8 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
setSupportActionBar(mToolbar);
setToolbarGoToTop(mToolbar);
+ fragmentManager = getSupportFragmentManager();
+
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
@@ -162,7 +167,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
}
getCurrentAccountAndFetchMessage(savedInstanceState);
- viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
+ viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
fab.show();
@@ -177,6 +182,18 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent pmIntent = new Intent(this, SendPrivateMessageActivity.class);
+ pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, thingEditText.getText().toString());
+ startActivity(pmIntent);
+ return true;
+ }
+ return false;
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.choose_a_user)
.setView(rootView)
@@ -250,8 +267,8 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
}
private void bindView(Bundle savedInstanceState) {
- sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
- viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
+ sectionsPagerAdapter = new SectionsPagerAdapter(this);
+ viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
if (position == 0) {
@@ -261,12 +278,23 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
}
}
});
- viewPager.setAdapter(sectionsPagerAdapter);
- viewPager.setOffscreenPageLimit(2);
- tabLayout.setupWithViewPager(viewPager);
+ viewPager2.setAdapter(sectionsPagerAdapter);
+ viewPager2.setOffscreenPageLimit(2);
+ new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
+ switch (position) {
+ case 0:
+ tab.setText(R.string.notifications);
+ break;
+ case 1:
+ tab.setText(R.string.messages);
+ break;
+ }
+ }).attach();
if (savedInstanceState == null && getIntent().getBooleanExtra(EXTRA_VIEW_MESSAGE, false)) {
- viewPager.setCurrentItem(1);
+ viewPager2.setCurrentItem(1, false);
}
+
+ fixViewPager2Sensitivity(viewPager2);
}
@Override
@@ -376,17 +404,44 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
fab.hide();
}
- private class SectionsPagerAdapter extends FragmentPagerAdapter {
- private InboxFragment tab1;
- private InboxFragment tab2;
+ private class SectionsPagerAdapter extends FragmentStateAdapter {
- public SectionsPagerAdapter(@NonNull FragmentManager fm) {
- super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
+ SectionsPagerAdapter(FragmentActivity fa) {
+ super(fa);
+ }
+
+ @Nullable
+ private Fragment getCurrentFragment() {
+ if (viewPager2 == null || fragmentManager == null) {
+ return null;
+ }
+ return fragmentManager.findFragmentByTag("f" + viewPager2.getCurrentItem());
+ }
+
+ void refresh() {
+ InboxFragment fragment = (InboxFragment) getCurrentFragment();
+ if (fragment != null) {
+ fragment.refresh();
+ }
+ }
+
+ void goBackToTop() {
+ InboxFragment fragment = (InboxFragment) getCurrentFragment();
+ if (fragment != null) {
+ fragment.goBackToTop();
+ }
+ }
+
+ void readAllMessages() {
+ InboxFragment fragment = (InboxFragment) getCurrentFragment();
+ if (fragment != null) {
+ fragment.markAllMessagesRead();
+ }
}
@NonNull
@Override
- public Fragment getItem(int position) {
+ public Fragment createFragment(int position) {
if (position == 0) {
InboxFragment fragment = new InboxFragment();
Bundle bundle = new Bundle();
@@ -405,62 +460,8 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
}
@Override
- public int getCount() {
+ public int getItemCount() {
return 2;
}
-
- @Nullable
- @Override
- public CharSequence getPageTitle(int position) {
- if (position == 0) {
- return getString(R.string.notifications);
- }
-
- return getString(R.string.messages);
- }
-
- @NonNull
- @Override
- public Object instantiateItem(@NonNull ViewGroup container, int position) {
- Fragment fragment = (Fragment) super.instantiateItem(container, position);
- if (position == 0) {
- tab1 = (InboxFragment) fragment;
- } else if (position == 1) {
- tab2 = (InboxFragment) fragment;
- }
-
- return fragment;
- }
-
- void refresh() {
- if (viewPager.getCurrentItem() == 0) {
- if (tab1 != null) {
- tab1.refresh();
- }
- } else if (viewPager.getCurrentItem() == 1 && tab2 != null) {
- tab2.refresh();
- }
- }
-
- void goBackToTop() {
- if (viewPager.getCurrentItem() == 0) {
- if (tab1 != null) {
- tab1.goBackToTop();
- }
- } else if (viewPager.getCurrentItem() == 1) {
- if (tab2 != null) {
- tab2.goBackToTop();
- }
- }
- }
-
- void readAllMessages() {
- if (tab1 != null) {
- tab1.markAllMessagesRead();
- }
- if (tab2 != null) {
- tab2.markAllMessagesRead();
- }
- }
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LinkResolverActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LinkResolverActivity.java
index 7f834f48..a6596edb 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LinkResolverActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LinkResolverActivity.java
@@ -48,6 +48,8 @@ public class LinkResolverActivity extends AppCompatActivity {
private static final String IMGUR_GALLERY_PATTERN = "/gallery/\\w+/?";
private static final String IMGUR_ALBUM_PATTERN = "/(album|a)/\\w+/?";
private static final String IMGUR_IMAGE_PATTERN = "/\\w+/?";
+ private static final String RPAN_BROADCAST_PATTERN = "/rpan/r/[\\w-]+/\\w+/?\\w+/?";
+ private static final String WIKI_PATTERN = "/[rR]/[\\w-]+/(wiki|w)/?\\w+";
@Inject
@Named("default")
@@ -117,7 +119,19 @@ public class LinkResolverActivity extends AppCompatActivity {
List<String> segments = uri.getPathSegments();
if (authority != null) {
- if (authority.equals("v.redd.it")) {
+ if (authority.equals("reddit-uploaded-media.s3-accelerate.amazonaws.com")) {
+ String unescapedUrl = uri.toString().replace("%2F", "/");
+ int lastSlashIndex = unescapedUrl.lastIndexOf("/");
+ if (lastSlashIndex < 0 || lastSlashIndex == unescapedUrl.length() - 1) {
+ deepLinkError(uri);
+ return;
+ }
+ String id = unescapedUrl.substring(lastSlashIndex + 1);
+ Intent intent = new Intent(this, ViewImageOrGifActivity.class);
+ intent.putExtra(ViewImageOrGifActivity.EXTRA_IMAGE_URL_KEY, uri.toString());
+ intent.putExtra(ViewImageOrGifActivity.EXTRA_FILE_NAME_KEY, id + ".jpg");
+ startActivity(intent);
+ } else if (authority.equals("v.redd.it")) {
Intent intent = new Intent(this, ViewVideoActivity.class);
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_TYPE, ViewVideoActivity.VIDEO_TYPE_V_REDD_IT);
intent.putExtra(ViewVideoActivity.EXTRA_V_REDD_IT_URL, uri.toString());
@@ -158,6 +172,10 @@ public class LinkResolverActivity extends AppCompatActivity {
} else {
deepLinkError(uri);
}
+ } else if (path.matches(WIKI_PATTERN)) {
+ Intent intent = new Intent(this, WikiActivity.class);
+ intent.putExtra(WikiActivity.EXTRA_SUBREDDIT_NAME, segments.get(1));
+ startActivity(intent);
} else if (path.matches(SUBREDDIT_PATTERN)) {
Intent intent = new Intent(this, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, path.substring(3));
@@ -186,6 +204,10 @@ public class LinkResolverActivity extends AppCompatActivity {
intent.putExtra(ViewSubredditDetailActivity.EXTRA_MESSAGE_FULLNAME, messageFullname);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_NEW_ACCOUNT_NAME, newAccountName);
startActivity(intent);
+ } else if (path.matches(RPAN_BROADCAST_PATTERN)) {
+ Intent intent = new Intent(this, RPANActivity.class);
+ intent.putExtra(RPANActivity.EXTRA_RPAN_BROADCAST_FULLNAME_OR_ID, path.substring(path.lastIndexOf('/') + 1));
+ startActivity(intent);
} else if (authority.equals("redd.it") && path.matches(REDD_IT_POST_PATTERN)) {
Intent intent = new Intent(this, ViewPostDetailActivity.class);
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, path.substring(1));
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LockScreenActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LockScreenActivity.java
new file mode 100644
index 00000000..3ba73440
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/LockScreenActivity.java
@@ -0,0 +1,83 @@
+package ml.docilealligator.infinityforreddit.activities;
+
+import static androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG;
+import static androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL;
+
+import android.content.SharedPreferences;
+import android.os.Bundle;
+
+import androidx.annotation.NonNull;
+import androidx.biometric.BiometricManager;
+import androidx.biometric.BiometricPrompt;
+import androidx.core.content.ContextCompat;
+
+import java.util.concurrent.Executor;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+
+public class LockScreenActivity extends BaseActivity {
+
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ CustomThemeWrapper mCustomThemeWrapper;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ ((Infinity) getApplication()).getAppComponent().inject(this);
+
+ setImmersiveModeNotApplicable();
+
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_look_screen);
+
+ applyCustomTheme();
+
+ BiometricManager biometricManager = BiometricManager.from(this);
+ if (biometricManager.canAuthenticate(BIOMETRIC_STRONG | DEVICE_CREDENTIAL) == BiometricManager.BIOMETRIC_SUCCESS) {
+ Executor executor = ContextCompat.getMainExecutor(this);
+ BiometricPrompt biometricPrompt = new BiometricPrompt(this,
+ executor, new BiometricPrompt.AuthenticationCallback() {
+ @Override
+ public void onAuthenticationSucceeded(
+ @NonNull BiometricPrompt.AuthenticationResult result) {
+ super.onAuthenticationSucceeded(result);
+ finish();
+ }
+ });
+
+ BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
+ .setTitle(getString(R.string.unlock_account_section))
+ .setAllowedAuthenticators(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)
+ .build();
+
+ biometricPrompt.authenticate(promptInfo);
+ } else {
+ finish();
+ }
+ }
+
+ @Override
+ protected SharedPreferences getDefaultSharedPreferences() {
+ return mSharedPreferences;
+ }
+
+ @Override
+ protected CustomThemeWrapper getCustomThemeWrapper() {
+ return mCustomThemeWrapper;
+ }
+
+ @Override
+ protected void applyCustomTheme() {
+
+ }
+
+ @Override
+ public void onBackPressed() { }
+} \ No newline at end of file
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 89c95efa..55522aa9 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/MainActivity.java
@@ -1,5 +1,8 @@
package ml.docilealligator.infinityforreddit.activities;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
+
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
@@ -9,6 +12,8 @@ import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
+import android.text.Editable;
+import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
@@ -16,6 +21,7 @@ import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
+import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
@@ -33,8 +39,8 @@ import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
+import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
@@ -79,6 +85,8 @@ 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.adapters.SubredditAutocompleteRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings;
import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount;
import ml.docilealligator.infinityforreddit.asynctasks.SwitchToAnonymousMode;
@@ -89,6 +97,7 @@ import ml.docilealligator.infinityforreddit.bottomsheetfragments.RandomBottomShe
import ml.docilealligator.infinityforreddit.bottomsheetfragments.SortTimeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.SortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.ChangeConfirmToExitEvent;
import ml.docilealligator.infinityforreddit.events.ChangeDisableSwipingBetweenTabsEvent;
import ml.docilealligator.infinityforreddit.events.ChangeLockBottomAppBarEvent;
@@ -99,23 +108,27 @@ import ml.docilealligator.infinityforreddit.events.RecreateActivityEvent;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.fragments.PostFragment;
import ml.docilealligator.infinityforreddit.message.ReadMessage;
+import ml.docilealligator.infinityforreddit.multireddit.MultiReddit;
+import ml.docilealligator.infinityforreddit.multireddit.MultiRedditViewModel;
import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.post.PostDataSource;
import ml.docilealligator.infinityforreddit.readpost.InsertReadPost;
+import ml.docilealligator.infinityforreddit.subreddit.ParseSubredditData;
import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData;
import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditViewModel;
import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData;
import ml.docilealligator.infinityforreddit.user.FetchUserData;
import ml.docilealligator.infinityforreddit.user.UserData;
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.CustomThemeSharedPreferencesUtils;
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 androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
-
public class MainActivity extends BaseActivity implements SortTypeSelectionCallback,
PostTypeBottomSheetFragment.PostTypeSelectionCallback, PostLayoutBottomSheetFragment.PostLayoutSelectionCallback,
ActivityToolbarInterface, FABMoreOptionsBottomSheetFragment.FABOptionSelectionCallback,
@@ -168,6 +181,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
ImageView option4BottomAppBar;
@BindView(R.id.fab_main_activity)
FloatingActionButton fab;
+ MultiRedditViewModel multiRedditViewModel;
SubscribedSubredditViewModel subscribedSubredditViewModel;
AccountViewModel accountViewModel;
@Inject
@@ -210,6 +224,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
private SectionsPagerAdapter sectionsPagerAdapter;
private AppBarLayout.LayoutParams params;
private NavigationDrawerRecyclerViewAdapter adapter;
+ private Call<String> subredditAutocompleteCall;
private String mAccessToken;
private String mAccountName;
private boolean mFetchUserInfoSuccess = false;
@@ -223,6 +238,8 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
private boolean mConfirmToExit;
private boolean mLockBottomAppBar;
private boolean mDisableSwipingBetweenTabs;
+ private boolean mShowFavoriteMultiReddits;
+ private boolean mShowMultiReddits;
private boolean mShowFavoriteSubscribedSubreddits;
private boolean mShowSubscribedSubreddits;
private int fabOption;
@@ -300,7 +317,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
- showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, false);
+ showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, true);
mConfirmToExit = mSharedPreferences.getBoolean(SharedPreferencesUtils.CONFIRM_TO_EXIT, false);
mLockBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_BOTTOM_APP_BAR, false);
mDisableSwipingBetweenTabs = mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_SWIPING_BETWEEN_TABS, false);
@@ -745,6 +762,10 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
} else if (stringId == R.string.multi_reddit) {
intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
intent.putExtra(SubscribedThingListingActivity.EXTRA_SHOW_MULTIREDDITS, true);
+ } else if (stringId == R.string.rpan) {
+ intent = new Intent(MainActivity.this, RPANActivity.class);
+ } else if (stringId == R.string.trending) {
+ intent = new Intent(MainActivity.this, TrendingActivity.class);
} else if (stringId == R.string.upvoted) {
intent = new Intent(MainActivity.this, AccountPostsActivity.class);
intent.putExtra(AccountPostsActivity.EXTRA_USER_WHERE, PostDataSource.USER_WHERE_UPVOTED);
@@ -826,19 +847,21 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
}
});
adapter.setInboxCount(inboxCount);
- navDrawerRecyclerView.setLayoutManager(new LinearLayoutManager(this));
+ navDrawerRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this));
navDrawerRecyclerView.setAdapter(adapter);
int tabCount = mMainActivityTabsSharedPreferences.getInt((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_COUNT, 3);
+ mShowFavoriteMultiReddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_MULTIREDDITS, false);
+ mShowMultiReddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_MULTIREDDITS, false);
mShowFavoriteSubscribedSubreddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS, false);
mShowSubscribedSubreddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS, false);
- sectionsPagerAdapter = new SectionsPagerAdapter(this, tabCount,
- mShowFavoriteSubscribedSubreddits, mShowSubscribedSubreddits);
+ sectionsPagerAdapter = new SectionsPagerAdapter(this, tabCount, mShowFavoriteMultiReddits,
+ mShowMultiReddits, mShowFavoriteSubscribedSubreddits, mShowSubscribedSubreddits);
viewPager2.setAdapter(sectionsPagerAdapter);
viewPager2.setOffscreenPageLimit(1);
viewPager2.setUserInputEnabled(!mDisableSwipingBetweenTabs);
if (mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_TAB_NAMES, true)) {
- if (mShowFavoriteSubscribedSubreddits || mShowSubscribedSubreddits) {
+ if (mShowFavoriteMultiReddits || mShowMultiReddits || mShowFavoriteSubscribedSubreddits || mShowSubscribedSubreddits) {
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
} else {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
@@ -868,13 +891,26 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
tab.setText(mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_3_TITLE, getString(R.string.all)));
break;
}
- if (position >= tabCount && (mShowFavoriteSubscribedSubreddits || mShowSubscribedSubreddits) && sectionsPagerAdapter != null) {
- List<SubscribedSubredditData> favoriteSubscribedSubreddits = sectionsPagerAdapter.favoriteSubscribedSubreddits;
- List<SubscribedSubredditData> subscribedSubreddits = sectionsPagerAdapter.subscribedSubreddits;
- if (position - tabCount < favoriteSubscribedSubreddits.size()) {
- tab.setText(favoriteSubscribedSubreddits.get(position - tabCount).getName());
- } else if (position - tabCount - favoriteSubscribedSubreddits.size() < subscribedSubreddits.size()) {
- tab.setText(subscribedSubreddits.get(position - tabCount - favoriteSubscribedSubreddits.size()).getName());
+ if (position >= tabCount && (mShowFavoriteMultiReddits || mShowMultiReddits ||
+ mShowFavoriteSubscribedSubreddits || mShowSubscribedSubreddits)
+ && sectionsPagerAdapter != null) {
+ if (position - tabCount < sectionsPagerAdapter.favoriteMultiReddits.size()) {
+ tab.setText(sectionsPagerAdapter.favoriteMultiReddits.get(position - tabCount).getName());
+ } else if (position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size() < sectionsPagerAdapter.multiReddits.size()) {
+ tab.setText(sectionsPagerAdapter.multiReddits.get(position - tabCount
+ - sectionsPagerAdapter.favoriteMultiReddits.size()).getName());
+ } else if (position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size()
+ - sectionsPagerAdapter.multiReddits.size() < sectionsPagerAdapter.favoriteSubscribedSubreddits.size()) {
+ tab.setText(sectionsPagerAdapter.favoriteSubscribedSubreddits.get(position - tabCount
+ - sectionsPagerAdapter.favoriteMultiReddits.size()
+ - sectionsPagerAdapter.multiReddits.size()).getName());
+ } else if (position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size()
+ - sectionsPagerAdapter.multiReddits.size()
+ - sectionsPagerAdapter.favoriteSubscribedSubreddits.size() < sectionsPagerAdapter.subscribedSubreddits.size()) {
+ tab.setText(sectionsPagerAdapter.subscribedSubreddits.get(position - tabCount
+ - sectionsPagerAdapter.favoriteMultiReddits.size()
+ - sectionsPagerAdapter.multiReddits.size()
+ - sectionsPagerAdapter.favoriteSubscribedSubreddits.size()).getName());
}
}
}
@@ -900,6 +936,25 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
loadSubscriptions();
+ multiRedditViewModel = new ViewModelProvider(this, new MultiRedditViewModel.Factory(getApplication(),
+ mRedditDataRoomDatabase, mAccountName))
+ .get(MultiRedditViewModel.class);
+
+ multiRedditViewModel.getAllFavoriteMultiReddits().observe(this, multiReddits -> {
+ if (mShowFavoriteMultiReddits && sectionsPagerAdapter != null) {
+ sectionsPagerAdapter.setFavoriteMultiReddits(multiReddits);
+ }
+ });
+
+ multiRedditViewModel.getAllMultiReddits().observe(this, new Observer<List<MultiReddit>>() {
+ @Override
+ public void onChanged(List<MultiReddit> multiReddits) {
+ if (mShowMultiReddits && sectionsPagerAdapter != null) {
+ sectionsPagerAdapter.setMultiReddits(multiReddits);
+ }
+ }
+ });
+
subscribedSubredditViewModel = new ViewModelProvider(this,
new SubscribedSubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, mAccountName))
.get(SubscribedSubredditViewModel.class);
@@ -1173,6 +1228,10 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
case PostTypeBottomSheetFragment.TYPE_VIDEO:
intent = new Intent(MainActivity.this, PostVideoActivity.class);
startActivity(intent);
+ break;
+ case PostTypeBottomSheetFragment.TYPE_GALLERY:
+ intent = new Intent(MainActivity.this, PostGalleryActivity.class);
+ startActivity(intent);
}
}
@@ -1250,7 +1309,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
adapter.setShowAvatarOnTheRightInTheNavigationDrawer(event.showAvatarOnTheRightInTheNavigationDrawer);
int previousPosition = -1;
if (navDrawerRecyclerView.getLayoutManager() != null) {
- previousPosition = ((LinearLayoutManager) navDrawerRecyclerView.getLayoutManager()).findFirstVisibleItemPosition();
+ previousPosition = ((LinearLayoutManagerBugFixed) navDrawerRecyclerView.getLayoutManager()).findFirstVisibleItemPosition();
}
RecyclerView.LayoutManager layoutManager = navDrawerRecyclerView.getLayoutManager();
@@ -1332,11 +1391,80 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
private void goToSubreddit() {
View rootView = getLayoutInflater().inflate(R.layout.dialog_go_to_thing_edit_text, coordinatorLayout, false);
TextInputEditText thingEditText = rootView.findViewById(R.id.text_input_edit_text_go_to_thing_edit_text);
- thingEditText.requestFocus();
+ RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_go_to_thing_edit_text);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+ SubredditAutocompleteRecyclerViewAdapter adapter = new SubredditAutocompleteRecyclerViewAdapter(
+ this, mCustomThemeWrapper, subredditData -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent intent = new Intent(MainActivity.this, ViewSubredditDetailActivity.class);
+ intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditData.getName());
+ startActivity(intent);
+ });
+ recyclerView.setAdapter(adapter);
+
+ thingEditText.requestFocus();
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent subredditIntent = new Intent(this, ViewSubredditDetailActivity.class);
+ subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
+ startActivity(subredditIntent);
+ return true;
+ }
+ return false;
+ });
+
+ boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, false);
+ thingEditText.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ if (subredditAutocompleteCall != null) {
+ subredditAutocompleteCall.cancel();
+ }
+ subredditAutocompleteCall = mOauthRetrofit.create(RedditAPI.class).subredditAutocomplete(APIUtils.getOAuthHeader(mAccessToken),
+ editable.toString(), nsfw);
+ subredditAutocompleteCall.enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ ParseSubredditData.parseSubredditListingData(response.body(), nsfw, new ParseSubredditData.ParseSubredditListingDataListener() {
+ @Override
+ public void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after) {
+ adapter.setSubreddits(subredditData);
+ }
+
+ @Override
+ public void onParseSubredditListingDataFail() {
+
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+
+ }
+ });
+ }
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_subreddit)
.setView(rootView)
@@ -1349,7 +1477,11 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
startActivity(subredditIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -1366,6 +1498,18 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent userIntent = new Intent(this, ViewUserDetailActivity.class);
+ userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
+ startActivity(userIntent);
+ return true;
+ }
+ return false;
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_user)
.setView(rootView)
@@ -1378,7 +1522,11 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
startActivity(userIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -1409,16 +1557,26 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
private class SectionsPagerAdapter extends FragmentStateAdapter {
int tabCount;
+ boolean showFavoriteMultiReddits;
+ boolean showMultiReddits;
boolean showFavoriteSubscribedSubreddits;
boolean showSubscribedSubreddits;
+ List<MultiReddit> favoriteMultiReddits;
+ List<MultiReddit> multiReddits;
List<SubscribedSubredditData> favoriteSubscribedSubreddits;
List<SubscribedSubredditData> subscribedSubreddits;
- SectionsPagerAdapter(FragmentActivity fa, int tabCount, boolean showFavoriteSubscribedSubreddits, boolean showSubscribedSubreddits) {
+ SectionsPagerAdapter(FragmentActivity fa, int tabCount, boolean showFavoriteMultiReddits,
+ boolean showMultiReddits, boolean showFavoriteSubscribedSubreddits,
+ boolean showSubscribedSubreddits) {
super(fa);
this.tabCount = tabCount;
+ favoriteMultiReddits = new ArrayList<>();
+ multiReddits = new ArrayList<>();
favoriteSubscribedSubreddits = new ArrayList<>();
subscribedSubreddits = new ArrayList<>();
+ this.showFavoriteMultiReddits = showFavoriteMultiReddits;
+ this.showMultiReddits = showMultiReddits;
this.showFavoriteSubscribedSubreddits = showFavoriteSubscribedSubreddits;
this.showSubscribedSubreddits = showSubscribedSubreddits;
}
@@ -1463,17 +1621,38 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
String name = mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_NAME, "");
return generatePostFragment(postType, name);
} else {
+ if (showFavoriteMultiReddits) {
+ if (position >= tabCount && position - tabCount < favoriteMultiReddits.size()) {
+ int postType = SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_MULTIREDDIT;
+ String name = favoriteMultiReddits.get(position - tabCount).getPath();
+ return generatePostFragment(postType, name);
+ }
+ }
+
+ if (showMultiReddits) {
+ if (position >= tabCount && position - tabCount - favoriteMultiReddits.size() < multiReddits.size()) {
+ int postType = SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_MULTIREDDIT;
+ String name = multiReddits.get(position - tabCount - favoriteMultiReddits.size()).getPath();
+ return generatePostFragment(postType, name);
+ }
+ }
+
if (showFavoriteSubscribedSubreddits) {
- if (position >= tabCount && position - tabCount < favoriteSubscribedSubreddits.size()) {
+ if (position >= tabCount && position - tabCount - favoriteMultiReddits.size()
+ - multiReddits.size() < favoriteSubscribedSubreddits.size()) {
int postType = SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_SUBREDDIT;
- String name = favoriteSubscribedSubreddits.get(position - tabCount).getName();
+ String name = favoriteSubscribedSubreddits.get(position - tabCount
+ - favoriteMultiReddits.size()
+ - multiReddits.size()).getName();
return generatePostFragment(postType, name);
}
}
if (showSubscribedSubreddits) {
- if (position >= tabCount && position - tabCount - favoriteSubscribedSubreddits.size() < subscribedSubreddits.size()) {
+ if (position >= tabCount && position - tabCount - favoriteMultiReddits.size()
+ - multiReddits.size() - favoriteSubscribedSubreddits.size() < subscribedSubreddits.size()) {
int postType = SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_SUBREDDIT;
- String name = subscribedSubreddits.get(position - tabCount - favoriteSubscribedSubreddits.size()).getName();
+ String name = subscribedSubreddits.get(position - tabCount - favoriteMultiReddits.size()
+ - multiReddits.size() - favoriteSubscribedSubreddits.size()).getName();
return generatePostFragment(postType, name);
}
}
@@ -1483,6 +1662,16 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
}
}
+ public void setFavoriteMultiReddits(List<MultiReddit> favoriteMultiReddits) {
+ this.favoriteMultiReddits = favoriteMultiReddits;
+ notifyDataSetChanged();
+ }
+
+ public void setMultiReddits(List<MultiReddit> multiReddits) {
+ this.multiReddits = multiReddits;
+ notifyDataSetChanged();
+ }
+
public void setFavoriteSubscribedSubreddits(List<SubscribedSubredditData> favoriteSubscribedSubreddits) {
this.favoriteSubscribedSubreddits = favoriteSubscribedSubreddits;
notifyDataSetChanged();
@@ -1583,7 +1772,8 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
if (mAccessToken == null) {
return 3;
}
- return tabCount + favoriteSubscribedSubreddits.size() + subscribedSubreddits.size();
+ return tabCount + favoriteMultiReddits.size() + multiReddits.size() +
+ favoriteSubscribedSubreddits.size() + subscribedSubreddits.size();
}
@Nullable
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostFilterPreferenceActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostFilterPreferenceActivity.java
index e64bf21e..4ed7534d 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostFilterPreferenceActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostFilterPreferenceActivity.java
@@ -36,6 +36,8 @@ import ml.docilealligator.infinityforreddit.postfilter.PostFilterViewModel;
public class PostFilterPreferenceActivity extends BaseActivity {
public static final String EXTRA_POST = "EP";
+ public static final String EXTRA_SUBREDDIT_NAME = "ESN";
+ public static final String EXTRA_USER_NAME = "EUN";
@BindView(R.id.coordinator_layout_post_filter_preference_activity)
CoordinatorLayout coordinatorLayout;
@@ -76,26 +78,36 @@ public class PostFilterPreferenceActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Post post = getIntent().getParcelableExtra(EXTRA_POST);
+ String subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
+ String username = getIntent().getStringExtra(EXTRA_USER_NAME);
fab.setOnClickListener(view -> {
- if (post == null) {
+ if (post != null) {
+ showPostFilterOptions(post, null);
+ } else if (subredditName != null) {
+ excludeSubredditInFilter(subredditName, null);
+ } else if (username != null) {
+ excludeUserInFilter(username, null);
+ } else {
Intent intent = new Intent(PostFilterPreferenceActivity.this, CustomizePostFilterActivity.class);
intent.putExtra(CustomizePostFilterActivity.EXTRA_FROM_SETTINGS, true);
startActivity(intent);
- } else {
- showPostFilterOptions(post, null);
}
});
adapter = new PostFilterRecyclerViewAdapter(postFilter -> {
- if (post == null) {
+ if (post != null) {
+ showPostFilterOptions(post, postFilter);
+ } else if (subredditName != null) {
+ excludeSubredditInFilter(subredditName, postFilter);
+ } else if (username != null) {
+ excludeUserInFilter(username, postFilter);
+ } else {
PostFilterOptionsBottomSheetFragment postFilterOptionsBottomSheetFragment = new PostFilterOptionsBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(PostFilterOptionsBottomSheetFragment.EXTRA_POST_FILTER, postFilter);
postFilterOptionsBottomSheetFragment.setArguments(bundle);
postFilterOptionsBottomSheetFragment.show(getSupportFragmentManager(), postFilterOptionsBottomSheetFragment.getTag());
- } else {
- showPostFilterOptions(post, postFilter);
}
});
@@ -145,6 +157,24 @@ public class PostFilterPreferenceActivity extends BaseActivity {
.show();
}
+ public void excludeSubredditInFilter(String subredditName, PostFilter postFilter) {
+ Intent intent = new Intent(this, CustomizePostFilterActivity.class);
+ intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_SUBREDDIT, subredditName);
+ if (postFilter != null) {
+ intent.putExtra(CustomizePostFilterActivity.EXTRA_POST_FILTER, postFilter);
+ }
+ startActivity(intent);
+ }
+
+ public void excludeUserInFilter(String username, PostFilter postFilter) {
+ Intent intent = new Intent(this, CustomizePostFilterActivity.class);
+ intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_USER, username);
+ if (postFilter != null) {
+ intent.putExtra(CustomizePostFilterActivity.EXTRA_POST_FILTER, postFilter);
+ }
+ startActivity(intent);
+ }
+
public void editPostFilter(PostFilter postFilter) {
Intent intent = new Intent(PostFilterPreferenceActivity.this, CustomizePostFilterActivity.class);
intent.putExtra(CustomizePostFilterActivity.EXTRA_POST_FILTER, postFilter);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostGalleryActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostGalleryActivity.java
new file mode 100644
index 00000000..8edb4516
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostGalleryActivity.java
@@ -0,0 +1,709 @@
+package ml.docilealligator.infinityforreddit.activities;
+
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.Rect;
+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;
+import android.view.View;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.appcompat.widget.Toolbar;
+import androidx.coordinatorlayout.widget.CoordinatorLayout;
+import androidx.core.content.ContextCompat;
+import androidx.core.content.FileProvider;
+import androidx.recyclerview.widget.GridLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.RequestManager;
+import com.bumptech.glide.request.RequestOptions;
+import com.google.android.material.appbar.AppBarLayout;
+import com.google.android.material.button.MaterialButton;
+import com.google.android.material.dialog.MaterialAlertDialogBuilder;
+import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.switchmaterial.SwitchMaterial;
+import com.google.gson.Gson;
+import com.libRG.CustomTextView;
+
+import org.greenrobot.eventbus.EventBus;
+import org.greenrobot.eventbus.Subscribe;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
+import ml.docilealligator.infinityforreddit.Flair;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
+import ml.docilealligator.infinityforreddit.RedditGalleryPayload;
+import ml.docilealligator.infinityforreddit.adapters.RedditGallerySubmissionRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.SelectOrCaptureImageBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.events.SubmitGalleryPostEvent;
+import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
+import ml.docilealligator.infinityforreddit.services.SubmitPostService;
+import ml.docilealligator.infinityforreddit.utils.JSONUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import ml.docilealligator.infinityforreddit.utils.UploadImageUtils;
+import ml.docilealligator.infinityforreddit.utils.Utils;
+import pl.droidsonroids.gif.GifImageView;
+import retrofit2.Retrofit;
+
+public class PostGalleryActivity extends BaseActivity implements FlairBottomSheetFragment.FlairSelectionCallback {
+
+ static final String EXTRA_SUBREDDIT_NAME = "ESN";
+
+ private static final String SUBREDDIT_NAME_STATE = "SNS";
+ private static final String SUBREDDIT_ICON_STATE = "SIS";
+ private static final String SUBREDDIT_SELECTED_STATE = "SSS";
+ private static final String SUBREDDIT_IS_USER_STATE = "SIUS";
+ private static final String LOAD_SUBREDDIT_ICON_STATE = "LSIS";
+ private static final String IS_POSTING_STATE = "IPS";
+ private static final String FLAIR_STATE = "FS";
+ private static final String IS_SPOILER_STATE = "ISS";
+ private static final String IS_NSFW_STATE = "INS";
+ private static final String REDDIT_GALLERY_IMAGE_INFO_STATE = "RGIIS";
+
+ private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0;
+ private static final int PICK_IMAGE_REQUEST_CODE = 1;
+ private static final int CAPTURE_IMAGE_REQUEST_CODE = 2;
+
+ @BindView(R.id.coordinator_layout_post_gallery_activity)
+ CoordinatorLayout coordinatorLayout;
+ @BindView(R.id.appbar_layout_post_gallery_activity)
+ AppBarLayout appBarLayout;
+ @BindView(R.id.toolbar_post_gallery_activity)
+ Toolbar toolbar;
+ @BindView(R.id.subreddit_icon_gif_image_view_post_gallery_activity)
+ GifImageView iconGifImageView;
+ @BindView(R.id.subreddit_name_text_view_post_gallery_activity)
+ TextView subredditNameTextView;
+ @BindView(R.id.rules_button_post_gallery_activity)
+ MaterialButton rulesButton;
+ @BindView(R.id.divider_1_post_gallery_activity)
+ View divider1;
+ @BindView(R.id.flair_custom_text_view_post_gallery_activity)
+ CustomTextView flairTextView;
+ @BindView(R.id.spoiler_custom_text_view_post_gallery_activity)
+ CustomTextView spoilerTextView;
+ @BindView(R.id.nsfw_custom_text_view_post_gallery_activity)
+ CustomTextView nsfwTextView;
+ @BindView(R.id.divider_2_post_gallery_activity)
+ View divider2;
+ @BindView(R.id.receive_post_reply_notifications_linear_layout_post_gallery_activity)
+ LinearLayout receivePostReplyNotificationsLinearLayout;
+ @BindView(R.id.receive_post_reply_notifications_text_view_post_gallery_activity)
+ TextView receivePostReplyNotificationsTextView;
+ @BindView(R.id.receive_post_reply_notifications_switch_material_post_gallery_activity)
+ SwitchMaterial receivePostReplyNotificationsSwitchMaterial;
+ @BindView(R.id.divider_3_post_gallery_activity)
+ View divider3;
+ @BindView(R.id.post_title_edit_text_post_gallery_activity)
+ EditText titleEditText;
+ @BindView(R.id.divider_4_post_gallery_activity)
+ View divider4;
+ @BindView(R.id.images_recycler_view_post_gallery_activity)
+ RecyclerView imagesRecyclerView;
+ @Inject
+ @Named("no_oauth")
+ Retrofit mRetrofit;
+ @Inject
+ @Named("oauth")
+ Retrofit mOauthRetrofit;
+ @Inject
+ @Named("upload_media")
+ Retrofit mUploadMediaRetrofit;
+ @Inject
+ RedditDataRoomDatabase mRedditDataRoomDatabase;
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ @Named("current_account")
+ SharedPreferences mCurrentAccountSharedPreferences;
+ @Inject
+ CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
+ private ArrayList<RedditGallerySubmissionRecyclerViewAdapter.RedditGalleryImageInfo> redditGalleryImageInfoList;
+ private String mAccessToken;
+ private String mAccountName;
+ private String iconUrl;
+ private String subredditName;
+ private boolean subredditSelected = false;
+ private boolean subredditIsUser;
+ private boolean loadSubredditIconSuccessful = true;
+ private boolean isPosting;
+ private int primaryTextColor;
+ private int flairBackgroundColor;
+ private int flairTextColor;
+ private int spoilerBackgroundColor;
+ private int spoilerTextColor;
+ private int nsfwBackgroundColor;
+ private int nsfwTextColor;
+ private Flair flair;
+ private boolean isSpoiler = false;
+ private boolean isNSFW = false;
+ private Resources resources;
+ private Menu mMemu;
+ private RequestManager mGlide;
+ private FlairBottomSheetFragment flairSelectionBottomSheetFragment;
+ private Snackbar mPostingSnackbar;
+ private RedditGallerySubmissionRecyclerViewAdapter adapter;
+ private Uri imageUri;
+ private boolean isUploading;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ ((Infinity) getApplication()).getAppComponent().inject(this);
+
+ setImmersiveModeNotApplicable();
+
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_post_gallery);
+
+ ButterKnife.bind(this);
+
+ EventBus.getDefault().register(this);
+
+ applyCustomTheme();
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isChangeStatusBarIconColor()) {
+ addOnOffsetChangedListener(appBarLayout);
+ }
+
+ setSupportActionBar(toolbar);
+ getSupportActionBar().setDisplayHomeAsUpEnabled(true);
+
+ mGlide = Glide.with(this);
+
+ mPostingSnackbar = Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_INDEFINITE);
+
+ resources = getResources();
+
+ mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
+ mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
+
+ adapter = new RedditGallerySubmissionRecyclerViewAdapter(this, mCustomThemeWrapper, new RedditGallerySubmissionRecyclerViewAdapter.ItemClickListener() {
+ @Override
+ public void onAddImageClicked() {
+ if (!isUploading) {
+ SelectOrCaptureImageBottomSheetFragment fragment = new SelectOrCaptureImageBottomSheetFragment();
+ fragment.show(getSupportFragmentManager(), fragment.getTag());
+ } else {
+ Snackbar.make(coordinatorLayout, R.string.please_wait_image_is_uploading, Snackbar.LENGTH_SHORT).show();
+ }
+ }
+ });
+ imagesRecyclerView.setAdapter(adapter);
+ Resources resources = getResources();
+ int nColumns = resources.getBoolean(R.bool.isTablet) || resources.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2;
+ ((GridLayoutManager) imagesRecyclerView.getLayoutManager()).setSpanCount(nColumns);
+ imagesRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
+ @Override
+ public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
+ GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) view.getLayoutParams();
+
+ int spanIndex = layoutParams.getSpanIndex();
+
+ int offset = (int) (Utils.convertDpToPixel(16, PostGalleryActivity.this));
+ int halfOffset = offset / 2;
+
+ if (nColumns == 2) {
+ if (spanIndex == 0) {
+ outRect.set(halfOffset, 0, halfOffset, offset);
+ } else {
+ outRect.set(halfOffset, 0, halfOffset, offset);
+ }
+ } else if (nColumns == 3) {
+ if (spanIndex == 0) {
+ outRect.set(halfOffset, 0, halfOffset, offset);
+ } else if (spanIndex == 1) {
+ outRect.set(halfOffset, 0, halfOffset, offset);
+ } else {
+ outRect.set(halfOffset, 0, halfOffset, offset);
+ }
+ }
+ }
+ });
+
+ if (savedInstanceState != null) {
+ subredditName = savedInstanceState.getString(SUBREDDIT_NAME_STATE);
+ iconUrl = savedInstanceState.getString(SUBREDDIT_ICON_STATE);
+ subredditSelected = savedInstanceState.getBoolean(SUBREDDIT_SELECTED_STATE);
+ subredditIsUser = savedInstanceState.getBoolean(SUBREDDIT_IS_USER_STATE);
+ loadSubredditIconSuccessful = savedInstanceState.getBoolean(LOAD_SUBREDDIT_ICON_STATE);
+ isPosting = savedInstanceState.getBoolean(IS_POSTING_STATE);
+ flair = savedInstanceState.getParcelable(FLAIR_STATE);
+ isSpoiler = savedInstanceState.getBoolean(IS_SPOILER_STATE);
+ isNSFW = savedInstanceState.getBoolean(IS_NSFW_STATE);
+ redditGalleryImageInfoList = savedInstanceState.getParcelableArrayList(REDDIT_GALLERY_IMAGE_INFO_STATE);
+ if (redditGalleryImageInfoList != null && !redditGalleryImageInfoList.isEmpty()) {
+ if (redditGalleryImageInfoList.get(redditGalleryImageInfoList.size() - 1).payload == null) {
+ imageUri = Uri.parse(redditGalleryImageInfoList.get(redditGalleryImageInfoList.size() - 1).imageUrlString);
+ uploadImage();
+ }
+ }
+ adapter.setRedditGalleryImageInfoList(redditGalleryImageInfoList);
+
+ if (subredditName != null) {
+ subredditNameTextView.setTextColor(primaryTextColor);
+ subredditNameTextView.setText(subredditName);
+ flairTextView.setVisibility(View.VISIBLE);
+ if (!loadSubredditIconSuccessful) {
+ loadSubredditIcon();
+ }
+ }
+ displaySubredditIcon();
+
+ if (isPosting) {
+ mPostingSnackbar.show();
+ }
+
+ if (flair != null) {
+ flairTextView.setText(flair.getText());
+ flairTextView.setBackgroundColor(flairBackgroundColor);
+ flairTextView.setBorderColor(flairBackgroundColor);
+ flairTextView.setTextColor(flairTextColor);
+ }
+ if (isSpoiler) {
+ spoilerTextView.setBackgroundColor(spoilerBackgroundColor);
+ spoilerTextView.setBorderColor(spoilerBackgroundColor);
+ spoilerTextView.setTextColor(spoilerTextColor);
+ }
+ if (isNSFW) {
+ nsfwTextView.setBackgroundColor(nsfwBackgroundColor);
+ nsfwTextView.setBorderColor(nsfwBackgroundColor);
+ nsfwTextView.setTextColor(nsfwTextColor);
+ }
+ } else {
+ isPosting = false;
+
+ if (getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
+ loadSubredditIconSuccessful = false;
+ subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
+ subredditSelected = true;
+ subredditNameTextView.setTextColor(primaryTextColor);
+ subredditNameTextView.setText(subredditName);
+ flairTextView.setVisibility(View.VISIBLE);
+ loadSubredditIcon();
+ } else {
+ mGlide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .into(iconGifImageView);
+ }
+ }
+
+ iconGifImageView.setOnClickListener(view -> {
+ Intent intent = new Intent(this, SubredditSelectionActivity.class);
+ startActivityForResult(intent, SUBREDDIT_SELECTION_REQUEST_CODE);
+ });
+
+ subredditNameTextView.setOnClickListener(view -> {
+ Intent intent = new Intent(this, SubredditSelectionActivity.class);
+ startActivityForResult(intent, SUBREDDIT_SELECTION_REQUEST_CODE);
+ });
+
+ rulesButton.setOnClickListener(view -> {
+ if (subredditName == null) {
+ Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ } else {
+ Intent intent = new Intent(this, RulesActivity.class);
+ if (subredditIsUser) {
+ intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
+ } else {
+ intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, subredditName);
+ }
+ startActivity(intent);
+ }
+ });
+
+ flairTextView.setOnClickListener(view -> {
+ if (flair == null) {
+ flairSelectionBottomSheetFragment = new FlairBottomSheetFragment();
+ Bundle bundle = new Bundle();
+ bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
+ bundle.putString(FlairBottomSheetFragment.EXTRA_SUBREDDIT_NAME, subredditName);
+ flairSelectionBottomSheetFragment.setArguments(bundle);
+ flairSelectionBottomSheetFragment.show(getSupportFragmentManager(), flairSelectionBottomSheetFragment.getTag());
+ } else {
+ flairTextView.setBackgroundColor(resources.getColor(android.R.color.transparent));
+ flairTextView.setTextColor(primaryTextColor);
+ flairTextView.setText(getString(R.string.flair));
+ flair = null;
+ }
+ });
+
+ spoilerTextView.setOnClickListener(view -> {
+ if (!isSpoiler) {
+ spoilerTextView.setBackgroundColor(spoilerBackgroundColor);
+ spoilerTextView.setBorderColor(spoilerBackgroundColor);
+ spoilerTextView.setTextColor(spoilerTextColor);
+ isSpoiler = true;
+ } else {
+ spoilerTextView.setBackgroundColor(resources.getColor(android.R.color.transparent));
+ spoilerTextView.setTextColor(primaryTextColor);
+ isSpoiler = false;
+ }
+ });
+
+ nsfwTextView.setOnClickListener(view -> {
+ if (!isNSFW) {
+ nsfwTextView.setBackgroundColor(nsfwBackgroundColor);
+ nsfwTextView.setBorderColor(nsfwBackgroundColor);
+ nsfwTextView.setTextColor(nsfwTextColor);
+ isNSFW = true;
+ } else {
+ nsfwTextView.setBackgroundColor(resources.getColor(android.R.color.transparent));
+ nsfwTextView.setTextColor(primaryTextColor);
+ isNSFW = false;
+ }
+ });
+
+ receivePostReplyNotificationsLinearLayout.setOnClickListener(view -> {
+ receivePostReplyNotificationsSwitchMaterial.performClick();
+ });
+ }
+
+ @Override
+ protected SharedPreferences getDefaultSharedPreferences() {
+ return mSharedPreferences;
+ }
+
+ @Override
+ protected CustomThemeWrapper getCustomThemeWrapper() {
+ return mCustomThemeWrapper;
+ }
+
+ @Override
+ protected void applyCustomTheme() {
+ coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
+ applyAppBarLayoutAndToolbarTheme(appBarLayout, toolbar);
+ int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
+ subredditNameTextView.setTextColor(secondaryTextColor);
+ rulesButton.setTextColor(mCustomThemeWrapper.getButtonTextColor());
+ rulesButton.setBackgroundColor(mCustomThemeWrapper.getColorPrimaryLightTheme());
+ primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ receivePostReplyNotificationsTextView.setTextColor(primaryTextColor);
+ int dividerColor = mCustomThemeWrapper.getDividerColor();
+ divider1.setBackgroundColor(dividerColor);
+ divider2.setBackgroundColor(dividerColor);
+ divider3.setBackgroundColor(dividerColor);
+ divider4.setBackgroundColor(dividerColor);
+ flairBackgroundColor = mCustomThemeWrapper.getFlairBackgroundColor();
+ flairTextColor = mCustomThemeWrapper.getFlairTextColor();
+ spoilerBackgroundColor = mCustomThemeWrapper.getSpoilerBackgroundColor();
+ spoilerTextColor = mCustomThemeWrapper.getSpoilerTextColor();
+ nsfwBackgroundColor = mCustomThemeWrapper.getNsfwBackgroundColor();
+ nsfwTextColor = mCustomThemeWrapper.getNsfwTextColor();
+ flairTextView.setTextColor(primaryTextColor);
+ spoilerTextView.setTextColor(primaryTextColor);
+ nsfwTextView.setTextColor(primaryTextColor);
+ titleEditText.setTextColor(primaryTextColor);
+ titleEditText.setHintTextColor(secondaryTextColor);
+ }
+
+ public void selectImage() {
+ Intent intent = new Intent();
+ intent.setType("image/*");
+ intent.setAction(Intent.ACTION_GET_CONTENT);
+ startActivityForResult(Intent.createChooser(intent, resources.getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
+ }
+
+ public void captureImage() {
+ Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ try {
+ imageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
+ File.createTempFile("temp_img", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
+ pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
+ startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
+ } catch (IOException ex) {
+ Snackbar.make(coordinatorLayout, R.string.error_creating_temp_file, Snackbar.LENGTH_SHORT).show();
+ } catch (ActivityNotFoundException e) {
+ Snackbar.make(coordinatorLayout, R.string.no_camera_available, Snackbar.LENGTH_SHORT).show();
+ }
+ }
+
+ private void uploadImage() {
+ Handler handler = new Handler();
+ isUploading = true;
+ mExecutor.execute(() -> {
+ try {
+ Bitmap resource = Glide.with(PostGalleryActivity.this).asBitmap().load(imageUri).submit().get();
+ String response = UploadImageUtils.uploadImage(mOauthRetrofit, mUploadMediaRetrofit, mAccessToken, resource, true);
+ String mediaId = new JSONObject(response).getJSONObject(JSONUtils.ASSET_KEY).getString(JSONUtils.ASSET_ID_KEY);
+ handler.post(() -> {
+ adapter.setImageAsUploaded(mediaId);
+ isUploading = false;
+ });
+ } catch (ExecutionException | InterruptedException e) {
+ e.printStackTrace();
+ handler.post(() -> {
+ adapter.removeFailedToUploadImage();
+ Snackbar.make(coordinatorLayout, R.string.get_image_bitmap_failed, Snackbar.LENGTH_LONG).show();
+ isUploading = false;
+ });
+ } catch (XmlPullParserException | JSONException | IOException e) {
+ e.printStackTrace();
+ handler.post(() -> {
+ adapter.removeFailedToUploadImage();
+ Snackbar.make(coordinatorLayout, R.string.upload_image_failed, Snackbar.LENGTH_LONG).show();
+ isUploading = false;
+ });
+ }
+ });
+ }
+
+ private void displaySubredditIcon() {
+ if (iconUrl != null && !iconUrl.equals("")) {
+ mGlide.load(iconUrl)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .error(mGlide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
+ .into(iconGifImageView);
+ } else {
+ mGlide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .into(iconGifImageView);
+ }
+ }
+
+ private void loadSubredditIcon() {
+ LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mRetrofit, iconImageUrl -> {
+ iconUrl = iconImageUrl;
+ displaySubredditIcon();
+ loadSubredditIconSuccessful = true;
+ });
+ }
+
+ private void promptAlertDialog(int titleResId, int messageResId) {
+ new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
+ .setTitle(titleResId)
+ .setMessage(messageResId)
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i)
+ -> finish())
+ .setNegativeButton(R.string.no, null)
+ .show();
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.post_gallery_activity, menu);
+ applyMenuItemTheme(menu);
+ mMemu = menu;
+ if (isPosting) {
+ mMemu.findItem(R.id.action_send_post_gallery_activity).setEnabled(false);
+ mMemu.findItem(R.id.action_send_post_gallery_activity).getIcon().setAlpha(130);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(@NonNull MenuItem item) {
+ int itemId = item.getItemId();
+ if (itemId == android.R.id.home) {
+ if (isPosting) {
+ promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
+ return true;
+ } else {
+ if (!titleEditText.getText().toString().equals("") || redditGalleryImageInfoList != null) {
+ promptAlertDialog(R.string.discard, R.string.discard_detail);
+ return true;
+ }
+ }
+ finish();
+ return true;
+ } else if (itemId == R.id.action_send_post_gallery_activity) {
+ if (!subredditSelected) {
+ Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
+
+ if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
+
+ if (redditGalleryImageInfoList == null || redditGalleryImageInfoList.isEmpty()) {
+ Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
+
+ if (redditGalleryImageInfoList.get(redditGalleryImageInfoList.size() - 1).payload == null) {
+ Snackbar.make(coordinatorLayout, R.string.please_wait_image_is_uploading, Snackbar.LENGTH_LONG).show();
+ return true;
+ }
+
+ isPosting = true;
+
+ item.setEnabled(false);
+ item.getIcon().setAlpha(130);
+
+ mPostingSnackbar.show();
+
+ String subredditName;
+ if (subredditIsUser) {
+ subredditName = "u_" + subredditNameTextView.getText().toString();
+ } else {
+ subredditName = subredditNameTextView.getText().toString();
+ }
+
+ Intent intent = new Intent(this, SubmitPostService.class);
+ intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
+ intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
+ intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_GALLERY);
+ ArrayList<RedditGalleryPayload.Item> items = new ArrayList<>();
+ for (RedditGallerySubmissionRecyclerViewAdapter.RedditGalleryImageInfo i : redditGalleryImageInfoList) {
+ items.add(i.payload);
+ }
+ RedditGalleryPayload payload = new RedditGalleryPayload(subredditName, subredditIsUser ? "profile" : "subreddit",
+ titleEditText.getText().toString(), isSpoiler, isNSFW, receivePostReplyNotificationsSwitchMaterial.isChecked(),
+ flair, items);
+ intent.putExtra(SubmitPostService.EXTRA_REDDIT_GALLERY_PAYLOAD, new Gson().toJson(payload));
+
+ ContextCompat.startForegroundService(this, intent);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public void onBackPressed() {
+ if (isPosting) {
+ promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
+ } else {
+ if (!titleEditText.getText().toString().equals("") || redditGalleryImageInfoList != null) {
+ promptAlertDialog(R.string.discard, R.string.discard_detail);
+ } else {
+ finish();
+ }
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString(SUBREDDIT_NAME_STATE, subredditName);
+ outState.putString(SUBREDDIT_ICON_STATE, iconUrl);
+ outState.putBoolean(SUBREDDIT_SELECTED_STATE, subredditSelected);
+ outState.putBoolean(SUBREDDIT_IS_USER_STATE, subredditIsUser);
+ outState.putBoolean(LOAD_SUBREDDIT_ICON_STATE, loadSubredditIconSuccessful);
+ outState.putBoolean(IS_POSTING_STATE, isPosting);
+ outState.putParcelable(FLAIR_STATE, flair);
+ outState.putBoolean(IS_SPOILER_STATE, isSpoiler);
+ outState.putBoolean(IS_NSFW_STATE, isNSFW);
+ redditGalleryImageInfoList = adapter.getRedditGalleryImageInfoList();
+ outState.putParcelableArrayList(REDDIT_GALLERY_IMAGE_INFO_STATE, redditGalleryImageInfoList);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
+ if (resultCode == RESULT_OK) {
+ subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
+ iconUrl = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
+ subredditSelected = true;
+ subredditIsUser = data.getExtras().getBoolean(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_IS_USER);
+
+ subredditNameTextView.setTextColor(primaryTextColor);
+ subredditNameTextView.setText(subredditName);
+ displaySubredditIcon();
+
+ flairTextView.setVisibility(View.VISIBLE);
+ flairTextView.setBackgroundColor(resources.getColor(android.R.color.transparent));
+ flairTextView.setTextColor(primaryTextColor);
+ flairTextView.setText(getString(R.string.flair));
+ flair = null;
+ }
+ } else if (requestCode == PICK_IMAGE_REQUEST_CODE) {
+ if (resultCode == RESULT_OK) {
+ if (data == null) {
+ Snackbar.make(coordinatorLayout, R.string.error_getting_image, Snackbar.LENGTH_SHORT).show();
+ return;
+ }
+
+ imageUri = data.getData();
+ adapter.addImage(imageUri.toString());
+ uploadImage();
+ }
+ } else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
+ if (resultCode == RESULT_OK) {
+ adapter.addImage(imageUri.toString());
+ uploadImage();
+ }
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ EventBus.getDefault().unregister(this);
+ super.onDestroy();
+ }
+
+ @Override
+ public void flairSelected(Flair flair) {
+ this.flair = flair;
+ flairTextView.setText(flair.getText());
+ flairTextView.setBackgroundColor(flairBackgroundColor);
+ flairTextView.setBorderColor(flairBackgroundColor);
+ flairTextView.setTextColor(flairTextColor);
+ }
+
+ @Subscribe
+ public void onAccountSwitchEvent(SwitchAccountEvent event) {
+ finish();
+ }
+
+ @Subscribe
+ public void onSubmitGalleryPostEvent(SubmitGalleryPostEvent submitGalleryPostEvent) {
+ isPosting = false;
+ mPostingSnackbar.dismiss();
+ if (submitGalleryPostEvent.postSuccess) {
+ Intent intent = new Intent(this, LinkResolverActivity.class);
+ intent.setData(Uri.parse(submitGalleryPostEvent.postUrl));
+ startActivity(intent);
+ finish();
+ } else {
+ mMemu.findItem(R.id.action_send_post_gallery_activity).setEnabled(true);
+ mMemu.findItem(R.id.action_send_post_gallery_activity).getIcon().setAlpha(255);
+ if (submitGalleryPostEvent.errorMessage == null || submitGalleryPostEvent.errorMessage.equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
+ } else {
+ Snackbar.make(coordinatorLayout, submitGalleryPostEvent.errorMessage.substring(0, 1).toUpperCase()
+ + submitGalleryPostEvent.errorMessage.substring(1), Snackbar.LENGTH_SHORT).show();
+ }
+ }
+ }
+} \ No newline at end of file
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 cbab1914..acf5034d 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostImageActivity.java
@@ -1,8 +1,8 @@
package ml.docilealligator.infinityforreddit.activities;
+import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
@@ -13,9 +13,9 @@ import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
-import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
+import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
@@ -30,9 +30,11 @@ import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
+import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.switchmaterial.SwitchMaterial;
import com.libRG.CustomTextView;
import org.greenrobot.eventbus.EventBus;
@@ -93,7 +95,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
@BindView(R.id.subreddit_name_text_view_post_image_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_image_activity)
- Button rulesButton;
+ MaterialButton rulesButton;
@BindView(R.id.divider_1_post_image_activity)
View divider1;
@BindView(R.id.flair_custom_text_view_post_image_activity)
@@ -104,10 +106,18 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
CustomTextView nsfwTextView;
@BindView(R.id.divider_2_post_image_activity)
View divider2;
- @BindView(R.id.post_title_edit_text_post_image_activity)
- EditText titleEditText;
+ @BindView(R.id.receive_post_reply_notifications_linear_layout_post_image_activity)
+ LinearLayout receivePostReplyNotificationsLinearLayout;
+ @BindView(R.id.receive_post_reply_notifications_text_view_post_image_activity)
+ TextView receivePostReplyNotificationsTextView;
+ @BindView(R.id.receive_post_reply_notifications_switch_material_post_image_activity)
+ SwitchMaterial receivePostReplyNotificationsSwitchMaterial;
@BindView(R.id.divider_3_post_image_activity)
View divider3;
+ @BindView(R.id.post_title_edit_text_post_image_activity)
+ EditText titleEditText;
+ @BindView(R.id.divider_4_post_image_activity)
+ View divider4;
@BindView(R.id.select_image_constraint_layout_post_image_activity)
ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_image_activity)
@@ -331,18 +341,20 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
}
});
+ receivePostReplyNotificationsLinearLayout.setOnClickListener(view -> {
+ receivePostReplyNotificationsSwitchMaterial.performClick();
+ });
+
captureFab.setOnClickListener(view -> {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- if (pictureIntent.resolveActivity(getPackageManager()) != null) {
- try {
- imageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
- File.createTempFile("temp_img", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
- pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
- startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
- } catch (IOException ex) {
- Snackbar.make(coordinatorLayout, R.string.error_creating_temp_file, Snackbar.LENGTH_SHORT).show();
- }
- } else {
+ try {
+ imageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
+ File.createTempFile("temp_img", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
+ pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
+ startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
+ } catch (IOException ex) {
+ Snackbar.make(coordinatorLayout, R.string.error_creating_temp_file, Snackbar.LENGTH_SHORT).show();
+ } catch (ActivityNotFoundException e) {
Snackbar.make(coordinatorLayout, R.string.no_camera_available, Snackbar.LENGTH_SHORT).show();
}
});
@@ -380,12 +392,14 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
subredditNameTextView.setTextColor(secondaryTextColor);
rulesButton.setTextColor(mCustomThemeWrapper.getButtonTextColor());
- rulesButton.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimaryLightTheme()));
+ rulesButton.setBackgroundColor(mCustomThemeWrapper.getColorPrimaryLightTheme());
+ primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ receivePostReplyNotificationsTextView.setTextColor(primaryTextColor);
int dividerColor = mCustomThemeWrapper.getDividerColor();
divider1.setBackgroundColor(dividerColor);
divider2.setBackgroundColor(dividerColor);
divider3.setBackgroundColor(dividerColor);
- primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ divider4.setBackgroundColor(dividerColor);
flairBackgroundColor = mCustomThemeWrapper.getFlairBackgroundColor();
flairTextColor = mCustomThemeWrapper.getFlairTextColor();
spoilerBackgroundColor = mCustomThemeWrapper.getSpoilerBackgroundColor();
@@ -435,7 +449,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(titleResId)
.setMessage(messageResId)
- .setPositiveButton(R.string.yes, (dialogInterface, i)
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i)
-> finish())
.setNegativeButton(R.string.no, null)
.show();
@@ -455,68 +469,69 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
- switch (item.getItemId()) {
- case android.R.id.home:
- if (isPosting) {
- promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
- return true;
- } else {
- if (!titleEditText.getText().toString().equals("") || imageUri != null) {
- promptAlertDialog(R.string.discard, R.string.discard_detail);
- return true;
- }
- }
- finish();
+ int itemId = item.getItemId();
+ if (itemId == android.R.id.home) {
+ if (isPosting) {
+ promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
return true;
- case R.id.action_send_post_image_activity:
- if (!subredditSelected) {
- Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ } else {
+ if (!titleEditText.getText().toString().equals("") || imageUri != null) {
+ promptAlertDialog(R.string.discard, R.string.discard_detail);
return true;
}
+ }
+ finish();
+ return true;
+ } else if (itemId == R.id.action_send_post_image_activity) {
+ if (!subredditSelected) {
+ Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
- Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
- return true;
- }
+ if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- if (imageUri == null) {
- Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
- return true;
- }
+ if (imageUri == null) {
+ Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- isPosting = true;
+ isPosting = true;
- item.setEnabled(false);
- item.getIcon().setAlpha(130);
+ item.setEnabled(false);
+ item.getIcon().setAlpha(130);
- mPostingSnackbar.show();
+ mPostingSnackbar.show();
- String subredditName;
- if (subredditIsUser) {
- subredditName = "u_" + subredditNameTextView.getText().toString();
- } else {
- subredditName = subredditNameTextView.getText().toString();
- }
+ String subredditName;
+ if (subredditIsUser) {
+ subredditName = "u_" + subredditNameTextView.getText().toString();
+ } else {
+ subredditName = subredditNameTextView.getText().toString();
+ }
- Intent intent = new Intent(this, SubmitPostService.class);
- intent.setData(imageUri);
- intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
- intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
- intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
- intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
- intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
- intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
- String mimeType = getContentResolver().getType(imageUri);
- if (mimeType != null && mimeType.contains("gif")) {
- intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_VIDEO);
- } else {
- intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_IMAGE);
- }
- intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+ Intent intent = new Intent(this, SubmitPostService.class);
+ intent.setData(imageUri);
+ intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
+ intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
+ intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
+ intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
+ intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
+ intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
+ intent.putExtra(SubmitPostService.EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, receivePostReplyNotificationsSwitchMaterial.isChecked());
+ String mimeType = getContentResolver().getType(imageUri);
+ if (mimeType != null && mimeType.contains("gif")) {
+ intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_VIDEO);
+ } else {
+ intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_IMAGE);
+ }
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
- ContextCompat.startForegroundService(this, intent);
+ ContextCompat.startForegroundService(this, intent);
- return true;
+ return true;
}
return false;
@@ -631,7 +646,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
}
@Subscribe
- public void onSubmitVideoOrGifPostEvent(SubmitVideoOrGifPostEvent submitVideoOrGifPostEvent) {
+ public void onSubmitGifPostEvent(SubmitVideoOrGifPostEvent submitVideoOrGifPostEvent) {
isPosting = false;
mPostingSnackbar.dismiss();
mMemu.findItem(R.id.action_send_post_image_activity).setEnabled(true);
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 ab1852bc..8ce97d55 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostLinkActivity.java
@@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit.activities;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
@@ -10,8 +9,8 @@ import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
-import android.widget.Button;
import android.widget.EditText;
+import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@@ -28,6 +27,7 @@ import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.switchmaterial.SwitchMaterial;
import com.libRG.CustomTextView;
import org.greenrobot.eventbus.EventBus;
@@ -89,19 +89,27 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
@BindView(R.id.subreddit_name_text_view_post_link_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_link_activity)
- Button rulesButton;
+ MaterialButton rulesButton;
@BindView(R.id.divider_1_post_link_activity)
View divider1;
@BindView(R.id.divider_2_post_link_activity)
View divider2;
- @BindView(R.id.divider_3_post_link_activity)
- View divider3;
+ @BindView(R.id.divider_4_post_link_activity)
+ View divider4;
@BindView(R.id.flair_custom_text_view_post_link_activity)
CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_link_activity)
CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_link_activity)
CustomTextView nsfwTextView;
+ @BindView(R.id.receive_post_reply_notifications_linear_layout_post_link_activity)
+ LinearLayout receivePostReplyNotificationsLinearLayout;
+ @BindView(R.id.receive_post_reply_notifications_text_view_post_link_activity)
+ TextView receivePostReplyNotificationsTextView;
+ @BindView(R.id.receive_post_reply_notifications_switch_material_post_link_activity)
+ SwitchMaterial receivePostReplyNotificationsSwitchMaterial;
+ @BindView(R.id.divider_3_post_link_activity)
+ View divider3;
@BindView(R.id.post_title_edit_text_post_link_activity)
EditText titleEditText;
@BindView(R.id.suggest_title_button_post_link_activity)
@@ -310,6 +318,10 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
}
});
+ receivePostReplyNotificationsLinearLayout.setOnClickListener(view -> {
+ receivePostReplyNotificationsSwitchMaterial.performClick();
+ });
+
suggestTitleButton.setOnClickListener(view -> {
Toast.makeText(this, R.string.please_wait, Toast.LENGTH_SHORT).show();
String url = linkEditText.getText().toString().trim();
@@ -354,12 +366,14 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
subredditNameTextView.setTextColor(secondaryTextColor);
rulesButton.setTextColor(mCustomThemeWrapper.getButtonTextColor());
- rulesButton.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimaryLightTheme()));
+ rulesButton.setBackgroundColor(mCustomThemeWrapper.getColorPrimaryLightTheme());
+ primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ receivePostReplyNotificationsTextView.setTextColor(primaryTextColor);
int dividerColor = mCustomThemeWrapper.getDividerColor();
divider1.setBackgroundColor(dividerColor);
divider2.setBackgroundColor(dividerColor);
divider3.setBackgroundColor(dividerColor);
- primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ divider4.setBackgroundColor(dividerColor);
flairBackgroundColor = mCustomThemeWrapper.getFlairBackgroundColor();
flairTextColor = mCustomThemeWrapper.getFlairTextColor();
spoilerBackgroundColor = mCustomThemeWrapper.getSpoilerBackgroundColor();
@@ -404,7 +418,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(titleResId)
.setMessage(messageResId)
- .setPositiveButton(R.string.yes, (dialogInterface, i) -> finish())
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i) -> finish())
.setNegativeButton(R.string.no, null)
.show();
}
@@ -475,6 +489,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
+ intent.putExtra(SubmitPostService.EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, receivePostReplyNotificationsSwitchMaterial.isChecked());
intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TEXT_OR_LINK);
ContextCompat.startForegroundService(this, intent);
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 7d93fef7..a03f7355 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostTextActivity.java
@@ -1,24 +1,29 @@
package ml.docilealligator.infinityforreddit.activities;
+import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.content.res.ColorStateList;
import android.content.res.Resources;
+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;
import android.view.View;
-import android.widget.Button;
import android.widget.EditText;
+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.ContextCompat;
+import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@@ -26,13 +31,18 @@ import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
+import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.switchmaterial.SwitchMaterial;
import com.libRG.CustomTextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
import java.util.concurrent.Executor;
import javax.inject.Inject;
@@ -45,19 +55,25 @@ import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
+import ml.docilealligator.infinityforreddit.UploadImageEnabledActivity;
+import ml.docilealligator.infinityforreddit.UploadedImage;
import ml.docilealligator.infinityforreddit.adapters.MarkdownBottomBarRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.asynctasks.LoadSubredditIcon;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.UploadedImagesBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.SubmitTextOrLinkPostEvent;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.services.SubmitPostService;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import ml.docilealligator.infinityforreddit.utils.Utils;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
-public class PostTextActivity extends BaseActivity implements FlairBottomSheetFragment.FlairSelectionCallback {
+public class PostTextActivity extends BaseActivity implements FlairBottomSheetFragment.FlairSelectionCallback,
+ UploadImageEnabledActivity {
static final String EXTRA_SUBREDDIT_NAME = "ESN";
static final String EXTRA_CONTENT = "EC";
@@ -71,8 +87,12 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
private static final String FLAIR_STATE = "FS";
private static final String IS_SPOILER_STATE = "ISS";
private static final String IS_NSFW_STATE = "INS";
+ private static final String UPLOADED_IMAGES_STATE = "UIS";
private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0;
+ private static final int PICK_IMAGE_REQUEST_CODE = 100;
+ private static final int CAPTURE_IMAGE_REQUEST_CODE = 200;
+ private static final int MARKDOWN_PREVIEW_REQUEST_CODE = 300;
@BindView(R.id.coordinator_layout_post_text_activity)
CoordinatorLayout coordinatorLayout;
@@ -80,12 +100,12 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_post_text_activity)
Toolbar toolbar;
- @BindView(R.id.subreddit_icon_gif_image_view_search_activity)
+ @BindView(R.id.subreddit_icon_gif_image_view_post_text_activity)
GifImageView iconGifImageView;
- @BindView(R.id.subreddit_name_text_view_search_activity)
+ @BindView(R.id.subreddit_name_text_view_post_text_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_text_activity)
- Button rulesButton;
+ MaterialButton rulesButton;
@BindView(R.id.divider_1_post_text_activity)
View divider1;
@BindView(R.id.flair_custom_text_view_post_text_activity)
@@ -96,10 +116,18 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
CustomTextView nsfwTextView;
@BindView(R.id.divider_2_post_text_activity)
View divider2;
- @BindView(R.id.post_title_edit_text_post_text_activity)
- EditText titleEditText;
+ @BindView(R.id.receive_post_reply_notifications_linear_layout_post_text_activity)
+ LinearLayout receivePostReplyNotificationsLinearLayout;
+ @BindView(R.id.receive_post_reply_notifications_text_view_post_text_activity)
+ TextView receivePostReplyNotificationsTextView;
+ @BindView(R.id.receive_post_reply_notifications_switch_material_post_text_activity)
+ SwitchMaterial receivePostReplyNotificationsSwitchMaterial;
@BindView(R.id.divider_3_post_text_activity)
View divider3;
+ @BindView(R.id.post_title_edit_text_post_text_activity)
+ EditText titleEditText;
+ @BindView(R.id.divider_4_post_text_activity)
+ View divider4;
@BindView(R.id.post_text_content_edit_text_post_text_activity)
EditText contentEditText;
@BindView(R.id.markdown_bottom_bar_recycler_view_post_text_activity)
@@ -111,6 +139,9 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
+ @Named("upload_media")
+ Retrofit mUploadMediaRetrofit;
+ @Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
@@ -144,6 +175,8 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
private RequestManager mGlide;
private FlairBottomSheetFragment flairSelectionBottomSheetFragment;
private Snackbar mPostingSnackbar;
+ private Uri capturedImageUri;
+ private ArrayList<UploadedImage> uploadedImages = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -186,6 +219,7 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
flair = savedInstanceState.getParcelable(FLAIR_STATE);
isSpoiler = savedInstanceState.getBoolean(IS_SPOILER_STATE);
isNSFW = savedInstanceState.getBoolean(IS_NSFW_STATE);
+ uploadedImages = savedInstanceState.getParcelableArrayList(UPLOADED_IMAGES_STATE);
if (subredditName != null) {
subredditNameTextView.setTextColor(primaryTextColor);
@@ -310,11 +344,31 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
}
});
- MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(mCustomThemeWrapper, item -> {
- MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(this, contentEditText, item);
+ receivePostReplyNotificationsLinearLayout.setOnClickListener(view -> {
+ receivePostReplyNotificationsSwitchMaterial.performClick();
+ });
+
+ MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(
+ mCustomThemeWrapper, new MarkdownBottomBarRecyclerViewAdapter.ItemClickListener() {
+ @Override
+ public void onClick(int item) {
+ MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(
+ PostTextActivity.this, contentEditText, item);
+ }
+
+ @Override
+ public void onUploadImage() {
+ Utils.hideKeyboard(PostTextActivity.this);
+ UploadedImagesBottomSheetFragment fragment = new UploadedImagesBottomSheetFragment();
+ Bundle arguments = new Bundle();
+ arguments.putParcelableArrayList(UploadedImagesBottomSheetFragment.EXTRA_UPLOADED_IMAGES,
+ uploadedImages);
+ fragment.setArguments(arguments);
+ fragment.show(getSupportFragmentManager(), fragment.getTag());
+ }
});
- markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManager(this,
+ markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this,
LinearLayoutManager.HORIZONTAL, false));
markdownBottomBarRecyclerView.setAdapter(adapter);
}
@@ -336,12 +390,14 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
subredditNameTextView.setTextColor(secondaryTextColor);
rulesButton.setTextColor(mCustomThemeWrapper.getButtonTextColor());
- rulesButton.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimaryLightTheme()));
+ rulesButton.setBackgroundColor(mCustomThemeWrapper.getColorPrimaryLightTheme());
+ primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ receivePostReplyNotificationsTextView.setTextColor(primaryTextColor);
int dividerColor = mCustomThemeWrapper.getDividerColor();
divider1.setBackgroundColor(dividerColor);
divider2.setBackgroundColor(dividerColor);
divider3.setBackgroundColor(dividerColor);
- primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ divider4.setBackgroundColor(dividerColor);
flairBackgroundColor = mCustomThemeWrapper.getFlairBackgroundColor();
flairTextColor = mCustomThemeWrapper.getFlairTextColor();
spoilerBackgroundColor = mCustomThemeWrapper.getSpoilerBackgroundColor();
@@ -384,9 +440,9 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(titleResId)
.setMessage(messageResId)
- .setPositiveButton(R.string.yes, (dialogInterface, i)
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i)
-> finish())
- .setNegativeButton(R.string.no, null)
+ .setNegativeButton(R.string.cancel, null)
.show();
}
@@ -420,48 +476,55 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
} else if (itemId == R.id.action_preview_post_text_activity) {
Intent intent = new Intent(this, FullMarkdownActivity.class);
intent.putExtra(FullMarkdownActivity.EXTRA_COMMENT_MARKDOWN, contentEditText.getText().toString());
- startActivity(intent);
+ intent.putExtra(FullMarkdownActivity.EXTRA_SUBMIT_POST, true);
+ startActivityForResult(intent, MARKDOWN_PREVIEW_REQUEST_CODE);
} else if (itemId == R.id.action_send_post_text_activity) {
- if (!subredditSelected) {
- Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
- return true;
- }
+ submitPost(item);
+ return true;
+ }
- if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
- Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
- return true;
- }
+ return false;
+ }
- isPosting = true;
+ private void submitPost(MenuItem item) {
+ if (!subredditSelected) {
+ Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ return;
+ }
- item.setEnabled(false);
- item.getIcon().setAlpha(130);
+ if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
+ return;
+ }
- mPostingSnackbar.show();
+ isPosting = true;
- String subredditName;
- if (subredditIsUser) {
- subredditName = "u_" + subredditNameTextView.getText().toString();
- } else {
- subredditName = subredditNameTextView.getText().toString();
- }
+ if (item != null) {
+ item.setEnabled(false);
+ item.getIcon().setAlpha(130);
+ }
- Intent intent = new Intent(this, SubmitPostService.class);
- intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
- intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
- intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
- intent.putExtra(SubmitPostService.EXTRA_CONTENT, contentEditText.getText().toString());
- intent.putExtra(SubmitPostService.EXTRA_KIND, APIUtils.KIND_SELF);
- intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
- intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
- intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
- intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TEXT_OR_LINK);
- ContextCompat.startForegroundService(this, intent);
+ mPostingSnackbar.show();
- return true;
+ String subredditName;
+ if (subredditIsUser) {
+ subredditName = "u_" + subredditNameTextView.getText().toString();
+ } else {
+ subredditName = subredditNameTextView.getText().toString();
}
- return false;
+ Intent intent = new Intent(this, SubmitPostService.class);
+ intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
+ intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
+ intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
+ intent.putExtra(SubmitPostService.EXTRA_CONTENT, contentEditText.getText().toString());
+ intent.putExtra(SubmitPostService.EXTRA_KIND, APIUtils.KIND_SELF);
+ intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
+ intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
+ intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
+ intent.putExtra(SubmitPostService.EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, receivePostReplyNotificationsSwitchMaterial.isChecked());
+ intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TEXT_OR_LINK);
+ ContextCompat.startForegroundService(this, intent);
}
@Override
@@ -489,13 +552,14 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
outState.putParcelable(FLAIR_STATE, flair);
outState.putBoolean(IS_SPOILER_STATE, isSpoiler);
outState.putBoolean(IS_NSFW_STATE, isNSFW);
+ outState.putParcelableArrayList(UPLOADED_IMAGES_STATE, uploadedImages);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
- if (resultCode == RESULT_OK) {
+ if (resultCode == RESULT_OK) {
+ if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
iconUrl = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
subredditSelected = true;
@@ -510,8 +574,22 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
flairTextView.setTextColor(primaryTextColor);
flairTextView.setText(getString(R.string.flair));
flair = null;
+
+ } else if (requestCode == PICK_IMAGE_REQUEST_CODE) {
+ if (data == null) {
+ Toast.makeText(PostTextActivity.this, R.string.error_getting_image, Toast.LENGTH_LONG).show();
+ return;
+ }
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, contentEditText, coordinatorLayout, data.getData(), uploadedImages);
+ } else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
+ Utils.uploadImageToReddit(this, mExecutor, mOauthRetrofit, mUploadMediaRetrofit,
+ mAccessToken, contentEditText, coordinatorLayout, capturedImageUri, uploadedImages);
+ } else if (requestCode == MARKDOWN_PREVIEW_REQUEST_CODE) {
+ submitPost(mMenu.findItem(R.id.action_send_post_text_activity));
}
}
+
}
@Override
@@ -554,4 +632,37 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
}
}
}
+
+ @Override
+ public void uploadImage() {
+ Intent intent = new Intent();
+ intent.setType("image/*");
+ intent.setAction(Intent.ACTION_GET_CONTENT);
+ startActivityForResult(Intent.createChooser(intent,
+ getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
+ }
+
+ @Override
+ public void captureImage() {
+ Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ try {
+ capturedImageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
+ File.createTempFile("captured_image", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
+ pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
+ startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
+ } catch (IOException ex) {
+ Toast.makeText(this, R.string.error_creating_temp_file, Toast.LENGTH_SHORT).show();
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.no_camera_available, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ @Override
+ public void insertImageUrl(UploadedImage uploadedImage) {
+ int start = Math.max(contentEditText.getSelectionStart(), 0);
+ int end = Math.max(contentEditText.getSelectionEnd(), 0);
+ contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
+ "[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
+ 0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
+ }
}
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 420477ff..109d10d3 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/PostVideoActivity.java
@@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit.activities;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
@@ -12,8 +11,8 @@ import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
-import android.widget.Button;
import android.widget.EditText;
+import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
@@ -35,9 +34,11 @@ import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.google.android.material.appbar.AppBarLayout;
+import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.switchmaterial.SwitchMaterial;
import com.libRG.CustomTextView;
import org.greenrobot.eventbus.EventBus;
@@ -95,7 +96,7 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
@BindView(R.id.subreddit_name_text_view_post_video_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_video_activity)
- Button rulesButton;
+ MaterialButton rulesButton;
@BindView(R.id.divider_1_post_video_activity)
View divider1;
@BindView(R.id.flair_custom_text_view_post_video_activity)
@@ -106,10 +107,18 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
CustomTextView nsfwTextView;
@BindView(R.id.divider_2_post_video_activity)
View divider2;
- @BindView(R.id.post_title_edit_text_post_video_activity)
- EditText titleEditText;
+ @BindView(R.id.receive_post_reply_notifications_linear_layout_post_video_activity)
+ LinearLayout receivePostReplyNotificationsLinearLayout;
+ @BindView(R.id.receive_post_reply_notifications_text_view_post_video_activity)
+ TextView receivePostReplyNotificationsTextView;
+ @BindView(R.id.receive_post_reply_notifications_switch_material_post_video_activity)
+ SwitchMaterial receivePostReplyNotificationsSwitchMaterial;
@BindView(R.id.divider_3_post_video_activity)
View divider3;
+ @BindView(R.id.post_title_edit_text_post_video_activity)
+ EditText titleEditText;
+ @BindView(R.id.divider_4_post_video_activity)
+ View divider4;
@BindView(R.id.select_video_constraint_layout_post_video_activity)
ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_video_activity)
@@ -345,6 +354,10 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
}
});
+ receivePostReplyNotificationsLinearLayout.setOnClickListener(view -> {
+ receivePostReplyNotificationsSwitchMaterial.performClick();
+ });
+
captureFab.setOnClickListener(view -> {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
@@ -386,12 +399,14 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
subredditNameTextView.setTextColor(secondaryTextColor);
rulesButton.setTextColor(mCustomThemeWrapper.getButtonTextColor());
- rulesButton.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimaryLightTheme()));
+ rulesButton.setBackgroundColor(mCustomThemeWrapper.getColorPrimaryLightTheme());
+ primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ receivePostReplyNotificationsTextView.setTextColor(primaryTextColor);
int dividerColor = mCustomThemeWrapper.getDividerColor();
divider1.setBackgroundColor(dividerColor);
divider2.setBackgroundColor(dividerColor);
divider3.setBackgroundColor(dividerColor);
- primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ divider4.setBackgroundColor(dividerColor);
flairBackgroundColor = mCustomThemeWrapper.getFlairBackgroundColor();
flairTextColor = mCustomThemeWrapper.getFlairTextColor();
spoilerBackgroundColor = mCustomThemeWrapper.getSpoilerBackgroundColor();
@@ -444,7 +459,7 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(titleResId)
.setMessage(messageResId)
- .setPositiveButton(R.string.yes, (dialogInterface, i) -> finish())
+ .setPositiveButton(R.string.discard_dialog_button, (dialogInterface, i) -> finish())
.setNegativeButton(R.string.no, null)
.show();
}
@@ -463,63 +478,64 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
- switch (item.getItemId()) {
- case android.R.id.home:
- if (isPosting) {
- promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
- return true;
- } else {
- if (!titleEditText.getText().toString().equals("") || videoUri != null) {
- promptAlertDialog(R.string.discard, R.string.discard_detail);
- return true;
- }
- }
- finish();
+ int itemId = item.getItemId();
+ if (itemId == android.R.id.home) {
+ if (isPosting) {
+ promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
return true;
- case R.id.action_send_post_video_activity:
- if (!subredditSelected) {
- Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
- return true;
- }
-
- if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
- Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
- return true;
- }
-
- if (videoUri == null) {
- Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
+ } else {
+ if (!titleEditText.getText().toString().equals("") || videoUri != null) {
+ promptAlertDialog(R.string.discard, R.string.discard_detail);
return true;
}
+ }
+ finish();
+ return true;
+ } else if (itemId == R.id.action_send_post_video_activity) {
+ if (!subredditSelected) {
+ Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- isPosting = true;
+ if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- item.setEnabled(false);
- item.getIcon().setAlpha(130);
+ if (videoUri == null) {
+ Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- mPostingSnackbar.show();
+ isPosting = true;
- String subredditName;
- if (subredditIsUser) {
- subredditName = "u_" + subredditNameTextView.getText().toString();
- } else {
- subredditName = subredditNameTextView.getText().toString();
- }
+ item.setEnabled(false);
+ item.getIcon().setAlpha(130);
- Intent intent = new Intent(this, SubmitPostService.class);
- intent.setData(videoUri);
- intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
- intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
- intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
- intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
- intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
- intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
- intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_VIDEO);
- intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+ mPostingSnackbar.show();
- ContextCompat.startForegroundService(this, intent);
+ String subredditName;
+ if (subredditIsUser) {
+ subredditName = "u_" + subredditNameTextView.getText().toString();
+ } else {
+ subredditName = subredditNameTextView.getText().toString();
+ }
- return true;
+ Intent intent = new Intent(this, SubmitPostService.class);
+ intent.setData(videoUri);
+ intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
+ intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
+ intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
+ intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
+ intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
+ intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
+ intent.putExtra(SubmitPostService.EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, receivePostReplyNotificationsSwitchMaterial.isChecked());
+ intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_VIDEO);
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+
+ ContextCompat.startForegroundService(this, intent);
+
+ return true;
}
return false;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RPANActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RPANActivity.java
new file mode 100644
index 00000000..d99511ac
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RPANActivity.java
@@ -0,0 +1,412 @@
+package ml.docilealligator.infinityforreddit.activities;
+
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.graphics.Color;
+import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.Drawable;
+import android.media.AudioManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.ProgressBar;
+import android.widget.Toast;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.coordinatorlayout.widget.CoordinatorLayout;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
+import androidx.recyclerview.widget.RecyclerView;
+import androidx.viewpager2.adapter.FragmentStateAdapter;
+import androidx.viewpager2.widget.ViewPager2;
+
+import com.evernote.android.state.State;
+import com.google.android.material.snackbar.Snackbar;
+import com.livefront.bridge.Bridge;
+
+import org.greenrobot.eventbus.EventBus;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.concurrent.Executor;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.RPANBroadcast;
+import ml.docilealligator.infinityforreddit.apis.Strapi;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.font.ContentFontFamily;
+import ml.docilealligator.infinityforreddit.font.ContentFontStyle;
+import ml.docilealligator.infinityforreddit.font.FontFamily;
+import ml.docilealligator.infinityforreddit.font.FontStyle;
+import ml.docilealligator.infinityforreddit.font.TitleFontFamily;
+import ml.docilealligator.infinityforreddit.font.TitleFontStyle;
+import ml.docilealligator.infinityforreddit.fragments.ViewRPANBroadcastFragment;
+import ml.docilealligator.infinityforreddit.utils.JSONUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import okhttp3.ResponseBody;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+
+public class RPANActivity extends AppCompatActivity {
+
+ public static final String EXTRA_RPAN_BROADCAST_FULLNAME_OR_ID = "ERBFOI";
+
+ @BindView(R.id.coordinator_layout_rpan_activity)
+ CoordinatorLayout coordinatorLayout;
+ @BindView(R.id.view_pager_2_rpan_activity)
+ ViewPager2 viewPager2;
+ @BindView(R.id.progress_bar_rpan_activity)
+ ProgressBar progressBar;
+ @Inject
+ @Named("strapi")
+ Retrofit strapiRetrofit;
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
+ @State
+ ArrayList<RPANBroadcast> rpanBroadcasts;
+ @State
+ String nextCursor;
+ private SectionsPagerAdapter sectionsPagerAdapter;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ ((Infinity) getApplication()).getAppComponent().inject(this);
+
+ super.onCreate(savedInstanceState);
+
+ getTheme().applyStyle(R.style.Theme_Normal, true);
+
+ getTheme().applyStyle(FontStyle.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.FONT_SIZE_KEY, FontStyle.Normal.name())).getResId(), true);
+
+ getTheme().applyStyle(TitleFontStyle.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.TITLE_FONT_SIZE_KEY, TitleFontStyle.Normal.name())).getResId(), true);
+
+ getTheme().applyStyle(ContentFontStyle.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.CONTENT_FONT_SIZE_KEY, ContentFontStyle.Normal.name())).getResId(), true);
+
+ getTheme().applyStyle(FontFamily.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.FONT_FAMILY_KEY, FontFamily.Default.name())).getResId(), true);
+
+ getTheme().applyStyle(TitleFontFamily.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.TITLE_FONT_FAMILY_KEY, TitleFontFamily.Default.name())).getResId(), true);
+
+ getTheme().applyStyle(ContentFontFamily.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.CONTENT_FONT_FAMILY_KEY, ContentFontFamily.Default.name())).getResId(), true);
+
+ setContentView(R.layout.activity_rpanactivity);
+
+ setVolumeControlStream(AudioManager.STREAM_MUSIC);
+
+ Bridge.restoreInstanceState(this, savedInstanceState);
+
+ ButterKnife.bind(this);
+
+ ActionBar actionBar = getSupportActionBar();
+ Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
+ actionBar.setHomeAsUpIndicator(upArrow);
+ actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
+
+ if (rpanBroadcasts == null) {
+ loadRPANVideos();
+ } else {
+ initializeViewPager();
+ }
+ }
+
+ private void loadRPANVideos() {
+ String rpanBroadcastFullNameOrId = getIntent().getStringExtra(EXTRA_RPAN_BROADCAST_FULLNAME_OR_ID);
+ if (rpanBroadcastFullNameOrId == null) {
+ strapiRetrofit.create(Strapi.class).getAllBroadcasts().enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ progressBar.setVisibility(View.GONE);
+ if (response.isSuccessful()) {
+ parseRPANBroadcasts(response.body());
+ } else {
+ try {
+ ResponseBody responseBody = response.errorBody();
+ if (responseBody != null) {
+ JSONObject errorObject = new JSONObject(responseBody.string());
+ String errorMessage = errorObject.getString(JSONUtils.DATA_KEY);
+ if (!errorMessage.isEmpty() && !errorMessage.equals("null")) {
+ Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ } else {
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ } catch (IOException | JSONException e) {
+ e.printStackTrace();
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+ progressBar.setVisibility(View.GONE);
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ });
+ } else {
+ strapiRetrofit.create(Strapi.class).getRPANBroadcast(rpanBroadcastFullNameOrId).enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ progressBar.setVisibility(View.GONE);
+ if (response.isSuccessful()) {
+ Handler handler = new Handler();
+ mExecutor.execute(() -> {
+ try {
+ rpanBroadcasts = new ArrayList<>();
+ rpanBroadcasts.add(parseSingleRPANBroadcast(new JSONObject(response.body()).getJSONObject(JSONUtils.DATA_KEY)));
+ handler.post(() -> initializeViewPager());
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(() -> Toast.makeText(RPANActivity.this,
+ R.string.parse_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show());
+ }
+ });
+ } else {
+ try {
+ ResponseBody responseBody = response.errorBody();
+ if (responseBody != null) {
+ JSONObject errorObject = new JSONObject(responseBody.string());
+ String errorMessage = errorObject.getString(JSONUtils.DATA_KEY);
+ if (!errorMessage.isEmpty() && !errorMessage.equals("null")) {
+ Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ } else {
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ } catch (IOException | JSONException e) {
+ e.printStackTrace();
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+ progressBar.setVisibility(View.GONE);
+ Toast.makeText(RPANActivity.this,
+ R.string.load_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show();
+ }
+ });
+ }
+ }
+
+ private void parseRPANBroadcasts(String response) {
+ Handler handler = new Handler();
+ mExecutor.execute(() -> {
+ try {
+ ArrayList<RPANBroadcast> rpanBroadcasts = new ArrayList<>();
+ JSONObject responseObject = new JSONObject(response);
+ String nextCursor = responseObject.getString(JSONUtils.NEXT_CURSOR_KEY);
+
+ JSONArray dataArray = responseObject.getJSONArray(JSONUtils.DATA_KEY);
+ for (int i = 0; i < dataArray.length(); i++) {
+ try {
+ JSONObject singleData = dataArray.getJSONObject(i);
+ rpanBroadcasts.add(parseSingleRPANBroadcast(singleData));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ handler.post(() -> {
+ RPANActivity.this.rpanBroadcasts = rpanBroadcasts;
+ RPANActivity.this.nextCursor = nextCursor;
+
+ initializeViewPager();
+ });
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(() -> Toast.makeText(RPANActivity.this,
+ R.string.parse_rpan_broadcasts_failed, Toast.LENGTH_SHORT).show());
+ }
+ });
+ }
+
+ private RPANBroadcast parseSingleRPANBroadcast(JSONObject singleData) throws JSONException {
+ JSONObject rpanPostObject = singleData.getJSONObject(JSONUtils.POST_KEY);
+ RPANBroadcast.RPANPost rpanPost = new RPANBroadcast.RPANPost(
+ rpanPostObject.getString(JSONUtils.ID_KEY),
+ rpanPostObject.getString(JSONUtils.TITLE_KEY),
+ rpanPostObject.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.NAME_KEY),
+ rpanPostObject.getJSONObject(JSONUtils.SUBREDDIT_KEY).getJSONObject(JSONUtils.STYLES_KEY).getString(JSONUtils.ICON_KEY),
+ rpanPostObject.getJSONObject(JSONUtils.AUTHOR_INFO_KEY).getString(JSONUtils.NAME_KEY),
+ rpanPostObject.getInt(JSONUtils.SCORE_KEY),
+ rpanPostObject.getString(JSONUtils.VOTE_STATE_KEY),
+ rpanPostObject.getDouble(JSONUtils.UPVOTE_RATIO_CAMEL_CASE_KEY),
+ rpanPostObject.getString(JSONUtils.PERMALINK_KEY),
+ rpanPostObject.getJSONObject(JSONUtils.OUTBOUND_LINK_KEY).getString(JSONUtils.URL_KEY),
+ rpanPostObject.getBoolean(JSONUtils.IS_NSFW_KEY),
+ rpanPostObject.getBoolean(JSONUtils.IS_LOCKED_KEY),
+ rpanPostObject.getBoolean(JSONUtils.IS_ARCHIVED_KEY),
+ rpanPostObject.getBoolean(JSONUtils.IS_SPOILER),
+ rpanPostObject.getString(JSONUtils.SUGGESTED_COMMENT_SORT_CAMEL_CASE_KEY),
+ rpanPostObject.getString(JSONUtils.LIVE_COMMENTS_WEBSOCKET_KEY)
+ );
+
+ JSONObject rpanStreamObject = singleData.getJSONObject(JSONUtils.STREAM_KEY);
+ RPANBroadcast.RPANStream rpanStream = new RPANBroadcast.RPANStream(
+ rpanStreamObject.getString(JSONUtils.STREAM_ID_KEY),
+ rpanStreamObject.getString(JSONUtils.HLS_URL_KEY),
+ rpanStreamObject.getString(JSONUtils.THUMBNAIL_KEY),
+ rpanStreamObject.getInt(JSONUtils.WIDTH_KEY),
+ rpanStreamObject.getInt(JSONUtils.HEIGHT_KEY),
+ rpanStreamObject.getLong(JSONUtils.PUBLISH_AT_KEY),
+ rpanStreamObject.getString(JSONUtils.STATE_KEY)
+ );
+
+ return new RPANBroadcast(
+ singleData.getInt(JSONUtils.UPVOTES_KEY),
+ singleData.getInt(JSONUtils.DOWNVOTES_KEY),
+ singleData.getInt(JSONUtils.UNIQUE_WATCHERS_KEY),
+ singleData.getInt(JSONUtils.CONTINUOUS_WATCHERS_KEY),
+ singleData.getInt(JSONUtils.TOTAL_CONTINUOUS_WATCHERS_KEY),
+ singleData.getBoolean(JSONUtils.CHAT_DISABLED_KEY),
+ singleData.getDouble(JSONUtils.BROADCAST_TIME_KEY),
+ singleData.getDouble(JSONUtils.ESTIMATED_REMAINING_TIME_KEY),
+ rpanPost,
+ rpanStream
+ );
+ }
+
+ private void initializeViewPager() {
+ sectionsPagerAdapter = new SectionsPagerAdapter(this);
+ viewPager2.setAdapter(sectionsPagerAdapter);
+ viewPager2.setOffscreenPageLimit(3);
+ fixViewPager2Sensitivity(viewPager2);
+ }
+
+ private void fixViewPager2Sensitivity(ViewPager2 viewPager2) {
+ try {
+ Field recyclerViewField = ViewPager2.class.getDeclaredField("mRecyclerView");
+ recyclerViewField.setAccessible(true);
+
+ RecyclerView recyclerView = (RecyclerView) recyclerViewField.get(viewPager2);
+
+ Field touchSlopField = RecyclerView.class.getDeclaredField("mTouchSlop");
+ touchSlopField.setAccessible(true);
+
+ Object touchSlopBox = touchSlopField.get(recyclerView);
+ if (touchSlopBox != null) {
+ int touchSlop = (int) touchSlopBox;
+ touchSlopField.set(recyclerView, touchSlop * 4);
+ }
+ } catch (NoSuchFieldException | IllegalAccessException ignore) {}
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.rpan_activity, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(@NonNull MenuItem item) {
+ if (item.getItemId() == android.R.id.home) {
+ finish();
+ return true;
+ } else if (item.getItemId() == R.id.action_share_rpan_link_rpan_activity) {
+ if (rpanBroadcasts != null) {
+ int position = viewPager2.getCurrentItem();
+ if (position >= 0 && position < rpanBroadcasts.size()) {
+ shareLink(rpanBroadcasts.get(position).rpanPost.rpanUrl);
+ return true;
+ }
+ }
+ } else if (item.getItemId() == R.id.action_share_post_link_rpan_activity) {
+ if (rpanBroadcasts != null) {
+ int position = viewPager2.getCurrentItem();
+ if (position >= 0 && position < rpanBroadcasts.size()) {
+ shareLink(rpanBroadcasts.get(position).rpanPost.postPermalink);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ EventBus.getDefault().unregister(this);
+ }
+
+ private void shareLink(String link) {
+ try {
+ Intent intent = new Intent(Intent.ACTION_SEND);
+ intent.setType("text/plain");
+ intent.putExtra(Intent.EXTRA_TEXT, link);
+ startActivity(Intent.createChooser(intent, getString(R.string.share)));
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.no_activity_found_for_share, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ private class SectionsPagerAdapter extends FragmentStateAdapter {
+
+ public SectionsPagerAdapter(FragmentActivity fa) {
+ super(fa);
+ }
+
+ @NonNull
+ @Override
+ public Fragment createFragment(int position) {
+ ViewRPANBroadcastFragment fragment = new ViewRPANBroadcastFragment();
+ Bundle bundle = new Bundle();
+ bundle.putParcelable(ViewRPANBroadcastFragment.EXTRA_RPAN_BROADCAST, rpanBroadcasts.get(position));
+ fragment.setArguments(bundle);
+ return fragment;
+ }
+
+ @Nullable
+ private Fragment getCurrentFragment() {
+ if (viewPager2 == null || getSupportFragmentManager() == null) {
+ return null;
+ }
+ return getSupportFragmentManager().findFragmentByTag("f" + viewPager2.getCurrentItem());
+ }
+
+ @Override
+ public int getItemCount() {
+ return rpanBroadcasts == null ? 0 : rpanBroadcasts.size();
+ }
+ }
+} \ No newline at end of file
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 0c88bcb4..4b8f9b38 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ReportActivity.java
@@ -3,6 +3,7 @@ package ml.docilealligator.infinityforreddit.activities;
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.widget.Toast;
@@ -10,7 +11,6 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -18,6 +18,7 @@ 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;
@@ -67,6 +68,8 @@ public class ReportActivity extends BaseActivity {
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
private String mAccessToken;
private String mFullname;
private String mSubredditName;
@@ -113,11 +116,10 @@ public class ReportActivity extends BaseActivity {
} else {
mAdapter = new ReportReasonRecyclerViewAdapter(mCustomThemeWrapper, ReportReason.getGeneralReasons(this));
}
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
if (rulesReasons == null) {
- FetchRules.fetchRules(mRetrofit, mSubredditName, new FetchRules.FetchRulesListener() {
+ FetchRules.fetchRules(mExecutor, new Handler(), mRetrofit, mSubredditName, new FetchRules.FetchRulesListener() {
@Override
public void success(ArrayList<Rule> rules) {
mAdapter.setRules(ReportReason.convertRulesToReasons(rules));
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RulesActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RulesActivity.java
index 0e3021e9..ca687cf1 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RulesActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/RulesActivity.java
@@ -4,6 +4,7 @@ import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
+import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
@@ -14,7 +15,6 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -24,6 +24,7 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
+import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
@@ -64,6 +65,8 @@ public class RulesActivity extends BaseActivity {
SharedPreferences mSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
private String mSubredditName;
private RulesRecyclerViewAdapter mAdapter;
@@ -115,13 +118,10 @@ public class RulesActivity extends BaseActivity {
mSubredditName = getIntent().getExtras().getString(EXTRA_SUBREDDIT_NAME);
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new RulesRecyclerViewAdapter(this, mCustomThemeWrapper);
recyclerView.setAdapter(mAdapter);
- //fetchRules();
-
- FetchRules.fetchRules(mRetrofit, mSubredditName, new FetchRules.FetchRulesListener() {
+ FetchRules.fetchRules(mExecutor, new Handler(), mRetrofit, mSubredditName, new FetchRules.FetchRulesListener() {
@Override
public void success(ArrayList<Rule> rules) {
progressBar.setVisibility(View.GONE);
@@ -159,46 +159,6 @@ public class RulesActivity extends BaseActivity {
errorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
}
- /*private void fetchRules() {
- progressBar.setVisibility(View.VISIBLE);
- errorTextView.setVisibility(View.GONE);
-
- RedditAPI api = mRetrofit.create(RedditAPI.class);
- Call<String> rulesCall = api.getRules(mSubredditName);
- rulesCall.enqueue(new Callback<String>() {
- @Override
- public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
- if (response.isSuccessful()) {
- new ParseRulesAsyncTask(response.body(), new ParseRulesAsyncTask.ParseRulesAsyncTaskListener() {
- @Override
- public void parseSuccessful(ArrayList<Rule> rules) {
- progressBar.setVisibility(View.GONE);
- if (rules == null || rules.size() == 0) {
- errorTextView.setVisibility(View.VISIBLE);
- errorTextView.setText(R.string.no_rule);
- errorTextView.setOnClickListener(view -> {
- });
- }
- mAdapter.changeDataset(rules);
- }
-
- @Override
- public void parseFailed() {
- displayError();
- }
- }).execute();
- } else {
- displayError();
- }
- }
-
- @Override
- public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
- displayError();
- }
- });
- }*/
-
private void displayError() {
progressBar.setVisibility(View.GONE);
errorTextView.setVisibility(View.VISIBLE);
@@ -206,7 +166,7 @@ public class RulesActivity extends BaseActivity {
errorTextView.setOnClickListener(view -> {
progressBar.setVisibility(View.VISIBLE);
errorTextView.setVisibility(View.GONE);
- FetchRules.fetchRules(mRetrofit, mSubredditName, new FetchRules.FetchRulesListener() {
+ FetchRules.fetchRules(mExecutor, new Handler(), mRetrofit, mSubredditName, new FetchRules.FetchRulesListener() {
@Override
public void success(ArrayList<Rule> rules) {
progressBar.setVisibility(View.GONE);
@@ -247,49 +207,4 @@ public class RulesActivity extends BaseActivity {
public void onAccountSwitchEvent(SwitchAccountEvent event) {
finish();
}
-
- /*private static class ParseRulesAsyncTask extends AsyncTask<Void, ArrayList<Rule>, ArrayList<Rule>> {
- private String response;
- private ParseRulesAsyncTaskListener parseRulesAsyncTaskListener;
-
- ParseRulesAsyncTask(String response, ParseRulesAsyncTaskListener parseRulesAsyncTaskListener) {
- this.response = response;
- this.parseRulesAsyncTaskListener = parseRulesAsyncTaskListener;
- }
-
- @Override
- protected ArrayList<Rule> doInBackground(Void... voids) {
- try {
- JSONArray rulesArray = new JSONObject(response).getJSONArray(JSONUtils.RULES_KEY);
- ArrayList<Rule> rules = new ArrayList<>();
- for (int i = 0; i < rulesArray.length(); i++) {
- String shortName = rulesArray.getJSONObject(i).getString(JSONUtils.SHORT_NAME_KEY);
- String description = null;
- if (rulesArray.getJSONObject(i).has(JSONUtils.DESCRIPTION_KEY)) {
- description = Utils.modifyMarkdown(rulesArray.getJSONObject(i).getString(JSONUtils.DESCRIPTION_KEY));
- }
- rules.add(new Rule(shortName, description));
- }
- return rules;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(ArrayList<Rule> rules) {
- if (rules != null) {
- parseRulesAsyncTaskListener.parseSuccessful(rules);
- } else {
- parseRulesAsyncTaskListener.parseFailed();
- }
- }
-
- interface ParseRulesAsyncTaskListener {
- void parseSuccessful(ArrayList<Rule> rules);
-
- void parseFailed();
- }
- }*/
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchActivity.java
index cd6c2c5c..66369953 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchActivity.java
@@ -18,7 +18,6 @@ import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.ferfalk.simplesearchview.SimpleSearchView;
@@ -28,6 +27,8 @@ import com.r0adkll.slidr.Slidr;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
+import java.util.ArrayList;
+
import javax.inject.Inject;
import javax.inject.Named;
@@ -37,12 +38,21 @@ import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.adapters.SearchActivityRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.adapters.SubredditAutocompleteRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.recentsearchquery.DeleteRecentSearchQuery;
import ml.docilealligator.infinityforreddit.recentsearchquery.RecentSearchQuery;
import ml.docilealligator.infinityforreddit.recentsearchquery.RecentSearchQueryViewModel;
+import ml.docilealligator.infinityforreddit.subreddit.ParseSubredditData;
+import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
public class SearchActivity extends BaseActivity {
@@ -83,11 +93,12 @@ public class SearchActivity extends BaseActivity {
TextView subredditNameTextView;
@BindView(R.id.divider_search_activity)
View divider;
- @BindView(R.id.recent_summary_text_view_search_activity)
- TextView recentSummaryTextView;
@BindView(R.id.recycler_view_search_activity)
RecyclerView recyclerView;
@Inject
+ @Named("oauth")
+ Retrofit mOauthRetrofit;
+ @Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
@@ -96,14 +107,20 @@ public class SearchActivity extends BaseActivity {
@Named("current_account")
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
+ @Named("nsfw_and_spoiler")
+ SharedPreferences mNsfwAndSpoilerSharedPreferences;
+ @Inject
CustomThemeWrapper mCustomThemeWrapper;
private String mAccountName;
+ private String mAccessToken;
private String query;
private String subredditName;
private boolean subredditIsUser;
private boolean searchOnlySubreddits;
private boolean searchOnlyUsers;
private SearchActivityRecyclerViewAdapter adapter;
+ private SubredditAutocompleteRecyclerViewAdapter subredditAutocompleteRecyclerViewAdapter;
+ private Call<String> subredditAutocompleteCall;
RecentSearchQueryViewModel mRecentSearchQueryViewModel;
@Override
@@ -159,6 +176,31 @@ public class SearchActivity extends BaseActivity {
}
});
+ mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
+ mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
+ boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, false);
+
+ subredditAutocompleteRecyclerViewAdapter = new SubredditAutocompleteRecyclerViewAdapter(this,
+ mCustomThemeWrapper, subredditData -> {
+ if (searchOnlySubreddits) {
+ Intent returnIntent = new Intent();
+ if (getIntent().getBooleanExtra(EXTRA_IS_MULTI_SELECTION, false)) {
+ ArrayList<String> subredditNameList = new ArrayList<>();
+ subredditNameList.add(subredditData.getName());
+ returnIntent.putStringArrayListExtra(RETURN_EXTRA_SELECTED_SUBREDDIT_NAMES, subredditNameList);
+ } else {
+ returnIntent.putExtra(EXTRA_RETURN_SUBREDDIT_NAME, subredditData.getName());
+ returnIntent.putExtra(EXTRA_RETURN_SUBREDDIT_ICON_URL, subredditData.getIconUrl());
+ }
+ setResult(Activity.RESULT_OK, returnIntent);
+ } else {
+ Intent intent = new Intent(SearchActivity.this, ViewSubredditDetailActivity.class);
+ intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditData.getName());
+ startActivity(intent);
+ }
+ finish();
+ });
+
simpleSearchView.setOnQueryTextListener(new SimpleSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
@@ -168,6 +210,38 @@ public class SearchActivity extends BaseActivity {
@Override
public boolean onQueryTextChange(String newText) {
+ if (!newText.isEmpty()) {
+ if (subredditAutocompleteCall != null) {
+ subredditAutocompleteCall.cancel();
+ }
+ subredditAutocompleteCall = mOauthRetrofit.create(RedditAPI.class).subredditAutocomplete(APIUtils.getOAuthHeader(mAccessToken),
+ newText, nsfw);
+ subredditAutocompleteCall.enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ ParseSubredditData.parseSubredditListingData(response.body(), nsfw, new ParseSubredditData.ParseSubredditListingDataListener() {
+ @Override
+ public void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after) {
+ subredditAutocompleteRecyclerViewAdapter.setSubreddits(subredditData);
+ recyclerView.setAdapter(subredditAutocompleteRecyclerViewAdapter);
+ }
+
+ @Override
+ public void onParseSubredditListingDataFail() {
+
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+
+ }
+ });
+ return true;
+ }
return false;
}
@@ -177,8 +251,6 @@ public class SearchActivity extends BaseActivity {
}
});
- mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
-
if (savedInstanceState != null) {
subredditName = savedInstanceState.getString(SUBREDDIT_NAME_STATE);
subredditIsUser = savedInstanceState.getBoolean(SUBREDDIT_IS_USER_STATE);
@@ -227,7 +299,6 @@ public class SearchActivity extends BaseActivity {
});
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setNestedScrollingEnabled(false);
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
if (mSharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_SEARCH_HISTORY, true)) {
@@ -238,10 +309,8 @@ public class SearchActivity extends BaseActivity {
mRecentSearchQueryViewModel.getAllRecentSearchQueries().observe(this, recentSearchQueries -> {
if (recentSearchQueries != null && !recentSearchQueries.isEmpty()) {
divider.setVisibility(View.VISIBLE);
- recentSummaryTextView.setVisibility(View.VISIBLE);
} else {
divider.setVisibility(View.GONE);
- recentSummaryTextView.setVisibility(View.GONE);
}
adapter.setRecentSearchQueries(recentSearchQueries);
});
@@ -309,7 +378,6 @@ public class SearchActivity extends BaseActivity {
searchInTextView.setTextColor(colorAccent);
subredditNameTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
divider.setBackgroundColor(mCustomThemeWrapper.getDividerColor());
- recentSummaryTextView.setTextColor(colorAccent);
}
@Override
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 5ca8a554..f2096b97 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SearchResultActivity.java
@@ -5,12 +5,15 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
+import android.text.Editable;
+import android.text.TextWatcher;
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.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.NonNull;
@@ -20,6 +23,7 @@ import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
+import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
@@ -35,6 +39,8 @@ import com.r0adkll.slidr.model.SlidrInterface;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
+import java.util.ArrayList;
+
import javax.inject.Inject;
import javax.inject.Named;
@@ -48,6 +54,8 @@ import ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterfac
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback;
+import ml.docilealligator.infinityforreddit.adapters.SubredditAutocompleteRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostLayoutBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostTypeBottomSheetFragment;
@@ -63,14 +71,23 @@ import ml.docilealligator.infinityforreddit.fragments.SubredditListingFragment;
import ml.docilealligator.infinityforreddit.fragments.UserListingFragment;
import ml.docilealligator.infinityforreddit.post.PostDataSource;
import ml.docilealligator.infinityforreddit.recentsearchquery.InsertRecentSearchQuery;
+import ml.docilealligator.infinityforreddit.subreddit.ParseSubredditData;
+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;
public class SearchResultActivity extends BaseActivity implements SortTypeSelectionCallback,
PostLayoutBottomSheetFragment.PostLayoutSelectionCallback, ActivityToolbarInterface,
FABMoreOptionsBottomSheetFragment.FABOptionSelectionCallback, RandomBottomSheetFragment.RandomOptionSelectionCallback,
PostTypeBottomSheetFragment.PostTypeSelectionCallback, RecyclerViewContentScrollingInterface {
- static final String EXTRA_QUERY = "QK";
+
+ static final String EXTRA_QUERY = "EQ";
+ static final String EXTRA_TRENDING_SOURCE = "ETS";
static final String EXTRA_SUBREDDIT_NAME = "ESN";
private static final String INSERT_SEARCH_QUERY_SUCCESS_STATE = "ISQSS";
@@ -87,6 +104,9 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
@BindView(R.id.fab_search_result_activity)
FloatingActionButton fab;
@Inject
+ @Named("oauth")
+ Retrofit mOauthRetrofit;
+ @Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
@@ -108,6 +128,7 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ private Call<String> subredditAutocompleteCall;
private String mAccessToken;
private String mAccountName;
private String mQuery;
@@ -543,11 +564,79 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
private void goToSubreddit() {
View rootView = getLayoutInflater().inflate(R.layout.dialog_go_to_thing_edit_text, coordinatorLayout, false);
TextInputEditText thingEditText = rootView.findViewById(R.id.text_input_edit_text_go_to_thing_edit_text);
+ RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_go_to_thing_edit_text);
thingEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+ SubredditAutocompleteRecyclerViewAdapter adapter = new SubredditAutocompleteRecyclerViewAdapter(
+ this, mCustomThemeWrapper, subredditData -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent intent = new Intent(SearchResultActivity.this, ViewSubredditDetailActivity.class);
+ intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditData.getName());
+ startActivity(intent);
+ });
+ recyclerView.setAdapter(adapter);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent subredditIntent = new Intent(this, ViewSubredditDetailActivity.class);
+ subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
+ startActivity(subredditIntent);
+ return true;
+ }
+ return false;
+ });
+
+ boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, false);
+ thingEditText.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ if (subredditAutocompleteCall != null) {
+ subredditAutocompleteCall.cancel();
+ }
+ subredditAutocompleteCall = mOauthRetrofit.create(RedditAPI.class).subredditAutocomplete(APIUtils.getOAuthHeader(mAccessToken),
+ editable.toString(), nsfw);
+ subredditAutocompleteCall.enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ ParseSubredditData.parseSubredditListingData(response.body(), nsfw, new ParseSubredditData.ParseSubredditListingDataListener() {
+ @Override
+ public void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after) {
+ adapter.setSubreddits(subredditData);
+ }
+
+ @Override
+ public void onParseSubredditListingDataFail() {
+
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+
+ }
+ });
+ }
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_subreddit)
.setView(rootView)
@@ -560,7 +649,11 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
startActivity(subredditIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -577,6 +670,18 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent userIntent = new Intent(this, ViewUserDetailActivity.class);
+ userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
+ startActivity(userIntent);
+ return true;
+ }
+ return false;
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_user)
.setView(rootView)
@@ -589,7 +694,11 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
startActivity(userIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -625,6 +734,10 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
case PostTypeBottomSheetFragment.TYPE_VIDEO:
intent = new Intent(this, PostVideoActivity.class);
startActivity(intent);
+ break;
+ case PostTypeBottomSheetFragment.TYPE_GALLERY:
+ intent = new Intent(this, PostGalleryActivity.class);
+ startActivity(intent);
}
}
@@ -661,6 +774,7 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_SEARCH);
bundle.putString(PostFragment.EXTRA_NAME, mSubredditName);
bundle.putString(PostFragment.EXTRA_QUERY, mQuery);
+ bundle.putString(PostFragment.EXTRA_TRENDING_SOURCE, getIntent().getStringExtra(EXTRA_TRENDING_SOURCE));
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName);
mFragment.setArguments(bundle);
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 84db322c..f9a7460e 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectUserFlairActivity.java
@@ -13,7 +13,6 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -36,6 +35,7 @@ import ml.docilealligator.infinityforreddit.SelectUserFlair;
import ml.docilealligator.infinityforreddit.UserFlair;
import ml.docilealligator.infinityforreddit.adapters.UserFlairRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
@@ -63,7 +63,7 @@ public class SelectUserFlairActivity extends BaseActivity implements ActivityToo
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
@@ -170,7 +170,7 @@ public class SelectUserFlairActivity extends BaseActivity implements ActivityToo
.show();
}
});
- mLinearLayoutManager = new LinearLayoutManager(SelectUserFlairActivity.this);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(SelectUserFlairActivity.this);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(mAdapter);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectedSubredditsAndUsersActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectedSubredditsAndUsersActivity.java
index cfc30dcf..38502fd4 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectedSubredditsAndUsersActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SelectedSubredditsAndUsersActivity.java
@@ -11,7 +11,6 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
@@ -31,6 +30,7 @@ import ml.docilealligator.infinityforreddit.bottomsheetfragments.SelectSubreddit
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
public class SelectedSubredditsAndUsersActivity extends BaseActivity implements ActivityToolbarInterface {
@@ -56,7 +56,7 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
SharedPreferences mSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
- private LinearLayoutManager linearLayoutManager;
+ private LinearLayoutManagerBugFixed linearLayoutManager;
private SelectedSubredditsRecyclerViewAdapter adapter;
private ArrayList<String> subreddits;
@@ -88,7 +88,7 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
}
adapter = new SelectedSubredditsRecyclerViewAdapter(mCustomThemeWrapper, subreddits);
- linearLayoutManager = new LinearLayoutManager(this);
+ linearLayoutManager = new LinearLayoutManagerBugFixed(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
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 7e97c0a6..d6c5e68f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubmitCrosspostActivity.java
@@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit.activities;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
@@ -12,10 +11,10 @@ import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
-import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
+import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
@@ -32,8 +31,10 @@ import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.google.android.material.appbar.AppBarLayout;
+import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.switchmaterial.SwitchMaterial;
import com.libRG.CustomTextView;
import org.greenrobot.eventbus.EventBus;
@@ -91,7 +92,7 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
@BindView(R.id.subreddit_name_text_view_submit_crosspost_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_submit_crosspost_activity)
- Button rulesButton;
+ MaterialButton rulesButton;
@BindView(R.id.divider_1_submit_crosspost_activity)
View divider1;
@BindView(R.id.flair_custom_text_view_submit_crosspost_activity)
@@ -102,10 +103,18 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
CustomTextView nsfwTextView;
@BindView(R.id.divider_2_submit_crosspost_activity)
View divider2;
- @BindView(R.id.post_title_edit_text_submit_crosspost_activity)
- EditText titleEditText;
+ @BindView(R.id.receive_post_reply_notifications_linear_layout_submit_crosspost_activity)
+ LinearLayout receivePostReplyNotificationsLinearLayout;
+ @BindView(R.id.receive_post_reply_notifications_text_view_submit_crosspost_activity)
+ TextView receivePostReplyNotificationsTextView;
+ @BindView(R.id.receive_post_reply_notifications_switch_material_submit_crosspost_activity)
+ SwitchMaterial receivePostReplyNotificationsSwitchMaterial;
@BindView(R.id.divider_3_submit_crosspost_activity)
View divider3;
+ @BindView(R.id.post_title_edit_text_submit_crosspost_activity)
+ EditText titleEditText;
+ @BindView(R.id.divider_4_submit_crosspost_activity)
+ View divider4;
@BindView(R.id.post_content_text_view_submit_crosspost_activity)
TextView contentTextView;
@BindView(R.id.frame_layout_submit_crosspost_activity)
@@ -360,6 +369,10 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
isNSFW = false;
}
});
+
+ receivePostReplyNotificationsLinearLayout.setOnClickListener(view -> {
+ receivePostReplyNotificationsSwitchMaterial.performClick();
+ });
}
@Nullable
@@ -389,12 +402,14 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
subredditNameTextView.setTextColor(secondaryTextColor);
rulesButton.setTextColor(mCustomThemeWrapper.getButtonTextColor());
- rulesButton.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimaryLightTheme()));
+ rulesButton.setBackgroundColor(mCustomThemeWrapper.getColorPrimaryLightTheme());
+ primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ receivePostReplyNotificationsTextView.setTextColor(primaryTextColor);
int dividerColor = mCustomThemeWrapper.getDividerColor();
divider1.setBackgroundColor(dividerColor);
divider2.setBackgroundColor(dividerColor);
divider3.setBackgroundColor(dividerColor);
- primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
+ divider4.setBackgroundColor(dividerColor);
flairBackgroundColor = mCustomThemeWrapper.getFlairBackgroundColor();
flairTextColor = mCustomThemeWrapper.getFlairTextColor();
spoilerBackgroundColor = mCustomThemeWrapper.getSpoilerBackgroundColor();
@@ -457,61 +472,62 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
- switch (item.getItemId()) {
- case android.R.id.home:
- if (isPosting) {
- promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
- return true;
- } else {
- if (!titleEditText.getText().toString().equals("")) {
- promptAlertDialog(R.string.discard, R.string.discard_detail);
- return true;
- }
- }
- finish();
+ int itemId = item.getItemId();
+ if (itemId == android.R.id.home) {
+ if (isPosting) {
+ promptAlertDialog(R.string.exit_when_submit, R.string.exit_when_submit_post_detail);
return true;
- case R.id.action_send_submit_crosspost_activity:
- if (!subredditSelected) {
- Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
- return true;
- }
-
- if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
- Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
+ } else {
+ if (!titleEditText.getText().toString().equals("")) {
+ promptAlertDialog(R.string.discard, R.string.discard_detail);
return true;
}
+ }
+ finish();
+ return true;
+ } else if (itemId == R.id.action_send_submit_crosspost_activity) {
+ if (!subredditSelected) {
+ Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- isPosting = true;
+ if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
+ Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
+ return true;
+ }
- item.setEnabled(false);
- item.getIcon().setAlpha(130);
+ isPosting = true;
- mPostingSnackbar.show();
+ item.setEnabled(false);
+ item.getIcon().setAlpha(130);
- String subredditName;
- if (subredditIsUser) {
- subredditName = "u_" + subredditNameTextView.getText().toString();
- } else {
- subredditName = subredditNameTextView.getText().toString();
- }
+ mPostingSnackbar.show();
- Intent intent = new Intent(this, SubmitPostService.class);
- intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
- intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
- intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
- if (post.isCrosspost()) {
- intent.putExtra(SubmitPostService.EXTRA_CONTENT, "t3_" + post.getCrosspostParentId());
- } else {
- intent.putExtra(SubmitPostService.EXTRA_CONTENT, post.getFullName());
- }
- intent.putExtra(SubmitPostService.EXTRA_KIND, APIUtils.KIND_CROSSPOST);
- intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
- intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
- intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
- intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_CROSSPOST);
- ContextCompat.startForegroundService(this, intent);
+ String subredditName;
+ if (subredditIsUser) {
+ subredditName = "u_" + subredditNameTextView.getText().toString();
+ } else {
+ subredditName = subredditNameTextView.getText().toString();
+ }
- return true;
+ Intent intent = new Intent(this, SubmitPostService.class);
+ intent.putExtra(SubmitPostService.EXTRA_ACCESS_TOKEN, mAccessToken);
+ intent.putExtra(SubmitPostService.EXTRA_SUBREDDIT_NAME, subredditName);
+ intent.putExtra(SubmitPostService.EXTRA_TITLE, titleEditText.getText().toString());
+ if (post.isCrosspost()) {
+ intent.putExtra(SubmitPostService.EXTRA_CONTENT, "t3_" + post.getCrosspostParentId());
+ } else {
+ intent.putExtra(SubmitPostService.EXTRA_CONTENT, post.getFullName());
+ }
+ intent.putExtra(SubmitPostService.EXTRA_KIND, APIUtils.KIND_CROSSPOST);
+ intent.putExtra(SubmitPostService.EXTRA_FLAIR, flair);
+ intent.putExtra(SubmitPostService.EXTRA_IS_SPOILER, isSpoiler);
+ intent.putExtra(SubmitPostService.EXTRA_IS_NSFW, isNSFW);
+ intent.putExtra(SubmitPostService.EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, receivePostReplyNotificationsSwitchMaterial.isChecked());
+ intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_CROSSPOST);
+ ContextCompat.startForegroundService(this, intent);
+
+ return true;
}
return false;
@@ -588,7 +604,7 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
}
@Subscribe
- public void onSubmitTextPostEvent(SubmitCrosspostEvent submitCrosspostEvent) {
+ public void onSubmitCrosspostEvent(SubmitCrosspostEvent submitCrosspostEvent) {
isPosting = false;
mPostingSnackbar.dismiss();
if (submitCrosspostEvent.postSuccess) {
@@ -597,8 +613,8 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
startActivity(intent);
finish();
} else {
- mMenu.findItem(R.id.action_send_post_text_activity).setEnabled(true);
- mMenu.findItem(R.id.action_send_post_text_activity).getIcon().setAlpha(255);
+ mMenu.findItem(R.id.action_send_submit_crosspost_activity).setEnabled(true);
+ mMenu.findItem(R.id.action_send_submit_crosspost_activity).getIcon().setAlpha(255);
if (submitCrosspostEvent.errorMessage == null || submitCrosspostEvent.errorMessage.equals("")) {
Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
} else {
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 69b83579..f2d00212 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubredditMultiselectionActivity.java
@@ -19,7 +19,6 @@ import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -41,6 +40,7 @@ import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.adapters.SubredditMultiselectionRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
@@ -83,7 +83,7 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act
public SubscribedSubredditViewModel mSubscribedSubredditViewModel;
private String mAccessToken;
private String mAccountName;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private SubredditMultiselectionRecyclerViewAdapter mAdapter;
private RequestManager mGlide;
@@ -142,7 +142,7 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act
}
private void bindView() {
- mLinearLayoutManager = new LinearLayoutManager(this);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mAdapter = new SubredditMultiselectionRecyclerViewAdapter(this, mCustomThemeWrapper);
mRecyclerView.setAdapter(mAdapter);
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 e5b2e225..0d33b2a8 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/SubscribedThingListingActivity.java
@@ -47,6 +47,7 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.asynctasks.InsertMultireddit;
import ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.ViewPagerBugFixed;
import ml.docilealligator.infinityforreddit.events.GoBackToMainPageEvent;
import ml.docilealligator.infinityforreddit.events.RefreshMultiRedditsEvent;
import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
@@ -77,7 +78,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
@BindView(R.id.tab_layout_subscribed_thing_listing_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_subscribed_thing_listing_activity)
- ViewPager viewPager;
+ ViewPagerBugFixed viewPager;
@BindView(R.id.fab_subscribed_thing_listing_activity)
FloatingActionButton fab;
@Inject
@@ -211,7 +212,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
tabLayout.setupWithViewPager(viewPager);
if (showMultiReddits) {
- viewPager.setCurrentItem(2);
+ viewPager.setCurrentItem(2, false);
}
loadSubscriptions(false);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/TrendingActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/TrendingActivity.java
new file mode 100644
index 00000000..ca1a5887
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/TrendingActivity.java
@@ -0,0 +1,328 @@
+package ml.docilealligator.infinityforreddit.activities;
+
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.DisplayMetrics;
+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 androidx.annotation.NonNull;
+import androidx.appcompat.widget.Toolbar;
+import androidx.coordinatorlayout.widget.CoordinatorLayout;
+import androidx.recyclerview.widget.RecyclerView;
+import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
+
+import com.bumptech.glide.Glide;
+import com.google.android.material.appbar.AppBarLayout;
+import com.google.android.material.appbar.CollapsingToolbarLayout;
+import com.r0adkll.slidr.Slidr;
+
+import org.greenrobot.eventbus.EventBus;
+import org.greenrobot.eventbus.Subscribe;
+import org.json.JSONArray;
+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;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.TrendingSearch;
+import ml.docilealligator.infinityforreddit.adapters.TrendingSearchRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
+import ml.docilealligator.infinityforreddit.post.ParsePost;
+import ml.docilealligator.infinityforreddit.post.Post;
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
+import ml.docilealligator.infinityforreddit.utils.JSONUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import ml.docilealligator.infinityforreddit.utils.Utils;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+
+public class TrendingActivity extends BaseActivity {
+
+ private static final String TRENDING_SEARCHES_STATE = "TSS";
+
+ @BindView(R.id.coordinator_layout_trending_activity)
+ CoordinatorLayout coordinatorLayout;
+ @BindView(R.id.collapsing_toolbar_layout_trending_activity)
+ CollapsingToolbarLayout collapsingToolbarLayout;
+ @BindView(R.id.appbar_layout_trending_activity)
+ AppBarLayout appBarLayout;
+ @BindView(R.id.toolbar_trending_activity)
+ Toolbar toolbar;
+ @BindView(R.id.swipe_refresh_layout_trending_activity)
+ SwipeRefreshLayout swipeRefreshLayout;
+ @BindView(R.id.recycler_view_trending_activity)
+ RecyclerView recyclerView;
+ @BindView(R.id.fetch_trending_search_linear_layout_trending_activity)
+ LinearLayout errorLinearLayout;
+ @BindView(R.id.fetch_trending_search_image_view_trending_activity)
+ ImageView errorImageView;
+ @BindView(R.id.fetch_trending_search_text_view_trending_activity)
+ TextView errorTextView;
+ @Inject
+ @Named("oauth")
+ Retrofit mOauthRetrofit;
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ @Named("post_layout")
+ SharedPreferences mPostLayoutSharedPreferences;
+ @Inject
+ @Named("current_account")
+ SharedPreferences mCurrentAccountSharedPreferences;
+ @Inject
+ CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
+ private String mAccessToken;
+ private String mAccountName;
+ private boolean isRefreshing = false;
+ private ArrayList<TrendingSearch> trendingSearches;
+ private TrendingSearchRecyclerViewAdapter adapter;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ ((Infinity) getApplication()).getAppComponent().inject(this);
+
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_trending);
+
+ ButterKnife.bind(this);
+
+ EventBus.getDefault().register(this);
+
+ applyCustomTheme();
+
+ if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) {
+ Slidr.attach(this);
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ Window window = getWindow();
+
+ if (isChangeStatusBarIconColor()) {
+ addOnOffsetChangedListener(appBarLayout);
+ }
+
+ if (isImmersiveInterface()) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ coordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
+ View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
+ View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
+ } else {
+ window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
+ }
+ adjustToolbar(toolbar);
+
+ int navBarResourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
+ if (navBarResourceId > 0) {
+ recyclerView.setPadding(0, 0, 0, recyclerView.getPaddingBottom() + getResources().getDimensionPixelSize(navBarResourceId));
+ }
+ }
+ }
+
+ setSupportActionBar(toolbar);
+ getSupportActionBar().setDisplayHomeAsUpEnabled(true);
+ setToolbarGoToTop(toolbar);
+
+ mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
+ mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
+
+ DisplayMetrics displayMetrics = new DisplayMetrics();
+ getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
+ int windowWidth = displayMetrics.widthPixels;
+
+ String dataSavingModeString = mSharedPreferences.getString(SharedPreferencesUtils.DATA_SAVING_MODE, SharedPreferencesUtils.DATA_SAVING_MODE_OFF);
+ boolean dataSavingMode = false;
+ if (dataSavingModeString.equals(SharedPreferencesUtils.DATA_SAVING_MODE_ALWAYS)) {
+ dataSavingMode = true;
+ } else if (dataSavingModeString.equals(SharedPreferencesUtils.DATA_SAVING_MODE_ONLY_ON_CELLULAR_DATA)) {
+ int networkType = Utils.getConnectedNetwork(this);
+ dataSavingMode = networkType == Utils.NETWORK_TYPE_CELLULAR;
+ }
+ boolean disableImagePreview = mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_IMAGE_PREVIEW, false);
+ adapter = new TrendingSearchRecyclerViewAdapter(this, mCustomThemeWrapper, windowWidth,
+ dataSavingMode, disableImagePreview, new TrendingSearchRecyclerViewAdapter.ItemClickListener() {
+ @Override
+ public void onClick(TrendingSearch trendingSearch) {
+ Intent intent = new Intent(TrendingActivity.this, SearchResultActivity.class);
+ intent.putExtra(SearchResultActivity.EXTRA_QUERY, trendingSearch.queryString);
+ intent.putExtra(SearchResultActivity.EXTRA_TRENDING_SOURCE, "trending");
+ startActivity(intent);
+ }
+ });
+ recyclerView.setAdapter(adapter);
+
+ swipeRefreshLayout.setEnabled(mSharedPreferences.getBoolean(SharedPreferencesUtils.PULL_TO_REFRESH, true));
+ swipeRefreshLayout.setOnRefreshListener(this::fetchTrendingSearches);
+
+ if (savedInstanceState != null) {
+ trendingSearches = savedInstanceState.getParcelableArrayList(TRENDING_SEARCHES_STATE);
+ }
+ if (trendingSearches != null) {
+ adapter.setTrendingSearches(trendingSearches);
+ } else {
+ fetchTrendingSearches();
+ }
+ }
+
+ private void fetchTrendingSearches() {
+ if (isRefreshing) {
+ return;
+ }
+ isRefreshing = true;
+
+ errorLinearLayout.setVisibility(View.GONE);
+ Glide.with(this).clear(errorImageView);
+ swipeRefreshLayout.setRefreshing(true);
+ trendingSearches = null;
+ adapter.setTrendingSearches(null);
+ Handler handler = new Handler();
+ mOauthRetrofit.create(RedditAPI.class).getTrendingSearches(APIUtils.getOAuthHeader(mAccessToken)).enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ mExecutor.execute(() -> {
+ try {
+ JSONArray trendingSearchesArray = new JSONObject(response.body()).getJSONArray(JSONUtils.TRENDING_SEARCHES_KEY);
+ ArrayList<TrendingSearch> trendingSearchList = new ArrayList<>();
+ for (int i = 0; i < trendingSearchesArray.length(); i++) {
+ try {
+ JSONObject trendingSearchObject = trendingSearchesArray.getJSONObject(i);
+ String queryString = trendingSearchObject.getString(JSONUtils.QUERY_STRING_KEY);
+ String displayString = trendingSearchObject.getString(JSONUtils.DISPLAY_STRING_KEY);
+ JSONArray childrenWithOnlyOneChild = trendingSearchObject
+ .getJSONObject(JSONUtils.RESULTS_KEY)
+ .getJSONObject(JSONUtils.DATA_KEY)
+ .getJSONArray(JSONUtils.CHILDREN_KEY);
+ if (childrenWithOnlyOneChild.length() > 0) {
+ Post post = ParsePost.parseBasicData(childrenWithOnlyOneChild.getJSONObject(0)
+ .getJSONObject(JSONUtils.DATA_KEY));
+
+ trendingSearchList.add(new TrendingSearch(queryString, displayString,
+ post.getTitle(), post.getPreviews()));
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ handler.post(() -> {
+ trendingSearches = trendingSearchList;
+ swipeRefreshLayout.setRefreshing(false);
+ adapter.setTrendingSearches(trendingSearches);
+ isRefreshing = false;
+ });
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(() -> {
+ swipeRefreshLayout.setRefreshing(false);
+ showErrorView(R.string.error_parse_trending_search);
+ isRefreshing = false;
+ });
+ }
+ });
+ } else {
+ handler.post(() -> {
+ swipeRefreshLayout.setRefreshing(false);
+ showErrorView(R.string.error_fetch_trending_search);
+ isRefreshing = false;
+ });
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+ handler.post(() -> {
+ swipeRefreshLayout.setRefreshing(false);
+ showErrorView(R.string.error_fetch_trending_search);
+ isRefreshing = false;
+ });
+ }
+ });
+ }
+
+ private void showErrorView(int stringId) {
+ errorLinearLayout.setVisibility(View.VISIBLE);
+ Glide.with(this).load(R.drawable.error_image).into(errorImageView);
+ errorTextView.setText(stringId);
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.trending_activity, menu);
+ applyMenuItemTheme(menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(@NonNull MenuItem item) {
+ if (item.getItemId() == android.R.id.home) {
+ finish();
+ return true;
+ } else if (item.getItemId() == R.id.action_refresh_trending_activity) {
+ fetchTrendingSearches();
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ protected void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putParcelableArrayList(TRENDING_SEARCHES_STATE, trendingSearches);
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ EventBus.getDefault().unregister(this);
+ }
+
+ @Override
+ protected SharedPreferences getDefaultSharedPreferences() {
+ return mSharedPreferences;
+ }
+
+ @Override
+ protected CustomThemeWrapper getCustomThemeWrapper() {
+ return mCustomThemeWrapper;
+ }
+
+ @Override
+ protected void applyCustomTheme() {
+ coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
+ applyAppBarLayoutAndToolbarTheme(appBarLayout, toolbar);
+ swipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
+ swipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
+ errorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
+ }
+
+ @Subscribe
+ public void onAccountSwitchEvent(SwitchAccountEvent event) {
+ finish();
+ }
+} \ No newline at end of file
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 e82ea47a..9602da8b 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImageOrGifActivity.java
@@ -12,11 +12,14 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
+import android.text.Spanned;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
+import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
+import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -42,6 +45,7 @@ import com.github.piasy.biv.loader.ImageLoader;
import com.github.piasy.biv.loader.glide.GlideImageLoader;
import com.github.piasy.biv.view.BigImageView;
import com.github.piasy.biv.view.GlideImageViewFactory;
+import com.google.android.material.bottomappbar.BottomAppBar;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrConfig;
import com.r0adkll.slidr.model.SlidrPosition;
@@ -85,6 +89,16 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
BigImageView mImageView;
@BindView(R.id.load_image_error_linear_layout_view_image_or_gif_activity)
LinearLayout mLoadErrorLinearLayout;
+ @BindView(R.id.bottom_navigation_view_image_or_gif_activity)
+ BottomAppBar bottomAppBar;
+ @BindView(R.id.title_text_view_view_image_or_gif_activity)
+ TextView titleTextView;
+ @BindView(R.id.download_image_view_view_image_or_gif_activity)
+ ImageView downloadImageView;
+ @BindView(R.id.share_image_view_view_image_or_gif_activity)
+ ImageView shareImageView;
+ @BindView(R.id.wallpaper_image_view_view_image_or_gif_activity)
+ ImageView wallpaperImageView;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@@ -130,12 +144,9 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
ButterKnife.bind(this);
- ActionBar actionBar = getSupportActionBar();
- Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
- actionBar.setHomeAsUpIndicator(upArrow);
- actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
-
- Slidr.attach(this, new SlidrConfig.Builder().position(SlidrPosition.VERTICAL).distanceThreshold(0.125f).build());
+ if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_VERTICALLY_TO_GO_BACK_FROM_MEDIA, true)) {
+ Slidr.attach(this, new SlidrConfig.Builder().position(SlidrPosition.VERTICAL).distanceThreshold(0.125f).build());
+ }
glide = Glide.with(this);
@@ -149,10 +160,44 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
String postTitle = intent.getStringExtra(EXTRA_POST_TITLE_KEY);
mSubredditName = intent.getStringExtra(EXTRA_SUBREDDIT_OR_USERNAME_KEY);
+ boolean useBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.USE_BOTTOM_TOOLBAR_IN_MEDIA_VIEWER, false);
if (postTitle != null) {
- setTitle(Html.fromHtml(String.format("<small>%s</small>", postTitle)));
+ Spanned title = Html.fromHtml(String.format("<small>%s</small>", postTitle));
+ if (useBottomAppBar) {
+ titleTextView.setText(title);
+ } else {
+ setTitle(title);
+ }
} else {
- setTitle("");
+ if (!useBottomAppBar) {
+ setTitle("");
+ }
+ }
+
+ if (useBottomAppBar) {
+ getSupportActionBar().hide();
+ bottomAppBar.setVisibility(View.VISIBLE);
+ downloadImageView.setOnClickListener(view -> {
+ if (isDownloading) {
+ return;
+ }
+ isDownloading = true;
+ requestPermissionAndDownload();
+ });
+ shareImageView.setOnClickListener(view -> {
+ if (isGif)
+ shareGif();
+ else
+ shareImage();
+ });
+ wallpaperImageView.setOnClickListener(view -> {
+ setWallpaper();
+ });
+ } else {
+ ActionBar actionBar = getSupportActionBar();
+ Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
+ actionBar.setHomeAsUpIndicator(upArrow);
+ actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
}
mLoadErrorLinearLayout.setOnClickListener(view -> {
@@ -168,6 +213,9 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
isActionBarHidden = false;
+ if (useBottomAppBar) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ }
} else {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
@@ -177,6 +225,9 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE);
isActionBarHidden = true;
+ if (useBottomAppBar) {
+ bottomAppBar.setVisibility(View.GONE);
+ }
}
});
@@ -285,26 +336,8 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
if (isDownloading) {
return false;
}
-
isDownloading = true;
-
- 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();
- }
- } else {
- download();
- }
-
+ requestPermissionAndDownload();
return true;
} else if (itemId == R.id.action_share_view_image_or_gif_activity) {
if (isGif)
@@ -313,31 +346,32 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
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();
- }
- });
- }
- }
+ setWallpaper();
return true;
}
return false;
}
+ private void requestPermissionAndDownload() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ 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();
+ }
+ } else {
+ download();
+ }
+ }
+
private void download() {
isDownloading = false;
@@ -431,6 +465,28 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
}).submit();
}
+ private void setWallpaper() {
+ 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();
+ }
+ });
+ }
+ }
+ }
+
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
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 10866770..8aab0011 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewImgurMediaActivity.java
@@ -36,7 +36,13 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
+import ml.docilealligator.infinityforreddit.ImgurMedia;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback;
+import ml.docilealligator.infinityforreddit.WallpaperSetter;
import ml.docilealligator.infinityforreddit.apis.ImgurAPI;
+import ml.docilealligator.infinityforreddit.customviews.ViewPagerBugFixed;
import ml.docilealligator.infinityforreddit.font.ContentFontFamily;
import ml.docilealligator.infinityforreddit.font.ContentFontStyle;
import ml.docilealligator.infinityforreddit.font.FontFamily;
@@ -45,14 +51,9 @@ import ml.docilealligator.infinityforreddit.font.TitleFontFamily;
import ml.docilealligator.infinityforreddit.font.TitleFontStyle;
import ml.docilealligator.infinityforreddit.fragments.ViewImgurImageFragment;
import ml.docilealligator.infinityforreddit.fragments.ViewImgurVideoFragment;
-import ml.docilealligator.infinityforreddit.ImgurMedia;
-import ml.docilealligator.infinityforreddit.Infinity;
-import ml.docilealligator.infinityforreddit.R;
-import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
-import ml.docilealligator.infinityforreddit.WallpaperSetter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@@ -72,11 +73,12 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa
@BindView(R.id.progress_bar_view_imgur_media_activity)
ProgressBar progressBar;
@BindView(R.id.view_pager_view_imgur_media_activity)
- ViewPager viewPager;
+ ViewPagerBugFixed viewPager;
@BindView(R.id.load_image_error_linear_layout_view_imgur_media_activity)
LinearLayout errorLinearLayout;
private SectionsPagerAdapter sectionsPagerAdapter;
private ArrayList<ImgurMedia> images;
+ private boolean useBottomAppBar;
@Inject
@Named("imgur")
Retrofit imgurRetrofit;
@@ -116,12 +118,17 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa
ButterKnife.bind(this);
- ActionBar actionBar = getSupportActionBar();
- Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
- actionBar.setHomeAsUpIndicator(upArrow);
- actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
+ useBottomAppBar = sharedPreferences.getBoolean(SharedPreferencesUtils.USE_BOTTOM_TOOLBAR_IN_MEDIA_VIEWER, false);
- setTitle(" ");
+ if (!useBottomAppBar) {
+ ActionBar actionBar = getSupportActionBar();
+ Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
+ actionBar.setHomeAsUpIndicator(upArrow);
+ actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
+ setTitle(" ");
+ } else {
+ getSupportActionBar().hide();
+ }
String imgurId = getIntent().getStringExtra(EXTRA_IMGUR_ID);
if (imgurId == null) {
@@ -133,11 +140,15 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa
images = savedInstanceState.getParcelableArrayList(IMGUR_IMAGES_STATE);
}
- haulerView.setOnDragDismissedListener(dragDirection -> {
- int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down;
- finish();
- overridePendingTransition(0, slide);
- });
+ if (sharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_VERTICALLY_TO_GO_BACK_FROM_MEDIA, true)) {
+ haulerView.setOnDragDismissedListener(dragDirection -> {
+ int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down;
+ finish();
+ overridePendingTransition(0, slide);
+ });
+ } else {
+ haulerView.setDragEnabled(false);
+ }
if (images == null) {
fetchImgurMedia(imgurId);
@@ -149,6 +160,10 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa
errorLinearLayout.setOnClickListener(view -> fetchImgurMedia(imgurId));
}
+ public boolean isUseBottomAppBar() {
+ return useBottomAppBar;
+ }
+
private void fetchImgurMedia(String imgurId) {
errorLinearLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
@@ -260,15 +275,18 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa
}
private void setupViewPager() {
- setToolbarTitle(0);
+ if (!useBottomAppBar) {
+ setToolbarTitle(0);
+ viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
+ @Override
+ public void onPageSelected(int position) {
+ setToolbarTitle(position);
+ }
+ });
+ }
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
- viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
- @Override
- public void onPageSelected(int position) {
- setToolbarTitle(position);
- }
- });
viewPager.setAdapter(sectionsPagerAdapter);
+ viewPager.setOffscreenPageLimit(3);
}
private void setToolbarTitle(int position) {
@@ -374,12 +392,16 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa
ViewImgurVideoFragment fragment = new ViewImgurVideoFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(ViewImgurVideoFragment.EXTRA_IMGUR_VIDEO, imgurMedia);
+ bundle.putInt(ViewImgurVideoFragment.EXTRA_INDEX, position);
+ bundle.putInt(ViewImgurVideoFragment.EXTRA_MEDIA_COUNT, images.size());
fragment.setArguments(bundle);
return fragment;
} else {
ViewImgurImageFragment fragment = new ViewImgurImageFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(ViewImgurImageFragment.EXTRA_IMGUR_IMAGES, imgurMedia);
+ bundle.putInt(ViewImgurImageFragment.EXTRA_INDEX, position);
+ bundle.putInt(ViewImgurImageFragment.EXTRA_MEDIA_COUNT, images.size());
fragment.setArguments(bundle);
return fragment;
}
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 cd4e7fdb..ae3538b1 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPostDetailActivity.java
@@ -1,8 +1,11 @@
package ml.docilealligator.infinityforreddit.activities;
+import static ml.docilealligator.infinityforreddit.activities.CommentActivity.RETURN_EXTRA_COMMENT_DATA_KEY;
+
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
@@ -11,6 +14,7 @@ import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
+import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -27,8 +31,11 @@ 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.card.MaterialCardView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
+import com.google.android.material.textfield.TextInputEditText;
+import com.google.android.material.textfield.TextInputLayout;
import com.livefront.bridge.Bridge;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrInterface;
@@ -62,8 +69,6 @@ import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
-import static ml.docilealligator.infinityforreddit.activities.CommentActivity.RETURN_EXTRA_COMMENT_DATA_KEY;
-
public class ViewPostDetailActivity extends BaseActivity implements SortTypeSelectionCallback, ActivityToolbarInterface {
public static final String EXTRA_POST_DATA = "EPD";
@@ -89,6 +94,18 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
ViewPager2 viewPager2;
@BindView(R.id.fab_view_post_detail_activity)
FloatingActionButton fab;
+ @BindView(R.id.search_panel_material_card_view_view_post_detail_activity)
+ MaterialCardView searchPanelMaterialCardView;
+ @BindView(R.id.search_text_input_layout_view_post_detail_activity)
+ TextInputLayout searchTextInputLayout;
+ @BindView(R.id.search_text_input_edit_text_view_post_detail_activity)
+ TextInputEditText searchTextInputEditText;
+ @BindView(R.id.previous_result_image_view_view_post_detail_activity)
+ ImageView previousResultImageView;
+ @BindView(R.id.next_result_image_view_view_post_detail_activity)
+ ImageView nextResultImageView;
+ @BindView(R.id.close_search_panel_image_view_view_post_detail_activity)
+ ImageView closeSearchPanelImageView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@@ -160,13 +177,21 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
params.bottomMargin += navBarHeight;
fab.setLayoutParams(params);
+
+ searchPanelMaterialCardView.setContentPadding(searchPanelMaterialCardView.getPaddingStart(),
+ searchPanelMaterialCardView.getPaddingTop(),
+ searchPanelMaterialCardView.getPaddingEnd(),
+ searchPanelMaterialCardView.getPaddingBottom() + navBarHeight);
}
}
}
boolean swipeBetweenPosts = mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_BETWEEN_POSTS, false);
- if (!swipeBetweenPosts && mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) {
- mSlidrInterface = Slidr.attach(this);
+ if (!swipeBetweenPosts) {
+ if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) {
+ mSlidrInterface = Slidr.attach(this);
+ }
+ viewPager2.setUserInputEnabled(false);
}
postFragmentId = getIntent().getLongExtra(EXTRA_POST_FRAGMENT_ID, -1);
if (swipeBetweenPosts && posts == null && postFragmentId > 0) {
@@ -206,6 +231,17 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
}
});
+ fab.setOnLongClickListener(view -> {
+ if (sectionsPagerAdapter != null) {
+ ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment();
+ if (fragment != null) {
+ fragment.scrollToPreviousParentComment();
+ return true;
+ }
+ }
+ return false;
+ });
+
checkNewAccountAndBindView(savedInstanceState);
}
@@ -242,6 +278,14 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
mCoordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
applyAppBarLayoutAndToolbarTheme(mAppBarLayout, mToolbar);
applyFABTheme(fab);
+ searchPanelMaterialCardView.setBackgroundTintList(ColorStateList.valueOf(mCustomThemeWrapper.getColorPrimary()));
+ int searchPanelTextAndIconColor = mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor();
+ searchTextInputLayout.setBoxStrokeColor(searchPanelTextAndIconColor);
+ searchTextInputLayout.setDefaultHintTextColor(ColorStateList.valueOf(searchPanelTextAndIconColor));
+ searchTextInputEditText.setTextColor(searchPanelTextAndIconColor);
+ previousResultImageView.setColorFilter(searchPanelTextAndIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ nextResultImageView.setColorFilter(searchPanelTextAndIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ closeSearchPanelImageView.setColorFilter(searchPanelTextAndIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
}
private void checkNewAccountAndBindView(Bundle savedInstanceState) {
@@ -270,6 +314,31 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
if (savedInstanceState == null) {
viewPager2.setCurrentItem(getIntent().getIntExtra(EXTRA_POST_LIST_POSITION, 0), false);
}
+
+ searchPanelMaterialCardView.setOnClickListener(null);
+
+ nextResultImageView.setOnClickListener(view -> {
+ ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment();
+ if (fragment != null) {
+ searchComment(fragment, true);
+ }
+ });
+
+ previousResultImageView.setOnClickListener(view -> {
+ ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment();
+ if (fragment != null) {
+ searchComment(fragment, false);
+ }
+ });
+
+ closeSearchPanelImageView.setOnClickListener(view -> {
+ ViewPostDetailFragment fragment = sectionsPagerAdapter.getCurrentFragment();
+ if (fragment != null) {
+ fragment.resetSearchCommentIndex();
+ }
+
+ searchPanelMaterialCardView.setVisibility(View.GONE);
+ });
}
public boolean isNsfwSubreddit() {
@@ -358,6 +427,23 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
}
}
+ public boolean toggleSearchPanelVisibility() {
+ if (searchPanelMaterialCardView.getVisibility() == View.GONE) {
+ searchPanelMaterialCardView.setVisibility(View.VISIBLE);
+ return false;
+ } else {
+ searchPanelMaterialCardView.setVisibility(View.GONE);
+ searchTextInputEditText.setText("");
+ return true;
+ }
+ }
+
+ public void searchComment(ViewPostDetailFragment fragment, boolean searchNextComment) {
+ if (!searchTextInputEditText.getText().toString().isEmpty()) {
+ fragment.searchComment(searchTextInputEditText.getText().toString(), searchNextComment);
+ }
+ }
+
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
if (!getClass().getName().equals(event.excludeActivityClassName)) {
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 b7f914b9..ad09e76e 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewPrivateMessagesActivity.java
@@ -14,7 +14,6 @@ import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.transition.AutoTransition;
import androidx.transition.TransitionManager;
@@ -39,6 +38,7 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.adapters.PrivateMessagesDetailRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.asynctasks.LoadUserData;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.RepliedToPrivateMessageEvent;
import ml.docilealligator.infinityforreddit.message.Message;
import ml.docilealligator.infinityforreddit.message.ReadMessage;
@@ -87,7 +87,7 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private PrivateMessagesDetailRecyclerViewAdapter mAdapter;
private Message privateMessage;
private String mAccessToken;
@@ -154,7 +154,7 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
}
mAdapter = new PrivateMessagesDetailRecyclerViewAdapter(this, mSharedPreferences,
getResources().getConfiguration().locale, privateMessage, mAccountName, mCustomThemeWrapper);
- mLinearLayoutManager = new LinearLayoutManager(this);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(this);
mLinearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
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 6bcccfa3..b5047cc6 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewRedditGalleryActivity.java
@@ -28,6 +28,7 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
+import ml.docilealligator.infinityforreddit.customviews.ViewPagerBugFixed;
import ml.docilealligator.infinityforreddit.font.ContentFontFamily;
import ml.docilealligator.infinityforreddit.font.ContentFontStyle;
import ml.docilealligator.infinityforreddit.font.FontFamily;
@@ -51,10 +52,11 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA
@BindView(R.id.hauler_view_view_reddit_gallery_activity)
HaulerView haulerView;
@BindView(R.id.view_pager_view_reddit_gallery_activity)
- ViewPager viewPager;
+ ViewPagerBugFixed viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
private ArrayList<Post.Gallery> gallery;
private String subredditName;
+ private boolean useBottomAppBar;
@Inject
@Named("default")
SharedPreferences sharedPreferences;
@@ -91,12 +93,17 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA
ButterKnife.bind(this);
- ActionBar actionBar = getSupportActionBar();
- Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
- actionBar.setHomeAsUpIndicator(upArrow);
- actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
+ useBottomAppBar = sharedPreferences.getBoolean(SharedPreferencesUtils.USE_BOTTOM_TOOLBAR_IN_MEDIA_VIEWER, false);
- setTitle(" ");
+ if (!useBottomAppBar) {
+ ActionBar actionBar = getSupportActionBar();
+ Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
+ actionBar.setHomeAsUpIndicator(upArrow);
+ actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
+ setTitle(" ");
+ } else {
+ getSupportActionBar().hide();
+ }
gallery = getIntent().getParcelableArrayListExtra(EXTRA_REDDIT_GALLERY);
if (gallery == null || gallery.isEmpty()) {
@@ -105,25 +112,36 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA
}
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
- haulerView.setOnDragDismissedListener(dragDirection -> {
- int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down;
- finish();
- overridePendingTransition(0, slide);
- });
+ if (sharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_VERTICALLY_TO_GO_BACK_FROM_MEDIA, true)) {
+ haulerView.setOnDragDismissedListener(dragDirection -> {
+ int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down;
+ finish();
+ overridePendingTransition(0, slide);
+ });
+ } else {
+ haulerView.setDragEnabled(false);
+ }
setupViewPager();
}
+ public boolean isUseBottomAppBar() {
+ return useBottomAppBar;
+ }
+
private void setupViewPager() {
- setToolbarTitle(0);
+ if (!useBottomAppBar) {
+ setToolbarTitle(0);
+ viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
+ @Override
+ public void onPageSelected(int position) {
+ setToolbarTitle(position);
+ }
+ });
+ }
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
- viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
- @Override
- public void onPageSelected(int position) {
- setToolbarTitle(position);
- }
- });
viewPager.setAdapter(sectionsPagerAdapter);
+ viewPager.setOffscreenPageLimit(3);
}
private void setToolbarTitle(int position) {
@@ -226,6 +244,8 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA
Bundle bundle = new Bundle();
bundle.putParcelable(ViewRedditGalleryVideoFragment.EXTRA_REDDIT_GALLERY_VIDEO, media);
bundle.putString(ViewRedditGalleryVideoFragment.EXTRA_SUBREDDIT_NAME, subredditName);
+ bundle.putInt(ViewRedditGalleryVideoFragment.EXTRA_INDEX, position);
+ bundle.putInt(ViewRedditGalleryVideoFragment.EXTRA_MEDIA_COUNT, gallery.size());
fragment.setArguments(bundle);
return fragment;
} else {
@@ -233,6 +253,8 @@ public class ViewRedditGalleryActivity extends AppCompatActivity implements SetA
Bundle bundle = new Bundle();
bundle.putParcelable(ViewRedditGalleryImageOrGifFragment.EXTRA_REDDIT_GALLERY_MEDIA, media);
bundle.putString(ViewRedditGalleryImageOrGifFragment.EXTRA_SUBREDDIT_NAME, subredditName);
+ bundle.putInt(ViewRedditGalleryImageOrGifFragment.EXTRA_INDEX, position);
+ bundle.putInt(ViewRedditGalleryImageOrGifFragment.EXTRA_MEDIA_COUNT, gallery.size());
fragment.setArguments(bundle);
return fragment;
}
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 bd73d838..57620c51 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewSubredditDetailActivity.java
@@ -4,9 +4,13 @@ import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
+import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.text.util.Linkify;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
@@ -14,6 +18,7 @@ import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
+import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
@@ -28,6 +33,7 @@ import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
+import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
@@ -51,6 +57,7 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.Executor;
@@ -59,7 +66,14 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
+import io.noties.markwon.AbstractMarkwonPlugin;
+import io.noties.markwon.Markwon;
+import io.noties.markwon.MarkwonConfiguration;
+import io.noties.markwon.core.MarkwonTheme;
+import io.noties.markwon.linkify.LinkifyPlugin;
+import io.noties.markwon.movement.MovementMethodPlugin;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
+import me.saket.bettermovementmethod.BetterLinkMovementMethod;
import ml.docilealligator.infinityforreddit.ActivityToolbarInterface;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
@@ -70,16 +84,20 @@ import ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterfac
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback;
+import ml.docilealligator.infinityforreddit.adapters.SubredditAutocompleteRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.asynctasks.AddSubredditOrUserToMultiReddit;
import ml.docilealligator.infinityforreddit.asynctasks.CheckIsSubscribedToSubreddit;
import ml.docilealligator.infinityforreddit.asynctasks.InsertSubredditData;
import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.CopyTextBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostLayoutBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.RandomBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.SortTimeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.SortTypeBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.UrlMenuBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.events.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.events.GoBackToMainPageEvent;
@@ -92,12 +110,17 @@ import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.post.PostDataSource;
import ml.docilealligator.infinityforreddit.readpost.InsertReadPost;
import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData;
+import ml.docilealligator.infinityforreddit.subreddit.ParseSubredditData;
import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
import ml.docilealligator.infinityforreddit.subreddit.SubredditSubscription;
import ml.docilealligator.infinityforreddit.subreddit.SubredditViewModel;
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import pl.droidsonroids.gif.GifImageView;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
import retrofit2.Retrofit;
public class ViewSubredditDetailActivity extends BaseActivity implements SortTypeSelectionCallback,
@@ -196,9 +219,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
public SubredditViewModel mSubredditViewModel;
private FragmentManager fragmentManager;
private SectionsPagerAdapter sectionsPagerAdapter;
+ private Call<String> subredditAutocompleteCall;
private String mAccessToken;
private String mAccountName;
private String subredditName;
+ private String description;
private boolean mFetchSubredditInfoSuccess = false;
private int mNCurrentOnlineSubscribers = 0;
private boolean isNsfwSubreddit = false;
@@ -317,7 +342,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
});
}
- showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, false);
+ showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, true);
lockBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_BOTTOM_APP_BAR, false);
boolean hideSubredditDescription = mSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBREDDIT_DESCRIPTION, false);
@@ -360,6 +385,44 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
glide = Glide.with(this);
Locale locale = getResources().getConfiguration().locale;
+ Markwon markwon = Markwon.builder(this)
+ .usePlugin(new AbstractMarkwonPlugin() {
+ @Override
+ public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
+ builder.linkResolver((view, link) -> {
+ Intent intent = new Intent(ViewSubredditDetailActivity.this, LinkResolverActivity.class);
+ Uri uri = Uri.parse(link);
+ intent.setData(uri);
+ startActivity(intent);
+ });
+ }
+
+ @Override
+ public void configureTheme(@NonNull MarkwonTheme.Builder builder) {
+ builder.linkColor(mCustomThemeWrapper.getLinkColor());
+ }
+ })
+ .usePlugin(MovementMethodPlugin.create(BetterLinkMovementMethod.linkify(Linkify.WEB_URLS, this).setOnLinkLongClickListener((textView, url) -> {
+ UrlMenuBottomSheetFragment urlMenuBottomSheetFragment = new UrlMenuBottomSheetFragment();
+ Bundle bundle = new Bundle();
+ bundle.putString(UrlMenuBottomSheetFragment.EXTRA_URL, url);
+ urlMenuBottomSheetFragment.setArguments(bundle);
+ urlMenuBottomSheetFragment.show(getSupportFragmentManager(), urlMenuBottomSheetFragment.getTag());
+ return true;
+ })))
+ .usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS)).build();
+
+ descriptionTextView.setOnLongClickListener(view -> {
+ if (description != null && !description.equals("") && descriptionTextView.getSelectionStart() == -1 && descriptionTextView.getSelectionEnd() == -1) {
+ Bundle bundle = new Bundle();
+ bundle.putString(CopyTextBottomSheetFragment.EXTRA_RAW_TEXT, description);
+ CopyTextBottomSheetFragment copyTextBottomSheetFragment = new CopyTextBottomSheetFragment();
+ copyTextBottomSheetFragment.setArguments(bundle);
+ copyTextBottomSheetFragment.show(getSupportFragmentManager(), copyTextBottomSheetFragment.getTag());
+ }
+ return true;
+ });
+
mSubredditViewModel = new ViewModelProvider(this,
new SubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, subredditName))
.get(SubredditViewModel.class);
@@ -411,11 +474,12 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
nSubscribersTextView.setText(nSubscribers);
creationTimeTextView.setText(new SimpleDateFormat("MMM d, yyyy",
locale).format(subredditData.getCreatedUTC()));
- if (hideSubredditDescription || subredditData.getDescription().equals("")) {
+ description = subredditData.getDescription();
+ if (hideSubredditDescription || description.equals("")) {
descriptionTextView.setVisibility(View.GONE);
} else {
descriptionTextView.setVisibility(View.VISIBLE);
- descriptionTextView.setText(subredditData.getDescription());
+ markwon.setMarkdown(descriptionTextView, description);
}
if (subredditData.isNSFW()) {
@@ -1101,6 +1165,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
}
Intent intent = new Intent(this, MultiredditSelectionActivity.class);
startActivityForResult(intent, ADD_TO_MULTIREDDIT_REQUEST_CODE);
+ } else if (itemId == R.id.action_add_to_post_filter_view_subreddit_detail_activity) {
+ Intent intent = new Intent(this, PostFilterPreferenceActivity.class);
+ intent.putExtra(PostFilterPreferenceActivity.EXTRA_SUBREDDIT_NAME, subredditName);
+ startActivity(intent);
+ return true;
} else if (itemId == R.id.action_share_view_subreddit_detail_activity) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
@@ -1215,6 +1284,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
intent = new Intent(this, PostVideoActivity.class);
intent.putExtra(PostVideoActivity.EXTRA_SUBREDDIT_NAME, subredditName);
startActivity(intent);
+ break;
+ case PostTypeBottomSheetFragment.TYPE_GALLERY:
+ intent = new Intent(this, PostGalleryActivity.class);
+ intent.putExtra(PostVideoActivity.EXTRA_SUBREDDIT_NAME, subredditName);
+ startActivity(intent);
}
}
@@ -1333,11 +1407,79 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private void goToSubreddit() {
View rootView = getLayoutInflater().inflate(R.layout.dialog_go_to_thing_edit_text, coordinatorLayout, false);
TextInputEditText thingEditText = rootView.findViewById(R.id.text_input_edit_text_go_to_thing_edit_text);
+ RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_go_to_thing_edit_text);
thingEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+ SubredditAutocompleteRecyclerViewAdapter adapter = new SubredditAutocompleteRecyclerViewAdapter(
+ this, mCustomThemeWrapper, subredditData -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewSubredditDetailActivity.class);
+ intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditData.getName());
+ startActivity(intent);
+ });
+ recyclerView.setAdapter(adapter);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent subredditIntent = new Intent(this, ViewSubredditDetailActivity.class);
+ subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
+ startActivity(subredditIntent);
+ return true;
+ }
+ return false;
+ });
+
+ boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, false);
+ thingEditText.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ if (subredditAutocompleteCall != null) {
+ subredditAutocompleteCall.cancel();
+ }
+ subredditAutocompleteCall = mOauthRetrofit.create(RedditAPI.class).subredditAutocomplete(APIUtils.getOAuthHeader(mAccessToken),
+ editable.toString(), nsfw);
+ subredditAutocompleteCall.enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ ParseSubredditData.parseSubredditListingData(response.body(), nsfw, new ParseSubredditData.ParseSubredditListingDataListener() {
+ @Override
+ public void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after) {
+ adapter.setSubreddits(subredditData);
+ }
+
+ @Override
+ public void onParseSubredditListingDataFail() {
+
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+
+ }
+ });
+ }
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_subreddit)
.setView(rootView)
@@ -1350,7 +1492,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
startActivity(subredditIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -1367,6 +1513,18 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent userIntent = new Intent(this, ViewUserDetailActivity.class);
+ userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
+ startActivity(userIntent);
+ return true;
+ }
+ return false;
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_user)
.setView(rootView)
@@ -1379,7 +1537,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
startActivity(userIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
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 47b6fac1..d6fbb3d4 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewUserDetailActivity.java
@@ -10,6 +10,8 @@ import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
+import android.text.Editable;
+import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
@@ -17,6 +19,7 @@ import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
+import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
@@ -31,6 +34,7 @@ import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
+import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
@@ -54,6 +58,7 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.Executor;
@@ -74,6 +79,8 @@ import ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterfac
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.SortTypeSelectionCallback;
+import ml.docilealligator.infinityforreddit.adapters.SubredditAutocompleteRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.asynctasks.AddSubredditOrUserToMultiReddit;
import ml.docilealligator.infinityforreddit.asynctasks.CheckIsFollowingUser;
import ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount;
@@ -94,15 +101,21 @@ 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.subreddit.ParseSubredditData;
+import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
import ml.docilealligator.infinityforreddit.user.BlockUser;
import ml.docilealligator.infinityforreddit.user.FetchUserData;
import ml.docilealligator.infinityforreddit.user.UserDao;
import ml.docilealligator.infinityforreddit.user.UserData;
import ml.docilealligator.infinityforreddit.user.UserFollowing;
import ml.docilealligator.infinityforreddit.user.UserViewModel;
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import pl.droidsonroids.gif.GifImageView;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
import retrofit2.Retrofit;
public class ViewUserDetailActivity extends BaseActivity implements SortTypeSelectionCallback,
@@ -203,7 +216,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private UserThingSortTypeBottomSheetFragment userThingSortTypeBottomSheetFragment;
private SortTimeBottomSheetFragment sortTimeBottomSheetFragment;
private PostLayoutBottomSheetFragment postLayoutBottomSheetFragment;
- private boolean mNullAccessToken = false;
+ private Call<String> subredditAutocompleteCall;
private String mAccessToken;
private String mAccountName;
private String username;
@@ -353,7 +366,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
});
}
- showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, false);
+ showBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, true);
lockBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.LOCK_BOTTOM_APP_BAR, false);
glide = Glide.with(this);
@@ -968,6 +981,11 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
}
Intent intent = new Intent(this, MultiredditSelectionActivity.class);
startActivityForResult(intent, ADD_TO_MULTIREDDIT_REQUEST_CODE);
+ } else if (itemId == R.id.action_add_to_post_filter_view_user_detail_activity) {
+ Intent intent = new Intent(this, PostFilterPreferenceActivity.class);
+ intent.putExtra(PostFilterPreferenceActivity.EXTRA_USER_NAME, username);
+ startActivity(intent);
+ return true;
} else if (itemId == R.id.action_report_view_user_detail_activity) {
Intent reportIntent = new Intent(this, LinkResolverActivity.class);
reportIntent.setData(Uri.parse("https://www.reddithelp.com/en/categories/rules-reporting/account-and-community-restrictions/what-should-i-do-if-i-see-something-i"));
@@ -1144,11 +1162,79 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private void goToSubreddit() {
View rootView = getLayoutInflater().inflate(R.layout.dialog_go_to_thing_edit_text, coordinatorLayout, false);
TextInputEditText thingEditText = rootView.findViewById(R.id.text_input_edit_text_go_to_thing_edit_text);
+ RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_go_to_thing_edit_text);
thingEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+ SubredditAutocompleteRecyclerViewAdapter adapter = new SubredditAutocompleteRecyclerViewAdapter(
+ this, mCustomThemeWrapper, subredditData -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent intent = new Intent(ViewUserDetailActivity.this, ViewSubredditDetailActivity.class);
+ intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditData.getName());
+ startActivity(intent);
+ });
+ recyclerView.setAdapter(adapter);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent subredditIntent = new Intent(this, ViewSubredditDetailActivity.class);
+ subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
+ startActivity(subredditIntent);
+ return true;
+ }
+ return false;
+ });
+
+ boolean nsfw = mNsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, false);
+ thingEditText.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+
+ }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ if (subredditAutocompleteCall != null) {
+ subredditAutocompleteCall.cancel();
+ }
+ subredditAutocompleteCall = mOauthRetrofit.create(RedditAPI.class).subredditAutocomplete(APIUtils.getOAuthHeader(mAccessToken),
+ editable.toString(), nsfw);
+ subredditAutocompleteCall.enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ ParseSubredditData.parseSubredditListingData(response.body(), nsfw, new ParseSubredditData.ParseSubredditListingDataListener() {
+ @Override
+ public void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after) {
+ adapter.setSubreddits(subredditData);
+ }
+
+ @Override
+ public void onParseSubredditListingDataFail() {
+
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+
+ }
+ });
+ }
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_subreddit)
.setView(rootView)
@@ -1161,7 +1247,11 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
startActivity(subredditIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -1178,6 +1268,18 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
+ thingEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
+ if (i == EditorInfo.IME_ACTION_DONE) {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ Intent userIntent = new Intent(this, ViewUserDetailActivity.class);
+ userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
+ startActivity(userIntent);
+ return true;
+ }
+ return false;
+ });
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.go_to_user)
.setView(rootView)
@@ -1190,7 +1292,11 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
startActivity(userIntent);
})
- .setNegativeButton(R.string.cancel, null)
+ .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
+ if (imm != null) {
+ imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
+ }
+ })
.setOnDismissListener(dialogInterface -> {
if (imm != null) {
imm.hideSoftInputFromWindow(thingEditText.getWindowToken(), 0);
@@ -1293,6 +1399,10 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
case PostTypeBottomSheetFragment.TYPE_VIDEO:
intent = new Intent(this, PostVideoActivity.class);
startActivity(intent);
+ break;
+ case PostTypeBottomSheetFragment.TYPE_GALLERY:
+ intent = new Intent(this, PostGalleryActivity.class);
+ startActivity(intent);
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewVideoActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewVideoActivity.java
index 61a12366..7362e892 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewVideoActivity.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/ViewVideoActivity.java
@@ -3,22 +3,29 @@ package ml.docilealligator.infinityforreddit.activities;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
+import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
+import android.os.Handler;
+import android.provider.Settings;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
+import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
+import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
+import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -43,7 +50,10 @@ import com.google.android.exoplayer2.ui.TrackSelectionDialogBuilder;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
+import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
+import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
+import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.snackbar.Snackbar;
import com.thefuntasty.hauler.DragDirection;
import com.thefuntasty.hauler.HaulerView;
@@ -51,6 +61,7 @@ import com.thefuntasty.hauler.HaulerView;
import org.apache.commons.io.FilenameUtils;
import java.util.List;
+import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
@@ -62,8 +73,11 @@ import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.apis.VReddIt;
import ml.docilealligator.infinityforreddit.font.ContentFontFamily;
+import ml.docilealligator.infinityforreddit.font.ContentFontStyle;
import ml.docilealligator.infinityforreddit.font.FontFamily;
+import ml.docilealligator.infinityforreddit.font.FontStyle;
import ml.docilealligator.infinityforreddit.font.TitleFontFamily;
+import ml.docilealligator.infinityforreddit.font.TitleFontStyle;
import ml.docilealligator.infinityforreddit.post.FetchPost;
import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.services.DownloadMediaService;
@@ -112,6 +126,12 @@ public class ViewVideoActivity extends AppCompatActivity {
ImageButton muteButton;
@BindView(R.id.hd_exo_playback_control_view)
ImageButton hdButton;
+ @BindView(R.id.bottom_navigation_exo_playback_control_view)
+ BottomAppBar bottomAppBar;
+ @BindView(R.id.title_text_view_exo_playback_control_view)
+ TextView titleTextView;
+ @BindView(R.id.download_image_view_exo_playback_control_view)
+ ImageView downloadImageView;
private Uri mVideoUri;
private SimpleExoPlayer player;
@@ -131,6 +151,7 @@ public class ViewVideoActivity extends AppCompatActivity {
private int videoType;
private boolean isDataSavingMode;
private boolean isHd;
+ private Integer originalOrientation;
@Inject
@Named("no_oauth")
@@ -152,6 +173,12 @@ public class ViewVideoActivity extends AppCompatActivity {
@Named("default")
SharedPreferences mSharedPreferences;
+ @Inject
+ Executor mExecutor;
+
+ @Inject
+ SimpleCache mSimpleCache;
+
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -160,6 +187,15 @@ public class ViewVideoActivity extends AppCompatActivity {
getTheme().applyStyle(R.style.Theme_Normal, true);
+ getTheme().applyStyle(FontStyle.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.FONT_SIZE_KEY, FontStyle.Normal.name())).getResId(), true);
+
+ getTheme().applyStyle(TitleFontStyle.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.TITLE_FONT_SIZE_KEY, TitleFontStyle.Normal.name())).getResId(), true);
+
+ getTheme().applyStyle(ContentFontStyle.valueOf(mSharedPreferences
+ .getString(SharedPreferencesUtils.CONTENT_FONT_SIZE_KEY, ContentFontStyle.Normal.name())).getResId(), true);
+
getTheme().applyStyle(FontFamily.valueOf(mSharedPreferences
.getString(SharedPreferencesUtils.FONT_FAMILY_KEY, FontFamily.Default.name())).getResId(), true);
@@ -174,10 +210,31 @@ public class ViewVideoActivity extends AppCompatActivity {
ButterKnife.bind(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
- ActionBar actionBar = getSupportActionBar();
- Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
- actionBar.setHomeAsUpIndicator(upArrow);
- actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
+ Resources resources = getResources();
+
+ boolean useBottomAppBar = mSharedPreferences.getBoolean(SharedPreferencesUtils.USE_BOTTOM_TOOLBAR_IN_MEDIA_VIEWER, false);
+ if (useBottomAppBar) {
+ getSupportActionBar().hide();
+ bottomAppBar.setVisibility(View.VISIBLE);
+ downloadImageView.setOnClickListener(view -> {
+ if (isDownloading) {
+ return;
+ }
+
+ if (videoDownloadUrl == null) {
+ Toast.makeText(this, R.string.fetching_video_info_please_wait, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ isDownloading = true;
+ requestPermissionAndDownload();
+ });
+ } else {
+ ActionBar actionBar = getSupportActionBar();
+ Drawable upArrow = resources.getDrawable(R.drawable.ic_arrow_back_white_24dp);
+ actionBar.setHomeAsUpIndicator(upArrow);
+ actionBar.setBackgroundDrawable(new ColorDrawable(resources.getColor(R.color.transparentActionBarAndExoPlayerControllerColor)));
+ }
String dataSavingModeString = mSharedPreferences.getString(SharedPreferencesUtils.DATA_SAVING_MODE, SharedPreferencesUtils.DATA_SAVING_MODE_OFF);
int networkType = Utils.getConnectedNetwork(this);
@@ -189,18 +246,18 @@ public class ViewVideoActivity extends AppCompatActivity {
isHd = !isDataSavingMode;
if (!mSharedPreferences.getBoolean(SharedPreferencesUtils.VIDEO_PLAYER_IGNORE_NAV_BAR, false)) {
- if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || getResources().getBoolean(R.bool.isTablet)) {
+ if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
//Set player controller bottom margin in order to display it above the navbar
- int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
+ int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
LinearLayout controllerLinearLayout = findViewById(R.id.linear_layout_exo_playback_control_view);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) controllerLinearLayout.getLayoutParams();
- params.bottomMargin = getResources().getDimensionPixelSize(resourceId);
+ params.bottomMargin = resources.getDimensionPixelSize(resourceId);
} else {
//Set player controller right margin in order to display it above the navbar
- int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
+ int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
LinearLayout controllerLinearLayout = findViewById(R.id.linear_layout_exo_playback_control_view);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) controllerLinearLayout.getLayoutParams();
- params.rightMargin = getResources().getDimensionPixelSize(resourceId);
+ params.rightMargin = resources.getDimensionPixelSize(resourceId);
}
}
@@ -215,13 +272,45 @@ public class ViewVideoActivity extends AppCompatActivity {
isNSFW = intent.getBooleanExtra(EXTRA_IS_NSFW, false);
if (savedInstanceState == null) {
resumePosition = intent.getLongExtra(EXTRA_PROGRESS_SECONDS, -1);
+ if (mSharedPreferences.getBoolean(SharedPreferencesUtils.VIDEO_PLAYER_AUTOMATIC_LANDSCAPE_ORIENTATION, false)) {
+ originalOrientation = resources.getConfiguration().orientation;
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
+
+ if (android.provider.Settings.System.getInt(getContentResolver(),
+ Settings.System.ACCELEROMETER_ROTATION, 0) == 1) {
+ OrientationEventListener orientationEventListener = new OrientationEventListener(this) {
+ @Override
+ public void onOrientationChanged(int orientation) {
+ int epsilon = 10;
+ int leftLandscape = 90;
+ int rightLandscape = 270;
+ if(epsilonCheck(orientation, leftLandscape, epsilon) ||
+ epsilonCheck(orientation, rightLandscape, epsilon)) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
+ disable();
+ }
+ }
+
+ private boolean epsilonCheck(int a, int b, int epsilon) {
+ return a > b - epsilon && a < b + epsilon;
+ }
+ };
+ orientationEventListener.enable();
+ }
+ }
}
if (postTitle != null) {
- setTitle(Html.fromHtml(String.format("<small>%s</small>", postTitle)));
+ if (useBottomAppBar) {
+ titleTextView.setText(Html.fromHtml(String.format("<small>%s</small>", postTitle)));
+ } else {
+ setTitle(Html.fromHtml(String.format("<small>%s</small>", postTitle)));
+ }
} else {
- setTitle("");
+ if (!useBottomAppBar) {
+ setTitle("");
+ }
}
videoPlayerView.setControllerVisibilityListener(visibility -> {
@@ -284,8 +373,9 @@ public class ViewVideoActivity extends AppCompatActivity {
loadGfycatOrRedgifsVideo(redgifsRetrofit, gfycatId, savedInstanceState, false);
}
} else {
- dataSourceFactory = new DefaultDataSourceFactory(ViewVideoActivity.this,
- Util.getUserAgent(ViewVideoActivity.this, "Infinity"));
+ dataSourceFactory = new CacheDataSourceFactory(mSimpleCache,
+ new DefaultDataSourceFactory(ViewVideoActivity.this,
+ Util.getUserAgent(ViewVideoActivity.this, "Infinity")));
player.prepare(new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mVideoUri));
preparePlayer(savedInstanceState);
}
@@ -293,7 +383,8 @@ public class ViewVideoActivity extends AppCompatActivity {
videoDownloadUrl = mVideoUri.toString();
videoFileName = FilenameUtils.getName(videoDownloadUrl);
// Produces DataSource instances through which media data is loaded.
- dataSourceFactory = new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "Infinity"));
+ dataSourceFactory = new CacheDataSourceFactory(mSimpleCache,
+ new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "Infinity")));
// Prepare the player with the source.
player.prepare(new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mVideoUri));
preparePlayer(savedInstanceState);
@@ -303,7 +394,8 @@ public class ViewVideoActivity extends AppCompatActivity {
id = intent.getStringExtra(EXTRA_ID);
videoFileName = subredditName + "-" + id + ".mp4";
// Produces DataSource instances through which media data is loaded.
- dataSourceFactory = new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "Infinity"));
+ dataSourceFactory = new CacheDataSourceFactory(mSimpleCache,
+ new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "Infinity")));
// Prepare the player with the source.
player.prepare(new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(mVideoUri));
preparePlayer(savedInstanceState);
@@ -385,15 +477,16 @@ public class ViewVideoActivity extends AppCompatActivity {
private void loadGfycatOrRedgifsVideo(Retrofit retrofit, String gfycatId, Bundle savedInstanceState, boolean needErrorHandling) {
progressBar.setVisibility(View.VISIBLE);
- FetchGfycatOrRedgifsVideoLinks.fetchGfycatOrRedgifsVideoLinks(retrofit, gfycatId,
+ FetchGfycatOrRedgifsVideoLinks.fetchGfycatOrRedgifsVideoLinks(mExecutor, new Handler(), retrofit, gfycatId,
new FetchGfycatOrRedgifsVideoLinks.FetchGfycatOrRedgifsVideoLinksListener() {
@Override
public void success(String webm, String mp4) {
progressBar.setVisibility(View.GONE);
mVideoUri = Uri.parse(webm);
videoDownloadUrl = mp4;
- dataSourceFactory = new DefaultDataSourceFactory(ViewVideoActivity.this,
- Util.getUserAgent(ViewVideoActivity.this, "Infinity"));
+ dataSourceFactory = new CacheDataSourceFactory(mSimpleCache,
+ new DefaultDataSourceFactory(ViewVideoActivity.this,
+ Util.getUserAgent(ViewVideoActivity.this, "Infinity")));
player.prepare(new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mVideoUri));
preparePlayer(savedInstanceState);
}
@@ -430,54 +523,58 @@ public class ViewVideoActivity extends AppCompatActivity {
List<String> segments = redirectUri.getPathSegments();
int commentsIndex = segments.lastIndexOf("comments");
String postId = segments.get(commentsIndex + 1);
- FetchPost.fetchPost(retrofit, postId, null, new FetchPost.FetchPostListener() {
- @Override
- public void fetchPostSuccess(Post post) {
- if (post.isGfycat()) {
- videoType = VIDEO_TYPE_GFYCAT;
- String gfycatId = post.getGfycatId();
- if (gfycatId != null && gfycatId.contains("-")) {
- gfycatId = gfycatId.substring(0, gfycatId.indexOf('-'));
+ FetchPost.fetchPost(mExecutor, new Handler(), retrofit, postId, null,
+ new FetchPost.FetchPostListener() {
+ @Override
+ public void fetchPostSuccess(Post post) {
+ if (post.isGfycat()) {
+ videoType = VIDEO_TYPE_GFYCAT;
+ String gfycatId = post.getGfycatId();
+ if (gfycatId != null && gfycatId.contains("-")) {
+ gfycatId = gfycatId.substring(0, gfycatId.indexOf('-'));
+ }
+ if (videoType == VIDEO_TYPE_GFYCAT) {
+ videoFileName = "Gfycat-" + gfycatId + ".mp4";
+ } else {
+ videoFileName = "Redgifs-" + gfycatId + ".mp4";
+ }
+ loadGfycatOrRedgifsVideo(gfycatRetrofit, gfycatId, savedInstanceState, true);
+ } else if (post.isRedgifs()) {
+ videoType = VIDEO_TYPE_REDGIFS;
+ String gfycatId = post.getGfycatId();
+ if (gfycatId != null && gfycatId.contains("-")) {
+ gfycatId = gfycatId.substring(0, gfycatId.indexOf('-'));
+ }
+ if (videoType == VIDEO_TYPE_GFYCAT) {
+ videoFileName = "Gfycat-" + gfycatId + ".mp4";
+ } else {
+ videoFileName = "Redgifs-" + gfycatId + ".mp4";
+ }
+ loadGfycatOrRedgifsVideo(redgifsRetrofit, gfycatId, savedInstanceState, false);
+ } else {
+ progressBar.setVisibility(View.INVISIBLE);
+ mVideoUri = Uri.parse(post.getVideoUrl());
+ subredditName = post.getSubredditName();
+ id = post.getId();
+ videoDownloadUrl = post.getVideoDownloadUrl();
+
+ videoFileName = subredditName + "-" + id + ".mp4";
+ // Produces DataSource instances through which media data is loaded.
+ dataSourceFactory = new CacheDataSourceFactory(mSimpleCache,
+ new DefaultHttpDataSourceFactory(
+ Util.getUserAgent(ViewVideoActivity.this,
+ "Infinity")));
+ // Prepare the player with the source.
+ player.prepare(new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(mVideoUri));
+ preparePlayer(savedInstanceState);
+ }
}
- if (videoType == VIDEO_TYPE_GFYCAT) {
- videoFileName = "Gfycat-" + gfycatId + ".mp4";
- } else {
- videoFileName = "Redgifs-" + gfycatId + ".mp4";
- }
- loadGfycatOrRedgifsVideo(gfycatRetrofit, gfycatId, savedInstanceState, true);
- } else if (post.isRedgifs()) {
- videoType = VIDEO_TYPE_REDGIFS;
- String gfycatId = post.getGfycatId();
- if (gfycatId != null && gfycatId.contains("-")) {
- gfycatId = gfycatId.substring(0, gfycatId.indexOf('-'));
- }
- if (videoType == VIDEO_TYPE_GFYCAT) {
- videoFileName = "Gfycat-" + gfycatId + ".mp4";
- } else {
- videoFileName = "Redgifs-" + gfycatId + ".mp4";
- }
- loadGfycatOrRedgifsVideo(redgifsRetrofit, gfycatId, savedInstanceState, false);
- } else {
- progressBar.setVisibility(View.INVISIBLE);
- mVideoUri = Uri.parse(post.getVideoUrl());
- subredditName = post.getSubredditName();
- id = post.getId();
- videoDownloadUrl = post.getVideoDownloadUrl();
-
- videoFileName = subredditName + "-" + id + ".mp4";
- // Produces DataSource instances through which media data is loaded.
- dataSourceFactory = new DefaultHttpDataSourceFactory(Util.getUserAgent(ViewVideoActivity.this, "Infinity"));
- // Prepare the player with the source.
- player.prepare(new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(mVideoUri));
- preparePlayer(savedInstanceState);
- }
- }
- @Override
- public void fetchPostFailed() {
- Toast.makeText(ViewVideoActivity.this, R.string.error_fetching_v_redd_it_video_cannot_get_post, Toast.LENGTH_LONG).show();
- }
- });
+ @Override
+ public void fetchPostFailed() {
+ Toast.makeText(ViewVideoActivity.this, R.string.error_fetching_v_redd_it_video_cannot_get_post, Toast.LENGTH_LONG).show();
+ }
+ });
} else {
Toast.makeText(ViewVideoActivity.this, R.string.error_fetching_v_redd_it_video_cannot_get_post_id, Toast.LENGTH_LONG).show();
}
@@ -521,29 +618,33 @@ public class ViewVideoActivity extends AppCompatActivity {
}
isDownloading = true;
- 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();
- }
- } else {
- download();
- }
+ requestPermissionAndDownload();
return true;
}
return false;
}
+ private void requestPermissionAndDownload() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ 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();
+ }
+ } else {
+ download();
+ }
+ }
+
@Override
protected void onStart() {
super.onStart();
@@ -557,6 +658,9 @@ public class ViewVideoActivity extends AppCompatActivity {
super.onStop();
wasPlaying = player.getPlayWhenReady();
player.setPlayWhenReady(false);
+ if (originalOrientation != null) {
+ setRequestedOrientation(originalOrientation);
+ }
}
@Override
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/activities/WikiActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/WikiActivity.java
new file mode 100644
index 00000000..f4cc17fa
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/activities/WikiActivity.java
@@ -0,0 +1,370 @@
+package ml.docilealligator.infinityforreddit.activities;
+
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.graphics.Color;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.text.SpannableStringBuilder;
+import android.text.Spanned;
+import android.text.TextPaint;
+import android.text.style.ClickableSpan;
+import android.text.util.Linkify;
+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 androidx.annotation.NonNull;
+import androidx.appcompat.widget.Toolbar;
+import androidx.coordinatorlayout.widget.CoordinatorLayout;
+import androidx.recyclerview.widget.RecyclerView;
+import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
+
+import com.bumptech.glide.Glide;
+import com.google.android.material.appbar.AppBarLayout;
+import com.r0adkll.slidr.Slidr;
+import com.r0adkll.slidr.model.SlidrInterface;
+
+import org.commonmark.ext.gfm.tables.TableBlock;
+import org.greenrobot.eventbus.EventBus;
+import org.greenrobot.eventbus.Subscribe;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import io.noties.markwon.AbstractMarkwonPlugin;
+import io.noties.markwon.Markwon;
+import io.noties.markwon.MarkwonConfiguration;
+import io.noties.markwon.core.MarkwonTheme;
+import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
+import io.noties.markwon.html.HtmlPlugin;
+import io.noties.markwon.linkify.LinkifyPlugin;
+import io.noties.markwon.recycler.MarkwonAdapter;
+import io.noties.markwon.recycler.table.TableEntry;
+import io.noties.markwon.recycler.table.TableEntryPlugin;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
+import ml.docilealligator.infinityforreddit.customviews.MarkwonLinearLayoutManager;
+import ml.docilealligator.infinityforreddit.events.SwitchAccountEvent;
+import ml.docilealligator.infinityforreddit.utils.JSONUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+
+public class WikiActivity extends BaseActivity {
+
+ public static final String EXTRA_SUBREDDIT_NAME = "ESN";
+ private static final String WIKI_MARKDOWN_STATE = "WMS";
+
+ @BindView(R.id.coordinator_layout_comment_wiki_activity)
+ CoordinatorLayout coordinatorLayout;
+ @BindView(R.id.appbar_layout_comment_wiki_activity)
+ AppBarLayout appBarLayout;
+ @BindView(R.id.toolbar_comment_wiki_activity)
+ Toolbar toolbar;
+ @BindView(R.id.swipe_refresh_layout_wiki_activity)
+ SwipeRefreshLayout swipeRefreshLayout;
+ @BindView(R.id.content_markdown_view_comment_wiki_activity)
+ RecyclerView markdownRecyclerView;
+ @BindView(R.id.fetch_wiki_linear_layout_wiki_activity)
+ LinearLayout mFetchWikiInfoLinearLayout;
+ @BindView(R.id.fetch_wiki_image_view_wiki_activity)
+ ImageView mFetchWikiInfoImageView;
+ @BindView(R.id.fetch_wiki_text_view_wiki_activity)
+ TextView mFetchWikiInfoTextView;
+
+ @Inject
+ @Named("no_oauth")
+ Retrofit retrofit;
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ CustomThemeWrapper mCustomThemeWrapper;
+ private SlidrInterface mSlidrInterface;
+ private String wikiMarkdown;
+ private Markwon markwon;
+ private MarkwonAdapter markwonAdapter;
+ private boolean isRefreshing = false;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ ((Infinity) getApplication()).getAppComponent().inject(this);
+
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_wiki);
+
+ ButterKnife.bind(this);
+
+ EventBus.getDefault().register(this);
+
+ applyCustomTheme();
+
+ setSupportActionBar(toolbar);
+ getSupportActionBar().setDisplayHomeAsUpEnabled(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();
+
+ if (isChangeStatusBarIconColor()) {
+ addOnOffsetChangedListener(appBarLayout);
+ }
+
+ if (isImmersiveInterface()) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ coordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
+ View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
+ View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
+ } else {
+ window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
+ }
+ adjustToolbar(toolbar);
+ markdownRecyclerView.setPadding(markdownRecyclerView.getPaddingLeft(), 0, markdownRecyclerView.getPaddingRight(), getNavBarHeight());
+ }
+ }
+
+ swipeRefreshLayout.setEnabled(mSharedPreferences.getBoolean(SharedPreferencesUtils.PULL_TO_REFRESH, true));
+ swipeRefreshLayout.setOnRefreshListener(this::loadWiki);
+
+ int markdownColor = mCustomThemeWrapper.getPrimaryTextColor();
+ int spoilerBackgroundColor = markdownColor | 0xFF000000;
+ int linkColor = mCustomThemeWrapper.getLinkColor();
+ markwon = Markwon.builder(this)
+ .usePlugin(HtmlPlugin.create())
+ .usePlugin(new AbstractMarkwonPlugin() {
+ @NonNull
+ @Override
+ public String processMarkdown(@NonNull String markdown) {
+ StringBuilder markdownStringBuilder = new StringBuilder(markdown);
+ Pattern spoilerPattern = Pattern.compile(">![\\S\\s]*?!<");
+ Matcher matcher = spoilerPattern.matcher(markdownStringBuilder);
+ while (matcher.find()) {
+ markdownStringBuilder.replace(matcher.start(), matcher.start() + 1, "&gt;");
+ }
+ return super.processMarkdown(markdownStringBuilder.toString());
+ }
+
+ @Override
+ public void afterSetText(@NonNull TextView textView) {
+ textView.setHighlightColor(Color.TRANSPARENT);
+ SpannableStringBuilder markdownStringBuilder = new SpannableStringBuilder(textView.getText().toString());
+ Pattern spoilerPattern = Pattern.compile(">![\\S\\s]*?!<");
+ Matcher matcher = spoilerPattern.matcher(markdownStringBuilder);
+ int start = 0;
+ boolean find = false;
+ while (matcher.find(start)) {
+ if (markdownStringBuilder.length() < 4
+ || matcher.start() < 0
+ || matcher.end() > markdownStringBuilder.length()) {
+ break;
+ }
+ find = true;
+ markdownStringBuilder.delete(matcher.end() - 2, matcher.end());
+ markdownStringBuilder.delete(matcher.start(), matcher.start() + 2);
+ ClickableSpan clickableSpan = new ClickableSpan() {
+ private boolean isShowing = false;
+ @Override
+ public void updateDrawState(@NonNull TextPaint ds) {
+ if (isShowing) {
+ super.updateDrawState(ds);
+ ds.setColor(markdownColor);
+ } else {
+ ds.bgColor = spoilerBackgroundColor;
+ ds.setColor(markdownColor);
+ }
+ ds.setUnderlineText(false);
+ }
+
+ @Override
+ public void onClick(@NonNull View view) {
+ isShowing = !isShowing;
+ view.invalidate();
+ }
+ };
+ markdownStringBuilder.setSpan(clickableSpan, matcher.start(), matcher.end() - 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+ start = matcher.end() - 4;
+ }
+ if (find) {
+ textView.setText(markdownStringBuilder);
+ }
+ }
+
+ @Override
+ public void beforeSetText(@NonNull TextView textView, @NonNull Spanned markdown) {
+ textView.setTextColor(markdownColor);
+ }
+
+ @Override
+ public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
+ builder.linkResolver((view, link) -> {
+ Intent intent = new Intent(WikiActivity.this, LinkResolverActivity.class);
+ Uri uri = Uri.parse(link);
+ intent.setData(uri);
+ startActivity(intent);
+ });
+ }
+
+ @Override
+ public void configureTheme(@NonNull MarkwonTheme.Builder builder) {
+ builder.linkColor(linkColor);
+ }
+ })
+ .usePlugin(StrikethroughPlugin.create())
+ .usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
+ .usePlugin(TableEntryPlugin.create(this))
+ .build();
+
+ markwonAdapter = MarkwonAdapter.builder(R.layout.adapter_default_entry, R.id.text)
+ .include(TableBlock.class, TableEntry.create(builder -> builder
+ .tableLayout(R.layout.adapter_table_block, R.id.table_layout)
+ .textLayoutIsRoot(R.layout.view_table_entry_cell)))
+ .build();
+ LinearLayoutManagerBugFixed linearLayoutManager = new MarkwonLinearLayoutManager(this, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
+ @Override
+ public void onScrolledLeft() {
+ if (mSlidrInterface != null) {
+ mSlidrInterface.lock();
+ }
+ }
+
+ @Override
+ public void onScrolledRight() {
+ if (mSlidrInterface != null) {
+ mSlidrInterface.unlock();
+ }
+ }
+ });
+ markdownRecyclerView.setLayoutManager(linearLayoutManager);
+ markdownRecyclerView.setAdapter(markwonAdapter);
+
+ if (savedInstanceState != null) {
+ wikiMarkdown = savedInstanceState.getString(WIKI_MARKDOWN_STATE);
+ }
+
+ if (wikiMarkdown == null) {
+ loadWiki();
+ } else {
+ markwonAdapter.setMarkdown(markwon, wikiMarkdown);
+ markwonAdapter.notifyDataSetChanged();
+ }
+ }
+
+ private void loadWiki() {
+ if (isRefreshing) {
+ return;
+ }
+ isRefreshing = true;
+
+ swipeRefreshLayout.setRefreshing(true);
+
+ Glide.with(this).clear(mFetchWikiInfoImageView);
+ mFetchWikiInfoLinearLayout.setVisibility(View.GONE);
+
+ retrofit.create(RedditAPI.class).getWiki(getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME)).enqueue(new Callback<String>() {
+ @Override
+ public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
+ if (response.isSuccessful()) {
+ try {
+ markwonAdapter.setMarkdown(markwon, new JSONObject(response.body())
+ .getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.CONTENT_MD_KEY));
+ markwonAdapter.notifyDataSetChanged();
+ } catch (JSONException e) {
+ e.printStackTrace();
+ showErrorView(R.string.error_loading_wiki);
+ }
+ } else {
+ if (response.code() == 404 || response.code() == 403) {
+ showErrorView(R.string.no_wiki);
+ } else {
+ showErrorView(R.string.error_loading_wiki);
+ }
+ }
+ isRefreshing = false;
+ swipeRefreshLayout.setRefreshing(false);
+ }
+
+ @Override
+ public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
+ showErrorView(R.string.error_loading_wiki);
+ isRefreshing = false;
+ swipeRefreshLayout.setRefreshing(false);
+ }
+ });
+ }
+
+ private void showErrorView(int stringResId) {
+ swipeRefreshLayout.setRefreshing(false);
+ mFetchWikiInfoLinearLayout.setVisibility(View.VISIBLE);
+ mFetchWikiInfoTextView.setText(stringResId);
+ Glide.with(this).load(R.drawable.error_image).into(mFetchWikiInfoImageView);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(@NonNull MenuItem item) {
+ if (item.getItemId() == android.R.id.home) {
+ finish();
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ protected void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString(WIKI_MARKDOWN_STATE, wikiMarkdown);
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ EventBus.getDefault().unregister(this);
+ }
+
+ @Override
+ protected SharedPreferences getDefaultSharedPreferences() {
+ return mSharedPreferences;
+ }
+
+ @Override
+ protected CustomThemeWrapper getCustomThemeWrapper() {
+ return mCustomThemeWrapper;
+ }
+
+ @Override
+ protected void applyCustomTheme() {
+ coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
+ applyAppBarLayoutAndToolbarTheme(appBarLayout, toolbar);
+ swipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
+ swipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
+ mFetchWikiInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
+ }
+
+ @Subscribe
+ public void onAccountSwitchEvent(SwitchAccountEvent event) {
+ if (!getClass().getName().equals(event.excludeActivityClassName)) {
+ finish();
+ }
+ }
+} \ No newline at end of file
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsListingRecyclerViewAdapter.java
index f3a9c582..15dce401 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsListingRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsListingRecyclerViewAdapter.java
@@ -16,6 +16,7 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
+import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
@@ -400,6 +401,8 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
public class CommentViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.vertical_block_indentation_item_comment)
CommentIndentationView commentIndentationView;
+ @BindView(R.id.linear_layout_item_comment)
+ LinearLayout linearLayout;
@BindView(R.id.author_text_view_item_post_comment)
TextView authorTextView;
@BindView(R.id.author_flair_text_view_item_post_comment)
@@ -455,6 +458,8 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
constraintSet.applyTo(bottomConstraintLayout);
}
+ linearLayout.getLayoutTransition().setAnimateParentHierarchy(false);
+
commentIndentationView.setVisibility(View.GONE);
if (mShowCommentDivider) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsRecyclerViewAdapter.java
new file mode 100644
index 00000000..14f53a2d
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentsRecyclerViewAdapter.java
@@ -0,0 +1,1715 @@
+package ml.docilealligator.infinityforreddit.adapters;
+
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.res.ColorStateList;
+import android.graphics.Color;
+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;
+import android.text.style.ClickableSpan;
+import android.text.util.Linkify;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.ProgressBar;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.constraintlayout.widget.ConstraintLayout;
+import androidx.constraintlayout.widget.ConstraintSet;
+import androidx.core.graphics.drawable.DrawableCompat;
+import androidx.recyclerview.widget.ItemTouchHelper;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
+
+import java.util.ArrayList;
+import java.util.Locale;
+import java.util.concurrent.Executor;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import io.noties.markwon.AbstractMarkwonPlugin;
+import io.noties.markwon.Markwon;
+import io.noties.markwon.MarkwonConfiguration;
+import io.noties.markwon.core.MarkwonTheme;
+import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
+import io.noties.markwon.html.HtmlPlugin;
+import io.noties.markwon.linkify.LinkifyPlugin;
+import io.noties.markwon.movement.MovementMethodPlugin;
+import me.saket.bettermovementmethod.BetterLinkMovementMethod;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.SaveThing;
+import ml.docilealligator.infinityforreddit.VoteThing;
+import ml.docilealligator.infinityforreddit.activities.CommentActivity;
+import ml.docilealligator.infinityforreddit.activities.LinkResolverActivity;
+import ml.docilealligator.infinityforreddit.activities.ViewPostDetailActivity;
+import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.CommentMoreBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.UrlMenuBottomSheetFragment;
+import ml.docilealligator.infinityforreddit.comment.Comment;
+import ml.docilealligator.infinityforreddit.comment.FetchComment;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.CommentIndentationView;
+import ml.docilealligator.infinityforreddit.fragments.ViewPostDetailFragment;
+import ml.docilealligator.infinityforreddit.post.Post;
+import ml.docilealligator.infinityforreddit.utils.APIUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import ml.docilealligator.infinityforreddit.utils.Utils;
+import retrofit2.Retrofit;
+
+public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+ private static final int VIEW_TYPE_FIRST_LOADING = 9;
+ private static final int VIEW_TYPE_FIRST_LOADING_FAILED = 10;
+ private static final int VIEW_TYPE_NO_COMMENT_PLACEHOLDER = 11;
+ private static final int VIEW_TYPE_COMMENT = 12;
+ private static final int VIEW_TYPE_COMMENT_FULLY_COLLAPSED = 13;
+ private static final int VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS = 14;
+ private static final int VIEW_TYPE_IS_LOADING_MORE_COMMENTS = 15;
+ private static final int VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED = 16;
+ 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 Markwon mCommentMarkwon;
+ private String mAccessToken;
+ private String mAccountName;
+ private Post mPost;
+ private ArrayList<Comment> mVisibleComments;
+ private Locale mLocale;
+ private String mSingleCommentId;
+ private boolean mIsSingleCommentThreadMode;
+ private boolean mVoteButtonsOnTheRight;
+ private boolean mShowElapsedTime;
+ private String mTimeFormatPattern;
+ private boolean mExpandChildren;
+ private boolean mCommentToolbarHidden;
+ private boolean mCommentToolbarHideOnClick;
+ private boolean mSwapTapAndLong;
+ private boolean mShowCommentDivider;
+ private boolean mShowAbsoluteNumberOfVotes;
+ private boolean mFullyCollapseComment;
+ private boolean mShowOnlyOneCommentLevelIndicator;
+ private CommentRecyclerViewAdapterCallback mCommentRecyclerViewAdapterCallback;
+ private boolean isInitiallyLoading;
+ private boolean isInitiallyLoadingFailed;
+ private boolean mHasMoreComments;
+ private boolean loadMoreCommentsFailed;
+
+ private int depthThreshold = 5;
+ private int mColorPrimaryLightTheme;
+ private int mColorAccent;
+ private int mCircularProgressBarBackgroundColor;
+ private int mSecondaryTextColor;
+ private int mPrimaryTextColor;
+ private int mCommentTextColor;
+ private int mCommentBackgroundColor;
+ private int mDividerColor;
+ private int mUsernameColor;
+ private int mSubmitterColor;
+ private int mModeratorColor;
+ private int mCurrentUserColor;
+ private int mAuthorFlairTextColor;
+ private int mUpvotedColor;
+ private int mDownvotedColor;
+ private int mSingleCommentThreadBackgroundColor;
+ private int mVoteAndReplyUnavailableVoteButtonColor;
+ private int mButtonTextColor;
+ private int mPostIconAndInfoColor;
+ private int mCommentIconAndInfoColor;
+ private int mFullyCollapsedCommentBackgroundColor;
+ private int mAwardedCommentBackgroundColor;
+ private Integer[] verticalBlockColors;
+
+ private Drawable mCommentIcon;
+
+ private int mSearchCommentIndex = -1;
+
+ public CommentsRecyclerViewAdapter(AppCompatActivity activity, ViewPostDetailFragment fragment,
+ CustomThemeWrapper customThemeWrapper,
+ Executor executor, Retrofit retrofit, Retrofit oauthRetrofit,
+ String accessToken, String accountName,
+ Post post, Locale locale, String singleCommentId,
+ boolean isSingleCommentThreadMode,
+ SharedPreferences sharedPreferences,
+ CommentRecyclerViewAdapterCallback commentRecyclerViewAdapterCallback) {
+ mActivity = activity;
+ mFragment = fragment;
+ mExecutor = executor;
+ mRetrofit = retrofit;
+ mOauthRetrofit = oauthRetrofit;
+ mSecondaryTextColor = customThemeWrapper.getSecondaryTextColor();
+ mCommentTextColor = customThemeWrapper.getCommentColor();
+ int commentSpoilerBackgroundColor = mCommentTextColor | 0xFF000000;
+ int linkColor = customThemeWrapper.getLinkColor();
+ mCommentMarkwon = Markwon.builder(mActivity)
+ .usePlugin(HtmlPlugin.create())
+ .usePlugin(new AbstractMarkwonPlugin() {
+ @NonNull
+ @Override
+ public String processMarkdown(@NonNull String markdown) {
+ StringBuilder markdownStringBuilder = new StringBuilder(markdown);
+ Pattern spoilerPattern = Pattern.compile(">![\\S\\s]*?!<");
+ Matcher matcher = spoilerPattern.matcher(markdownStringBuilder);
+ while (matcher.find()) {
+ markdownStringBuilder.replace(matcher.start(), matcher.start() + 1, "&gt;");
+ }
+ return super.processMarkdown(markdownStringBuilder.toString());
+ }
+
+ @Override
+ public void afterSetText(@NonNull TextView textView) {
+ SpannableStringBuilder markdownStringBuilder = new SpannableStringBuilder(textView.getText().toString());
+ Pattern spoilerPattern = Pattern.compile(">![\\S\\s]*?!<");
+ Matcher matcher = spoilerPattern.matcher(markdownStringBuilder);
+ int start = 0;
+ boolean find = false;
+ while (matcher.find(start)) {
+ if (markdownStringBuilder.length() < 4
+ || matcher.start() < 0
+ || matcher.end() > markdownStringBuilder.length()) {
+ break;
+ }
+ find = true;
+ markdownStringBuilder.delete(matcher.end() - 2, matcher.end());
+ markdownStringBuilder.delete(matcher.start(), matcher.start() + 2);
+ ClickableSpan clickableSpan = new ClickableSpan() {
+ private boolean isShowing = false;
+ @Override
+ public void updateDrawState(@NonNull TextPaint ds) {
+ if (isShowing) {
+ super.updateDrawState(ds);
+ ds.setColor(mCommentTextColor);
+ } else {
+ ds.bgColor = commentSpoilerBackgroundColor;
+ ds.setColor(mCommentTextColor);
+ }
+ ds.setUnderlineText(false);
+ }
+
+ @Override
+ public void onClick(@NonNull View view) {
+ isShowing = !isShowing;
+ view.invalidate();
+ }
+ };
+ markdownStringBuilder.setSpan(clickableSpan, matcher.start(), matcher.end() - 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+ start = matcher.end() - 4;
+ }
+ if (find) {
+ textView.setText(markdownStringBuilder);
+ }
+ }
+
+ @Override
+ public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
+ builder.linkResolver((view, link) -> {
+ Intent intent = new Intent(mActivity, LinkResolverActivity.class);
+ Uri uri = Uri.parse(link);
+ intent.setData(uri);
+ intent.putExtra(LinkResolverActivity.EXTRA_IS_NSFW, mPost.isNSFW());
+ mActivity.startActivity(intent);
+ });
+ }
+
+ @Override
+ public void configureTheme(@NonNull MarkwonTheme.Builder builder) {
+ builder.linkColor(linkColor);
+ }
+ })
+ .usePlugin(StrikethroughPlugin.create())
+ .usePlugin(MovementMethodPlugin.create(BetterLinkMovementMethod.linkify(Linkify.WEB_URLS, activity).setOnLinkLongClickListener((textView, url) -> {
+ if (!activity.isDestroyed() && !activity.isFinishing()) {
+ UrlMenuBottomSheetFragment urlMenuBottomSheetFragment = new UrlMenuBottomSheetFragment();
+ Bundle bundle = new Bundle();
+ bundle.putString(UrlMenuBottomSheetFragment.EXTRA_URL, url);
+ urlMenuBottomSheetFragment.setArguments(bundle);
+ urlMenuBottomSheetFragment.show(activity.getSupportFragmentManager(), urlMenuBottomSheetFragment.getTag());
+ }
+ return true;
+ })))
+ .usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
+ .build();
+ mAccessToken = accessToken;
+ mAccountName = accountName;
+ mPost = post;
+ mVisibleComments = new ArrayList<>();
+ mLocale = locale;
+ mSingleCommentId = singleCommentId;
+ mIsSingleCommentThreadMode = isSingleCommentThreadMode;
+
+ mVoteButtonsOnTheRight = sharedPreferences.getBoolean(SharedPreferencesUtils.VOTE_BUTTONS_ON_THE_RIGHT_KEY, false);
+ mShowElapsedTime = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_ELAPSED_TIME_KEY, false);
+ mTimeFormatPattern = sharedPreferences.getString(SharedPreferencesUtils.TIME_FORMAT_KEY, SharedPreferencesUtils.TIME_FORMAT_DEFAULT_VALUE);
+ mExpandChildren = !sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_TOP_LEVEL_COMMENTS_FIRST, false);
+ mCommentToolbarHidden = sharedPreferences.getBoolean(SharedPreferencesUtils.COMMENT_TOOLBAR_HIDDEN, false);
+ mCommentToolbarHideOnClick = sharedPreferences.getBoolean(SharedPreferencesUtils.COMMENT_TOOLBAR_HIDE_ON_CLICK, true);
+ mSwapTapAndLong = sharedPreferences.getBoolean(SharedPreferencesUtils.SWAP_TAP_AND_LONG_COMMENTS, false);
+ mShowCommentDivider = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_COMMENT_DIVIDER, false);
+ mShowAbsoluteNumberOfVotes = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_ABSOLUTE_NUMBER_OF_VOTES, true);
+
+ mFullyCollapseComment = sharedPreferences.getBoolean(SharedPreferencesUtils.FULLY_COLLAPSE_COMMENT, false);
+
+ mShowOnlyOneCommentLevelIndicator = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_ONLY_ONE_COMMENT_LEVEL_INDICATOR, false);
+
+ mCommentRecyclerViewAdapterCallback = commentRecyclerViewAdapterCallback;
+ isInitiallyLoading = true;
+ isInitiallyLoadingFailed = false;
+ mHasMoreComments = false;
+ loadMoreCommentsFailed = false;
+
+ mColorPrimaryLightTheme = customThemeWrapper.getColorPrimaryLightTheme();
+ mColorAccent = customThemeWrapper.getColorAccent();
+ mCircularProgressBarBackgroundColor = customThemeWrapper.getCircularProgressBarBackground();
+ mPrimaryTextColor = customThemeWrapper.getPrimaryTextColor();
+ mDividerColor = customThemeWrapper.getDividerColor();
+ mCommentBackgroundColor = customThemeWrapper.getCommentBackgroundColor();
+ mSubmitterColor = customThemeWrapper.getSubmitter();
+ mModeratorColor = customThemeWrapper.getModerator();
+ mCurrentUserColor = customThemeWrapper.getCurrentUser();
+ mAuthorFlairTextColor = customThemeWrapper.getAuthorFlairTextColor();
+ mUsernameColor = customThemeWrapper.getUsername();
+ mUpvotedColor = customThemeWrapper.getUpvoted();
+ mDownvotedColor = customThemeWrapper.getDownvoted();
+ mSingleCommentThreadBackgroundColor = customThemeWrapper.getSingleCommentThreadBackgroundColor();
+ mVoteAndReplyUnavailableVoteButtonColor = customThemeWrapper.getVoteAndReplyUnavailableButtonColor();
+ mButtonTextColor = customThemeWrapper.getButtonTextColor();
+ mPostIconAndInfoColor = customThemeWrapper.getPostIconAndInfoColor();
+ mCommentIconAndInfoColor = customThemeWrapper.getCommentIconAndInfoColor();
+ mFullyCollapsedCommentBackgroundColor = customThemeWrapper.getFullyCollapsedCommentBackgroundColor();
+ mAwardedCommentBackgroundColor = customThemeWrapper.getAwardedCommentBackgroundColor();
+
+ verticalBlockColors = new Integer[] {
+ customThemeWrapper.getCommentVerticalBarColor1(),
+ customThemeWrapper.getCommentVerticalBarColor2(),
+ customThemeWrapper.getCommentVerticalBarColor3(),
+ customThemeWrapper.getCommentVerticalBarColor4(),
+ customThemeWrapper.getCommentVerticalBarColor5(),
+ customThemeWrapper.getCommentVerticalBarColor6(),
+ customThemeWrapper.getCommentVerticalBarColor7(),
+ };
+
+ mCommentIcon = activity.getDrawable(R.drawable.ic_comment_grey_24dp);
+ if (mCommentIcon != null) {
+ DrawableCompat.setTint(mCommentIcon, mPostIconAndInfoColor);
+ }
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ if (mVisibleComments.size() == 0) {
+ if (isInitiallyLoading) {
+ return VIEW_TYPE_FIRST_LOADING;
+ } else if (isInitiallyLoadingFailed) {
+ return VIEW_TYPE_FIRST_LOADING_FAILED;
+ } else {
+ return VIEW_TYPE_NO_COMMENT_PLACEHOLDER;
+ }
+ }
+
+ if (mIsSingleCommentThreadMode) {
+ if (position == 0) {
+ return VIEW_TYPE_VIEW_ALL_COMMENTS;
+ }
+
+ if (position == mVisibleComments.size() + 1) {
+ if (mHasMoreComments) {
+ return VIEW_TYPE_IS_LOADING_MORE_COMMENTS;
+ } else {
+ return VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED;
+ }
+ }
+
+ Comment comment = mVisibleComments.get(position - 1);
+ if (comment.getPlaceholderType() == Comment.NOT_PLACEHOLDER) {
+ if (mFullyCollapseComment && !comment.isExpanded() && comment.hasExpandedBefore()) {
+ return VIEW_TYPE_COMMENT_FULLY_COLLAPSED;
+ }
+ return VIEW_TYPE_COMMENT;
+ } else {
+ return VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS;
+ }
+ } else {
+ if (position == mVisibleComments.size()) {
+ if (mHasMoreComments) {
+ return VIEW_TYPE_IS_LOADING_MORE_COMMENTS;
+ } else {
+ return VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED;
+ }
+ }
+
+ Comment comment = mVisibleComments.get(position);
+ if (comment.getPlaceholderType() == Comment.NOT_PLACEHOLDER) {
+ if (mFullyCollapseComment && !comment.isExpanded() && comment.hasExpandedBefore()) {
+ return VIEW_TYPE_COMMENT_FULLY_COLLAPSED;
+ }
+ return VIEW_TYPE_COMMENT;
+ } else {
+ return VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS;
+ }
+ }
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ switch (viewType) {
+ case VIEW_TYPE_FIRST_LOADING:
+ return new LoadCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_comments, parent, false));
+ case VIEW_TYPE_FIRST_LOADING_FAILED:
+ return new LoadCommentsFailedViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_comments_failed_placeholder, parent, false));
+ case VIEW_TYPE_NO_COMMENT_PLACEHOLDER:
+ return new NoCommentViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_no_comment_placeholder, parent, false));
+ case VIEW_TYPE_COMMENT:
+ return new CommentViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false));
+ case VIEW_TYPE_COMMENT_FULLY_COLLAPSED:
+ return new CommentFullyCollapsedViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_fully_collapsed, parent, false));
+ case VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS:
+ return new LoadMoreChildCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_more_comments_placeholder, parent, false));
+ case VIEW_TYPE_IS_LOADING_MORE_COMMENTS:
+ return new IsLoadingMoreCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_footer_loading, parent, false));
+ case VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED:
+ return new LoadMoreCommentsFailedViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_footer_error, parent, false));
+ default:
+ return new ViewAllCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_all_comments, parent, false));
+ }
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ if (holder instanceof CommentViewHolder) {
+ Comment comment = getCurrentComment(position);
+ if (comment != null) {
+ if (mIsSingleCommentThreadMode && comment.getId().equals(mSingleCommentId)) {
+ holder.itemView.setBackgroundColor(mSingleCommentThreadBackgroundColor);
+ } else if (comment.getAwards() != null && !comment.getAwards().equals("")) {
+ holder.itemView.setBackgroundColor(mAwardedCommentBackgroundColor);
+ }
+
+ String authorPrefixed = "u/" + comment.getAuthor();
+ ((CommentViewHolder) holder).authorTextView.setText(authorPrefixed);
+
+ if (comment.getAuthorFlairHTML() != null && !comment.getAuthorFlairHTML().equals("")) {
+ ((CommentViewHolder) holder).authorFlairTextView.setVisibility(View.VISIBLE);
+ Utils.setHTMLWithImageToTextView(((CommentViewHolder) holder).authorFlairTextView, comment.getAuthorFlairHTML(), true);
+ } else if (comment.getAuthorFlair() != null && !comment.getAuthorFlair().equals("")) {
+ ((CommentViewHolder) holder).authorFlairTextView.setVisibility(View.VISIBLE);
+ ((CommentViewHolder) holder).authorFlairTextView.setText(comment.getAuthorFlair());
+ }
+
+ if (comment.isSubmitter()) {
+ ((CommentViewHolder) holder).authorTextView.setTextColor(mSubmitterColor);
+ Drawable submitterDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_mic_14dp, mSubmitterColor);
+ ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
+ submitterDrawable, null, null, null);
+ } else if (comment.isModerator()) {
+ ((CommentViewHolder) holder).authorTextView.setTextColor(mModeratorColor);
+ Drawable moderatorDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_verified_user_14dp, mModeratorColor);
+ ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
+ moderatorDrawable, null, null, null);
+ } else if (comment.getAuthor().equals(mAccountName)) {
+ ((CommentViewHolder) holder).authorTextView.setTextColor(mCurrentUserColor);
+ Drawable currentUserDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_current_user_14dp, mCurrentUserColor);
+ ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
+ currentUserDrawable, null, null, null);
+ }
+
+ if (mShowElapsedTime) {
+ ((CommentViewHolder) holder).commentTimeTextView.setText(
+ Utils.getElapsedTime(mActivity, comment.getCommentTimeMillis()));
+ } else {
+ ((CommentViewHolder) holder).commentTimeTextView.setText(Utils.getFormattedTime(mLocale, comment.getCommentTimeMillis(), mTimeFormatPattern));
+ }
+
+ if (mCommentToolbarHidden) {
+ ((CommentViewHolder) holder).bottomConstraintLayout.getLayoutParams().height = 0;
+ ((CommentViewHolder) holder).topScoreTextView.setVisibility(View.VISIBLE);
+ } else {
+ ((CommentViewHolder) holder).bottomConstraintLayout.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT;
+ ((CommentViewHolder) holder).topScoreTextView.setVisibility(View.GONE);
+ }
+
+ if (comment.getAwards() != null && !comment.getAwards().equals("")) {
+ ((CommentViewHolder) holder).awardsTextView.setVisibility(View.VISIBLE);
+ Utils.setHTMLWithImageToTextView(((CommentViewHolder) holder).awardsTextView, comment.getAwards(), true);
+ }
+
+ mCommentMarkwon.setMarkdown(((CommentViewHolder) holder).commentMarkdownView, comment.getCommentMarkdown());
+ ((CommentViewHolder) holder).scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType()));
+ ((CommentViewHolder) holder).topScoreTextView.setText(mActivity.getString(R.string.top_score,
+ Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType())));
+
+ ((CommentViewHolder) holder).commentIndentationView.setShowOnlyOneDivider(mShowOnlyOneCommentLevelIndicator);
+ ((CommentViewHolder) holder).commentIndentationView.setLevelAndColors(comment.getDepth(), verticalBlockColors);
+ if (comment.getDepth() > depthThreshold) {
+ ((CommentViewHolder) holder).saveButton.setVisibility(View.GONE);
+ ((CommentViewHolder) holder).replyButton.setVisibility(View.GONE);
+ } else {
+ ((CommentViewHolder) holder).saveButton.setVisibility(View.VISIBLE);
+ ((CommentViewHolder) holder).replyButton.setVisibility(View.VISIBLE);
+ }
+
+ if (comment.hasReply()) {
+ if (comment.isExpanded()) {
+ ((CommentViewHolder) holder).expandButton.setImageResource(R.drawable.ic_expand_less_grey_24dp);
+ } else {
+ ((CommentViewHolder) holder).expandButton.setImageResource(R.drawable.ic_expand_more_grey_24dp);
+ }
+ ((CommentViewHolder) holder).expandButton.setVisibility(View.VISIBLE);
+ }
+
+ switch (comment.getVoteType()) {
+ case Comment.VOTE_TYPE_UPVOTE:
+ ((CommentViewHolder) holder).upvoteButton
+ .setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ ((CommentViewHolder) holder).scoreTextView.setTextColor(mUpvotedColor);
+ ((CommentViewHolder) holder).topScoreTextView.setTextColor(mUpvotedColor);
+ break;
+ case Comment.VOTE_TYPE_DOWNVOTE:
+ ((CommentViewHolder) holder).downvoteButton
+ .setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ ((CommentViewHolder) holder).scoreTextView.setTextColor(mDownvotedColor);
+ ((CommentViewHolder) holder).topScoreTextView.setTextColor(mDownvotedColor);
+ break;
+ }
+
+ if (mPost.isArchived()) {
+ ((CommentViewHolder) holder).replyButton
+ .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
+ android.graphics.PorterDuff.Mode.SRC_IN);
+ ((CommentViewHolder) holder).upvoteButton
+ .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
+ android.graphics.PorterDuff.Mode.SRC_IN);
+ ((CommentViewHolder) holder).downvoteButton
+ .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
+ android.graphics.PorterDuff.Mode.SRC_IN);
+ }
+
+ if (mPost.isLocked()) {
+ ((CommentViewHolder) holder).replyButton
+ .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
+ android.graphics.PorterDuff.Mode.SRC_IN);
+ }
+
+ if (comment.isSaved()) {
+ ((CommentViewHolder) holder).saveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
+ } else {
+ ((CommentViewHolder) holder).saveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
+ }
+
+ if (position == mSearchCommentIndex) {
+ holder.itemView.setBackgroundColor(Color.parseColor("#03A9F4"));
+ }
+ }
+ } else if (holder instanceof CommentFullyCollapsedViewHolder) {
+ Comment comment = getCurrentComment(position);
+ if (comment != null) {
+ String authorWithPrefix = "u/" + comment.getAuthor();
+ ((CommentFullyCollapsedViewHolder) holder).usernameTextView.setText(authorWithPrefix);
+ if (mShowElapsedTime) {
+ ((CommentFullyCollapsedViewHolder) holder).commentTimeTextView.setText(Utils.getElapsedTime(mActivity, comment.getCommentTimeMillis()));
+ } else {
+ ((CommentFullyCollapsedViewHolder) holder).commentTimeTextView.setText(Utils.getFormattedTime(mLocale, comment.getCommentTimeMillis(), mTimeFormatPattern));
+ }
+ ((CommentFullyCollapsedViewHolder) holder).scoreTextView.setText(mActivity.getString(R.string.top_score,
+ Utils.getNVotes(mShowAbsoluteNumberOfVotes, comment.getScore() + comment.getVoteType())));
+ ((CommentFullyCollapsedViewHolder) holder).commentIndentationView.setShowOnlyOneDivider(mShowOnlyOneCommentLevelIndicator);
+ ((CommentFullyCollapsedViewHolder) holder).commentIndentationView.setLevelAndColors(comment.getDepth(), verticalBlockColors);
+ }
+ } else if (holder instanceof LoadMoreChildCommentsViewHolder) {
+ Comment placeholder;
+ placeholder = mIsSingleCommentThreadMode ? mVisibleComments.get(holder.getBindingAdapterPosition() - 1)
+ : mVisibleComments.get(holder.getBindingAdapterPosition());
+
+ ((LoadMoreChildCommentsViewHolder) holder).commentIndentationView.setShowOnlyOneDivider(mShowOnlyOneCommentLevelIndicator);
+ ((LoadMoreChildCommentsViewHolder) holder).commentIndentationView.setLevelAndColors(placeholder.getDepth(), verticalBlockColors);
+
+ if (placeholder.getPlaceholderType() == Comment.PLACEHOLDER_LOAD_MORE_COMMENTS) {
+ if (placeholder.isLoadingMoreChildren()) {
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.loading);
+ } else if (placeholder.isLoadMoreChildrenFailed()) {
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments_failed);
+ } else {
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments);
+ }
+ } else {
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_continue_thread);
+ }
+
+ if (placeholder.getPlaceholderType() == Comment.PLACEHOLDER_LOAD_MORE_COMMENTS) {
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setOnClickListener(view -> {
+ int commentPosition = mIsSingleCommentThreadMode ? holder.getBindingAdapterPosition() - 1 : holder.getBindingAdapterPosition();
+ int parentPosition = getParentPosition(commentPosition);
+ if (parentPosition >= 0) {
+ Comment parentComment = mVisibleComments.get(parentPosition);
+
+ mVisibleComments.get(commentPosition).setLoadingMoreChildren(true);
+ mVisibleComments.get(commentPosition).setLoadMoreChildrenFailed(false);
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.loading);
+
+ Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit;
+ FetchComment.fetchMoreComment(mExecutor, new Handler(), retrofit, mAccessToken,
+ parentComment.getMoreChildrenFullnames(),
+ parentComment.getMoreChildrenStartingIndex(), parentComment.getDepth() + 1,
+ mExpandChildren, new FetchComment.FetchMoreCommentListener() {
+ @Override
+ public void onFetchMoreCommentSuccess(ArrayList<Comment> expandedComments,
+ int childrenStartingIndex) {
+ if (mVisibleComments.size() > parentPosition
+ && parentComment.getFullName().equals(mVisibleComments.get(parentPosition).getFullName())) {
+ if (mVisibleComments.get(parentPosition).isExpanded()) {
+ if (mVisibleComments.get(parentPosition).getChildren().size() > childrenStartingIndex) {
+ mVisibleComments.get(parentPosition).setMoreChildrenStartingIndex(childrenStartingIndex);
+ mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
+ .setLoadingMoreChildren(false);
+ mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
+ .setLoadMoreChildrenFailed(false);
+
+ int placeholderPosition = commentPosition;
+ if (mVisibleComments.get(commentPosition).getFullName().equals(parentComment.getFullName())) {
+ for (int i = parentPosition + 1; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
+ placeholderPosition = i;
+ break;
+ }
+ }
+ }
+
+ mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
+ mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(false);
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments);
+
+ mVisibleComments.addAll(placeholderPosition, expandedComments);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRangeInserted(placeholderPosition + 1, expandedComments.size());
+ } else {
+ notifyItemRangeInserted(placeholderPosition, expandedComments.size());
+ }
+ } else {
+ mVisibleComments.get(parentPosition).getChildren()
+ .remove(mVisibleComments.get(parentPosition).getChildren().size() - 1);
+ mVisibleComments.get(parentPosition).removeMoreChildrenFullnames();
+
+ int placeholderPosition = commentPosition;
+ if (mVisibleComments.get(commentPosition).getFullName().equals(parentComment.getFullName())) {
+ for (int i = parentPosition + 1; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
+ placeholderPosition = i;
+ break;
+ }
+ }
+ }
+
+ mVisibleComments.remove(placeholderPosition);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRemoved(placeholderPosition + 1);
+ } else {
+ notifyItemRemoved(placeholderPosition);
+ }
+
+ mVisibleComments.addAll(placeholderPosition, expandedComments);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRangeInserted(placeholderPosition + 1, expandedComments.size());
+ } else {
+ notifyItemRangeInserted(placeholderPosition, expandedComments.size());
+ }
+ }
+ } else {
+ if (mVisibleComments.get(parentPosition).hasReply() && mVisibleComments.get(parentPosition).getChildren().size() <= childrenStartingIndex) {
+ mVisibleComments.get(parentPosition).getChildren()
+ .remove(mVisibleComments.get(parentPosition).getChildren().size() - 1);
+ mVisibleComments.get(parentPosition).removeMoreChildrenFullnames();
+ }
+ }
+
+ mVisibleComments.get(parentPosition).addChildren(expandedComments);
+ } else {
+ for (int i = 0; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
+ if (mVisibleComments.get(i).isExpanded()) {
+ int placeholderPosition = i + mVisibleComments.get(i).getChildren().size();
+
+ if (!mVisibleComments.get(i).getFullName()
+ .equals(mVisibleComments.get(placeholderPosition).getFullName())) {
+ for (int j = i + 1; j < mVisibleComments.size(); j++) {
+ if (mVisibleComments.get(j).getFullName().equals(mVisibleComments.get(i).getFullName())) {
+ placeholderPosition = j;
+ }
+ }
+ }
+
+ mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
+ mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(false);
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments);
+
+ mVisibleComments.addAll(placeholderPosition, expandedComments);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRangeInserted(placeholderPosition + 1, expandedComments.size());
+ } else {
+ notifyItemRangeInserted(placeholderPosition, expandedComments.size());
+ }
+ }
+
+ mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1)
+ .setLoadingMoreChildren(false);
+ mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1)
+ .setLoadMoreChildrenFailed(false);
+ mVisibleComments.get(i).addChildren(expandedComments);
+
+ break;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onFetchMoreCommentFailed() {
+ if (parentPosition < mVisibleComments.size()
+ && parentComment.getFullName().equals(mVisibleComments.get(parentPosition).getFullName())) {
+ if (mVisibleComments.get(parentPosition).isExpanded()) {
+ int commentPosition = mIsSingleCommentThreadMode ? holder.getBindingAdapterPosition() - 1 : holder.getBindingAdapterPosition();
+ int placeholderPosition = commentPosition;
+ if (commentPosition >= mVisibleComments.size() || commentPosition < 0 || !mVisibleComments.get(commentPosition).getFullName().equals(parentComment.getFullName())) {
+ for (int i = parentPosition + 1; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
+ placeholderPosition = i;
+ break;
+ }
+ }
+ }
+
+ if (placeholderPosition >= mVisibleComments.size() || placeholderPosition < 0) {
+ mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
+ mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(true);
+ }
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments_failed);
+ }
+
+ mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
+ .setLoadingMoreChildren(false);
+ mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
+ .setLoadMoreChildrenFailed(true);
+ } else {
+ for (int i = 0; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
+ if (mVisibleComments.get(i).isExpanded()) {
+ int placeholderPosition = i + mVisibleComments.get(i).getChildren().size();
+ if (!mVisibleComments.get(placeholderPosition).getFullName().equals(mVisibleComments.get(i).getFullName())) {
+ for (int j = i + 1; j < mVisibleComments.size(); j++) {
+ if (mVisibleComments.get(j).getFullName().equals(mVisibleComments.get(i).getFullName())) {
+ placeholderPosition = j;
+ break;
+ }
+ }
+ }
+
+ mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
+ mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(true);
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments_failed);
+ }
+
+ mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1).setLoadingMoreChildren(false);
+ mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1).setLoadMoreChildrenFailed(true);
+
+ break;
+ }
+ }
+ }
+ }
+ });
+ }
+ });
+ } else {
+ ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setOnClickListener(view -> {
+ Comment comment = getCurrentComment(position);
+ if (comment != null) {
+ Intent intent = new Intent(mActivity, ViewPostDetailActivity.class);
+ intent.putExtra(ViewPostDetailActivity.EXTRA_POST_DATA, mPost);
+ intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, comment.getParentId());
+ intent.putExtra(ViewPostDetailActivity.EXTRA_CONTEXT_NUMBER, "0");
+ mActivity.startActivity(intent);
+ }
+ });
+ }
+ }
+ }
+
+ private int getParentPosition(int position) {
+ if (position >= 0 && position < mVisibleComments.size()) {
+ int childDepth = mVisibleComments.get(position).getDepth();
+ for (int i = position; i >= 0; i--) {
+ if (mVisibleComments.get(i).getDepth() < childDepth) {
+ return i;
+ }
+ }
+ }
+ return -1;
+ }
+
+ private void expandChildren(ArrayList<Comment> comments, ArrayList<Comment> newList, int position) {
+ if (comments != null && comments.size() > 0) {
+ newList.addAll(position, comments);
+ for (int i = 0; i < comments.size(); i++) {
+ position++;
+ if (comments.get(i).getChildren() != null && comments.get(i).getChildren().size() > 0) {
+ expandChildren(comments.get(i).getChildren(), newList, position);
+ position = position + comments.get(i).getChildren().size();
+ }
+ comments.get(i).setExpanded(true);
+ }
+ }
+ }
+
+ private void collapseChildren(int position) {
+ mVisibleComments.get(position).setExpanded(false);
+ int depth = mVisibleComments.get(position).getDepth();
+ int allChildrenSize = 0;
+ for (int i = position + 1; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getDepth() > depth) {
+ allChildrenSize++;
+ } else {
+ break;
+ }
+ }
+
+ if (allChildrenSize > 0) {
+ mVisibleComments.subList(position + 1, position + 1 + allChildrenSize).clear();
+ }
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRangeRemoved(position + 2, allChildrenSize);
+ if (mFullyCollapseComment) {
+ notifyItemChanged(position + 1);
+ }
+ } else {
+ notifyItemRangeRemoved(position + 1, allChildrenSize);
+ if (mFullyCollapseComment) {
+ notifyItemChanged(position);
+ }
+ }
+ }
+
+ public void addComments(@NonNull ArrayList<Comment> comments, boolean hasMoreComments) {
+ if (mVisibleComments.size() == 0) {
+ isInitiallyLoading = false;
+ isInitiallyLoadingFailed = false;
+ if (comments.size() == 0) {
+ notifyItemChanged(0);
+ } else {
+ notifyItemRemoved(0);
+ }
+ }
+
+ int sizeBefore = mVisibleComments.size();
+ mVisibleComments.addAll(comments);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRangeInserted(sizeBefore, comments.size() + 1);
+ } else {
+ notifyItemRangeInserted(sizeBefore, comments.size());
+ }
+
+ if (mHasMoreComments != hasMoreComments) {
+ if (hasMoreComments) {
+ if (mIsSingleCommentThreadMode) {
+ notifyItemInserted(mVisibleComments.size() + 1);
+ } else {
+ notifyItemInserted(mVisibleComments.size());
+ }
+ } else {
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRemoved(mVisibleComments.size() + 1);
+ } else {
+ notifyItemRemoved(mVisibleComments.size());
+ }
+ }
+ }
+ mHasMoreComments = hasMoreComments;
+ }
+
+ public void addComment(Comment comment) {
+ if (mVisibleComments.size() == 0 || isInitiallyLoadingFailed) {
+ notifyItemRemoved(1);
+ }
+
+ mVisibleComments.add(0, comment);
+
+ if (isInitiallyLoading) {
+ notifyItemInserted(1);
+ } else {
+ notifyItemInserted(0);
+ }
+ }
+
+ public void addChildComment(Comment comment, String parentFullname, int parentPosition) {
+ if (!parentFullname.equals(mVisibleComments.get(parentPosition).getFullName())) {
+ for (int i = 0; i < mVisibleComments.size(); i++) {
+ if (parentFullname.equals(mVisibleComments.get(i).getFullName())) {
+ parentPosition = i;
+ break;
+ }
+ }
+ }
+
+ mVisibleComments.get(parentPosition).addChild(comment);
+ mVisibleComments.get(parentPosition).setHasReply(true);
+ if (!mVisibleComments.get(parentPosition).isExpanded()) {
+ ArrayList<Comment> newList = new ArrayList<>();
+ expandChildren(mVisibleComments.get(parentPosition).getChildren(), newList, 0);
+ mVisibleComments.get(parentPosition).setExpanded(true);
+ mVisibleComments.addAll(parentPosition + 1, newList);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemChanged(parentPosition + 1);
+ notifyItemRangeInserted(parentPosition + 2, newList.size());
+ } else {
+ notifyItemChanged(parentPosition);
+ notifyItemRangeInserted(parentPosition + 1, newList.size());
+ }
+ } else {
+ mVisibleComments.add(parentPosition + 1, comment);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemInserted(parentPosition + 2);
+ } else {
+ notifyItemInserted(parentPosition + 1);
+ }
+ }
+ }
+
+ public void setSingleComment(String singleCommentId, boolean isSingleCommentThreadMode) {
+ mSingleCommentId = singleCommentId;
+ mIsSingleCommentThreadMode = isSingleCommentThreadMode;
+ }
+
+ public ArrayList<Comment> getVisibleComments() {
+ return mVisibleComments;
+ }
+
+ public void initiallyLoading() {
+ resetCommentSearchIndex();
+ notifyItemRangeRemoved(0, getItemCount());
+ mVisibleComments.clear();
+ isInitiallyLoading = true;
+ isInitiallyLoadingFailed = false;
+ notifyItemInserted(0);
+ }
+
+ public void initiallyLoadCommentsFailed() {
+ isInitiallyLoading = false;
+ isInitiallyLoadingFailed = true;
+ notifyItemChanged(0);
+ }
+
+ public void loadMoreCommentsFailed() {
+ loadMoreCommentsFailed = true;
+ if (mIsSingleCommentThreadMode) {
+ notifyItemChanged(mVisibleComments.size() + 1);
+ } else {
+ notifyItemChanged(mVisibleComments.size());
+ }
+ }
+
+ public void editComment(String commentAuthor, String commentContentMarkdown, int position) {
+ if (commentAuthor != null)
+ mVisibleComments.get(position).setAuthor(commentAuthor);
+
+ mVisibleComments.get(position).setCommentMarkdown(commentContentMarkdown);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemChanged(position + 1);
+ } else {
+ notifyItemChanged(position);
+ }
+ }
+
+ public void deleteComment(int position) {
+ if (mVisibleComments != null && position >= 0 && position < mVisibleComments.size()) {
+ if (mVisibleComments.get(position).hasReply()) {
+ mVisibleComments.get(position).setAuthor("[deleted]");
+ mVisibleComments.get(position).setCommentMarkdown("[deleted]");
+ if (mIsSingleCommentThreadMode) {
+ notifyItemChanged(position + 1);
+ } else {
+ notifyItemChanged(position);
+ }
+ } else {
+ mVisibleComments.remove(position);
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRemoved(position + 1);
+ } else {
+ notifyItemRemoved(position);
+ }
+ }
+ }
+ }
+
+ public int getNextParentCommentPosition(int currentPosition) {
+ if (mVisibleComments != null && !mVisibleComments.isEmpty()) {
+ if (mIsSingleCommentThreadMode) {
+ for (int i = currentPosition + 1; i - 1 < mVisibleComments.size() && i - 1 >= 0; i++) {
+ if (mVisibleComments.get(i - 1).getDepth() == 0) {
+ return i;
+ }
+ }
+ } else {
+ for (int i = currentPosition + 1; i < mVisibleComments.size(); i++) {
+ if (mVisibleComments.get(i).getDepth() == 0) {
+ return i;
+ }
+ }
+ }
+ }
+ return -1;
+ }
+
+ public int getPreviousParentCommentPosition(int currentPosition) {
+ if (mVisibleComments != null && !mVisibleComments.isEmpty()) {
+ if (mIsSingleCommentThreadMode) {
+ for (int i = currentPosition - 1; i - 1 >= 0; i--) {
+ if (mVisibleComments.get(i - 1).getDepth() == 0) {
+ return i;
+ }
+ }
+ } else {
+ for (int i = currentPosition - 1; i >= 0; i--) {
+ if (mVisibleComments.get(i).getDepth() == 0) {
+ return i;
+ }
+ }
+ }
+ }
+ return -1;
+ }
+
+ public void onItemSwipe(RecyclerView.ViewHolder viewHolder, int direction, int swipeLeftAction, int swipeRightAction) {
+ if (viewHolder instanceof CommentViewHolder) {
+ if (direction == ItemTouchHelper.LEFT || direction == ItemTouchHelper.START) {
+ if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) {
+ ((CommentViewHolder) viewHolder).upvoteButton.performClick();
+ } else if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) {
+ ((CommentViewHolder) viewHolder).downvoteButton.performClick();
+ }
+ } else {
+ if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) {
+ ((CommentViewHolder) viewHolder).upvoteButton.performClick();
+ } else if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) {
+ ((CommentViewHolder) viewHolder).downvoteButton.performClick();
+ }
+ }
+ }
+ }
+
+ public void giveAward(String awardsHTML, int awardCount, int position) {
+ position = mIsSingleCommentThreadMode ? position + 1 : position;
+ Comment comment = getCurrentComment(position);
+ if (comment != null) {
+ comment.addAwards(awardsHTML);
+ notifyItemChanged(position);
+ }
+ }
+
+ public void setSaveComment(int position, boolean isSaved) {
+ Comment comment = getCurrentComment(position);
+ if (comment != null) {
+ comment.setSaved(isSaved);
+ }
+ }
+
+ public int getSearchCommentIndex() {
+ return mSearchCommentIndex;
+ }
+
+ public void highlightSearchResult(int searchCommentIndex) {
+ mSearchCommentIndex = searchCommentIndex;
+ }
+
+ public void resetCommentSearchIndex() {
+ mSearchCommentIndex = -1;
+ }
+
+ @Override
+ public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
+ if (holder instanceof CommentViewHolder) {
+ holder.itemView.setBackgroundColor(mCommentBackgroundColor);
+ ((CommentViewHolder) holder).authorTextView.setTextColor(mUsernameColor);
+ ((CommentViewHolder) holder).authorFlairTextView.setVisibility(View.GONE);
+ ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
+ ((CommentViewHolder) holder).topScoreTextView.setTextColor(mSecondaryTextColor);
+ ((CommentViewHolder) holder).awardsTextView.setText("");
+ ((CommentViewHolder) holder).awardsTextView.setVisibility(View.GONE);
+ ((CommentViewHolder) holder).expandButton.setVisibility(View.GONE);
+ ((CommentViewHolder) holder).upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ ((CommentViewHolder) holder).scoreTextView.setTextColor(mCommentIconAndInfoColor);
+ ((CommentViewHolder) holder).downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ ((CommentViewHolder) holder).replyButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ }
+ }
+
+ @Override
+ public int getItemCount() {
+ if (isInitiallyLoading || isInitiallyLoadingFailed || mVisibleComments.size() == 0) {
+ return 1;
+ }
+
+ if (mHasMoreComments || loadMoreCommentsFailed) {
+ if (mIsSingleCommentThreadMode) {
+ return mVisibleComments.size() + 2;
+ } else {
+ return mVisibleComments.size() + 1;
+ }
+ }
+
+ if (mIsSingleCommentThreadMode) {
+ return mVisibleComments.size() + 1;
+ } else {
+ return mVisibleComments.size();
+ }
+ }
+
+ public interface CommentRecyclerViewAdapterCallback {
+ void retryFetchingComments();
+
+ void retryFetchingMoreComments();
+ }
+
+ public class CommentViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.linear_layout_item_comment)
+ LinearLayout linearLayout;
+ @BindView(R.id.author_text_view_item_post_comment)
+ TextView authorTextView;
+ @BindView(R.id.author_flair_text_view_item_post_comment)
+ TextView authorFlairTextView;
+ @BindView(R.id.comment_time_text_view_item_post_comment)
+ TextView commentTimeTextView;
+ @BindView(R.id.top_score_text_view_item_post_comment)
+ TextView topScoreTextView;
+ @BindView(R.id.awards_text_view_item_comment)
+ TextView awardsTextView;
+ @BindView(R.id.comment_markdown_view_item_post_comment)
+ TextView commentMarkdownView;
+ @BindView(R.id.bottom_constraint_layout_item_post_comment)
+ ConstraintLayout bottomConstraintLayout;
+ @BindView(R.id.up_vote_button_item_post_comment)
+ ImageView upvoteButton;
+ @BindView(R.id.score_text_view_item_post_comment)
+ TextView scoreTextView;
+ @BindView(R.id.down_vote_button_item_post_comment)
+ ImageView downvoteButton;
+ @BindView(R.id.more_button_item_post_comment)
+ ImageView moreButton;
+ @BindView(R.id.save_button_item_post_comment)
+ ImageView saveButton;
+ @BindView(R.id.expand_button_item_post_comment)
+ ImageView expandButton;
+ @BindView(R.id.reply_button_item_post_comment)
+ ImageView replyButton;
+ @BindView(R.id.vertical_block_indentation_item_comment)
+ CommentIndentationView commentIndentationView;
+ @BindView(R.id.divider_item_comment)
+ View commentDivider;
+
+ CommentViewHolder(View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+
+ if (mVoteButtonsOnTheRight) {
+ ConstraintSet constraintSet = new ConstraintSet();
+ constraintSet.clone(bottomConstraintLayout);
+ constraintSet.clear(upvoteButton.getId(), ConstraintSet.START);
+ constraintSet.clear(scoreTextView.getId(), ConstraintSet.START);
+ constraintSet.clear(downvoteButton.getId(), ConstraintSet.START);
+ constraintSet.clear(expandButton.getId(), ConstraintSet.END);
+ constraintSet.clear(saveButton.getId(), ConstraintSet.END);
+ constraintSet.clear(replyButton.getId(), ConstraintSet.END);
+ constraintSet.clear(moreButton.getId(), ConstraintSet.END);
+ constraintSet.connect(upvoteButton.getId(), ConstraintSet.END, scoreTextView.getId(), ConstraintSet.START);
+ constraintSet.connect(scoreTextView.getId(), ConstraintSet.END, downvoteButton.getId(), ConstraintSet.START);
+ constraintSet.connect(downvoteButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
+ constraintSet.connect(moreButton.getId(), ConstraintSet.START, expandButton.getId(), ConstraintSet.END);
+ constraintSet.connect(expandButton.getId(), ConstraintSet.START, saveButton.getId(), ConstraintSet.END);
+ constraintSet.connect(saveButton.getId(), ConstraintSet.START, replyButton.getId(), ConstraintSet.END);
+ constraintSet.connect(replyButton.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
+ constraintSet.setHorizontalBias(moreButton.getId(), 0);
+ constraintSet.applyTo(bottomConstraintLayout);
+ }
+
+ if (linearLayout.getLayoutTransition() != null) {
+ linearLayout.getLayoutTransition().setAnimateParentHierarchy(false);
+ }
+
+ if (mShowCommentDivider) {
+ commentDivider.setBackgroundColor(mDividerColor);
+ commentDivider.setVisibility(View.VISIBLE);
+ }
+
+ itemView.setBackgroundColor(mCommentBackgroundColor);
+ authorTextView.setTextColor(mUsernameColor);
+ commentTimeTextView.setTextColor(mSecondaryTextColor);
+ commentMarkdownView.setTextColor(mCommentTextColor);
+ authorFlairTextView.setTextColor(mAuthorFlairTextColor);
+ topScoreTextView.setTextColor(mSecondaryTextColor);
+ awardsTextView.setTextColor(mSecondaryTextColor);
+ commentDivider.setBackgroundColor(mDividerColor);
+ upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mCommentIconAndInfoColor);
+ downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ moreButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ expandButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ saveButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ replyButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+
+ authorFlairTextView.setOnClickListener(view -> authorTextView.performClick());
+
+ moreButton.setOnClickListener(view -> {
+ getItemCount();
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ Bundle bundle = new Bundle();
+ if (!mPost.isArchived() && !mPost.isLocked() && comment.getAuthor().equals(mAccountName)) {
+ bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_EDIT_AND_DELETE_AVAILABLE, true);
+ }
+ bundle.putString(CommentMoreBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
+ bundle.putParcelable(CommentMoreBottomSheetFragment.EXTRA_COMMENT, comment);
+ if (mIsSingleCommentThreadMode) {
+ bundle.putInt(CommentMoreBottomSheetFragment.EXTRA_POSITION, getBindingAdapterPosition() - 1);
+ } else {
+ bundle.putInt(CommentMoreBottomSheetFragment.EXTRA_POSITION, getBindingAdapterPosition());
+ }
+ bundle.putString(CommentMoreBottomSheetFragment.EXTRA_COMMENT_MARKDOWN, comment.getCommentMarkdown());
+ bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_IS_NSFW, mPost.isNSFW());
+ if (comment.getDepth() > depthThreshold) {
+ bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_SHOW_REPLY_AND_SAVE_OPTION, true);
+ }
+ CommentMoreBottomSheetFragment commentMoreBottomSheetFragment = new CommentMoreBottomSheetFragment();
+ commentMoreBottomSheetFragment.setArguments(bundle);
+ commentMoreBottomSheetFragment.show(mActivity.getSupportFragmentManager(), commentMoreBottomSheetFragment.getTag());
+ }
+ });
+
+ replyButton.setOnClickListener(view -> {
+ if (mAccessToken == null) {
+ Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ if (mPost.isArchived()) {
+ Toast.makeText(mActivity, R.string.archived_post_reply_unavailable, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ if (mPost.isLocked()) {
+ Toast.makeText(mActivity, R.string.locked_post_reply_unavailable, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ Intent intent = new Intent(mActivity, CommentActivity.class);
+ intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, comment.getDepth() + 1);
+ intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TEXT_MARKDOWN_KEY, comment.getCommentMarkdown());
+ intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TEXT_KEY, comment.getCommentRawText());
+ intent.putExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY, comment.getFullName());
+ intent.putExtra(CommentActivity.EXTRA_IS_REPLYING_KEY, true);
+
+ int parentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 1 : getBindingAdapterPosition();
+ intent.putExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, parentPosition);
+ mFragment.startActivityForResult(intent, CommentActivity.WRITE_COMMENT_REQUEST_CODE);
+ }
+ });
+
+ upvoteButton.setOnClickListener(view -> {
+ if (mPost.isArchived()) {
+ Toast.makeText(mActivity, R.string.archived_post_vote_unavailable, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ if (mAccessToken == null) {
+ Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ int previousVoteType = comment.getVoteType();
+ String newVoteType;
+
+ downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+
+ if (previousVoteType != Comment.VOTE_TYPE_UPVOTE) {
+ //Not upvoted before
+ comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
+ newVoteType = APIUtils.DIR_UPVOTE;
+ upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mUpvotedColor);
+ topScoreTextView.setTextColor(mUpvotedColor);
+ } else {
+ //Upvoted before
+ comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
+ newVoteType = APIUtils.DIR_UNVOTE;
+ upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mCommentIconAndInfoColor);
+ topScoreTextView.setTextColor(mSecondaryTextColor);
+ }
+
+ scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType()));
+ topScoreTextView.setText(mActivity.getString(R.string.top_score,
+ Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType())));
+
+ int position = getBindingAdapterPosition();
+ VoteThing.voteThing(mActivity, mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
+ @Override
+ public void onVoteThingSuccess(int position) {
+ int currentPosition = getBindingAdapterPosition();
+ if (newVoteType.equals(APIUtils.DIR_UPVOTE)) {
+ comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
+ if (currentPosition == position) {
+ upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mUpvotedColor);
+ topScoreTextView.setTextColor(mUpvotedColor);
+ }
+ } else {
+ comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
+ if (currentPosition == position) {
+ upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mCommentIconAndInfoColor);
+ topScoreTextView.setTextColor(mSecondaryTextColor);
+ }
+ }
+
+ if (currentPosition == position) {
+ downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType()));
+ topScoreTextView.setText(mActivity.getString(R.string.top_score,
+ Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType())));
+ }
+ }
+
+ @Override
+ public void onVoteThingFail(int position) {
+ }
+ }, comment.getFullName(), newVoteType, getBindingAdapterPosition());
+ }
+ });
+
+ downvoteButton.setOnClickListener(view -> {
+ if (mPost.isArchived()) {
+ Toast.makeText(mActivity, R.string.archived_post_vote_unavailable, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ if (mAccessToken == null) {
+ Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ int previousVoteType = comment.getVoteType();
+ String newVoteType;
+
+ upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+
+ if (previousVoteType != Comment.VOTE_TYPE_DOWNVOTE) {
+ //Not downvoted before
+ comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
+ newVoteType = APIUtils.DIR_DOWNVOTE;
+ downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mDownvotedColor);
+ topScoreTextView.setTextColor(mDownvotedColor);
+ } else {
+ //Downvoted before
+ comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
+ newVoteType = APIUtils.DIR_UNVOTE;
+ downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mCommentIconAndInfoColor);
+ topScoreTextView.setTextColor(mSecondaryTextColor);
+ }
+
+ scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType()));
+ topScoreTextView.setText(mActivity.getString(R.string.top_score,
+ Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType())));
+
+ int position = getBindingAdapterPosition();
+ VoteThing.voteThing(mActivity, mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
+ @Override
+ public void onVoteThingSuccess(int position1) {
+ int currentPosition = getBindingAdapterPosition();
+ if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) {
+ comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
+ if (currentPosition == position) {
+ downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mDownvotedColor);
+ topScoreTextView.setTextColor(mDownvotedColor);
+ }
+ } else {
+ comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
+ if (currentPosition == position) {
+ downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setTextColor(mCommentIconAndInfoColor);
+ topScoreTextView.setTextColor(mSecondaryTextColor);
+ }
+ }
+
+ if (currentPosition == position) {
+ upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
+ scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType()));
+ topScoreTextView.setText(mActivity.getString(R.string.top_score,
+ Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ comment.getScore() + comment.getVoteType())));
+ }
+ }
+
+ @Override
+ public void onVoteThingFail(int position1) {
+ }
+ }, comment.getFullName(), newVoteType, getBindingAdapterPosition());
+ }
+ });
+
+ saveButton.setOnClickListener(view -> {
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ int position = getBindingAdapterPosition();
+ if (comment.isSaved()) {
+ comment.setSaved(false);
+ SaveThing.unsaveThing(mOauthRetrofit, mAccessToken, comment.getFullName(), new SaveThing.SaveThingListener() {
+ @Override
+ public void success() {
+ comment.setSaved(false);
+ if (getBindingAdapterPosition() == position) {
+ saveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
+ }
+ Toast.makeText(mActivity, R.string.comment_unsaved_success, Toast.LENGTH_SHORT).show();
+ }
+
+ @Override
+ public void failed() {
+ comment.setSaved(true);
+ if (getBindingAdapterPosition() == position) {
+ saveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
+ }
+ Toast.makeText(mActivity, R.string.comment_unsaved_failed, Toast.LENGTH_SHORT).show();
+ }
+ });
+ } else {
+ comment.setSaved(true);
+ SaveThing.saveThing(mOauthRetrofit, mAccessToken, comment.getFullName(), new SaveThing.SaveThingListener() {
+ @Override
+ public void success() {
+ comment.setSaved(true);
+ if (getBindingAdapterPosition() == position) {
+ saveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
+ }
+ Toast.makeText(mActivity, R.string.comment_saved_success, Toast.LENGTH_SHORT).show();
+ }
+
+ @Override
+ public void failed() {
+ comment.setSaved(false);
+ if (getBindingAdapterPosition() == position) {
+ saveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
+ }
+ Toast.makeText(mActivity, R.string.comment_saved_failed, Toast.LENGTH_SHORT).show();
+ }
+ });
+ }
+ }
+ });
+
+ authorTextView.setOnClickListener(view -> {
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
+ intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, comment.getAuthor());
+ mActivity.startActivity(intent);
+ }
+ });
+
+ expandButton.setOnClickListener(view -> {
+ if (expandButton.getVisibility() == View.VISIBLE) {
+ int commentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 1 : getBindingAdapterPosition();
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ if (mVisibleComments.get(commentPosition).isExpanded()) {
+ collapseChildren(commentPosition);
+ expandButton.setImageResource(R.drawable.ic_expand_more_grey_24dp);
+ } else {
+ comment.setExpanded(true);
+ ArrayList<Comment> newList = new ArrayList<>();
+ expandChildren(mVisibleComments.get(commentPosition).getChildren(), newList, 0);
+ mVisibleComments.get(commentPosition).setExpanded(true);
+ mVisibleComments.addAll(commentPosition + 1, newList);
+
+ if (mIsSingleCommentThreadMode) {
+ notifyItemRangeInserted(commentPosition + 2, newList.size());
+ } else {
+ notifyItemRangeInserted(commentPosition + 1, newList.size());
+ }
+ expandButton.setImageResource(R.drawable.ic_expand_less_grey_24dp);
+ }
+ }
+ } else if (mFullyCollapseComment) {
+ int commentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 1 : getBindingAdapterPosition();
+ if (commentPosition >= 0 && commentPosition < mVisibleComments.size()) {
+ collapseChildren(commentPosition);
+ }
+ }
+ });
+
+ if (mSwapTapAndLong) {
+ if (mCommentToolbarHideOnClick) {
+ View.OnLongClickListener hideToolbarOnLongClickListener = view -> hideToolbar();
+ itemView.setOnLongClickListener(hideToolbarOnLongClickListener);
+ commentMarkdownView.setOnLongClickListener(hideToolbarOnLongClickListener);
+ commentTimeTextView.setOnLongClickListener(hideToolbarOnLongClickListener);
+ }
+ commentMarkdownView.setOnClickListener(view -> {
+ if (commentMarkdownView.getSelectionStart() == -1 && commentMarkdownView.getSelectionEnd() == -1) {
+ expandComments();
+ }
+ });
+ itemView.setOnClickListener(view -> expandComments());
+ } else {
+ if (mCommentToolbarHideOnClick) {
+ commentMarkdownView.setOnClickListener(view -> {
+ if (commentMarkdownView.getSelectionStart() == -1 && commentMarkdownView.getSelectionEnd() == -1) {
+ hideToolbar();
+ }
+ });
+ View.OnClickListener hideToolbarOnClickListener = view -> hideToolbar();
+ itemView.setOnClickListener(hideToolbarOnClickListener);
+ commentTimeTextView.setOnClickListener(hideToolbarOnClickListener);
+ }
+ commentMarkdownView.setOnLongClickListener(view -> {
+ if (commentMarkdownView.getSelectionStart() == -1 && commentMarkdownView.getSelectionEnd() == -1) {
+ expandComments();
+ }
+ return true;
+ });
+ itemView.setOnLongClickListener(view -> {
+ expandComments();
+ return true;
+ });
+ }
+ commentMarkdownView.setHighlightColor(Color.TRANSPARENT);
+ }
+
+ private boolean expandComments() {
+ expandButton.performClick();
+ return true;
+ }
+
+ private boolean hideToolbar() {
+ if (bottomConstraintLayout.getLayoutParams().height == 0) {
+ bottomConstraintLayout.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT;
+ topScoreTextView.setVisibility(View.GONE);
+ mFragment.delayTransition();
+ } else {
+ mFragment.delayTransition();
+ bottomConstraintLayout.getLayoutParams().height = 0;
+ topScoreTextView.setVisibility(View.VISIBLE);
+ }
+ return true;
+ }
+ }
+
+ @Nullable
+ private Comment getCurrentComment(RecyclerView.ViewHolder holder) {
+ return getCurrentComment(holder.getBindingAdapterPosition());
+ }
+
+ @Nullable
+ private Comment getCurrentComment(int position) {
+ if (mIsSingleCommentThreadMode) {
+ if (position - 1 >= 0 && position - 1 < mVisibleComments.size()) {
+ return mVisibleComments.get(position - 1);
+ }
+ } else {
+ if (position >= 0 && position < mVisibleComments.size()) {
+ return mVisibleComments.get(position);
+ }
+ }
+
+ return null;
+ }
+
+ class CommentFullyCollapsedViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.vertical_block_indentation_item_comment_fully_collapsed)
+ CommentIndentationView commentIndentationView;
+ @BindView(R.id.user_name_text_view_item_comment_fully_collapsed)
+ TextView usernameTextView;
+ @BindView(R.id.score_text_view_item_comment_fully_collapsed)
+ TextView scoreTextView;
+ @BindView(R.id.time_text_view_item_comment_fully_collapsed)
+ TextView commentTimeTextView;
+ @BindView(R.id.divider_item_comment_fully_collapsed)
+ View commentDivider;
+
+ public CommentFullyCollapsedViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+
+ itemView.setBackgroundColor(mFullyCollapsedCommentBackgroundColor);
+ usernameTextView.setTextColor(mUsernameColor);
+ scoreTextView.setTextColor(mSecondaryTextColor);
+ commentTimeTextView.setTextColor(mSecondaryTextColor);
+
+ if (mShowCommentDivider) {
+ commentDivider.setBackgroundColor(mDividerColor);
+ commentDivider.setVisibility(View.VISIBLE);
+ }
+
+ itemView.setOnClickListener(view -> {
+ int commentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 1 : getBindingAdapterPosition();
+ if (commentPosition >= 0 && commentPosition < mVisibleComments.size()) {
+ Comment comment = getCurrentComment(this);
+ if (comment != null) {
+ comment.setExpanded(true);
+ ArrayList<Comment> newList = new ArrayList<>();
+ expandChildren(mVisibleComments.get(commentPosition).getChildren(), newList, 0);
+ mVisibleComments.get(commentPosition).setExpanded(true);
+ mVisibleComments.addAll(commentPosition + 1, newList);
+
+ if (mIsSingleCommentThreadMode) {
+ notifyItemChanged(commentPosition + 1);
+ notifyItemRangeInserted(commentPosition + 2, newList.size());
+ } else {
+ notifyItemChanged(commentPosition);
+ notifyItemRangeInserted(commentPosition + 1, newList.size());
+ }
+ }
+ }
+ });
+
+ itemView.setOnLongClickListener(view -> {
+ itemView.performClick();
+ return true;
+ });
+ }
+ }
+
+ class LoadMoreChildCommentsViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.vertical_block_indentation_item_load_more_comments_placeholder)
+ CommentIndentationView commentIndentationView;
+ @BindView(R.id.placeholder_text_view_item_load_more_comments)
+ TextView placeholderTextView;
+ @BindView(R.id.divider_item_load_more_comments_placeholder)
+ View commentDivider;
+
+ LoadMoreChildCommentsViewHolder(View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+
+ if (mShowCommentDivider) {
+ commentDivider.setVisibility(View.VISIBLE);
+ }
+
+ itemView.setBackgroundColor(mCommentBackgroundColor);
+ placeholderTextView.setTextColor(mPrimaryTextColor);
+ commentDivider.setBackgroundColor(mDividerColor);
+ }
+ }
+
+ class LoadCommentsViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.comment_progress_bar_item_load_comments)
+ CircleProgressBar circleProgressBar;
+
+ LoadCommentsViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+ circleProgressBar.setBackgroundTintList(ColorStateList.valueOf(mCircularProgressBarBackgroundColor));
+ circleProgressBar.setColorSchemeColors(mColorAccent);
+ }
+ }
+
+ class LoadCommentsFailedViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.error_text_view_item_load_comments_failed_placeholder)
+ TextView errorTextView;
+
+ LoadCommentsFailedViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+ itemView.setOnClickListener(view -> mCommentRecyclerViewAdapterCallback.retryFetchingComments());
+ errorTextView.setTextColor(mSecondaryTextColor);
+ }
+ }
+
+ class NoCommentViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.error_text_view_item_no_comment_placeholder)
+ TextView errorTextView;
+
+ NoCommentViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+ errorTextView.setTextColor(mSecondaryTextColor);
+ }
+ }
+
+ class IsLoadingMoreCommentsViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.progress_bar_item_comment_footer_loading)
+ ProgressBar progressbar;
+
+ IsLoadingMoreCommentsViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+ progressbar.setIndeterminateTintList(ColorStateList.valueOf(mColorAccent));
+ }
+ }
+
+ class LoadMoreCommentsFailedViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.error_text_view_item_comment_footer_error)
+ TextView errorTextView;
+ @BindView(R.id.retry_button_item_comment_footer_error)
+ Button retryButton;
+
+ LoadMoreCommentsFailedViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+ errorTextView.setText(R.string.load_comments_failed);
+ retryButton.setOnClickListener(view -> mCommentRecyclerViewAdapterCallback.retryFetchingMoreComments());
+ errorTextView.setTextColor(mSecondaryTextColor);
+ retryButton.setBackgroundTintList(ColorStateList.valueOf(mColorPrimaryLightTheme));
+ retryButton.setTextColor(mButtonTextColor);
+ }
+ }
+
+ class ViewAllCommentsViewHolder extends RecyclerView.ViewHolder {
+
+ ViewAllCommentsViewHolder(@NonNull View itemView) {
+ super(itemView);
+
+ itemView.setOnClickListener(view -> {
+ if (mActivity != null && mActivity instanceof ViewPostDetailActivity) {
+ mIsSingleCommentThreadMode = false;
+ mSingleCommentId = null;
+ notifyItemRemoved(0);
+ mFragment.changeToNomalThreadMode();
+ }
+ });
+
+ itemView.setBackgroundTintList(ColorStateList.valueOf(mCommentBackgroundColor));
+ ((TextView) itemView).setTextColor(mColorAccent);
+ }
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FlairBottomSheetRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FlairBottomSheetRecyclerViewAdapter.java
index 4585c95e..4d738aa3 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FlairBottomSheetRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/FlairBottomSheetRecyclerViewAdapter.java
@@ -39,7 +39,7 @@ public class FlairBottomSheetRecyclerViewAdapter extends RecyclerView.Adapter<Fl
@NonNull
@Override
public FlairViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
- return new FlairViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_flair, null, false));
+ return new FlairViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_flair, parent, false));
}
@Override
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MarkdownBottomBarRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MarkdownBottomBarRecyclerViewAdapter.java
index b7057106..54f0c090 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MarkdownBottomBarRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/MarkdownBottomBarRecyclerViewAdapter.java
@@ -29,6 +29,7 @@ public class MarkdownBottomBarRecyclerViewAdapter extends RecyclerView.Adapter<R
public static final int SPOILER = 7;
public static final int QUOTE = 8;
public static final int CODE_BLOCK = 9;
+ public static final int UPLOAD_IMAGE = 10;
private static final int ITEM_COUNT = 10;
@@ -37,6 +38,7 @@ public class MarkdownBottomBarRecyclerViewAdapter extends RecyclerView.Adapter<R
public interface ItemClickListener {
void onClick(int item);
+ void onUploadImage();
}
public MarkdownBottomBarRecyclerViewAdapter(CustomThemeWrapper customThemeWrapper,
@@ -85,6 +87,9 @@ public class MarkdownBottomBarRecyclerViewAdapter extends RecyclerView.Adapter<R
case CODE_BLOCK:
((MarkdownBottomBarItemViewHolder) holder).imageView.setImageResource(R.drawable.ic_code_24dp);
break;
+ case UPLOAD_IMAGE:
+ ((MarkdownBottomBarItemViewHolder) holder).imageView.setImageResource(R.drawable.ic_image_24dp);
+ break;
}
}
}
@@ -289,7 +294,14 @@ public class MarkdownBottomBarRecyclerViewAdapter extends RecyclerView.Adapter<R
public MarkdownBottomBarItemViewHolder(@NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView;
- itemView.setOnClickListener(view -> itemClickListener.onClick(getAdapterPosition()));
+ itemView.setOnClickListener(view -> {
+ int position = getBindingAdapterPosition();
+ if (position == UPLOAD_IMAGE) {
+ itemClickListener.onUploadImage();
+ } else {
+ itemClickListener.onClick(position);
+ }
+ });
imageView.setColorFilter(customThemeWrapper.getPrimaryIconColor(), android.graphics.PorterDuff.Mode.SRC_IN);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/NavigationDrawerRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/NavigationDrawerRecyclerViewAdapter.java
index f7046a7c..bf9dea5b 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/NavigationDrawerRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/NavigationDrawerRecyclerViewAdapter.java
@@ -56,8 +56,9 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
private static final int VIEW_TYPE_FAVORITE_SUBSCRIBED_SUBREDDIT = 4;
private static final int VIEW_TYPE_SUBSCRIBED_SUBREDDIT = 5;
private static final int VIEW_TYPE_ACCOUNT = 6;
- private static final int CURRENT_MENU_ITEMS = 17;
+ private static final int CURRENT_MENU_ITEMS = 20;
private static final int ACCOUNT_SECTION_ITEMS = 4;
+ private static final int REDDIT_SECTION_ITEMS = 2;
private static final int POST_SECTION_ITEMS = 5;
private static final int PREFERENCES_SECTION_ITEMS = 3;
@@ -76,6 +77,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
private boolean isLoggedIn;
private boolean isInMainPage = true;
private boolean collapseAccountSection;
+ private boolean collapseRedditSection;
private boolean collapsePostSection;
private boolean collapsePreferencesSection;
private boolean collapseFavoriteSubredditsSection;
@@ -105,12 +107,14 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
showAvatarOnTheRightInTheNavigationDrawer = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_AVATAR_ON_THE_RIGHT, false);
isLoggedIn = accountName != null;
collapseAccountSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.COLLAPSE_ACCOUNT_SECTION, false);
+ collapseRedditSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.COLLAPSE_REDDIT_SECTION, false);
collapsePostSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.COLLAPSE_POST_SECTION, false);
collapsePreferencesSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.COLLAPSE_PREFERENCES_SECTION, false);
collapseFavoriteSubredditsSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.COLLAPSE_FAVORITE_SUBREDDITS_SECTION, false);
collapseSubscribedSubredditsSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.COLLAPSE_SUBSCRIBED_SUBREDDITS_SECTION, false);
hideFavoriteSubredditsSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_FAVORITE_SUBREDDITS_SECTION, false);
hideSubscribedSubredditsSection = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBSCRIBED_SUBREDDITS_SECTIONS, false);
+ showAvatarOnTheRightInTheNavigationDrawer = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_AVATAR_ON_THE_RIGHT, false);
this.itemClickListener = itemClickListener;
primaryTextColor = customThemeWrapper.getPrimaryTextColor();
@@ -126,21 +130,25 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
if (isInMainPage) {
if (isLoggedIn) {
if (position == CURRENT_MENU_ITEMS - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)) {
return VIEW_TYPE_MENU_GROUP_TITLE;
} else if (!hideFavoriteSubredditsSection && !favoriteSubscribedSubreddits.isEmpty() && position == CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)
+ (collapseFavoriteSubredditsSection ? 0 : favoriteSubscribedSubreddits.size()) + 1) {
return VIEW_TYPE_MENU_GROUP_TITLE;
} else if (position > CURRENT_MENU_ITEMS - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)) {
if (!favoriteSubscribedSubreddits.isEmpty() && !hideFavoriteSubredditsSection &&
!collapseFavoriteSubredditsSection && position <= CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)
+ favoriteSubscribedSubreddits.size()) {
@@ -151,11 +159,17 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
} else if (position == 0) {
return VIEW_TYPE_NAV_HEADER;
} else if (position == 1
- || position == 6 - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
- || position == 12 - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ || position == (ACCOUNT_SECTION_ITEMS + 2) - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ || position == (ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS + 3)
+ - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
+ || position == (ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS + POST_SECTION_ITEMS + 4)
+ - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)) {
return VIEW_TYPE_MENU_GROUP_TITLE;
- } else if (position == 16 - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ } else if (position == (CURRENT_MENU_ITEMS - 1) - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)) {
return VIEW_TYPE_DIVIDER;
@@ -216,15 +230,13 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof NavHeaderViewHolder) {
+ RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ((NavHeaderViewHolder) holder).profileImageView.getLayoutParams();
if (showAvatarOnTheRightInTheNavigationDrawer) {
- RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ((NavHeaderViewHolder) holder).profileImageView.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_END);
- ((NavHeaderViewHolder) holder).profileImageView.setLayoutParams(params);
} else {
- RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ((NavHeaderViewHolder) holder).profileImageView.getLayoutParams();
params.removeRule(RelativeLayout.ALIGN_PARENT_END);
- ((NavHeaderViewHolder) holder).profileImageView.setLayoutParams(params);
}
+ ((NavHeaderViewHolder) holder).profileImageView.setLayoutParams(params);
if (isLoggedIn) {
((NavHeaderViewHolder) holder).karmaTextView.setText(appCompatActivity.getString(R.string.karma_info, karma));
((NavHeaderViewHolder) holder).accountNameTextView.setText(accountName);
@@ -257,7 +269,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
((NavHeaderViewHolder) holder).dropIconImageView.setImageDrawable(resources.getDrawable(R.drawable.ic_baseline_arrow_drop_up_24px));
}
- ((NavHeaderViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
if (isInMainPage) {
if (requireAuthToAccountSection) {
BiometricManager biometricManager = BiometricManager.from(appCompatActivity);
@@ -300,15 +312,27 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24px);
}
type = 0;
- } else if (position == 6 - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)) {
+ } else if (position == (ACCOUNT_SECTION_ITEMS + 2) - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)) {
+ ((MenuGroupTitleViewHolder) holder).titleTextView.setText(R.string.label_reddit);
+ if (collapseRedditSection) {
+ ((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_up_24px);
+ } else {
+ ((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24px);
+ }
+ type = 1;
+ } else if (position == (ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS + 3)
+ - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)) {
((MenuGroupTitleViewHolder) holder).titleTextView.setText(R.string.label_post);
if (collapsePostSection) {
((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_up_24px);
} else {
((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24px);
}
- type = 1;
- } else if (position == 12 - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ type = 2;
+ } else if (position == (ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS + POST_SECTION_ITEMS + 4)
+ - (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)) {
((MenuGroupTitleViewHolder) holder).titleTextView.setText(R.string.label_preferences);
if (collapsePreferencesSection) {
@@ -316,10 +340,11 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
} else {
((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24px);
}
- type = 2;
+ type = 3;
} else {
if (!hideFavoriteSubredditsSection && !favoriteSubscribedSubreddits.isEmpty() && position == CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)) {
((MenuGroupTitleViewHolder) holder).titleTextView.setText(R.string.favorites);
@@ -328,7 +353,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
} else {
((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24px);
}
- type = 3;
+ type = 4;
} else {
((MenuGroupTitleViewHolder) holder).titleTextView.setText(R.string.subscriptions);
if (collapseSubscribedSubredditsSection) {
@@ -336,11 +361,11 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
} else {
((MenuGroupTitleViewHolder) holder).collapseIndicatorImageView.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24px);
}
- type = 4;
+ type = 5;
}
}
- ((MenuGroupTitleViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
switch (type) {
case 0:
if (collapseAccountSection) {
@@ -352,6 +377,15 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
}
break;
case 1:
+ if (collapseRedditSection) {
+ collapseRedditSection = !collapseRedditSection;
+ notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, REDDIT_SECTION_ITEMS);
+ } else {
+ collapseRedditSection = !collapseRedditSection;
+ notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, REDDIT_SECTION_ITEMS);
+ }
+ break;
+ case 2:
if (collapsePostSection) {
collapsePostSection = !collapsePostSection;
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, POST_SECTION_ITEMS);
@@ -360,7 +394,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, POST_SECTION_ITEMS);
}
break;
- case 2:
+ case 3:
if (collapsePreferencesSection) {
collapsePreferencesSection = !collapsePreferencesSection;
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, PREFERENCES_SECTION_ITEMS);
@@ -369,7 +403,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, PREFERENCES_SECTION_ITEMS);
}
break;
- case 3:
+ case 4:
if (collapseFavoriteSubredditsSection) {
collapseFavoriteSubredditsSection = !collapseFavoriteSubredditsSection;
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, favoriteSubscribedSubreddits.size());
@@ -378,7 +412,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, favoriteSubscribedSubreddits.size());
}
break;
- case 4:
+ case 5:
if (collapseSubscribedSubredditsSection) {
collapseSubscribedSubredditsSection = !collapseSubscribedSubredditsSection;
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, subscribedSubreddits.size());
@@ -398,14 +432,28 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
if (isInMainPage) {
if (isLoggedIn) {
int pseudoPosition = position;
- if (collapseAccountSection && collapsePostSection) {
- pseudoPosition += ACCOUNT_SECTION_ITEMS + POST_SECTION_ITEMS;
- } else if (collapseAccountSection && collapsePreferencesSection) {
- pseudoPosition += ACCOUNT_SECTION_ITEMS;
+ if (collapseAccountSection && collapseRedditSection && collapsePostSection) {
+ pseudoPosition += ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS + POST_SECTION_ITEMS;
+ } else if (collapseAccountSection && collapseRedditSection) {
+ pseudoPosition += ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS;
+ } else if (collapseAccountSection && collapsePostSection) {
+ if (position > REDDIT_SECTION_ITEMS + 2) {
+ pseudoPosition += ACCOUNT_SECTION_ITEMS + POST_SECTION_ITEMS;
+ } else {
+ pseudoPosition += ACCOUNT_SECTION_ITEMS;
+ }
+ } else if (collapseRedditSection && collapsePostSection) {
+ if (position > ACCOUNT_SECTION_ITEMS + 1) {
+ pseudoPosition += REDDIT_SECTION_ITEMS + POST_SECTION_ITEMS;
+ }
} else if (collapseAccountSection) {
pseudoPosition += ACCOUNT_SECTION_ITEMS;
- } else if (collapsePostSection) {
+ } else if (collapseRedditSection) {
if (position > ACCOUNT_SECTION_ITEMS + 1) {
+ pseudoPosition += REDDIT_SECTION_ITEMS;
+ }
+ } else if (collapsePostSection) {
+ if (position > ACCOUNT_SECTION_ITEMS + REDDIT_SECTION_ITEMS + 2) {
pseudoPosition += POST_SECTION_ITEMS;
}
}
@@ -430,32 +478,40 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
((MenuItemViewHolder) holder).menuTextView.setText(R.string.inbox);
}
((MenuItemViewHolder) holder).imageView.setImageDrawable(ContextCompat.getDrawable(appCompatActivity, R.drawable.ic_inbox_24dp));
- ((MenuItemViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(appCompatActivity, InboxActivity.class);
appCompatActivity.startActivity(intent);
});
break;
case 7:
+ stringId = R.string.rpan;
+ drawableId = R.drawable.ic_rpan_24dp;
+ break;
+ case 8:
+ stringId = R.string.trending;
+ drawableId = R.drawable.ic_trending_24dp;
+ break;
+ case 10:
stringId = R.string.upvoted;
drawableId = R.drawable.ic_arrow_upward_black_24dp;
break;
- case 8:
+ case 11:
stringId = R.string.downvoted;
drawableId = R.drawable.ic_arrow_downward_black_24dp;
break;
- case 9:
+ case 12:
stringId = R.string.hidden;
drawableId = R.drawable.ic_outline_lock_24dp;
break;
- case 10:
+ case 13:
stringId = R.string.account_saved_thing_activity_label;
drawableId = R.drawable.ic_outline_bookmarks_24dp;
break;
- case 11:
+ case 14:
stringId = R.string.gilded;
drawableId = R.drawable.ic_star_border_24dp;
break;
- case 13:
+ case 16:
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
stringId = R.string.dark_theme;
drawableId = R.drawable.ic_dark_theme_24dp;
@@ -464,7 +520,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
drawableId = R.drawable.ic_light_theme_24dp;
}
break;
- case 14:
+ case 17:
setOnClickListener = false;
if (isNSFWEnabled) {
stringId = R.string.disable_nsfw;
@@ -474,21 +530,21 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
drawableId = R.drawable.ic_nsfw_on_24dp;
}
- ((MenuItemViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
if (isNSFWEnabled) {
isNSFWEnabled = false;
((MenuItemViewHolder) holder).menuTextView.setText(R.string.enable_nsfw);
- ((MenuItemViewHolder) holder).imageView.setImageDrawable(appCompatActivity.getDrawable(R.drawable.ic_nsfw_on_24dp));
+ ((MenuItemViewHolder) holder).imageView.setImageDrawable(ContextCompat.getDrawable(appCompatActivity, R.drawable.ic_nsfw_on_24dp));
itemClickListener.onMenuClick(R.string.disable_nsfw);
} else {
isNSFWEnabled = true;
((MenuItemViewHolder) holder).menuTextView.setText(R.string.disable_nsfw);
- ((MenuItemViewHolder) holder).imageView.setImageDrawable(appCompatActivity.getDrawable(R.drawable.ic_nsfw_off_24dp));
+ ((MenuItemViewHolder) holder).imageView.setImageDrawable(ContextCompat.getDrawable(appCompatActivity, R.drawable.ic_nsfw_off_24dp));
itemClickListener.onMenuClick(R.string.enable_nsfw);
}
});
break;
- case 15:
+ case 18:
stringId = R.string.settings;
drawableId = R.drawable.ic_settings_24dp;
}
@@ -517,16 +573,16 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
drawableId = R.drawable.ic_nsfw_on_24dp;
}
- ((MenuItemViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
if (isNSFWEnabled) {
isNSFWEnabled = false;
((MenuItemViewHolder) holder).menuTextView.setText(R.string.enable_nsfw);
- ((MenuItemViewHolder) holder).imageView.setImageDrawable(appCompatActivity.getDrawable(R.drawable.ic_nsfw_on_24dp));
+ ((MenuItemViewHolder) holder).imageView.setImageDrawable(ContextCompat.getDrawable(appCompatActivity, R.drawable.ic_nsfw_on_24dp));
itemClickListener.onMenuClick(R.string.disable_nsfw);
} else {
isNSFWEnabled = true;
((MenuItemViewHolder) holder).menuTextView.setText(R.string.disable_nsfw);
- ((MenuItemViewHolder) holder).imageView.setImageDrawable(appCompatActivity.getDrawable(R.drawable.ic_nsfw_off_24dp));
+ ((MenuItemViewHolder) holder).imageView.setImageDrawable(ContextCompat.getDrawable(appCompatActivity, R.drawable.ic_nsfw_off_24dp));
itemClickListener.onMenuClick(R.string.enable_nsfw);
}
});
@@ -557,15 +613,16 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
if (stringId != 0) {
((MenuItemViewHolder) holder).menuTextView.setText(stringId);
- ((MenuItemViewHolder) holder).imageView.setImageDrawable(appCompatActivity.getDrawable(drawableId));
+ ((MenuItemViewHolder) holder).imageView.setImageDrawable(ContextCompat.getDrawable(appCompatActivity, drawableId));
if (setOnClickListener) {
int finalStringId = stringId;
- ((MenuItemViewHolder) holder).itemView.setOnClickListener(view -> itemClickListener.onMenuClick(finalStringId));
+ holder.itemView.setOnClickListener(view -> itemClickListener.onMenuClick(finalStringId));
}
}
} else if (holder instanceof FavoriteSubscribedThingViewHolder) {
SubscribedSubredditData subreddit = favoriteSubscribedSubreddits.get(position - (CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0))
- 1);
@@ -584,17 +641,19 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
.into(((FavoriteSubscribedThingViewHolder) holder).iconGifImageView);
}
- ((FavoriteSubscribedThingViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
itemClickListener.onSubscribedSubredditClick(subredditName);
});
} else if (holder instanceof SubscribedThingViewHolder) {
SubscribedSubredditData subreddit = favoriteSubscribedSubreddits.isEmpty() || hideFavoriteSubredditsSection ? subscribedSubreddits.get(position - (CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0))
- 1)
: subscribedSubreddits.get(position - (CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0))
- (collapseFavoriteSubredditsSection ? 0 : favoriteSubscribedSubreddits.size())
@@ -614,7 +673,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
.into(((SubscribedThingViewHolder) holder).iconGifImageView);
}
- ((SubscribedThingViewHolder) holder).itemView.setOnClickListener(view -> {
+ holder.itemView.setOnClickListener(view -> {
itemClickListener.onSubscribedSubredditClick(subredditName);
});
} else if (holder instanceof AccountViewHolder) {
@@ -623,7 +682,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
.into(((AccountViewHolder) holder).profileImageGifImageView);
((AccountViewHolder) holder).usernameTextView.setText(accounts.get(position - 1).getAccountName());
- ((AccountViewHolder) holder).itemView.setOnClickListener(view ->
+ holder.itemView.setOnClickListener(view ->
itemClickListener.onAccountClick(accounts.get(position - 1).getAccountName()));
}
}
@@ -668,18 +727,21 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
if (hideFavoriteSubredditsSection && hideSubscribedSubredditsSection) {
return CURRENT_MENU_ITEMS
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0);
} else if (hideFavoriteSubredditsSection) {
return CURRENT_MENU_ITEMS
+ (subscribedSubreddits.isEmpty() ? 0 : subscribedSubreddits.size() + 1)
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)
- (collapseSubscribedSubredditsSection ? subscribedSubreddits.size() : 0);
} else if (hideSubscribedSubredditsSection) {
return CURRENT_MENU_ITEMS + (favoriteSubscribedSubreddits.isEmpty() ? 0 : favoriteSubscribedSubreddits.size() + 1)
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)
- (collapseFavoriteSubredditsSection ? favoriteSubscribedSubreddits.size() : 0);
@@ -687,6 +749,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
return CURRENT_MENU_ITEMS + (favoriteSubscribedSubreddits.isEmpty() ? 0 : favoriteSubscribedSubreddits.size() + 1)
+ (subscribedSubreddits.isEmpty() ? 0 : subscribedSubreddits.size() + 1)
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0)
- (collapseFavoriteSubredditsSection ? favoriteSubscribedSubreddits.size() : 0)
@@ -694,6 +757,7 @@ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<Re
}
return CURRENT_MENU_ITEMS - 1
- (collapseAccountSection ? ACCOUNT_SECTION_ITEMS : 0)
+ - (collapseRedditSection ? REDDIT_SECTION_ITEMS : 0)
- (collapsePostSection ? POST_SECTION_ITEMS : 0)
- (collapsePreferencesSection ? PREFERENCES_SECTION_ITEMS : 0);
} else {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostDetailRecyclerViewAdapter.java
index a3e8dbb4..5529f1fd 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/CommentAndPostRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostDetailRecyclerViewAdapter.java
@@ -1,5 +1,7 @@
package ml.docilealligator.infinityforreddit.adapters;
+import static ml.docilealligator.infinityforreddit.activities.CommentActivity.WRITE_COMMENT_REQUEST_CODE;
+
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
@@ -20,9 +22,7 @@ import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.Button;
import android.widget.ImageView;
-import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
@@ -35,7 +35,6 @@ import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.RequestBuilder;
@@ -52,7 +51,6 @@ import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.libRG.CustomTextView;
-import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import org.commonmark.ext.gfm.tables.TableBlock;
@@ -103,15 +101,12 @@ import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity;
import ml.docilealligator.infinityforreddit.activities.ViewVideoActivity;
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;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.UrlMenuBottomSheetFragment;
-import ml.docilealligator.infinityforreddit.comment.Comment;
-import ml.docilealligator.infinityforreddit.comment.FetchComment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.customviews.AspectRatioGifImageView;
-import ml.docilealligator.infinityforreddit.customviews.CommentIndentationView;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.customviews.MarkwonLinearLayoutManager;
import ml.docilealligator.infinityforreddit.fragments.ViewPostDetailFragment;
import ml.docilealligator.infinityforreddit.post.Post;
@@ -122,9 +117,7 @@ import ml.docilealligator.infinityforreddit.utils.Utils;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
-import static ml.docilealligator.infinityforreddit.activities.CommentActivity.WRITE_COMMENT_REQUEST_CODE;
-
-public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements CacheManager {
+public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements CacheManager {
private static final int VIEW_TYPE_POST_DETAIL_VIDEO_AUTOPLAY = 1;
private static final int VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW = 2;
private static final int VIEW_TYPE_POST_DETAIL_IMAGE = 3;
@@ -133,15 +126,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private static final int VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK = 6;
private static final int VIEW_TYPE_POST_DETAIL_GALLERY = 7;
private static final int VIEW_TYPE_POST_DETAIL_TEXT_TYPE = 8;
- private static final int VIEW_TYPE_FIRST_LOADING = 9;
- private static final int VIEW_TYPE_FIRST_LOADING_FAILED = 10;
- private static final int VIEW_TYPE_NO_COMMENT_PLACEHOLDER = 11;
- private static final int VIEW_TYPE_COMMENT = 12;
- private static final int VIEW_TYPE_COMMENT_FULLY_COLLAPSED = 13;
- private static final int VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS = 14;
- private static final int VIEW_TYPE_IS_LOADING_MORE_COMMENTS = 15;
- private static final int VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED = 16;
- private static final int VIEW_TYPE_VIEW_ALL_COMMENTS = 17;
private AppCompatActivity mActivity;
private ViewPostDetailFragment mFragment;
@@ -153,63 +137,47 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private RequestManager mGlide;
private Markwon mPostDetailMarkwon;
- private Markwon mCommentMarkwon;
private final MarkwonAdapter mMarkwonAdapter;
private int mImageViewWidth;
private String mAccessToken;
private String mAccountName;
private Post mPost;
- private ArrayList<Comment> mVisibleComments;
private String mSubredditNamePrefixed;
private Locale mLocale;
- private String mSingleCommentId;
- private boolean mIsSingleCommentThreadMode;
private boolean mNeedBlurNsfw;
private boolean mDoNotBlurNsfwInNsfwSubreddits;
private boolean mNeedBlurSpoiler;
private boolean mVoteButtonsOnTheRight;
private boolean mShowElapsedTime;
private String mTimeFormatPattern;
- private boolean mExpandChildren;
- private boolean mCommentToolbarHidden;
- private boolean mCommentToolbarHideOnClick;
- private boolean mSwapTapAndLong;
- private boolean mShowCommentDivider;
private boolean mShowAbsoluteNumberOfVotes;
private boolean mAutoplay = false;
private boolean mAutoplayNsfwVideos;
private boolean mMuteAutoplayingVideos;
- private boolean mFullyCollapseComment;
private double mStartAutoplayVisibleAreaOffset;
private boolean mMuteNSFWVideo;
private boolean mAutomaticallyTryRedgifs;
private boolean mDataSavingMode;
private boolean mDisableImagePreview;
private boolean mOnlyDisablePreviewInVideoAndGifPosts;
- private CommentRecyclerViewAdapterCallback mCommentRecyclerViewAdapterCallback;
- private boolean isInitiallyLoading;
- private boolean isInitiallyLoadingFailed;
- private boolean mHasMoreComments;
- private boolean loadMoreCommentsFailed;
-
- private int depthThreshold = 5;
- private int mColorPrimaryLightTheme;
+ private boolean mHidePostType;
+ private boolean mHidePostFlair;
+ private boolean mHideTheNumberOfAwards;
+ private boolean mHideSubredditAndUserPrefix;
+ private boolean mHideTheNumberOfVotes;
+ private boolean mHideTheNumberOfComments;
+ private boolean mSeparatePostAndComments;
+ private PostDetailRecyclerViewAdapterCallback mPostDetailRecyclerViewAdapterCallback;
+
private int mColorAccent;
- private int mCircularProgressBarBackgroundColor;
private int mCardViewColor;
private int mSecondaryTextColor;
private int mPostTitleColor;
private int mPrimaryTextColor;
- private int mCommentTextColor;
- private int mCommentBackgroundColor;
private int mPostTypeBackgroundColor;
private int mPostTypeTextColor;
- private int mDividerColor;
private int mSubredditColor;
private int mUsernameColor;
- private int mSubmitterColor;
- private int mModeratorColor;
- private int mCurrentUserColor;
private int mAuthorFlairTextColor;
private int mSpoilerBackgroundColor;
private int mSpoilerTextColor;
@@ -225,29 +193,25 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private int mNoPreviewPostTypeIconTint;
private int mUpvotedColor;
private int mDownvotedColor;
- private int mSingleCommentThreadBackgroundColor;
private int mVoteAndReplyUnavailableVoteButtonColor;
- private int mButtonTextColor;
private int mPostIconAndInfoColor;
- private int mCommentIconAndInfoColor;
- private int mFullyCollapsedCommentBackgroundColor;
- private int mAwardedCommentBackgroundColor;
- private Integer[] verticalBlockColors;
private Drawable mCommentIcon;
private float mScale;
private ExoCreator mExoCreator;
- public CommentAndPostRecyclerViewAdapter(AppCompatActivity activity, ViewPostDetailFragment fragment, Executor executor, CustomThemeWrapper customThemeWrapper,
- Retrofit retrofit, Retrofit oauthRetrofit, Retrofit gfycatRetrofit,
- Retrofit redgifsRetrofit,
- RedditDataRoomDatabase redditDataRoomDatabase, RequestManager glide,
- int imageViewWidth, String accessToken, String accountName,
- Post post, Locale locale, String singleCommentId,
- boolean isSingleCommentThreadMode,
- SharedPreferences sharedPreferences,
- SharedPreferences nsfwAndSpoilerSharedPreferences, ExoCreator exoCreator,
- CommentRecyclerViewAdapterCallback commentRecyclerViewAdapterCallback) {
+ public PostDetailRecyclerViewAdapter(AppCompatActivity activity, ViewPostDetailFragment fragment,
+ Executor executor, CustomThemeWrapper customThemeWrapper,
+ Retrofit retrofit, Retrofit oauthRetrofit, Retrofit gfycatRetrofit,
+ Retrofit redgifsRetrofit, RedditDataRoomDatabase redditDataRoomDatabase,
+ RequestManager glide, int imageViewWidth,
+ boolean separatePostAndComments, String accessToken,
+ String accountName, Post post, Locale locale,
+ SharedPreferences sharedPreferences,
+ SharedPreferences nsfwAndSpoilerSharedPreferences,
+ SharedPreferences postDetailsSharedPreferences,
+ ExoCreator exoCreator,
+ PostDetailRecyclerViewAdapterCallback postDetailRecyclerViewAdapterCallback) {
mActivity = activity;
mFragment = fragment;
mExecutor = executor;
@@ -258,8 +222,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mRedditDataRoomDatabase = redditDataRoomDatabase;
mGlide = glide;
mSecondaryTextColor = customThemeWrapper.getSecondaryTextColor();
- mCommentTextColor = customThemeWrapper.getCommentColor();
- int commentSpoilerBackgroundColor = mCommentTextColor | 0xFF000000;
int markdownColor = customThemeWrapper.getPostContentColor();
int postSpoilerBackgroundColor = markdownColor | 0xFF000000;
int linkColor = customThemeWrapper.getLinkColor();
@@ -369,108 +331,18 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(TableEntryPlugin.create(mActivity))
.build();
- mCommentMarkwon = Markwon.builder(mActivity)
- .usePlugin(HtmlPlugin.create())
- .usePlugin(new AbstractMarkwonPlugin() {
- @NonNull
- @Override
- public String processMarkdown(@NonNull String markdown) {
- StringBuilder markdownStringBuilder = new StringBuilder(markdown);
- Pattern spoilerPattern = Pattern.compile(">![\\S\\s]*?!<");
- Matcher matcher = spoilerPattern.matcher(markdownStringBuilder);
- while (matcher.find()) {
- markdownStringBuilder.replace(matcher.start(), matcher.start() + 1, "&gt;");
- }
- return super.processMarkdown(markdownStringBuilder.toString());
- }
-
- @Override
- public void afterSetText(@NonNull TextView textView) {
- SpannableStringBuilder markdownStringBuilder = new SpannableStringBuilder(textView.getText().toString());
- Pattern spoilerPattern = Pattern.compile(">![\\S\\s]*?!<");
- Matcher matcher = spoilerPattern.matcher(markdownStringBuilder);
- int start = 0;
- boolean find = false;
- while (matcher.find(start)) {
- if (markdownStringBuilder.length() < 4
- || matcher.start() < 0
- || matcher.end() > markdownStringBuilder.length()) {
- break;
- }
- find = true;
- markdownStringBuilder.delete(matcher.end() - 2, matcher.end());
- markdownStringBuilder.delete(matcher.start(), matcher.start() + 2);
- ClickableSpan clickableSpan = new ClickableSpan() {
- private boolean isShowing = false;
- @Override
- public void updateDrawState(@NonNull TextPaint ds) {
- if (isShowing) {
- super.updateDrawState(ds);
- ds.setColor(mCommentTextColor);
- } else {
- ds.bgColor = commentSpoilerBackgroundColor;
- ds.setColor(mCommentTextColor);
- }
- ds.setUnderlineText(false);
- }
-
- @Override
- public void onClick(@NonNull View view) {
- isShowing = !isShowing;
- view.invalidate();
- }
- };
- markdownStringBuilder.setSpan(clickableSpan, matcher.start(), matcher.end() - 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- start = matcher.end() - 4;
- }
- if (find) {
- textView.setText(markdownStringBuilder);
- }
- }
-
- @Override
- public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
- builder.linkResolver((view, link) -> {
- Intent intent = new Intent(mActivity, LinkResolverActivity.class);
- Uri uri = Uri.parse(link);
- intent.setData(uri);
- intent.putExtra(LinkResolverActivity.EXTRA_IS_NSFW, mPost.isNSFW());
- mActivity.startActivity(intent);
- });
- }
-
- @Override
- public void configureTheme(@NonNull MarkwonTheme.Builder builder) {
- builder.linkColor(linkColor);
- }
- })
- .usePlugin(StrikethroughPlugin.create())
- .usePlugin(MovementMethodPlugin.create(BetterLinkMovementMethod.linkify(Linkify.WEB_URLS, activity).setOnLinkLongClickListener((textView, url) -> {
- if (activity != null && !activity.isDestroyed() && !activity.isFinishing()) {
- UrlMenuBottomSheetFragment urlMenuBottomSheetFragment = new UrlMenuBottomSheetFragment();
- Bundle bundle = new Bundle();
- bundle.putString(UrlMenuBottomSheetFragment.EXTRA_URL, url);
- urlMenuBottomSheetFragment.setArguments(bundle);
- urlMenuBottomSheetFragment.show(activity.getSupportFragmentManager(), urlMenuBottomSheetFragment.getTag());
- }
- return true;
- })))
- .usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
- .build();
mMarkwonAdapter = MarkwonAdapter.builder(R.layout.adapter_default_entry, R.id.text)
.include(TableBlock.class, TableEntry.create(builder -> builder
.tableLayout(R.layout.adapter_table_block, R.id.table_layout)
.textLayoutIsRoot(R.layout.view_table_entry_cell)))
.build();
mImageViewWidth = imageViewWidth;
+ mSeparatePostAndComments = separatePostAndComments;
mAccessToken = accessToken;
mAccountName = accountName;
mPost = post;
- mVisibleComments = new ArrayList<>();
mSubredditNamePrefixed = post.getSubredditNamePrefixed();
mLocale = locale;
- mSingleCommentId = singleCommentId;
- mIsSingleCommentThreadMode = isSingleCommentThreadMode;
mNeedBlurNsfw = nsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.BLUR_NSFW_BASE, true);
mDoNotBlurNsfwInNsfwSubreddits = nsfwAndSpoilerSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.DO_NOT_BLUR_NSFW_IN_NSFW_SUBREDDITS, false);
@@ -478,11 +350,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mVoteButtonsOnTheRight = sharedPreferences.getBoolean(SharedPreferencesUtils.VOTE_BUTTONS_ON_THE_RIGHT_KEY, false);
mShowElapsedTime = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_ELAPSED_TIME_KEY, false);
mTimeFormatPattern = sharedPreferences.getString(SharedPreferencesUtils.TIME_FORMAT_KEY, SharedPreferencesUtils.TIME_FORMAT_DEFAULT_VALUE);
- mExpandChildren = !sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_TOP_LEVEL_COMMENTS_FIRST, false);
- mCommentToolbarHidden = sharedPreferences.getBoolean(SharedPreferencesUtils.COMMENT_TOOLBAR_HIDDEN, false);
- mCommentToolbarHideOnClick = sharedPreferences.getBoolean(SharedPreferencesUtils.COMMENT_TOOLBAR_HIDE_ON_CLICK, true);
- mSwapTapAndLong = sharedPreferences.getBoolean(SharedPreferencesUtils.SWAP_TAP_AND_LONG_COMMENTS, false);
- mShowCommentDivider = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_COMMENT_DIVIDER, false);
mShowAbsoluteNumberOfVotes = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_ABSOLUTE_NUMBER_OF_VOTES, true);
String autoplayString = sharedPreferences.getString(SharedPreferencesUtils.VIDEO_AUTOPLAY, SharedPreferencesUtils.VIDEO_AUTOPLAY_VALUE_NEVER);
@@ -494,7 +361,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
}
mAutoplayNsfwVideos = sharedPreferences.getBoolean(SharedPreferencesUtils.AUTOPLAY_NSFW_VIDEOS, true);
mMuteAutoplayingVideos = sharedPreferences.getBoolean(SharedPreferencesUtils.MUTE_AUTOPLAYING_VIDEOS, true);
- mFullyCollapseComment = sharedPreferences.getBoolean(SharedPreferencesUtils.FULLY_COLLAPSE_COMMENT, false);
Resources resources = activity.getResources();
mStartAutoplayVisibleAreaOffset = resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ?
@@ -513,26 +379,22 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mDisableImagePreview = sharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_IMAGE_PREVIEW, false);
mOnlyDisablePreviewInVideoAndGifPosts = sharedPreferences.getBoolean(SharedPreferencesUtils.ONLY_DISABLE_PREVIEW_IN_VIDEO_AND_GIF_POSTS, false);
- mCommentRecyclerViewAdapterCallback = commentRecyclerViewAdapterCallback;
- isInitiallyLoading = true;
- isInitiallyLoadingFailed = false;
- mHasMoreComments = false;
- loadMoreCommentsFailed = false;
+ mHidePostType = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_POST_TYPE, false);
+ mHidePostFlair = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_POST_FLAIR, false);
+ mHideTheNumberOfAwards = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_AWARDS, false);
+ mHideSubredditAndUserPrefix = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBREDDIT_AND_USER_PREFIX, false);
+ mHideTheNumberOfVotes = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_VOTES, false);
+ mHideTheNumberOfComments = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_COMMENTS, false);
+
+ mPostDetailRecyclerViewAdapterCallback = postDetailRecyclerViewAdapterCallback;
mScale = resources.getDisplayMetrics().density;
- mColorPrimaryLightTheme = customThemeWrapper.getColorPrimaryLightTheme();
mColorAccent = customThemeWrapper.getColorAccent();
- mCircularProgressBarBackgroundColor = customThemeWrapper.getCircularProgressBarBackground();
mCardViewColor = customThemeWrapper.getCardViewBackgroundColor();
mPostTitleColor = customThemeWrapper.getPostTitleColor();
mPrimaryTextColor = customThemeWrapper.getPrimaryTextColor();
- mDividerColor = customThemeWrapper.getDividerColor();
- mCommentBackgroundColor = customThemeWrapper.getCommentBackgroundColor();
mPostTypeBackgroundColor = customThemeWrapper.getPostTypeBackgroundColor();
mPostTypeTextColor = customThemeWrapper.getPostTypeTextColor();
- mSubmitterColor = customThemeWrapper.getSubmitter();
- mModeratorColor = customThemeWrapper.getModerator();
- mCurrentUserColor = customThemeWrapper.getCurrentUser();
mAuthorFlairTextColor = customThemeWrapper.getAuthorFlairTextColor();
mSpoilerBackgroundColor = customThemeWrapper.getSpoilerBackgroundColor();
mSpoilerTextColor = customThemeWrapper.getSpoilerTextColor();
@@ -550,23 +412,8 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mUsernameColor = customThemeWrapper.getUsername();
mUpvotedColor = customThemeWrapper.getUpvoted();
mDownvotedColor = customThemeWrapper.getDownvoted();
- mSingleCommentThreadBackgroundColor = customThemeWrapper.getSingleCommentThreadBackgroundColor();
mVoteAndReplyUnavailableVoteButtonColor = customThemeWrapper.getVoteAndReplyUnavailableButtonColor();
- mButtonTextColor = customThemeWrapper.getButtonTextColor();
mPostIconAndInfoColor = customThemeWrapper.getPostIconAndInfoColor();
- mCommentIconAndInfoColor = customThemeWrapper.getCommentIconAndInfoColor();
- mFullyCollapsedCommentBackgroundColor = customThemeWrapper.getFullyCollapsedCommentBackgroundColor();
- mAwardedCommentBackgroundColor = customThemeWrapper.getAwardedCommentBackgroundColor();
-
- verticalBlockColors = new Integer[] {
- customThemeWrapper.getCommentVerticalBarColor1(),
- customThemeWrapper.getCommentVerticalBarColor2(),
- customThemeWrapper.getCommentVerticalBarColor3(),
- customThemeWrapper.getCommentVerticalBarColor4(),
- customThemeWrapper.getCommentVerticalBarColor5(),
- customThemeWrapper.getCommentVerticalBarColor6(),
- customThemeWrapper.getCommentVerticalBarColor7(),
- };
mCommentIcon = activity.getDrawable(R.drawable.ic_comment_grey_24dp);
if (mCommentIcon != null) {
@@ -578,91 +425,35 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
@Override
public int getItemViewType(int position) {
- if (position == 0) {
- switch (mPost.getPostType()) {
- case Post.VIDEO_TYPE:
- if (mAutoplay) {
- if (!mAutoplayNsfwVideos && mPost.isNSFW()) {
- return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
- }
- return VIEW_TYPE_POST_DETAIL_VIDEO_AUTOPLAY;
- } else {
- return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
- }
- case Post.GIF_TYPE:
- if (mAutoplay) {
- if (!mAutoplayNsfwVideos && mPost.isNSFW()) {
- return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
- }
- return VIEW_TYPE_POST_DETAIL_GIF_AUTOPLAY;
- } else {
+ switch (mPost.getPostType()) {
+ case Post.VIDEO_TYPE:
+ if (mAutoplay && !mSeparatePostAndComments) {
+ if (!mAutoplayNsfwVideos && mPost.isNSFW()) {
return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
}
- case Post.IMAGE_TYPE:
- return VIEW_TYPE_POST_DETAIL_IMAGE;
- case Post.LINK_TYPE:
- return VIEW_TYPE_POST_DETAIL_LINK;
- case Post.NO_PREVIEW_LINK_TYPE:
- return VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK;
- case Post.GALLERY_TYPE:
- return VIEW_TYPE_POST_DETAIL_GALLERY;
- default:
- return VIEW_TYPE_POST_DETAIL_TEXT_TYPE;
- }
- }
-
- if (mVisibleComments.size() == 0) {
- if (position == 1) {
- if (isInitiallyLoading) {
- return VIEW_TYPE_FIRST_LOADING;
- } else if (isInitiallyLoadingFailed) {
- return VIEW_TYPE_FIRST_LOADING_FAILED;
- } else {
- return VIEW_TYPE_NO_COMMENT_PLACEHOLDER;
- }
- }
- }
-
- if (mIsSingleCommentThreadMode) {
- if (position == 1) {
- return VIEW_TYPE_VIEW_ALL_COMMENTS;
- }
-
- if (position == mVisibleComments.size() + 2) {
- if (mHasMoreComments) {
- return VIEW_TYPE_IS_LOADING_MORE_COMMENTS;
+ return VIEW_TYPE_POST_DETAIL_VIDEO_AUTOPLAY;
} else {
- return VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED;
- }
- }
-
- Comment comment = mVisibleComments.get(position - 2);
- if (comment.getPlaceholderType() == Comment.NOT_PLACEHOLDER) {
- if (mFullyCollapseComment && !comment.isExpanded() && comment.hasExpandedBefore()) {
- return VIEW_TYPE_COMMENT_FULLY_COLLAPSED;
+ return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
}
- return VIEW_TYPE_COMMENT;
- } else {
- return VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS;
- }
- } else {
- if (position == mVisibleComments.size() + 1) {
- if (mHasMoreComments) {
- return VIEW_TYPE_IS_LOADING_MORE_COMMENTS;
+ case Post.GIF_TYPE:
+ if (mAutoplay) {
+ if (!mAutoplayNsfwVideos && mPost.isNSFW()) {
+ return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
+ }
+ return VIEW_TYPE_POST_DETAIL_GIF_AUTOPLAY;
} else {
- return VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED;
- }
- }
-
- Comment comment = mVisibleComments.get(position - 1);
- if (comment.getPlaceholderType() == Comment.NOT_PLACEHOLDER) {
- if (mFullyCollapseComment && !comment.isExpanded() && comment.hasExpandedBefore()) {
- return VIEW_TYPE_COMMENT_FULLY_COLLAPSED;
- }
- return VIEW_TYPE_COMMENT;
- } else {
- return VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS;
- }
+ return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
+ }
+ case Post.IMAGE_TYPE:
+ return VIEW_TYPE_POST_DETAIL_IMAGE;
+ case Post.LINK_TYPE:
+ return VIEW_TYPE_POST_DETAIL_LINK;
+ case Post.NO_PREVIEW_LINK_TYPE:
+ return VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK;
+ case Post.GALLERY_TYPE:
+ return VIEW_TYPE_POST_DETAIL_GALLERY;
+ default:
+ return VIEW_TYPE_POST_DETAIL_TEXT_TYPE;
}
}
@@ -702,26 +493,8 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
return new PostDetailNoPreviewViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_detail_no_preview, parent, false));
case VIEW_TYPE_POST_DETAIL_GALLERY:
return new PostDetailGalleryViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_detail_gallery, parent, false));
- case VIEW_TYPE_POST_DETAIL_TEXT_TYPE:
- return new PostDetailTextViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_detail_text, parent, false));
- case VIEW_TYPE_FIRST_LOADING:
- return new LoadCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_comments, parent, false));
- case VIEW_TYPE_FIRST_LOADING_FAILED:
- return new LoadCommentsFailedViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_comments_failed_placeholder, parent, false));
- case VIEW_TYPE_NO_COMMENT_PLACEHOLDER:
- return new NoCommentViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_no_comment_placeholder, parent, false));
- case VIEW_TYPE_COMMENT:
- return new CommentViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false));
- case VIEW_TYPE_COMMENT_FULLY_COLLAPSED:
- return new CommentFullyCollapsedViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_fully_collapsed, parent, false));
- case VIEW_TYPE_LOAD_MORE_CHILD_COMMENTS:
- return new LoadMoreChildCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_more_comments_placeholder, parent, false));
- case VIEW_TYPE_IS_LOADING_MORE_COMMENTS:
- return new IsLoadingMoreCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_footer_loading, parent, false));
- case VIEW_TYPE_LOAD_MORE_COMMENTS_FAILED:
- return new LoadMoreCommentsFailedViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_footer_error, parent, false));
default:
- return new ViewAllCommentsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_all_comments, parent, false));
+ return new PostDetailTextViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_detail_text, parent, false));
}
}
@@ -767,20 +540,20 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(),
mRedditDataRoomDatabase, mPost.getSubredditNamePrefixed().substring(2),
mRetrofit, iconImageUrl -> {
- if (iconImageUrl == null || iconImageUrl.equals("")) {
- mGlide.load(R.drawable.subreddit_default_icon)
- .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
- .into(((PostDetailBaseViewHolder) holder).mIconGifImageView);
- } else {
- mGlide.load(iconImageUrl)
- .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
- .error(mGlide.load(R.drawable.subreddit_default_icon)
- .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
- .into(((PostDetailBaseViewHolder) holder).mIconGifImageView);
- }
+ if (iconImageUrl == null || iconImageUrl.equals("")) {
+ mGlide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .into(((PostDetailBaseViewHolder) holder).mIconGifImageView);
+ } else {
+ mGlide.load(iconImageUrl)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .error(mGlide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
+ .into(((PostDetailBaseViewHolder) holder).mIconGifImageView);
+ }
- mPost.setSubredditIconUrl(iconImageUrl);
- });
+ mPost.setSubredditIconUrl(iconImageUrl);
+ });
} else if (!mPost.getSubredditIconUrl().equals("")) {
mGlide.load(mPost.getSubredditIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
@@ -830,8 +603,13 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
((PostDetailBaseViewHolder) holder).mCrosspostImageView.setVisibility(View.VISIBLE);
}
- ((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditNamePrefixed());
- ((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthorNamePrefixed());
+ if (!mHideSubredditAndUserPrefix) {
+ ((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditNamePrefixed());
+ ((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthorNamePrefixed());
+ } else {
+ ((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditName());
+ ((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthor());
+ }
if (mShowElapsedTime) {
((PostDetailBaseViewHolder) holder).mPostTimeTextView.setText(
@@ -852,12 +630,12 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
((PostDetailBaseViewHolder) holder).mSpoilerTextView.setVisibility(View.VISIBLE);
}
- if (mPost.getFlair() != null && !mPost.getFlair().equals("")) {
+ if (!mHidePostFlair && mPost.getFlair() != null && !mPost.getFlair().equals("")) {
((PostDetailBaseViewHolder) holder).mFlairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostDetailBaseViewHolder) holder).mFlairTextView, mPost.getFlair(), false);
}
- if (mPost.getAwards() != null && !mPost.getAwards().equals("")) {
+ if (!mHideTheNumberOfAwards && mPost.getAwards() != null && !mPost.getAwards().equals("")) {
((PostDetailBaseViewHolder) holder).mAwardsTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostDetailBaseViewHolder) holder).mAwardsTextView, mPost.getAwards(), true);
}
@@ -870,7 +648,11 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
((PostDetailBaseViewHolder) holder).mNSFWTextView.setVisibility(View.GONE);
}
- ((PostDetailBaseViewHolder) holder).mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, mPost.getScore() + mPost.getVoteType()));
+ if (!mHideTheNumberOfVotes) {
+ ((PostDetailBaseViewHolder) holder).mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, mPost.getScore() + mPost.getVoteType()));
+ } else {
+ ((PostDetailBaseViewHolder) holder).mScoreTextView.setText(mActivity.getString(R.string.vote));
+ }
((PostDetailBaseViewHolder) holder).commentsCountTextView.setText(Integer.toString(mPost.getNComments()));
@@ -911,16 +693,19 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
}
});
((PostDetailVideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks
- .fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(mGfycatRetrofit, mRedgifsRetrofit,
- mPost.getGfycatId(), mPost.isGfycat(), mAutomaticallyTryRedgifs);
+ .fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(mExecutor, new Handler(),
+ mGfycatRetrofit, mRedgifsRetrofit, mPost.getGfycatId(),
+ mPost.isGfycat(), mAutomaticallyTryRedgifs);
} else {
((PostDetailVideoAutoplayViewHolder) holder).bindVideoUri(Uri.parse(mPost.getVideoUrl()));
}
} else if (holder instanceof PostDetailVideoAndGifPreviewHolder) {
- if (mPost.getPostType() == Post.GIF_TYPE) {
- ((PostDetailVideoAndGifPreviewHolder) holder).mTypeTextView.setText(mActivity.getString(R.string.gif));
- } else {
- ((PostDetailVideoAndGifPreviewHolder) holder).mTypeTextView.setText(mActivity.getString(R.string.video));
+ if (!mHidePostType) {
+ if (mPost.getPostType() == Post.GIF_TYPE) {
+ ((PostDetailVideoAndGifPreviewHolder) holder).mTypeTextView.setText(mActivity.getString(R.string.gif));
+ } else {
+ ((PostDetailVideoAndGifPreviewHolder) holder).mTypeTextView.setText(mActivity.getString(R.string.video));
+ }
}
Post.Preview preview = getSuitablePreview(mPost.getPreviews());
if (preview != null) {
@@ -928,10 +713,12 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
loadImage((PostDetailVideoAndGifPreviewHolder) holder, preview);
}
} else if (holder instanceof PostDetailImageAndGifAutoplayViewHolder) {
- if (mPost.getPostType() == Post.IMAGE_TYPE) {
- ((PostDetailImageAndGifAutoplayViewHolder) holder).mTypeTextView.setText(R.string.image);
- } else {
- ((PostDetailImageAndGifAutoplayViewHolder) holder).mTypeTextView.setText(R.string.gif);
+ if (!mHidePostType) {
+ if (mPost.getPostType() == Post.IMAGE_TYPE) {
+ ((PostDetailImageAndGifAutoplayViewHolder) holder).mTypeTextView.setText(R.string.image);
+ } else {
+ ((PostDetailImageAndGifAutoplayViewHolder) holder).mTypeTextView.setText(R.string.gif);
+ }
}
Post.Preview preview = getSuitablePreview(mPost.getPreviews());
@@ -958,7 +745,9 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
} else if (holder instanceof PostDetailNoPreviewViewHolder) {
if (mPost.getPostType() == Post.LINK_TYPE || mPost.getPostType() == Post.NO_PREVIEW_LINK_TYPE) {
- ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.link);
+ if (!mHidePostType) {
+ ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.link);
+ }
String noPreviewLinkDomain = Uri.parse(mPost.getUrl()).getHost();
((PostDetailNoPreviewViewHolder) holder).mLinkTextView.setVisibility(View.VISIBLE);
((PostDetailNoPreviewViewHolder) holder).mLinkTextView.setText(noPreviewLinkDomain);
@@ -967,27 +756,35 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
((PostDetailNoPreviewViewHolder) holder).mLinkTextView.setVisibility(View.GONE);
switch (mPost.getPostType()) {
case Post.VIDEO_TYPE:
- ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.video);
+ if (!mHidePostType) {
+ ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.video);
+ }
((PostDetailNoPreviewViewHolder) holder).mNoPreviewPostTypeImageView.setImageResource(R.drawable.ic_outline_video_24dp);
break;
case Post.IMAGE_TYPE:
- ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.image);
+ if (!mHidePostType) {
+ ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.image);
+ }
((PostDetailNoPreviewViewHolder) holder).mNoPreviewPostTypeImageView.setImageResource(R.drawable.ic_image_24dp);
break;
case Post.GIF_TYPE:
- ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.gif);
+ if (!mHidePostType) {
+ ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.gif);
+ }
((PostDetailNoPreviewViewHolder) holder).mNoPreviewPostTypeImageView.setImageResource(R.drawable.ic_image_24dp);
break;
case Post.GALLERY_TYPE:
- ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.gallery);
- ((PostDetailNoPreviewViewHolder) holder).mNoPreviewPostTypeImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ if (!mHidePostType) {
+ ((PostDetailNoPreviewViewHolder) holder).mTypeTextView.setText(R.string.gallery);
+ }
+ ((PostDetailNoPreviewViewHolder) holder).mNoPreviewPostTypeImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
break;
}
}
if (mPost.getSelfText() != null && !mPost.getSelfText().equals("")) {
((PostDetailNoPreviewViewHolder) holder).mContentMarkdownView.setVisibility(View.VISIBLE);
- LinearLayoutManager linearLayoutManager = new MarkwonLinearLayoutManager(mActivity, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
+ LinearLayoutManagerBugFixed linearLayoutManager = new MarkwonLinearLayoutManager(mActivity, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
@Override
public void onScrolledLeft() {
((ViewPostDetailActivity) mActivity).lockSwipeRightToGoBack();
@@ -1017,7 +814,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
} else if (holder instanceof PostDetailTextViewHolder) {
if (mPost.getSelfText() != null && !mPost.getSelfText().equals("")) {
((PostDetailTextViewHolder) holder).mContentMarkdownView.setVisibility(View.VISIBLE);
- LinearLayoutManager linearLayoutManager = new MarkwonLinearLayoutManager(mActivity, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
+ LinearLayoutManagerBugFixed linearLayoutManager = new MarkwonLinearLayoutManager(mActivity, new MarkwonLinearLayoutManager.HorizontalScrollViewScrolledListener() {
@Override
public void onScrolledLeft() {
((ViewPostDetailActivity) mActivity).lockSwipeRightToGoBack();
@@ -1034,353 +831,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mMarkwonAdapter.notifyDataSetChanged();
}
}
- } else if (holder instanceof CommentViewHolder) {
- Comment comment = getCurrentComment(position);
- if (comment != null) {
- if (mIsSingleCommentThreadMode && comment.getId().equals(mSingleCommentId)) {
- ((CommentViewHolder) holder).itemView.setBackgroundColor(mSingleCommentThreadBackgroundColor);
- } else if (comment.getAwards() != null && !comment.getAwards().equals("")) {
- ((CommentViewHolder) holder).itemView.setBackgroundColor(mAwardedCommentBackgroundColor);
- }
-
- String authorPrefixed = "u/" + comment.getAuthor();
- ((CommentViewHolder) holder).authorTextView.setText(authorPrefixed);
-
- if (comment.getAuthorFlairHTML() != null && !comment.getAuthorFlairHTML().equals("")) {
- ((CommentViewHolder) holder).authorFlairTextView.setVisibility(View.VISIBLE);
- Utils.setHTMLWithImageToTextView(((CommentViewHolder) holder).authorFlairTextView, comment.getAuthorFlairHTML(), true);
- } else if (comment.getAuthorFlair() != null && !comment.getAuthorFlair().equals("")) {
- ((CommentViewHolder) holder).authorFlairTextView.setVisibility(View.VISIBLE);
- ((CommentViewHolder) holder).authorFlairTextView.setText(comment.getAuthorFlair());
- }
-
- if (comment.isSubmitter()) {
- ((CommentViewHolder) holder).authorTextView.setTextColor(mSubmitterColor);
- Drawable submitterDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_mic_14dp, mSubmitterColor);
- ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
- submitterDrawable, null, null, null);
- } else if (comment.isModerator()) {
- ((CommentViewHolder) holder).authorTextView.setTextColor(mModeratorColor);
- Drawable moderatorDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_verified_user_14dp, mModeratorColor);
- ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
- moderatorDrawable, null, null, null);
- } else if (comment.getAuthor().equals(mAccountName)) {
- ((CommentViewHolder) holder).authorTextView.setTextColor(mCurrentUserColor);
- Drawable currentUserDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_current_user_14dp, mCurrentUserColor);
- ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
- currentUserDrawable, null, null, null);
- }
-
- if (mShowElapsedTime) {
- ((CommentViewHolder) holder).commentTimeTextView.setText(
- Utils.getElapsedTime(mActivity, comment.getCommentTimeMillis()));
- } else {
- ((CommentViewHolder) holder).commentTimeTextView.setText(Utils.getFormattedTime(mLocale, comment.getCommentTimeMillis(), mTimeFormatPattern));
- }
-
- if (mCommentToolbarHidden) {
- ((CommentViewHolder) holder).bottomConstraintLayout.getLayoutParams().height = 0;
- ((CommentViewHolder) holder).topScoreTextView.setVisibility(View.VISIBLE);
- } else {
- ((CommentViewHolder) holder).bottomConstraintLayout.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT;
- ((CommentViewHolder) holder).topScoreTextView.setVisibility(View.GONE);
- }
-
- if (comment.getAwards() != null && !comment.getAwards().equals("")) {
- ((CommentViewHolder) holder).awardsTextView.setVisibility(View.VISIBLE);
- Utils.setHTMLWithImageToTextView(((CommentViewHolder) holder).awardsTextView, comment.getAwards(), true);
- }
-
- mCommentMarkwon.setMarkdown(((CommentViewHolder) holder).commentMarkdownView, comment.getCommentMarkdown());
- ((CommentViewHolder) holder).scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType()));
- ((CommentViewHolder) holder).topScoreTextView.setText(mActivity.getString(R.string.top_score,
- Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType())));
-
- ((CommentViewHolder) holder).commentIndentationView.setLevelAndColors(comment.getDepth(), verticalBlockColors);
- if (comment.getDepth() > depthThreshold) {
- ((CommentViewHolder) holder).saveButton.setVisibility(View.GONE);
- ((CommentViewHolder) holder).replyButton.setVisibility(View.GONE);
- } else {
- ((CommentViewHolder) holder).saveButton.setVisibility(View.VISIBLE);
- ((CommentViewHolder) holder).replyButton.setVisibility(View.VISIBLE);
- }
-
- if (comment.hasReply()) {
- if (comment.isExpanded()) {
- ((CommentViewHolder) holder).expandButton.setImageResource(R.drawable.ic_expand_less_grey_24dp);
- } else {
- ((CommentViewHolder) holder).expandButton.setImageResource(R.drawable.ic_expand_more_grey_24dp);
- }
- ((CommentViewHolder) holder).expandButton.setVisibility(View.VISIBLE);
- }
-
- switch (comment.getVoteType()) {
- case Comment.VOTE_TYPE_UPVOTE:
- ((CommentViewHolder) holder).upvoteButton
- .setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).scoreTextView.setTextColor(mUpvotedColor);
- ((CommentViewHolder) holder).topScoreTextView.setTextColor(mUpvotedColor);
- break;
- case Comment.VOTE_TYPE_DOWNVOTE:
- ((CommentViewHolder) holder).downvoteButton
- .setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).scoreTextView.setTextColor(mDownvotedColor);
- ((CommentViewHolder) holder).topScoreTextView.setTextColor(mDownvotedColor);
- break;
- }
-
- if (mPost.isArchived()) {
- ((CommentViewHolder) holder).replyButton
- .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
- android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).upvoteButton
- .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
- android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).downvoteButton
- .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
- android.graphics.PorterDuff.Mode.SRC_IN);
- }
-
- if (mPost.isLocked()) {
- ((CommentViewHolder) holder).replyButton
- .setColorFilter(mVoteAndReplyUnavailableVoteButtonColor,
- android.graphics.PorterDuff.Mode.SRC_IN);
- }
-
- if (comment.isSaved()) {
- ((CommentViewHolder) holder).saveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
- } else {
- ((CommentViewHolder) holder).saveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
- }
- }
- } else if (holder instanceof CommentFullyCollapsedViewHolder) {
- Comment comment = getCurrentComment(position);
- if (comment != null) {
- String authorWithPrefix = "u/" + comment.getAuthor();
- ((CommentFullyCollapsedViewHolder) holder).usernameTextView.setText(authorWithPrefix);
- if (mShowElapsedTime) {
- ((CommentFullyCollapsedViewHolder) holder).commentTimeTextView.setText(Utils.getElapsedTime(mActivity, comment.getCommentTimeMillis()));
- } else {
- ((CommentFullyCollapsedViewHolder) holder).commentTimeTextView.setText(Utils.getFormattedTime(mLocale, comment.getCommentTimeMillis(), mTimeFormatPattern));
- }
- ((CommentFullyCollapsedViewHolder) holder).scoreTextView.setText(mActivity.getString(R.string.top_score,
- Utils.getNVotes(mShowAbsoluteNumberOfVotes, comment.getScore() + comment.getVoteType())));
- ((CommentFullyCollapsedViewHolder) holder).commentIndentationView.setLevelAndColors(comment.getDepth(), verticalBlockColors);
- }
- } else if (holder instanceof LoadMoreChildCommentsViewHolder) {
- Comment placeholder;
- placeholder = mIsSingleCommentThreadMode ? mVisibleComments.get(holder.getBindingAdapterPosition() - 2)
- : mVisibleComments.get(holder.getBindingAdapterPosition() - 1);
-
- ((LoadMoreChildCommentsViewHolder) holder).commentIndentationView.setLevelAndColors(placeholder.getDepth(), verticalBlockColors);
-
- if (placeholder.getPlaceholderType() == Comment.PLACEHOLDER_LOAD_MORE_COMMENTS) {
- if (placeholder.isLoadingMoreChildren()) {
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.loading);
- } else if (placeholder.isLoadMoreChildrenFailed()) {
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments_failed);
- } else {
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments);
- }
- } else {
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_continue_thread);
- }
-
- if (placeholder.getPlaceholderType() == Comment.PLACEHOLDER_LOAD_MORE_COMMENTS) {
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setOnClickListener(view -> {
- int commentPosition = mIsSingleCommentThreadMode ? holder.getBindingAdapterPosition() - 2 : holder.getBindingAdapterPosition() - 1;
- int parentPosition = getParentPosition(commentPosition);
- if (parentPosition >= 0) {
- Comment parentComment = mVisibleComments.get(parentPosition);
-
- mVisibleComments.get(commentPosition).setLoadingMoreChildren(true);
- mVisibleComments.get(commentPosition).setLoadMoreChildrenFailed(false);
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.loading);
-
- Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit;
- FetchComment.fetchMoreComment(retrofit, mAccessToken, parentComment.getMoreChildrenFullnames(),
- parentComment.getMoreChildrenStartingIndex(), parentComment.getDepth() + 1,
- mExpandChildren, mLocale,
- new FetchComment.FetchMoreCommentListener() {
- @Override
- public void onFetchMoreCommentSuccess(ArrayList<Comment> expandedComments,
- int childrenStartingIndex) {
- if (mVisibleComments.size() > parentPosition
- && parentComment.getFullName().equals(mVisibleComments.get(parentPosition).getFullName())) {
- if (mVisibleComments.get(parentPosition).isExpanded()) {
- if (mVisibleComments.get(parentPosition).getChildren().size() > childrenStartingIndex) {
- mVisibleComments.get(parentPosition).setMoreChildrenStartingIndex(childrenStartingIndex);
- mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
- .setLoadingMoreChildren(false);
- mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
- .setLoadMoreChildrenFailed(false);
-
- int placeholderPosition = commentPosition;
- if (mVisibleComments.get(commentPosition).getFullName().equals(parentComment.getFullName())) {
- for (int i = parentPosition + 1; i < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
- placeholderPosition = i;
- break;
- }
- }
- }
-
- mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
- mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(false);
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments);
-
- mVisibleComments.addAll(placeholderPosition, expandedComments);
- if (mIsSingleCommentThreadMode) {
- notifyItemRangeInserted(placeholderPosition + 2, expandedComments.size());
- } else {
- notifyItemRangeInserted(placeholderPosition + 1, expandedComments.size());
- }
- } else {
- mVisibleComments.get(parentPosition).getChildren()
- .remove(mVisibleComments.get(parentPosition).getChildren().size() - 1);
- mVisibleComments.get(parentPosition).removeMoreChildrenFullnames();
-
- int placeholderPosition = commentPosition;
- if (mVisibleComments.get(commentPosition).getFullName().equals(parentComment.getFullName())) {
- for (int i = parentPosition + 1; i < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
- placeholderPosition = i;
- break;
- }
- }
- }
-
- mVisibleComments.remove(placeholderPosition);
- if (mIsSingleCommentThreadMode) {
- notifyItemRemoved(placeholderPosition + 2);
- } else {
- notifyItemRemoved(placeholderPosition + 1);
- }
-
- mVisibleComments.addAll(placeholderPosition, expandedComments);
- if (mIsSingleCommentThreadMode) {
- notifyItemRangeInserted(placeholderPosition + 2, expandedComments.size());
- } else {
- notifyItemRangeInserted(placeholderPosition + 1, expandedComments.size());
- }
- }
- } else {
- if (mVisibleComments.get(parentPosition).hasReply() && mVisibleComments.get(parentPosition).getChildren().size() <= childrenStartingIndex) {
- mVisibleComments.get(parentPosition).getChildren()
- .remove(mVisibleComments.get(parentPosition).getChildren().size() - 1);
- mVisibleComments.get(parentPosition).removeMoreChildrenFullnames();
- }
- }
-
- mVisibleComments.get(parentPosition).addChildren(expandedComments);
- } else {
- for (int i = 0; i < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
- if (mVisibleComments.get(i).isExpanded()) {
- int placeholderPosition = i + mVisibleComments.get(i).getChildren().size();
-
- if (!mVisibleComments.get(i).getFullName()
- .equals(mVisibleComments.get(placeholderPosition).getFullName())) {
- for (int j = i + 1; j < mVisibleComments.size(); j++) {
- if (mVisibleComments.get(j).getFullName().equals(mVisibleComments.get(i).getFullName())) {
- placeholderPosition = j;
- }
- }
- }
-
- mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
- mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(false);
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments);
-
- mVisibleComments.addAll(placeholderPosition, expandedComments);
- if (mIsSingleCommentThreadMode) {
- notifyItemRangeInserted(placeholderPosition + 2, expandedComments.size());
- } else {
- notifyItemRangeInserted(placeholderPosition + 1, expandedComments.size());
- }
- }
-
- mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1)
- .setLoadingMoreChildren(false);
- mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1)
- .setLoadMoreChildrenFailed(false);
- mVisibleComments.get(i).addChildren(expandedComments);
-
- break;
- }
- }
- }
- }
-
- @Override
- public void onFetchMoreCommentFailed() {
- if (parentPosition < mVisibleComments.size()
- && parentComment.getFullName().equals(mVisibleComments.get(parentPosition).getFullName())) {
- if (mVisibleComments.get(parentPosition).isExpanded()) {
- int commentPosition = mIsSingleCommentThreadMode ? holder.getBindingAdapterPosition() - 2 : holder.getBindingAdapterPosition() - 1;
- int placeholderPosition = commentPosition;
- if (commentPosition >= mVisibleComments.size() || commentPosition < 0 || !mVisibleComments.get(commentPosition).getFullName().equals(parentComment.getFullName())) {
- for (int i = parentPosition + 1; i < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
- placeholderPosition = i;
- break;
- }
- }
- }
-
- mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
- mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(true);
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments_failed);
- }
-
- mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
- .setLoadingMoreChildren(false);
- mVisibleComments.get(parentPosition).getChildren().get(mVisibleComments.get(parentPosition).getChildren().size() - 1)
- .setLoadMoreChildrenFailed(true);
- } else {
- for (int i = 0; i < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i).getFullName().equals(parentComment.getFullName())) {
- if (mVisibleComments.get(i).isExpanded()) {
- int placeholderPosition = i + mVisibleComments.get(i).getChildren().size();
- if (!mVisibleComments.get(placeholderPosition).getFullName().equals(mVisibleComments.get(i).getFullName())) {
- for (int j = i + 1; j < mVisibleComments.size(); j++) {
- if (mVisibleComments.get(j).getFullName().equals(mVisibleComments.get(i).getFullName())) {
- placeholderPosition = j;
- break;
- }
- }
- }
-
- mVisibleComments.get(placeholderPosition).setLoadingMoreChildren(false);
- mVisibleComments.get(placeholderPosition).setLoadMoreChildrenFailed(true);
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setText(R.string.comment_load_more_comments_failed);
- }
-
- mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1).setLoadingMoreChildren(false);
- mVisibleComments.get(i).getChildren().get(mVisibleComments.get(i).getChildren().size() - 1).setLoadMoreChildrenFailed(true);
-
- break;
- }
- }
- }
- }
- });
- }
- });
- } else {
- ((LoadMoreChildCommentsViewHolder) holder).placeholderTextView.setOnClickListener(view -> {
- Comment comment = getCurrentComment(position);
- if (comment != null) {
- Intent intent = new Intent(mActivity, ViewPostDetailActivity.class);
- intent.putExtra(ViewPostDetailActivity.EXTRA_POST_DATA, mPost);
- intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, comment.getParentId());
- intent.putExtra(ViewPostDetailActivity.EXTRA_CONTEXT_NUMBER, "0");
- mActivity.startActivity(intent);
- }
- });
- }
}
}
@@ -1428,7 +878,8 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private void loadImage(PostDetailBaseViewHolder holder, @NonNull Post.Preview preview) {
if (holder instanceof PostDetailImageAndGifAutoplayViewHolder) {
- String url = mPost.getPostType() == Post.IMAGE_TYPE ? preview.getPreviewUrl() : mPost.getUrl();
+ boolean blurImage = (mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mPost.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || (mPost.isSpoiler() && mNeedBlurSpoiler);
+ String url = mPost.getPostType() == Post.IMAGE_TYPE || blurImage ? preview.getPreviewUrl() : mPost.getUrl();
RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(url)
.listener(new RequestListener<Drawable>() {
@Override
@@ -1450,7 +901,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
}
});
- if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mPost.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || (mPost.isSpoiler() && mNeedBlurSpoiler)) {
+ if (blurImage) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10))).into(((PostDetailImageAndGifAutoplayViewHolder) holder).mImageView);
} else {
if (mImageViewWidth > preview.getPreviewWidth()) {
@@ -1562,224 +1013,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
notifyItemChanged(0);
}
- private int getParentPosition(int position) {
- if (position >= 0 && position < mVisibleComments.size()) {
- int childDepth = mVisibleComments.get(position).getDepth();
- for (int i = position; i >= 0; i--) {
- if (mVisibleComments.get(i).getDepth() < childDepth) {
- return i;
- }
- }
- }
- return -1;
- }
-
- private void expandChildren(ArrayList<Comment> comments, ArrayList<Comment> newList, int position) {
- if (comments != null && comments.size() > 0) {
- newList.addAll(position, comments);
- for (int i = 0; i < comments.size(); i++) {
- position++;
- if (comments.get(i).getChildren() != null && comments.get(i).getChildren().size() > 0) {
- expandChildren(comments.get(i).getChildren(), newList, position);
- position = position + comments.get(i).getChildren().size();
- }
- comments.get(i).setExpanded(true);
- }
- }
- }
-
- private void collapseChildren(int position) {
- mVisibleComments.get(position).setExpanded(false);
- int depth = mVisibleComments.get(position).getDepth();
- int allChildrenSize = 0;
- for (int i = position + 1; i < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i).getDepth() > depth) {
- allChildrenSize++;
- } else {
- break;
- }
- }
-
- if (allChildrenSize > 0) {
- mVisibleComments.subList(position + 1, position + 1 + allChildrenSize).clear();
- }
- if (mIsSingleCommentThreadMode) {
- if (mFullyCollapseComment) {
- notifyItemChanged(position + 2);
- }
- notifyItemRangeRemoved(position + 3, allChildrenSize);
- } else {
- if (mFullyCollapseComment) {
- notifyItemChanged(position + 1);
- }
- notifyItemRangeRemoved(position + 2, allChildrenSize);
- }
- }
-
- public void addComments(@NonNull ArrayList<Comment> comments, boolean hasMoreComments) {
- if (mVisibleComments.size() == 0) {
- isInitiallyLoading = false;
- isInitiallyLoadingFailed = false;
- if (comments.size() == 0) {
- notifyItemChanged(1);
- } else {
- notifyItemRemoved(1);
- }
- }
-
- int sizeBefore = mVisibleComments.size();
- mVisibleComments.addAll(comments);
- if (mIsSingleCommentThreadMode) {
- notifyItemRangeInserted(sizeBefore + 2, comments.size());
- } else {
- notifyItemRangeInserted(sizeBefore + 1, comments.size());
- }
-
- if (mHasMoreComments != hasMoreComments) {
- if (hasMoreComments) {
- if (mIsSingleCommentThreadMode) {
- notifyItemInserted(mVisibleComments.size() + 2);
- } else {
- notifyItemInserted(mVisibleComments.size() + 1);
- }
- } else {
- if (mIsSingleCommentThreadMode) {
- notifyItemRemoved(mVisibleComments.size() + 2);
- } else {
- notifyItemRemoved(mVisibleComments.size() + 1);
- }
- }
- }
- mHasMoreComments = hasMoreComments;
- }
-
- public void addComment(Comment comment) {
- if (mVisibleComments.size() == 0 || isInitiallyLoadingFailed) {
- notifyItemRemoved(1);
- }
-
- mVisibleComments.add(0, comment);
-
- if (isInitiallyLoading) {
- notifyItemInserted(2);
- } else {
- notifyItemInserted(1);
- }
- }
-
- public void addChildComment(Comment comment, String parentFullname, int parentPosition) {
- if (!parentFullname.equals(mVisibleComments.get(parentPosition).getFullName())) {
- for (int i = 0; i < mVisibleComments.size(); i++) {
- if (parentFullname.equals(mVisibleComments.get(i).getFullName())) {
- parentPosition = i;
- break;
- }
- }
- }
-
- mVisibleComments.get(parentPosition).addChild(comment);
- mVisibleComments.get(parentPosition).setHasReply(true);
- if (!mVisibleComments.get(parentPosition).isExpanded()) {
- ArrayList<Comment> newList = new ArrayList<>();
- expandChildren(mVisibleComments.get(parentPosition).getChildren(), newList, 0);
- mVisibleComments.get(parentPosition).setExpanded(true);
- mVisibleComments.addAll(parentPosition + 1, newList);
- if (mIsSingleCommentThreadMode) {
- notifyItemChanged(parentPosition + 2);
- notifyItemRangeInserted(parentPosition + 3, newList.size());
- } else {
- notifyItemChanged(parentPosition + 1);
- notifyItemRangeInserted(parentPosition + 2, newList.size());
- }
- } else {
- mVisibleComments.add(parentPosition + 1, comment);
- if (mIsSingleCommentThreadMode) {
- notifyItemInserted(parentPosition + 3);
- } else {
- notifyItemInserted(parentPosition + 2);
- }
- }
- }
-
- public void setSingleComment(String singleCommentId, boolean isSingleCommentThreadMode) {
- mSingleCommentId = singleCommentId;
- mIsSingleCommentThreadMode = isSingleCommentThreadMode;
- }
-
- public ArrayList<Comment> getVisibleComments() {
- return mVisibleComments;
- }
-
- public void initiallyLoading() {
- if (mVisibleComments.size() != 0) {
- int previousSize = mVisibleComments.size();
- mVisibleComments.clear();
- if (mIsSingleCommentThreadMode) {
- notifyItemRangeRemoved(1, previousSize + 1);
- } else {
- notifyItemRangeRemoved(1, previousSize);
- }
- }
-
- if (isInitiallyLoading || isInitiallyLoadingFailed || mVisibleComments.size() == 0) {
- isInitiallyLoading = true;
- isInitiallyLoadingFailed = false;
- notifyItemChanged(1);
- } else {
- isInitiallyLoading = true;
- isInitiallyLoadingFailed = false;
- notifyItemInserted(1);
- }
- }
-
- public void initiallyLoadCommentsFailed() {
- isInitiallyLoading = false;
- isInitiallyLoadingFailed = true;
- notifyItemChanged(1);
- }
-
- public void loadMoreCommentsFailed() {
- loadMoreCommentsFailed = true;
- if (mIsSingleCommentThreadMode) {
- notifyItemChanged(mVisibleComments.size() + 2);
- } else {
- notifyItemChanged(mVisibleComments.size() + 1);
- }
- }
-
- public void editComment(String commentAuthor, String commentContentMarkdown, int position) {
- if (commentAuthor != null)
- mVisibleComments.get(position).setAuthor(commentAuthor);
-
- mVisibleComments.get(position).setCommentMarkdown(commentContentMarkdown);
- if (mIsSingleCommentThreadMode) {
- notifyItemChanged(position + 2);
- } else {
- notifyItemChanged(position + 1);
- }
- }
-
- public void deleteComment(int position) {
- if (mVisibleComments != null && position >= 0 && position < mVisibleComments.size()) {
- if (mVisibleComments.get(position).hasReply()) {
- mVisibleComments.get(position).setAuthor("[deleted]");
- mVisibleComments.get(position).setCommentMarkdown("[deleted]");
- if (mIsSingleCommentThreadMode) {
- notifyItemChanged(position + 2);
- } else {
- notifyItemChanged(position + 1);
- }
- } else {
- mVisibleComments.remove(position);
- if (mIsSingleCommentThreadMode) {
- notifyItemRemoved(position + 2);
- } else {
- notifyItemRemoved(position + 1);
- }
- }
- }
- }
-
public void setBlurNsfwAndDoNotBlurNsfwInNsfwSubreddits(boolean needBlurNsfw, boolean doNotBlurNsfwInNsfwSubreddits) {
mNeedBlurNsfw = needBlurNsfw;
mDoNotBlurNsfwInNsfwSubreddits = doNotBlurNsfwInNsfwSubreddits;
@@ -1789,44 +1022,6 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mNeedBlurSpoiler = needBlurSpoiler;
}
- public int getNextParentCommentPosition(int currentPosition) {
- if (mVisibleComments != null && !mVisibleComments.isEmpty()) {
- if (mIsSingleCommentThreadMode) {
- for (int i = currentPosition + 1; i - 2 < mVisibleComments.size() && i - 2 >= 0; i++) {
- if (mVisibleComments.get(i - 2).getDepth() == 0) {
- return i;
- }
- }
- } else {
- for (int i = currentPosition + 1; i - 1 < mVisibleComments.size(); i++) {
- if (mVisibleComments.get(i - 1).getDepth() == 0) {
- return i;
- }
- }
- }
- }
- return -1;
- }
-
- public int getPreviousParentCommentPosition(int currentPosition) {
- if (mVisibleComments != null && !mVisibleComments.isEmpty()) {
- if (mIsSingleCommentThreadMode) {
- for (int i = currentPosition + 1; i - 2 >= 0; i--) {
- if (mVisibleComments.get(i - 2).getDepth() == 0) {
- return i;
- }
- }
- } else {
- for (int i = currentPosition - 1; i - 1 >= 0; i--) {
- if (mVisibleComments.get(i - 1).getDepth() == 0) {
- return i;
- }
- }
- }
- }
- return -1;
- }
-
public void setAutoplay(boolean autoplay) {
mAutoplay = autoplay;
}
@@ -1850,63 +1045,20 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
((PostDetailBaseViewHolder) viewHolder).mDownvoteButton.performClick();
}
}
- } else if (viewHolder instanceof CommentViewHolder) {
- if (direction == ItemTouchHelper.LEFT || direction == ItemTouchHelper.START) {
- if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) {
- ((CommentViewHolder) viewHolder).upvoteButton.performClick();
- } else if (swipeLeftAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) {
- ((CommentViewHolder) viewHolder).downvoteButton.performClick();
- }
- } else {
- if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_UPVOTE) {
- ((CommentViewHolder) viewHolder).upvoteButton.performClick();
- } else if (swipeRightAction == SharedPreferencesUtils.SWIPE_ACITON_DOWNVOTE) {
- ((CommentViewHolder) viewHolder).downvoteButton.performClick();
- }
- }
- }
- }
-
- public void giveAward(String awardsHTML, int awardCount, int position) {
- if (position == 0) {
- if (mPost != null) {
- mPost.addAwards(awardsHTML);
- mPost.addAwards(awardCount);
- notifyItemChanged(0);
- }
- } else {
- position = mIsSingleCommentThreadMode ? position + 2 : position + 1;
- Comment comment = getCurrentComment(position);
- if (comment != null) {
- comment.addAwards(awardsHTML);
- notifyItemChanged(position);
- }
}
}
- public void setSaveComment(int position, boolean isSaved) {
- Comment comment = getCurrentComment(position);
- if (comment != null) {
- comment.setSaved(isSaved);
+ public void giveAward(String awardsHTML, int awardCount) {
+ if (mPost != null) {
+ mPost.addAwards(awardsHTML);
+ mPost.addAwards(awardCount);
+ notifyItemChanged(0);
}
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
- if (holder instanceof CommentViewHolder) {
- ((CommentViewHolder) holder).authorTextView.setTextColor(mUsernameColor);
- ((CommentViewHolder) holder).authorFlairTextView.setVisibility(View.GONE);
- ((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
- ((CommentViewHolder) holder).topScoreTextView.setTextColor(mSecondaryTextColor);
- ((CommentViewHolder) holder).awardsTextView.setText("");
- ((CommentViewHolder) holder).awardsTextView.setVisibility(View.GONE);
- ((CommentViewHolder) holder).expandButton.setVisibility(View.GONE);
- ((CommentViewHolder) holder).upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).scoreTextView.setTextColor(mCommentIconAndInfoColor);
- ((CommentViewHolder) holder).downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).replyButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- ((CommentViewHolder) holder).itemView.setBackgroundColor(mCommentBackgroundColor);
- } else if (holder instanceof PostDetailBaseViewHolder) {
+ if (holder instanceof PostDetailBaseViewHolder) {
((PostDetailBaseViewHolder) holder).mUpvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
((PostDetailBaseViewHolder) holder).mScoreTextView.setTextColor(mPostIconAndInfoColor);
((PostDetailBaseViewHolder) holder).mDownvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
@@ -1935,23 +1087,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
@Override
public int getItemCount() {
- if (isInitiallyLoading || isInitiallyLoadingFailed || mVisibleComments.size() == 0) {
- return 2;
- }
-
- if (mHasMoreComments || loadMoreCommentsFailed) {
- if (mIsSingleCommentThreadMode) {
- return mVisibleComments.size() + 3;
- } else {
- return mVisibleComments.size() + 2;
- }
- }
-
- if (mIsSingleCommentThreadMode) {
- return mVisibleComments.size() + 2;
- } else {
- return mVisibleComments.size() + 1;
- }
+ return 1;
}
@Nullable
@@ -1966,12 +1102,8 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
return 0;
}
- public interface CommentRecyclerViewAdapterCallback {
+ public interface PostDetailRecyclerViewAdapterCallback {
void updatePost(Post post);
-
- void retryFetchingComments();
-
- void retryFetchingMoreComments();
}
public class PostDetailBaseViewHolder extends RecyclerView.ViewHolder {
@@ -2076,21 +1208,29 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mActivity.startActivity(crosspostIntent);
});
- mTypeTextView.setOnClickListener(view -> {
- Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
- intent.putExtra(FilteredPostsActivity.EXTRA_NAME, mSubredditNamePrefixed.substring(2));
- intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT);
- intent.putExtra(FilteredPostsActivity.EXTRA_FILTER, mPost.getPostType());
- mActivity.startActivity(intent);
- });
+ if (!mHidePostType) {
+ mTypeTextView.setOnClickListener(view -> {
+ Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
+ intent.putExtra(FilteredPostsActivity.EXTRA_NAME, mSubredditNamePrefixed.substring(2));
+ intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT);
+ intent.putExtra(FilteredPostsActivity.EXTRA_FILTER, mPost.getPostType());
+ mActivity.startActivity(intent);
+ });
+ } else {
+ mTypeTextView.setVisibility(View.GONE);
+ }
- mFlairTextView.setOnClickListener(view -> {
- Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
- intent.putExtra(FilteredPostsActivity.EXTRA_NAME, mSubredditNamePrefixed.substring(2));
- intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT);
- intent.putExtra(FilteredPostsActivity.EXTRA_CONTAIN_FLAIR, mPost.getFlair());
- mActivity.startActivity(intent);
- });
+ if (!mHidePostFlair) {
+ mFlairTextView.setOnClickListener(view -> {
+ Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
+ intent.putExtra(FilteredPostsActivity.EXTRA_NAME, mSubredditNamePrefixed.substring(2));
+ intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT);
+ intent.putExtra(FilteredPostsActivity.EXTRA_CONTAIN_FLAIR, mPost.getFlair());
+ mActivity.startActivity(intent);
+ });
+ } else {
+ mFlairTextView.setVisibility(View.GONE);
+ }
mNSFWTextView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
@@ -2134,10 +1274,12 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mScoreTextView.setTextColor(mPostIconAndInfoColor);
}
- mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- mPost.getScore() + mPost.getVoteType()));
+ if (!mHideTheNumberOfVotes) {
+ mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ mPost.getScore() + mPost.getVoteType()));
+ }
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
VoteThing.voteThing(mActivity, mOauthRetrofit, mAccessToken, new VoteThing.VoteThingWithoutPositionListener() {
@Override
@@ -2153,23 +1295,27 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
}
mDownvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- mPost.getScore() + mPost.getVoteType()));
+ if (!mHideTheNumberOfVotes) {
+ mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ mPost.getScore() + mPost.getVoteType()));
+ }
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
@Override
public void onVoteThingFail() {
Toast.makeText(mActivity, R.string.vote_failed, Toast.LENGTH_SHORT).show();
mPost.setVoteType(previousVoteType);
- mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- mPost.getScore() + previousVoteType));
+ if (!mHideTheNumberOfVotes) {
+ mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ mPost.getScore() + previousVoteType));
+ }
mUpvoteButton.setColorFilter(previousUpvoteButtonColorFilter);
mDownvoteButton.setColorFilter(previousDownvoteButtonColorFilter);
mScoreTextView.setTextColor(previousScoreTextViewColor);
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
}, mPost.getFullName(), newVoteType);
});
@@ -2208,10 +1354,12 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mScoreTextView.setTextColor(mPostIconAndInfoColor);
}
- mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- mPost.getScore() + mPost.getVoteType()));
+ if (!mHideTheNumberOfVotes) {
+ mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ mPost.getScore() + mPost.getVoteType()));
+ }
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
VoteThing.voteThing(mActivity, mOauthRetrofit, mAccessToken, new VoteThing.VoteThingWithoutPositionListener() {
@Override
@@ -2227,52 +1375,60 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
}
mUpvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- mPost.getScore() + mPost.getVoteType()));
+ if (!mHideTheNumberOfVotes) {
+ mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ mPost.getScore() + mPost.getVoteType()));
+ }
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
@Override
public void onVoteThingFail() {
Toast.makeText(mActivity, R.string.vote_failed, Toast.LENGTH_SHORT).show();
mPost.setVoteType(previousVoteType);
- mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- mPost.getScore() + previousVoteType));
+ if (!mHideTheNumberOfVotes) {
+ mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
+ mPost.getScore() + previousVoteType));
+ }
mUpvoteButton.setColorFilter(previousUpvoteButtonColorFilter);
mDownvoteButton.setColorFilter(previousDownvoteButtonColorFilter);
mScoreTextView.setTextColor(previousScoreTextViewColor);
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
}, mPost.getFullName(), newVoteType);
});
- commentsCountTextView.setOnClickListener(view -> {
- if (mPost.isArchived()) {
- Toast.makeText(mActivity, R.string.archived_post_comment_unavailable, Toast.LENGTH_SHORT).show();
- return;
- }
+ if (!mHideTheNumberOfComments) {
+ commentsCountTextView.setOnClickListener(view -> {
+ if (mPost.isArchived()) {
+ Toast.makeText(mActivity, R.string.archived_post_comment_unavailable, Toast.LENGTH_SHORT).show();
+ return;
+ }
- if (mPost.isLocked()) {
- Toast.makeText(mActivity, R.string.locked_post_comment_unavailable, Toast.LENGTH_SHORT).show();
- return;
- }
+ if (mPost.isLocked()) {
+ Toast.makeText(mActivity, R.string.locked_post_comment_unavailable, Toast.LENGTH_SHORT).show();
+ return;
+ }
- if (mAccessToken == null) {
- Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
- return;
- }
+ if (mAccessToken == null) {
+ Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
+ return;
+ }
- Intent intent = new Intent(mActivity, CommentActivity.class);
- intent.putExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY, mPost.getFullName());
- 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_IS_REPLYING_KEY, false);
- intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, 0);
- mActivity.startActivityForResult(intent, WRITE_COMMENT_REQUEST_CODE);
- });
+ Intent intent = new Intent(mActivity, CommentActivity.class);
+ intent.putExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY, mPost.getFullName());
+ 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_IS_REPLYING_KEY, false);
+ intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, 0);
+ mActivity.startActivityForResult(intent, WRITE_COMMENT_REQUEST_CODE);
+ });
+ } else {
+ commentsCountTextView.setVisibility(View.GONE);
+ }
mSaveButton.setOnClickListener(view -> {
if (mAccessToken == null) {
@@ -2289,7 +1445,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mPost.setSaved(false);
mSaveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
Toast.makeText(mActivity, R.string.post_unsaved_success, Toast.LENGTH_SHORT).show();
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
@Override
@@ -2297,7 +1453,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mPost.setSaved(true);
mSaveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
Toast.makeText(mActivity, R.string.post_unsaved_failed, Toast.LENGTH_SHORT).show();
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
});
} else {
@@ -2309,7 +1465,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mPost.setSaved(true);
mSaveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
Toast.makeText(mActivity, R.string.post_saved_success, Toast.LENGTH_SHORT).show();
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
@Override
@@ -2317,7 +1473,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mPost.setSaved(false);
mSaveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
Toast.makeText(mActivity, R.string.post_saved_failed, Toast.LENGTH_SHORT).show();
- mCommentRecyclerViewAdapterCallback.updatePost(mPost);
+ mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
}
});
}
@@ -2495,11 +1651,11 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
muteButton.setOnClickListener(view -> {
if (helper != null) {
if (helper.getVolume() != 0) {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_18dp));
+ muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_24dp));
helper.setVolume(0f);
volume = 0f;
} else {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_18dp));
+ muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_24dp));
helper.setVolume(1f);
volume = 1f;
}
@@ -2523,6 +1679,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_DOWNLOAD_URL, mPost.getVideoDownloadUrl());
}
} else {
+ intent.setData(Uri.parse(mPost.getVideoUrl()));
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_DOWNLOAD_URL, mPost.getVideoDownloadUrl());
intent.putExtra(ViewVideoActivity.EXTRA_SUBREDDIT, mPost.getSubredditName());
intent.putExtra(ViewVideoActivity.EXTRA_ID, mPost.getId());
@@ -2580,9 +1737,9 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
helper.setVolume(volume);
muteButton.setVisibility(View.VISIBLE);
if (volume != 0f) {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_18dp));
+ muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_24dp));
} else {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_18dp));
+ muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_24dp));
}
break;
}
@@ -2642,7 +1799,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
@Override
public int getPlayerOrder() {
- return getBindingAdapterPosition();
+ return 0;
}
}
@@ -3276,625 +2433,4 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<Recy
mShareButton);
}
}
-
- public class CommentViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.author_text_view_item_post_comment)
- TextView authorTextView;
- @BindView(R.id.author_flair_text_view_item_post_comment)
- TextView authorFlairTextView;
- @BindView(R.id.comment_time_text_view_item_post_comment)
- TextView commentTimeTextView;
- @BindView(R.id.top_score_text_view_item_post_comment)
- TextView topScoreTextView;
- @BindView(R.id.awards_text_view_item_comment)
- TextView awardsTextView;
- @BindView(R.id.comment_markdown_view_item_post_comment)
- TextView commentMarkdownView;
- @BindView(R.id.bottom_constraint_layout_item_post_comment)
- ConstraintLayout bottomConstraintLayout;
- @BindView(R.id.up_vote_button_item_post_comment)
- ImageView upvoteButton;
- @BindView(R.id.score_text_view_item_post_comment)
- TextView scoreTextView;
- @BindView(R.id.down_vote_button_item_post_comment)
- ImageView downvoteButton;
- @BindView(R.id.more_button_item_post_comment)
- ImageView moreButton;
- @BindView(R.id.save_button_item_post_comment)
- ImageView saveButton;
- @BindView(R.id.expand_button_item_post_comment)
- ImageView expandButton;
- @BindView(R.id.reply_button_item_post_comment)
- ImageView replyButton;
- @BindView(R.id.vertical_block_indentation_item_comment)
- CommentIndentationView commentIndentationView;
- @BindView(R.id.divider_item_comment)
- View commentDivider;
-
- CommentViewHolder(View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
-
- if (mVoteButtonsOnTheRight) {
- ConstraintSet constraintSet = new ConstraintSet();
- constraintSet.clone(bottomConstraintLayout);
- constraintSet.clear(upvoteButton.getId(), ConstraintSet.START);
- constraintSet.clear(scoreTextView.getId(), ConstraintSet.START);
- constraintSet.clear(downvoteButton.getId(), ConstraintSet.START);
- constraintSet.clear(expandButton.getId(), ConstraintSet.END);
- constraintSet.clear(saveButton.getId(), ConstraintSet.END);
- constraintSet.clear(replyButton.getId(), ConstraintSet.END);
- constraintSet.clear(moreButton.getId(), ConstraintSet.END);
- constraintSet.connect(upvoteButton.getId(), ConstraintSet.END, scoreTextView.getId(), ConstraintSet.START);
- constraintSet.connect(scoreTextView.getId(), ConstraintSet.END, downvoteButton.getId(), ConstraintSet.START);
- constraintSet.connect(downvoteButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
- constraintSet.connect(moreButton.getId(), ConstraintSet.START, expandButton.getId(), ConstraintSet.END);
- constraintSet.connect(expandButton.getId(), ConstraintSet.START, saveButton.getId(), ConstraintSet.END);
- constraintSet.connect(saveButton.getId(), ConstraintSet.START, replyButton.getId(), ConstraintSet.END);
- constraintSet.connect(replyButton.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
- constraintSet.setHorizontalBias(moreButton.getId(), 0);
- constraintSet.applyTo(bottomConstraintLayout);
- }
-
- if (mShowCommentDivider) {
- commentDivider.setBackgroundColor(mDividerColor);
- commentDivider.setVisibility(View.VISIBLE);
- }
-
- itemView.setBackgroundColor(mCommentBackgroundColor);
- authorTextView.setTextColor(mUsernameColor);
- commentTimeTextView.setTextColor(mSecondaryTextColor);
- commentMarkdownView.setTextColor(mCommentTextColor);
- authorFlairTextView.setTextColor(mAuthorFlairTextColor);
- topScoreTextView.setTextColor(mSecondaryTextColor);
- awardsTextView.setTextColor(mSecondaryTextColor);
- commentDivider.setBackgroundColor(mDividerColor);
- upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mCommentIconAndInfoColor);
- downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- moreButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- expandButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- saveButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- replyButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
-
- authorFlairTextView.setOnClickListener(view -> authorTextView.performClick());
-
- moreButton.setOnClickListener(view -> {
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- Bundle bundle = new Bundle();
- if (!mPost.isArchived() && !mPost.isLocked() && comment.getAuthor().equals(mAccountName)) {
- bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_EDIT_AND_DELETE_AVAILABLE, true);
- }
- bundle.putString(CommentMoreBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
- bundle.putParcelable(CommentMoreBottomSheetFragment.EXTRA_COMMENT, comment);
- if (mIsSingleCommentThreadMode) {
- bundle.putInt(CommentMoreBottomSheetFragment.EXTRA_POSITION, getBindingAdapterPosition() - 2);
- } else {
- bundle.putInt(CommentMoreBottomSheetFragment.EXTRA_POSITION, getBindingAdapterPosition() - 1);
- }
- bundle.putString(CommentMoreBottomSheetFragment.EXTRA_COMMENT_MARKDOWN, comment.getCommentMarkdown());
- bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_IS_NSFW, mPost.isNSFW());
- if (comment.getDepth() > depthThreshold) {
- bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_SHOW_REPLY_AND_SAVE_OPTION, true);
- }
- CommentMoreBottomSheetFragment commentMoreBottomSheetFragment = new CommentMoreBottomSheetFragment();
- commentMoreBottomSheetFragment.setArguments(bundle);
- commentMoreBottomSheetFragment.show(mActivity.getSupportFragmentManager(), commentMoreBottomSheetFragment.getTag());
- }
- });
-
- replyButton.setOnClickListener(view -> {
- if (mAccessToken == null) {
- Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
- return;
- }
-
- if (mPost.isArchived()) {
- Toast.makeText(mActivity, R.string.archived_post_reply_unavailable, Toast.LENGTH_SHORT).show();
- return;
- }
-
- if (mPost.isLocked()) {
- Toast.makeText(mActivity, R.string.locked_post_reply_unavailable, Toast.LENGTH_SHORT).show();
- return;
- }
-
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- Intent intent = new Intent(mActivity, CommentActivity.class);
- intent.putExtra(CommentActivity.EXTRA_PARENT_DEPTH_KEY, comment.getDepth() + 1);
- intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TEXT_MARKDOWN_KEY, comment.getCommentMarkdown());
- intent.putExtra(CommentActivity.EXTRA_COMMENT_PARENT_TEXT_KEY, comment.getCommentRawText());
- intent.putExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY, comment.getFullName());
- intent.putExtra(CommentActivity.EXTRA_IS_REPLYING_KEY, true);
-
- int parentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 2 : getBindingAdapterPosition() - 1;
- intent.putExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, parentPosition);
- mFragment.startActivityForResult(intent, CommentActivity.WRITE_COMMENT_REQUEST_CODE);
- }
- });
-
- upvoteButton.setOnClickListener(view -> {
- if (mPost.isArchived()) {
- Toast.makeText(mActivity, R.string.archived_post_vote_unavailable, Toast.LENGTH_SHORT).show();
- return;
- }
-
- if (mAccessToken == null) {
- Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
- return;
- }
-
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- int previousVoteType = comment.getVoteType();
- String newVoteType;
-
- downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
-
- if (previousVoteType != Comment.VOTE_TYPE_UPVOTE) {
- //Not upvoted before
- comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
- newVoteType = APIUtils.DIR_UPVOTE;
- upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mUpvotedColor);
- topScoreTextView.setTextColor(mUpvotedColor);
- } else {
- //Upvoted before
- comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
- newVoteType = APIUtils.DIR_UNVOTE;
- upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mCommentIconAndInfoColor);
- topScoreTextView.setTextColor(mSecondaryTextColor);
- }
-
- scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType()));
- topScoreTextView.setText(mActivity.getString(R.string.top_score,
- Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType())));
-
- int position = getBindingAdapterPosition();
- VoteThing.voteThing(mActivity, mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
- @Override
- public void onVoteThingSuccess(int position) {
- int currentPosition = getBindingAdapterPosition();
- if (newVoteType.equals(APIUtils.DIR_UPVOTE)) {
- comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
- if (currentPosition == position) {
- upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mUpvotedColor);
- topScoreTextView.setTextColor(mUpvotedColor);
- }
- } else {
- comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
- if (currentPosition == position) {
- upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mCommentIconAndInfoColor);
- topScoreTextView.setTextColor(mSecondaryTextColor);
- }
- }
-
- if (currentPosition == position) {
- downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType()));
- topScoreTextView.setText(mActivity.getString(R.string.top_score,
- Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType())));
- }
- }
-
- @Override
- public void onVoteThingFail(int position) {
- }
- }, comment.getFullName(), newVoteType, getBindingAdapterPosition());
- }
- });
-
- downvoteButton.setOnClickListener(view -> {
- if (mPost.isArchived()) {
- Toast.makeText(mActivity, R.string.archived_post_vote_unavailable, Toast.LENGTH_SHORT).show();
- return;
- }
-
- if (mAccessToken == null) {
- Toast.makeText(mActivity, R.string.login_first, Toast.LENGTH_SHORT).show();
- return;
- }
-
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- int previousVoteType = comment.getVoteType();
- String newVoteType;
-
- upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
-
- if (previousVoteType != Comment.VOTE_TYPE_DOWNVOTE) {
- //Not downvoted before
- comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
- newVoteType = APIUtils.DIR_DOWNVOTE;
- downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mDownvotedColor);
- topScoreTextView.setTextColor(mDownvotedColor);
- } else {
- //Downvoted before
- comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
- newVoteType = APIUtils.DIR_UNVOTE;
- downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mCommentIconAndInfoColor);
- topScoreTextView.setTextColor(mSecondaryTextColor);
- }
-
- scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType()));
- topScoreTextView.setText(mActivity.getString(R.string.top_score,
- Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType())));
-
- int position = getBindingAdapterPosition();
- VoteThing.voteThing(mActivity, mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
- @Override
- public void onVoteThingSuccess(int position1) {
- int currentPosition = getBindingAdapterPosition();
- if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) {
- comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
- if (currentPosition == position) {
- downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mDownvotedColor);
- topScoreTextView.setTextColor(mDownvotedColor);
- }
- } else {
- comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
- if (currentPosition == position) {
- downvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setTextColor(mCommentIconAndInfoColor);
- topScoreTextView.setTextColor(mSecondaryTextColor);
- }
- }
-
- if (currentPosition == position) {
- upvoteButton.setColorFilter(mCommentIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
- scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType()));
- topScoreTextView.setText(mActivity.getString(R.string.top_score,
- Utils.getNVotes(mShowAbsoluteNumberOfVotes,
- comment.getScore() + comment.getVoteType())));
- }
- }
-
- @Override
- public void onVoteThingFail(int position1) {
- }
- }, comment.getFullName(), newVoteType, getBindingAdapterPosition());
- }
- });
-
- saveButton.setOnClickListener(view -> {
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- int position = getBindingAdapterPosition();
- if (comment.isSaved()) {
- comment.setSaved(false);
- SaveThing.unsaveThing(mOauthRetrofit, mAccessToken, comment.getFullName(), new SaveThing.SaveThingListener() {
- @Override
- public void success() {
- comment.setSaved(false);
- if (getBindingAdapterPosition() == position) {
- saveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
- }
- Toast.makeText(mActivity, R.string.comment_unsaved_success, Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void failed() {
- comment.setSaved(true);
- if (getBindingAdapterPosition() == position) {
- saveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
- }
- Toast.makeText(mActivity, R.string.comment_unsaved_failed, Toast.LENGTH_SHORT).show();
- }
- });
- } else {
- comment.setSaved(true);
- SaveThing.saveThing(mOauthRetrofit, mAccessToken, comment.getFullName(), new SaveThing.SaveThingListener() {
- @Override
- public void success() {
- comment.setSaved(true);
- if (getBindingAdapterPosition() == position) {
- saveButton.setImageResource(R.drawable.ic_bookmark_grey_24dp);
- }
- Toast.makeText(mActivity, R.string.comment_saved_success, Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void failed() {
- comment.setSaved(false);
- if (getBindingAdapterPosition() == position) {
- saveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
- }
- Toast.makeText(mActivity, R.string.comment_saved_failed, Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
- });
-
- authorTextView.setOnClickListener(view -> {
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
- intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, comment.getAuthor());
- mActivity.startActivity(intent);
- }
- });
-
- expandButton.setOnClickListener(view -> {
- if (expandButton.getVisibility() == View.VISIBLE) {
- int commentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 2 : getBindingAdapterPosition() - 1;
- if (commentPosition >= 0 && commentPosition < mVisibleComments.size()) {
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- if (mVisibleComments.get(commentPosition).isExpanded()) {
- collapseChildren(commentPosition);
- expandButton.setImageResource(R.drawable.ic_expand_more_grey_24dp);
- } else {
- comment.setExpanded(true);
- ArrayList<Comment> newList = new ArrayList<>();
- expandChildren(mVisibleComments.get(commentPosition).getChildren(), newList, 0);
- mVisibleComments.get(commentPosition).setExpanded(true);
- mVisibleComments.addAll(commentPosition + 1, newList);
-
- if (mIsSingleCommentThreadMode) {
- notifyItemRangeInserted(commentPosition + 3, newList.size());
- } else {
- notifyItemRangeInserted(commentPosition + 2, newList.size());
- }
- expandButton.setImageResource(R.drawable.ic_expand_less_grey_24dp);
- }
- }
- }
- } else if (mFullyCollapseComment) {
- int commentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 2 : getBindingAdapterPosition() - 1;
- if (commentPosition >= 0 && commentPosition < mVisibleComments.size()) {
- collapseChildren(commentPosition);
- }
- }
- });
-
- if (mSwapTapAndLong) {
- if (mCommentToolbarHideOnClick) {
- View.OnLongClickListener hideToolbarOnLongClickListener = view -> hideToolbar();
- itemView.setOnLongClickListener(hideToolbarOnLongClickListener);
- commentMarkdownView.setOnLongClickListener(hideToolbarOnLongClickListener);
- commentTimeTextView.setOnLongClickListener(hideToolbarOnLongClickListener);
- }
- commentMarkdownView.setOnClickListener(view -> {
- if (commentMarkdownView.getSelectionStart() == -1 && commentMarkdownView.getSelectionEnd() == -1) {
- expandComments();
- }
- });
- itemView.setOnClickListener(view -> expandComments());
- } else {
- if (mCommentToolbarHideOnClick) {
- commentMarkdownView.setOnClickListener(view -> {
- if (commentMarkdownView.getSelectionStart() == -1 && commentMarkdownView.getSelectionEnd() == -1) {
- hideToolbar();
- }
- });
- View.OnClickListener hideToolbarOnClickListener = view -> hideToolbar();
- itemView.setOnClickListener(hideToolbarOnClickListener);
- commentTimeTextView.setOnClickListener(hideToolbarOnClickListener);
- }
- commentMarkdownView.setOnLongClickListener(view -> {
- if (commentMarkdownView.getSelectionStart() == -1 && commentMarkdownView.getSelectionEnd() == -1) {
- expandComments();
- }
- return true;
- });
- itemView.setOnLongClickListener(view -> {
- expandComments();
- return true;
- });
- }
- commentMarkdownView.setHighlightColor(Color.TRANSPARENT);
- }
-
- private boolean expandComments() {
- expandButton.performClick();
- return true;
- }
-
- private boolean hideToolbar() {
- if (bottomConstraintLayout.getLayoutParams().height == 0) {
- bottomConstraintLayout.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT;
- topScoreTextView.setVisibility(View.GONE);
- mFragment.delayTransition();
- } else {
- mFragment.delayTransition();
- bottomConstraintLayout.getLayoutParams().height = 0;
- topScoreTextView.setVisibility(View.VISIBLE);
- }
- return true;
- }
- }
-
- @Nullable
- private Comment getCurrentComment(RecyclerView.ViewHolder holder) {
- return getCurrentComment(holder.getBindingAdapterPosition());
- }
-
- @Nullable
- private Comment getCurrentComment(int position) {
- if (mIsSingleCommentThreadMode) {
- if (position - 2 >= 0 && position - 2 < mVisibleComments.size()) {
- return mVisibleComments.get(position - 2);
- }
- } else {
- if (position - 1 >= 0 && position - 1 < mVisibleComments.size()) {
- return mVisibleComments.get(position - 1);
- }
- }
-
- return null;
- }
-
- class CommentFullyCollapsedViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.vertical_block_indentation_item_comment_fully_collapsed)
- CommentIndentationView commentIndentationView;
- @BindView(R.id.user_name_text_view_item_comment_fully_collapsed)
- TextView usernameTextView;
- @BindView(R.id.score_text_view_item_comment_fully_collapsed)
- TextView scoreTextView;
- @BindView(R.id.time_text_view_item_comment_fully_collapsed)
- TextView commentTimeTextView;
- @BindView(R.id.divider_item_comment_fully_collapsed)
- View commentDivider;
-
- public CommentFullyCollapsedViewHolder(@NonNull View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
-
- itemView.setBackgroundColor(mFullyCollapsedCommentBackgroundColor);
- usernameTextView.setTextColor(mUsernameColor);
- scoreTextView.setTextColor(mSecondaryTextColor);
- commentTimeTextView.setTextColor(mSecondaryTextColor);
-
- if (mShowCommentDivider) {
- commentDivider.setBackgroundColor(mDividerColor);
- commentDivider.setVisibility(View.VISIBLE);
- }
-
- itemView.setOnClickListener(view -> {
- int commentPosition = mIsSingleCommentThreadMode ? getBindingAdapterPosition() - 2 : getBindingAdapterPosition() - 1;
- if (commentPosition >= 0 && commentPosition < mVisibleComments.size()) {
- Comment comment = getCurrentComment(this);
- if (comment != null) {
- comment.setExpanded(true);
- ArrayList<Comment> newList = new ArrayList<>();
- expandChildren(mVisibleComments.get(commentPosition).getChildren(), newList, 0);
- mVisibleComments.get(commentPosition).setExpanded(true);
- mVisibleComments.addAll(commentPosition + 1, newList);
-
- if (mIsSingleCommentThreadMode) {
- notifyItemChanged(commentPosition + 2);
- notifyItemRangeInserted(commentPosition + 3, newList.size());
- } else {
- notifyItemChanged(commentPosition + 1);
- notifyItemRangeInserted(commentPosition + 2, newList.size());
- }
- }
- }
- });
-
- itemView.setOnLongClickListener(view -> {
- itemView.performClick();
- return true;
- });
- }
- }
-
- class LoadMoreChildCommentsViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.vertical_block_indentation_item_load_more_comments_placeholder)
- CommentIndentationView commentIndentationView;
- @BindView(R.id.placeholder_text_view_item_load_more_comments)
- TextView placeholderTextView;
- @BindView(R.id.divider_item_load_more_comments_placeholder)
- View commentDivider;
-
- LoadMoreChildCommentsViewHolder(View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
-
- if (mShowCommentDivider) {
- commentDivider.setVisibility(View.VISIBLE);
- }
-
- itemView.setBackgroundColor(mCommentBackgroundColor);
- placeholderTextView.setTextColor(mPrimaryTextColor);
- commentDivider.setBackgroundColor(mDividerColor);
- }
- }
-
- class LoadCommentsViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.comment_progress_bar_item_load_comments)
- CircleProgressBar circleProgressBar;
-
- LoadCommentsViewHolder(@NonNull View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
- circleProgressBar.setBackgroundTintList(ColorStateList.valueOf(mCircularProgressBarBackgroundColor));
- circleProgressBar.setColorSchemeColors(mColorAccent);
- }
- }
-
- class LoadCommentsFailedViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.error_text_view_item_load_comments_failed_placeholder)
- TextView errorTextView;
-
- LoadCommentsFailedViewHolder(@NonNull View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
- itemView.setOnClickListener(view -> mCommentRecyclerViewAdapterCallback.retryFetchingComments());
- errorTextView.setTextColor(mSecondaryTextColor);
- }
- }
-
- class NoCommentViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.error_text_view_item_no_comment_placeholder)
- TextView errorTextView;
-
- NoCommentViewHolder(@NonNull View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
- errorTextView.setTextColor(mSecondaryTextColor);
- }
- }
-
- class IsLoadingMoreCommentsViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.progress_bar_item_comment_footer_loading)
- ProgressBar progressbar;
-
- IsLoadingMoreCommentsViewHolder(@NonNull View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
- progressbar.setIndeterminateTintList(ColorStateList.valueOf(mColorAccent));
- }
- }
-
- class LoadMoreCommentsFailedViewHolder extends RecyclerView.ViewHolder {
- @BindView(R.id.error_text_view_item_comment_footer_error)
- TextView errorTextView;
- @BindView(R.id.retry_button_item_comment_footer_error)
- Button retryButton;
-
- LoadMoreCommentsFailedViewHolder(@NonNull View itemView) {
- super(itemView);
- ButterKnife.bind(this, itemView);
- errorTextView.setText(R.string.load_comments_failed);
- retryButton.setOnClickListener(view -> mCommentRecyclerViewAdapterCallback.retryFetchingMoreComments());
- errorTextView.setTextColor(mSecondaryTextColor);
- retryButton.setBackgroundTintList(ColorStateList.valueOf(mColorPrimaryLightTheme));
- retryButton.setTextColor(mButtonTextColor);
- }
- }
-
- class ViewAllCommentsViewHolder extends RecyclerView.ViewHolder {
-
- ViewAllCommentsViewHolder(@NonNull View itemView) {
- super(itemView);
-
- itemView.setOnClickListener(view -> {
- if (mActivity != null && mActivity instanceof ViewPostDetailActivity) {
- mIsSingleCommentThreadMode = false;
- mSingleCommentId = null;
- mFragment.changeToNomalThreadMode();
- }
- });
-
- itemView.setBackgroundTintList(ColorStateList.valueOf(mCommentBackgroundColor));
- ((TextView) itemView).setTextColor(mColorAccent);
- }
- }
}
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 95be0ca5..12d6c0d1 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/PostRecyclerViewAdapter.java
@@ -29,6 +29,7 @@ import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.Barrier;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
+import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
@@ -106,19 +107,15 @@ import retrofit2.Retrofit;
public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHolder> implements CacheManager {
private static final int VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE = 1;
- private static final int VIEW_TYPE_POST_CARD_VIDEO_AND_GIF_PREVIEW_TYPE = 2;
- private static final int VIEW_TYPE_POST_CARD_IMAGE_AND_GIF_AUTOPLAY_TYPE = 3;
- private static final int VIEW_TYPE_POST_CARD_LINK_TYPE = 4;
- private static final int VIEW_TYPE_POST_CARD_NO_PREVIEW_LINK_TYPE = 5;
- private static final int VIEW_TYPE_POST_CARD_TEXT_TYPE = 6;
- private static final int VIEW_TYPE_POST_CARD_GALLERY_TYPE = 7;
- private static final int VIEW_TYPE_POST_COMPACT = 8;
- private static final int VIEW_TYPE_POST_GALLERY = 9;
- private static final int VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE = 10;
- private static final int VIEW_TYPE_POST_CARD_2_WITH_PREVIEW = 11;
- private static final int VIEW_TYPE_POST_CARD_2_TEXT_TYPE = 12;
- private static final int VIEW_TYPE_ERROR = 13;
- private static final int VIEW_TYPE_LOADING = 14;
+ private static final int VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE = 2;
+ private static final int VIEW_TYPE_POST_CARD_TEXT_TYPE = 3;
+ private static final int VIEW_TYPE_POST_COMPACT = 4;
+ private static final int VIEW_TYPE_POST_GALLERY = 5;
+ private static final int VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE = 6;
+ private static final int VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE = 7;
+ private static final int VIEW_TYPE_POST_CARD_2_TEXT_TYPE = 8;
+ private static final int VIEW_TYPE_ERROR = 9;
+ private static final int VIEW_TYPE_LOADING = 10;
private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() {
@Override
@@ -148,6 +145,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
private boolean canStartActivity = true;
private int mPostType;
private int mPostLayout;
+ private int mDefaultLinkPostLayout;
private int mColorPrimaryLightTheme;
private int mColorAccent;
private int mCardViewBackgroundColor;
@@ -210,6 +208,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
private boolean mMarkPostsAsReadOnScroll;
private boolean mHideReadPostsAutomatically;
private boolean mHidePostType;
+ private boolean mHidePostFlair;
private boolean mHideTheNumberOfAwards;
private boolean mHideSubredditAndUserPrefix;
private boolean mHideTheNumberOfVotes;
@@ -287,12 +286,14 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
mHideReadPostsAutomatically = postHistorySharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.HIDE_READ_POSTS_AUTOMATICALLY_BASE, false);
mHidePostType = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_POST_TYPE, false);
+ mHidePostFlair = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_POST_FLAIR, false);
mHideTheNumberOfAwards = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_AWARDS, false);
mHideSubredditAndUserPrefix = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBREDDIT_AND_USER_PREFIX, false);
mHideTheNumberOfVotes = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_VOTES, false);
mHideTheNumberOfComments = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_COMMENTS, false);
mPostLayout = postLayout;
+ mDefaultLinkPostLayout = Integer.parseInt(sharedPreferences.getString(SharedPreferencesUtils.DEFAULT_LINK_POST_LAYOUT_KEY, "-1"));
mColorPrimaryLightTheme = customThemeWrapper.getColorPrimaryLightTheme();
mColorAccent = customThemeWrapper.getColorAccent();
@@ -364,33 +365,45 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
case Post.VIDEO_TYPE:
if (mAutoplay) {
if (!mAutoplayNsfwVideos && post.isNSFW()) {
- return VIEW_TYPE_POST_CARD_VIDEO_AND_GIF_PREVIEW_TYPE;
+ return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
}
return VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE;
}
- return VIEW_TYPE_POST_CARD_VIDEO_AND_GIF_PREVIEW_TYPE;
+ return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
case Post.GIF_TYPE:
- if (mAutoplay) {
- if (!mAutoplayNsfwVideos && post.isNSFW()) {
- return VIEW_TYPE_POST_CARD_VIDEO_AND_GIF_PREVIEW_TYPE;
- }
- return VIEW_TYPE_POST_CARD_IMAGE_AND_GIF_AUTOPLAY_TYPE;
- }
- return VIEW_TYPE_POST_CARD_VIDEO_AND_GIF_PREVIEW_TYPE;
case Post.IMAGE_TYPE:
- return VIEW_TYPE_POST_CARD_IMAGE_AND_GIF_AUTOPLAY_TYPE;
+ case Post.GALLERY_TYPE:
+ return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
case Post.LINK_TYPE:
- return VIEW_TYPE_POST_CARD_LINK_TYPE;
case Post.NO_PREVIEW_LINK_TYPE:
- return VIEW_TYPE_POST_CARD_NO_PREVIEW_LINK_TYPE;
- case Post.GALLERY_TYPE:
- return VIEW_TYPE_POST_CARD_GALLERY_TYPE;
+ switch (mDefaultLinkPostLayout) {
+ case SharedPreferencesUtils.POST_LAYOUT_CARD_2:
+ return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
+ case SharedPreferencesUtils.POST_LAYOUT_GALLERY:
+ return VIEW_TYPE_POST_GALLERY;
+ case SharedPreferencesUtils.POST_LAYOUT_COMPACT:
+ return VIEW_TYPE_POST_COMPACT;
+ }
+ return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
default:
return VIEW_TYPE_POST_CARD_TEXT_TYPE;
}
}
return VIEW_TYPE_POST_CARD_TEXT_TYPE;
} else if (mPostLayout == SharedPreferencesUtils.POST_LAYOUT_COMPACT) {
+ Post post = getItem(position);
+ if (post != null) {
+ if (post.getPostType() == Post.LINK_TYPE || post.getPostType() == Post.NO_PREVIEW_LINK_TYPE) {
+ switch (mDefaultLinkPostLayout) {
+ case SharedPreferencesUtils.POST_LAYOUT_CARD:
+ return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
+ case SharedPreferencesUtils.POST_LAYOUT_GALLERY:
+ return VIEW_TYPE_POST_GALLERY;
+ case SharedPreferencesUtils.POST_LAYOUT_CARD_2:
+ return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
+ }
+ }
+ }
return VIEW_TYPE_POST_COMPACT;
} else if (mPostLayout == SharedPreferencesUtils.POST_LAYOUT_GALLERY) {
return VIEW_TYPE_POST_GALLERY;
@@ -401,17 +414,26 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
case Post.VIDEO_TYPE:
if (mAutoplay) {
if (!mAutoplayNsfwVideos && post.isNSFW()) {
- return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW;
+ return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
}
return VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE;
}
- return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW;
+ return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
case Post.GIF_TYPE:
case Post.IMAGE_TYPE:
+ case Post.GALLERY_TYPE:
+ return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
case Post.LINK_TYPE:
case Post.NO_PREVIEW_LINK_TYPE:
- case Post.GALLERY_TYPE:
- return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW;
+ switch (mDefaultLinkPostLayout) {
+ case SharedPreferencesUtils.POST_LAYOUT_CARD:
+ return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
+ case SharedPreferencesUtils.POST_LAYOUT_GALLERY:
+ return VIEW_TYPE_POST_GALLERY;
+ case SharedPreferencesUtils.POST_LAYOUT_COMPACT:
+ return VIEW_TYPE_POST_COMPACT;
+ }
+ return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
default:
return VIEW_TYPE_POST_CARD_2_TEXT_TYPE;
}
@@ -429,11 +451,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
return new PostWithPreviewTypeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_with_preview, parent, false));
}
return new PostVideoAutoplayViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_video_type_autoplay, parent, false));
- } else if (viewType == VIEW_TYPE_POST_CARD_VIDEO_AND_GIF_PREVIEW_TYPE
- || viewType == VIEW_TYPE_POST_CARD_IMAGE_AND_GIF_AUTOPLAY_TYPE
- || viewType == VIEW_TYPE_POST_CARD_LINK_TYPE
- || viewType == VIEW_TYPE_POST_CARD_NO_PREVIEW_LINK_TYPE
- || viewType == VIEW_TYPE_POST_CARD_GALLERY_TYPE) {
+ } else if (viewType == VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE) {
return new PostWithPreviewTypeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_with_preview, parent, false));
} else if (viewType == VIEW_TYPE_POST_CARD_TEXT_TYPE) {
return new PostTextTypeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_text, parent, false));
@@ -447,7 +465,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
return new PostGalleryViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_gallery, parent, false));
} else if (viewType == VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE) {
return new PostCard2VideoAutoplayViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_card_2_video_autoplay, parent, false));
- } else if (viewType == VIEW_TYPE_POST_CARD_2_WITH_PREVIEW) {
+ } else if (viewType == VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE) {
return new PostCard2WithPreviewViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_card_2_with_preview, parent, false));
} else if (viewType == VIEW_TYPE_POST_CARD_2_TEXT_TYPE) {
return new PostCard2TextTypeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_card_2_text, parent, false));
@@ -474,7 +492,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
holder.itemView.setLayoutParams(params);
return;
}
- holder.itemView.setBackgroundTintList(ColorStateList.valueOf(mReadPostCardViewBackgroundColor));
+ if (((PostBaseViewHolder) holder).itemViewIsNotCardView) {
+ holder.itemView.setBackgroundColor(mReadPostCardViewBackgroundColor);
+ } else {
+ holder.itemView.setBackgroundTintList(ColorStateList.valueOf(mReadPostCardViewBackgroundColor));
+ }
+
((PostBaseViewHolder) holder).titleTextView.setTextColor(mReadPostTitleColor);
}
String subredditNamePrefixed = post.getSubredditNamePrefixed();
@@ -622,8 +645,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
if (flair != null && !flair.equals("")) {
- ((PostBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
- Utils.setHTMLWithImageToTextView(((PostBaseViewHolder) holder).flairTextView, flair, false);
+ if (mHidePostFlair) {
+ ((PostBaseViewHolder) holder).flairTextView.setVisibility(View.GONE);
+ } else {
+ ((PostBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
+ Utils.setHTMLWithImageToTextView(((PostBaseViewHolder) holder).flairTextView, flair, false);
+ }
}
if (nAwards > 0 && !mHideTheNumberOfAwards) {
@@ -698,7 +725,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
} else {
((PostVideoAutoplayViewHolder) holder).aspectRatioFrameLayout.setAspectRatio(1);
}
- ((PostVideoAutoplayViewHolder) holder).setVolume(mMuteAutoplayingVideos || (post.isNSFW() && mMuteNSFWVideo) ? 0f : 1f);
+ if (mFragment.getMasterMutingOption() == null) {
+ ((PostVideoAutoplayViewHolder) holder).setVolume(mMuteAutoplayingVideos || (post.isNSFW() && mMuteNSFWVideo) ? 0f : 1f);
+ } else {
+ ((PostVideoAutoplayViewHolder) holder).setVolume(mFragment.getMasterMutingOption() ? 0f : 1f);
+ }
if (post.isGfycat() || post.isRedgifs() && !post.isLoadGfyOrRedgifsVideoSuccess()) {
((PostVideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks = new FetchGfycatOrRedgifsVideoLinks(new FetchGfycatOrRedgifsVideoLinks.FetchGfycatOrRedgifsVideoLinksListener() {
@@ -720,18 +751,21 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
((PostVideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks
- .fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(mGfycatRetrofit, mRedgifsRetrofit,
- post.getGfycatId(), post.isGfycat(), mAutomaticallyTryRedgifs);
+ .fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(mExecutor, new Handler(),
+ mGfycatRetrofit, mRedgifsRetrofit, post.getGfycatId(),
+ post.isGfycat(), mAutomaticallyTryRedgifs);
} else {
((PostVideoAutoplayViewHolder) holder).bindVideoUri(Uri.parse(post.getVideoUrl()));
}
} else if (holder instanceof PostWithPreviewTypeViewHolder) {
if (post.getPostType() == Post.VIDEO_TYPE) {
((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
+ ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_play_circle_36dp));
((PostWithPreviewTypeViewHolder) holder).typeTextView.setText(mActivity.getString(R.string.video));
} else if (post.getPostType() == Post.GIF_TYPE) {
if (!mAutoplay) {
((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
+ ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_play_circle_36dp));
}
((PostWithPreviewTypeViewHolder) holder).typeTextView.setText(mActivity.getString(R.string.gif));
} else if (post.getPostType() == Post.IMAGE_TYPE) {
@@ -747,6 +781,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
} else if (post.getPostType() == Post.GALLERY_TYPE) {
((PostWithPreviewTypeViewHolder) holder).typeTextView.setText(mActivity.getString(R.string.gallery));
+ ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
+ ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_gallery_reverse_color_24dp));
}
if (post.getPostType() != Post.NO_PREVIEW_LINK_TYPE) {
@@ -764,7 +800,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
} else if (post.getPostType() == Post.LINK_TYPE) {
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_link);
} else if (post.getPostType() == Post.GALLERY_TYPE) {
- ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
} else if (mDataSavingMode && mOnlyDisablePreviewInVideoAndGifPosts && (post.getPostType() == Post.VIDEO_TYPE || post.getPostType() == Post.GIF_TYPE)) {
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE);
@@ -796,7 +832,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
} else if (post.getPostType() == Post.LINK_TYPE) {
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_link);
} else if (post.getPostType() == Post.GALLERY_TYPE) {
- ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
}
}
@@ -821,7 +857,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
} else {
((PostCard2VideoAutoplayViewHolder) holder).aspectRatioFrameLayout.setAspectRatio(1);
}
- ((PostCard2VideoAutoplayViewHolder) holder).setVolume(mMuteAutoplayingVideos || (post.isNSFW() && mMuteNSFWVideo) ? 0f : 1f);
+ if (mFragment.getMasterMutingOption() == null) {
+ ((PostCard2VideoAutoplayViewHolder) holder).setVolume(mMuteAutoplayingVideos || (post.isNSFW() && mMuteNSFWVideo) ? 0f : 1f);
+ } else {
+ ((PostCard2VideoAutoplayViewHolder) holder).setVolume(mFragment.getMasterMutingOption() ? 0f : 1f);
+ }
if (post.isGfycat() || post.isRedgifs() && !post.isLoadGfyOrRedgifsVideoSuccess()) {
((PostCard2VideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks = new FetchGfycatOrRedgifsVideoLinks(new FetchGfycatOrRedgifsVideoLinks.FetchGfycatOrRedgifsVideoLinksListener() {
@@ -843,18 +883,21 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
((PostCard2VideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks
- .fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(mGfycatRetrofit, mRedgifsRetrofit,
- post.getGfycatId(), post.isGfycat(), mAutomaticallyTryRedgifs);
+ .fetchGfycatOrRedgifsVideoLinksInRecyclerViewAdapter(mExecutor, new Handler(),
+ mGfycatRetrofit, mRedgifsRetrofit, post.getGfycatId(), post.isGfycat(),
+ mAutomaticallyTryRedgifs);
} else {
((PostCard2VideoAutoplayViewHolder) holder).bindVideoUri(Uri.parse(post.getVideoUrl()));
}
} else if (holder instanceof PostCard2WithPreviewViewHolder) {
if (post.getPostType() == Post.VIDEO_TYPE) {
((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
+ ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_play_circle_36dp));
((PostCard2WithPreviewViewHolder) holder).typeTextView.setText(mActivity.getString(R.string.video));
} else if (post.getPostType() == Post.GIF_TYPE) {
if (!mAutoplay) {
((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
+ ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_play_circle_36dp));
}
((PostCard2WithPreviewViewHolder) holder).typeTextView.setText(mActivity.getString(R.string.gif));
} else if (post.getPostType() == Post.IMAGE_TYPE) {
@@ -870,6 +913,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
} else if (post.getPostType() == Post.GALLERY_TYPE) {
((PostCard2WithPreviewViewHolder) holder).typeTextView.setText(mActivity.getString(R.string.gallery));
+ ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
+ ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_gallery_reverse_color_24dp));
}
if (post.getPostType() != Post.NO_PREVIEW_LINK_TYPE) {
@@ -888,7 +933,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
} else if (post.getPostType() == Post.LINK_TYPE) {
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_link);
} else if (post.getPostType() == Post.GALLERY_TYPE) {
- ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
} else if (mDataSavingMode && mOnlyDisablePreviewInVideoAndGifPosts && (post.getPostType() == Post.VIDEO_TYPE || post.getPostType() == Post.GIF_TYPE)) {
((PostCard2WithPreviewViewHolder) holder).progressBar.setVisibility(View.GONE);
@@ -922,7 +967,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
} else if (post.getPostType() == Post.LINK_TYPE) {
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_link);
} else if (post.getPostType() == Post.GALLERY_TYPE) {
- ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
}
}
@@ -1123,8 +1168,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
if (flair != null && !flair.equals("")) {
- ((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
- Utils.setHTMLWithImageToTextView(((PostCompactBaseViewHolder) holder).flairTextView, flair, false);
+ if (mHidePostFlair) {
+ ((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.GONE);
+ } else {
+ ((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
+ Utils.setHTMLWithImageToTextView(((PostCompactBaseViewHolder) holder).flairTextView, flair, false);
+ }
}
if (nAwards > 0 && !mHideTheNumberOfAwards) {
@@ -1153,7 +1202,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostCompactBaseViewHolder) holder).relativeLayout.setVisibility(View.VISIBLE);
if (post.getPostType() == Post.GALLERY_TYPE && post.getPreviews() != null && post.getPreviews().isEmpty()) {
((PostCompactBaseViewHolder) holder).noPreviewPostImageFrameLayout.setVisibility(View.VISIBLE);
- ((PostCompactBaseViewHolder) holder).noPreviewPostImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostCompactBaseViewHolder) holder).noPreviewPostImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
ArrayList<Post.Preview> previews = post.getPreviews();
if (previews != null && !previews.isEmpty()) {
@@ -1242,7 +1291,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostCompactBaseViewHolder) holder).typeTextView.setText(R.string.gallery);
if (mDataSavingMode && mDisableImagePreview) {
((PostCompactBaseViewHolder) holder).noPreviewPostImageFrameLayout.setVisibility(View.VISIBLE);
- ((PostCompactBaseViewHolder) holder).noPreviewPostImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostCompactBaseViewHolder) holder).noPreviewPostImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
break;
case Post.TEXT_TYPE:
@@ -1307,12 +1356,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_outline_video_24dp);
((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
} else if (post.getPostType() == Post.IMAGE_TYPE || post.getPostType() == Post.GIF_TYPE) {
-
((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
} else if (post.getPostType() == Post.LINK_TYPE) {
((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_link);
} else if (post.getPostType() == Post.GALLERY_TYPE) {
- ((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp);
}
@@ -1322,7 +1370,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostGalleryViewHolder) holder).imageView.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
- ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(mActivity.getDrawable(R.drawable.ic_play_circle_36dp));
+ ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_play_circle_36dp));
Post.Preview preview = getSuitablePreview(post.getPreviews());
if (preview != null) {
@@ -1347,7 +1395,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostGalleryViewHolder) holder).imageView.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
- ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(mActivity.getDrawable(R.drawable.ic_play_circle_36dp));
+ ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_play_circle_36dp));
Post.Preview preview = getSuitablePreview(post.getPreviews());
if (preview != null) {
@@ -1372,7 +1420,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostGalleryViewHolder) holder).imageView.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
- ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(mActivity.getDrawable(R.drawable.ic_link_post_type_indicator));
+ ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_link_post_type_indicator));
Post.Preview preview = getSuitablePreview(post.getPreviews());
if (preview != null) {
@@ -1407,7 +1455,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostGalleryViewHolder) holder).imageView.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.VISIBLE);
- ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(mActivity.getDrawable(R.drawable.ic_gallery_24dp));
+ ((PostGalleryViewHolder) holder).videoOrGifIndicatorImageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_gallery_reverse_color_24dp));
Post.Preview preview = getSuitablePreview(post.getPreviews());
if (preview != null) {
@@ -1424,7 +1472,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
loadImage(holder, post, preview);
} else {
((PostGalleryViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE);
- ((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_24dp);
+ ((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_gallery_reverse_color_24dp);
}
break;
}
@@ -1477,7 +1525,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
private void loadImage(final RecyclerView.ViewHolder holder, final Post post, @NonNull Post.Preview preview) {
if (holder instanceof PostWithPreviewTypeViewHolder) {
String url;
- if (post.getPostType() == Post.GIF_TYPE && mAutoplay) {
+ boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler;
+ if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl();
} else {
url = preview.getPreviewUrl();
@@ -1503,7 +1552,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
- if ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler) {
+ if (blurImage) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10)))
.into(((PostWithPreviewTypeViewHolder) holder).imageView);
} else {
@@ -1546,7 +1595,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
} else if (holder instanceof PostGalleryViewHolder) {
String url;
- if (post.getPostType() == Post.GIF_TYPE && mAutoplay) {
+ boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler;
+ if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl();
} else {
url = preview.getPreviewUrl();
@@ -1572,7 +1622,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
- if ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler) {
+ if (blurImage) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10)))
.into(((PostGalleryViewHolder) holder).imageView);
} else {
@@ -1584,7 +1634,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
} else if (holder instanceof PostCard2WithPreviewViewHolder) {
String url;
- if (post.getPostType() == Post.GIF_TYPE && mAutoplay) {
+ boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler;
+ if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl();
} else {
url = preview.getPreviewUrl();
@@ -1610,7 +1661,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
- if ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler) {
+ if (blurImage) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10)))
.into(((PostCard2WithPreviewViewHolder) holder).imageView);
} else {
@@ -1801,6 +1852,10 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
mHidePostType = hidePostType;
}
+ public void setHidePostFlair(boolean hidePostFlair) {
+ mHidePostFlair = hidePostFlair;
+ }
+
public void setHideTheNumberOfAwards(boolean hideTheNumberOfAwards) {
mHideTheNumberOfAwards = hideTheNumberOfAwards;
}
@@ -1817,6 +1872,10 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
mHideTheNumberOfComments = hideTheNumberOfComments;
}
+ public void setDefaultLinkPostLayout(int defaultLinkPostLayout) {
+ mDefaultLinkPostLayout = defaultLinkPostLayout;
+ }
+
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
@@ -1828,22 +1887,26 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostBaseViewHolder) holder).markPostRead(post, false);
}
}
- ((PostBaseViewHolder) holder).itemView.setVisibility(View.VISIBLE);
+ holder.itemView.setVisibility(View.VISIBLE);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
if (holder instanceof PostCard2VideoAutoplayViewHolder || holder instanceof PostCard2WithPreviewViewHolder) {
int paddingPixel = (int) Utils.convertDpToPixel(16, mActivity);
- ((PostBaseViewHolder) holder).itemView.setPadding(0, paddingPixel, 0, 0);
+ holder.itemView.setPadding(0, paddingPixel, 0, 0);
} else if (holder instanceof PostCard2TextTypeViewHolder) {
int paddingPixel = (int) Utils.convertDpToPixel(12, mActivity);
- ((PostBaseViewHolder) holder).itemView.setPadding(0, paddingPixel, 0, 0);
+ holder.itemView.setPadding(0, paddingPixel, 0, 0);
} else {
int marginPixel = (int) Utils.convertDpToPixel(8, mActivity);
params.topMargin = marginPixel;
params.bottomMargin = marginPixel;
}
holder.itemView.setLayoutParams(params);
- ((PostBaseViewHolder) holder).itemView.setBackgroundTintList(ColorStateList.valueOf(mCardViewBackgroundColor));
+ if (((PostBaseViewHolder) holder).itemViewIsNotCardView) {
+ holder.itemView.setBackgroundColor(mCardViewBackgroundColor);
+ } else {
+ holder.itemView.setBackgroundTintList(ColorStateList.valueOf(mCardViewBackgroundColor));
+ }
((PostBaseViewHolder) holder).titleTextView.setTextColor(mPostTitleColor);
if (holder instanceof PostVideoAutoplayViewHolder) {
((PostVideoAutoplayViewHolder) holder).mediaUri = null;
@@ -1867,6 +1930,16 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((PostTextTypeViewHolder) holder).contentTextView.setText("");
((PostTextTypeViewHolder) holder).contentTextView.setTextColor(mPostContentColor);
((PostTextTypeViewHolder) holder).contentTextView.setVisibility(View.GONE);
+ } else if (holder instanceof PostCard2VideoAutoplayViewHolder) {
+ ((PostCard2VideoAutoplayViewHolder) holder).mediaUri = null;
+ if (((PostCard2VideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks != null) {
+ ((PostCard2VideoAutoplayViewHolder) holder).fetchGfycatOrRedgifsVideoLinks.cancel();
+ }
+ ((PostCard2VideoAutoplayViewHolder) holder).errorLoadingGfycatImageView.setVisibility(View.GONE);
+ ((PostCard2VideoAutoplayViewHolder) holder).muteButton.setVisibility(View.GONE);
+ ((PostCard2VideoAutoplayViewHolder) holder).resetVolume();
+ mGlide.clear(((PostCard2VideoAutoplayViewHolder) holder).previewImageView);
+ ((PostCard2VideoAutoplayViewHolder) holder).previewImageView.setVisibility(View.GONE);
} else if (holder instanceof PostCard2WithPreviewViewHolder) {
mGlide.clear(((PostCard2WithPreviewViewHolder) holder).imageView);
((PostCard2WithPreviewViewHolder) holder).imageView.setVisibility(View.GONE);
@@ -1964,14 +2037,14 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
if (super.getItemCount() <= 0 || order >= super.getItemCount()) {
return null;
}
- return getItem(order);
+ return order;
}
@Nullable
@Override
public Integer getOrderForKey(@NonNull Object key) {
- if (getCurrentList() != null && key instanceof Post) {
- return getCurrentList().indexOf(key);
+ if (key instanceof Integer) {
+ return (Integer) key;
}
return null;
@@ -2103,6 +2176,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
ImageView saveButton;
ImageView shareButton;
+ boolean itemViewIsNotCardView = false;
+
PostBaseViewHolder(@NonNull View itemView) {
super(itemView);
}
@@ -2171,7 +2246,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
constraintSet.applyTo(bottomConstraintLayout);
}
- itemView.setBackgroundTintList(ColorStateList.valueOf(mCardViewBackgroundColor));
+ if (itemViewIsNotCardView) {
+ itemView.setBackgroundColor(mCardViewBackgroundColor);
+ } else {
+ itemView.setBackgroundTintList(ColorStateList.valueOf(mCardViewBackgroundColor));
+ }
subredditTextView.setTextColor(mSubredditColor);
userTextView.setTextColor(mUsernameColor);
postTimeTextView.setTextColor(mSecondaryTextColor);
@@ -2587,11 +2666,44 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
});
}
+ void setBaseView(AspectRatioGifImageView iconGifImageView,
+ TextView subredditTextView,
+ TextView userTextView,
+ ImageView stickiedPostImageView,
+ TextView postTimeTextView,
+ TextView titleTextView,
+ CustomTextView typeTextView,
+ ImageView archivedImageView,
+ ImageView lockedImageView,
+ ImageView crosspostImageView,
+ CustomTextView nsfwTextView,
+ CustomTextView spoilerTextView,
+ CustomTextView flairTextView,
+ CustomTextView awardsTextView,
+ ConstraintLayout bottomConstraintLayout,
+ ImageView upvoteButton,
+ TextView scoreTextView,
+ ImageView downvoteButton,
+ TextView commentsCountTextView,
+ ImageView saveButton,
+ ImageView shareButton, boolean itemViewIsNotCardView) {
+ this.itemViewIsNotCardView = itemViewIsNotCardView;
+
+ setBaseView(iconGifImageView, subredditTextView, userTextView, stickiedPostImageView, postTimeTextView,
+ titleTextView, typeTextView, archivedImageView, lockedImageView, crosspostImageView,
+ nsfwTextView, spoilerTextView, flairTextView, awardsTextView, bottomConstraintLayout,
+ upvoteButton, scoreTextView, downvoteButton, commentsCountTextView, saveButton, shareButton);
+ }
+
void markPostRead(Post post, boolean changePostItemColor) {
if (mAccessToken != null && !post.isRead() && mMarkPostsAsRead) {
post.markAsRead(true);
if (changePostItemColor) {
- itemView.setBackgroundTintList(ColorStateList.valueOf(mReadPostCardViewBackgroundColor));
+ if (itemViewIsNotCardView) {
+ itemView.setBackgroundColor(mReadPostCardViewBackgroundColor);
+ } else {
+ itemView.setBackgroundTintList(ColorStateList.valueOf(mReadPostCardViewBackgroundColor));
+ }
titleTextView.setTextColor(mReadPostTitleColor);
if (this instanceof PostTextTypeViewHolder) {
((PostTextTypeViewHolder) this).contentTextView.setTextColor(mReadPostContentColor);
@@ -2697,13 +2809,15 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
muteButton.setOnClickListener(view -> {
if (helper != null) {
if (helper.getVolume() != 0) {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_mute_white_rounded_24dp));
helper.setVolume(0f);
volume = 0f;
+ mFragment.videoAutoplayChangeMutingOption(true);
} else {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_unmute_white_rounded_24dp));
helper.setVolume(1f);
volume = 1f;
+ mFragment.videoAutoplayChangeMutingOption(false);
}
}
});
@@ -2747,7 +2861,6 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
});
previewImageView.setOnLongClickListener(view -> fullscreenButton.performClick());
- videoPlayer.setOnLongClickListener(view -> fullscreenButton.performClick());
}
void bindVideoUri(Uri videoUri) {
@@ -2788,12 +2901,15 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
for (int i = 0; i < trackGroups.length; i++) {
String mimeType = trackGroups.get(i).getFormat(0).sampleMimeType;
if (mimeType != null && mimeType.contains("audio")) {
+ if (mFragment.getMasterMutingOption() != null) {
+ volume = mFragment.getMasterMutingOption() ? 0f : 1f;
+ }
helper.setVolume(volume);
muteButton.setVisibility(View.VISIBLE);
if (volume != 0f) {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_unmute_white_rounded_24dp));
} else {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_mute_white_rounded_24dp));
}
break;
}
@@ -3149,6 +3265,10 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
constraintSet.applyTo(bottomConstraintLayout);
}
+ if (((ViewGroup) itemView).getLayoutTransition() != null) {
+ ((ViewGroup) itemView).getLayoutTransition().setAnimateParentHierarchy(false);
+ }
+
itemView.setBackgroundColor(mCardViewBackgroundColor);
postTimeTextView.setTextColor(mSecondaryTextColor);
titleTextView.setTextColor(mPostTitleColor);
@@ -3902,7 +4022,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
downvoteButton,
commentsCountTextView,
saveButton,
- shareButton);
+ shareButton,
+ true);
divider.setBackgroundColor(mDividerColor);
@@ -3911,13 +4032,15 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
muteButton.setOnClickListener(view -> {
if (helper != null) {
if (helper.getVolume() != 0) {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_mute_white_rounded_24dp));
helper.setVolume(0f);
volume = 0f;
+ mFragment.videoAutoplayChangeMutingOption(true);
} else {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_unmute_white_rounded_24dp));
helper.setVolume(1f);
volume = 1f;
+ mFragment.videoAutoplayChangeMutingOption(false);
}
}
});
@@ -3961,7 +4084,6 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
});
previewImageView.setOnLongClickListener(view -> fullscreenButton.performClick());
- videoPlayer.setOnLongClickListener(view -> fullscreenButton.performClick());
}
void bindVideoUri(Uri videoUri) {
@@ -4002,12 +4124,15 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
for (int i = 0; i < trackGroups.length; i++) {
String mimeType = trackGroups.get(i).getFormat(0).sampleMimeType;
if (mimeType != null && mimeType.contains("audio")) {
+ if (mFragment.getMasterMutingOption() != null) {
+ volume = mFragment.getMasterMutingOption() ? 0f : 1f;
+ }
helper.setVolume(volume);
muteButton.setVisibility(View.VISIBLE);
if (volume != 0f) {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_unmute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_unmute_white_rounded_24dp));
} else {
- muteButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_mute_white_rounded_18dp));
+ muteButton.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_mute_white_rounded_24dp));
}
break;
}
@@ -4157,7 +4282,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
downvoteButton,
commentsCountTextView,
saveButton,
- shareButton);
+ shareButton,
+ true);
linkTextView.setTextColor(mSecondaryTextColor);
noPreviewImageView.setBackgroundColor(mNoPreviewPostTypeBackgroundColor);
@@ -4256,7 +4382,8 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
downvoteButton,
commentsCountTextView,
saveButton,
- shareButton);
+ shareButton,
+ true);
contentTextView.setTextColor(mPostContentColor);
divider.setBackgroundColor(mDividerColor);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RPANCommentStreamRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RPANCommentStreamRecyclerViewAdapter.java
new file mode 100644
index 00000000..ba7dcd34
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RPANCommentStreamRecyclerViewAdapter.java
@@ -0,0 +1,83 @@
+package ml.docilealligator.infinityforreddit.adapters;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.RequestManager;
+import com.bumptech.glide.request.RequestOptions;
+
+import java.util.ArrayList;
+
+import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.RPANComment;
+
+public class RPANCommentStreamRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+ private RequestManager glide;
+ private ArrayList<RPANComment> rpanComments;
+
+ public RPANCommentStreamRecyclerViewAdapter(Context context) {
+ glide = Glide.with(context);
+ rpanComments = new ArrayList<>();
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ return new RPANCommentViewHolder(LayoutInflater.from(parent.getContext()).inflate(
+ R.layout.item_rpan_comment, parent, false));
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ if (holder instanceof RPANCommentViewHolder) {
+ ((RPANCommentViewHolder) holder).authorTextView.setText(rpanComments.get(position).author);
+ ((RPANCommentViewHolder) holder).contentTextView.setText(rpanComments.get(position).content);
+ glide.load(rpanComments.get(position).authorIconImage)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .error(glide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
+ .into(((RPANCommentViewHolder) holder).iconImageView);
+ }
+ }
+
+ @Override
+ public int getItemCount() {
+ return rpanComments == null ? 0 : rpanComments.size();
+ }
+
+ @Override
+ public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
+ super.onViewRecycled(holder);
+ if (holder instanceof RPANCommentViewHolder) {
+ glide.clear(((RPANCommentViewHolder) holder).iconImageView);
+ }
+ }
+
+ public void addRPANComment(RPANComment rpanComment) {
+ rpanComments.add(rpanComment);
+ notifyItemInserted(rpanComments.size() - 1);
+ }
+
+ class RPANCommentViewHolder extends RecyclerView.ViewHolder {
+ ImageView iconImageView;
+ TextView authorTextView;
+ TextView timeTextView;
+ TextView contentTextView;
+
+ public RPANCommentViewHolder(@NonNull View itemView) {
+ super(itemView);
+ iconImageView = itemView.findViewById(R.id.icon_image_view_item_rpan_comment);
+ authorTextView = itemView.findViewById(R.id.author_text_view_item_rpan_comment);
+ contentTextView = itemView.findViewById(R.id.content_text_view_item_rpan_comment);
+ }
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RedditGallerySubmissionRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RedditGallerySubmissionRecyclerViewAdapter.java
new file mode 100644
index 00000000..bec2d265
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/RedditGallerySubmissionRecyclerViewAdapter.java
@@ -0,0 +1,231 @@
+package ml.docilealligator.infinityforreddit.adapters;
+
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.graphics.drawable.Drawable;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewTreeObserver;
+import android.widget.ImageView;
+import android.widget.ProgressBar;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.RequestManager;
+import com.bumptech.glide.load.DataSource;
+import com.bumptech.glide.load.engine.GlideException;
+import com.bumptech.glide.load.resource.bitmap.CenterCrop;
+import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
+import com.bumptech.glide.request.RequestListener;
+import com.bumptech.glide.request.RequestOptions;
+import com.bumptech.glide.request.target.Target;
+import com.google.android.material.floatingactionbutton.FloatingActionButton;
+
+import java.util.ArrayList;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.RedditGalleryPayload;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.AspectRatioGifImageView;
+
+public class RedditGallerySubmissionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+
+ private static final int VIEW_TYPE_IMAGE = 1;
+ private static final int VIEW_TYPE_ADD_IMAGE = 2;
+
+ private ArrayList<RedditGalleryImageInfo> redditGalleryImageInfoList;
+ private CustomThemeWrapper customThemeWrapper;
+ private ItemClickListener itemClickListener;
+ private RequestManager glide;
+
+ public RedditGallerySubmissionRecyclerViewAdapter(Context context, CustomThemeWrapper customThemeWrapper,
+ ItemClickListener itemClickListener) {
+ glide = Glide.with(context);
+ this.customThemeWrapper = customThemeWrapper;
+ this.itemClickListener = itemClickListener;
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ if (redditGalleryImageInfoList == null || position >= redditGalleryImageInfoList.size()) {
+ return VIEW_TYPE_ADD_IMAGE;
+ }
+
+ return VIEW_TYPE_IMAGE;
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ if (viewType == VIEW_TYPE_ADD_IMAGE) {
+ return new AddImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_reddit_gallery_submission_add_image, parent, false));
+ }
+ return new ImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_reddit_gallery_submission_image, parent, false));
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ if (holder instanceof ImageViewHolder) {
+ glide.load(redditGalleryImageInfoList.get(position).imageUrlString)
+ .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(48)))
+ .listener(new RequestListener<Drawable>() {
+
+ @Override
+ public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
+ ((ImageViewHolder) holder).progressBar.setVisibility(View.GONE);
+ ((ImageViewHolder) holder).closeImageView.setVisibility(View.VISIBLE);
+ return false;
+ }
+
+ @Override
+ public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
+ return false;
+ }
+ })
+ .into(((ImageViewHolder) holder).imageView);
+
+ if (redditGalleryImageInfoList.get(position).payload != null) {
+ ((ImageViewHolder) holder).progressBar.setVisibility(View.GONE);
+ ((ImageViewHolder) holder).closeImageView.setVisibility(View.VISIBLE);
+ }
+ }
+ }
+
+ @Override
+ public int getItemCount() {
+ return redditGalleryImageInfoList == null ? 1 : (redditGalleryImageInfoList.size() >= 20 ? 20 : redditGalleryImageInfoList.size() + 1);
+ }
+
+ @Override
+ public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
+ super.onViewRecycled(holder);
+ if (holder instanceof ImageViewHolder) {
+ glide.clear(((ImageViewHolder) holder).imageView);
+ ((ImageViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
+ ((ImageViewHolder) holder).closeImageView.setVisibility(View.GONE);
+ }
+ }
+
+ public ArrayList<RedditGalleryImageInfo> getRedditGalleryImageInfoList() {
+ return redditGalleryImageInfoList;
+ }
+
+ public void setRedditGalleryImageInfoList(ArrayList<RedditGalleryImageInfo> redditGalleryImageInfoList) {
+ this.redditGalleryImageInfoList = redditGalleryImageInfoList;
+ notifyDataSetChanged();
+ }
+
+ public void addImage(String imageUrl) {
+ if (redditGalleryImageInfoList == null) {
+ redditGalleryImageInfoList = new ArrayList<>();
+ }
+ redditGalleryImageInfoList.add(new RedditGalleryImageInfo(imageUrl));
+ notifyItemInserted(redditGalleryImageInfoList.size() - 1);
+ }
+
+ public void setImageAsUploaded(String mediaId) {
+ redditGalleryImageInfoList.get(redditGalleryImageInfoList.size() - 1).payload = new RedditGalleryPayload.Item("", "", mediaId);
+ notifyItemChanged(redditGalleryImageInfoList.size() - 1);
+ }
+
+ public void removeFailedToUploadImage() {
+ redditGalleryImageInfoList.remove(redditGalleryImageInfoList.size() - 1);
+ notifyItemRemoved(redditGalleryImageInfoList.size());
+ }
+
+ class ImageViewHolder extends RecyclerView.ViewHolder {
+ @BindView(R.id.aspect_ratio_gif_image_view_item_reddit_gallery_submission_image)
+ AspectRatioGifImageView imageView;
+ @BindView(R.id.progress_bar_item_reddit_gallery_submission_image)
+ ProgressBar progressBar;
+ @BindView(R.id.close_image_view_item_reddit_gallery_submission_image)
+ ImageView closeImageView;
+
+ public ImageViewHolder(@NonNull View itemView) {
+ super(itemView);
+
+ ButterKnife.bind(this, itemView);
+
+ imageView.setRatio(1);
+
+ closeImageView.setOnClickListener(view -> {
+ redditGalleryImageInfoList.remove(getBindingAdapterPosition());
+ notifyItemRemoved(getBindingAdapterPosition());
+ });
+ }
+ }
+
+ class AddImageViewHolder extends RecyclerView.ViewHolder {
+
+ public AddImageViewHolder(@NonNull View itemView) {
+ super(itemView);
+
+ FloatingActionButton fab = itemView.findViewById(R.id.fab_item_gallery_submission_add_image);
+ fab.setBackgroundTintList(ColorStateList.valueOf(customThemeWrapper.getColorPrimaryLightTheme()));
+ fab.setImageTintList(ColorStateList.valueOf(customThemeWrapper.getFABIconColor()));
+
+ itemView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
+ @Override
+ public void onGlobalLayout() {
+ itemView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
+ int width = itemView.getMeasuredWidth();
+ ViewGroup.LayoutParams params = itemView.getLayoutParams();
+ params.height = width;
+ itemView.setLayoutParams(params);
+ }
+ });
+
+ fab.setOnClickListener(view -> itemClickListener.onAddImageClicked());
+ itemView.setOnClickListener(view -> fab.performClick());
+ }
+ }
+
+ public static class RedditGalleryImageInfo implements Parcelable {
+ public String imageUrlString;
+ public RedditGalleryPayload.Item payload;
+
+ public RedditGalleryImageInfo(String imageUrlString) {
+ this.imageUrlString = imageUrlString;
+ }
+
+ protected RedditGalleryImageInfo(Parcel in) {
+ imageUrlString = in.readString();
+ payload = in.readParcelable(RedditGalleryPayload.Item.class.getClassLoader());
+ }
+
+ public static final Creator<RedditGalleryImageInfo> CREATOR = new Creator<RedditGalleryImageInfo>() {
+ @Override
+ public RedditGalleryImageInfo createFromParcel(Parcel in) {
+ return new RedditGalleryImageInfo(in);
+ }
+
+ @Override
+ public RedditGalleryImageInfo[] newArray(int size) {
+ return new RedditGalleryImageInfo[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int i) {
+ parcel.writeString(imageUrlString);
+ parcel.writeParcelable(payload, i);
+ }
+ }
+
+ public interface ItemClickListener {
+ void onAddImageClicked();
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditAutocompleteRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditAutocompleteRecyclerViewAdapter.java
new file mode 100644
index 00000000..c657f422
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditAutocompleteRecyclerViewAdapter.java
@@ -0,0 +1,103 @@
+package ml.docilealligator.infinityforreddit.adapters;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.RequestManager;
+import com.bumptech.glide.request.RequestOptions;
+import com.google.android.material.checkbox.MaterialCheckBox;
+
+import java.util.List;
+
+import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
+import pl.droidsonroids.gif.GifImageView;
+
+public class SubredditAutocompleteRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+ private List<SubredditData> subreddits;
+ private RequestManager glide;
+ private CustomThemeWrapper customThemeWrapper;
+ private ItemOnClickListener itemOnClickListener;
+
+ public SubredditAutocompleteRecyclerViewAdapter(Context context, CustomThemeWrapper customThemeWrapper,
+ ItemOnClickListener itemOnClickListener) {
+ glide = Glide.with(context);
+ this.customThemeWrapper = customThemeWrapper;
+ this.itemOnClickListener = itemOnClickListener;
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ return new SubredditViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_subreddit_listing, parent, false));
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ if (holder instanceof SubredditViewHolder) {
+ glide.load(subreddits.get(position).getIconUrl())
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .error(glide.load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
+ .into(((SubredditViewHolder) holder).iconImageView);
+ ((SubredditViewHolder) holder).subredditNameTextView.setText(subreddits.get(position).getName());
+ }
+ }
+
+ @Override
+ public int getItemCount() {
+ return subreddits == null ? 0 : subreddits.size();
+ }
+
+ @Override
+ public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
+ super.onViewRecycled(holder);
+ if (holder instanceof SubredditViewHolder) {
+ glide.clear(((SubredditViewHolder) holder).iconImageView);
+ }
+ }
+
+ public void setSubreddits(List<SubredditData> subreddits) {
+ this.subreddits = subreddits;
+ notifyDataSetChanged();
+ }
+
+ class SubredditViewHolder extends RecyclerView.ViewHolder {
+
+ GifImageView iconImageView;
+ TextView subredditNameTextView;
+ ImageView subscribeImageView;
+ MaterialCheckBox checkBox;
+
+ public SubredditViewHolder(@NonNull View itemView) {
+ super(itemView);
+ iconImageView = itemView.findViewById(R.id.subreddit_icon_gif_image_view_item_subreddit_listing);
+ subredditNameTextView = itemView.findViewById(R.id.subreddit_name_text_view_item_subreddit_listing);
+ subscribeImageView = itemView.findViewById(R.id.subscribe_image_view_item_subreddit_listing);
+ checkBox = itemView.findViewById(R.id.checkbox_item_subreddit_listing);
+
+ subscribeImageView.setVisibility(View.GONE);
+ checkBox.setVisibility(View.GONE);
+
+ subredditNameTextView.setTextColor(customThemeWrapper.getPrimaryTextColor());
+
+ itemView.setOnClickListener(view -> {
+ itemOnClickListener.onClick(subreddits.get(getBindingAdapterPosition()));
+ });
+ }
+ }
+
+ public interface ItemOnClickListener {
+ void onClick(SubredditData subredditData);
+ }
+}
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 f7891958..18268b54 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/SubredditListingRecyclerViewAdapter.java
@@ -262,7 +262,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
TextView subredditNameTextView;
@BindView(R.id.subscribe_image_view_item_subreddit_listing)
ImageView subscribeButton;
- @BindView(R.id.checkbox__item_subreddit_listing)
+ @BindView(R.id.checkbox_item_subreddit_listing)
MaterialCheckBox checkBox;
DataViewHolder(View itemView) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/TrendingSearchRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/TrendingSearchRecyclerViewAdapter.java
new file mode 100644
index 00000000..8ab40aff
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/TrendingSearchRecyclerViewAdapter.java
@@ -0,0 +1,228 @@
+package ml.docilealligator.infinityforreddit.adapters;
+
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.graphics.drawable.Drawable;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.ProgressBar;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.RequestBuilder;
+import com.bumptech.glide.RequestManager;
+import com.bumptech.glide.load.DataSource;
+import com.bumptech.glide.load.engine.GlideException;
+import com.bumptech.glide.request.RequestListener;
+import com.bumptech.glide.request.target.Target;
+
+import java.util.ArrayList;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.TrendingSearch;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.AspectRatioGifImageView;
+import ml.docilealligator.infinityforreddit.post.Post;
+
+public class TrendingSearchRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+ private ArrayList<TrendingSearch> trendingSearches;
+ private CustomThemeWrapper customThemeWrapper;
+ private RequestManager glide;
+ private int imageViewWidth;
+ private boolean dataSavingMode;
+ private boolean disableImagePreview;
+ private float mScale;
+ private ItemClickListener itemClickListener;
+
+ public TrendingSearchRecyclerViewAdapter(Context context, CustomThemeWrapper customThemeWrapper,
+ int imageViewWidth, boolean dataSavingMode, boolean disableImagePreview,
+ ItemClickListener itemClickListener) {
+ this.customThemeWrapper = customThemeWrapper;
+ this.glide = Glide.with(context);
+ this.imageViewWidth = imageViewWidth;
+ this.dataSavingMode = dataSavingMode;
+ this.disableImagePreview = disableImagePreview;
+ mScale = context.getResources().getDisplayMetrics().density;
+ this.itemClickListener = itemClickListener;
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ return new TrendingSearchViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_trending_search, parent, false));
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ if (holder instanceof TrendingSearchViewHolder) {
+ TrendingSearch trendingSearch = trendingSearches.get(position);
+ if (dataSavingMode && disableImagePreview) {
+ ((TrendingSearchViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE);
+ } else {
+ Post.Preview preview = getSuitablePreview(trendingSearch.previews);
+ if (preview != null) {
+ ((TrendingSearchViewHolder) holder).imageWrapperRelativeLayout.setVisibility(View.VISIBLE);
+ if (preview.getPreviewWidth() <= 0 || preview.getPreviewHeight() <= 0) {
+ int height = (int) (400 * mScale);
+ ((TrendingSearchViewHolder) holder).imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
+ ((TrendingSearchViewHolder) holder).imageView.getLayoutParams().height = height;
+ preview.setPreviewWidth(imageViewWidth);
+ preview.setPreviewHeight(height);
+ } else {
+ ((TrendingSearchViewHolder) holder).imageView
+ .setRatio((float) preview.getPreviewHeight() / preview.getPreviewWidth());
+ }
+ loadImage((TrendingSearchViewHolder) holder, preview);
+ } else {
+ ((TrendingSearchViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE);
+ }
+ }
+
+ ((TrendingSearchViewHolder) holder).titleTextView.setText(trendingSearch.displayString);
+ }
+ }
+
+ @Override
+ public int getItemCount() {
+ return trendingSearches == null ? 0 : trendingSearches.size();
+ }
+
+ @Override
+ public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
+ super.onViewRecycled(holder);
+ if (holder instanceof TrendingSearchViewHolder) {
+ glide.clear(((TrendingSearchViewHolder) holder).imageView);
+ ((TrendingSearchViewHolder) holder).imageWrapperRelativeLayout.setVisibility(View.GONE);
+ ((TrendingSearchViewHolder) holder).errorRelativeLayout.setVisibility(View.GONE);
+ ((TrendingSearchViewHolder) holder).noPreviewLinkImageView.setVisibility(View.GONE);
+ ((TrendingSearchViewHolder) holder).progressBar.setVisibility(View.GONE);
+ }
+ }
+
+ @Nullable
+ private Post.Preview getSuitablePreview(ArrayList<Post.Preview> previews) {
+ Post.Preview preview;
+ if (!previews.isEmpty()) {
+ int previewIndex;
+ if (dataSavingMode && previews.size() > 2) {
+ previewIndex = previews.size() / 2;
+ } else {
+ previewIndex = 0;
+ }
+ preview = previews.get(previewIndex);
+ if (preview.getPreviewWidth() * preview.getPreviewHeight() > 10_000_000) {
+ for (int i = previews.size() - 1; i >= 1; i--) {
+ preview = previews.get(i);
+ if (imageViewWidth >= preview.getPreviewWidth()) {
+ if (preview.getPreviewWidth() * preview.getPreviewHeight() <= 10_000_000) {
+ return preview;
+ }
+ } else {
+ int height = imageViewWidth / preview.getPreviewWidth() * preview.getPreviewHeight();
+ if (imageViewWidth * height <= 10_000_000) {
+ return preview;
+ }
+ }
+ }
+ }
+
+ if (preview.getPreviewWidth() * preview.getPreviewHeight() > 10_000_000) {
+ int divisor = 2;
+ do {
+ preview.setPreviewWidth(preview.getPreviewWidth() / divisor);
+ preview.setPreviewHeight(preview.getPreviewHeight() / divisor);
+ divisor *= 2;
+ } while (preview.getPreviewWidth() * preview.getPreviewHeight() > 10_000_000);
+ }
+ return preview;
+ }
+
+ return null;
+ }
+
+ private void loadImage(final TrendingSearchViewHolder holder, @NonNull Post.Preview preview) {
+ String url = preview.getPreviewUrl();
+ RequestBuilder<Drawable> imageRequestBuilder = glide.load(url).listener(new RequestListener<Drawable>() {
+ @Override
+ public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
+ holder.progressBar.setVisibility(View.GONE);
+ holder.errorRelativeLayout.setVisibility(View.VISIBLE);
+ holder.errorRelativeLayout.setOnClickListener(view -> {
+ holder.progressBar.setVisibility(View.VISIBLE);
+ holder.errorRelativeLayout.setVisibility(View.GONE);
+ loadImage(holder, preview);
+ });
+ return false;
+ }
+
+ @Override
+ public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
+ holder.errorRelativeLayout.setVisibility(View.GONE);
+ holder.progressBar.setVisibility(View.GONE);
+ return false;
+ }
+ });
+
+ if (imageViewWidth > preview.getPreviewWidth()) {
+ imageRequestBuilder.override(preview.getPreviewWidth(), preview.getPreviewHeight()).into(holder.imageView);
+ } else {
+ imageRequestBuilder.into(holder.imageView);
+ }
+ }
+
+ public void setTrendingSearches(ArrayList<TrendingSearch> trendingSearches) {
+ if (trendingSearches != null) {
+ this.trendingSearches = trendingSearches;
+ notifyItemRangeInserted(0, trendingSearches.size());
+ } else {
+ int size = this.trendingSearches == null ? 0 : this.trendingSearches.size();
+ this.trendingSearches = null;
+ notifyItemRangeRemoved(0, size);
+ }
+ }
+
+ class TrendingSearchViewHolder extends RecyclerView.ViewHolder {
+
+ @BindView(R.id.image_wrapper_relative_layout_item_trending_search)
+ RelativeLayout imageWrapperRelativeLayout;
+ @BindView(R.id.progress_bar_item_trending_search)
+ ProgressBar progressBar;
+ @BindView(R.id.image_view_item_trending_search)
+ AspectRatioGifImageView imageView;
+ @BindView(R.id.load_image_error_relative_layout_item_trending_search)
+ RelativeLayout errorRelativeLayout;
+ @BindView(R.id.load_image_error_text_view_item_trending_search)
+ TextView errorTextView;
+ @BindView(R.id.image_view_no_preview_gallery_item_trending_search)
+ ImageView noPreviewLinkImageView;
+ @BindView(R.id.title_text_view_item_trending_search)
+ TextView titleTextView;
+
+ public TrendingSearchViewHolder(@NonNull View itemView) {
+ super(itemView);
+ ButterKnife.bind(this, itemView);
+
+ noPreviewLinkImageView.setBackgroundColor(customThemeWrapper.getNoPreviewPostTypeBackgroundColor());
+ noPreviewLinkImageView.setColorFilter(customThemeWrapper.getNoPreviewPostTypeIconTint(), android.graphics.PorterDuff.Mode.SRC_IN);
+ progressBar.setIndeterminateTintList(ColorStateList.valueOf(customThemeWrapper.getColorAccent()));
+ errorTextView.setTextColor(customThemeWrapper.getPrimaryTextColor());
+
+ itemView.setOnClickListener(view -> {
+ itemClickListener.onClick(trendingSearches.get(getBindingAdapterPosition()));
+ });
+ }
+ }
+
+ public interface ItemClickListener {
+ void onClick(TrendingSearch trendingSearch);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UploadedImagesRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UploadedImagesRecyclerViewAdapter.java
new file mode 100644
index 00000000..eebd6482
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/adapters/UploadedImagesRecyclerViewAdapter.java
@@ -0,0 +1,61 @@
+package ml.docilealligator.infinityforreddit.adapters;
+
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.recyclerview.widget.RecyclerView;
+
+import java.util.ArrayList;
+
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.UploadedImage;
+
+public class UploadedImagesRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+ private ArrayList<UploadedImage> uploadedImages;
+ private ItemClickListener itemClickListener;
+
+ public UploadedImagesRecyclerViewAdapter(ArrayList<UploadedImage> uploadedImages, ItemClickListener itemClickListener) {
+ this.uploadedImages = uploadedImages;
+ this.itemClickListener = itemClickListener;
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ return new UploadedImageViewHolder(LayoutInflater.from(parent.getContext())
+ .inflate(R.layout.item_uploaded_image, parent, false));
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ ((UploadedImageViewHolder) holder).imageNameTextView.setText(uploadedImages.get(position).imageName);
+ ((UploadedImageViewHolder) holder).imageUrlTextView.setText(uploadedImages.get(position).imageUrl);
+ }
+
+ @Override
+ public int getItemCount() {
+ return uploadedImages == null ? 0 : uploadedImages.size();
+ }
+
+ private class UploadedImageViewHolder extends RecyclerView.ViewHolder {
+ TextView imageNameTextView;
+ TextView imageUrlTextView;
+
+ public UploadedImageViewHolder(@NonNull View itemView) {
+ super(itemView);
+ imageNameTextView = itemView.findViewById(R.id.image_name_item_uploaded_image);
+ imageUrlTextView = itemView.findViewById(R.id.image_url_item_uploaded_image);
+
+ itemView.setOnClickListener(view -> {
+ itemClickListener.onClick(uploadedImages.get(getBindingAdapterPosition()));
+ });
+ }
+ }
+
+ public interface ItemClickListener {
+ void onClick(UploadedImage uploadedImage);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/apis/RedditAPI.java b/app/src/main/java/ml/docilealligator/infinityforreddit/apis/RedditAPI.java
index 5e43ca3d..44a65ebb 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/apis/RedditAPI.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/apis/RedditAPI.java
@@ -5,6 +5,7 @@ import java.util.Map;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
+import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
@@ -137,21 +138,23 @@ public interface RedditAPI {
@GET("search.json?include_over_18=1&raw_json=1&type=link")
Call<String> searchPostsOauth(@Query("q") String query, @Query("after") String after,
- @Query("sort") String sort,
+ @Query("sort") String sort, @Query("source") String source,
@HeaderMap Map<String, String> headers);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
Call<String> searchPostsOauth(@Query("q") String query, @Query("after") String after,
@Query("sort") String sort, @Query("t") String sortTime,
+ @Query("source") String source,
@HeaderMap Map<String, String> headers);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
Call<String> searchPosts(@Query("q") String query, @Query("after") String after,
- @Query("sort") String sort);
+ @Query("sort") String sort, @Query("source") String source);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
Call<String> searchPosts(@Query("q") String query, @Query("after") String after,
- @Query("sort") String sort, @Query("t") String sortTime);
+ @Query("sort") String sort, @Query("t") String sortTime,
+ @Query("source") String source);
@GET("r/{subredditName}/search.json?include_over_18=1&raw_json=1&type=link&restrict_sr=true")
Call<String> searchPostsInSpecificSubredditOauth(@Path("subredditName") String subredditName,
@@ -345,11 +348,24 @@ public interface RedditAPI {
@FormUrlEncoded
- @PUT("/api/multi{multipath}r/{subredditName}")
+ @PUT("/api/multi{multipath}/r/{subredditName}")
Call<String> addSubredditToMultiReddit(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> params,
@Path(value = "multipath", encoded = true) String multipath, @Path("subredditName") String subredditName);
@FormUrlEncoded
- @POST("/api/quarantine_optin?raw_json=1")
+ @POST("/api/quarantine_option?raw_json=1")
Call<String> optInQuarantinedSubreddit(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> params);
+
+ @GET("/api/subreddit_autocomplete_v2?typeahead_active=true&include_profiles=false&raw_json=1")
+ Call<String> subredditAutocomplete(@HeaderMap Map<String ,String> headers, @Query("query") String query,
+ @Query("include_over_18") boolean nsfw);
+
+ @POST("/api/submit_gallery_post.json?resubmit=true&raw_json=1")
+ Call<String> submitGalleryPost(@HeaderMap Map<String, String> headers, @Body String body);
+
+ @GET("/api/trending_searches_v1.json?withAds=0&raw_json=1&gilding_detail=1")
+ Call<String> getTrendingSearches(@HeaderMap Map<String, String> headers);
+
+ @GET("/r/{subredditName}/wiki/index.json?raw_json=1")
+ Call<String> getWiki(@Path("subredditName") String subredditName);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/apis/Strapi.java b/app/src/main/java/ml/docilealligator/infinityforreddit/apis/Strapi.java
new file mode 100644
index 00000000..e68b8850
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/apis/Strapi.java
@@ -0,0 +1,13 @@
+package ml.docilealligator.infinityforreddit.apis;
+
+import retrofit2.Call;
+import retrofit2.http.GET;
+import retrofit2.http.Path;
+
+public interface Strapi {
+ @GET("/broadcasts")
+ Call<String> getAllBroadcasts();
+
+ @GET("/videos/{rpan_id_or_fullname}")
+ Call<String> getRPANBroadcast(@Path("rpan_id_or_fullname") String rpanIdOrFullname);
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java
index f6768d11..572baf17 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/asynctasks/CheckIsSubscribedToSubreddit.java
@@ -5,6 +5,7 @@ import android.os.Handler;
import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
+import ml.docilealligator.infinityforreddit.account.Account;
import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData;
public class CheckIsSubscribedToSubreddit {
@@ -13,8 +14,10 @@ public class CheckIsSubscribedToSubreddit {
String subredditName, String accountName,
CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) {
executor.execute(() -> {
- if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) {
- redditDataRoomDatabase.accountDao().insertAnonymousAccount();
+ if (accountName == null) {
+ if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) {
+ redditDataRoomDatabase.accountDao().insert(Account.getAnonymousAccount());
+ }
}
SubscribedSubredditData subscribedSubredditData = redditDataRoomDatabase.subscribedSubredditDao().getSubscribedSubreddit(subredditName, accountName == null ? "-" : accountName);
handler.post(() -> {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/CopyTextBottomSheetFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/CopyTextBottomSheetFragment.java
index d29a1510..7b6452ec 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/CopyTextBottomSheetFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/CopyTextBottomSheetFragment.java
@@ -39,6 +39,7 @@ public class CopyTextBottomSheetFragment extends RoundedBottomSheetDialogFragmen
TextView copyAllMarkdownTextView;
private Activity activity;
+ private String markdownText;
public CopyTextBottomSheetFragment() {
// Required empty public constructor
@@ -52,20 +53,26 @@ public class CopyTextBottomSheetFragment extends RoundedBottomSheetDialogFragmen
View rootView = inflater.inflate(R.layout.fragment_copy_text_bottom_sheet, container, false);
ButterKnife.bind(this, rootView);
- String rawText = getArguments().getString(EXTRA_RAW_TEXT);
- String markdownText = getArguments().getString(EXTRA_MARKDOWN).replaceAll("<sup>", "^").replaceAll("</sup>", "");
+ String rawText = getArguments().getString(EXTRA_RAW_TEXT, null);
+ markdownText = getArguments().getString(EXTRA_MARKDOWN, null);
- copyRawTextTextView.setOnClickListener(view -> {
- showCopyDialog(rawText);
- dismiss();
- });
+ if (rawText != null) {
+ copyRawTextTextView.setOnClickListener(view -> {
+ showCopyDialog(rawText);
+ dismiss();
+ });
- copyAllRawTextTextView.setOnClickListener(view -> {
- copyText(rawText);
- dismiss();
- });
+ copyAllRawTextTextView.setOnClickListener(view -> {
+ copyText(rawText);
+ dismiss();
+ });
+ } else {
+ copyRawTextTextView.setVisibility(View.GONE);
+ copyAllRawTextTextView.setVisibility(View.GONE);
+ }
if (markdownText != null) {
+ markdownText = markdownText.replaceAll("<sup>", "^").replaceAll("</sup>", "");
copyMarkdownTextView.setOnClickListener(view -> {
showCopyDialog(markdownText);
dismiss();
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/FlairBottomSheetFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/FlairBottomSheetFragment.java
index d8b39b7e..b7b651a6 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/FlairBottomSheetFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/FlairBottomSheetFragment.java
@@ -12,7 +12,6 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
@@ -87,7 +86,6 @@ public class FlairBottomSheetFragment extends BottomSheetDialogFragment {
dismiss();
});
- recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mAdapter);
mAccessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/PostTypeBottomSheetFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/PostTypeBottomSheetFragment.java
index 64b604ab..046c512b 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/PostTypeBottomSheetFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/PostTypeBottomSheetFragment.java
@@ -30,6 +30,7 @@ public class PostTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
public static final int TYPE_LINK = 1;
public static final int TYPE_IMAGE = 2;
public static final int TYPE_VIDEO = 3;
+ public static final int TYPE_GALLERY = 4;
@BindView(R.id.text_type_linear_layout_post_type_bottom_sheet_fragment)
TextView textTypeTextView;
@BindView(R.id.link_type_linear_layout_post_type_bottom_sheet_fragment)
@@ -38,6 +39,8 @@ public class PostTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
TextView imageTypeTextView;
@BindView(R.id.video_type_linear_layout_post_type_bottom_sheet_fragment)
TextView videoTypeTextView;
+ @BindView(R.id.gallery_type_linear_layout_post_type_bottom_sheet_fragment)
+ TextView galleryTypeTextView;
private Activity activity;
public PostTypeBottomSheetFragment() {
@@ -75,6 +78,11 @@ public class PostTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
dismiss();
});
+ galleryTypeTextView.setOnClickListener(view -> {
+ ((PostTypeSelectionCallback) activity).postTypeSelected(TYPE_GALLERY);
+ dismiss();
+ });
+
return rootView;
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/SelectOrCaptureImageBottomSheetFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/SelectOrCaptureImageBottomSheetFragment.java
new file mode 100644
index 00000000..4be9b51f
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/SelectOrCaptureImageBottomSheetFragment.java
@@ -0,0 +1,52 @@
+package ml.docilealligator.infinityforreddit.bottomsheetfragments;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+
+import com.deishelon.roundedbottomsheet.RoundedBottomSheetDialogFragment;
+
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.activities.PostGalleryActivity;
+
+public class SelectOrCaptureImageBottomSheetFragment extends RoundedBottomSheetDialogFragment {
+
+ private PostGalleryActivity mActivity;
+
+ public SelectOrCaptureImageBottomSheetFragment() {
+ // 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_select_or_capture_image_bottom_sheet, container, false);
+
+ TextView selectImageTextView = rootView.findViewById(R.id.select_image_text_view_select_or_capture_image_bottom_sheet_fragment);
+ TextView captureImageTextView = rootView.findViewById(R.id.capture_image_text_view_select_or_capture_image_bottom_sheet_fragment);
+
+ selectImageTextView.setOnClickListener(view -> {
+ mActivity.selectImage();
+ dismiss();
+ });
+
+ captureImageTextView.setOnClickListener(view -> {
+ mActivity.captureImage();
+ dismiss();
+ });
+
+ return rootView;
+ }
+
+ @Override
+ public void onAttach(@NonNull Context context) {
+ super.onAttach(context);
+ mActivity = (PostGalleryActivity) context;
+ }
+} \ No newline at end of file
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/UploadedImagesBottomSheetFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/UploadedImagesBottomSheetFragment.java
new file mode 100644
index 00000000..cc100c79
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/bottomsheetfragments/UploadedImagesBottomSheetFragment.java
@@ -0,0 +1,67 @@
+package ml.docilealligator.infinityforreddit.bottomsheetfragments;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.annotation.NonNull;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.deishelon.roundedbottomsheet.RoundedBottomSheetDialogFragment;
+import com.google.android.material.button.MaterialButton;
+
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.UploadImageEnabledActivity;
+import ml.docilealligator.infinityforreddit.adapters.UploadedImagesRecyclerViewAdapter;
+
+public class UploadedImagesBottomSheetFragment extends RoundedBottomSheetDialogFragment {
+
+ public static final String EXTRA_UPLOADED_IMAGES = "EUI";
+
+ private MaterialButton uploadButton;
+ private MaterialButton captureButton;
+ private RecyclerView uploadedImagesRecyclerView;
+ private UploadedImagesRecyclerViewAdapter adapter;
+ private UploadImageEnabledActivity activity;
+
+ public UploadedImagesBottomSheetFragment() {
+ // 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_uploaded_images_bottom_sheet, container, false);
+ uploadButton = rootView.findViewById(R.id.upload_button_uploaded_images_bottom_sheet_fragment);
+ captureButton = rootView.findViewById(R.id.capture_button_uploaded_images_bottom_sheet_fragment);
+
+ uploadButton.setOnClickListener(view -> {
+ activity.uploadImage();
+ dismiss();
+ });
+
+ captureButton.setOnClickListener(view -> {
+ activity.captureImage();
+ dismiss();
+ });
+
+ uploadedImagesRecyclerView = rootView.findViewById(R.id.recycler_view_uploaded_images_bottom_sheet);
+ adapter = new UploadedImagesRecyclerViewAdapter(
+ getArguments().getParcelableArrayList(EXTRA_UPLOADED_IMAGES), uploadedImage -> {
+ activity.insertImageUrl(uploadedImage);
+ dismiss();
+ });
+ uploadedImagesRecyclerView.setAdapter(adapter);
+
+ return rootView;
+ }
+
+ @Override
+ public void onAttach(@NonNull Context context) {
+ super.onAttach(context);
+ this.activity = (UploadImageEnabledActivity) context;
+ }
+} \ No newline at end of file
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/broadcastreceivers/WallpaperChangeReceiver.java b/app/src/main/java/ml/docilealligator/infinityforreddit/broadcastreceivers/WallpaperChangeReceiver.java
new file mode 100644
index 00000000..5a596308
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/broadcastreceivers/WallpaperChangeReceiver.java
@@ -0,0 +1,18 @@
+package ml.docilealligator.infinityforreddit.broadcastreceivers;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+import androidx.core.content.ContextCompat;
+
+import ml.docilealligator.infinityforreddit.services.MaterialYouService;
+
+public class WallpaperChangeReceiver extends BroadcastReceiver {
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Intent materialYouIntent = new Intent(context, MaterialYouService.class);
+ ContextCompat.startForegroundService(context, materialYouIntent);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/Comment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/Comment.java
index fcbd58c1..7cb0b695 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/Comment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/Comment.java
@@ -97,6 +97,7 @@ public class Comment implements Parcelable {
if (placeholderType == PLACEHOLDER_LOAD_MORE_COMMENTS) {
this.fullName = parentFullName;
} else {
+ this.fullName = parentFullName;
this.parentId = parentFullName.substring(3);
}
this.depth = depth;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/FetchComment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/FetchComment.java
index 14849870..6162865b 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/FetchComment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/FetchComment.java
@@ -1,10 +1,13 @@
package ml.docilealligator.infinityforreddit.comment;
+import android.os.Handler;
+
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Locale;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
@@ -14,7 +17,8 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchComment {
- public static void fetchComments(Retrofit retrofit, @Nullable String accessToken, String article,
+ public static void fetchComments(Executor executor, Handler handler, Retrofit retrofit,
+ @Nullable String accessToken, String article,
String commentId, String sortType, String contextNumber, boolean expandChildren,
Locale locale, FetchCommentListener fetchCommentListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
@@ -38,8 +42,8 @@ public class FetchComment {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- ParseComment.parseComment(response.body(), new ArrayList<>(),
- locale, expandChildren, new ParseComment.ParseCommentListener() {
+ ParseComment.parseComment(executor, handler, response.body(), new ArrayList<>(),
+ expandChildren, new ParseComment.ParseCommentListener() {
@Override
public void onParseCommentSuccess(ArrayList<Comment> expandedComments,
String parentId, ArrayList<String> moreChildrenFullnames) {
@@ -64,9 +68,10 @@ public class FetchComment {
});
}
- public static void fetchMoreComment(Retrofit retrofit, @Nullable String accessToken,
+ public static void fetchMoreComment(Executor executor, Handler handler, Retrofit retrofit,
+ @Nullable String accessToken,
ArrayList<String> allChildren, int startingIndex,
- int depth, boolean expandChildren, Locale locale,
+ int depth, boolean expandChildren,
FetchMoreCommentListener fetchMoreCommentListener) {
if (allChildren == null) {
return;
@@ -98,7 +103,7 @@ public class FetchComment {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- ParseComment.parseMoreComment(response.body(), new ArrayList<>(), locale,
+ ParseComment.parseMoreComment(executor, handler, response.body(), new ArrayList<>(),
depth, expandChildren, new ParseComment.ParseCommentListener() {
@Override
public void onParseCommentSuccess(ArrayList<Comment> expandedComments,
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/ParseComment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/ParseComment.java
index ace36940..62283989 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/ParseComment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/ParseComment.java
@@ -1,6 +1,6 @@
package ml.docilealligator.infinityforreddit.comment;
-import android.os.AsyncTask;
+import android.os.Handler;
import android.text.Html;
import androidx.annotation.Nullable;
@@ -10,7 +10,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
-import java.util.Locale;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
@@ -20,39 +20,83 @@ import static ml.docilealligator.infinityforreddit.comment.Comment.VOTE_TYPE_NO_
import static ml.docilealligator.infinityforreddit.comment.Comment.VOTE_TYPE_UPVOTE;
public class ParseComment {
- public static void parseComment(String response, ArrayList<Comment> commentData, Locale locale,
- boolean expandChildren, ParseCommentListener parseCommentListener) {
- try {
- JSONArray childrenArray = new JSONArray(response);
- String parentId = childrenArray.getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY)
- .getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.NAME_KEY);
- childrenArray = childrenArray.getJSONObject(1).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
+ public static void parseComment(Executor executor, Handler handler, String response,
+ ArrayList<Comment> commentData, boolean expandChildren,
+ ParseCommentListener parseCommentListener) {
+ executor.execute(() -> {
+ try {
+ JSONArray childrenArray = new JSONArray(response);
+ String parentId = childrenArray.getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY)
+ .getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.NAME_KEY);
+ childrenArray = childrenArray.getJSONObject(1).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
- new ParseCommentAsyncTask(childrenArray, commentData, locale, parentId, 0, expandChildren, parseCommentListener).execute();
- } catch (JSONException e) {
- e.printStackTrace();
- parseCommentListener.onParseCommentFailed();
- }
+ ArrayList<Comment> expandedNewComments = new ArrayList<>();
+ ArrayList<String> moreChildrenFullnames = new ArrayList<>();
+ ArrayList<Comment> newComments = new ArrayList<>();
+
+ parseCommentRecursion(childrenArray, newComments, moreChildrenFullnames, 0);
+ expandChildren(newComments, expandedNewComments, expandChildren);
+
+ if (expandChildren) {
+ commentData.addAll(expandedNewComments);
+ } else {
+ commentData.addAll(newComments);
+ }
+
+ handler.post(() -> parseCommentListener.onParseCommentSuccess(commentData, parentId, moreChildrenFullnames));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(parseCommentListener::onParseCommentFailed);
+ }
+ });
}
- static void parseMoreComment(String response, ArrayList<Comment> commentData, Locale locale,
- int depth, boolean expandChildren, ParseCommentListener parseCommentListener) {
- try {
- JSONArray childrenArray = new JSONObject(response).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
- new ParseCommentAsyncTask(childrenArray, commentData, locale, null, depth, expandChildren, parseCommentListener).execute();
- } catch (JSONException e) {
- e.printStackTrace();
- parseCommentListener.onParseCommentFailed();
- }
+ static void parseMoreComment(Executor executor, Handler handler, String response,
+ ArrayList<Comment> commentData, int depth, boolean expandChildren,
+ ParseCommentListener parseCommentListener) {
+ executor.execute(() -> {
+ try {
+ JSONArray childrenArray = new JSONObject(response).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
+
+ ArrayList<Comment> newComments = new ArrayList<>();
+ ArrayList<Comment> expandedNewComments = new ArrayList<>();
+ ArrayList<String> moreChildrenFullnames = new ArrayList<>();
+
+ parseCommentRecursion(childrenArray, newComments, moreChildrenFullnames, depth);
+ expandChildren(newComments, expandedNewComments, expandChildren);
+
+ if (expandChildren) {
+ commentData.addAll(expandedNewComments);
+ } else {
+ commentData.addAll(newComments);
+ }
+
+ handler.post(() -> parseCommentListener.onParseCommentSuccess(commentData, null, moreChildrenFullnames));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(parseCommentListener::onParseCommentFailed);
+ }
+ });
}
- static void parseSentComment(String response, int depth, Locale locale,
+ static void parseSentComment(Executor executor, Handler handler, String response, int depth,
ParseSentCommentListener parseSentCommentListener) {
- new ParseSentCommentAsyncTask(response, depth, locale, parseSentCommentListener).execute();
+ executor.execute(() -> {
+ try {
+ JSONObject sentCommentData = new JSONObject(response);
+ Comment comment = parseSingleComment(sentCommentData, depth);
+
+ handler.post(() -> parseSentCommentListener.onParseSentCommentSuccess(comment));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ String errorMessage = parseSentCommentErrorMessage(response);
+ handler.post(() -> parseSentCommentListener.onParseSentCommentFailed(errorMessage));
+ }
+ });
}
private static void parseCommentRecursion(JSONArray comments, ArrayList<Comment> newCommentData,
- ArrayList<String> moreChildrenFullnames, int depth, Locale locale) throws JSONException {
+ ArrayList<String> moreChildrenFullnames, int depth) throws JSONException {
int actualCommentLength;
if (comments.length() == 0) {
@@ -88,8 +132,7 @@ public class ParseComment {
.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
ArrayList<Comment> children = new ArrayList<>();
ArrayList<String> nextMoreChildrenFullnames = new ArrayList<>();
- parseCommentRecursion(childrenArray, children, nextMoreChildrenFullnames, singleComment.getDepth(),
- locale);
+ parseCommentRecursion(childrenArray, children, nextMoreChildrenFullnames, singleComment.getDepth());
singleComment.addChildren(children);
singleComment.setMoreChildrenFullnames(nextMoreChildrenFullnames);
}
@@ -230,101 +273,4 @@ public class ParseComment {
void onParseSentCommentFailed(@Nullable String errorMessage);
}
-
- private static class ParseCommentAsyncTask extends AsyncTask<Void, Void, Void> {
- private JSONArray commentsJSONArray;
- private ArrayList<Comment> comments;
- private ArrayList<Comment> newComments;
- private ArrayList<Comment> expandedNewComments;
- private ArrayList<String> moreChildrenFullnames;
- private Locale locale;
- private String parentId;
- private int depth;
- private boolean expandChildren;
- private ParseCommentListener parseCommentListener;
- private boolean parseFailed;
-
- ParseCommentAsyncTask(JSONArray commentsJSONArray, ArrayList<Comment> comments, Locale locale,
- @Nullable String parentId, int depth, boolean expandChildren,
- ParseCommentListener parseCommentListener) {
- this.commentsJSONArray = commentsJSONArray;
- this.comments = comments;
- newComments = new ArrayList<>();
- expandedNewComments = new ArrayList<>();
- moreChildrenFullnames = new ArrayList<>();
- this.locale = locale;
- this.parentId = parentId;
- this.depth = depth;
- this.expandChildren = expandChildren;
- parseFailed = false;
- this.parseCommentListener = parseCommentListener;
- }
-
- @Override
- protected Void doInBackground(Void... voids) {
- try {
- parseCommentRecursion(commentsJSONArray, newComments, moreChildrenFullnames, depth, locale);
- expandChildren(newComments, expandedNewComments, expandChildren);
- } catch (JSONException e) {
- parseFailed = true;
- e.printStackTrace();
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(Void aVoid) {
- if (!parseFailed) {
- if (expandChildren) {
- comments.addAll(expandedNewComments);
- } else {
- comments.addAll(newComments);
- }
- parseCommentListener.onParseCommentSuccess(comments, parentId, moreChildrenFullnames);
- } else {
- parseCommentListener.onParseCommentFailed();
- }
- }
- }
-
- private static class ParseSentCommentAsyncTask extends AsyncTask<Void, Void, Void> {
- private String response;
- private int depth;
- private Locale locale;
- private ParseSentCommentListener parseSentCommentListener;
- private boolean parseFailed;
- private String errorMessage;
- private Comment comment;
-
- ParseSentCommentAsyncTask(String response, int depth, Locale locale, ParseSentCommentListener parseSentCommentListener) {
- this.response = response;
- this.depth = depth;
- this.locale = locale;
- this.parseSentCommentListener = parseSentCommentListener;
- parseFailed = false;
- }
-
- @Override
- protected Void doInBackground(Void... voids) {
- try {
- JSONObject sentCommentData = new JSONObject(response);
- comment = parseSingleComment(sentCommentData, depth);
- } catch (JSONException e) {
- e.printStackTrace();
- errorMessage = parseSentCommentErrorMessage(response);
- parseFailed = true;
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(Void aVoid) {
- super.onPostExecute(aVoid);
- if (parseFailed) {
- parseSentCommentListener.onParseSentCommentFailed(errorMessage);
- } else {
- parseSentCommentListener.onParseSentCommentSuccess(comment);
- }
- }
- }
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/SendComment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/SendComment.java
index 114cc30e..cf9efa54 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/comment/SendComment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/comment/SendComment.java
@@ -1,11 +1,13 @@
package ml.docilealligator.infinityforreddit.comment;
+import android.os.Handler;
+
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashMap;
-import java.util.Locale;
import java.util.Map;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
@@ -15,9 +17,9 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class SendComment {
-
- public static void sendComment(String commentMarkdown, String thingFullname, int parentDepth,
- Locale locale, Retrofit oauthRetrofit, String accessToken,
+ public static void sendComment(Executor executor, Handler handler, String commentMarkdown,
+ String thingFullname, int parentDepth,
+ Retrofit oauthRetrofit, String accessToken,
SendCommentListener sendCommentListener) {
Map<String, String> headers = APIUtils.getOAuthHeader(accessToken);
Map<String, String> params = new HashMap<>();
@@ -30,7 +32,7 @@ public class SendComment {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- ParseComment.parseSentComment(response.body(), parentDepth, locale, new ParseComment.ParseSentCommentListener() {
+ ParseComment.parseSentComment(executor, handler, response.body(), parentDepth, new ParseComment.ParseSentCommentListener() {
@Override
public void onParseSentCommentSuccess(Comment comment) {
sendCommentListener.sendCommentSuccess(comment);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/customtheme/CustomThemeWrapper.java b/app/src/main/java/ml/docilealligator/infinityforreddit/customtheme/CustomThemeWrapper.java
index f5e9c6bd..a5753d53 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/customtheme/CustomThemeWrapper.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/customtheme/CustomThemeWrapper.java
@@ -54,22 +54,22 @@ public class CustomThemeWrapper {
public int getColorPrimary() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_PRIMARY,
- getDefaultColor("#1565C0", "#242424", "#000000"));
+ getDefaultColor("#0336FF", "#242424", "#000000"));
}
public int getColorPrimaryDark() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_PRIMARY_DARK,
- getDefaultColor("#0D47A1", "#121212", "#000000"));
+ getDefaultColor("#002BF0", "#121212", "#000000"));
}
public int getColorAccent() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_ACCENT,
- getDefaultColor("#FF4081", "#FF4081", "#FF4081"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getColorPrimaryLightTheme() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_PRIMARY_LIGHT_THEME,
- getDefaultColor("#1565C0", "#1565C0", "#1565C0"));
+ getDefaultColor("#0336FF", "#0336FF", "#0336FF"));
}
public int getPrimaryTextColor() {
@@ -179,17 +179,17 @@ public class CustomThemeWrapper {
public int getTabLayoutWithExpandedCollapsingToolbarTextColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.TAB_LAYOUT_WITH_EXPANDED_COLLAPSING_TOOLBAR_TEXT_COLOR,
- getDefaultColor("#1565C0", "#FFFFFF", "#FFFFFF"));
+ getDefaultColor("#0336FF", "#FFFFFF", "#FFFFFF"));
}
public int getTabLayoutWithExpandedCollapsingToolbarTabIndicator() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.TAB_LAYOUT_WITH_EXPANDED_COLLAPSING_TOOLBAR_TAB_INDICATOR,
- getDefaultColor("#1565C0", "#FFFFFF", "#FFFFFF"));
+ getDefaultColor("#0336FF", "#FFFFFF", "#FFFFFF"));
}
public int getTabLayoutWithCollapsedCollapsingToolbarTabBackground() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.TAB_LAYOUT_WITH_COLLAPSED_COLLAPSING_TOOLBAR_TAB_BACKGROUND,
- getDefaultColor("#1565C0", "#242424", "#000000"));
+ getDefaultColor("#0336FF", "#242424", "#000000"));
}
public int getTabLayoutWithCollapsedCollapsingToolbarTextColor() {
@@ -204,7 +204,7 @@ public class CustomThemeWrapper {
public int getUpvoted() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.UPVOTED,
- getDefaultColor("#E91E63", "#E91E63", "#E91E63"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getDownvoted() {
@@ -214,7 +214,7 @@ public class CustomThemeWrapper {
public int getPostTypeBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.POST_TYPE_BACKGROUND_COLOR,
- getDefaultColor("#0D47A1", "#1565C0", "#1565C0"));
+ getDefaultColor("#002BF0", "#0336FF", "#0336FF"));
}
public int getPostTypeTextColor() {
@@ -234,7 +234,7 @@ public class CustomThemeWrapper {
public int getNsfwBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.NSFW_BACKGROUND_COLOR,
- getDefaultColor("#FF4081", "#FF4081", "#FF4081"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getNsfwTextColor() {
@@ -274,7 +274,7 @@ public class CustomThemeWrapper {
public int getCrosspostIconTint() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.CROSSPOST_ICON_TINT,
- getDefaultColor("#FF4081", "#FF4081", "#FF4081"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getUpvoteRatioIconTint() {
@@ -284,7 +284,7 @@ public class CustomThemeWrapper {
public int getStickiedPostIconTint() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.STICKIED_POST_ICON_TINT,
- getDefaultColor("#0D47A1", "#1565C0", "#1565C0"));
+ getDefaultColor("#002BF0", "#0336FF", "#0336FF"));
}
public int getNoPreviewPostTypeIconTint() {
@@ -294,22 +294,22 @@ public class CustomThemeWrapper {
public int getSubscribed() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.SUBSCRIBED,
- getDefaultColor("#FF4081", "#FF4081", "#FF4081"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getUnsubscribed() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.UNSUBSCRIBED,
- getDefaultColor("#0D47A1", "#1565C0", "#1565C0"));
+ getDefaultColor("#002BF0", "#0336FF", "#0336FF"));
}
public int getUsername() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.USERNAME,
- getDefaultColor("#0D47A1", "#1E88E5", "#1E88E5"));
+ getDefaultColor("#002BF0", "#1E88E5", "#1E88E5"));
}
public int getSubreddit() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.SUBREDDIT,
- getDefaultColor("#E91E63", "#E91E63", "#E91E63"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getAuthorFlairTextColor() {
@@ -359,7 +359,7 @@ public class CustomThemeWrapper {
public Integer getCommentVerticalBarColor1() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_1,
- getDefaultColor("#1565C0", "#1565C0", "#1565C0"));
+ getDefaultColor("#0336FF", "#0336FF", "#0336FF"));
}
public Integer getCommentVerticalBarColor2() {
@@ -404,7 +404,7 @@ public class CustomThemeWrapper {
public int getLinkColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.LINK_COLOR,
- getDefaultColor("#FF4081", "#FF4081", "#FF4081"));
+ getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
}
public int getReceivedMessageTextColor() {
@@ -509,10 +509,10 @@ public class CustomThemeWrapper {
customTheme.isLightTheme = true;
customTheme.isDarkTheme = false;
customTheme.isAmoledTheme = false;
- customTheme.colorPrimary = Color.parseColor("#1565C0");
- customTheme.colorPrimaryDark = Color.parseColor("#0D47A1");
- customTheme.colorAccent = Color.parseColor("#FF4081");
- customTheme.colorPrimaryLightTheme = Color.parseColor("#1565C0");
+ customTheme.colorPrimary = Color.parseColor("#0336FF");
+ customTheme.colorPrimaryDark = Color.parseColor("#002BF0");
+ customTheme.colorAccent = Color.parseColor("#FF1868");
+ customTheme.colorPrimaryLightTheme = Color.parseColor("#0336FF");
customTheme.primaryTextColor = Color.parseColor("#000000");
customTheme.secondaryTextColor = Color.parseColor("#8A000000");
customTheme.postTitleColor = Color.parseColor("#000000");
@@ -534,18 +534,18 @@ public class CustomThemeWrapper {
customTheme.toolbarSecondaryTextColor = Color.parseColor("#FFFFFF");
customTheme.circularProgressBarBackground = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithExpandedCollapsingToolbarTabBackground = Color.parseColor("#FFFFFF");
- customTheme.tabLayoutWithExpandedCollapsingToolbarTextColor = Color.parseColor("#1565C0");
- customTheme.tabLayoutWithExpandedCollapsingToolbarTabIndicator = Color.parseColor("#1565C0");
- customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#1565C0");
+ customTheme.tabLayoutWithExpandedCollapsingToolbarTextColor = Color.parseColor("#0336FF");
+ customTheme.tabLayoutWithExpandedCollapsingToolbarTabIndicator = Color.parseColor("#0336FF");
+ customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#0336FF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#0D47A1");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#002BF0");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -553,14 +553,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#0D47A1");
+ customTheme.stickiedPostIconTint = Color.parseColor("#002BF0");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#0D47A1");
- customTheme.username = Color.parseColor("#0D47A1");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#002BF0");
+ customTheme.username = Color.parseColor("#002BF0");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -570,7 +570,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#E0E0E0");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#E0E0E0");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#F0F0F0");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#EE02BE");
customTheme.commentVerticalBarColor3 = Color.parseColor("#02DFEE");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EED502");
@@ -579,7 +579,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -602,8 +602,8 @@ public class CustomThemeWrapper {
customTheme.isAmoledTheme = false;
customTheme.colorPrimary = Color.parseColor("#242424");
customTheme.colorPrimaryDark = Color.parseColor("#121212");
- customTheme.colorAccent = Color.parseColor("#FF4081");
- customTheme.colorPrimaryLightTheme = Color.parseColor("#1565C0");
+ customTheme.colorAccent = Color.parseColor("#FF1868");
+ customTheme.colorPrimaryLightTheme = Color.parseColor("#0336FF");
customTheme.primaryTextColor = Color.parseColor("#FFFFFF");
customTheme.secondaryTextColor = Color.parseColor("#B3FFFFFF");
customTheme.postTitleColor = Color.parseColor("#FFFFFF");
@@ -630,13 +630,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#242424");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -644,14 +644,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#1565C0");
+ customTheme.stickiedPostIconTint = Color.parseColor("#0336FF");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#1565C0");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#0336FF");
customTheme.username = Color.parseColor("#1E88E5");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -661,7 +661,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#69666C");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#424242");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#3C3C3C");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#C300B3");
customTheme.commentVerticalBarColor3 = Color.parseColor("#00B8DA");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EDCA00");
@@ -670,7 +670,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -693,8 +693,8 @@ public class CustomThemeWrapper {
customTheme.isAmoledTheme = true;
customTheme.colorPrimary = Color.parseColor("#000000");
customTheme.colorPrimaryDark = Color.parseColor("#000000");
- customTheme.colorAccent = Color.parseColor("#FF4081");
- customTheme.colorPrimaryLightTheme = Color.parseColor("#1565C0");
+ customTheme.colorAccent = Color.parseColor("#FF1868");
+ customTheme.colorPrimaryLightTheme = Color.parseColor("#0336FF");
customTheme.primaryTextColor = Color.parseColor("#FFFFFF");
customTheme.secondaryTextColor = Color.parseColor("#B3FFFFFF");
customTheme.postTitleColor = Color.parseColor("#FFFFFF");
@@ -721,13 +721,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#000000");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -735,14 +735,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#1565C0");
+ customTheme.stickiedPostIconTint = Color.parseColor("#0336FF");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#1565C0");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#0336FF");
customTheme.username = Color.parseColor("#1E88E5");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -752,7 +752,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#69666C");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#424242");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#3C3C3C");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#C300B3");
customTheme.commentVerticalBarColor3 = Color.parseColor("#00B8DA");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EDCA00");
@@ -761,7 +761,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -812,13 +812,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#3C4043");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#3C4043");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#0D47A1");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#002BF0");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -826,14 +826,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#0D47A1");
+ customTheme.stickiedPostIconTint = Color.parseColor("#002BF0");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#FFFFFF");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#0D47A1");
- customTheme.username = Color.parseColor("#0D47A1");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#002BF0");
+ customTheme.username = Color.parseColor("#002BF0");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -843,7 +843,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#E0E0E0");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#000000");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#F0F0F0");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#EE02BE");
customTheme.commentVerticalBarColor3 = Color.parseColor("#02DFEE");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EED502");
@@ -852,7 +852,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#000000");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -903,13 +903,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#242424");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -917,14 +917,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#1565C0");
+ customTheme.stickiedPostIconTint = Color.parseColor("#0336FF");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#FFFFFF");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#1565C0");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#0336FF");
customTheme.username = Color.parseColor("#1E88E5");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -934,7 +934,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#69666C");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#000000");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#3C3C3C");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#C300B3");
customTheme.commentVerticalBarColor3 = Color.parseColor("#00B8DA");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EDCA00");
@@ -943,7 +943,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -994,13 +994,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#000000");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -1008,14 +1008,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#1565C0");
+ customTheme.stickiedPostIconTint = Color.parseColor("#0336FF");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#FFFFFF");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#1565C0");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#0336FF");
customTheme.username = Color.parseColor("#1E88E5");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -1025,7 +1025,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#69666C");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#000000");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#3C3C3C");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#C300B3");
customTheme.commentVerticalBarColor3 = Color.parseColor("#00B8DA");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EDCA00");
@@ -1034,7 +1034,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -1085,13 +1085,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#EE0270");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#0D47A1");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#002BF0");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -1099,14 +1099,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#0D47A1");
+ customTheme.stickiedPostIconTint = Color.parseColor("#002BF0");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#0D47A1");
- customTheme.username = Color.parseColor("#0D47A1");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#002BF0");
+ customTheme.username = Color.parseColor("#002BF0");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -1116,7 +1116,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#E0E0E0");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#E0E0E0");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#F0F0F0");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#EE02BE");
customTheme.commentVerticalBarColor3 = Color.parseColor("#02DFEE");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EED502");
@@ -1125,7 +1125,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -1176,13 +1176,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#242424");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -1190,14 +1190,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#1565C0");
+ customTheme.stickiedPostIconTint = Color.parseColor("#0336FF");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#1565C0");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#0336FF");
customTheme.username = Color.parseColor("#1E88E5");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -1207,7 +1207,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#69666C");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#424242");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#3C3C3C");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#C300B3");
customTheme.commentVerticalBarColor3 = Color.parseColor("#00B8DA");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EDCA00");
@@ -1216,7 +1216,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -1267,13 +1267,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#000000");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#FFFFFF");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -1281,14 +1281,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#1565C0");
+ customTheme.stickiedPostIconTint = Color.parseColor("#0336FF");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#1565C0");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#0336FF");
customTheme.username = Color.parseColor("#1E88E5");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -1298,7 +1298,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#69666C");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#424242");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#3C3C3C");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#C300B3");
customTheme.commentVerticalBarColor3 = Color.parseColor("#00B8DA");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EDCA00");
@@ -1307,7 +1307,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -1360,11 +1360,11 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#FFFFFF");
customTheme.upvoted = Color.parseColor("#FF008C");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#1565C0");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#0336FF");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -1372,12 +1372,12 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
customTheme.stickiedPostIconTint = Color.parseColor("#02ABEE");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#FFFFFF");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#0D47A1");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#002BF0");
customTheme.username = Color.parseColor("#1E88E5");
customTheme.subreddit = Color.parseColor("#FF4B9C");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
@@ -1398,7 +1398,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#F1FA8C");
customTheme.fabIconColor = Color.parseColor("#FFFFFF");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
@@ -1449,13 +1449,13 @@ public class CustomThemeWrapper {
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = Color.parseColor("#D48AE0");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = Color.parseColor("#3C4043");
customTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = Color.parseColor("#3C4043");
- customTheme.upvoted = Color.parseColor("#E91E63");
+ customTheme.upvoted = Color.parseColor("#FF1868");
customTheme.downvoted = Color.parseColor("#007DDE");
- customTheme.postTypeBackgroundColor = Color.parseColor("#0D47A1");
+ customTheme.postTypeBackgroundColor = Color.parseColor("#002BF0");
customTheme.postTypeTextColor = Color.parseColor("#FFFFFF");
customTheme.spoilerBackgroundColor = Color.parseColor("#EE02EB");
customTheme.spoilerTextColor = Color.parseColor("#FFFFFF");
- customTheme.nsfwBackgroundColor = Color.parseColor("#FF4081");
+ customTheme.nsfwBackgroundColor = Color.parseColor("#FF1868");
customTheme.nsfwTextColor = Color.parseColor("#FFFFFF");
customTheme.flairBackgroundColor = Color.parseColor("#00AA8C");
customTheme.flairTextColor = Color.parseColor("#FFFFFF");
@@ -1463,14 +1463,14 @@ public class CustomThemeWrapper {
customTheme.awardsTextColor = Color.parseColor("#FFFFFF");
customTheme.archivedTint = Color.parseColor("#B4009F");
customTheme.lockedIconTint = Color.parseColor("#EE7302");
- customTheme.crosspostIconTint = Color.parseColor("#FF4081");
+ customTheme.crosspostIconTint = Color.parseColor("#FF1868");
customTheme.upvoteRatioIconTint = Color.parseColor("#0256EE");
- customTheme.stickiedPostIconTint = Color.parseColor("#0D47A1");
+ customTheme.stickiedPostIconTint = Color.parseColor("#002BF0");
customTheme.noPreviewPostTypeIconTint = Color.parseColor("#808080");
- customTheme.subscribed = Color.parseColor("#FF4081");
- customTheme.unsubscribed = Color.parseColor("#0D47A1");
- customTheme.username = Color.parseColor("#0D47A1");
- customTheme.subreddit = Color.parseColor("#E91E63");
+ customTheme.subscribed = Color.parseColor("#FF1868");
+ customTheme.unsubscribed = Color.parseColor("#002BF0");
+ customTheme.username = Color.parseColor("#002BF0");
+ customTheme.subreddit = Color.parseColor("#FF1868");
customTheme.authorFlairTextColor = Color.parseColor("#EE02C4");
customTheme.submitter = Color.parseColor("#EE8A02");
customTheme.moderator = Color.parseColor("#00BA81");
@@ -1480,7 +1480,7 @@ public class CustomThemeWrapper {
customTheme.dividerColor = Color.parseColor("#E0E0E0");
customTheme.noPreviewPostTypeBackgroundColor = Color.parseColor("#E0E0E0");
customTheme.voteAndReplyUnavailableButtonColor = Color.parseColor("#F0F0F0");
- customTheme.commentVerticalBarColor1 = Color.parseColor("#1565C0");
+ customTheme.commentVerticalBarColor1 = Color.parseColor("#0336FF");
customTheme.commentVerticalBarColor2 = Color.parseColor("#EE02BE");
customTheme.commentVerticalBarColor3 = Color.parseColor("#02DFEE");
customTheme.commentVerticalBarColor4 = Color.parseColor("#EED502");
@@ -1489,7 +1489,7 @@ public class CustomThemeWrapper {
customTheme.commentVerticalBarColor7 = Color.parseColor("#EE4602");
customTheme.fabIconColor = Color.parseColor("#000000");
customTheme.chipTextColor = Color.parseColor("#FFFFFF");
- customTheme.linkColor = Color.parseColor("#FF4081");
+ customTheme.linkColor = Color.parseColor("#FF1868");
customTheme.receivedMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.sentMessageTextColor = Color.parseColor("#FFFFFF");
customTheme.receivedMessageBackgroundColor = Color.parseColor("#4185F4");
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ClickableMotionLayout.java b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ClickableMotionLayout.java
new file mode 100644
index 00000000..8c0f47ff
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ClickableMotionLayout.java
@@ -0,0 +1,39 @@
+package ml.docilealligator.infinityforreddit.customviews;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+import android.view.ViewConfiguration;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.constraintlayout.motion.widget.MotionLayout;
+
+public class ClickableMotionLayout extends MotionLayout {
+ private long mStartTime = 0;
+
+ public ClickableMotionLayout(@NonNull Context context) {
+ super(context);
+ }
+
+ public ClickableMotionLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public ClickableMotionLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent event) {
+ if ( event.getAction() == MotionEvent.ACTION_DOWN ) {
+ mStartTime = event.getEventTime();
+ } else if ( event.getAction() == MotionEvent.ACTION_UP ) {
+ if ( event.getEventTime() - mStartTime <= ViewConfiguration.getTapTimeout() ) {
+ return false;
+ }
+ }
+
+ return super.onInterceptTouchEvent(event);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/CommentIndentationView.java b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/CommentIndentationView.java
index fc9dba03..27e1e142 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/CommentIndentationView.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/CommentIndentationView.java
@@ -21,7 +21,8 @@ public class CommentIndentationView extends LinearLayout {
private Integer[] colors;
private ArrayList<Integer> startXs;
private final int spacing;
- private final int pathWidth;
+ private int pathWidth;
+ private boolean showOnlyOneDivider = false;
public CommentIndentationView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
@@ -49,9 +50,16 @@ public class CommentIndentationView extends LinearLayout {
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
- for (int i = 0; i < startXs.size(); i++) {
- paint.setColor(colors[i % 7]);
- canvas.drawLine(startXs.get(i), 0, startXs.get(i), getHeight(), paint);
+ if (showOnlyOneDivider) {
+ if (startXs.size() > 0) {
+ paint.setColor(colors[(startXs.size() - 1) % 7]);
+ canvas.drawLine(level * pathWidth, 0, level * pathWidth, getHeight(), paint);
+ }
+ } else {
+ for (int i = 0; i < startXs.size(); i++) {
+ paint.setColor(colors[i % 7]);
+ canvas.drawLine(startXs.get(i), 0, startXs.get(i), getHeight(), paint);
+ }
}
}
@@ -81,7 +89,7 @@ public class CommentIndentationView extends LinearLayout {
this.colors = colors;
this.level = level;
if (level > 0) {
- int indentationSpacing = level * spacing + pathWidth;
+ int indentationSpacing = showOnlyOneDivider ? pathWidth * level : level * spacing + pathWidth;
setPaddingRelative(indentationSpacing, 0, pathWidth, 0);
} else {
setPaddingRelative(0, 0, 0, 0);
@@ -89,6 +97,13 @@ public class CommentIndentationView extends LinearLayout {
invalidate();
}
+ public void setShowOnlyOneDivider(boolean showOnlyOneDivider) {
+ this.showOnlyOneDivider = showOnlyOneDivider;
+ if (showOnlyOneDivider) {
+ pathWidth = (int) Utils.convertDpToPixel(4, getContext());
+ }
+ }
+
private static class SavedState extends BaseSavedState {
ArrayList<Integer> startXs;
Integer[] colors;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/LinearLayoutManagerBugFixed.java b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/LinearLayoutManagerBugFixed.java
new file mode 100644
index 00000000..e2264225
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/LinearLayoutManagerBugFixed.java
@@ -0,0 +1,25 @@
+package ml.docilealligator.infinityforreddit.customviews;
+
+import android.content.Context;
+import android.util.AttributeSet;
+
+import androidx.recyclerview.widget.LinearLayoutManager;
+
+public class LinearLayoutManagerBugFixed extends LinearLayoutManager {
+ public LinearLayoutManagerBugFixed(Context context) {
+ super(context);
+ }
+
+ public LinearLayoutManagerBugFixed(Context context, int orientation, boolean reverseLayout) {
+ super(context, orientation, reverseLayout);
+ }
+
+ public LinearLayoutManagerBugFixed(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
+ super(context, attrs, defStyleAttr, defStyleRes);
+ }
+
+ @Override
+ public boolean supportsPredictiveItemAnimations() {
+ return false;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/MarkwonLinearLayoutManager.java b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/MarkwonLinearLayoutManager.java
index a654b437..35923fa6 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/MarkwonLinearLayoutManager.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/MarkwonLinearLayoutManager.java
@@ -5,9 +5,7 @@ import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.HorizontalScrollView;
-import androidx.recyclerview.widget.LinearLayoutManager;
-
-public class MarkwonLinearLayoutManager extends LinearLayoutManager {
+public class MarkwonLinearLayoutManager extends LinearLayoutManagerBugFixed {
public interface HorizontalScrollViewScrolledListener {
void onScrolledLeft();
void onScrolledRight();
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ViewPagerBugFixed.java b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ViewPagerBugFixed.java
new file mode 100644
index 00000000..78e7b88e
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/customviews/ViewPagerBugFixed.java
@@ -0,0 +1,37 @@
+package ml.docilealligator.infinityforreddit.customviews;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.viewpager.widget.ViewPager;
+
+public class ViewPagerBugFixed extends ViewPager {
+ public ViewPagerBugFixed(@NonNull Context context) {
+ super(context);
+ }
+
+ public ViewPagerBugFixed(@NonNull Context context, @Nullable AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent ev) {
+ try {
+ return super.onTouchEvent(ev);
+ } catch (IllegalArgumentException ignore) {}
+
+ return false;
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ try {
+ return super.onInterceptTouchEvent(ev);
+ } catch (IllegalArgumentException ignore) {}
+
+ return false;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeDefaultLinkPostLayoutEvent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeDefaultLinkPostLayoutEvent.java
new file mode 100644
index 00000000..d7897beb
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeDefaultLinkPostLayoutEvent.java
@@ -0,0 +1,9 @@
+package ml.docilealligator.infinityforreddit.events;
+
+public class ChangeDefaultLinkPostLayoutEvent {
+ public int defaultLinkPostLayout;
+
+ public ChangeDefaultLinkPostLayoutEvent(int defaultLinkPostLayout) {
+ this.defaultLinkPostLayout = defaultLinkPostLayout;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeHidePostFlairEvent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeHidePostFlairEvent.java
new file mode 100644
index 00000000..f3a9a7a4
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeHidePostFlairEvent.java
@@ -0,0 +1,9 @@
+package ml.docilealligator.infinityforreddit.events;
+
+public class ChangeHidePostFlairEvent {
+ public boolean hidePostFlair;
+
+ public ChangeHidePostFlairEvent(boolean hidePostFlair) {
+ this.hidePostFlair = hidePostFlair;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeRememberMutingOptionInPostFeedEvent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeRememberMutingOptionInPostFeedEvent.java
new file mode 100644
index 00000000..d49d5939
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ChangeRememberMutingOptionInPostFeedEvent.java
@@ -0,0 +1,9 @@
+package ml.docilealligator.infinityforreddit.events;
+
+public class ChangeRememberMutingOptionInPostFeedEvent {
+ public boolean rememberMutingOptionInPostFeedEvent;
+
+ public ChangeRememberMutingOptionInPostFeedEvent(boolean rememberMutingOptionInPostFeedEvent) {
+ this.rememberMutingOptionInPostFeedEvent = rememberMutingOptionInPostFeedEvent;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/events/SubmitGalleryPostEvent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/events/SubmitGalleryPostEvent.java
new file mode 100644
index 00000000..fcab85cd
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/events/SubmitGalleryPostEvent.java
@@ -0,0 +1,13 @@
+package ml.docilealligator.infinityforreddit.events;
+
+public class SubmitGalleryPostEvent {
+ public boolean postSuccess;
+ public String postUrl;
+ public String errorMessage;
+
+ public SubmitGalleryPostEvent(boolean postSuccess, String postUrl, String errorMessage) {
+ this.postSuccess = postSuccess;
+ this.postUrl = postUrl;
+ this.errorMessage = errorMessage;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/events/ToggleSecureModeEvent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ToggleSecureModeEvent.java
new file mode 100644
index 00000000..a7c27eb3
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/events/ToggleSecureModeEvent.java
@@ -0,0 +1,9 @@
+package ml.docilealligator.infinityforreddit.events;
+
+public class ToggleSecureModeEvent {
+ public boolean isSecureMode;
+
+ public ToggleSecureModeEvent(boolean isSecureMode) {
+ this.isSecureMode = isSecureMode;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/CommentsListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/CommentsListingFragment.java
index c730b4ba..04cabb7a 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/CommentsListingFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/CommentsListingFragment.java
@@ -25,7 +25,6 @@ import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -50,6 +49,7 @@ import ml.docilealligator.infinityforreddit.activities.BaseActivity;
import ml.docilealligator.infinityforreddit.adapters.CommentsListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.comment.CommentViewModel;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import retrofit2.Retrofit;
@@ -105,7 +105,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
private String mAccessToken;
private RequestManager mGlide;
private AppCompatActivity mActivity;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private CommentsListingRecyclerViewAdapter mAdapter;
private SortType sortType;
private ColorDrawable backgroundSwipeRight;
@@ -255,7 +255,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
private void bindView(Resources resources) {
if (mActivity != null && !mActivity.isFinishing() && !mActivity.isDestroyed()) {
- mLinearLayoutManager = new LinearLayoutManager(mActivity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mCommentRecyclerView.setLayoutManager(mLinearLayoutManager);
mAdapter = new CommentsListingRecyclerViewAdapter(mActivity, mOauthRetrofit, customThemeWrapper,
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 38726cd8..1fda28d4 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/FollowedUsersListingFragment.java
@@ -17,7 +17,6 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -40,6 +39,7 @@ 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.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
@@ -78,7 +78,7 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo
SubscribedUserViewModel mSubscribedUserViewModel;
private Activity mActivity;
private RequestManager mGlide;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
public FollowedUsersListingFragment() {
// Required empty public constructor
@@ -109,7 +109,7 @@ public class FollowedUsersListingFragment extends Fragment implements FragmentCo
mGlide = Glide.with(this);
- mLinearLayoutManager = new LinearLayoutManager(mActivity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
FollowedUsersRecyclerViewAdapter adapter = new FollowedUsersRecyclerViewAdapter(mActivity,
mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper,
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/InboxFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/InboxFragment.java
index b9879c3e..567f3a1b 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/InboxFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/InboxFragment.java
@@ -14,7 +14,6 @@ import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -38,6 +37,7 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.activities.BaseActivity;
import ml.docilealligator.infinityforreddit.adapters.MessageRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.RepliedToPrivateMessageEvent;
import ml.docilealligator.infinityforreddit.message.FetchMessage;
import ml.docilealligator.infinityforreddit.message.MessageViewModel;
@@ -72,7 +72,7 @@ public class InboxFragment extends Fragment implements FragmentCommunicator {
private String mWhere;
private MessageRecyclerViewAdapter mAdapter;
private RequestManager mGlide;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private BaseActivity mActivity;
public InboxFragment() {
@@ -106,7 +106,7 @@ public class InboxFragment extends Fragment implements FragmentCommunicator {
mWhere = arguments.getString(EXTRA_MESSAGE_WHERE, FetchMessage.WHERE_INBOX);
mAdapter = new MessageRecyclerViewAdapter(mActivity, mOauthRetrofit, mCustomThemeWrapper,
mAccessToken, mWhere, () -> mMessageViewModel.retryLoadingMore());
- mLinearLayoutManager = new LinearLayoutManager(mActivity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mActivity, mLinearLayoutManager.getOrientation());
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 fc0723eb..0f80d47a 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/MultiRedditListingFragment.java
@@ -17,7 +17,6 @@ import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -43,6 +42,7 @@ import ml.docilealligator.infinityforreddit.activities.ViewMultiRedditDetailActi
import ml.docilealligator.infinityforreddit.adapters.MultiRedditListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.MultiRedditOptionsBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.multireddit.MultiReddit;
import ml.docilealligator.infinityforreddit.multireddit.MultiRedditViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
@@ -80,7 +80,7 @@ public class MultiRedditListingFragment extends Fragment implements FragmentComm
public MultiRedditViewModel mMultiRedditViewModel;
private AppCompatActivity mActivity;
private RequestManager mGlide;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
public MultiRedditListingFragment() {
// Required empty public constructor
@@ -114,7 +114,7 @@ public class MultiRedditListingFragment extends Fragment implements FragmentComm
mGlide = Glide.with(this);
- mLinearLayoutManager = new LinearLayoutManager(mActivity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
MultiRedditListingRecyclerViewAdapter adapter = new MultiRedditListingRecyclerViewAdapter(mActivity,
mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, accessToken,
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 7110e057..c98f27e6 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/PostFragment.java
@@ -1,6 +1,9 @@
package ml.docilealligator.infinityforreddit.fragments;
+import static im.ene.toro.media.PlaybackInfo.INDEX_UNSET;
+import static im.ene.toro.media.PlaybackInfo.TIME_UNSET;
+
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
@@ -29,14 +32,13 @@ import android.widget.Toast;
import androidx.annotation.DimenRes;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
-import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.ItemTouchHelper;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
@@ -79,12 +81,15 @@ import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivi
import ml.docilealligator.infinityforreddit.adapters.PostRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.customviews.CustomToroContainer;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.ChangeAutoplayNsfwVideosEvent;
import ml.docilealligator.infinityforreddit.events.ChangeCompactLayoutToolbarHiddenByDefaultEvent;
import ml.docilealligator.infinityforreddit.events.ChangeDataSavingModeEvent;
+import ml.docilealligator.infinityforreddit.events.ChangeDefaultLinkPostLayoutEvent;
import ml.docilealligator.infinityforreddit.events.ChangeDefaultPostLayoutEvent;
import ml.docilealligator.infinityforreddit.events.ChangeDisableImagePreviewEvent;
import ml.docilealligator.infinityforreddit.events.ChangeEnableSwipeActionSwitchEvent;
+import ml.docilealligator.infinityforreddit.events.ChangeHidePostFlairEvent;
import ml.docilealligator.infinityforreddit.events.ChangeHidePostTypeEvent;
import ml.docilealligator.infinityforreddit.events.ChangeHideSubredditAndUserPrefixEvent;
import ml.docilealligator.infinityforreddit.events.ChangeHideTheNumberOfAwardsEvent;
@@ -97,6 +102,7 @@ import ml.docilealligator.infinityforreddit.events.ChangeNSFWBlurEvent;
import ml.docilealligator.infinityforreddit.events.ChangeNetworkStatusEvent;
import ml.docilealligator.infinityforreddit.events.ChangeOnlyDisablePreviewInVideoAndGifPostsEvent;
import ml.docilealligator.infinityforreddit.events.ChangePostLayoutEvent;
+import ml.docilealligator.infinityforreddit.events.ChangeRememberMutingOptionInPostFeedEvent;
import ml.docilealligator.infinityforreddit.events.ChangeSavePostFeedScrolledPositionEvent;
import ml.docilealligator.infinityforreddit.events.ChangeShowAbsoluteNumberOfVotesEvent;
import ml.docilealligator.infinityforreddit.events.ChangeShowElapsedTimeEvent;
@@ -123,9 +129,6 @@ import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import retrofit2.Retrofit;
-import static im.ene.toro.media.PlaybackInfo.INDEX_UNSET;
-import static im.ene.toro.media.PlaybackInfo.TIME_UNSET;
-
/**
* A simple {@link Fragment} subclass.
@@ -136,6 +139,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
public static final String EXTRA_USER_NAME = "EUN";
public static final String EXTRA_USER_WHERE = "EUW";
public static final String EXTRA_QUERY = "EQ";
+ public static final String EXTRA_TRENDING_SOURCE = "ETS";
public static final String EXTRA_POST_TYPE = "EPT";
public static final String EXTRA_FILTER = "EF";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
@@ -201,7 +205,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
Executor mExecutor;
private RequestManager mGlide;
private AppCompatActivity activity;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private StaggeredGridLayoutManager mStaggeredGridLayoutManager;
private long postFragmentId;
private int postType;
@@ -210,6 +214,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private boolean hasPost = false;
private boolean isShown = false;
private boolean savePostFeedScrolledPosition;
+ private boolean rememberMutingOptionInPostFeed;
+ private Boolean masterMutingOption;
private PostRecyclerViewAdapter mAdapter;
private RecyclerView.SmoothScroller smoothScroller;
private Window window;
@@ -221,6 +227,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private String subredditName;
private String username;
private String query;
+ private String trendingSource;
private String where;
private String multiRedditPath;
private String concatenatedSubredditNames;
@@ -373,12 +380,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mSwipeRefreshLayout.setEnabled(mSharedPreferences.getBoolean(SharedPreferencesUtils.PULL_TO_REFRESH, true));
mSwipeRefreshLayout.setOnRefreshListener(this::refresh);
+ int recyclerViewPosition = 0;
int hideReadPostsIndex = 0;
if (savedInstanceState != null) {
- int recyclerViewPosition = savedInstanceState.getInt(RECYCLER_VIEW_POSITION_STATE);
- if (recyclerViewPosition > 0) {
- mPostRecyclerView.scrollToPosition(recyclerViewPosition);
- }
+ recyclerViewPosition = savedInstanceState.getInt(RECYCLER_VIEW_POSITION_STATE);
isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE);
readPosts = savedInstanceState.getParcelableArrayList(READ_POST_LIST_STATE);
@@ -417,6 +422,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
accountName = getArguments().getString(EXTRA_ACCOUNT_NAME);
int defaultPostLayout = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.DEFAULT_POST_LAYOUT_KEY, "0"));
savePostFeedScrolledPosition = mSharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_FRONT_PAGE_SCROLLED_POSITION, false);
+ rememberMutingOptionInPostFeed = mSharedPreferences.getBoolean(SharedPreferencesUtils.REMEMBER_MUTING_OPTION_IN_POST_FEED, false);
Locale locale = getResources().getConfiguration().locale;
int usage;
@@ -425,6 +431,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
if (postType == PostDataSource.TYPE_SEARCH) {
subredditName = getArguments().getString(EXTRA_NAME);
query = getArguments().getString(EXTRA_QUERY);
+ trendingSource = getArguments().getString(EXTRA_TRENDING_SOURCE);
if (savedInstanceState == null) {
postFragmentId += query.hashCode();
}
@@ -452,6 +459,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
Intent intent = new Intent(activity, FilteredPostsActivity.class);
intent.putExtra(FilteredPostsActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredPostsActivity.EXTRA_QUERY, query);
+ intent.putExtra(FilteredPostsActivity.EXTRA_TRENDING_SOURCE, trendingSource);
intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredPostsActivity.EXTRA_FILTER, filter);
startActivity(intent);
@@ -462,6 +470,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
Intent intent = new Intent(activity, FilteredPostsActivity.class);
intent.putExtra(FilteredPostsActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredPostsActivity.EXTRA_QUERY, query);
+ intent.putExtra(FilteredPostsActivity.EXTRA_TRENDING_SOURCE, trendingSource);
intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredPostsActivity.EXTRA_CONTAIN_FLAIR, flair);
startActivity(intent);
@@ -472,6 +481,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
Intent intent = new Intent(activity, FilteredPostsActivity.class);
intent.putExtra(FilteredPostsActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredPostsActivity.EXTRA_QUERY, query);
+ intent.putExtra(FilteredPostsActivity.EXTRA_TRENDING_SOURCE, trendingSource);
intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredPostsActivity.EXTRA_FILTER, Post.NSFW_TYPE);
startActivity(intent);
@@ -651,12 +661,6 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
usage = PostFilterUsage.USER_TYPE;
nameOfUsage = username;
- if (where != null && where.equals(PostDataSource.USER_WHERE_SUBMITTED)) {
- CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mFetchPostInfoLinearLayout.getLayoutParams();
- params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
- mFetchPostInfoLinearLayout.setLayoutParams(params);
- }
-
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_USER_POST_BASE + username,
mSharedPreferences.getString(SharedPreferencesUtils.USER_DEFAULT_SORT_TYPE, SortType.Type.NEW.name()));
if (sort.equals(SortType.Type.CONTROVERSIAL.name()) || sort.equals(SortType.Type.TOP.name())) {
@@ -843,7 +847,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
int nColumns = getNColumns(resources);
if (nColumns == 1) {
- mLinearLayoutManager = new LinearLayoutManager(activity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(activity);
mPostRecyclerView.setLayoutManager(mLinearLayoutManager);
} else {
mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(nColumns, StaggeredGridLayoutManager.VERTICAL);
@@ -854,6 +858,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
windowWidth /= 2;
}
+ if (recyclerViewPosition > 0) {
+ mPostRecyclerView.scrollToPosition(recyclerViewPosition);
+ }
+
mAdapter.setHideReadPostsIndex(hideReadPostsIndex);
if (activity instanceof ActivityToolbarInterface) {
@@ -1097,27 +1105,32 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void initializeAndBindPostViewModel(String accessToken) {
if (postType == PostDataSource.TYPE_SEARCH) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
- mPostFeedScrolledPositionSharedPreferences, subredditName, query, postType, sortType,
- postFilter, readPosts)).get(PostViewModel.class);
+ mPostFeedScrolledPositionSharedPreferences, subredditName, query, trendingSource,
+ postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, subredditName, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostDataSource.TYPE_MULTI_REDDIT) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, multiRedditPath, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostDataSource.TYPE_USER) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, username, postType, sortType, postFilter,
where, readPosts)).get(PostViewModel.class);
} else {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mOauthRetrofit, accessToken,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), mOauthRetrofit, accessToken,
accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
}
@@ -1128,28 +1141,33 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void initializeAndBindPostViewModelForAnonymous(String concatenatedSubredditNames) {
//For anonymous user
if (postType == PostDataSource.TYPE_SEARCH) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mRetrofit, null,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), mRetrofit, null,
accountName, mSharedPreferences,
- mPostFeedScrolledPositionSharedPreferences, subredditName, query, postType, sortType,
- postFilter, readPosts)).get(PostViewModel.class);
+ mPostFeedScrolledPositionSharedPreferences, subredditName, query, trendingSource,
+ postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
- mPostViewModel = new ViewModelProvider(this, new PostViewModel.Factory(mRetrofit, null,
+ mPostViewModel = new ViewModelProvider(this, new PostViewModel.Factory(mExecutor,
+ new Handler(), mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, subredditName, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostDataSource.TYPE_MULTI_REDDIT) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mRetrofit, null,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, multiRedditPath, postType, sortType, postFilter,
readPosts)).get(PostViewModel.class);
} else if (postType == PostDataSource.TYPE_USER) {
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mRetrofit, null,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, username, postType, sortType, postFilter,
where, readPosts)).get(PostViewModel.class);
} else {
//Anonymous Front Page
- mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mRetrofit,
+ mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
+ new Handler(), mRetrofit,
mSharedPreferences, concatenatedSubredditNames, postType, sortType, postFilter)).get(PostViewModel.class);
}
@@ -1442,9 +1460,16 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
break;
}
+ int previousPosition = -1;
+ if (mLinearLayoutManager != null) {
+ previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
+ } else if (mStaggeredGridLayoutManager != null) {
+ int[] into = new int[mStaggeredGridLayoutManager.getSpanCount()];
+ previousPosition = mStaggeredGridLayoutManager.findFirstVisibleItemPositions(into)[0];
+ }
int nColumns = getNColumns(getResources());
if (nColumns == 1) {
- mLinearLayoutManager = new LinearLayoutManager(activity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(activity);
if (mPostRecyclerView.getItemDecorationCount() > 0) {
mPostRecyclerView.removeItemDecorationAt(0);
}
@@ -1462,6 +1487,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mLinearLayoutManager = null;
}
+ if (previousPosition > 0) {
+ mPostRecyclerView.scrollToPosition(previousPosition);
+ }
+
if (mAdapter != null) {
mAdapter.setPostLayout(postLayout);
refreshAdapter();
@@ -1503,6 +1532,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
Intent intent = new Intent(activity, FilteredPostsActivity.class);
intent.putExtra(FilteredPostsActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredPostsActivity.EXTRA_QUERY, query);
+ intent.putExtra(FilteredPostsActivity.EXTRA_TRENDING_SOURCE, trendingSource);
intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, postType);
startActivity(intent);
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
@@ -1537,6 +1567,17 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
}
+ @Nullable
+ public Boolean getMasterMutingOption() {
+ return masterMutingOption;
+ }
+
+ public void videoAutoplayChangeMutingOption(boolean isMute) {
+ if (rememberMutingOptionInPostFeed) {
+ masterMutingOption = isMute;
+ }
+ }
+
@Subscribe
public void onPostUpdateEvent(PostUpdateEventToPostList event) {
PagedList<Post> posts = mAdapter.getCurrentList();
@@ -1644,6 +1685,14 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
@Subscribe
+ public void onChangeDefaultLinkPostLayoutEvent(ChangeDefaultLinkPostLayoutEvent event) {
+ if (mAdapter != null) {
+ mAdapter.setDefaultLinkPostLayout(event.defaultLinkPostLayout);
+ refreshAdapter();
+ }
+ }
+
+ @Subscribe
public void onChangeShowAbsoluteNumberOfVotesEvent(ChangeShowAbsoluteNumberOfVotesEvent changeShowAbsoluteNumberOfVotesEvent) {
if (mAdapter != null) {
mAdapter.setShowAbsoluteNumberOfVotes(changeShowAbsoluteNumberOfVotesEvent.showAbsoluteNumberOfVotes);
@@ -1826,6 +1875,14 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
@Subscribe
+ public void onChangeHidePostFlairEvent(ChangeHidePostFlairEvent event) {
+ if (mAdapter != null) {
+ mAdapter.setHidePostFlair(event.hidePostFlair);
+ refreshAdapter();
+ }
+ }
+
+ @Subscribe
public void onChangeHideTheNumberOfAwardsEvent(ChangeHideTheNumberOfAwardsEvent event) {
if (mAdapter != null) {
mAdapter.setHideTheNumberOfAwards(event.hideTheNumberOfAwards);
@@ -1857,6 +1914,14 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
}
+ @Subscribe
+ public void onChangeRememberMutingOptionInPostFeedEvent(ChangeRememberMutingOptionInPostFeedEvent event) {
+ rememberMutingOptionInPostFeed = event.rememberMutingOptionInPostFeedEvent;
+ if (!event.rememberMutingOptionInPostFeedEvent) {
+ masterMutingOption = null;
+ }
+ }
+
private void refreshAdapter() {
int previousPosition = -1;
if (mLinearLayoutManager != null) {
@@ -1871,7 +1936,6 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mPostRecyclerView.setLayoutManager(null);
mPostRecyclerView.setAdapter(mAdapter);
mPostRecyclerView.setLayoutManager(layoutManager);
-
if (previousPosition > 0) {
mPostRecyclerView.scrollToPosition(previousPosition);
}
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 7297cb54..d7a77b07 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SidebarFragment.java
@@ -17,7 +17,6 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -48,8 +47,10 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.activities.LinkResolverActivity;
import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivity;
import ml.docilealligator.infinityforreddit.asynctasks.InsertSubredditData;
+import ml.docilealligator.infinityforreddit.bottomsheetfragments.CopyTextBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.UrlMenuBottomSheetFragment;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.subreddit.FetchSubredditData;
import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
import ml.docilealligator.infinityforreddit.subreddit.SubredditViewModel;
@@ -65,7 +66,7 @@ public class SidebarFragment extends Fragment {
private Activity activity;
private String subredditName;
public SubredditViewModel mSubredditViewModel;
- private LinearLayoutManager linearLayoutManager;
+ private LinearLayoutManagerBugFixed linearLayoutManager;
private int markdownColor;
@Inject
@Named("no_oauth")
@@ -76,6 +77,7 @@ public class SidebarFragment extends Fragment {
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
+ private String sidebarDescription;
public SidebarFragment() {
// Required empty public constructor
@@ -99,7 +101,7 @@ public class SidebarFragment extends Fragment {
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
swipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
- markdownColor = mCustomThemeWrapper.getSecondaryTextColor();
+ markdownColor = mCustomThemeWrapper.getPrimaryTextColor();
Markwon markwon = Markwon.builder(activity)
.usePlugin(HtmlPlugin.create())
@@ -107,6 +109,16 @@ public class SidebarFragment extends Fragment {
@Override
public void beforeSetText(@NonNull TextView textView, @NonNull Spanned markdown) {
textView.setTextColor(markdownColor);
+ textView.setOnLongClickListener(view -> {
+ if (sidebarDescription != null && !sidebarDescription.equals("") && textView.getSelectionStart() == -1 && textView.getSelectionEnd() == -1) {
+ Bundle bundle = new Bundle();
+ bundle.putString(CopyTextBottomSheetFragment.EXTRA_MARKDOWN, sidebarDescription);
+ CopyTextBottomSheetFragment copyTextBottomSheetFragment = new CopyTextBottomSheetFragment();
+ copyTextBottomSheetFragment.setArguments(bundle);
+ copyTextBottomSheetFragment.show(getChildFragmentManager(), copyTextBottomSheetFragment.getTag());
+ }
+ return true;
+ });
}
@Override
@@ -142,7 +154,7 @@ public class SidebarFragment extends Fragment {
.textLayoutIsRoot(R.layout.view_table_entry_cell)))
.build();
- linearLayoutManager = new LinearLayoutManager(activity);
+ linearLayoutManager = new LinearLayoutManagerBugFixed(activity);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(markwonAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@@ -162,8 +174,9 @@ public class SidebarFragment extends Fragment {
.get(SubredditViewModel.class);
mSubredditViewModel.getSubredditLiveData().observe(getViewLifecycleOwner(), subredditData -> {
if (subredditData != null) {
- if (subredditData.getSidebarDescription() != null && !subredditData.getSidebarDescription().equals("")) {
- markwonAdapter.setMarkdown(markwon, subredditData.getSidebarDescription());
+ sidebarDescription = subredditData.getSidebarDescription();
+ if (sidebarDescription != null && !sidebarDescription.equals("")) {
+ markwonAdapter.setMarkdown(markwon, sidebarDescription);
markwonAdapter.notifyDataSetChanged();
}
} else {
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 e35520bd..46513616 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubredditListingFragment.java
@@ -19,7 +19,6 @@ import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -46,6 +45,7 @@ import ml.docilealligator.infinityforreddit.activities.SearchSubredditsResultAct
import ml.docilealligator.infinityforreddit.activities.ViewSubredditDetailActivity;
import ml.docilealligator.infinityforreddit.adapters.SubredditListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.subreddit.SubredditData;
import ml.docilealligator.infinityforreddit.subreddit.SubredditListingViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
@@ -97,7 +97,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private SubredditListingRecyclerViewAdapter mAdapter;
private Activity mActivity;
private SortType sortType;
@@ -131,7 +131,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
}
}
- mLinearLayoutManager = new LinearLayoutManager(getActivity());
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(getActivity());
mSubredditListingRecyclerView.setLayoutManager(mLinearLayoutManager);
String query = getArguments().getString(EXTRA_QUERY);
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 7bb69a76..61333955 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/SubscribedSubredditsListingFragment.java
@@ -17,7 +17,6 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -41,6 +40,7 @@ import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
@@ -82,7 +82,7 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra
public SubscribedSubredditViewModel mSubscribedSubredditViewModel;
private Activity mActivity;
private RequestManager mGlide;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
public SubscribedSubredditsListingFragment() {
// Required empty public constructor
@@ -115,7 +115,7 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra
mGlide = Glide.with(this);
- mLinearLayoutManager = new LinearLayoutManager(mActivity);
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
SubscribedSubredditsRecyclerViewAdapter adapter;
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 5e894706..912176d5 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/UserListingFragment.java
@@ -19,7 +19,6 @@ import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@@ -46,6 +45,7 @@ import ml.docilealligator.infinityforreddit.activities.SearchUsersResultActivity
import ml.docilealligator.infinityforreddit.activities.ViewUserDetailActivity;
import ml.docilealligator.infinityforreddit.adapters.UserListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.user.UserData;
import ml.docilealligator.infinityforreddit.user.UserListingViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
@@ -97,7 +97,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
- private LinearLayoutManager mLinearLayoutManager;
+ private LinearLayoutManagerBugFixed mLinearLayoutManager;
private String mQuery;
private UserListingRecyclerViewAdapter mAdapter;
private Activity mActivity;
@@ -132,7 +132,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
}
}
- mLinearLayoutManager = new LinearLayoutManager(getActivity());
+ mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mUserListingRecyclerView.setLayoutManager(mLinearLayoutManager);
mQuery = getArguments().getString(EXTRA_QUERY);
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 0dcf1f01..2b6e9ea9 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurImageFragment.java
@@ -16,8 +16,10 @@ 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.ProgressBar;
+import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -36,6 +38,7 @@ import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
+import com.google.android.material.bottomappbar.BottomAppBar;
import java.io.File;
import java.util.concurrent.Executor;
@@ -57,6 +60,8 @@ import ml.docilealligator.infinityforreddit.services.DownloadMediaService;
public class ViewImgurImageFragment extends Fragment {
public static final String EXTRA_IMGUR_IMAGES = "EII";
+ public static final String EXTRA_INDEX = "EI";
+ public static final String EXTRA_MEDIA_COUNT = "EMC";
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
@BindView(R.id.progress_bar_view_imgur_image_fragment)
@@ -65,6 +70,16 @@ public class ViewImgurImageFragment extends Fragment {
SubsamplingScaleImageView imageView;
@BindView(R.id.load_image_error_linear_layout_view_imgur_image_fragment)
LinearLayout errorLinearLayout;
+ @BindView(R.id.bottom_navigation_view_imgur_image_fragment)
+ BottomAppBar bottomAppBar;
+ @BindView(R.id.title_text_view_view_imgur_image_fragment)
+ TextView titleTextView;
+ @BindView(R.id.download_image_view_view_imgur_image_fragment)
+ ImageView downloadImageView;
+ @BindView(R.id.share_image_view_view_imgur_image_fragment)
+ ImageView shareImageView;
+ @BindView(R.id.wallpaper_image_view_view_imgur_image_fragment)
+ ImageView wallpaperImageView;
@Inject
Executor mExecutor;
@@ -81,7 +96,7 @@ public class ViewImgurImageFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- View rootView = inflater.inflate(R.layout.fragment_view_imgur_images, container, false);
+ View rootView = inflater.inflate(R.layout.fragment_view_imgur_image, container, false);
((Infinity) activity.getApplication()).getAppComponent().inject(this);
@@ -100,6 +115,9 @@ public class ViewImgurImageFragment extends Fragment {
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
isActionBarHidden = false;
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ }
} else {
activity.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
@@ -109,6 +127,9 @@ public class ViewImgurImageFragment extends Fragment {
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE);
isActionBarHidden = true;
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.GONE);
+ }
}
});
imageView.setMinimumDpi(80);
@@ -121,6 +142,25 @@ public class ViewImgurImageFragment extends Fragment {
loadImage();
});
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ titleTextView.setText(getString(R.string.view_imgur_media_activity_image_label,
+ getArguments().getInt(EXTRA_INDEX) + 1, getArguments().getInt(EXTRA_MEDIA_COUNT)));
+ downloadImageView.setOnClickListener(view -> {
+ if (isDownloading) {
+ return;
+ }
+ isDownloading = true;
+ requestPermissionAndDownload();
+ });
+ shareImageView.setOnClickListener(view -> {
+ shareImage();
+ });
+ wallpaperImageView.setOnClickListener(view -> {
+ setWallpaper();
+ });
+ }
+
return rootView;
}
@@ -164,83 +204,39 @@ public class ViewImgurImageFragment extends Fragment {
if (isDownloading) {
return false;
}
-
isDownloading = true;
-
- 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();
- }
- } else {
- download();
- }
-
+ requestPermissionAndDownload();
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) {
-
- }
- });
+ shareImage();
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());
- }
+ setWallpaper();
return true;
}
return false;
}
+ private void requestPermissionAndDownload() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ 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();
+ }
+ } else {
+ download();
+ }
+ }
+
private void download() {
isDownloading = false;
@@ -252,6 +248,59 @@ public class ViewImgurImageFragment extends Fragment {
Toast.makeText(activity, R.string.download_started, Toast.LENGTH_SHORT).show();
}
+ private void shareImage() {
+ 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) {
+
+ }
+ });
+ }
+
+ private void setWallpaper() {
+ 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());
+ }
+ }
+
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
@@ -269,4 +318,10 @@ public class ViewImgurImageFragment extends Fragment {
super.onAttach(context);
activity = (ViewImgurMediaActivity) context;
}
+
+ @Override
+ public void onDestroyView() {
+ super.onDestroyView();
+ glide.clear(imageView);
+ }
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurVideoFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurVideoFragment.java
index 01961e17..65b283e1 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurVideoFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewImgurVideoFragment.java
@@ -1,7 +1,6 @@
package ml.docilealligator.infinityforreddit.fragments;
import android.Manifest;
-import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
@@ -18,7 +17,9 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
+import android.widget.ImageView;
import android.widget.LinearLayout;
+import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -39,6 +40,7 @@ import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
+import com.google.android.material.bottomappbar.BottomAppBar;
import javax.inject.Inject;
import javax.inject.Named;
@@ -48,6 +50,7 @@ import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.ImgurMedia;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.activities.ViewImgurMediaActivity;
import ml.docilealligator.infinityforreddit.services.DownloadMediaService;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
@@ -56,12 +59,20 @@ public class ViewImgurVideoFragment extends Fragment {
public static final String EXTRA_IMGUR_VIDEO = "EIV";
private static final String IS_MUTE_STATE = "IMS";
private static final String POSITION_STATE = "PS";
+ public static final String EXTRA_INDEX = "EI";
+ public static final String EXTRA_MEDIA_COUNT = "EMC";
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
@BindView(R.id.player_view_view_imgur_video_fragment)
PlayerView videoPlayerView;
@BindView(R.id.mute_exo_playback_control_view)
ImageButton muteButton;
- private Activity activity;
+ @BindView(R.id.bottom_navigation_exo_playback_control_view)
+ BottomAppBar bottomAppBar;
+ @BindView(R.id.title_text_view_exo_playback_control_view)
+ TextView titleTextView;
+ @BindView(R.id.download_image_view_exo_playback_control_view)
+ ImageView downloadImageView;
+ private ViewImgurMediaActivity activity;
private ImgurMedia imgurMedia;
private SimpleExoPlayer player;
private DataSource.Factory dataSourceFactory;
@@ -136,6 +147,19 @@ public class ViewImgurVideoFragment extends Fragment {
player.prepare(new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(imgurMedia.getLink())));
preparePlayer(savedInstanceState);
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ titleTextView.setText(getString(R.string.view_imgur_media_activity_video_label,
+ getArguments().getInt(EXTRA_INDEX) + 1, getArguments().getInt(EXTRA_MEDIA_COUNT)));
+ downloadImageView.setOnClickListener(view -> {
+ if (isDownloading) {
+ return;
+ }
+ isDownloading = true;
+ requestPermissionAndDownload();
+ });
+ }
+
return rootView;
}
@@ -149,25 +173,29 @@ public class ViewImgurVideoFragment extends Fragment {
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_download_view_imgur_video_fragment) {
isDownloading = true;
- 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();
- }
+ requestPermissionAndDownload();
+ return true;
+ }
+ return false;
+ }
+
+ private void requestPermissionAndDownload() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ 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();
}
- return true;
+ } else {
+ download();
}
- return false;
}
@Override
@@ -282,6 +310,6 @@ public class ViewImgurVideoFragment extends Fragment {
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
- activity = (Activity) context;
+ activity = (ViewImgurMediaActivity) context;
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java
index c8400b31..2b79125d 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewPostDetailFragment.java
@@ -1,14 +1,21 @@
package ml.docilealligator.infinityforreddit.fragments;
+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;
+
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
+import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
@@ -29,8 +36,8 @@ 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.ConcatAdapter;
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;
@@ -75,7 +82,8 @@ import ml.docilealligator.infinityforreddit.activities.PostFilterPreferenceActiv
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.adapters.CommentsRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.adapters.PostDetailRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.FlairBottomSheetFragment;
import ml.docilealligator.infinityforreddit.bottomsheetfragments.PostCommentSortTypeBottomSheetFragment;
@@ -85,6 +93,7 @@ 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.customviews.LinearLayoutManagerBugFixed;
import ml.docilealligator.infinityforreddit.events.ChangeNSFWBlurEvent;
import ml.docilealligator.infinityforreddit.events.ChangeNetworkStatusEvent;
import ml.docilealligator.infinityforreddit.events.ChangeSpoilerBlurEvent;
@@ -107,11 +116,6 @@ 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";
@@ -124,8 +128,9 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@BindView(R.id.swipe_refresh_layout_view_post_detail_fragment)
SwipeRefreshLayout mSwipeRefreshLayout;
- @BindView(R.id.recycler_view_view_post_detail_fragment)
+ @BindView(R.id.post_detail_recycler_view_view_post_detail_fragment)
CustomToroContainer mRecyclerView;
+ RecyclerView mCommentsRecyclerView;
@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)
@@ -162,6 +167,9 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Named("current_account")
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
+ @Named("post_details")
+ SharedPreferences mPostDetailsSharedPreferences;
+ @Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
ExoCreator mExoCreator;
@@ -210,9 +218,11 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
private boolean mLockFab;
private boolean mSwipeUpToHideFab;
private boolean mExpandChildren;
+ private boolean mSeparatePostAndComments = false;
private int mWindowWidth;
- private LinearLayoutManager mLinearLayoutManager;
- private CommentAndPostRecyclerViewAdapter mAdapter;
+ private ConcatAdapter mConcatAdapter;
+ private PostDetailRecyclerViewAdapter mPostAdapter;
+ private CommentsRecyclerViewAdapter mCommentsAdapter;
private RecyclerView.SmoothScroller mSmoothScroller;
private Drawable mSavedIcon;
private Drawable mUnsavedIcon;
@@ -253,8 +263,25 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mSavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_toolbar_24dp);
mUnsavedIcon = getMenuItemIcon(R.drawable.ic_bookmark_border_toolbar_24dp);
+ if (getResources().getBoolean(R.bool.isTablet) || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
+ mCommentsRecyclerView = rootView.findViewById(R.id.comments_recycler_view_view_post_detail_fragment);
+ }
+ if (!((mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_LANDSCAPE_MODE, true)
+ && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
+ || (mPostDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_POST_AND_COMMENTS_IN_PORTRAIT_MODE, false)))) {
+ if (mCommentsRecyclerView != null) {
+ mCommentsRecyclerView.setVisibility(View.GONE);
+ mCommentsRecyclerView = null;
+ }
+ } else {
+ mSeparatePostAndComments = true;
+ }
+
if (activity != null && activity.isImmersiveInterface()) {
mRecyclerView.setPadding(0, 0, 0, activity.getNavBarHeight() + mRecyclerView.getPaddingBottom());
+ if (mCommentsRecyclerView != null) {
+ mCommentsRecyclerView.setPadding(0, 0, 0, activity.getNavBarHeight() + mCommentsRecyclerView.getPaddingBottom());
+ }
showToast = true;
}
@@ -273,11 +300,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mGlide = Glide.with(this);
mLocale = getResources().getConfiguration().locale;
- mLinearLayoutManager = new LinearLayoutManager(activity);
- mRecyclerView.setLayoutManager(mLinearLayoutManager);
-
if (children != null && children.size() > 0) {
- mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
@@ -302,11 +326,11 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
- int visibleItemCount = mLinearLayoutManager.getChildCount();
- int totalItemCount = mLinearLayoutManager.getItemCount();
- int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
+ int visibleItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getChildCount();
+ int totalItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getItemCount();
+ int firstVisibleItemPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();
- if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
+ if (mCommentsAdapter != null && mCommentsAdapter.getItemCount() >= 1 && (visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
fetchMoreComments();
}
}
@@ -320,7 +344,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
});
} else {
- mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
@@ -365,7 +389,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
- if (!(viewHolder instanceof CommentAndPostRecyclerViewAdapter.CommentViewHolder)) {
+ if (!(viewHolder instanceof CommentsRecyclerViewAdapter.CommentViewHolder)) {
return makeMovementFlags(0, 0);
}
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
@@ -386,9 +410,9 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
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);
+ touchHelper.attachToRecyclerView((mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView));
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.onItemSwipe(viewHolder, direction, swipeLeftAction, swipeRightAction);
}
}
}
@@ -450,7 +474,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
});
if (enableSwipeAction) {
- touchHelper.attachToRecyclerView(mRecyclerView);
+ touchHelper.attachToRecyclerView((mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView));
}
mSwipeRefreshLayout.setOnRefreshListener(() -> refresh(true, true));
@@ -517,17 +541,17 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
} else {
setupMenu();
- mAdapter = new CommentAndPostRecyclerViewAdapter(activity,
+ mPostAdapter = new PostDetailRecyclerViewAdapter(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));
- }
-
+ mWindowWidth, mSeparatePostAndComments, mAccessToken, mAccountName, mPost, mLocale,
+ mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostDetailsSharedPreferences,
+ mExoCreator, post -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
+ mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
+ this, mCustomThemeWrapper, mExecutor, mRetrofit, mOauthRetrofit,
+ mAccessToken, mAccountName, mPost, mLocale, mSingleCommentId,
+ isSingleCommentThreadMode, mSharedPreferences,
+ new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
@Override
public void retryFetchingComments() {
fetchCommentsRespectRecommendedSort(false);
@@ -541,7 +565,13 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
fetchMoreComments();
}
});
- mRecyclerView.setAdapter(mAdapter);
+ if (mCommentsRecyclerView != null) {
+ mRecyclerView.setAdapter(mPostAdapter);
+ mCommentsRecyclerView.setAdapter(mCommentsAdapter);
+ } else {
+ mConcatAdapter = new ConcatAdapter(mPostAdapter, mCommentsAdapter);
+ mRecyclerView.setAdapter(mConcatAdapter);
+ }
if (comments == null) {
fetchCommentsRespectRecommendedSort(false);
@@ -552,7 +582,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
} else if (isFetchingComments) {
fetchCommentsRespectRecommendedSort(false);
} else {
- mAdapter.addComments(comments, hasMoreChildren);
+ mCommentsAdapter.addComments(comments, hasMoreChildren);
if (isLoadingMoreChildren) {
isLoadingMoreChildren = false;
fetchMoreComments();
@@ -561,7 +591,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
}
- mRecyclerView.setCacheManager(mAdapter);
+ mRecyclerView.setCacheManager(mPostAdapter);
mRecyclerView.setPlayerInitializer(order -> {
VolumeInfo volumeInfo = new VolumeInfo(true, 0f);
return new PlaybackInfo(INDEX_UNSET, TIME_UNSET, volumeInfo);
@@ -661,28 +691,28 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
public void addComment(Comment comment) {
- if (mAdapter != null) {
- mAdapter.addComment(comment);
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.addComment(comment);
}
}
public void addChildComment(Comment comment, String parentFullname, int parentPosition) {
- if (mAdapter != null) {
- mAdapter.addChildComment(comment, parentFullname, parentPosition);
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.addChildComment(comment, parentFullname, parentPosition);
}
}
public void editComment(String commentAuthor, String commentContentMarkdown, int position) {
- if (mAdapter != null) {
- mAdapter.editComment(commentAuthor,
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.editComment(commentAuthor,
commentContentMarkdown,
position);
}
}
public void awardGiven(String awardsHTML, int awardCount, int position) {
- if (mAdapter != null) {
- mAdapter.giveAward(awardsHTML, awardCount, position);
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.giveAward(awardsHTML, awardCount, position);
}
}
@@ -728,14 +758,70 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
public void goToTop() {
- if (mLinearLayoutManager != null) {
- mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
+ ((LinearLayoutManagerBugFixed) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0);
+ if (mCommentsRecyclerView != null) {
+ ((LinearLayoutManagerBugFixed) mCommentsRecyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0);
}
}
public void saveComment(int position, boolean isSaved) {
- if (mAdapter != null) {
- mAdapter.setSaveComment(position, isSaved);
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.setSaveComment(position, isSaved);
+ }
+ }
+
+ public void searchComment(String query, boolean searchNextComment) {
+ if (mCommentsAdapter != null) {
+ ArrayList<Comment> visibleComments = mCommentsAdapter.getVisibleComments();
+ int currentSearchIndex = mCommentsAdapter.getSearchCommentIndex();
+ if (currentSearchIndex >= 0) {
+ mCommentsAdapter.notifyItemChanged(currentSearchIndex);
+ }
+ if (visibleComments != null) {
+ if (searchNextComment) {
+ for (int i = currentSearchIndex + 1; i < visibleComments.size(); i++) {
+ if (visibleComments.get(i).getCommentRawText() != null &&
+ visibleComments.get(i).getCommentRawText().toLowerCase().contains(query.toLowerCase())) {
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.highlightSearchResult(i);
+ mCommentsAdapter.notifyItemChanged(i);
+ if (mCommentsRecyclerView == null) {
+ mRecyclerView.scrollToPosition(i + 1);
+ } else {
+ mCommentsRecyclerView.scrollToPosition(i);
+ }
+ }
+ return;
+ }
+ }
+
+ return;
+ } else {
+ for (int i = currentSearchIndex - 1; i >= 0; i--) {
+ if (visibleComments.get(i).getCommentRawText() !=null &&
+ visibleComments.get(i).getCommentRawText().toLowerCase().contains(query.toLowerCase())) {
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.highlightSearchResult(i);
+ mCommentsAdapter.notifyItemChanged(i);
+ if (mCommentsRecyclerView == null) {
+ mRecyclerView.scrollToPosition(i + 1);
+ } else {
+ mCommentsRecyclerView.scrollToPosition(i);
+ }
+ }
+ return;
+ }
+ }
+
+ return;
+ }
+ }
+ }
+ }
+
+ public void resetSearchCommentIndex() {
+ if (mCommentsAdapter != null) {
+ mCommentsAdapter.resetCommentSearchIndex();
}
}
@@ -752,7 +838,11 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
- if (itemId == R.id.action_refresh_view_post_detail_fragment) {
+ if (itemId == R.id.action_search_view_post_detail_fragment) {
+ if (activity.toggleSearchPanelVisibility() && mCommentsAdapter != null) {
+ mCommentsAdapter.resetCommentSearchIndex();
+ }
+ } else 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) {
@@ -1000,7 +1090,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void onResume() {
super.onResume();
- if (mAdapter != null && mRecyclerView != null) {
+ if (mRecyclerView != null) {
mRecyclerView.onWindowVisibilityChanged(View.VISIBLE);
}
}
@@ -1008,7 +1098,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void onPause() {
super.onPause();
- if (mAdapter != null && mRecyclerView != null) {
+ if (mRecyclerView != null) {
mRecyclerView.onWindowVisibilityChanged(View.GONE);
}
}
@@ -1016,7 +1106,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
- comments = mAdapter == null ? null : mAdapter.getVisibleComments();
+ comments = mCommentsAdapter == null ? null : mCommentsAdapter.getVisibleComments();
Bridge.saveInstanceState(this, outState);
}
@@ -1079,25 +1169,27 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mSwipeRefreshLayout.setRefreshing(false);
if (response.isSuccessful()) {
- ParsePost.parsePost(response.body(), new ParsePost.ParsePostListener() {
+ ParsePost.parsePost(mExecutor, new Handler(), 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,
+ mPostAdapter = new PostDetailRecyclerViewAdapter(activity,
+ ViewPostDetailFragment.this, mExecutor, mCustomThemeWrapper,
+ mRetrofit, mOauthRetrofit, mGfycatRetrofit, mRedgifsRetrofit,
+ mRedditDataRoomDatabase, mGlide, mWindowWidth, mSeparatePostAndComments,
+ mAccessToken, mAccountName, mPost, mLocale, mSharedPreferences,
+ mNsfwAndSpoilerSharedPreferences, mPostDetailsSharedPreferences,
+ mExoCreator,
+ post1 -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
+
+ mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
+ ViewPostDetailFragment.this, mCustomThemeWrapper, mExecutor,
+ mRetrofit, mOauthRetrofit, 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));
- }
-
+ new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
@Override
public void retryFetchingComments() {
fetchCommentsRespectRecommendedSort(false);
@@ -1111,23 +1203,29 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
fetchMoreComments();
}
});
- mRecyclerView.setAdapter(mAdapter);
+ if (mCommentsRecyclerView != null) {
+ mRecyclerView.setAdapter(mPostAdapter);
+ mCommentsRecyclerView.setAdapter(mCommentsAdapter);
+ } else {
+ mConcatAdapter = new ConcatAdapter(mPostAdapter, mCommentsAdapter);
+ mRecyclerView.setAdapter(mConcatAdapter);
+ }
if (mRespectSubredditRecommendedSortType) {
fetchCommentsRespectRecommendedSort(false);
} else {
- ParseComment.parseComment(response.body(), new ArrayList<>(), mLocale,
+ ParseComment.parseComment(mExecutor, new Handler(), response.body(), new ArrayList<>(),
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);
+ mCommentsAdapter.addComments(expandedComments, hasMoreChildren);
if (children.size() > 0) {
- mRecyclerView.clearOnScrollListeners();
- mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).clearOnScrollListeners();
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
@@ -1152,9 +1250,9 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
- int visibleItemCount = mLinearLayoutManager.getChildCount();
- int totalItemCount = mLinearLayoutManager.getItemCount();
- int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
+ int visibleItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getChildCount();
+ int totalItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getItemCount();
+ int firstVisibleItemPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();
if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
fetchMoreComments();
@@ -1174,7 +1272,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void onParseCommentFailed() {
- mAdapter.initiallyLoadCommentsFailed();
+ mCommentsAdapter.initiallyLoadCommentsFailed();
}
});
}
@@ -1236,15 +1334,15 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
private void fetchComments(boolean changeRefreshState, boolean checkSortState, String sortType) {
isFetchingComments = true;
- mAdapter.setSingleComment(mSingleCommentId, isSingleCommentThreadMode);
- mAdapter.initiallyLoading();
+ mCommentsAdapter.setSingleComment(mSingleCommentId, isSingleCommentThreadMode);
+ mCommentsAdapter.initiallyLoading();
String commentId = null;
if (isSingleCommentThreadMode) {
commentId = mSingleCommentId;
}
Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit;
- FetchComment.fetchComments(retrofit, mAccessToken, mPost.getId(), commentId, sortType,
+ FetchComment.fetchComments(mExecutor, new Handler(), retrofit, mAccessToken, mPost.getId(), commentId, sortType,
mContextNumber, mExpandChildren, mLocale, new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(ArrayList<Comment> expandedComments,
@@ -1261,11 +1359,11 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
comments = expandedComments;
hasMoreChildren = children.size() != 0;
- mAdapter.addComments(expandedComments, hasMoreChildren);
+ mCommentsAdapter.addComments(expandedComments, hasMoreChildren);
if (children.size() > 0) {
- mRecyclerView.clearOnScrollListeners();
- mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).clearOnScrollListeners();
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
@@ -1290,9 +1388,9 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
- int visibleItemCount = mLinearLayoutManager.getChildCount();
- int totalItemCount = mLinearLayoutManager.getItemCount();
- int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
+ int visibleItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getChildCount();
+ int totalItemCount = (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().getItemCount();
+ int firstVisibleItemPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();
if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
fetchMoreComments();
@@ -1326,7 +1424,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
return;
}
- mAdapter.initiallyLoadCommentsFailed();
+ mCommentsAdapter.initiallyLoadCommentsFailed();
if (changeRefreshState) {
isRefreshing = false;
}
@@ -1346,12 +1444,12 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
isLoadingMoreChildren = true;
Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit;
- FetchComment.fetchMoreComment(retrofit, mAccessToken, children, mChildrenStartingIndex,
- 0, mExpandChildren, mLocale, new FetchComment.FetchMoreCommentListener() {
+ FetchComment.fetchMoreComment(mExecutor, new Handler(), retrofit, mAccessToken, children, mChildrenStartingIndex,
+ 0, mExpandChildren, new FetchComment.FetchMoreCommentListener() {
@Override
public void onFetchMoreCommentSuccess(ArrayList<Comment> expandedComments, int childrenStartingIndex) {
hasMoreChildren = childrenStartingIndex < children.size();
- mAdapter.addComments(expandedComments, hasMoreChildren);
+ mCommentsAdapter.addComments(expandedComments, hasMoreChildren);
mChildrenStartingIndex = childrenStartingIndex;
isLoadingMoreChildren = false;
loadMoreChildrenSuccess = true;
@@ -1361,13 +1459,13 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
public void onFetchMoreCommentFailed() {
isLoadingMoreChildren = false;
loadMoreChildrenSuccess = false;
- mAdapter.loadMoreCommentsFailed();
+ mCommentsAdapter.loadMoreCommentsFailed();
}
});
}
public void refresh(boolean fetchPost, boolean fetchComments) {
- if (mAdapter != null && !isRefreshing) {
+ if (mPostAdapter != null && !isRefreshing) {
isRefreshing = true;
mChildrenStartingIndex = 0;
@@ -1385,12 +1483,12 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
} else {
retrofit = mOauthRetrofit;
}
- FetchPost.fetchPost(retrofit, mPost.getId(), mAccessToken,
+ FetchPost.fetchPost(mExecutor, new Handler(), retrofit, mPost.getId(), mAccessToken,
new FetchPost.FetchPostListener() {
@Override
public void fetchPostSuccess(Post post) {
mPost = post;
- mAdapter.updatePost(mPost);
+ mPostAdapter.updatePost(mPost);
EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
isRefreshing = false;
setupMenu();
@@ -1584,7 +1682,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void deleteSuccess() {
Toast.makeText(activity, R.string.delete_post_success, Toast.LENGTH_SHORT).show();
- mAdapter.deleteComment(position);
+ mCommentsAdapter.deleteComment(position);
}
@Override
@@ -1604,7 +1702,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
new FetchRemovedComment.FetchRemovedCommentListener() {
@Override
public void fetchSuccess(Comment comment) {
- mAdapter.editComment(comment.getAuthor(), comment.getCommentMarkdown(), position);
+ mCommentsAdapter.editComment(comment.getAuthor(), comment.getCommentMarkdown(), position);
}
@Override
@@ -1622,41 +1720,33 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
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);
- }
+ int currentPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();
+ if (mCommentsAdapter != null) {
+ int nextParentPosition = mCommentsAdapter.getNextParentCommentPosition(mCommentsRecyclerView == null ? currentPosition - 1 : currentPosition);
+ if (nextParentPosition < 0) {
+ return;
}
+ mSmoothScroller.setTargetPosition(mCommentsRecyclerView == null ? nextParentPosition + 1 : nextParentPosition);
+ mIsSmoothScrolling = true;
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().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);
- }
+ int currentPosition = ((LinearLayoutManagerBugFixed) (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager()).findFirstVisibleItemPosition();
+ if (mCommentsAdapter != null) {
+ int previousParentPosition = mCommentsAdapter.getPreviousParentCommentPosition(mCommentsRecyclerView == null ? currentPosition - 1 : currentPosition);
+ if (previousParentPosition < 0) {
+ return;
}
+ mSmoothScroller.setTargetPosition(mCommentsRecyclerView == null ? previousParentPosition + 1 : previousParentPosition);
+ mIsSmoothScrolling = true;
+ (mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView).getLayoutManager().startSmoothScroll(mSmoothScroller);
}
}
public void delayTransition() {
- TransitionManager.beginDelayedTransition(mRecyclerView, new AutoTransition());
+ TransitionManager.beginDelayedTransition((mCommentsRecyclerView == null ? mRecyclerView : mCommentsRecyclerView), new AutoTransition());
}
public void showRemovedPost() {
@@ -1668,7 +1758,9 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void fetchSuccess(Post post) {
mPost = post;
- mAdapter.updatePost(post);
+ if (mPostAdapter != null) {
+ mPostAdapter.updatePost(post);
+ }
}
@Override
@@ -1697,56 +1789,75 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mMenu.findItem(R.id.action_save_view_post_detail_fragment).setIcon(mUnsavedIcon);
}
}
- mAdapter.updatePost(mPost);
+ if (mPostAdapter != null) {
+ mPostAdapter.updatePost(mPost);
+ }
}
}
@Subscribe
public void onChangeNSFWBlurEvent(ChangeNSFWBlurEvent event) {
- mAdapter.setBlurNsfwAndDoNotBlurNsfwInNsfwSubreddits(event.needBlurNSFW, event.doNotBlurNsfwInNsfwSubreddits);
- refreshAdapter();
+ if (mPostAdapter != null) {
+ mPostAdapter.setBlurNsfwAndDoNotBlurNsfwInNsfwSubreddits(event.needBlurNSFW, event.doNotBlurNsfwInNsfwSubreddits);
+ }
+ if (mCommentsRecyclerView != null) {
+ refreshAdapter(mRecyclerView, mConcatAdapter);
+ } else {
+ refreshAdapter(mRecyclerView, mPostAdapter);
+ }
}
@Subscribe
public void onChangeSpoilerBlurEvent(ChangeSpoilerBlurEvent event) {
- mAdapter.setBlurSpoiler(event.needBlurSpoiler);
- refreshAdapter();
+ if (mPostAdapter != null) {
+ mPostAdapter.setBlurSpoiler(event.needBlurSpoiler);
+ }
+ if (mCommentsRecyclerView != null) {
+ refreshAdapter(mRecyclerView, mConcatAdapter);
+ } else {
+ refreshAdapter(mRecyclerView, mPostAdapter);
+ }
}
- private void refreshAdapter() {
+ private void refreshAdapter(RecyclerView recyclerView, RecyclerView.Adapter<RecyclerView.ViewHolder> adapter) {
int previousPosition = -1;
- if (mLinearLayoutManager != null) {
- previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
+ if (recyclerView.getLayoutManager() != null) {
+ previousPosition = ((LinearLayoutManagerBugFixed) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
}
- RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
- mRecyclerView.setAdapter(null);
- mRecyclerView.setLayoutManager(null);
- mRecyclerView.setAdapter(mAdapter);
- mRecyclerView.setLayoutManager(layoutManager);
+ RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
+ recyclerView.setAdapter(null);
+ recyclerView.setLayoutManager(null);
+ recyclerView.setAdapter(adapter);
+ recyclerView.setLayoutManager(layoutManager);
if (previousPosition > 0) {
- mRecyclerView.scrollToPosition(previousPosition);
+ recyclerView.scrollToPosition(previousPosition);
}
}
@Subscribe
public void onChangeNetworkStatusEvent(ChangeNetworkStatusEvent changeNetworkStatusEvent) {
- if (mAdapter != null) {
+ if (mPostAdapter != 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);
+ mPostAdapter.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);
+ mPostAdapter.setDataSavingMode(changeNetworkStatusEvent.connectedNetwork == Utils.NETWORK_TYPE_CELLULAR);
stateChanged = true;
}
if (stateChanged) {
- refreshAdapter();
+ if (mCommentsRecyclerView == null) {
+ refreshAdapter(mRecyclerView, mConcatAdapter);
+ } else {
+ refreshAdapter(mRecyclerView, mPostAdapter);
+ refreshAdapter(mCommentsRecyclerView, mCommentsAdapter);
+ }
}
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRPANBroadcastFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRPANBroadcastFragment.java
new file mode 100644
index 00000000..8c0c2f57
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRPANBroadcastFragment.java
@@ -0,0 +1,404 @@
+package ml.docilealligator.infinityforreddit.fragments;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.content.res.Configuration;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageButton;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.constraintlayout.widget.ConstraintLayout;
+import androidx.fragment.app.Fragment;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.request.RequestOptions;
+import com.google.android.exoplayer2.ExoPlaybackException;
+import com.google.android.exoplayer2.ExoPlayerFactory;
+import com.google.android.exoplayer2.Player;
+import com.google.android.exoplayer2.SimpleExoPlayer;
+import com.google.android.exoplayer2.source.BehindLiveWindowException;
+import com.google.android.exoplayer2.source.TrackGroupArray;
+import com.google.android.exoplayer2.source.hls.HlsMediaSource;
+import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
+import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
+import com.google.android.exoplayer2.trackselection.TrackSelection;
+import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
+import com.google.android.exoplayer2.ui.PlayerView;
+import com.google.android.exoplayer2.ui.TrackSelectionDialogBuilder;
+import com.google.android.exoplayer2.upstream.DataSource;
+import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
+import com.google.android.exoplayer2.util.Util;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.concurrent.Executor;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.RPANBroadcast;
+import ml.docilealligator.infinityforreddit.RPANComment;
+import ml.docilealligator.infinityforreddit.adapters.RPANCommentStreamRecyclerViewAdapter;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
+import ml.docilealligator.infinityforreddit.utils.JSONUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.WebSocket;
+import okhttp3.WebSocketListener;
+import retrofit2.Retrofit;
+
+public class ViewRPANBroadcastFragment extends Fragment {
+
+ public static final String EXTRA_RPAN_BROADCAST = "ERB";
+ private static final String IS_MUTE_STATE = "IMS";
+
+ @BindView(R.id.constraint_layout_exo_rpan_broadcast_playback_control_view)
+ ConstraintLayout constraintLayout;
+ @BindView(R.id.player_view_view_rpan_broadcast_fragment)
+ PlayerView playerView;
+ @BindView(R.id.subreddit_icon_image_view_exo_rpan_broadcast_playback_control_view)
+ ImageView subredditIconImageView;
+ @BindView(R.id.subreddit_name_text_view_exo_rpan_broadcast_playback_control_view)
+ TextView subredditNameTextView;
+ @BindView(R.id.username_text_view_exo_rpan_broadcast_playback_control_view)
+ TextView usernameTextView;
+ @BindView(R.id.title_text_view_exo_rpan_broadcast_playback_control_view)
+ TextView titleTextView;
+ @BindView(R.id.recycler_view_exo_rpan_broadcast_playback_control_view)
+ RecyclerView recyclerView;
+ @BindView(R.id.mute_exo_rpan_broadcast_playback_control_view)
+ ImageButton muteButton;
+ @BindView(R.id.hd_exo_rpan_broadcast_playback_control_view)
+ ImageButton hdButton;
+ @Inject
+ @Named("strapi")
+ Retrofit mStrapiRetrofit;
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ @Named("current_account")
+ SharedPreferences mCurrentAccountSharedPreferences;
+ @Inject
+ CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
+ @Inject
+ @Named("rpan")
+ OkHttpClient okHttpClient;
+ private AppCompatActivity mActivity;
+ private RPANBroadcast rpanBroadcast;
+ private SimpleExoPlayer player;
+ private DefaultTrackSelector trackSelector;
+ private DataSource.Factory dataSourceFactory;
+ private Handler handler;
+ private RPANCommentStreamRecyclerViewAdapter adapter;
+ private WebSocket webSocket;
+
+ private boolean wasPlaying;
+ private boolean isMute = false;
+ private long resumePosition = -1;
+ private boolean isDataSavingMode;
+
+ public ViewRPANBroadcastFragment() {
+ // 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_rpan_broadcast, container, false);
+
+ ((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
+
+ ButterKnife.bind(this, rootView);
+
+ rpanBroadcast = getArguments().getParcelable(EXTRA_RPAN_BROADCAST);
+
+ if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || getResources().getBoolean(R.bool.isTablet)) {
+ //Set player controller bottom margin in order to display it above the navbar
+ int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
+ //LinearLayout controllerLinearLayout = findViewById(R.id.linear_layout_exo_playback_control_view);
+ ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) constraintLayout.getLayoutParams();
+ params.bottomMargin = getResources().getDimensionPixelSize(resourceId);
+ } else {
+ //Set player controller right margin in order to display it above the navbar
+ int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
+ //LinearLayout controllerLinearLayout = findViewById(R.id.linear_layout_exo_playback_control_view);
+ ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) constraintLayout.getLayoutParams();
+ params.rightMargin = getResources().getDimensionPixelSize(resourceId);
+ }
+
+ playerView.setControllerVisibilityListener(visibility -> {
+ switch (visibility) {
+ case View.GONE:
+ mActivity.getWindow().getDecorView().setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_IMMERSIVE);
+ playerView.setControllerShowTimeoutMs(0);
+ break;
+ case View.VISIBLE:
+ mActivity.getWindow().getDecorView().setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
+ }
+ });
+
+ TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory();
+ trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
+ player = ExoPlayerFactory.newSimpleInstance(mActivity, trackSelector);
+ playerView.setPlayer(player);
+
+ wasPlaying = true;
+
+ boolean muteVideo = mSharedPreferences.getBoolean(SharedPreferencesUtils.MUTE_VIDEO, false) ||
+ (mSharedPreferences.getBoolean(SharedPreferencesUtils.MUTE_NSFW_VIDEO, false) && rpanBroadcast.rpanPost.isNsfw);
+
+ if (savedInstanceState != null) {
+ isMute = savedInstanceState.getBoolean(IS_MUTE_STATE);
+ if (isMute) {
+ player.setVolume(0f);
+ muteButton.setImageResource(R.drawable.ic_mute_24dp);
+ } else {
+ player.setVolume(1f);
+ muteButton.setImageResource(R.drawable.ic_unmute_24dp);
+ }
+ } else if (muteVideo) {
+ isMute = true;
+ player.setVolume(0f);
+ muteButton.setImageResource(R.drawable.ic_mute_24dp);
+ } else {
+ muteButton.setImageResource(R.drawable.ic_unmute_24dp);
+ }
+
+ player.addListener(new Player.EventListener() {
+ @Override
+ public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
+ if (!trackGroups.isEmpty()) {
+ if (isDataSavingMode) {
+ trackSelector.setParameters(
+ trackSelector.buildUponParameters()
+ .setMaxVideoSize(720, 720));
+ }
+
+ hdButton.setVisibility(View.VISIBLE);
+ hdButton.setOnClickListener(view -> {
+ TrackSelectionDialogBuilder build = new TrackSelectionDialogBuilder(mActivity,
+ getString(R.string.select_video_quality), trackSelector, 0);
+ build.setShowDisableOption(true);
+ build.setAllowAdaptiveSelections(false);
+ build.build().show();
+ });
+
+ for (int i = 0; i < trackGroups.length; i++) {
+ String mimeType = trackGroups.get(i).getFormat(0).sampleMimeType;
+ if (mimeType != null && mimeType.contains("audio")) {
+ muteButton.setVisibility(View.VISIBLE);
+ muteButton.setOnClickListener(view -> {
+ if (isMute) {
+ isMute = false;
+ player.setVolume(1f);
+ muteButton.setImageResource(R.drawable.ic_unmute_24dp);
+ } else {
+ isMute = true;
+ player.setVolume(0f);
+ muteButton.setImageResource(R.drawable.ic_mute_24dp);
+ }
+ });
+ break;
+ }
+ }
+ } else {
+ muteButton.setVisibility(View.GONE);
+ }
+ }
+ });
+
+ Glide.with(mActivity).load(rpanBroadcast.rpanPost.subredditIconUrl)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
+ .error(Glide.with(mActivity).load(R.drawable.subreddit_default_icon)
+ .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
+ .into(subredditIconImageView);
+ subredditNameTextView.setText(rpanBroadcast.rpanPost.subredditName);
+ usernameTextView.setText(rpanBroadcast.rpanPost.username);
+ titleTextView.setText(rpanBroadcast.rpanPost.title);
+
+ recyclerView.setOnTouchListener(new View.OnTouchListener() {
+ float x1;
+ float x2;
+ float y1;
+ float y2;
+
+ @Override
+ public boolean onTouch(View view, MotionEvent motionEvent) {
+ switch (motionEvent.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ x1 = motionEvent.getX();
+ y1 = motionEvent.getY();
+ return true;
+ case MotionEvent.ACTION_UP:
+ x2 = motionEvent.getX();
+ y2 = motionEvent.getY();
+
+ if (x1 == x2 && y1 == y2) {
+ playerView.hideController();
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+ });
+ adapter = new RPANCommentStreamRecyclerViewAdapter(mActivity);
+ recyclerView.setAdapter(adapter);
+
+ handler = new Handler();
+
+ return rootView;
+ }
+
+ private boolean isBehindLiveWindow(ExoPlaybackException e) {
+ if (e.type != ExoPlaybackException.TYPE_SOURCE) {
+ return false;
+ }
+ Throwable cause = e.getSourceException();
+ while (cause != null) {
+ if (cause instanceof BehindLiveWindowException) {
+ return true;
+ }
+ cause = cause.getCause();
+ }
+ return false;
+ }
+
+ private void parseComment(String commentJson) {
+ mExecutor.execute(() -> {
+ try {
+ JSONObject commentObject = new JSONObject(commentJson);
+ if (commentObject.getString(JSONUtils.TYPE_KEY).equals("new_comment")) {
+ JSONObject payload = commentObject.getJSONObject(JSONUtils.PAYLOAD_KEY);
+ RPANComment rpanComment = new RPANComment(
+ payload.getString(JSONUtils.AUTHOR_KEY),
+ payload.getString(JSONUtils.AUTHOR_ICON_IMAGE),
+ payload.getString(JSONUtils.BODY_KEY),
+ payload.getLong(JSONUtils.CREATED_UTC_KEY));
+
+ handler.post(() -> {
+ LinearLayoutManagerBugFixed manager = ((LinearLayoutManagerBugFixed) recyclerView.getLayoutManager());
+ boolean shouldScrollToBottom = false;
+ if (manager != null) {
+ int lastPosition = manager.findLastCompletelyVisibleItemPosition();
+ int currentItemCount = adapter.getItemCount();
+ if (currentItemCount > 0 && lastPosition == currentItemCount - 1) {
+ shouldScrollToBottom = true;
+ }
+ }
+ adapter.addRPANComment(rpanComment);
+ if (shouldScrollToBottom) {
+ recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
+ }
+ });
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ });
+ }
+
+ @Override
+ public void onSaveInstanceState(@NonNull Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putBoolean(IS_MUTE_STATE, isMute);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (dataSourceFactory == null) {
+ dataSourceFactory = new DefaultHttpDataSourceFactory(Util.getUserAgent(mActivity, "Infinity"));
+ // Prepare the player with the source.
+ player.prepare(new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(rpanBroadcast.rpanStream.hlsUrl)));
+ player.setRepeatMode(Player.REPEAT_MODE_ALL);
+ if (resumePosition > 0) {
+ player.seekTo(resumePosition);
+ }
+ }
+
+ if (wasPlaying) {
+ player.setPlayWhenReady(true);
+ }
+
+ if (webSocket == null) {
+ Request request = new Request.Builder().url(rpanBroadcast.rpanPost.liveCommentsWebsocketUrl).build();
+ CommentStreamWebSocketListener listener = new CommentStreamWebSocketListener(this::parseComment);
+ webSocket = okHttpClient.newWebSocket(request, listener);
+ }
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ wasPlaying = player.getPlayWhenReady();
+ player.setPlayWhenReady(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ player.seekToDefaultPosition();
+ player.stop(true);
+ player.release();
+
+ if (webSocket != null) {
+ webSocket.cancel();
+ }
+ }
+
+ @Override
+ public void onAttach(@NonNull Context context) {
+ super.onAttach(context);
+ mActivity = (AppCompatActivity) context;
+ }
+
+ private static class CommentStreamWebSocketListener extends WebSocketListener {
+ MessageReceivedListener messageReceivedListener;
+
+ CommentStreamWebSocketListener(MessageReceivedListener messageReceivedListener) {
+ this.messageReceivedListener = messageReceivedListener;
+ }
+
+ @Override
+ public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
+ messageReceivedListener.onMessage(text);
+ }
+
+ interface MessageReceivedListener {
+ void onMessage(String text);
+ }
+ }
+} \ 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 75e3b2c6..cee6d404 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryImageOrGifFragment.java
@@ -16,8 +16,10 @@ 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.ProgressBar;
+import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -41,6 +43,7 @@ import com.github.piasy.biv.loader.ImageLoader;
import com.github.piasy.biv.loader.glide.GlideImageLoader;
import com.github.piasy.biv.view.BigImageView;
import com.github.piasy.biv.view.GlideImageViewFactory;
+import com.google.android.material.bottomappbar.BottomAppBar;
import java.io.File;
import java.util.concurrent.Executor;
@@ -64,6 +67,8 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
public static final String EXTRA_REDDIT_GALLERY_MEDIA = "ERGM";
public static final String EXTRA_SUBREDDIT_NAME = "ESN";
+ public static final String EXTRA_INDEX = "EI";
+ public static final String EXTRA_MEDIA_COUNT = "EMC";
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
@BindView(R.id.progress_bar_view_reddit_gallery_image_or_gif_fragment)
@@ -72,6 +77,16 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
BigImageView imageView;
@BindView(R.id.load_image_error_linear_layout_view_reddit_gallery_image_or_gif_fragment)
LinearLayout errorLinearLayout;
+ @BindView(R.id.bottom_navigation_view_reddit_gallery_image_or_gif_fragment)
+ BottomAppBar bottomAppBar;
+ @BindView(R.id.title_text_view_view_reddit_gallery_image_or_gif_fragment)
+ TextView titleTextView;
+ @BindView(R.id.download_image_view_view_reddit_gallery_image_or_gif_fragment)
+ ImageView downloadImageView;
+ @BindView(R.id.share_image_view_view_reddit_gallery_image_or_gif_fragment)
+ ImageView shareImageView;
+ @BindView(R.id.wallpaper_image_view_view_reddit_gallery_image_or_gif_fragment)
+ ImageView wallpaperImageView;
@Inject
Executor mExecutor;
@@ -192,6 +207,9 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
isActionBarHidden = false;
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ }
} else {
activity.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
@@ -201,6 +219,9 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE);
isActionBarHidden = true;
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.GONE);
+ }
}
});
@@ -210,6 +231,34 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
loadImage();
});
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ if (media.mediaType == Post.Gallery.TYPE_GIF) {
+ titleTextView.setText(getString(R.string.view_reddit_gallery_activity_gif_label,
+ getArguments().getInt(EXTRA_INDEX) + 1, getArguments().getInt(EXTRA_MEDIA_COUNT)));
+ } else {
+ titleTextView.setText(getString(R.string.view_reddit_gallery_activity_image_label,
+ getArguments().getInt(EXTRA_INDEX) + 1, getArguments().getInt(EXTRA_MEDIA_COUNT)));
+ }
+ downloadImageView.setOnClickListener(view -> {
+ if (isDownloading) {
+ return;
+ }
+ isDownloading = true;
+ requestPermissionAndDownload();
+ });
+ shareImageView.setOnClickListener(view -> {
+ if (media.mediaType == Post.Gallery.TYPE_GIF) {
+ shareGif();
+ } else {
+ shareImage();
+ }
+ });
+ wallpaperImageView.setOnClickListener(view -> {
+ setWallpaper();
+ });
+ }
+
return rootView;
}
@@ -225,53 +274,46 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
- switch (item.getItemId()) {
- case R.id.action_download_view_reddit_gallery_image_or_gif_fragment:
- if (isDownloading) {
- return false;
- }
+ int itemId = item.getItemId();
+ if (itemId == R.id.action_download_view_reddit_gallery_image_or_gif_fragment) {
+ if (isDownloading) {
+ return false;
+ }
+ isDownloading = true;
+ requestPermissionAndDownload();
+ return true;
+ } else if (itemId == R.id.action_share_view_reddit_gallery_image_or_gif_fragment) {
+ if (media.mediaType == Post.Gallery.TYPE_GIF) {
+ shareGif();
+ } else {
+ shareImage();
+ }
+ return true;
+ } else if (itemId == R.id.action_set_wallpaper_view_reddit_gallery_image_or_gif_fragment) {
+ setWallpaper();
+ return true;
+ }
- isDownloading = true;
+ return false;
+ }
- 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();
- }
- } else {
- download();
- }
+ private void requestPermissionAndDownload() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ if (ContextCompat.checkSelfPermission(activity,
+ Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ != PackageManager.PERMISSION_GRANTED) {
- return true;
- case R.id.action_share_view_reddit_gallery_image_or_gif_fragment:
- if (media.mediaType == Post.Gallery.TYPE_GIF) {
- shareGif();
- } else {
- shareImage();
- }
- return true;
- case R.id.action_set_wallpaper_view_reddit_gallery_image_or_gif_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;
+ // 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 false;
}
private void download() {
@@ -366,6 +408,20 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
}).submit();
}
+ private void setWallpaper() {
+ if (media.mediaType != Post.Gallery.TYPE_GIF) {
+ 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());
+ }
+ }
+ }
+
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
@@ -385,8 +441,21 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
}
@Override
- public void onDestroy() {
- super.onDestroy();
+ public void onResume() {
+ super.onResume();
+ SubsamplingScaleImageView ssiv = imageView.getSSIV();
+ if (ssiv == null || !ssiv.hasImage()) {
+ imageView.showImage(Uri.parse(media.url));
+ }
+ }
+
+ @Override
+ public void onDestroyView() {
+ super.onDestroyView();
BigImageViewer.imageLoader().cancelAll();
+ SubsamplingScaleImageView subsamplingScaleImageView = imageView.getSSIV();
+ if (subsamplingScaleImageView != null) {
+ subsamplingScaleImageView.recycle();
+ }
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryVideoFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryVideoFragment.java
index a1258ce2..de1e5566 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryVideoFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/fragments/ViewRedditGalleryVideoFragment.java
@@ -1,7 +1,6 @@
package ml.docilealligator.infinityforreddit.fragments;
import android.Manifest;
-import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
@@ -18,7 +17,9 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
+import android.widget.ImageView;
import android.widget.LinearLayout;
+import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
@@ -39,6 +40,7 @@ import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
+import com.google.android.material.bottomappbar.BottomAppBar;
import javax.inject.Inject;
import javax.inject.Named;
@@ -46,8 +48,9 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.Infinity;
-import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.activities.ViewRedditGalleryActivity;
+import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.services.DownloadMediaService;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
@@ -57,12 +60,20 @@ public class ViewRedditGalleryVideoFragment extends Fragment {
public static final String EXTRA_SUBREDDIT_NAME = "ESN";
private static final String IS_MUTE_STATE = "IMS";
private static final String POSITION_STATE = "PS";
+ public static final String EXTRA_INDEX = "EI";
+ public static final String EXTRA_MEDIA_COUNT = "EMC";
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
@BindView(R.id.player_view_view_reddit_gallery_video_fragment)
PlayerView videoPlayerView;
@BindView(R.id.mute_exo_playback_control_view)
ImageButton muteButton;
- private Activity activity;
+ @BindView(R.id.bottom_navigation_exo_playback_control_view)
+ BottomAppBar bottomAppBar;
+ @BindView(R.id.title_text_view_exo_playback_control_view)
+ TextView titleTextView;
+ @BindView(R.id.download_image_view_exo_playback_control_view)
+ ImageView downloadImageView;
+ private ViewRedditGalleryActivity activity;
private Post.Gallery galleryVideo;
private String subredditName;
private SimpleExoPlayer player;
@@ -139,6 +150,19 @@ public class ViewRedditGalleryVideoFragment extends Fragment {
player.prepare(new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(galleryVideo.url)));
preparePlayer(savedInstanceState);
+ if (activity.isUseBottomAppBar()) {
+ bottomAppBar.setVisibility(View.VISIBLE);
+ titleTextView.setText(getString(R.string.view_reddit_gallery_activity_video_label,
+ getArguments().getInt(EXTRA_INDEX) + 1, getArguments().getInt(EXTRA_MEDIA_COUNT)));
+ downloadImageView.setOnClickListener(view -> {
+ if (isDownloading) {
+ return;
+ }
+ isDownloading = true;
+ requestPermissionAndDownload();
+ });
+ }
+
return rootView;
}
@@ -152,25 +176,29 @@ public class ViewRedditGalleryVideoFragment extends Fragment {
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_download_view_reddit_gallery_video_fragment) {
isDownloading = true;
- 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();
- }
+ requestPermissionAndDownload();
+ return true;
+ }
+ return false;
+ }
+
+ private void requestPermissionAndDownload() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ 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();
}
- return true;
+ } else {
+ download();
}
- return false;
}
@Override
@@ -286,6 +314,6 @@ public class ViewRedditGalleryVideoFragment extends Fragment {
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
- activity = (Activity) context;
+ activity = (ViewRedditGalleryActivity) context;
}
} \ No newline at end of file
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/post/FetchPost.java b/app/src/main/java/ml/docilealligator/infinityforreddit/post/FetchPost.java
index 6566b623..9d5f0445 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/FetchPost.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/FetchPost.java
@@ -1,7 +1,11 @@
package ml.docilealligator.infinityforreddit.post;
+import android.os.Handler;
+
import androidx.annotation.NonNull;
+import java.util.concurrent.Executor;
+
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import retrofit2.Call;
@@ -10,7 +14,8 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchPost {
- public static void fetchPost(Retrofit retrofit, String id, String accessToken, FetchPostListener fetchPostListener) {
+ public static void fetchPost(Executor executor, Handler handler, Retrofit retrofit, String id, String accessToken,
+ FetchPostListener fetchPostListener) {
Call<String> postCall;
if (accessToken == null) {
postCall = retrofit.create(RedditAPI.class).getPost(id);
@@ -21,7 +26,7 @@ public class FetchPost {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePost(response.body(), new ParsePost.ParsePostListener() {
+ ParsePost.parsePost(executor, handler, response.body(), new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(Post post) {
fetchPostListener.fetchPostSuccess(post);
@@ -44,7 +49,8 @@ public class FetchPost {
});
}
- public static void fetchRandomPost(Retrofit retrofit, boolean isNSFW, FetchRandomPostListener fetchRandomPostListener) {
+ public static void fetchRandomPost(Executor executor, Handler handler, Retrofit retrofit, boolean isNSFW,
+ FetchRandomPostListener fetchRandomPostListener) {
Call<String> call;
if (isNSFW) {
call = retrofit.create(RedditAPI.class).getRandomNSFWPost();
@@ -56,18 +62,18 @@ public class FetchPost {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
- new ParsePost.ParseRandomPostAsyncTask(response.body(), isNSFW, new ParsePost.ParseRandomPostListener() {
+ ParsePost.parseRandomPost(executor, handler, response.body(), isNSFW,
+ new ParsePost.ParseRandomPostListener() {
+ @Override
+ public void onParseRandomPostSuccess(String postId, String subredditName) {
+ fetchRandomPostListener.fetchRandomPostSuccess(postId, subredditName);
+ }
- @Override
- public void onParseRandomPostSuccess(String postId, String subredditName) {
- fetchRandomPostListener.fetchRandomPostSuccess(postId, subredditName);
- }
-
- @Override
- public void onParseRandomPostFailed() {
- fetchRandomPostListener.fetchRandomPostFailed();
- }
- }).execute();
+ @Override
+ public void onParseRandomPostFailed() {
+ fetchRandomPostListener.fetchRandomPostFailed();
+ }
+ });
} else {
fetchRandomPostListener.fetchRandomPostFailed();
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/post/ParsePost.java b/app/src/main/java/ml/docilealligator/infinityforreddit/post/ParsePost.java
index 9df78a45..881fb4d8 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/ParsePost.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/ParsePost.java
@@ -1,7 +1,7 @@
package ml.docilealligator.infinityforreddit.post;
import android.net.Uri;
-import android.os.AsyncTask;
+import android.os.Handler;
import android.text.Html;
import org.json.JSONArray;
@@ -12,6 +12,7 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
+import java.util.concurrent.Executor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -25,18 +26,100 @@ import ml.docilealligator.infinityforreddit.utils.Utils;
*/
public class ParsePost {
- public static void parsePosts(String response, int nPosts, PostFilter postFilter, List<ReadPost> readPostList,
+ public static void parsePosts(Executor executor, Handler handler, String response, int nPosts,
+ PostFilter postFilter, List<ReadPost> readPostList,
ParsePostsListingListener parsePostsListingListener) {
- new ParsePostDataAsyncTask(response, nPosts, postFilter, readPostList, parsePostsListingListener).execute();
+ executor.execute(() -> {
+ LinkedHashSet<Post> newPosts = new LinkedHashSet<>();
+ try {
+ JSONObject jsonResponse = new JSONObject(response);
+ JSONArray allData = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
+ String lastItem = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
+
+ //Posts listing
+ int size;
+ if (nPosts < 0 || nPosts > allData.length()) {
+ size = allData.length();
+ } else {
+ size = nPosts;
+ }
+
+ HashSet<ReadPost> readPostHashSet = null;
+ if (readPostList != null) {
+ readPostHashSet = new HashSet<>(readPostList);
+ }
+ for (int i = 0; i < size; i++) {
+ try {
+ if (allData.getJSONObject(i).getString(JSONUtils.KIND_KEY).equals("t3")) {
+ JSONObject data = allData.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
+ Post post = parseBasicData(data);
+ if (readPostHashSet != null && readPostHashSet.contains(ReadPost.convertPost(post))) {
+ post.markAsRead(false);
+ }
+ if (PostFilter.isPostAllowed(post, postFilter)) {
+ newPosts.add(post);
+ }
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ handler.post(() -> parsePostsListingListener.onParsePostsListingSuccess(newPosts, lastItem));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(parsePostsListingListener::onParsePostsListingFail);
+ }
+ });
}
- public static void parsePost(String response, ParsePostListener parsePostListener) {
+ public static void parsePost(Executor executor, Handler handler, String response, ParsePostListener parsePostListener) {
PostFilter postFilter = new PostFilter();
postFilter.allowNSFW = true;
- new ParsePostDataAsyncTask(response, postFilter, parsePostListener).execute();
+
+ executor.execute(() -> {
+ try {
+ JSONArray allData = new JSONArray(response).getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
+ if (allData.length() == 0) {
+ handler.post(parsePostListener::onParsePostFail);
+ return;
+ }
+ JSONObject data = allData.getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY);
+ Post post = parseBasicData(data);
+ handler.post(() -> parsePostListener.onParsePostSuccess(post));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(parsePostListener::onParsePostFail);
+ }
+ });
+ }
+
+ public static void parseRandomPost(Executor executor, Handler handler, String response, boolean isNSFW,
+ ParseRandomPostListener parseRandomPostListener) {
+ executor.execute(() -> {
+ try {
+ JSONArray postsArray = new JSONObject(response).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
+ if (postsArray.length() == 0) {
+ handler.post(parseRandomPostListener::onParseRandomPostFailed);
+ } else {
+ JSONObject post = postsArray.getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY);
+ String subredditName = post.getString(JSONUtils.SUBREDDIT_KEY);
+ String postId;
+ if (isNSFW) {
+ postId = post.getString(JSONUtils.ID_KEY);
+ } else {
+ postId = post.getString(JSONUtils.LINK_ID_KEY).substring("t3_".length());
+ }
+ handler.post(() -> parseRandomPostListener.onParseRandomPostSuccess(postId, subredditName));
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ handler.post(parseRandomPostListener::onParseRandomPostFailed);
+ }
+ });
}
- private static Post parseBasicData(JSONObject data) throws JSONException {
+ public static Post parseBasicData(JSONObject data) throws JSONException {
String id = data.getString(JSONUtils.ID_KEY);
String fullName = data.getString(JSONUtils.NAME_KEY);
String subredditName = data.getString(JSONUtils.SUBREDDIT_KEY);
@@ -217,16 +300,32 @@ public class ParsePost {
}
post.setPreviews(previews);
} else {
- //No preview link post
- int postType = Post.NO_PREVIEW_LINK_TYPE;
- post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
- authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score,
- postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden,
- spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
- if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
- post.setSelfText("");
+ if (isVideo) {
+ //No preview video post
+ JSONObject redditVideoObject = data.getJSONObject(JSONUtils.MEDIA_KEY).getJSONObject(JSONUtils.REDDIT_VIDEO_KEY);
+ int postType = Post.VIDEO_TYPE;
+ String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
+ String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY);
+
+ post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFlair,
+ authorFlairHTML, postTimeMillis, title, permalink, score, postType, voteType,
+ nComments, upvoteRatio, flair, awards, nAwards, hidden, spoiler, nsfw, stickied,
+ archived, locked, saved, isCrosspost);
+
+ post.setVideoUrl(videoUrl);
+ post.setVideoDownloadUrl(videoDownloadUrl);
} else {
- post.setSelfText(Utils.modifyMarkdown(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
+ //No preview link post
+ int postType = Post.NO_PREVIEW_LINK_TYPE;
+ post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
+ authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score,
+ postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden,
+ spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
+ if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
+ post.setSelfText("");
+ } else {
+ post.setSelfText(Utils.modifyMarkdown(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
+ }
}
}
}
@@ -494,13 +593,11 @@ public class ParsePost {
public interface ParsePostsListingListener {
void onParsePostsListingSuccess(LinkedHashSet<Post> newPostData, String lastItem);
-
void onParsePostsListingFail();
}
public interface ParsePostListener {
void onParsePostSuccess(Post post);
-
void onParsePostFail();
}
@@ -508,166 +605,4 @@ public class ParsePost {
void onParseRandomPostSuccess(String postId, String subredditName);
void onParseRandomPostFailed();
}
-
- private static class ParsePostDataAsyncTask extends AsyncTask<Void, Void, Void> {
- private JSONArray allData;
- private int nPosts;
- private PostFilter postFilter;
- private List<ReadPost> readPostList;
- private ParsePostsListingListener parsePostsListingListener;
- private ParsePostListener parsePostListener;
- private LinkedHashSet<Post> newPosts;
- private Post post;
- private String lastItem;
- private boolean parseFailed;
-
- ParsePostDataAsyncTask(String response, int nPosts, PostFilter postFilter, List<ReadPost> readPostList,
- ParsePostsListingListener parsePostsListingListener) {
- this.parsePostsListingListener = parsePostsListingListener;
- try {
- JSONObject jsonResponse = new JSONObject(response);
- allData = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
- lastItem = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
- this.nPosts = nPosts;
- this.postFilter = postFilter;
- this.readPostList = readPostList;
- newPosts = new LinkedHashSet<>();
- parseFailed = false;
- } catch (JSONException e) {
- e.printStackTrace();
- parseFailed = true;
- }
- }
-
- ParsePostDataAsyncTask(String response, PostFilter postFilter,
- ParsePostListener parsePostListener) {
- this.parsePostListener = parsePostListener;
- try {
- allData = new JSONArray(response).getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
- this.postFilter = postFilter;
- parseFailed = false;
- } catch (JSONException e) {
- e.printStackTrace();
- parseFailed = true;
- }
- }
-
- @Override
- protected Void doInBackground(Void... voids) {
- if (parseFailed) {
- return null;
- }
-
- if (newPosts == null) {
- //Only one post
- if (allData.length() == 0) {
- parseFailed = true;
- return null;
- }
-
- try {
- JSONObject data = allData.getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY);
- post = parseBasicData(data);
- } catch (JSONException e) {
- e.printStackTrace();
- parseFailed = true;
- }
- } else {
- //Posts listing
- int size;
- if (nPosts < 0 || nPosts > allData.length()) {
- size = allData.length();
- } else {
- size = nPosts;
- }
-
- HashSet<ReadPost> readPostHashSet = null;
- if (readPostList != null) {
- readPostHashSet = new HashSet<>(readPostList);
- }
- for (int i = 0; i < size; i++) {
- try {
- if (allData.getJSONObject(i).getString(JSONUtils.KIND_KEY).equals("t3")) {
- JSONObject data = allData.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
- Post post = parseBasicData(data);
- if (readPostHashSet != null && readPostHashSet.contains(ReadPost.convertPost(post))) {
- post.markAsRead(false);
- }
- if (PostFilter.isPostAllowed(post, postFilter)) {
- newPosts.add(post);
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(Void aVoid) {
- if (!parseFailed) {
- if (newPosts != null) {
- parsePostsListingListener.onParsePostsListingSuccess(newPosts, lastItem);
- } else {
- parsePostListener.onParsePostSuccess(post);
- }
- } else {
- if (parsePostsListingListener != null) {
- parsePostsListingListener.onParsePostsListingFail();
- } else {
- parsePostListener.onParsePostFail();
- }
- }
- }
- }
-
- public static class ParseRandomPostAsyncTask extends AsyncTask<Void, Void, Void> {
-
- private String response;
- private boolean isNSFW;
- private ParseRandomPostListener parseRandomPostListener;
- private String subredditName;
- private String postId;
- private boolean parseFailed = false;
-
- ParseRandomPostAsyncTask(String response, boolean isNSFW, ParseRandomPostListener parseRandomPostListener) {
- this.response = response;
- this.isNSFW = isNSFW;
- this.parseRandomPostListener = parseRandomPostListener;
- }
-
- @Override
- protected Void doInBackground(Void... voids) {
- try {
- JSONArray postsArray = new JSONObject(response).getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
- if (postsArray.length() == 0) {
- parseFailed = true;
- } else {
- JSONObject post = postsArray.getJSONObject(0).getJSONObject(JSONUtils.DATA_KEY);
- subredditName = post.getString(JSONUtils.SUBREDDIT_KEY);
- if (isNSFW) {
- postId = post.getString(JSONUtils.ID_KEY);
- } else {
- postId = post.getString(JSONUtils.LINK_ID_KEY).substring("t3_".length());
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- parseFailed = true;
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(Void aVoid) {
- super.onPostExecute(aVoid);
- if (parseFailed) {
- parseRandomPostListener.onParseRandomPostFailed();
- } else {
- parseRandomPostListener.onParseRandomPostSuccess(postId, subredditName);
- }
- }
- }
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSource.java b/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSource.java
index 8c567809..57a6b5e3 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSource.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSource.java
@@ -1,6 +1,7 @@
package ml.docilealligator.infinityforreddit.post;
import android.content.SharedPreferences;
+import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
@@ -9,6 +10,7 @@ import androidx.paging.PageKeyedDataSource;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.SortType;
@@ -37,6 +39,8 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
public static final String USER_WHERE_SAVED = "saved";
public static final String USER_WHERE_GILDED = "gilded";
+ private Executor executor;
+ private Handler handler;
private Retrofit retrofit;
private String accessToken;
private String accountName;
@@ -44,6 +48,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
private SharedPreferences postFeedScrolledPositionSharedPreferences;
private String subredditOrUserName;
private String query;
+ private String trendingSource;
private int postType;
private SortType sortType;
private PostFilter postFilter;
@@ -59,10 +64,12 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
private LoadParams<String> params;
private LoadCallback<String, Post> callback;
- PostDataSource(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSource(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -78,10 +85,12 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
postLinkedHashSet = new LinkedHashSet<>();
}
- PostDataSource(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSource(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String path, int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -118,10 +127,12 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
postLinkedHashSet = new LinkedHashSet<>();
}
- PostDataSource(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSource(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String subredditOrUserName, int postType, SortType sortType, PostFilter postFilter,
String where, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -139,10 +150,12 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
postLinkedHashSet = new LinkedHashSet<>();
}
- PostDataSource(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSource(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
- String subredditOrUserName, String query, int postType, SortType sortType, PostFilter postFilter,
- List<ReadPost> readPostList) {
+ String subredditOrUserName, String query, String trendingSource, int postType,
+ SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -150,6 +163,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.subredditOrUserName = subredditOrUserName;
this.query = query;
+ this.trendingSource = trendingSource;
paginationNetworkStateLiveData = new MutableLiveData<>();
initialLoadStateLiveData = new MutableLiveData<>();
hasPostLiveData = new MutableLiveData<>();
@@ -254,7 +268,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -317,7 +331,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -377,7 +391,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -451,7 +465,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -512,7 +526,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -583,7 +597,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -627,16 +641,17 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
if (subredditOrUserName == null) {
if (accessToken == null) {
if (sortType.getTime() != null) {
- getPost = api.searchPosts(query, lastItem, sortType.getType().value, sortType.getTime().value);
+ getPost = api.searchPosts(query, lastItem, sortType.getType().value, sortType.getTime().value,
+ trendingSource);
} else {
- getPost = api.searchPosts(query, lastItem, sortType.getType().value);
+ getPost = api.searchPosts(query, lastItem, sortType.getType().value, trendingSource);
}
} else {
if(sortType.getTime() != null) {
getPost = api.searchPostsOauth(query, lastItem, sortType.getType().value,
- sortType.getTime().value, APIUtils.getOAuthHeader(accessToken));
+ sortType.getTime().value, trendingSource, APIUtils.getOAuthHeader(accessToken));
} else {
- getPost = api.searchPostsOauth(query, lastItem, sortType.getType().value,
+ getPost = api.searchPostsOauth(query, lastItem, sortType.getType().value, trendingSource,
APIUtils.getOAuthHeader(accessToken));
}
}
@@ -666,7 +681,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -720,16 +735,18 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
if (subredditOrUserName == null) {
if (accessToken == null) {
if (sortType.getTime() != null) {
- getPost = api.searchPosts(query, after, sortType.getType().value, sortType.getTime().value);
+ getPost = api.searchPosts(query, after, sortType.getType().value, sortType.getTime().value,
+ trendingSource);
} else {
- getPost = api.searchPosts(query, after, sortType.getType().value);
+ getPost = api.searchPosts(query, after, sortType.getType().value, trendingSource);
}
} else {
if (sortType.getTime() != null) {
getPost = api.searchPostsOauth(query, after, sortType.getType().value,
- sortType.getTime().value, APIUtils.getOAuthHeader(accessToken));
+ sortType.getTime().value, trendingSource, APIUtils.getOAuthHeader(accessToken));
} else {
- getPost = api.searchPostsOauth(query, after, sortType.getType().value, APIUtils.getOAuthHeader(accessToken));
+ getPost = api.searchPostsOauth(query, after, sortType.getType().value, trendingSource,
+ APIUtils.getOAuthHeader(accessToken));
}
}
} else {
@@ -757,7 +774,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -817,7 +834,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -888,7 +905,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, readPostList,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, readPostList,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -938,7 +955,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, null,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, null,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
@@ -1002,7 +1019,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
- ParsePost.parsePosts(response.body(), -1, postFilter, null,
+ ParsePost.parsePosts(executor, handler, response.body(), -1, postFilter, null,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(LinkedHashSet<Post> newPosts, String lastItem) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSourceFactory.java b/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSourceFactory.java
index da99a508..dd8312b7 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSourceFactory.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostDataSourceFactory.java
@@ -1,6 +1,7 @@
package ml.docilealligator.infinityforreddit.post;
import android.content.SharedPreferences;
+import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
@@ -8,13 +9,16 @@ import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;
import java.util.List;
+import java.util.concurrent.Executor;
-import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.SortType;
+import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.readpost.ReadPost;
import retrofit2.Retrofit;
class PostDataSourceFactory extends DataSource.Factory {
+ private Executor executor;
+ private Handler handler;
private Retrofit retrofit;
private String accessToken;
private String accountName;
@@ -22,6 +26,7 @@ class PostDataSourceFactory extends DataSource.Factory {
private SharedPreferences postFeedScrolledPositionSharedPreferences;
private String name;
private String query;
+ private String trendingSource;
private int postType;
private SortType sortType;
private PostFilter postFilter;
@@ -31,10 +36,12 @@ class PostDataSourceFactory extends DataSource.Factory {
private PostDataSource postDataSource;
private MutableLiveData<PostDataSource> postDataSourceLiveData;
- PostDataSourceFactory(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSourceFactory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -47,10 +54,12 @@ class PostDataSourceFactory extends DataSource.Factory {
this.readPostList = readPostList;
}
- PostDataSourceFactory(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSourceFactory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -64,10 +73,12 @@ class PostDataSourceFactory extends DataSource.Factory {
this.readPostList = readPostList;
}
- PostDataSourceFactory(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSourceFactory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, int postType, SortType sortType, PostFilter postFilter,
String where, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -82,10 +93,12 @@ class PostDataSourceFactory extends DataSource.Factory {
this.readPostList = readPostList;
}
- PostDataSourceFactory(Retrofit retrofit, String accessToken, String accountName,
+ PostDataSourceFactory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
- String name, String query, int postType, SortType sortType, PostFilter postFilter,
- List<ReadPost> readPostList) {
+ String name, String query, String trendingSource, int postType, SortType sortType,
+ PostFilter postFilter, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -93,6 +106,7 @@ class PostDataSourceFactory extends DataSource.Factory {
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.name = name;
this.query = query;
+ this.trendingSource = trendingSource;
postDataSourceLiveData = new MutableLiveData<>();
this.postType = postType;
this.sortType = sortType;
@@ -104,24 +118,24 @@ class PostDataSourceFactory extends DataSource.Factory {
@Override
public DataSource<String, Post> create() {
if (postType == PostDataSource.TYPE_FRONT_PAGE) {
- postDataSource = new PostDataSource(retrofit, accessToken, accountName,
+ postDataSource = new PostDataSource(executor, handler, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, postType, sortType,
postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_SEARCH) {
- postDataSource = new PostDataSource(retrofit, accessToken, accountName,
- sharedPreferences, postFeedScrolledPositionSharedPreferences, name, query,
+ postDataSource = new PostDataSource(executor, handler, retrofit, accessToken, accountName,
+ sharedPreferences, postFeedScrolledPositionSharedPreferences, name, query, trendingSource,
postType, sortType, postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_SUBREDDIT || postType == PostDataSource.TYPE_MULTI_REDDIT) {
Log.i("asdasfd", "s5 " + (postFilter == null));
- postDataSource = new PostDataSource(retrofit, accessToken, accountName,
+ postDataSource = new PostDataSource(executor, handler, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, postType,
sortType, postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_ANONYMOUS_FRONT_PAGE) {
- postDataSource = new PostDataSource(retrofit, null, null,
+ postDataSource = new PostDataSource(executor, handler, retrofit, null, null,
sharedPreferences, null, name, postType,
sortType, postFilter, null);
} else {
- postDataSource = new PostDataSource(retrofit, accessToken, accountName,
+ postDataSource = new PostDataSource(executor, handler, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, postType,
sortType, postFilter, userWhere, readPostList);
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostViewModel.java b/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostViewModel.java
index 45001fbf..ea56f54e 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostViewModel.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/PostViewModel.java
@@ -1,6 +1,7 @@
package ml.docilealligator.infinityforreddit.post;
import android.content.SharedPreferences;
+import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.core.util.Pair;
@@ -14,6 +15,7 @@ import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import java.util.List;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
@@ -31,10 +33,10 @@ public class PostViewModel extends ViewModel {
private MutableLiveData<PostFilter> postFilterLiveData;
private SortTypeAndPostFilterLiveData sortTypeAndPostFilterLiveData;
- public PostViewModel(Retrofit retrofit, String accessToken, String accountName,
+ public PostViewModel(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
- postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, accountName,
+ postDataSourceFactory = new PostDataSourceFactory(executor, handler, retrofit, accessToken, accountName,
sharedPreferences, cache, postType, sortType, postFilter, readPostList);
initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
@@ -64,11 +66,11 @@ public class PostViewModel extends ViewModel {
});
}
- public PostViewModel(Retrofit retrofit, String accessToken, String accountName,
+ public PostViewModel(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, String subredditName,
int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {
- postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, accountName,
+ postDataSourceFactory = new PostDataSourceFactory(executor, handler, retrofit, accessToken, accountName,
sharedPreferences, cache, subredditName, postType, sortType, postFilter,
readPostList);
@@ -99,11 +101,11 @@ public class PostViewModel extends ViewModel {
});
}
- public PostViewModel(Retrofit retrofit, String accessToken, String accountName,
+ public PostViewModel(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, String username,
int postType, SortType sortType, PostFilter postFilter, String where,
List<ReadPost> readPostList) {
- postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, accountName,
+ postDataSourceFactory = new PostDataSourceFactory(executor, handler, retrofit, accessToken, accountName,
sharedPreferences, cache, username, postType, sortType, postFilter, where, readPostList);
initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
@@ -133,11 +135,12 @@ public class PostViewModel extends ViewModel {
});
}
- public PostViewModel(Retrofit retrofit, String accessToken, String accountName,
+ public PostViewModel(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, String subredditName,
- String query, int postType, SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
- postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, accountName,
- sharedPreferences, cache, subredditName, query, postType, sortType, postFilter,
+ String query, String trendingSource, int postType, SortType sortType,
+ PostFilter postFilter, List<ReadPost> readPostList) {
+ postDataSourceFactory = new PostDataSourceFactory(executor, handler, retrofit, accessToken, accountName,
+ sharedPreferences, cache, subredditName, query, trendingSource, postType, sortType, postFilter,
readPostList);
initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
@@ -200,6 +203,8 @@ public class PostViewModel extends ViewModel {
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
+ private Executor executor;
+ private Handler handler;
private Retrofit retrofit;
private String accessToken;
private String accountName;
@@ -207,15 +212,18 @@ public class PostViewModel extends ViewModel {
private SharedPreferences postFeedScrolledPositionSharedPreferences;
private String name;
private String query;
+ private String trendingSource;
private int postType;
private SortType sortType;
private PostFilter postFilter;
private String userWhere;
private List<ReadPost> readPostList;
- public Factory(Retrofit retrofit, String accessToken, String accountName,
+ public Factory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
int postType, SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -227,10 +235,11 @@ public class PostViewModel extends ViewModel {
this.readPostList = readPostList;
}
- public Factory(Retrofit retrofit, String accessToken, String accountName,
- SharedPreferences sharedPreferences,
- SharedPreferences postFeedScrolledPositionSharedPreferences, String name,
- int postType, SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
+ public Factory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
+ SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
+ String name, int postType, SortType sortType, PostFilter postFilter,
+ List<ReadPost> readPostList) {this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -244,9 +253,12 @@ public class PostViewModel extends ViewModel {
}
//User posts
- public Factory(Retrofit retrofit, String accessToken, String accountName,
- SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences, String username,
- int postType, SortType sortType, PostFilter postFilter, String where, List<ReadPost> readPostList) {
+ public Factory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
+ SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
+ String username, int postType, SortType sortType, PostFilter postFilter, String where,
+ List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -260,9 +272,12 @@ public class PostViewModel extends ViewModel {
this.readPostList = readPostList;
}
- public Factory(Retrofit retrofit, String accessToken, String accountName,
- SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences, String name,
- String query, int postType, SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
+ public Factory(Executor executor, Handler handler, Retrofit retrofit, String accessToken, String accountName,
+ SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
+ String name, String query, String trendingSource, int postType, SortType sortType,
+ PostFilter postFilter, List<ReadPost> readPostList) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
@@ -270,6 +285,7 @@ public class PostViewModel extends ViewModel {
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.name = name;
this.query = query;
+ this.trendingSource = trendingSource;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
@@ -277,8 +293,10 @@ public class PostViewModel extends ViewModel {
}
//Anonymous Front Page
- public Factory(Retrofit retrofit, SharedPreferences sharedPreferences, String concatenatedSubredditNames,
- int postType, SortType sortType, PostFilter postFilter) {
+ public Factory(Executor executor, Handler handler, Retrofit retrofit, SharedPreferences sharedPreferences,
+ String concatenatedSubredditNames, int postType, SortType sortType, PostFilter postFilter) {
+ this.executor = executor;
+ this.handler = handler;
this.retrofit = retrofit;
this.sharedPreferences = sharedPreferences;
this.name = concatenatedSubredditNames;
@@ -291,22 +309,22 @@ public class PostViewModel extends ViewModel {
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (postType == PostDataSource.TYPE_FRONT_PAGE) {
- return (T) new PostViewModel(retrofit, accessToken, accountName, sharedPreferences,
+ return (T) new PostViewModel(executor, handler, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, postType, sortType, postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_SEARCH) {
- return (T) new PostViewModel(retrofit, accessToken, accountName, sharedPreferences,
- postFeedScrolledPositionSharedPreferences, name, query, postType, sortType,
+ return (T) new PostViewModel(executor, handler, retrofit, accessToken, accountName, sharedPreferences,
+ postFeedScrolledPositionSharedPreferences, name, query, trendingSource, postType, sortType,
postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_SUBREDDIT || postType == PostDataSource.TYPE_MULTI_REDDIT) {
- return (T) new PostViewModel(retrofit, accessToken, accountName, sharedPreferences,
+ return (T) new PostViewModel(executor, handler, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, name, postType, sortType,
postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_ANONYMOUS_FRONT_PAGE) {
- return (T) new PostViewModel(retrofit, null, null, sharedPreferences,
+ return (T) new PostViewModel(executor, handler, retrofit, null, null, sharedPreferences,
null, name, postType, sortType,
postFilter, null);
} else {
- return (T) new PostViewModel(retrofit, accessToken, accountName, sharedPreferences,
+ return (T) new PostViewModel(executor, handler, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, name, postType, sortType,
postFilter, userWhere, readPostList);
}
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 c31da124..bf6fdbda 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/post/SubmitPost.java
@@ -1,28 +1,26 @@
package ml.docilealligator.infinityforreddit.post;
import android.graphics.Bitmap;
+import android.os.Handler;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
-import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlPullParserFactory;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
-import java.io.StringReader;
import java.util.HashMap;
-import java.util.Locale;
import java.util.Map;
+import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
+import ml.docilealligator.infinityforreddit.utils.UploadImageUtils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
@@ -31,23 +29,25 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class SubmitPost {
- public static void submitTextOrLinkPost(Retrofit oauthRetrofit, String accessToken,
- Locale locale, String subredditName, String title, String content,
- Flair flair, boolean isSpoiler, boolean isNSFW, String kind,
+ public static void submitTextOrLinkPost(Executor executor, Handler handler, Retrofit oauthRetrofit, String accessToken,
+ String subredditName, String title, String content,
+ Flair flair, boolean isSpoiler, boolean isNSFW,
+ boolean receivePostReplyNotifications, String kind,
SubmitPostListener submitPostListener) {
- submitPost(oauthRetrofit, accessToken, subredditName, title, content,
- flair, isSpoiler, isNSFW, kind, null, submitPostListener);
+ submitPost(executor, handler, oauthRetrofit, accessToken, subredditName, title, content,
+ flair, isSpoiler, isNSFW, receivePostReplyNotifications, kind, null, submitPostListener);
}
- public static void submitImagePost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
+ public static void submitImagePost(Executor executor, Handler handler, Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
String accessToken, String subredditName, String title, Bitmap image,
- Flair flair, boolean isSpoiler, boolean isNSFW, SubmitPostListener submitPostListener) {
+ Flair flair, boolean isSpoiler, boolean isNSFW,
+ boolean receivePostReplyNotifications, SubmitPostListener submitPostListener) {
try {
- String imageUrlOrError = uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, image);
+ String imageUrlOrError = UploadImageUtils.uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, image);
if (imageUrlOrError != null && !imageUrlOrError.startsWith("Error: ")) {
- submitPost(oauthRetrofit, accessToken,
+ submitPost(executor, handler, oauthRetrofit, accessToken,
subredditName, title, imageUrlOrError, flair, isSpoiler, isNSFW,
- APIUtils.KIND_IMAGE, null, submitPostListener);
+ receivePostReplyNotifications, APIUtils.KIND_IMAGE, null, submitPostListener);
} else {
submitPostListener.submitFailed(imageUrlOrError);
}
@@ -57,11 +57,11 @@ public class SubmitPost {
}
}
- public static void submitVideoPost(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
+ public static void submitVideoPost(Executor executor, Handler handler, Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
Retrofit uploadVideoRetrofit, String accessToken,
String subredditName, String title, File buffer, String mimeType,
Bitmap posterBitmap, Flair flair, boolean isSpoiler, boolean isNSFW,
- SubmitPostListener submitPostListener) {
+ boolean receivePostReplyNotifications, SubmitPostListener submitPostListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class);
String fileType = mimeType.substring(mimeType.indexOf("/") + 1);
@@ -74,7 +74,7 @@ public class SubmitPost {
try {
Response<String> uploadImageResponse = uploadImageCall.execute();
if (uploadImageResponse.isSuccessful()) {
- Map<String, RequestBody> nameValuePairsMap = parseJSONResponseFromAWS(uploadImageResponse.body());
+ Map<String, RequestBody> nameValuePairsMap = UploadImageUtils.parseJSONResponseFromAWS(uploadImageResponse.body());
RequestBody fileBody = RequestBody.create(buffer, MediaType.parse("application/octet-stream"));
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", "post_video." + fileType, fileBody);
@@ -88,21 +88,23 @@ public class SubmitPost {
Call<String> uploadMediaToAWS = uploadVideoToAWSApi.uploadMediaToAWS(nameValuePairsMap, fileToUpload);
Response<String> uploadMediaToAWSResponse = uploadMediaToAWS.execute();
if (uploadMediaToAWSResponse.isSuccessful()) {
- String url = parseXMLResponseFromAWS(uploadMediaToAWSResponse.body());
+ String url = UploadImageUtils.parseXMLResponseFromAWS(uploadMediaToAWSResponse.body());
if (url == null) {
submitPostListener.submitFailed(null);
return;
}
- String imageUrlOrError = uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, posterBitmap);
+ String imageUrlOrError = UploadImageUtils.uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, posterBitmap);
if (imageUrlOrError != null && !imageUrlOrError.startsWith("Error: ")) {
if (fileType.equals("gif")) {
- submitPost(oauthRetrofit, accessToken,
+ submitPost(executor, handler, oauthRetrofit, accessToken,
subredditName, title, url, flair, isSpoiler, isNSFW,
- APIUtils.KIND_VIDEOGIF, imageUrlOrError, submitPostListener);
+ receivePostReplyNotifications, APIUtils.KIND_VIDEOGIF, imageUrlOrError,
+ submitPostListener);
} else {
- submitPost(oauthRetrofit, accessToken,
+ submitPost(executor, handler, oauthRetrofit, accessToken,
subredditName, title, url, flair, isSpoiler, isNSFW,
- APIUtils.KIND_VIDEO, imageUrlOrError, submitPostListener);
+ receivePostReplyNotifications, APIUtils.KIND_VIDEO, imageUrlOrError,
+ submitPostListener);
}
} else {
submitPostListener.submitFailed(imageUrlOrError);
@@ -119,17 +121,19 @@ public class SubmitPost {
}
}
- public static void submitCrosspost(Retrofit oauthRetrofit, String accessToken,
- String subredditName, String title, String crosspostFullname,
- Flair flair, boolean isSpoiler, boolean isNSFW, String kind,
- SubmitPostListener submitPostListener) {
- submitPost(oauthRetrofit, accessToken, subredditName, title, crosspostFullname,
- flair, isSpoiler, isNSFW, kind, null, submitPostListener);
+ public static void submitCrosspost(Executor executor, Handler handler, Retrofit oauthRetrofit, String accessToken,
+ String subredditName, String title, String crosspostFullname,
+ Flair flair, boolean isSpoiler, boolean isNSFW,
+ boolean receivePostReplyNotifications, String kind,
+ SubmitPostListener submitPostListener) {
+ submitPost(executor, handler, oauthRetrofit, accessToken, subredditName, title, crosspostFullname,
+ flair, isSpoiler, isNSFW, receivePostReplyNotifications, kind, null, submitPostListener);
}
- private static void submitPost(Retrofit oauthRetrofit, String accessToken,
+ private static void submitPost(Executor executor, Handler handler, Retrofit oauthRetrofit, String accessToken,
String subredditName, String title, String content,
- Flair flair, boolean isSpoiler, boolean isNSFW, String kind,
+ Flair flair, boolean isSpoiler, boolean isNSFW,
+ boolean receivePostReplyNotifications, String kind,
@Nullable String posterUrl, SubmitPostListener submitPostListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class);
@@ -166,13 +170,15 @@ public class SubmitPost {
}
params.put(APIUtils.SPOILER_KEY, Boolean.toString(isSpoiler));
params.put(APIUtils.NSFW_KEY, Boolean.toString(isNSFW));
+ params.put(APIUtils.SEND_REPLIES_KEY, Boolean.toString(receivePostReplyNotifications));
Call<String> submitPostCall = api.submit(APIUtils.getOAuthHeader(accessToken), params);
try {
Response<String> response = submitPostCall.execute();
if (response.isSuccessful()) {
- getSubmittedPost(response.body(), kind, oauthRetrofit, accessToken, submitPostListener);
+ getSubmittedPost(executor, handler, response.body(), kind, oauthRetrofit, accessToken,
+ submitPostListener);
} else {
submitPostListener.submitFailed(response.message());
}
@@ -182,42 +188,9 @@ public class SubmitPost {
}
}
- @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<>();
- uploadImageParams.put(APIUtils.FILEPATH_KEY, "post_image.jpg");
- uploadImageParams.put(APIUtils.MIMETYPE_KEY, "image/jpeg");
-
- Call<String> uploadImageCall = api.uploadImage(APIUtils.getOAuthHeader(accessToken), uploadImageParams);
- 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, SubmitPostListener submitPostListener) throws JSONException, IOException {
+ private static void getSubmittedPost(Executor executor, Handler handler, String response, String kind,
+ Retrofit oauthRetrofit, 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)
@@ -245,7 +218,7 @@ public class SubmitPost {
Call<String> getPostCall = api.getPostOauth(postId, APIUtils.getOAuthHeader(accessToken));
Response<String> getPostCallResponse = getPostCall.execute();
if (getPostCallResponse.isSuccessful()) {
- ParsePost.parsePost(getPostCallResponse.body(), new ParsePost.ParsePostListener() {
+ ParsePost.parsePost(executor, handler, getPostCallResponse.body(), new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(Post post) {
submitPostListener.submitSuccessful(post);
@@ -269,40 +242,4 @@ public class SubmitPost {
void submitFailed(@Nullable String errorMessage);
}
-
- 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);
-
- 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)));
- }
-
- return nameValuePairsMap;
- }
-
- @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();
- }
- }
- eventType = xmlPullParser.next();
- }
-
- return null;
- }
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadMediaService.java b/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadMediaService.java
index a326d81f..e5534ef9 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadMediaService.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadMediaService.java
@@ -263,7 +263,7 @@ public class DownloadMediaService extends Service {
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, destinationFileUriString);
contentValues.put(mediaType == EXTRA_MEDIA_TYPE_VIDEO ? MediaStore.Video.Media.IS_PENDING : MediaStore.Images.Media.IS_PENDING, 1);
- final Uri contentUri = mediaType == EXTRA_MEDIA_TYPE_VIDEO ? MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL) : MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
+ final Uri contentUri = mediaType == EXTRA_MEDIA_TYPE_VIDEO ? MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) : MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri uri = contentResolver.insert(contentUri, contentValues);
if (uri == null) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadRedditVideoService.java b/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadRedditVideoService.java
index f1b9633e..a398871e 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadRedditVideoService.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/services/DownloadRedditVideoService.java
@@ -25,7 +25,6 @@ import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.provider.MediaStore;
-import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
@@ -417,7 +416,7 @@ public class DownloadRedditVideoService extends Service {
Uri uri = null;
try {
- final Uri contentUri = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
+ final Uri contentUri = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
uri = contentResolver.insert(contentUri, contentValues);
if (uri == null) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/services/MaterialYouService.java b/app/src/main/java/ml/docilealligator/infinityforreddit/services/MaterialYouService.java
new file mode 100644
index 00000000..66bd4e0b
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/services/MaterialYouService.java
@@ -0,0 +1,98 @@
+package ml.docilealligator.infinityforreddit.services;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.Service;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+
+import androidx.annotation.Nullable;
+import androidx.core.app.NotificationCompat;
+import androidx.core.app.NotificationManagerCompat;
+
+import java.util.concurrent.Executor;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+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.utils.MaterialYouUtils;
+import ml.docilealligator.infinityforreddit.utils.NotificationUtils;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+
+public class MaterialYouService extends Service {
+
+ @Inject
+ @Named("default")
+ SharedPreferences mSharedPreferences;
+ @Inject
+ @Named("light_theme")
+ SharedPreferences lightThemeSharedPreferences;
+ @Inject
+ @Named("dark_theme")
+ SharedPreferences darkThemeSharedPreferences;
+ @Inject
+ @Named("amoled_theme")
+ SharedPreferences amoledThemeSharedPreferences;
+ @Inject
+ RedditDataRoomDatabase redditDataRoomDatabase;
+ @Inject
+ CustomThemeWrapper customThemeWrapper;
+ @Inject
+ Executor executor;
+
+ public MaterialYouService() {
+ }
+
+ @Nullable
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ @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(
+ NotificationUtils.CHANNEL_ID_MATERIAL_YOU,
+ NotificationUtils.CHANNEL_MATERIAL_YOU,
+ NotificationManager.IMPORTANCE_LOW
+ );
+
+ NotificationManagerCompat manager = NotificationManagerCompat.from(this);
+ manager.createNotificationChannel(serviceChannel);
+ }
+ Notification notification = new NotificationCompat.Builder(this, NotificationUtils.CHANNEL_ID_MATERIAL_YOU)
+ .setContentTitle(getString(R.string.material_you_notification_title))
+ .setContentText(getString(R.string.please_wait))
+ .setSmallIcon(R.drawable.ic_notification)
+ .setColor(customThemeWrapper.getColorPrimaryLightTheme())
+ .build();
+ startForeground(NotificationUtils.MATERIAL_YOU_NOTIFICATION_ID, notification);
+
+ if (mSharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_MATERIAL_YOU, false)) {
+ MaterialYouUtils.changeTheme(this, executor, new Handler(), redditDataRoomDatabase,
+ customThemeWrapper, lightThemeSharedPreferences, darkThemeSharedPreferences,
+ amoledThemeSharedPreferences, () -> {
+ stopService();
+ });
+ } else {
+ stopService();
+ }
+
+ return START_NOT_STICKY;
+ }
+
+ private void stopService() {
+ stopForeground(true);
+ stopSelf();
+ }
+} \ No newline at end of file
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 2f313125..e22bc541 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/services/SubmitPostService.java
@@ -25,6 +25,9 @@ import androidx.core.app.NotificationManagerCompat;
import com.bumptech.glide.Glide;
import org.greenrobot.eventbus.EventBus;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
@@ -33,6 +36,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
@@ -40,15 +44,19 @@ import javax.inject.Named;
import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.events.SubmitCrosspostEvent;
+import ml.docilealligator.infinityforreddit.events.SubmitGalleryPostEvent;
import ml.docilealligator.infinityforreddit.events.SubmitImagePostEvent;
import ml.docilealligator.infinityforreddit.events.SubmitTextOrLinkPostEvent;
import ml.docilealligator.infinityforreddit.events.SubmitVideoOrGifPostEvent;
import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.post.SubmitPost;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
+import ml.docilealligator.infinityforreddit.utils.JSONUtils;
import ml.docilealligator.infinityforreddit.utils.NotificationUtils;
+import retrofit2.Response;
import retrofit2.Retrofit;
public class SubmitPostService extends Service {
@@ -56,15 +64,19 @@ public class SubmitPostService extends Service {
public static final String EXTRA_SUBREDDIT_NAME = "ESN";
public static final String EXTRA_TITLE = "ET";
public static final String EXTRA_CONTENT = "EC";
+ public static final String EXTRA_REDDIT_GALLERY_PAYLOAD = "ERGP";
public static final String EXTRA_KIND = "EK";
public static final String EXTRA_FLAIR = "EF";
public static final String EXTRA_IS_SPOILER = "EIS";
public static final String EXTRA_IS_NSFW = "EIN";
+ public static final String EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS = "ERPRN";
public static final String EXTRA_POST_TYPE = "EPT";
public static final int EXTRA_POST_TEXT_OR_LINK = 0;
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;
+ public static final int EXTRA_POST_TYPE_GALLERY = 3;
+ public static final int EXTRA_POST_TYPE_CROSSPOST = 4;
+
private static final String EXTRA_MEDIA_URI = "EU";
@Inject
@Named("oauth")
@@ -77,6 +89,9 @@ public class SubmitPostService extends Service {
Retrofit mUploadVideoRetrofit;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
+ @Inject
+ Executor mExecutor;
+ private Handler handler;
private ServiceHandler serviceHandler;
public SubmitPostService() {
@@ -103,21 +118,28 @@ public class SubmitPostService extends Service {
Flair flair = bundle.getParcelable(EXTRA_FLAIR);
boolean isSpoiler = bundle.getBoolean(EXTRA_IS_SPOILER, false);
boolean isNSFW = bundle.getBoolean(EXTRA_IS_NSFW, false);
+ boolean receivePostReplyNotifications = bundle.getBoolean(EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, true);
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);
+ submitTextOrLinkPost(accessToken, subredditName, title, content, flair, isSpoiler, isNSFW,
+ receivePostReplyNotifications, kind);
} else if (postType == EXTRA_POST_TYPE_CROSSPOST) {
String content = bundle.getString(EXTRA_CONTENT);
- submitCrosspost(accessToken, subredditName, title, content, flair, isSpoiler, isNSFW);
+ submitCrosspost(mExecutor, handler, accessToken, subredditName, title, content,
+ flair, isSpoiler, isNSFW, receivePostReplyNotifications);
} 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 {
+ submitImagePost(accessToken, mediaUri, subredditName, title, flair, isSpoiler, isNSFW,
+ receivePostReplyNotifications);
+ } else if (postType == EXTRA_POST_TYPE_VIDEO) {
Uri mediaUri = Uri.parse(bundle.getString(EXTRA_MEDIA_URI));
- submitVideoPost(accessToken, mediaUri, subredditName, title, flair, isSpoiler, isNSFW);
+ submitVideoPost(accessToken, mediaUri, subredditName, title, flair, isSpoiler, isNSFW,
+ receivePostReplyNotifications);
+ } else {
+ submitGalleryPost(accessToken, bundle.getString(EXTRA_REDDIT_GALLERY_PAYLOAD));
}
}
}
@@ -129,6 +151,7 @@ public class SubmitPostService extends Service {
// 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.
+ handler = new Handler();
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
@@ -163,9 +186,11 @@ public class SubmitPostService extends Service {
} else if (postType == EXTRA_POST_TYPE_IMAGE) {
bundle.putString(EXTRA_MEDIA_URI, intent.getData().toString());
startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting_image));
- } else {
+ } else if (postType == EXTRA_POST_TYPE_VIDEO) {
bundle.putString(EXTRA_MEDIA_URI, intent.getData().toString());
startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting_video));
+ } else {
+ startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID + randomNotificationIdOffset, createNotification(R.string.posting_gallery));
}
Message msg = serviceHandler.obtainMessage();
@@ -184,73 +209,83 @@ public class SubmitPostService extends Service {
.build();
}
- 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() {
+ private void submitTextOrLinkPost(String accessToken, String subredditName, String title, String content,
+ Flair flair, boolean isSpoiler, boolean isNSFW, boolean receivePostReplyNotifications,
+ String kind) {
+ SubmitPost.submitTextOrLinkPost(mExecutor, handler, mOauthRetrofit, accessToken,
+ subredditName, title, content, flair, isSpoiler,
+ isNSFW, receivePostReplyNotifications, kind, new SubmitPost.SubmitPostListener() {
@Override
public void submitSuccessful(Post post) {
- EventBus.getDefault().post(new SubmitTextOrLinkPostEvent(true, post, null));
+ handler.post(() -> EventBus.getDefault().post(new SubmitTextOrLinkPostEvent(true, post, null)));
stopService();
}
@Override
public void submitFailed(@Nullable String errorMessage) {
- EventBus.getDefault().post(new SubmitTextOrLinkPostEvent(false, null, errorMessage));
+ handler.post(() -> EventBus.getDefault().post(new SubmitTextOrLinkPostEvent(false, null, errorMessage)));
stopService();
}
});
}
- 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() {
+ private void submitCrosspost(Executor executor, Handler handler, String accessToken, String subredditName,
+ String title, String content, Flair flair, boolean isSpoiler, boolean isNSFW,
+ boolean receivePostReplyNotifications) {
+ SubmitPost.submitCrosspost(executor, handler, mOauthRetrofit, accessToken, subredditName, title,
+ content, flair, isSpoiler, isNSFW, receivePostReplyNotifications, APIUtils.KIND_CROSSPOST,
+ new SubmitPost.SubmitPostListener() {
@Override
public void submitSuccessful(Post post) {
- EventBus.getDefault().post(new SubmitCrosspostEvent(true, post, null));
+ handler.post(() -> EventBus.getDefault().post(new SubmitCrosspostEvent(true, post, null)));
stopService();
}
@Override
public void submitFailed(@Nullable String errorMessage) {
- EventBus.getDefault().post(new SubmitCrosspostEvent(false, null, errorMessage));
+ handler.post(() -> EventBus.getDefault().post(new SubmitCrosspostEvent(false, null, errorMessage)));
stopService();
}
});
}
- private void submitImagePost(String accessToken, Uri mediaUri, String subredditName, String title, Flair flair, boolean isSpoiler, boolean isNSFW) {
+ private void submitImagePost(String accessToken, Uri mediaUri, String subredditName, String title,
+ Flair flair, boolean isSpoiler, boolean isNSFW, boolean receivePostReplyNotifications) {
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() {
+ SubmitPost.submitImagePost(mExecutor, handler, mOauthRetrofit, mUploadMediaRetrofit,
+ accessToken, subredditName, title, resource, flair, isSpoiler, isNSFW, receivePostReplyNotifications,
+ 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();
+ handler.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));
+ handler.post(() -> 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)));
+ handler.post(() -> EventBus.getDefault().post(new SubmitImagePostEvent(false, getString(R.string.error_processing_image))));
stopService();
}
}
private void submitVideoPost(String accessToken, Uri mediaUri, String subredditName, String title,
- Flair flair, boolean isSpoiler, boolean isNSFW) {
+ Flair flair, boolean isSpoiler, boolean isNSFW, boolean receivePostReplyNotifications) {
try {
InputStream in = getContentResolver().openInputStream(mediaUri);
String type = getContentResolver().getType(mediaUri);
@@ -266,37 +301,77 @@ public class SubmitPostService extends Service {
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() {
+ SubmitPost.submitVideoPost(mExecutor, handler, mOauthRetrofit, mUploadMediaRetrofit,
+ mUploadVideoRetrofit, accessToken, subredditName, title, new File(cacheFilePath),
+ type, resource, flair, isSpoiler, isNSFW, receivePostReplyNotifications,
+ 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();
- }
+ handler.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));
+ handler.post(() -> EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, false, errorMessage)));
stopService();
}
});
} else {
- EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null));
+ handler.post(() -> EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)));
stopService();
}
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
- EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null));
+ handler.post(() -> EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, true, null)));
+
+ stopService();
+ }
+ }
+ private void submitGalleryPost(String accessToken, String payload) {
+ try {
+ Response<String> response = mOauthRetrofit.create(RedditAPI.class).submitGalleryPost(APIUtils.getOAuthHeader(accessToken), payload).execute();
+ if (response.isSuccessful()) {
+ JSONObject responseObject = new JSONObject(response.body()).getJSONObject(JSONUtils.JSON_KEY);
+ if (responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() != 0) {
+ JSONArray error = responseObject.getJSONArray(JSONUtils.ERRORS_KEY)
+ .getJSONArray(responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() - 1);
+ if (error.length() != 0) {
+ String errorMessage;
+ if (error.length() >= 2) {
+ errorMessage = error.getString(1);
+ } else {
+ errorMessage = error.getString(0);
+ }
+ handler.post(() -> EventBus.getDefault().post(new SubmitGalleryPostEvent(false, null, errorMessage)));
+ } else {
+ handler.post(() -> EventBus.getDefault().post(new SubmitGalleryPostEvent(false, null, null)));
+ }
+ } else {
+ String postUrl = responseObject.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.URL_KEY);
+ handler.post(() -> {
+ EventBus.getDefault().post(new SubmitGalleryPostEvent(true, postUrl, null));
+ });
+ }
+ } else {
+ handler.post(() -> EventBus.getDefault().post(new SubmitGalleryPostEvent(false, null, response.message())));
+ }
+ } catch (IOException | JSONException e) {
+ e.printStackTrace();
+ handler.post(() -> EventBus.getDefault().post(new SubmitGalleryPostEvent(false, null, e.getMessage())));
+ } finally {
stopService();
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AcknowledgementFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AcknowledgementFragment.java
index 59adcf9d..2f2aa91e 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AcknowledgementFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/AcknowledgementFragment.java
@@ -11,7 +11,6 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
@@ -20,6 +19,7 @@ import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.adapters.AcknowledgementRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed;
/**
* A simple {@link Fragment} subclass.
@@ -127,7 +127,7 @@ public class AcknowledgementFragment extends Fragment {
Uri.parse("https://github.com/saket/Better-Link-Movement-Method")));
AcknowledgementRecyclerViewAdapter adapter = new AcknowledgementRecyclerViewAdapter(activity, acknowledgements);
- recyclerView.setLayoutManager(new LinearLayoutManager(activity));
+ recyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(activity));
recyclerView.setAdapter(adapter);
return rootView;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CrashReportsFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CrashReportsFragment.java
index 350addf8..6cb67a5f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CrashReportsFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CrashReportsFragment.java
@@ -17,7 +17,6 @@ import androidx.annotation.NonNull;
import androidx.appcompat.view.menu.MenuItemImpl;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.fragment.app.Fragment;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.crazylegend.crashyreporter.CrashyReporter;
@@ -49,7 +48,6 @@ public class CrashReportsFragment extends Fragment {
setHasOptionsMenu(true);
- recyclerView.setLayoutManager(new LinearLayoutManager(activity));
recyclerView.setAdapter(new CrashReportsRecyclerViewAdapter(CrashyReporter.INSTANCE.getLogsAsStrings()));
return recyclerView;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CustomizeMainPageTabsFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CustomizeMainPageTabsFragment.java
index 7a2cca00..51813f8f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CustomizeMainPageTabsFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/CustomizeMainPageTabsFragment.java
@@ -101,6 +101,14 @@ public class CustomizeMainPageTabsFragment extends Fragment {
TextView moreTabsGroupSummaryTextView;
@BindView(R.id.more_tabs_info_text_view_customize_main_page_tabs_fragment)
TextView moreTabsInfoTextView;
+ @BindView(R.id.show_favorite_multireddits_linear_layout_customize_main_page_tabs_fragment)
+ LinearLayout showFavoriteMultiredditsLinearLayout;
+ @BindView(R.id.show_favorite_multireddits_switch_material_customize_main_page_tabs_fragment)
+ SwitchMaterial showFavoriteMultiredditsSwitchMaterial;
+ @BindView(R.id.show_multireddits_linear_layout_customize_main_page_tabs_fragment)
+ LinearLayout showMultiredditsLinearLayout;
+ @BindView(R.id.show_multireddits_switch_material_customize_main_page_tabs_fragment)
+ SwitchMaterial showMultiredditsSwitchMaterial;
@BindView(R.id.show_subscribed_subreddits_linear_layout_customize_main_page_tabs_fragment)
LinearLayout showSubscribedSubredditsLinearLayout;
@BindView(R.id.show_subscribed_subreddits_switch_material_customize_main_page_tabs_fragment)
@@ -159,6 +167,8 @@ public class CustomizeMainPageTabsFragment extends Fragment {
divider4.setVisibility(View.GONE);
moreTabsGroupSummaryTextView.setVisibility(View.GONE);
moreTabsInfoTextView.setVisibility(View.GONE);
+ showFavoriteMultiredditsLinearLayout.setVisibility(View.GONE);
+ showMultiredditsLinearLayout.setVisibility(View.GONE);
showSubscribedSubredditsLinearLayout.setVisibility(View.GONE);
showFavoriteSubscribedSubredditsLinearLayout.setVisibility(View.GONE);
@@ -483,14 +493,26 @@ public class CustomizeMainPageTabsFragment extends Fragment {
.show();
});
- showSubscribedSubredditsSwitchMaterial.setChecked(sharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS, false));
- showSubscribedSubredditsSwitchMaterial.setOnCheckedChangeListener((compoundButton, b) -> sharedPreferences.edit().putBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS, b).apply());
+ showMultiredditsSwitchMaterial.setChecked(sharedPreferences.getBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_MULTIREDDITS, false));
+ showMultiredditsSwitchMaterial.setOnCheckedChangeListener((compoundButton, b) -> sharedPreferences.edit().putBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_MULTIREDDITS, b).apply());
+ showMultiredditsLinearLayout.setOnClickListener(view -> {
+ showMultiredditsSwitchMaterial.performClick();
+ });
+
+ showFavoriteMultiredditsSwitchMaterial.setChecked(sharedPreferences.getBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_MULTIREDDITS, false));
+ showFavoriteMultiredditsSwitchMaterial.setOnCheckedChangeListener((compoundButton, b) -> sharedPreferences.edit().putBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_MULTIREDDITS, b).apply());
+ showFavoriteMultiredditsLinearLayout.setOnClickListener(view -> {
+ showFavoriteMultiredditsSwitchMaterial.performClick();
+ });
+
+ showSubscribedSubredditsSwitchMaterial.setChecked(sharedPreferences.getBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS, false));
+ showSubscribedSubredditsSwitchMaterial.setOnCheckedChangeListener((compoundButton, b) -> sharedPreferences.edit().putBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS, b).apply());
showSubscribedSubredditsLinearLayout.setOnClickListener(view -> {
showSubscribedSubredditsSwitchMaterial.performClick();
});
- showFavoriteSubscribedSubredditsSwitchMaterial.setChecked(sharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS, false));
- showFavoriteSubscribedSubredditsSwitchMaterial.setOnCheckedChangeListener((compoundButton, b) -> sharedPreferences.edit().putBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS, b).apply());
+ showFavoriteSubscribedSubredditsSwitchMaterial.setChecked(sharedPreferences.getBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS, false));
+ showFavoriteSubscribedSubredditsSwitchMaterial.setOnCheckedChangeListener((compoundButton, b) -> sharedPreferences.edit().putBoolean(accountName + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS, b).apply());
showFavoriteSubscribedSubredditsLinearLayout.setOnClickListener(view -> {
showFavoriteSubscribedSubredditsSwitchMaterial.performClick();
});
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/GesturesAndButtonsPreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/GesturesAndButtonsPreferenceFragment.java
index 882455ef..831755c2 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/GesturesAndButtonsPreferenceFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/GesturesAndButtonsPreferenceFragment.java
@@ -56,7 +56,7 @@ public class GesturesAndButtonsPreferenceFragment extends PreferenceFragmentComp
return true;
});
- if (sharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, false)) {
+ if (sharedPreferences.getBoolean(SharedPreferencesUtils.BOTTOM_APP_BAR_KEY, true)) {
lockBottomAppBarSwitch.setVisible(true);
lockBottomAppBarSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
EventBus.getDefault().post(new ChangeLockBottomAppBarEvent((Boolean) newValue));
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostDetailsPreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostDetailsPreferenceFragment.java
new file mode 100644
index 00000000..2e0db830
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostDetailsPreferenceFragment.java
@@ -0,0 +1,18 @@
+package ml.docilealligator.infinityforreddit.settings;
+
+import android.os.Bundle;
+
+import androidx.preference.PreferenceFragmentCompat;
+import androidx.preference.PreferenceManager;
+
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
+
+public class PostDetailsPreferenceFragment extends PreferenceFragmentCompat {
+ @Override
+ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
+ PreferenceManager preferenceManager = getPreferenceManager();
+ preferenceManager.setSharedPreferencesName(SharedPreferencesUtils.POST_DETAILS_SHARED_PREFERENCES_FILE);
+ setPreferencesFromResource(R.xml.post_details_preferences, rootKey);
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostPreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostPreferenceFragment.java
index c45a2c1a..5b508a96 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostPreferenceFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/PostPreferenceFragment.java
@@ -11,7 +11,9 @@ import org.greenrobot.eventbus.EventBus;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.events.ChangeCompactLayoutToolbarHiddenByDefaultEvent;
+import ml.docilealligator.infinityforreddit.events.ChangeDefaultLinkPostLayoutEvent;
import ml.docilealligator.infinityforreddit.events.ChangeDefaultPostLayoutEvent;
+import ml.docilealligator.infinityforreddit.events.ChangeHidePostFlairEvent;
import ml.docilealligator.infinityforreddit.events.ChangeHidePostTypeEvent;
import ml.docilealligator.infinityforreddit.events.ChangeHideSubredditAndUserPrefixEvent;
import ml.docilealligator.infinityforreddit.events.ChangeHideTheNumberOfAwardsEvent;
@@ -30,12 +32,14 @@ public class PostPreferenceFragment extends PreferenceFragmentCompat {
setPreferencesFromResource(R.xml.post_preferences, rootKey);
ListPreference defaultPostLayoutList = findPreference(SharedPreferencesUtils.DEFAULT_POST_LAYOUT_KEY);
+ ListPreference defaultLinkPostLayoutList = findPreference(SharedPreferencesUtils.DEFAULT_LINK_POST_LAYOUT_KEY);
SwitchPreference showDividerInCompactLayoutSwitch = findPreference(SharedPreferencesUtils.SHOW_DIVIDER_IN_COMPACT_LAYOUT);
SwitchPreference showThumbnailOnTheRightInCompactLayoutSwitch = findPreference(SharedPreferencesUtils.SHOW_THUMBNAIL_ON_THE_LEFT_IN_COMPACT_LAYOUT);
SwitchPreference showAbsoluteNumberOfVotesSwitch = findPreference(SharedPreferencesUtils.SHOW_ABSOLUTE_NUMBER_OF_VOTES);
SwitchPreference longPressToHideToolbarInCompactLayoutSwitch = findPreference(SharedPreferencesUtils.LONG_PRESS_TO_HIDE_TOOLBAR_IN_COMPACT_LAYOUT);
SwitchPreference postCompactLayoutToolbarHiddenByDefaultSwitch = findPreference(SharedPreferencesUtils.POST_COMPACT_LAYOUT_TOOLBAR_HIDDEN_BY_DEFAULT);
SwitchPreference hidePostTypeSwitch = findPreference(SharedPreferencesUtils.HIDE_POST_TYPE);
+ SwitchPreference hidePostFlairSwitch = findPreference(SharedPreferencesUtils.HIDE_POST_FLAIR);
SwitchPreference hideTheNumberOfAwardsSwitch = findPreference(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_AWARDS);
SwitchPreference hideSubredditAndUserPrefixSwitch = findPreference(SharedPreferencesUtils.HIDE_SUBREDDIT_AND_USER_PREFIX);
SwitchPreference hideTheNumberOfVotesSwitch = findPreference(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_VOTES);
@@ -48,6 +52,13 @@ public class PostPreferenceFragment extends PreferenceFragmentCompat {
});
}
+ if (defaultLinkPostLayoutList != null) {
+ defaultLinkPostLayoutList.setOnPreferenceChangeListener((preference, newValue) -> {
+ EventBus.getDefault().post(new ChangeDefaultLinkPostLayoutEvent(Integer.parseInt((String) newValue)));
+ return true;
+ });
+ }
+
if (showDividerInCompactLayoutSwitch != null) {
showDividerInCompactLayoutSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
EventBus.getDefault().post(new ShowDividerInCompactLayoutPreferenceEvent((Boolean) newValue));
@@ -90,6 +101,13 @@ public class PostPreferenceFragment extends PreferenceFragmentCompat {
});
}
+ if (hidePostFlairSwitch != null) {
+ hidePostFlairSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
+ EventBus.getDefault().post(new ChangeHidePostFlairEvent((Boolean) newValue));
+ return true;
+ });
+ }
+
if (hideTheNumberOfAwardsSwitch != null) {
hideTheNumberOfAwardsSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
EventBus.getDefault().post(new ChangeHideTheNumberOfAwardsEvent((Boolean) newValue));
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/SecurityPreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/SecurityPreferenceFragment.java
index cb6917c8..c4dd2b16 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/SecurityPreferenceFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/SecurityPreferenceFragment.java
@@ -1,5 +1,8 @@
package ml.docilealligator.infinityforreddit.settings;
+import static androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG;
+import static androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL;
+
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
@@ -18,14 +21,12 @@ import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
-import ml.docilealligator.infinityforreddit.events.ChangeRequireAuthToAccountSectionEvent;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.events.ChangeRequireAuthToAccountSectionEvent;
+import ml.docilealligator.infinityforreddit.events.ToggleSecureModeEvent;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
-import static androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG;
-import static androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL;
-
public class SecurityPreferenceFragment extends PreferenceFragmentCompat {
private AppCompatActivity activity;
@@ -40,6 +41,7 @@ public class SecurityPreferenceFragment extends PreferenceFragmentCompat {
((Infinity) activity.getApplication()).getAppComponent().inject(this);
SwitchPreference requireAuthToAccountSectionSwitch = findPreference(SharedPreferencesUtils.REQUIRE_AUTHENTICATION_TO_GO_TO_ACCOUNT_SECTION_IN_NAVIGATION_DRAWER);
+ SwitchPreference secureModeSwitch = findPreference(SharedPreferencesUtils.SECURE_MODE);
if (requireAuthToAccountSectionSwitch != null) {
requireAuthToAccountSectionSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
@@ -47,6 +49,13 @@ public class SecurityPreferenceFragment extends PreferenceFragmentCompat {
return true;
});
}
+
+ if (secureModeSwitch != null) {
+ secureModeSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
+ EventBus.getDefault().post(new ToggleSecureModeEvent((Boolean) newValue));
+ return true;
+ });
+ }
}
@Override
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/ThemePreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/ThemePreferenceFragment.java
index fba59d25..0e0a8c7d 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/ThemePreferenceFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/ThemePreferenceFragment.java
@@ -1,10 +1,17 @@
package ml.docilealligator.infinityforreddit.settings;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
+import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
+
import android.content.Context;
import android.content.Intent;
+import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
+import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
@@ -19,24 +26,23 @@ import androidx.preference.SwitchPreference;
import org.greenrobot.eventbus.EventBus;
+import java.util.concurrent.Executor;
+
import javax.inject.Inject;
+import javax.inject.Named;
+import ml.docilealligator.infinityforreddit.Infinity;
+import ml.docilealligator.infinityforreddit.R;
+import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.activities.CustomThemeListingActivity;
import ml.docilealligator.infinityforreddit.activities.CustomizeThemeActivity;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeViewModel;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
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.utils.CustomThemeSharedPreferencesUtils;
+import ml.docilealligator.infinityforreddit.utils.MaterialYouUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
-import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
-
/**
* A simple {@link Fragment} subclass.
*/
@@ -44,9 +50,23 @@ public class ThemePreferenceFragment extends PreferenceFragmentCompat {
private AppCompatActivity activity;
@Inject
+ @Named("default")
+ SharedPreferences sharedPreferences;
+ @Inject
+ @Named("light_theme")
+ SharedPreferences lightThemeSharedPreferences;
+ @Inject
+ @Named("dark_theme")
+ SharedPreferences darkThemeSharedPreferences;
+ @Inject
+ @Named("amoled_theme")
+ SharedPreferences amoledThemeSharedPreferences;
+ @Inject
RedditDataRoomDatabase redditDataRoomDatabase;
@Inject
CustomThemeWrapper customThemeWrapper;
+ @Inject
+ Executor executor;
public CustomThemeViewModel customThemeViewModel;
@Override
@@ -61,6 +81,8 @@ public class ThemePreferenceFragment extends PreferenceFragmentCompat {
Preference customizeDarkThemePreference = findPreference(SharedPreferencesUtils.CUSTOMIZE_DARK_THEME);
Preference customizeAmoledThemePreference = findPreference(SharedPreferencesUtils.CUSTOMIZE_AMOLED_THEME);
Preference selectAndCustomizeThemePreference = findPreference(SharedPreferencesUtils.MANAGE_THEMES);
+ SwitchPreference enableMaterialYouSwitchPreference = findPreference(SharedPreferencesUtils.ENABLE_MATERIAL_YOU);
+ Preference applyMaterialYouPreference = findPreference(SharedPreferencesUtils.APPLY_MATERIAL_YOU);
boolean systemDefault = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
if (themePreference != null && amoledDarkSwitch != null) {
@@ -151,6 +173,32 @@ public class ThemePreferenceFragment extends PreferenceFragmentCompat {
});
}
+ if (enableMaterialYouSwitchPreference != null && applyMaterialYouPreference != null) {
+ applyMaterialYouPreference.setVisible(
+ sharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_MATERIAL_YOU, false));
+
+ enableMaterialYouSwitchPreference.setOnPreferenceChangeListener((preference, newValue) -> {
+ if ((Boolean) newValue) {
+ MaterialYouUtils.changeTheme(activity, executor, new Handler(),
+ redditDataRoomDatabase, customThemeWrapper,
+ lightThemeSharedPreferences, darkThemeSharedPreferences,
+ amoledThemeSharedPreferences, null);
+ applyMaterialYouPreference.setVisible(true);
+ } else {
+ applyMaterialYouPreference.setVisible(false);
+ }
+ return true;
+ });
+
+ applyMaterialYouPreference.setOnPreferenceClickListener(preference -> {
+ MaterialYouUtils.changeTheme(activity, executor, new Handler(),
+ redditDataRoomDatabase, customThemeWrapper,
+ lightThemeSharedPreferences, darkThemeSharedPreferences,
+ amoledThemeSharedPreferences, null);
+ return true;
+ });
+ }
+
customThemeViewModel = new ViewModelProvider(this,
new CustomThemeViewModel.Factory(redditDataRoomDatabase))
.get(CustomThemeViewModel.class);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/Translation.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/Translation.java
index 84b8bd11..53ca6735 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/Translation.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/Translation.java
@@ -18,30 +18,31 @@ public class Translation {
public static ArrayList<Translation> getTranslationContributors() {
ArrayList<Translation> translationContributors = new ArrayList<>();
translationContributors.add(new Translation("български", "Iliqiliev373, zerw, Кристиян", R.drawable.flag_bulgaria));
- translationContributors.add(new Translation("简体中文", "1, 3273676671, AaronFeng, Angela Thayer, Bitlabwzh, cdggqa, deluxghost, Dwhite, Gloria, History_exe, Justin, Ray, Steps, Tunicar, wert", R.drawable.flag_china));
- translationContributors.add(new Translation("繁體中文", "1, Angela Thayer, Ray", R.drawable.flag_china));
- translationContributors.add(new Translation("Hrvatski", "Josip", R.drawable.flag_croatia));
+ translationContributors.add(new Translation("简体中文", "1, 3273676671, AaronFeng, Angela Thayer, Bitlabwzh, cdggqa, deluxghost, Dwhite, Gloria, gzwoyikythba, History_exe, Justin, Ray, Steps, Tunicar, wert", R.drawable.flag_china));
+ translationContributors.add(new Translation("繁體中文", "1, Angela Thayer, Hbhuh, Ray", R.drawable.flag_china));
+ translationContributors.add(new Translation("Hrvatski", "Andrej Ivanusec, Josip", R.drawable.flag_croatia));
translationContributors.add(new Translation("Nederlands", "KevinHF, Khawkfist, Mert", R.drawable.flag_netherlands));
translationContributors.add(new Translation("Esperanto", "AnimatorzPolski", -1));
translationContributors.add(new Translation("Française", "367, Darlene Sonalder, escatrag, Finn Olmsted, Imperator, Johan, Kerim Demirkaynak, oursonbleu, Owen, pinembour", R.drawable.flag_france));
- translationContributors.add(new Translation("Deutsche", "adth03, ducc1, Jan, Joe, Jorge, Kerim Demirkaynak, Netto Hikari, Nikodiamond3, NotABot34, translatewingman, translatorwiz", R.drawable.flag_germany));
+ translationContributors.add(new Translation("Deutsche", "adth03, ducc1, Jan, Joe, Jorge, Kerim Demirkaynak, Lm41, Netto Hikari, Nikodiamond3, NotABot34, Tischleindeckdich, translatewingman, translatorwiz", R.drawable.flag_germany));
translationContributors.add(new Translation("Ελληνικά", "fresh, Marios, Viktor", R.drawable.flag_greece));
+ translationContributors.add(new Translation("עִברִית", "Yuval", R.drawable.flag_israel));
translationContributors.add(new Translation("हिंदी", "a, Arya, charu, EnArvy, Harshit S Lawaniya, Mrigendra Bhandari, Nikhilcaddilac, prat, raghav, Sachin, Ved", R.drawable.flag_india));
- translationContributors.add(new Translation("Magyar", "Balázs, Bro momento, ekaktusz, Zoltan", R.drawable.flag_hungary));
- translationContributors.add(new Translation("Italiana", "Daniele Basso, DanOlivaw, Enri. braga, Gianni00palmieri, Gillauino, Giovanni, Giovanni Donisi, Matisse, Simoneg. work, ztiaa", R.drawable.flag_italy));
+ translationContributors.add(new Translation("Magyar", "Balázs, Bro momento, ekaktusz, trebron, Zoltan", R.drawable.flag_hungary));
+ translationContributors.add(new Translation("Italiana", "Daniele Basso, DanOlivaw, Enri. braga, Gianni00palmieri, Gillauino, Gio. gavio01, Giovanni, Giovanni Donisi, Lorenzo, Matisse, Simoneg. work, ztiaa", R.drawable.flag_italy));
translationContributors.add(new Translation("日本語", "Hira, Issa, Kerim Demirkaynak, Mrigendra Bhandari, Ryan", R.drawable.flag_japan));
translationContributors.add(new Translation("한국어", "noname", R.drawable.flag_south_korea));
translationContributors.add(new Translation("norsk", "", R.drawable.flag_norway));
- translationContributors.add(new Translation("Polskie", "Chupacabra, Erax, Kajetan, Maks, quark", R.drawable.flag_poland));
+ translationContributors.add(new Translation("Polskie", "Chupacabra, Erax, Kajetan, Maks, quark, ultrakox", R.drawable.flag_poland));
translationContributors.add(new Translation("Português", "., Bruno Guerreiro, Gabriel, Henry, Lucas, Ricky", R.drawable.flag_portugal));
- translationContributors.add(new Translation("Português (BR)", "., Asfuri, Davy, Laura Vasconcellos Pereira Felippe, luccipriano, Raul S., Ricardo, Ricky, Super_Iguanna, T. tony. br01, vsc", R.drawable.flag_brazil));
- translationContributors.add(new Translation("Română", "Loading Official", R.drawable.flag_romania));
- translationContributors.add(new Translation("русский язык", "Angela Thayer, Arseniy Tsekh, aveblazer, CaZzzer, Coolant, Draer, elena, flexagoon, Georgiy, Overseen, Vova", R.drawable.flag_russia));
+ translationContributors.add(new Translation("Português (BR)", "., Asfuri, Davy, Júlia Angst Coelho, John Seila, Laura Vasconcellos Pereira Felippe, luccipriano, Raul S., Ricardo, Ricky, Super_Iguanna, T. tony. br01, vsc", R.drawable.flag_brazil));
+ translationContributors.add(new Translation("Română", "Loading Official, RabdăInimăȘiTace", R.drawable.flag_romania));
+ translationContributors.add(new Translation("русский язык", "Angela Thayer, Anon, Arseniy Tsekh, aveblazer, CaZzzer, Coolant, Craysy, Draer, elena, flexagoon, Georgiy, Overseen, Stambro, Tysontl2007, Vova", R.drawable.flag_russia));
translationContributors.add(new Translation("Soomaali", "Nadir Nour", R.drawable.flag_somalia));
- translationContributors.add(new Translation("Español", "Alejandro, Alfredo, Angel, Angela Thayer, Gaynus, Jorge, Luis Antonio, Miguel, mvstermoe, Nana Snixx, Sergio, Sofia Flores, Theofficialdork", R.drawable.flag_spain));
+ translationContributors.add(new Translation("Español", "Agustin, Alejandro, Alfredo, Angel, Angela Thayer, Canutolab, Gaynus, Jorge, Luis Antonio, Meh, Miguel, mvstermoe, Nana Snixx, Sergio, Sofia Flores, Theofficialdork, Tirso Carranza", R.drawable.flag_spain));
translationContributors.add(new Translation("svenska", "Marcus Nordberg", R.drawable.flag_sweden));
translationContributors.add(new Translation("Türkçe", "adth03, Berk Bakır \"Faoiltiarna\", Emir481, Faoiltiarna, Kerim Demirkaynak, Mehmet Yavuz, Mert, Serif", R.drawable.flag_turkey));
- translationContributors.add(new Translation("Tiếng Việt", "Kai, Laezzy, Lmao, Ryan, viecdet69", R.drawable.flag_vietnam));
+ translationContributors.add(new Translation("Tiếng Việt", "bruh, Kai, Laezzy, Lmao, Ryan, viecdet69", R.drawable.flag_vietnam));
return translationContributors;
}
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/TranslationFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/TranslationFragment.java
index a0f9cd1e..62f5c50a 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/TranslationFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/TranslationFragment.java
@@ -9,7 +9,6 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
-import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import javax.inject.Inject;
@@ -44,7 +43,6 @@ public class TranslationFragment extends Fragment {
ButterKnife.bind(this, rootView);
TranslationFragmentRecyclerViewAdapter adapter = new TranslationFragmentRecyclerViewAdapter(activity, customThemeWrapper);
- recyclerView.setLayoutManager(new LinearLayoutManager(activity));
recyclerView.setAdapter(adapter);
return rootView;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/VideoPreferenceFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/VideoPreferenceFragment.java
index f7941534..6a89dcd6 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/settings/VideoPreferenceFragment.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/settings/VideoPreferenceFragment.java
@@ -22,6 +22,7 @@ import javax.inject.Named;
import ml.docilealligator.infinityforreddit.events.ChangeAutoplayNsfwVideosEvent;
import ml.docilealligator.infinityforreddit.events.ChangeMuteAutoplayingVideosEvent;
import ml.docilealligator.infinityforreddit.events.ChangeMuteNSFWVideoEvent;
+import ml.docilealligator.infinityforreddit.events.ChangeRememberMutingOptionInPostFeedEvent;
import ml.docilealligator.infinityforreddit.events.ChangeStartAutoplayVisibleAreaOffsetEvent;
import ml.docilealligator.infinityforreddit.events.ChangeVideoAutoplayEvent;
import ml.docilealligator.infinityforreddit.Infinity;
@@ -43,6 +44,7 @@ public class VideoPreferenceFragment extends PreferenceFragmentCompat {
ListPreference videoAutoplayListPreference = findPreference(SharedPreferencesUtils.VIDEO_AUTOPLAY);
SwitchPreference muteAutoplayingVideosSwitchPreference = findPreference(SharedPreferencesUtils.MUTE_AUTOPLAYING_VIDEOS);
+ SwitchPreference rememberMutingOptionInPostFeedSwitchPreference = findPreference(SharedPreferencesUtils.REMEMBER_MUTING_OPTION_IN_POST_FEED);
SwitchPreference muteNSFWVideosSwitchPreference = findPreference(SharedPreferencesUtils.MUTE_NSFW_VIDEO);
SwitchPreference autoplayNsfwVideosSwitchPreference = findPreference(SharedPreferencesUtils.AUTOPLAY_NSFW_VIDEOS);
SeekBarPreference startAutoplayVisibleAreaOffsetPortrait = findPreference(SharedPreferencesUtils.START_AUTOPLAY_VISIBLE_AREA_OFFSET_PORTRAIT);
@@ -74,6 +76,13 @@ public class VideoPreferenceFragment extends PreferenceFragmentCompat {
});
}
+ if (rememberMutingOptionInPostFeedSwitchPreference != null) {
+ rememberMutingOptionInPostFeedSwitchPreference.setOnPreferenceChangeListener((preference, newValue) -> {
+ EventBus.getDefault().post(new ChangeRememberMutingOptionInPostFeedEvent((Boolean) newValue));
+ return true;
+ });
+ }
+
int orientation = getResources().getConfiguration().orientation;
if (startAutoplayVisibleAreaOffsetPortrait != null) {
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/ParseSubredditData.java b/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/ParseSubredditData.java
index d673647d..694d5900 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/ParseSubredditData.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/ParseSubredditData.java
@@ -13,12 +13,12 @@ import java.util.ArrayList;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
-class ParseSubredditData {
- static void parseSubredditData(String response, ParseSubredditDataListener parseSubredditDataListener) {
+public class ParseSubredditData {
+ public static void parseSubredditData(String response, ParseSubredditDataListener parseSubredditDataListener) {
new ParseSubredditDataAsyncTask(response, parseSubredditDataListener).execute();
}
- static void parseSubredditListingData(String response, boolean nsfw, ParseSubredditListingDataListener parseSubredditListingDataListener) {
+ public static void parseSubredditListingData(String response, boolean nsfw, ParseSubredditListingDataListener parseSubredditListingDataListener) {
new ParseSubredditListingDataAsyncTask(response, nsfw, parseSubredditListingDataListener).execute();
}
@@ -70,7 +70,7 @@ class ParseSubredditData {
void onParseSubredditDataFail();
}
- interface ParseSubredditListingDataListener {
+ public interface ParseSubredditListingDataListener {
void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after);
void onParseSubredditListingDataFail();
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/SubredditSubscription.java b/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/SubredditSubscription.java
index 7302dd6a..242edf18 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/SubredditSubscription.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/subreddit/SubredditSubscription.java
@@ -9,6 +9,7 @@ import java.util.Map;
import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
+import ml.docilealligator.infinityforreddit.account.Account;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
@@ -129,7 +130,7 @@ public class SubredditSubscription {
subredditData.getIconUrl(), accountName, false);
if (accountName.equals("-")) {
if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) {
- redditDataRoomDatabase.accountDao().insertAnonymousAccount();
+ redditDataRoomDatabase.accountDao().insert(Account.getAnonymousAccount());
}
}
redditDataRoomDatabase.subscribedSubredditDao().insert(subscribedSubredditData);
@@ -144,7 +145,7 @@ public class SubredditSubscription {
executor.execute(() -> {
if (accountName.equals("-")) {
if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) {
- redditDataRoomDatabase.accountDao().insertAnonymousAccount();
+ redditDataRoomDatabase.accountDao().insert(Account.getAnonymousAccount());
}
}
redditDataRoomDatabase.subscribedSubredditDao().deleteSubscribedSubreddit(subredditName, accountName);
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/APIUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/APIUtils.java
index fb49b49e..465a31eb 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/APIUtils.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/APIUtils.java
@@ -22,6 +22,7 @@ public class APIUtils {
public static final String REDGIFS_API_BASE_URI = "https://api.redgifs.com/v1/gfycats/";
public static final String IMGUR_API_BASE_URI = "https://api.imgur.com/3/";
public static final String PUSHSHIFT_API_BASE_URI = "https://api.pushshift.io/";
+ public static final String STRAPI_BASE_URI = "https://strapi.reddit.com";
public static final String CLIENT_ID_KEY = "client_id";
public static final String CLIENT_ID = "NOe2iKrPPzwscA";
@@ -72,6 +73,7 @@ public class APIUtils {
public static final String SPOILER_KEY = "spoiler";
public static final String NSFW_KEY = "nsfw";
public static final String CROSSPOST_FULLNAME_KEY = "crosspost_fullname";
+ public static final String SEND_REPLIES_KEY = "sendreplies";
public static final String KIND_KEY = "kind";
public static final String KIND_SELF = "self";
public static final String KIND_LINK = "link";
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/JSONUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/JSONUtils.java
index 8ba23bf4..b76f198e 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/JSONUtils.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/JSONUtils.java
@@ -135,4 +135,40 @@ public class JSONUtils {
public static final String WEBM_URL_KEY = "webmUrl";
public static final String UPVOTE_RATIO_KEY = "upvote_ratio";
public static final String INBOX_COUNT_KEY = "inbox_count";
+ public static final String NEXT_CURSOR_KEY = "next_cursor";
+ public static final String POST_KEY = "post";
+ public static final String STYLES_KEY = "styles";
+ public static final String AUTHOR_INFO_KEY= "authorInfo";
+ public static final String VOTE_STATE_KEY = "voteState";
+ public static final String UPVOTE_RATIO_CAMEL_CASE_KEY = "upvoteRatio";
+ public static final String OUTBOUND_LINK_KEY = "outboundLink";
+ public static final String IS_NSFW_KEY = "isNsfw";
+ public static final String IS_LOCKED_KEY = "isLocked";
+ public static final String IS_ARCHIVED_KEY = "isArchived";
+ public static final String IS_SPOILER = "isSpoiler";
+ public static final String SUGGESTED_COMMENT_SORT_CAMEL_CASE_KEY = "suggestedCommentSort";
+ public static final String LIVE_COMMENTS_WEBSOCKET_KEY = "liveCommentsWebsocket";
+ public static final String ICON_KEY = "icon";
+ public static final String STREAM_KEY = "stream";
+ public static final String STREAM_ID_KEY = "stream_id";
+ public static final String THUMBNAIL_KEY = "thumbnail";
+ public static final String PUBLISH_AT_KEY = "publish_at";
+ public static final String STATE_KEY = "state";
+ public static final String UPVOTES_KEY = "upvotes";
+ public static final String DOWNVOTES_KEY = "downvotes";
+ public static final String UNIQUE_WATCHERS_KEY = "unique_watchers";
+ public static final String CONTINUOUS_WATCHERS_KEY = "continuous_watchers";
+ public static final String TOTAL_CONTINUOUS_WATCHERS_KEY = "total_continuous_watchers";
+ public static final String CHAT_DISABLED_KEY = "chat_disabled";
+ public static final String BROADCAST_TIME_KEY = "broadcast_time";
+ public static final String ESTIMATED_REMAINING_TIME_KEY = "estimated_remaining_time";
+ public static final String PAYLOAD_KEY = "payload";
+ public static final String AUTHOR_ICON_IMAGE = "author_icon_img";
+ public static final String ASSET_KEY = "asset";
+ public static final String ASSET_ID_KEY = "asset_id";
+ public static final String TRENDING_SEARCHES_KEY = "trending_searches";
+ public static final String QUERY_STRING_KEY = "query_string";
+ public static final String DISPLAY_STRING_KEY = "display_string";
+ public static final String RESULTS_KEY = "results";
+ public static final String CONTENT_MD_KEY = "content_md";
}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/MaterialYouUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/MaterialYouUtils.java
new file mode 100644
index 00000000..d470e1d0
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/MaterialYouUtils.java
@@ -0,0 +1,155 @@
+package ml.docilealligator.infinityforreddit.utils;
+
+import android.app.WallpaperColors;
+import android.app.WallpaperManager;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.graphics.Color;
+import android.os.Build;
+import android.os.Handler;
+
+import androidx.annotation.ColorInt;
+import androidx.annotation.Nullable;
+
+import org.greenrobot.eventbus.EventBus;
+
+import java.util.concurrent.Executor;
+
+import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
+import ml.docilealligator.infinityforreddit.customtheme.CustomTheme;
+import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
+import ml.docilealligator.infinityforreddit.events.RecreateActivityEvent;
+
+public class MaterialYouUtils {
+ public interface CheckThemeNameListener {
+ void themeNotExists();
+ void themeExists();
+ }
+
+ public static void checkThemeName(Executor executor, Handler handler,
+ RedditDataRoomDatabase redditDataRoomDatabase,
+ CheckThemeNameListener checkThemeNameListener) {
+ executor.execute(() -> {
+ if (redditDataRoomDatabase.customThemeDao().getCustomTheme("Material You") != null
+ || redditDataRoomDatabase.customThemeDao().getCustomTheme("Material You Dark") != null
+ || redditDataRoomDatabase.customThemeDao().getCustomTheme("Material You Amoled") != null) {
+ handler.post(checkThemeNameListener::themeExists);
+ } else {
+ handler.post(checkThemeNameListener::themeNotExists);
+ }
+ });
+ }
+
+ public static void changeTheme(Context context, Executor executor, Handler handler,
+ RedditDataRoomDatabase redditDataRoomDatabase,
+ CustomThemeWrapper customThemeWrapper,
+ SharedPreferences lightThemeSharedPreferences,
+ SharedPreferences darkThemeSharedPreferences,
+ SharedPreferences amoledThemeSharedPreferences,
+ @Nullable MaterialYouListener materialYouListener) {
+ executor.execute(() -> {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
+ WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
+ WallpaperColors wallpaperColors = wallpaperManager.getWallpaperColors(WallpaperManager.FLAG_SYSTEM);
+
+ if (wallpaperColors != null) {
+ int colorPrimaryInt = lightenColor(wallpaperColors.getPrimaryColor().toArgb(), 0.4);
+ int colorPrimaryDarkInt = darkenColor(colorPrimaryInt, 0.3);
+ int backgroundColor = lightenColor(colorPrimaryInt, 0.2);
+ int cardViewBackgroundColor = lightenColor(colorPrimaryInt, 0.6);
+ Color colorAccent = wallpaperColors.getSecondaryColor();
+ int colorAccentInt = lightenColor(colorAccent == null ? customThemeWrapper.getColorAccent() : colorAccent.toArgb(), 0.4);
+
+ int colorPrimaryAppropriateTextColor = getAppropriateTextColor(colorPrimaryInt);
+ int backgroundColorAppropriateTextColor = getAppropriateTextColor(backgroundColor);
+
+ CustomTheme lightTheme = CustomThemeWrapper.getIndigo(context);
+ CustomTheme darkTheme = CustomThemeWrapper.getIndigoDark(context);
+ CustomTheme amoledTheme = CustomThemeWrapper.getIndigoAmoled(context);
+
+ lightTheme.colorPrimary = colorPrimaryInt;
+ lightTheme.colorPrimaryDark = colorPrimaryDarkInt;
+ lightTheme.colorAccent = colorAccentInt;
+ lightTheme.colorPrimaryLightTheme = colorPrimaryInt;
+ lightTheme.backgroundColor = backgroundColor;
+ lightTheme.cardViewBackgroundColor = cardViewBackgroundColor;
+ lightTheme.commentBackgroundColor = cardViewBackgroundColor;
+ lightTheme.awardedCommentBackgroundColor = cardViewBackgroundColor;
+ lightTheme.bottomAppBarBackgroundColor = colorPrimaryInt;
+ lightTheme.navBarColor = colorPrimaryInt;
+ lightTheme.primaryTextColor = backgroundColorAppropriateTextColor;
+ lightTheme.secondaryTextColor = backgroundColorAppropriateTextColor == Color.BLACK ? Color.parseColor("#8A000000") : Color.parseColor("#B3FFFFFF");
+ lightTheme.bottomAppBarIconColor = colorPrimaryAppropriateTextColor;
+ lightTheme.primaryIconColor = backgroundColorAppropriateTextColor;
+ lightTheme.fabIconColor = colorPrimaryAppropriateTextColor;
+ lightTheme.toolbarPrimaryTextAndIconColor = colorPrimaryAppropriateTextColor;
+ lightTheme.toolbarSecondaryTextColor = colorPrimaryAppropriateTextColor;
+ lightTheme.tabLayoutWithCollapsedCollapsingToolbarTabIndicator = colorPrimaryAppropriateTextColor;
+ lightTheme.tabLayoutWithCollapsedCollapsingToolbarTextColor = colorPrimaryAppropriateTextColor;
+ lightTheme.tabLayoutWithCollapsedCollapsingToolbarTabBackground = colorPrimaryInt;
+ lightTheme.tabLayoutWithExpandedCollapsingToolbarTabBackground = colorPrimaryInt;
+ lightTheme.tabLayoutWithExpandedCollapsingToolbarTabIndicator = colorPrimaryAppropriateTextColor;
+ lightTheme.tabLayoutWithExpandedCollapsingToolbarTextColor = colorPrimaryAppropriateTextColor;
+ lightTheme.circularProgressBarBackground = colorPrimaryInt;
+ lightTheme.dividerColor = backgroundColorAppropriateTextColor == Color.BLACK ? Color.parseColor("#E0E0E0") : Color.parseColor("69666C");
+ lightTheme.isLightStatusBar = colorPrimaryAppropriateTextColor == Color.BLACK;
+ lightTheme.isChangeStatusBarIconColorAfterToolbarCollapsedInImmersiveInterface =
+ (lightTheme.isLightStatusBar && getAppropriateTextColor(cardViewBackgroundColor) == Color.WHITE)
+ || (!lightTheme.isLightStatusBar && getAppropriateTextColor(cardViewBackgroundColor) == Color.BLACK);
+ lightTheme.name = "Material You";
+
+ darkTheme.colorAccent = colorPrimaryInt;
+ darkTheme.colorPrimaryLightTheme = colorPrimaryInt;
+ darkTheme.name = "Material You Dark";
+
+ amoledTheme.colorAccent = colorPrimaryInt;
+ amoledTheme.colorPrimaryLightTheme = colorPrimaryInt;
+ amoledTheme.name = "Material You Amoled";
+
+ redditDataRoomDatabase.customThemeDao().unsetLightTheme();
+ redditDataRoomDatabase.customThemeDao().unsetDarkTheme();
+ redditDataRoomDatabase.customThemeDao().unsetAmoledTheme();
+
+ redditDataRoomDatabase.customThemeDao().insert(lightTheme);
+ redditDataRoomDatabase.customThemeDao().insert(darkTheme);
+ redditDataRoomDatabase.customThemeDao().insert(amoledTheme);
+
+ CustomThemeSharedPreferencesUtils.insertThemeToSharedPreferences(lightTheme, lightThemeSharedPreferences);
+ CustomThemeSharedPreferencesUtils.insertThemeToSharedPreferences(darkTheme, darkThemeSharedPreferences);
+ CustomThemeSharedPreferencesUtils.insertThemeToSharedPreferences(amoledTheme, amoledThemeSharedPreferences);
+
+ handler.post(() -> {
+ if (materialYouListener != null) {
+ materialYouListener.applied();
+ }
+ EventBus.getDefault().post(new RecreateActivityEvent());
+ });
+ }
+ }
+ });
+ }
+
+ private static int lightenColor(int color, double ratio) {
+ return Color.argb(Color.alpha(color), (int) (Color.red(color) + (255 - Color.red(color)) * ratio),
+ (int) (Color.green(color) + (255 - Color.green(color)) * ratio),
+ (int) (Color.blue(color) + (255 - Color.blue(color)) * ratio));
+ }
+
+ private static int darkenColor(int color, double ratio) {
+ return Color.argb(Color.alpha(color), (int) (Color.red(color) * (1 - ratio)),
+ (int) (Color.green(color) * (1 - ratio)),
+ (int) (Color.blue(color) * (1 - ratio)));
+
+ }
+
+ @ColorInt
+ public static int getAppropriateTextColor(@ColorInt int color) {
+ // Counting the perceptive luminance - human eye favors green color...
+ double luminance = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255;
+ return luminance < 0.5 ? Color.BLACK : Color.WHITE;
+ }
+
+ public interface MaterialYouListener {
+ void applied();
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/NotificationUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/NotificationUtils.java
index 3c3255de..5552271f 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/NotificationUtils.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/NotificationUtils.java
@@ -22,11 +22,14 @@ public class NotificationUtils {
public static final String CHANNEL_DOWNLOAD_IMAGE = "Download Image";
public static final String CHANNEL_ID_DOWNLOAD_GIF = "download_gif";
public static final String CHANNEL_DOWNLOAD_GIF = "Download Gif";
+ public static final String CHANNEL_ID_MATERIAL_YOU = "material_you";
+ public static final String CHANNEL_MATERIAL_YOU = "Material You";
public static final int SUBMIT_POST_SERVICE_NOTIFICATION_ID = 10000;
public static final int DOWNLOAD_REDDIT_VIDEO_NOTIFICATION_ID = 20000;
public static final int DOWNLOAD_VIDEO_NOTIFICATION_ID = 30000;
public static final int DOWNLOAD_IMAGE_NOTIFICATION_ID = 40000;
public static final int DOWNLOAD_GIF_NOTIFICATION_ID = 50000;
+ public static final int MATERIAL_YOU_NOTIFICATION_ID = 60000;
private static final int SUMMARY_BASE_ID_UNREAD_MESSAGE = 0;
private static final int NOTIFICATION_BASE_ID_UNREAD_MESSAGE = 1;
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/SharedPreferencesUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/SharedPreferencesUtils.java
index dc585d93..f3247d99 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/SharedPreferencesUtils.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/SharedPreferencesUtils.java
@@ -87,6 +87,7 @@ public class SharedPreferencesUtils {
public static final String NUMBER_OF_COLUMNS_IN_POST_FEED_PORTRAIT_GALLERY_LAYOUT = "number_of_columns_in_post_feed_portrait_gallery_layout";
public static final String NUMBER_OF_COLUMNS_IN_POST_FEED_LANDSCAPE_GALLERY_LAYOUT = "number_of_columns_in_post_feed_landscape_gallery_layout";
public static final String SWIPE_RIGHT_TO_GO_BACK = "swipe_to_go_back_from_post_detail";
+ public static final String SWIPE_VERTICALLY_TO_GO_BACK_FROM_MEDIA = "swipe_vertically_to_go_back_from_media";
public static final String VOLUME_KEYS_NAVIGATE_COMMENTS = "volume_keys_navigate_comments";
public static final String VOLUME_KEYS_NAVIGATE_POSTS = "volume_keys_navigate_posts";
public static final String MUTE_VIDEO = "mute_video";
@@ -165,6 +166,7 @@ public class SharedPreferencesUtils {
public static final String USER_DEFAULT_SORT_TIME = "user_default_sort_time";
public static final String CLICK_TO_SHOW_MEDIA_IN_GALLERY_LAYOUT = "click_to_show_media_in_gallery_layout";
public static final String HIDE_POST_TYPE = "hide_post_type";
+ public static final String HIDE_POST_FLAIR = "hide_post_flair";
public static final String HIDE_THE_NUMBER_OF_AWARDS = "hide_the_number_of_awards";
public static final String HIDE_SUBREDDIT_AND_USER_PREFIX = "hide_subreddit_and_user_prefix";
public static final String HIDE_THE_NUMBER_OF_VOTES = "hide_the_number_of_votes";
@@ -177,6 +179,14 @@ public class SharedPreferencesUtils {
public static final String NUMBER_OF_COLUMNS_IN_POST_FEED_PORTRAIT_CARD_LAYOUT_2 = "number_of_columns_in_post_feed_portrait_card_layout_2";
public static final String NUMBER_OF_COLUMNS_IN_POST_FEED_LANDSCAPE_CARD_LAYOUT_2 = "number_of_columns_in_post_feed_landscape_card_layout_2";
public static final String DISABLE_NSFW_FOREVER = "disable_nsfw_forever";
+ public static final String SHOW_ONLY_ONE_COMMENT_LEVEL_INDICATOR = "show_only_one_comment_level_indicator";
+ public static final String ENABLE_MATERIAL_YOU = "enable_material_you";
+ public static final String APPLY_MATERIAL_YOU = "apply_material_you";
+ public static final String VIDEO_PLAYER_AUTOMATIC_LANDSCAPE_ORIENTATION = "video_player_automatic_landscape_orientation";
+ public static final String REMEMBER_MUTING_OPTION_IN_POST_FEED = "remember_muting_option_in_post_feed";
+ public static final String DEFAULT_LINK_POST_LAYOUT_KEY = "default_link_post_layout";
+ public static final String USE_BOTTOM_TOOLBAR_IN_MEDIA_VIEWER = "use_bottom_toolbar_in_media_viewer";
+ public static final String SECURE_MODE = "secure_mode";
public static final String DEFAULT_PREFERENCES_FILE = "ml.docilealligator.infinityforreddit_preferences";
public static final String MAIN_PAGE_TABS_SHARED_PREFERENCES_FILE = "ml.docilealligator.infinityforreddit.main_page_tabs";
@@ -202,6 +212,8 @@ public class SharedPreferencesUtils {
public static final int MAIN_PAGE_TAB_POST_TYPE_HIDDEN = 8;
public static final int MAIN_PAGE_TAB_POST_TYPE_SAVED = 9;
public static final int MAIN_PAGE_TAB_POST_TYPE_GILDED = 10;
+ public static final String MAIN_PAGE_SHOW_MULTIREDDITS = "_main_page_show_multireddits";
+ public static final String MAIN_PAGE_SHOW_FAVORITE_MULTIREDDITS = "_main_page_show_favorite_multireddits";
public static final String MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS = "_main_page_show_subscribed_subreddits";
public static final String MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS = "_main_page_show_favorite_subscribed_subreddits";
@@ -301,6 +313,7 @@ public class SharedPreferencesUtils {
public static final String NAVIGATION_DRAWER_SHARED_PREFERENCES_FILE = "ml.docilealligator.infinityforreddit.navigation_drawer";
public static final String COLLAPSE_ACCOUNT_SECTION = "collapse_account_section";
+ public static final String COLLAPSE_REDDIT_SECTION = "collapse_reddit_section";
public static final String COLLAPSE_POST_SECTION = "collapse_post_section";
public static final String COLLAPSE_PREFERENCES_SECTION = "collapse_preferences_section";
public static final String COLLAPSE_FAVORITE_SUBREDDITS_SECTION = "collapse_favorite_subreddits_section";
@@ -308,6 +321,10 @@ public class SharedPreferencesUtils {
public static final String HIDE_FAVORITE_SUBREDDITS_SECTION = "hide_favorite_subreddits_sections";
public static final String HIDE_SUBSCRIBED_SUBREDDITS_SECTIONS = "hide_subscribed_subreddits_sections";
+ public static final String POST_DETAILS_SHARED_PREFERENCES_FILE = "ml.docilealligator.infinityforreddit.post_details";
+ public static final String SEPARATE_POST_AND_COMMENTS_IN_PORTRAIT_MODE = "separate_post_and_comments_in_portrait_mode";
+ public static final String SEPARATE_POST_AND_COMMENTS_IN_LANDSCAPE_MODE = "separate_post_and_comments_in_landscape_mode";
+
//Legacy Settings
public static final String MAIN_PAGE_TAB_1_TITLE_LEGACY = "main_page_tab_1_title";
public static final String MAIN_PAGE_TAB_2_TITLE_LEGACY = "main_page_tab_2_title";
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/UploadImageUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/UploadImageUtils.java
new file mode 100644
index 00000000..c7b5f728
--- /dev/null
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/UploadImageUtils.java
@@ -0,0 +1,107 @@
+package ml.docilealligator.infinityforreddit.utils;
+
+import android.graphics.Bitmap;
+
+import androidx.annotation.Nullable;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlPullParserFactory;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.Map;
+
+import ml.docilealligator.infinityforreddit.apis.RedditAPI;
+import okhttp3.MediaType;
+import okhttp3.MultipartBody;
+import okhttp3.RequestBody;
+import retrofit2.Call;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+
+public class UploadImageUtils {
+ @Nullable
+ public static String uploadImage(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
+ String accessToken, Bitmap image) throws IOException, JSONException, XmlPullParserException {
+ return uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, image, false);
+ }
+
+ @Nullable
+ public static String uploadImage(Retrofit oauthRetrofit, Retrofit uploadMediaRetrofit,
+ String accessToken, Bitmap image, boolean returnResponseForGallerySubmission) throws IOException, JSONException, XmlPullParserException {
+ RedditAPI api = oauthRetrofit.create(RedditAPI.class);
+
+ Map<String, String> uploadImageParams = new HashMap<>();
+ uploadImageParams.put(APIUtils.FILEPATH_KEY, "post_image.jpg");
+ uploadImageParams.put(APIUtils.MIMETYPE_KEY, "image/jpeg");
+
+ Call<String> uploadImageCall = api.uploadImage(APIUtils.getOAuthHeader(accessToken), uploadImageParams);
+ 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()) {
+ if (returnResponseForGallerySubmission) {
+ return uploadImageResponse.body();
+ }
+ return parseXMLResponseFromAWS(uploadMediaToAWSResponse.body());
+ } else {
+ return "Error: " + uploadMediaToAWSResponse.code();
+ }
+ } else {
+ return "Error: " + uploadImageResponse.message();
+ }
+ }
+
+ @Nullable
+ public 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();
+ }
+ }
+ eventType = xmlPullParser.next();
+ }
+
+ return null;
+ }
+
+ public 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);
+
+ 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)));
+ }
+
+ return nameValuePairsMap;
+ }
+}
diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/Utils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/Utils.java
index 1044f49c..ad2b7405 100644
--- a/app/src/main/java/ml/docilealligator/infinityforreddit/utils/Utils.java
+++ b/app/src/main/java/ml/docilealligator/infinityforreddit/utils/Utils.java
@@ -1,32 +1,53 @@
package ml.docilealligator.infinityforreddit.utils;
import android.app.Activity;
+import android.content.ContentResolver;
import android.content.Context;
+import android.database.Cursor;
+import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
+import android.net.Uri;
import android.os.Build;
+import android.os.Handler;
+import android.provider.OpenableColumns;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
+import android.widget.EditText;
import android.widget.TextView;
+import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
+import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.text.HtmlCompat;
+import com.bumptech.glide.Glide;
+import com.google.android.material.snackbar.Snackbar;
+
+import org.json.JSONException;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.SortType;
+import ml.docilealligator.infinityforreddit.UploadedImage;
+import retrofit2.Retrofit;
public class Utils {
public static final int NETWORK_TYPE_OTHER = -1;
@@ -199,15 +220,17 @@ public class Utils {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network nw = connMgr.getActiveNetwork();
if (nw == null) return NETWORK_TYPE_OTHER;
- NetworkCapabilities actNw = connMgr.getNetworkCapabilities(nw);
- if (actNw != null) {
- if (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
- return NETWORK_TYPE_WIFI;
+ try {
+ NetworkCapabilities actNw = connMgr.getNetworkCapabilities(nw);
+ if (actNw != null) {
+ if (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
+ return NETWORK_TYPE_WIFI;
+ }
+ if (actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
+ return NETWORK_TYPE_CELLULAR;
+ }
}
- if (actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
- return NETWORK_TYPE_CELLULAR;
- }
- }
+ } catch (SecurityException ignore) {}
return NETWORK_TYPE_OTHER;
} else {
boolean isWifi = false;
@@ -290,6 +313,13 @@ public class Utils {
}
public static void hideKeyboard(Activity activity) {
+ /*if (activity.getCurrentFocus() == null || !(activity.getCurrentFocus() instanceof EditText)) {
+ editText.requestFocus();
+ }
+ InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
+ activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);*/
+
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (inputMethodManager != null && activity.getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
@@ -311,4 +341,61 @@ public class Utils {
return null;
}
+
+ public static void uploadImageToReddit(Context context, Executor executor, Retrofit oauthRetrofit,
+ Retrofit uploadMediaRetrofit, String accessToken, EditText editText,
+ CoordinatorLayout coordinatorLayout, Uri imageUri,
+ ArrayList<UploadedImage>uploadedImages) {
+ Toast.makeText(context, R.string.uploading_image, Toast.LENGTH_SHORT).show();
+ Handler handler = new Handler();
+ executor.execute(() -> {
+ try {
+ Bitmap bitmap = Glide.with(context).asBitmap().load(imageUri).submit().get();
+ String imageUrlOrError = UploadImageUtils.uploadImage(oauthRetrofit, uploadMediaRetrofit, accessToken, bitmap);
+ handler.post(() -> {
+ if (imageUrlOrError != null && !imageUrlOrError.startsWith("Error: ")) {
+ String fileName = Utils.getFileName(context, imageUri);
+ if (fileName == null) {
+ fileName = imageUrlOrError;
+ }
+ uploadedImages.add(new UploadedImage(fileName, imageUrlOrError));
+
+ int start = Math.max(editText.getSelectionStart(), 0);
+ int end = Math.max(editText.getSelectionEnd(), 0);
+ editText.getText().replace(Math.min(start, end), Math.max(start, end),
+ "[" + fileName + "](" + imageUrlOrError + ")",
+ 0, "[]()".length() + fileName.length() + imageUrlOrError.length());
+ Snackbar.make(coordinatorLayout, R.string.upload_image_success, Snackbar.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(context, R.string.upload_image_failed, Toast.LENGTH_LONG).show();
+ }
+ });
+ } catch (ExecutionException | InterruptedException e) {
+ e.printStackTrace();
+ handler.post(() -> Toast.makeText(context, R.string.get_image_bitmap_failed, Toast.LENGTH_LONG).show());
+ } catch (XmlPullParserException | JSONException | IOException e) {
+ e.printStackTrace();
+ handler.post(() -> Toast.makeText(context, R.string.error_processing_image, Toast.LENGTH_LONG).show());
+ }
+ });
+ }
+
+ @Nullable
+ public static String getFileName(Context context, Uri uri) {
+ ContentResolver contentResolver = context.getContentResolver();
+ if (contentResolver != null) {
+ Cursor cursor = contentResolver.query(uri, null, null, null, null);
+ if (cursor != null) {
+ int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
+ cursor.moveToFirst();
+ String fileName = cursor.getString(nameIndex);
+ if(fileName != null && fileName.contains(".")) {
+ fileName = fileName.substring(0, fileName.lastIndexOf('.'));
+ }
+ return fileName;
+ }
+ }
+
+ return null;
+ }
}