Add blocked thing listing activity

Added activity that displays the blocked users and communities
This commit is contained in:
Balazs Toldi 2023-08-11 20:09:34 +02:00
parent 016801419f
commit e2a15ab925
No known key found for this signature in database
GPG Key ID: 6C7D440036F99D58
34 changed files with 2299 additions and 40 deletions

View File

@ -402,6 +402,11 @@
android:label="@string/subscriptions" android:label="@string/subscriptions"
android:parentActivityName=".activities.MainActivity" android:parentActivityName=".activities.MainActivity"
android:theme="@style/AppTheme.Slidable" /> android:theme="@style/AppTheme.Slidable" />
<activity
android:name=".activities.BlockedThingListingActivity"
android:label="@string/blocks"
android:parentActivityName=".activities.MainActivity"
android:theme="@style/AppTheme.Slidable" />
<activity <activity
android:name=".activities.SubredditSelectionActivity" android:name=".activities.SubredditSelectionActivity"
android:label="@string/community_selection_activity_label" android:label="@string/community_selection_activity_label"

View File

@ -8,6 +8,7 @@ import dagger.BindsInstance;
import dagger.Component; import dagger.Component;
import eu.toldi.infinityforlemmy.activities.AccountPostsActivity; import eu.toldi.infinityforlemmy.activities.AccountPostsActivity;
import eu.toldi.infinityforlemmy.activities.AccountSavedThingActivity; import eu.toldi.infinityforlemmy.activities.AccountSavedThingActivity;
import eu.toldi.infinityforlemmy.activities.BlockedThingListingActivity;
import eu.toldi.infinityforlemmy.activities.CommentActivity; import eu.toldi.infinityforlemmy.activities.CommentActivity;
import eu.toldi.infinityforlemmy.activities.CreateMultiRedditActivity; import eu.toldi.infinityforlemmy.activities.CreateMultiRedditActivity;
import eu.toldi.infinityforlemmy.activities.CustomThemeListingActivity; import eu.toldi.infinityforlemmy.activities.CustomThemeListingActivity;
@ -66,6 +67,8 @@ import eu.toldi.infinityforlemmy.activities.WebViewActivity;
import eu.toldi.infinityforlemmy.activities.WikiActivity; import eu.toldi.infinityforlemmy.activities.WikiActivity;
import eu.toldi.infinityforlemmy.bottomsheetfragments.AccountChooserBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.AccountChooserBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.FlairBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.FlairBottomSheetFragment;
import eu.toldi.infinityforlemmy.fragments.BlockedCommunitiesListingFragment;
import eu.toldi.infinityforlemmy.fragments.BlockedUsersListingFragment;
import eu.toldi.infinityforlemmy.fragments.CommentsListingFragment; import eu.toldi.infinityforlemmy.fragments.CommentsListingFragment;
import eu.toldi.infinityforlemmy.fragments.FollowedUsersListingFragment; import eu.toldi.infinityforlemmy.fragments.FollowedUsersListingFragment;
import eu.toldi.infinityforlemmy.fragments.HistoryPostFragment; import eu.toldi.infinityforlemmy.fragments.HistoryPostFragment;
@ -307,6 +310,12 @@ public interface AppComponent {
void inject(MorePostsInfoFragment morePostsInfoFragment); void inject(MorePostsInfoFragment morePostsInfoFragment);
void inject(BlockedThingListingActivity blockedThingListingActivity);
void inject(BlockedCommunitiesListingFragment blockedCommunitiesListingFragment);
void inject(BlockedUsersListingFragment blockedUsersListingFragment);
@Component.Factory @Component.Factory
interface Factory { interface Factory {

View File

@ -110,9 +110,9 @@ class ParseSubscribedThing {
boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods"); boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods");
int instanceId = community.getInt("instance_id"); int instanceId = community.getInt("instance_id");
int subscribers = data.getJSONObject("counts").getInt("subscribers"); int subscribers = data.getJSONObject("counts").getInt("subscribers");
boolean isBlocked = data.getBoolean("blocked");
newSubscribedSubredditData.add(new SubscribedSubredditData(id, title, LemmyUtils.actorID2FullName(actorId), iconUrl, accountName)); newSubscribedSubredditData.add(new SubscribedSubredditData(id, title, LemmyUtils.actorID2FullName(actorId), iconUrl, accountName));
newSubredditData.add(new SubredditData(id,name,title,description,removed,published,updated,deleted,nsfw,actorId,local,iconUrl,bannerImageUrl,hidden,postingRestrictedToMods,instanceId,subscribers)); newSubredditData.add(new SubredditData(id, name, title, description, removed, published, updated, deleted, nsfw, actorId, local, iconUrl, bannerImageUrl, hidden, postingRestrictedToMods, instanceId, subscribers, isBlocked));
} }
} catch (JSONException e) { } catch (JSONException e) {

View File

@ -13,6 +13,10 @@ import androidx.sqlite.db.SupportSQLiteDatabase;
import eu.toldi.infinityforlemmy.account.Account; import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.account.AccountDao; import eu.toldi.infinityforlemmy.account.AccountDao;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityDao;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserDao;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomTheme; import eu.toldi.infinityforlemmy.customtheme.CustomTheme;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeDao; import eu.toldi.infinityforlemmy.customtheme.CustomThemeDao;
import eu.toldi.infinityforlemmy.multireddit.AnonymousMultiredditSubreddit; import eu.toldi.infinityforlemmy.multireddit.AnonymousMultiredditSubreddit;
@ -38,7 +42,7 @@ import eu.toldi.infinityforlemmy.user.UserData;
@Database(entities = {Account.class, SubredditData.class, SubscribedSubredditData.class, UserData.class, @Database(entities = {Account.class, SubredditData.class, SubscribedSubredditData.class, UserData.class,
SubscribedUserData.class, MultiReddit.class, CustomTheme.class, RecentSearchQuery.class, SubscribedUserData.class, MultiReddit.class, CustomTheme.class, RecentSearchQuery.class,
ReadPost.class, PostFilter.class, PostFilterUsage.class, AnonymousMultiredditSubreddit.class}, version = 24) ReadPost.class, PostFilter.class, PostFilterUsage.class, AnonymousMultiredditSubreddit.class, BlockedUserData.class, BlockedCommunityData.class}, version = 26)
public abstract class RedditDataRoomDatabase extends RoomDatabase { public abstract class RedditDataRoomDatabase extends RoomDatabase {
public static RedditDataRoomDatabase create(final Context context) { public static RedditDataRoomDatabase create(final Context context) {
@ -49,7 +53,7 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13,
MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17,
MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,
MIGRATION_21_22, MIGRATION_22_23, MIGRATION_23_24) MIGRATION_21_22, MIGRATION_22_23, MIGRATION_23_24, MIGRATION_24_25, MIGRATION_25_26)
.build(); .build();
} }
@ -59,6 +63,10 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
public abstract SubscribedSubredditDao subscribedSubredditDao(); public abstract SubscribedSubredditDao subscribedSubredditDao();
public abstract BlockedUserDao blockedUserDao();
public abstract BlockedCommunityDao blockedCommunityDao();
public abstract UserDao userDao(); public abstract UserDao userDao();
public abstract SubscribedUserDao subscribedUserDao(); public abstract SubscribedUserDao subscribedUserDao();
@ -390,4 +398,22 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
database.execSQL("ALTER TABLE accounts ADD COLUMN can_downvote INTEGER DEFAULT 1 NOT NULL"); database.execSQL("ALTER TABLE accounts ADD COLUMN can_downvote INTEGER DEFAULT 1 NOT NULL");
} }
}; };
private static final Migration MIGRATION_24_25 = new Migration(24, 25) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE subreddits ADD COLUMN blocked INTEGER DEFAULT 1 NOT NULL");
}
};
private static final Migration MIGRATION_25_26 = new Migration(25, 26) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE blocked_users" +
"(name TEXT, id INTEGER NOT NULL, avatar TEXT, qualified_name TEXT, account_name TEXT NOT NULL, PRIMARY KEY( id, account_name))");
database.execSQL("CREATE TABLE blocked_communities" +
"(name TEXT, icon TEXT, id INTEGER NOT NULL, qualified_name TEXT, account_name TEXT NOT NULL, PRIMARY KEY( id, account_name))");
}
};
} }

View File

@ -0,0 +1,82 @@
package eu.toldi.infinityforlemmy.account;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.subreddit.ParseSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
public class FetchBlockedThings {
public static void fetchBlockedThings(Retrofit mRetrofit, String accessToken, String accountName, FetchBlockedThingsListener fetchBlockedThingsListener) {
LemmyAPI lemmyAPI = mRetrofit.create(LemmyAPI.class);
Call<String> call = lemmyAPI.getSiteInfo(accessToken);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if (response.isSuccessful()) {
String siteInfo = response.body();
if (siteInfo != null) {
List<BlockedUserData> blockedUsers = new ArrayList<>();
List<BlockedCommunityData> blockedCommunities = new ArrayList<>();
try {
JSONObject siteInfoJson = new JSONObject(siteInfo).getJSONObject("my_user");
JSONArray blockedUsersJson = (siteInfoJson.has("person_blocks")) ? siteInfoJson.getJSONArray("person_blocks") : null;
JSONArray blockedCommunitiesJson = (siteInfoJson.has("community_blocks")) ? siteInfoJson.getJSONArray("community_blocks") : null;
if (blockedUsersJson != null) {
for (int i = 0; i < blockedUsersJson.length(); i++) {
JSONObject blockedUserJson = blockedUsersJson.getJSONObject(i).getJSONObject("target");
int id = blockedUserJson.getInt("id");
String name = blockedUserJson.getString("name");
String avatar = blockedUserJson.getString("avatar");
String qualifiedName = LemmyUtils.actorID2FullName(blockedUserJson.getString("actor_id"));
BlockedUserData blockedUserData = new BlockedUserData(id, name, avatar, qualifiedName, accountName);
blockedUsers.add(blockedUserData);
}
}
if (blockedCommunitiesJson != null) {
for (int i = 0; i < blockedCommunitiesJson.length(); i++) {
JSONObject blockedCommunityJson = blockedCommunitiesJson.getJSONObject(i);
SubredditData blockedCommunityData = ParseSubredditData.parseSubredditData(blockedCommunityJson, true);
blockedCommunities.add(new BlockedCommunityData(blockedCommunityData, accountName));
}
}
fetchBlockedThingsListener.onFetchBlockedThingsSuccess(blockedUsers, blockedCommunities);
} catch (JSONException e) {
e.printStackTrace();
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
} else {
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
} else {
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
});
}
public interface FetchBlockedThingsListener {
void onFetchBlockedThingsSuccess(List<BlockedUserData> blockedUsers, List<BlockedCommunityData> blockedCommunities);
void onFetchBlockedThingsFailure();
}
}

View File

@ -0,0 +1,462 @@
package eu.toldi.infinityforlemmy.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
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.InputMethodManager;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.inputmethod.EditorInfoCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.List;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.ActivityToolbarInterface;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.account.FetchBlockedThings;
import eu.toldi.infinityforlemmy.asynctasks.InsertBlockedThings;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.ViewPagerBugFixed;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.events.GoBackToMainPageEvent;
import eu.toldi.infinityforlemmy.events.SwitchAccountEvent;
import eu.toldi.infinityforlemmy.fragments.BlockedCommunitiesListingFragment;
import eu.toldi.infinityforlemmy.fragments.BlockedUsersListingFragment;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Retrofit;
public class BlockedThingListingActivity extends BaseActivity implements ActivityToolbarInterface {
public static final String EXTRA_SHOW_MULTIREDDITS = "ESM";
private static final String INSERT_SUBSCRIBED_SUBREDDIT_STATE = "ISSS";
private static final String INSERT_MULTIREDDIT_STATE = "IMS";
@BindView(R.id.coordinator_layout_subscribed_thing_listing_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_subscribed_thing_listing_activity)
AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_subscribed_thing_listing_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar_subscribed_thing_listing_activity)
Toolbar toolbar;
@BindView(R.id.search_edit_text_subscribed_thing_listing_activity)
EditText searchEditText;
@BindView(R.id.tab_layout_subscribed_thing_listing_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_subscribed_thing_listing_activity)
ViewPagerBugFixed viewPager;
@BindView(R.id.fab_subscribed_thing_listing_activity)
FloatingActionButton fab;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
@Named("current_account")
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
private String mAccessToken;
private String mAccountName;
private String mAccountQualifiedName;
private boolean mInsertSuccess = false;
private boolean mInsertMultiredditSuccess = false;
private boolean showMultiReddits = false;
private SectionsPagerAdapter sectionsPagerAdapter;
private Menu mMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
((Infinity) getApplication()).getAppComponent().inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribed_thing_listing);
ButterKnife.bind(this);
EventBus.getDefault().register(this);
applyCustomTheme();
if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) {
mSliderPanel = 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) {
window.setDecorFitsSystemWindows(false);
} else {
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
adjustToolbar(toolbar);
int navBarHeight = getNavBarHeight();
if (navBarHeight > 0) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
params.bottomMargin += navBarHeight;
fab.setLayoutParams(params);
}
}
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setToolbarGoToTop(toolbar);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "-");
mAccountQualifiedName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, "-");
if (savedInstanceState != null) {
mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE);
mInsertMultiredditSuccess = savedInstanceState.getBoolean(INSERT_MULTIREDDIT_STATE);
} else {
showMultiReddits = getIntent().getBooleanExtra(EXTRA_SHOW_MULTIREDDITS, false);
}
if (mAccessToken == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
searchEditText.setImeOptions(searchEditText.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
}
searchEditText.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) {
sectionsPagerAdapter.changeSearchQuery(editable.toString());
}
});
initializeViewPagerAndLoadSubscriptions();
}
@Override
public SharedPreferences getDefaultSharedPreferences() {
return mSharedPreferences;
}
@Override
protected CustomThemeWrapper getCustomThemeWrapper() {
return mCustomThemeWrapper;
}
@Override
protected void applyCustomTheme() {
coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
applyAppBarLayoutAndCollapsingToolbarLayoutAndToolbarTheme(appBarLayout, collapsingToolbarLayout, toolbar);
applyTabLayoutTheme(tabLayout);
applyFABTheme(fab, mSharedPreferences.getBoolean(SharedPreferencesUtils.USE_CIRCULAR_FAB, false));
searchEditText.setTextColor(mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor());
searchEditText.setHintTextColor(mCustomThemeWrapper.getToolbarSecondaryTextColor());
}
private void initializeViewPagerAndLoadSubscriptions() {
fab.setOnClickListener(view -> {
Intent intent = new Intent(this, CreateMultiRedditActivity.class);
startActivity(intent);
});
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(2);
if (viewPager.getCurrentItem() != 2) {
fab.hide();
}
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position == 0) {
unlockSwipeRightToGoBack();
fab.hide();
} else {
lockSwipeRightToGoBack();
if (position != 2) {
fab.hide();
} else {
fab.show();
}
}
}
});
tabLayout.setupWithViewPager(viewPager);
if (showMultiReddits) {
viewPager.setCurrentItem(2, false);
}
loadBlocks(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.subscribed_thing_listing_activity, menu);
mMenu = menu;
applyMenuItemTheme(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_search_subscribed_thing_listing_activity) {
item.setVisible(false);
searchEditText.setVisibility(View.VISIBLE);
searchEditText.requestFocus();
if (searchEditText.requestFocus()) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT);
}
return true;
} else if (item.getItemId() == android.R.id.home) {
if (searchEditText.getVisibility() == View.VISIBLE) {
Utils.hideKeyboard(this);
searchEditText.setVisibility(View.GONE);
searchEditText.setText("");
mMenu.findItem(R.id.action_search_subscribed_thing_listing_activity).setVisible(true);
sectionsPagerAdapter.changeSearchQuery("");
return true;
}
finish();
return true;
}
return false;
}
@Override
public void onBackPressed() {
if (searchEditText.getVisibility() == View.VISIBLE) {
Utils.hideKeyboard(this);
searchEditText.setVisibility(View.GONE);
searchEditText.setText("");
mMenu.findItem(R.id.action_search_subscribed_thing_listing_activity).setVisible(true);
sectionsPagerAdapter.changeSearchQuery("");
} else {
super.onBackPressed();
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE, mInsertSuccess);
outState.putBoolean(INSERT_MULTIREDDIT_STATE, mInsertMultiredditSuccess);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
public void loadBlocks(boolean forceLoad) {
if (mAccessToken != null && !(!forceLoad && mInsertSuccess)) {
FetchBlockedThings.fetchBlockedThings(mRetrofit.getRetrofit(), mAccessToken, mAccountQualifiedName, new FetchBlockedThings.FetchBlockedThingsListener() {
@Override
public void onFetchBlockedThingsSuccess(List<BlockedUserData> blockedUsers, List<BlockedCommunityData> blockedCommunities) {
InsertBlockedThings.insertBlockedThings(mExecutor, new Handler(), mRedditDataRoomDatabase, mAccountQualifiedName,
blockedCommunities, blockedUsers, () -> {
mInsertSuccess = true;
sectionsPagerAdapter.stopRefreshProgressbar();
});
}
@Override
public void onFetchBlockedThingsFailure() {
}
});
}
}
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
finish();
}
@Subscribe
public void goBackToMainPageEvent(GoBackToMainPageEvent event) {
finish();
}
@Override
public void onLongPress() {
if (sectionsPagerAdapter != null) {
sectionsPagerAdapter.goBackToTop();
}
}
@Override
public void lockSwipeRightToGoBack() {
if (mSliderPanel != null) {
mSliderPanel.lock();
}
}
@Override
public void unlockSwipeRightToGoBack() {
if (mSliderPanel != null) {
mSliderPanel.unlock();
}
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private BlockedCommunitiesListingFragment blockedCommunitiesListingFragment;
private BlockedUsersListingFragment followedUsersListingFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
@NonNull
@Override
public Fragment getItem(int position) {
switch (position) {
default:
case 0: {
BlockedCommunitiesListingFragment fragment = new BlockedCommunitiesListingFragment();
Bundle bundle = new Bundle();
bundle.putBoolean(BlockedCommunitiesListingFragment.EXTRA_IS_SUBREDDIT_SELECTION, false);
bundle.putString(BlockedCommunitiesListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);
bundle.putString(BlockedCommunitiesListingFragment.EXTRA_ACCOUNT_QUALIFIED_NAME, mAccountQualifiedName);
bundle.putString(BlockedCommunitiesListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
fragment.setArguments(bundle);
return fragment;
}
case 1: {
BlockedUsersListingFragment fragment = new BlockedUsersListingFragment();
Bundle bundle = new Bundle();
bundle.putString(BlockedUsersListingFragment.EXTRA_ACCOUNT_NAME, mAccountQualifiedName);
bundle.putString(BlockedUsersListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
fragment.setArguments(bundle);
return fragment;
}
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return Utils.getTabTextWithCustomFont(typeface, getString(R.string.communities));
case 1:
return Utils.getTabTextWithCustomFont(typeface, getString(R.string.users));
case 2:
return Utils.getTabTextWithCustomFont(typeface, getString(R.string.multi_reddits));
}
return null;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
if (position == 0) {
blockedCommunitiesListingFragment = (BlockedCommunitiesListingFragment) fragment;
} else if (position == 1) {
followedUsersListingFragment = (BlockedUsersListingFragment) fragment;
}
return fragment;
}
void stopRefreshProgressbar() {
if (blockedCommunitiesListingFragment != null) {
((FragmentCommunicator) blockedCommunitiesListingFragment).stopRefreshProgressbar();
}
if (followedUsersListingFragment != null) {
((FragmentCommunicator) followedUsersListingFragment).stopRefreshProgressbar();
}
}
void goBackToTop() {
if (viewPager.getCurrentItem() == 0) {
blockedCommunitiesListingFragment.goBackToTop();
} else if (viewPager.getCurrentItem() == 1) {
followedUsersListingFragment.goBackToTop();
}
}
void changeSearchQuery(String searchQuery) {
if (blockedCommunitiesListingFragment != null) {
blockedCommunitiesListingFragment.changeSearchQuery(searchQuery);
}
if (followedUsersListingFragment != null) {
followedUsersListingFragment.changeSearchQuery(searchQuery);
}
}
}
}

View File

@ -882,6 +882,8 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
}); });
} else if (stringId == R.string.anonymous_account_instance) { } else if (stringId == R.string.anonymous_account_instance) {
changeAnonymousAccountInstance(); changeAnonymousAccountInstance();
} else if (stringId == R.string.blocks) {
intent = new Intent(MainActivity.this, BlockedThingListingActivity.class);
} }
if (intent != null) { if (intent != null) {
startActivity(intent); startActivity(intent);

View File

@ -73,7 +73,6 @@ import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils; import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Retrofit; import retrofit2.Retrofit;
;
public class SubscribedThingListingActivity extends BaseActivity implements ActivityToolbarInterface { public class SubscribedThingListingActivity extends BaseActivity implements ActivityToolbarInterface {

View File

@ -82,6 +82,7 @@ import eu.toldi.infinityforlemmy.bottomsheetfragments.RandomBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTimeBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTimeBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTypeBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTypeBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.UrlMenuBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.UrlMenuBottomSheetFragment;
import eu.toldi.infinityforlemmy.community.BlockCommunity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.NavigationWrapper; import eu.toldi.infinityforlemmy.customviews.NavigationWrapper;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr; import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
@ -210,6 +211,8 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private String communityName; private String communityName;
private int communityId; private int communityId;
private SubredditData communityData;
private String description; private String description;
private String qualifiedName; private String qualifiedName;
@ -693,6 +696,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
} }
setupVisibleElements(); setupVisibleElements();
communityId = communityData.getId(); communityId = communityData.getId();
ViewSubredditDetailActivity.this.communityData = communityData;
setupSubscribeChip(); setupSubscribeChip();
mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers; mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers;
@ -1123,6 +1127,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.view_subreddit_detail_activity, menu); getMenuInflater().inflate(R.menu.view_subreddit_detail_activity, menu);
if (communityData != null && communityData.isBlocked()) {
menu.findItem(R.id.block_community_view_subreddit_detail_activity).setVisible(false);
} else {
menu.findItem(R.id.unblock_community_view_subreddit_detail_activity).setVisible(false);
}
applyMenuItemTheme(menu); applyMenuItemTheme(menu);
return true; return true;
} }
@ -1151,15 +1160,6 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment(); PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment();
postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag()); postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag());
return true; return true;
} else if (itemId == R.id.action_select_user_flair_view_subreddit_detail_activity) {
if (mAccessToken == null) {
Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
Intent selectUserFlairIntent = new Intent(this, SelectUserFlairActivity.class);
selectUserFlairIntent.putExtra(SelectUserFlairActivity.EXTRA_SUBREDDIT_NAME, communityName);
startActivity(selectUserFlairIntent);
return true;
} else if (itemId == R.id.action_add_to_post_filter_view_subreddit_detail_activity) { } else if (itemId == R.id.action_add_to_post_filter_view_subreddit_detail_activity) {
Intent intent = new Intent(this, PostFilterPreferenceActivity.class); Intent intent = new Intent(this, PostFilterPreferenceActivity.class);
intent.putExtra(PostFilterPreferenceActivity.EXTRA_SUBREDDIT_NAME, communityName); intent.putExtra(PostFilterPreferenceActivity.EXTRA_SUBREDDIT_NAME, communityName);
@ -1179,7 +1179,39 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
} else if (itemId == R.id.action_contact_mods_view_subreddit_detail_activity) { } else if (itemId == R.id.action_contact_mods_view_subreddit_detail_activity) {
Intent intent = new Intent(this, SendPrivateMessageActivity.class); Intent intent = new Intent(this, SendPrivateMessageActivity.class);
intent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, "r/" + communityName); intent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, "r/" + communityName);
startActivity(intent); //startActivity(intent);
return true;
} else if (itemId == R.id.block_community_view_subreddit_detail_activity) {
BlockCommunity.INSTANCE.blockCommunity(mRetrofit.getRetrofit(), communityId, mAccessToken, new BlockCommunity.BlockCommunityListener() {
@Override
public void onBlockCommunitySuccess() {
communityData.setBlocked(true);
Toast.makeText(ViewSubredditDetailActivity.this, R.string.block_community_success, Toast.LENGTH_SHORT).show();
ViewSubredditDetailActivity.this.invalidateOptionsMenu();
sectionsPagerAdapter.refresh(false);
}
@Override
public void onBlockCommunityError() {
Toast.makeText(ViewSubredditDetailActivity.this, R.string.block_community_failed, Toast.LENGTH_SHORT).show();
}
});
return true;
} else if (itemId == R.id.unblock_community_view_subreddit_detail_activity) {
BlockCommunity.INSTANCE.unBlockCommunity(mRetrofit.getRetrofit(), communityId, mAccessToken, new BlockCommunity.BlockCommunityListener() {
@Override
public void onBlockCommunitySuccess() {
communityData.setBlocked(false);
Toast.makeText(ViewSubredditDetailActivity.this, R.string.unblock_community_success, Toast.LENGTH_SHORT).show();
ViewSubredditDetailActivity.this.invalidateOptionsMenu();
sectionsPagerAdapter.refresh(false);
}
@Override
public void onBlockCommunityError() {
Toast.makeText(ViewSubredditDetailActivity.this, R.string.unblock_community_failed, Toast.LENGTH_SHORT).show();
}
});
return true; return true;
} }
return false; return false;

View File

@ -0,0 +1,377 @@
package eu.toldi.infinityforlemmy.adapters;
import android.content.Intent;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import java.util.concurrent.Executor;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.ViewSubredditDetailActivity;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import me.zhanghai.android.fastscroll.PopupTextProvider;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class BlockedCommunitiesRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements PopupTextProvider {
private static final int VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER = 0;
private static final int VIEW_TYPE_FAVORITE_SUBREDDIT = 1;
private static final int VIEW_TYPE_SUBREDDIT_DIVIDER = 2;
private static final int VIEW_TYPE_SUBREDDIT = 3;
private BaseActivity mActivity;
private Executor mExecutor;
private Retrofit mOauthRetrofit;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private List<BlockedCommunityData> mBlockedCommunityData;
private List<BlockedCommunityData> mFavoriteBlockedCommunityData;
private RequestManager glide;
private ItemClickListener itemClickListener;
private String accessToken;
private String username;
private String userIconUrl;
private boolean hasClearSelectionRow;
private int primaryTextColor;
private int secondaryTextColor;
public BlockedCommunitiesRecyclerViewAdapter(BaseActivity activity, Executor executor, Retrofit oauthRetrofit,
RedditDataRoomDatabase redditDataRoomDatabase,
CustomThemeWrapper customThemeWrapper,
String accessToken) {
mActivity = activity;
mExecutor = executor;
glide = Glide.with(activity);
mOauthRetrofit = oauthRetrofit;
mRedditDataRoomDatabase = redditDataRoomDatabase;
this.accessToken = accessToken;
primaryTextColor = customThemeWrapper.getPrimaryTextColor();
secondaryTextColor = customThemeWrapper.getSecondaryTextColor();
}
public BlockedCommunitiesRecyclerViewAdapter(BaseActivity activity, Executor executor, Retrofit oauthRetrofit,
RedditDataRoomDatabase redditDataRoomDatabase,
CustomThemeWrapper customThemeWrapper,
String accessToken, boolean hasClearSelectionRow,
ItemClickListener itemClickListener) {
this(activity, executor, oauthRetrofit, redditDataRoomDatabase, customThemeWrapper, accessToken);
this.hasClearSelectionRow = hasClearSelectionRow;
this.itemClickListener = itemClickListener;
}
@Override
public int getItemViewType(int position) {
if (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) {
if (itemClickListener != null && !hasClearSelectionRow) {
if (position == 0) {
return VIEW_TYPE_SUBREDDIT;
} else if (position == 1) {
return VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER;
} else if (position == mFavoriteBlockedCommunityData.size() + 2) {
return VIEW_TYPE_SUBREDDIT_DIVIDER;
} else if (position <= mFavoriteBlockedCommunityData.size() + 1) {
return VIEW_TYPE_FAVORITE_SUBREDDIT;
} else {
return VIEW_TYPE_SUBREDDIT;
}
} else if (hasClearSelectionRow) {
if (position == 0) {
return VIEW_TYPE_SUBREDDIT;
} else if (position == 1) {
return VIEW_TYPE_SUBREDDIT;
} else if (position == 2) {
return VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER;
} else if (position == mFavoriteBlockedCommunityData.size() + 3) {
return VIEW_TYPE_SUBREDDIT_DIVIDER;
} else if (position <= mFavoriteBlockedCommunityData.size() + 2) {
return VIEW_TYPE_FAVORITE_SUBREDDIT;
} else {
return VIEW_TYPE_SUBREDDIT;
}
} else {
if (position == 0) {
return VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER;
} else if (position == mFavoriteBlockedCommunityData.size() + 1) {
return VIEW_TYPE_SUBREDDIT_DIVIDER;
} else if (position <= mFavoriteBlockedCommunityData.size()) {
return VIEW_TYPE_FAVORITE_SUBREDDIT;
} else {
return VIEW_TYPE_SUBREDDIT;
}
}
} else {
return VIEW_TYPE_SUBREDDIT;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
switch (i) {
case VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER:
return new FavoriteSubredditsDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
case VIEW_TYPE_FAVORITE_SUBREDDIT:
return new FavoriteSubredditViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_subscribed_thing, viewGroup, false));
case VIEW_TYPE_SUBREDDIT_DIVIDER:
return new AllSubredditsDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
default:
return new SubredditViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_subscribed_thing, viewGroup, false));
}
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof SubredditViewHolder) {
String name;
String fullname = "";
String iconUrl;
if (hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 0) {
((SubredditViewHolder) viewHolder).subredditNameTextView.setText(R.string.all_communities);
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(null));
return;
} else {
int offset = hasClearSelectionRow ? 1 : 0;
BlockedCommunityData communityData = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset);
name = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getName();
fullname = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getQualified_name();
iconUrl = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl();
if (itemClickListener != null) {
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(communityData));
}
}
if (itemClickListener == null) {
String finalFullname = fullname;
viewHolder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, name);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY,
finalFullname);
mActivity.startActivity(intent);
});
}
if (iconUrl != null && !iconUrl.equals("")) {
glide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((SubredditViewHolder) viewHolder).iconGifImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((SubredditViewHolder) viewHolder).iconGifImageView);
}
((SubredditViewHolder) viewHolder).subredditNameTextView.setText(name);
} else if (viewHolder instanceof FavoriteSubredditViewHolder) {
int offset;
if (itemClickListener != null) {
if (hasClearSelectionRow) {
offset = 3;
} else {
offset = 2;
}
} else {
offset = 1;
}
BlockedCommunityData communityData = mFavoriteBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset);
String name = mFavoriteBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getName();
String iconUrl = mFavoriteBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl();
if (itemClickListener != null) {
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(communityData));
} else {
viewHolder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, name);
mActivity.startActivity(intent);
});
}
if (iconUrl != null && !iconUrl.equals("")) {
glide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((FavoriteSubredditViewHolder) viewHolder).iconGifImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((FavoriteSubredditViewHolder) viewHolder).iconGifImageView);
}
((FavoriteSubredditViewHolder) viewHolder).subredditNameTextView.setText(name);
}
}
@Override
public int getItemCount() {
if (mBlockedCommunityData != null) {
if (itemClickListener != null) {
return mBlockedCommunityData.size() > 0 ? mBlockedCommunityData.size() + ((hasClearSelectionRow) ? 1 : 0) : 0;
}
return mBlockedCommunityData.size();
}
return 0;
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof SubredditViewHolder) {
glide.clear(((SubredditViewHolder) holder).iconGifImageView);
} else if (holder instanceof FavoriteSubredditViewHolder) {
glide.clear(((FavoriteSubredditViewHolder) holder).iconGifImageView);
}
}
public void setSubscribedSubreddits(List<BlockedCommunityData> subscribedSubreddits) {
mBlockedCommunityData = subscribedSubreddits;
notifyDataSetChanged();
}
public void setFavoriteSubscribedSubreddits(List<BlockedCommunityData> favoriteBlockedCommunityData) {
mFavoriteBlockedCommunityData = favoriteBlockedCommunityData;
notifyDataSetChanged();
}
public void addUser(String username, String userIconUrl) {
this.username = username;
this.userIconUrl = userIconUrl;
}
@NonNull
@Override
public String getPopupText(int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_SUBREDDIT:
if (hasClearSelectionRow && position == 0) {
return "";
} else if (itemClickListener != null && !hasClearSelectionRow && position == 0) {
return "";
} else if (hasClearSelectionRow && position == 1) {
return "";
} else {
int offset;
if (itemClickListener != null) {
if (hasClearSelectionRow) {
offset = (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) ?
mFavoriteBlockedCommunityData.size() + 4 : 0;
} else {
offset = (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) ?
mFavoriteBlockedCommunityData.size() + 3 : 0;
}
} else {
offset = (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) ?
mFavoriteBlockedCommunityData.size() + 2 : 0;
}
return mBlockedCommunityData.get(position - offset).getName().substring(0, 1).toUpperCase();
}
case VIEW_TYPE_FAVORITE_SUBREDDIT:
int offset;
if (itemClickListener != null) {
if (hasClearSelectionRow) {
offset = 3;
} else {
offset = 2;
}
} else {
offset = 1;
}
return mFavoriteBlockedCommunityData.get(position - offset).getName().substring(0, 1).toUpperCase();
default:
return "";
}
}
public interface ItemClickListener {
void onClick(BlockedCommunityData subredditData);
}
class SubredditViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.thing_icon_gif_image_view_item_subscribed_thing)
GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView subredditNameTextView;
SubredditViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
subredditNameTextView.setTypeface(mActivity.typeface);
}
subredditNameTextView.setTextColor(primaryTextColor);
}
}
class FavoriteSubredditViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.thing_icon_gif_image_view_item_subscribed_thing)
GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView subredditNameTextView;
FavoriteSubredditViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
subredditNameTextView.setTypeface(mActivity.typeface);
}
subredditNameTextView.setTextColor(primaryTextColor);
}
}
class FavoriteSubredditsDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
FavoriteSubredditsDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.favorites);
dividerTextView.setTextColor(secondaryTextColor);
}
}
class AllSubredditsDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
AllSubredditsDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.all);
dividerTextView.setTextColor(secondaryTextColor);
}
}
}

View File

@ -0,0 +1,216 @@
package eu.toldi.infinityforlemmy.adapters;
import android.content.Intent;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import java.util.concurrent.Executor;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.ViewUserDetailActivity;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import me.zhanghai.android.fastscroll.PopupTextProvider;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class BlockedUsersRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements PopupTextProvider {
private static final int VIEW_TYPE_FAVORITE_USER_DIVIDER = 0;
private static final int VIEW_TYPE_FAVORITE_USER = 1;
private static final int VIEW_TYPE_USER_DIVIDER = 2;
private static final int VIEW_TYPE_USER = 3;
private List<BlockedUserData> mBlockedUserData;
private List<BlockedUserData> mFavoriteBlockedUserData;
private BaseActivity mActivity;
private Executor mExecutor;
private Retrofit mOauthRetrofit;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccessToken;
private RequestManager glide;
private int mPrimaryTextColor;
private int mSecondaryTextColor;
public BlockedUsersRecyclerViewAdapter(BaseActivity activity, Executor executor, Retrofit oauthRetrofit,
RedditDataRoomDatabase redditDataRoomDatabase,
CustomThemeWrapper customThemeWrapper,
String accessToken) {
mActivity = activity;
mExecutor = executor;
mOauthRetrofit = oauthRetrofit;
mRedditDataRoomDatabase = redditDataRoomDatabase;
mAccessToken = accessToken;
glide = Glide.with(activity);
mPrimaryTextColor = customThemeWrapper.getPrimaryTextColor();
mSecondaryTextColor = customThemeWrapper.getSecondaryTextColor();
}
@Override
public int getItemViewType(int position) {
if (mFavoriteBlockedUserData != null && mFavoriteBlockedUserData.size() > 0) {
if (position == 0) {
return VIEW_TYPE_FAVORITE_USER_DIVIDER;
} else if (position == mFavoriteBlockedUserData.size() + 1) {
return VIEW_TYPE_USER_DIVIDER;
} else if (position <= mFavoriteBlockedUserData.size()) {
return VIEW_TYPE_FAVORITE_USER;
} else {
return VIEW_TYPE_USER;
}
} else {
return VIEW_TYPE_USER;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
switch (i) {
case VIEW_TYPE_FAVORITE_USER_DIVIDER:
return new FavoriteUsersDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
case VIEW_TYPE_USER_DIVIDER:
return new AllUsersDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
default:
return new UserViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_subscribed_thing, viewGroup, false));
}
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof UserViewHolder) {
int offset = 0;
if (!mBlockedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getAvatar().equals("")) {
glide.load(mBlockedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getAvatar())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((UserViewHolder) viewHolder).iconGifImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((UserViewHolder) viewHolder).iconGifImageView);
}
((UserViewHolder) viewHolder).userNameTextView.setText(mBlockedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getName());
}
}
@Override
public int getItemCount() {
if (mBlockedUserData != null && mBlockedUserData.size() > 0) {
return mBlockedUserData.size();
}
return 0;
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof UserViewHolder) {
glide.clear(((UserViewHolder) holder).iconGifImageView);
}
}
public void setSubscribedUsers(List<BlockedUserData> subscribedUsers) {
mBlockedUserData = subscribedUsers;
notifyDataSetChanged();
}
public void setFavoriteSubscribedUsers(List<BlockedUserData> favoriteSubscribedUsers) {
mFavoriteBlockedUserData = favoriteSubscribedUsers;
notifyDataSetChanged();
}
@NonNull
@Override
public String getPopupText(int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_USER:
int offset = (mFavoriteBlockedUserData != null && mFavoriteBlockedUserData.size() > 0) ?
mFavoriteBlockedUserData.size() + 2 : 0;
return mBlockedUserData.get(position - offset).getName().substring(0, 1).toUpperCase();
case VIEW_TYPE_FAVORITE_USER:
return mFavoriteBlockedUserData.get(position - 1).getName().substring(0, 1).toUpperCase();
default:
return "";
}
}
class UserViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.thing_icon_gif_image_view_item_subscribed_thing)
GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView userNameTextView;
UserViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
userNameTextView.setTypeface(mActivity.typeface);
}
userNameTextView.setTextColor(mPrimaryTextColor);
itemView.setOnClickListener(view -> {
int offset = (mFavoriteBlockedUserData != null && mFavoriteBlockedUserData.size() > 0) ?
mFavoriteBlockedUserData.size() + 2 : 0;
int position = getBindingAdapterPosition() - offset;
if (position >= 0 && mBlockedUserData.size() > position) {
Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mBlockedUserData.get(position).getName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mBlockedUserData.get(position).getQualifiedName());
mActivity.startActivity(intent);
}
});
}
}
class FavoriteUsersDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
FavoriteUsersDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.favorites);
dividerTextView.setTextColor(mSecondaryTextColor);
}
}
class AllUsersDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
AllUsersDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.all);
dividerTextView.setTextColor(mSecondaryTextColor);
}
}
}

View File

@ -25,7 +25,7 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1; private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1;
private static final int VIEW_TYPE_MENU_ITEM = 2; private static final int VIEW_TYPE_MENU_ITEM = 2;
private static final int ACCOUNT_SECTION_ITEMS = 4; private static final int ACCOUNT_SECTION_ITEMS = 4;
private static final int ANONYMOUS_ACCOUNT_SECTION_ITEMS = 2; private static final int ANONYMOUS_ACCOUNT_SECTION_ITEMS = 1;
private BaseActivity baseActivity; private BaseActivity baseActivity;
private int inboxCount; private int inboxCount;

View File

@ -18,13 +18,13 @@ import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils; import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class LemmySectionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1; private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1;
private static final int VIEW_TYPE_MENU_ITEM = 2; private static final int VIEW_TYPE_MENU_ITEM = 2;
private static final int REDDIT_SECTION_ITEMS = 1; private static final int LEMMY_SECTION_ITEMS = 2;
private static final int REDDIT_SECTION_ANONYMOUS_ITEMS = 2; private static final int LEMMY_SECTION_ANONYMOUS_ITEMS = 1;
private final boolean isLoggedIn; private final boolean isLoggedIn;
private BaseActivity baseActivity; private BaseActivity baseActivity;
@ -34,9 +34,9 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
private boolean collapseRedditSection; private boolean collapseRedditSection;
private NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener; private NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener;
public RedditSectionRecyclerViewAdapter(BaseActivity baseActivity, CustomThemeWrapper customThemeWrapper, public LemmySectionRecyclerViewAdapter(BaseActivity baseActivity, CustomThemeWrapper customThemeWrapper,
SharedPreferences navigationDrawerSharedPreferences, SharedPreferences navigationDrawerSharedPreferences,
NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener, boolean isLoggedIn) { NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener, boolean isLoggedIn) {
this.baseActivity = baseActivity; this.baseActivity = baseActivity;
primaryTextColor = customThemeWrapper.getPrimaryTextColor(); primaryTextColor = customThemeWrapper.getPrimaryTextColor();
secondaryTextColor = customThemeWrapper.getSecondaryTextColor(); secondaryTextColor = customThemeWrapper.getSecondaryTextColor();
@ -76,10 +76,10 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
holder.itemView.setOnClickListener(view -> { holder.itemView.setOnClickListener(view -> {
if (collapseRedditSection) { if (collapseRedditSection) {
collapseRedditSection = !collapseRedditSection; collapseRedditSection = !collapseRedditSection;
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, REDDIT_SECTION_ITEMS); notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, isLoggedIn ? LEMMY_SECTION_ITEMS : LEMMY_SECTION_ANONYMOUS_ITEMS);
} else { } else {
collapseRedditSection = !collapseRedditSection; collapseRedditSection = !collapseRedditSection;
notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, REDDIT_SECTION_ITEMS); notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, isLoggedIn ? LEMMY_SECTION_ITEMS : LEMMY_SECTION_ANONYMOUS_ITEMS);
} }
notifyItemChanged(holder.getBindingAdapterPosition()); notifyItemChanged(holder.getBindingAdapterPosition());
}); });
@ -89,12 +89,13 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
switch (position) { switch (position) {
case 1: case 1:
stringId = R.string.trending; stringId = R.string.instance_info;
drawableId = R.drawable.ic_trending_24dp; drawableId = R.drawable.ic_baseline_info_24;
break; break;
case 2: case 2:
stringId = R.string.anonymous_account_instance; stringId = R.string.blocks;
drawableId = R.drawable.ic_account_circle_24dp; drawableId = R.drawable.ic_outline_lock_24dp;
break;
} }
((MenuItemViewHolder) holder).menuTextView.setText(stringId); ((MenuItemViewHolder) holder).menuTextView.setText(stringId);
@ -106,7 +107,7 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
@Override @Override
public int getItemCount() { public int getItemCount() {
return !collapseRedditSection ? (isLoggedIn ? REDDIT_SECTION_ITEMS + 1 : REDDIT_SECTION_ANONYMOUS_ITEMS + 1) : 1; return !collapseRedditSection ? (isLoggedIn ? LEMMY_SECTION_ITEMS + 1 : LEMMY_SECTION_ANONYMOUS_ITEMS + 1) : 1;
} }
class MenuGroupTitleViewHolder extends RecyclerView.ViewHolder { class MenuGroupTitleViewHolder extends RecyclerView.ViewHolder {

View File

@ -21,6 +21,7 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
private FavoriteSubscribedSubredditsSectionRecyclerViewAdapter favoriteSubscribedSubredditsSectionRecyclerViewAdapter; private FavoriteSubscribedSubredditsSectionRecyclerViewAdapter favoriteSubscribedSubredditsSectionRecyclerViewAdapter;
private SubscribedSubredditsRecyclerViewAdapter subscribedSubredditsRecyclerViewAdapter; private SubscribedSubredditsRecyclerViewAdapter subscribedSubredditsRecyclerViewAdapter;
private AccountManagementSectionRecyclerViewAdapter accountManagementSectionRecyclerViewAdapter; private AccountManagementSectionRecyclerViewAdapter accountManagementSectionRecyclerViewAdapter;
private LemmySectionRecyclerViewAdapter lemmySectionRecyclerViewAdapter;
private ConcatAdapter mainPageConcatAdapter; private ConcatAdapter mainPageConcatAdapter;
public NavigationDrawerRecyclerViewMergedAdapter(BaseActivity baseActivity, SharedPreferences sharedPreferences, public NavigationDrawerRecyclerViewMergedAdapter(BaseActivity baseActivity, SharedPreferences sharedPreferences,
@ -55,10 +56,13 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
customThemeWrapper, navigationDrawerSharedPreferences, itemClickListener); customThemeWrapper, navigationDrawerSharedPreferences, itemClickListener);
accountManagementSectionRecyclerViewAdapter = new AccountManagementSectionRecyclerViewAdapter(baseActivity, accountManagementSectionRecyclerViewAdapter = new AccountManagementSectionRecyclerViewAdapter(baseActivity,
customThemeWrapper, glide, accountName != null, itemClickListener); customThemeWrapper, glide, accountName != null, itemClickListener);
lemmySectionRecyclerViewAdapter = new LemmySectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
navigationDrawerSharedPreferences, itemClickListener, accountName != null);
mainPageConcatAdapter = new ConcatAdapter( mainPageConcatAdapter = new ConcatAdapter(
headerSectionRecyclerViewAdapter, headerSectionRecyclerViewAdapter,
accountSectionRecyclerViewAdapter, accountSectionRecyclerViewAdapter,
lemmySectionRecyclerViewAdapter,
preferenceSectionRecyclerViewAdapter, preferenceSectionRecyclerViewAdapter,
favoriteSubscribedSubredditsSectionRecyclerViewAdapter, favoriteSubscribedSubredditsSectionRecyclerViewAdapter,
subscribedSubredditsRecyclerViewAdapter); subscribedSubredditsRecyclerViewAdapter);
@ -70,6 +74,7 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
private void openAccountSection() { private void openAccountSection() {
mainPageConcatAdapter.removeAdapter(accountSectionRecyclerViewAdapter); mainPageConcatAdapter.removeAdapter(accountSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(lemmySectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(preferenceSectionRecyclerViewAdapter); mainPageConcatAdapter.removeAdapter(preferenceSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(favoriteSubscribedSubredditsSectionRecyclerViewAdapter); mainPageConcatAdapter.removeAdapter(favoriteSubscribedSubredditsSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(subscribedSubredditsRecyclerViewAdapter); mainPageConcatAdapter.removeAdapter(subscribedSubredditsRecyclerViewAdapter);
@ -81,6 +86,7 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
mainPageConcatAdapter.removeAdapter(accountManagementSectionRecyclerViewAdapter); mainPageConcatAdapter.removeAdapter(accountManagementSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(accountSectionRecyclerViewAdapter); mainPageConcatAdapter.addAdapter(accountSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(lemmySectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(preferenceSectionRecyclerViewAdapter); mainPageConcatAdapter.addAdapter(preferenceSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(favoriteSubscribedSubredditsSectionRecyclerViewAdapter); mainPageConcatAdapter.addAdapter(favoriteSubscribedSubredditsSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(subscribedSubredditsRecyclerViewAdapter); mainPageConcatAdapter.addAdapter(subscribedSubredditsRecyclerViewAdapter);

View File

@ -6,6 +6,7 @@ import com.google.common.util.concurrent.ListenableFuture;
import eu.toldi.infinityforlemmy.dto.AccountLoginDTO; import eu.toldi.infinityforlemmy.dto.AccountLoginDTO;
import eu.toldi.infinityforlemmy.dto.AuthDTO; import eu.toldi.infinityforlemmy.dto.AuthDTO;
import eu.toldi.infinityforlemmy.dto.BlockCommunityDTO;
import eu.toldi.infinityforlemmy.dto.CommentDTO; import eu.toldi.infinityforlemmy.dto.CommentDTO;
import eu.toldi.infinityforlemmy.dto.CommentVoteDTO; import eu.toldi.infinityforlemmy.dto.CommentVoteDTO;
import eu.toldi.infinityforlemmy.dto.DeleteCommentDTO; import eu.toldi.infinityforlemmy.dto.DeleteCommentDTO;
@ -136,6 +137,10 @@ public interface LemmyAPI {
@POST("api/v3/community/follow") @POST("api/v3/community/follow")
Call<String> communityFollow(@Body FollowCommunityDTO params); Call<String> communityFollow(@Body FollowCommunityDTO params);
@Headers("Content-Type: application/json")
@POST("api/v3/community/block")
Call<String> communityBlock(@Body BlockCommunityDTO params);
@Headers("Content-Type: application/json") @Headers("Content-Type: application/json")
@PUT("api/v3/post/save") @PUT("api/v3/post/save")
Call<String> postSave(@Body SavePostDTO params); Call<String> postSave(@Body SavePostDTO params);

View File

@ -0,0 +1,130 @@
package eu.toldi.infinityforlemmy.asynctasks;
import android.os.Handler;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityDao;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserDao;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
public class InsertBlockedThings {
public static void insertBlockedThings(Executor executor, Handler handler,
RedditDataRoomDatabase redditDataRoomDatabase, @Nullable String accountName,
List<BlockedCommunityData> blockedCommunityDataList,
List<BlockedUserData> blockedUserDataDataList,
InsertBlockedThingListener insertSubscribedThingListener) {
executor.execute(() -> {
if (accountName != null && redditDataRoomDatabase.accountDao().getAccountData(accountName) == null) {
handler.post(insertSubscribedThingListener::insertSuccess);
return;
}
BlockedUserDao blockedUserDao = redditDataRoomDatabase.blockedUserDao();
BlockedCommunityDao blockedCommunityDao = redditDataRoomDatabase.blockedCommunityDao();
if (blockedCommunityDataList != null) {
List<BlockedCommunityData> existingBlockedCommunityDaoList =
blockedCommunityDao.getAllBlockedCommunitiesList(accountName);
Collections.sort(blockedCommunityDataList, (subscribedSubredditData, t1) -> subscribedSubredditData.getName().compareToIgnoreCase(t1.getName()));
List<String> unsubscribedSubreddits = new ArrayList<>();
compareTwoSubscribedSubredditList(blockedCommunityDataList, existingBlockedCommunityDaoList,
unsubscribedSubreddits);
for (String unsubscribed : unsubscribedSubreddits) {
blockedCommunityDao.deleteBlockedCommunity(unsubscribed, accountName);
}
for (BlockedCommunityData s : blockedCommunityDataList) {
blockedCommunityDao.insert(s);
}
}
if (blockedUserDataDataList != null) {
List<BlockedUserData> existingBlockedUserDataList =
blockedUserDao.getAllBlockedUsersList(accountName);
Collections.sort(blockedUserDataDataList, (subscribedUserData, t1) -> subscribedUserData.getName().compareToIgnoreCase(t1.getName()));
List<String> unsubscribedUsers = new ArrayList<>();
compareTwoSubscribedUserList(blockedUserDataDataList, existingBlockedUserDataList,
unsubscribedUsers);
for (String unsubscribed : unsubscribedUsers) {
blockedUserDao.deleteBlockedUser(unsubscribed, accountName);
}
for (BlockedUserData s : blockedUserDataDataList) {
blockedUserDao.insert(s);
}
}
handler.post(insertSubscribedThingListener::insertSuccess);
});
}
private static void compareTwoSubscribedSubredditList(List<BlockedCommunityData> newSubscribedSubreddits,
List<BlockedCommunityData> oldSubscribedSubreddits,
List<String> unsubscribedSubredditNames) {
int newIndex = 0;
for (int oldIndex = 0; oldIndex < oldSubscribedSubreddits.size(); oldIndex++) {
if (newIndex >= newSubscribedSubreddits.size()) {
for (; oldIndex < oldSubscribedSubreddits.size(); oldIndex++) {
unsubscribedSubredditNames.add(oldSubscribedSubreddits.get(oldIndex).getName());
}
return;
}
BlockedCommunityData old = oldSubscribedSubreddits.get(oldIndex);
for (; newIndex < newSubscribedSubreddits.size(); newIndex++) {
if (newSubscribedSubreddits.get(newIndex).getName().compareToIgnoreCase(old.getName()) == 0) {
newIndex++;
break;
}
if (newSubscribedSubreddits.get(newIndex).getName().compareToIgnoreCase(old.getName()) > 0) {
unsubscribedSubredditNames.add(old.getName());
break;
}
}
}
}
private static void compareTwoSubscribedUserList(List<BlockedUserData> newSubscribedUsers,
List<BlockedUserData> oldSubscribedUsers,
List<String> unsubscribedUserNames) {
int newIndex = 0;
for (int oldIndex = 0; oldIndex < oldSubscribedUsers.size(); oldIndex++) {
if (newIndex >= newSubscribedUsers.size()) {
for (; oldIndex < oldSubscribedUsers.size(); oldIndex++) {
unsubscribedUserNames.add(oldSubscribedUsers.get(oldIndex).getQualifiedName());
}
return;
}
BlockedUserData old = oldSubscribedUsers.get(oldIndex);
for (; newIndex < newSubscribedUsers.size(); newIndex++) {
if (newSubscribedUsers.get(newIndex).getName().compareToIgnoreCase(old.getName()) == 0) {
newIndex++;
break;
}
if (newSubscribedUsers.get(newIndex).getName().compareToIgnoreCase(old.getName()) > 0) {
unsubscribedUserNames.add(old.getQualifiedName());
break;
}
}
}
}
public interface InsertBlockedThingListener {
void insertSuccess();
}
}

View File

@ -0,0 +1,30 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface BlockedCommunityDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(BlockedCommunityData communityData);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<BlockedCommunityData> blockedCommunityDataList);
@Query("SELECT * FROM blocked_communities WHERE account_name = :accountName AND name LIKE '%' || :searchQuery || '%' COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
LiveData<List<BlockedCommunityData>> getAllBlockedCommunitiesWithSearchQuery(String accountName, String searchQuery);
@Query("SELECT * FROM blocked_communities WHERE account_name = :accountName COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
List<BlockedCommunityData> getAllBlockedCommunitiesList(String accountName);
@Query("SELECT * FROM blocked_communities WHERE name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE LIMIT 1")
BlockedCommunityData getBlockedCommunity(String name, String accountName);
@Query("DELETE FROM blocked_communities WHERE name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE")
void deleteBlockedCommunity(String name, String accountName);
}

View File

@ -0,0 +1,80 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
@Entity(tableName = "blocked_communities", primaryKeys = {"id", "account_name"})
public class BlockedCommunityData {
@ColumnInfo(name = "id")
private final int id;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "qualified_name")
private String qualified_name;
@ColumnInfo(name = "icon")
private String iconUrl;
@NonNull
@ColumnInfo(name = "account_name")
private String accountName;
public BlockedCommunityData(int id, String name, String qualified_name, String iconUrl, @NonNull String accountName) {
this.id = id;
this.name = name;
this.qualified_name = qualified_name;
this.iconUrl = iconUrl;
this.accountName = accountName;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getQualified_name() {
return qualified_name;
}
public String getIconUrl() {
return iconUrl;
}
@NonNull
public String getAccountName() {
return accountName;
}
public void setName(String name) {
this.name = name;
}
public void setQualified_name(String qualified_name) {
this.qualified_name = qualified_name;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public void setAccountName(@NonNull String accountName) {
this.accountName = accountName;
}
public BlockedCommunityData(SubredditData subredditData, @NonNull String accountName) {
this.id = subredditData.getId();
this.name = subredditData.getName();
this.qualified_name = LemmyUtils.actorID2FullName(subredditData.getActorId());
this.iconUrl = subredditData.getIconUrl();
this.accountName = accountName;
}
}

View File

@ -0,0 +1,42 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedCommunityRepository {
private BlockedCommunityDao blockedCommunityDao;
private String mAccountName;
BlockedCommunityRepository(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
mAccountName = accountName;
blockedCommunityDao = redditDataRoomDatabase.blockedCommunityDao();
}
LiveData<List<BlockedCommunityData>> getAllSubscribedSubredditsWithSearchQuery(String searchQuery) {
return blockedCommunityDao.getAllBlockedCommunitiesWithSearchQuery(mAccountName, searchQuery);
}
public void insert(BlockedCommunityData subscribedSubredditData) {
new insertAsyncTask(blockedCommunityDao).execute(subscribedSubredditData);
}
private static class insertAsyncTask extends AsyncTask<BlockedCommunityData, Void, Void> {
private BlockedCommunityDao mAsyncTaskDao;
insertAsyncTask(BlockedCommunityDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final BlockedCommunityData... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}

View File

@ -0,0 +1,60 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedCommunityViewModel extends AndroidViewModel {
private BlockedCommunityRepository blockedCommunityRepository;
private LiveData<List<BlockedCommunityData>> mAllBlockedCommunities;
private MutableLiveData<String> searchQueryLiveData;
public BlockedCommunityViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
super(application);
blockedCommunityRepository = new BlockedCommunityRepository(redditDataRoomDatabase, accountName);
searchQueryLiveData = new MutableLiveData<>();
searchQueryLiveData.postValue("");
mAllBlockedCommunities = Transformations.switchMap(searchQueryLiveData, searchQuery -> blockedCommunityRepository.getAllSubscribedSubredditsWithSearchQuery(searchQuery));
}
public LiveData<List<BlockedCommunityData>> getAllBlockedCommunities() {
return mAllBlockedCommunities;
}
public void insert(BlockedCommunityData subscribedSubredditData) {
blockedCommunityRepository.insert(subscribedSubredditData);
}
public void setSearchQuery(String searchQuery) {
searchQueryLiveData.postValue(searchQuery);
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private Application mApplication;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccountName;
public Factory(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
this.mApplication = application;
this.mRedditDataRoomDatabase = redditDataRoomDatabase;
this.mAccountName = accountName;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new BlockedCommunityViewModel(mApplication, mRedditDataRoomDatabase, mAccountName);
}
}
}

View File

@ -0,0 +1,31 @@
package eu.toldi.infinityforlemmy.blockeduser;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface BlockedUserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(BlockedUserData userData);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<BlockedUserData> blockedUserDataDataList);
@Query("SELECT * FROM blocked_users WHERE account_name = :accountName AND name LIKE '%' || :searchQuery || '%' COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
LiveData<List<BlockedUserData>> getAllBlockedUsersWithSearchQuery(String accountName, String searchQuery);
@Query("SELECT * FROM blocked_users WHERE account_name = :accountName COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
List<BlockedUserData> getAllBlockedUsersList(String accountName);
@Query("SELECT * FROM blocked_users WHERE name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE LIMIT 1")
BlockedUserData getBlockedUser(String name, String accountName);
@Query("DELETE FROM blocked_users WHERE name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE")
void deleteBlockedUser(String name, String accountName);
}

View File

@ -0,0 +1,80 @@
package eu.toldi.infinityforlemmy.blockeduser;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import eu.toldi.infinityforlemmy.user.UserData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
@Entity(tableName = "blocked_users", primaryKeys = {"id", "account_name"})
public class BlockedUserData {
@ColumnInfo(name = "id")
private final int id;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "avatar")
private String avatar;
@ColumnInfo(name = "qualified_name")
private String qualifiedName;
@NonNull
@ColumnInfo(name = "account_name")
private String accountName;
public BlockedUserData(int id, String name, String avatar, String qualifiedName, String accountName) {
this.id = id;
this.name = name;
this.avatar = avatar;
this.qualifiedName = qualifiedName;
this.accountName = accountName;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getQualifiedName() {
return qualifiedName;
}
public void setQualifiedName(String qualifiedName) {
this.qualifiedName = qualifiedName;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public BlockedUserData(UserData userData, @NonNull String accountName) {
this.id = userData.getId();
this.name = userData.getName();
this.avatar = userData.getAvatar();
this.qualifiedName = LemmyUtils.actorID2FullName(userData.getActorId());
this.accountName = accountName;
}
}

View File

@ -0,0 +1,47 @@
package eu.toldi.infinityforlemmy.blockeduser;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedUserRepository {
private BlockedUserDao mBlockedUserDao;
private String mAccountName;
BlockedUserRepository(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
mBlockedUserDao = redditDataRoomDatabase.blockedUserDao();
mAccountName = accountName;
}
LiveData<List<BlockedUserData>> getAllBlockedUsersWithSearchQuery(String searchQuery) {
return mBlockedUserDao.getAllBlockedUsersWithSearchQuery(mAccountName, searchQuery);
}
LiveData<List<BlockedUserData>> getAllFavoriteSubscribedUsersWithSearchQuery(String searchQuery) {
return mBlockedUserDao.getAllBlockedUsersWithSearchQuery(mAccountName, searchQuery);
}
public void insert(BlockedUserData BlockedUserData) {
new BlockedUserRepository.insertAsyncTask(mBlockedUserDao).execute(BlockedUserData);
}
private static class insertAsyncTask extends AsyncTask<BlockedUserData, Void, Void> {
private BlockedUserDao mAsyncTaskDao;
insertAsyncTask(BlockedUserDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final BlockedUserData... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}

View File

@ -0,0 +1,61 @@
package eu.toldi.infinityforlemmy.blockeduser;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedUserViewModel extends AndroidViewModel {
private BlockedUserRepository blockedUserRepository;
private LiveData<List<BlockedUserData>> mAllSubscribedUsers;
private MutableLiveData<String> searchQueryLiveData;
public BlockedUserViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
super(application);
blockedUserRepository = new BlockedUserRepository(redditDataRoomDatabase, accountName);
searchQueryLiveData = new MutableLiveData<>();
searchQueryLiveData.postValue("");
mAllSubscribedUsers = Transformations.switchMap(searchQueryLiveData, searchQuery -> blockedUserRepository.getAllFavoriteSubscribedUsersWithSearchQuery(searchQuery));
}
public LiveData<List<BlockedUserData>> getAllSubscribedUsers() {
return mAllSubscribedUsers;
}
public void insert(BlockedUserData BlockedUserData) {
blockedUserRepository.insert(BlockedUserData);
}
public void setSearchQuery(String searchQuery) {
searchQueryLiveData.postValue(searchQuery);
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private Application mApplication;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccountName;
public Factory(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
mApplication = application;
mRedditDataRoomDatabase = redditDataRoomDatabase;
mAccountName = accountName;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new BlockedUserViewModel(mApplication, mRedditDataRoomDatabase, mAccountName);
}
}
}

View File

@ -0,0 +1,202 @@
package eu.toldi.infinityforlemmy.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.SubscribedThingListingActivity;
import eu.toldi.infinityforlemmy.adapters.BlockedCommunitiesRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityViewModel;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;
import retrofit2.Retrofit;
/**
* A simple {@link Fragment} subclass.
*/
public class BlockedCommunitiesListingFragment extends Fragment implements FragmentCommunicator {
public static final String EXTRA_ACCOUNT_NAME = "EAN";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_ACCOUNT_PROFILE_IMAGE_URL = "EAPIU";
public static final String EXTRA_IS_SUBREDDIT_SELECTION = "EISS";
public static final String EXTRA_EXTRA_CLEAR_SELECTION = "EECS";
public static final String EXTRA_ACCOUNT_QUALIFIED_NAME = "EAQN";
@BindView(R.id.swipe_refresh_layout_subscribed_subreddits_listing_fragment)
SwipeRefreshLayout mSwipeRefreshLayout;
@BindView(R.id.recycler_view_subscribed_subreddits_listing_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_subreddits_listing_fragment)
LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_subreddits_listing_fragment)
ImageView mImageView;
@BindView(R.id.error_text_view_subscribed_subreddits_listing_fragment)
TextView mErrorTextView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
public BlockedCommunityViewModel mSubscribedSubredditViewModel;
private BaseActivity mActivity;
private RequestManager mGlide;
private LinearLayoutManagerBugFixed mLinearLayoutManager;
public BlockedCommunitiesListingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_subscribed_subreddits_listing, container, false);
ButterKnife.bind(this, rootView);
((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
applyTheme();
if ((mActivity instanceof BaseActivity && ((BaseActivity) mActivity).isImmersiveInterface())) {
mRecyclerView.setPadding(0, 0, 0, ((BaseActivity) mActivity).getNavBarHeight());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mSharedPreferences.getBoolean(SharedPreferencesUtils.IMMERSIVE_INTERFACE_KEY, true)) {
Resources resources = getResources();
int navBarResourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (navBarResourceId > 0) {
mRecyclerView.setPadding(0, 0, 0, resources.getDimensionPixelSize(navBarResourceId));
}
}
String accountName = getArguments().getString(EXTRA_ACCOUNT_NAME, "-");
String accountQualifiedName = getArguments().getString(EXTRA_ACCOUNT_QUALIFIED_NAME, "-");
String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
if (accessToken == null) {
mSwipeRefreshLayout.setEnabled(false);
}
mGlide = Glide.with(this);
mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
BlockedCommunitiesRecyclerViewAdapter adapter = new BlockedCommunitiesRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRedditDataRoomDatabase,
mCustomThemeWrapper, accessToken);
mRecyclerView.setAdapter(adapter);
new FastScrollerBuilder(mRecyclerView).useMd2Style().build();
mSubscribedSubredditViewModel = new ViewModelProvider(this,
new BlockedCommunityViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, accountQualifiedName))
.get(BlockedCommunityViewModel.class);
mSubscribedSubredditViewModel.getAllBlockedCommunities().observe(getViewLifecycleOwner(), subscribedSubredditData -> {
mSwipeRefreshLayout.setRefreshing(false);
if (subscribedSubredditData == null || subscribedSubredditData.size() == 0) {
mRecyclerView.setVisibility(View.GONE);
mLinearLayout.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.error_image).into(mImageView);
} else {
mLinearLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mGlide.clear(mImageView);
}
if (accessToken != null) {
adapter.addUser(accountName, getArguments().getString(EXTRA_ACCOUNT_PROFILE_IMAGE_URL));
}
adapter.setSubscribedSubreddits(subscribedSubredditData);
});
/* mSubscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(getViewLifecycleOwner(), favoriteSubscribedSubredditData -> {
mSwipeRefreshLayout.setRefreshing(false);
if (favoriteSubscribedSubredditData != null && favoriteSubscribedSubredditData.size() > 0) {
mLinearLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mGlide.clear(mImageView);
}
adapter.setFavoriteSubscribedSubreddits(favoriteSubscribedSubredditData);
});*/
return rootView;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mActivity = (BaseActivity) context;
}
@Override
public void stopRefreshProgressbar() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void applyTheme() {
if (mActivity instanceof SubscribedThingListingActivity) {
mSwipeRefreshLayout.setOnRefreshListener(() -> ((SubscribedThingListingActivity) mActivity).loadSubscriptions(true));
mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
} else {
mSwipeRefreshLayout.setEnabled(false);
}
mErrorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
if (mActivity.typeface != null) {
mErrorTextView.setTypeface(mActivity.contentTypeface);
}
}
public void goBackToTop() {
if (mLinearLayoutManager != null) {
mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
public void changeSearchQuery(String searchQuery) {
mSubscribedSubredditViewModel.setSearchQuery(searchQuery);
}
}

View File

@ -0,0 +1,172 @@
package eu.toldi.infinityforlemmy.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.BlockedThingListingActivity;
import eu.toldi.infinityforlemmy.adapters.BlockedUsersRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserViewModel;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;
import retrofit2.Retrofit;
public class BlockedUsersListingFragment extends Fragment implements FragmentCommunicator {
public static final String EXTRA_ACCOUNT_NAME = "EAN";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
@BindView(R.id.swipe_refresh_layout_followed_users_listing_fragment)
SwipeRefreshLayout mSwipeRefreshLayout;
@BindView(R.id.recycler_view_followed_users_listing_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_followed_users_listing_fragment)
LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_followed_users_listing_fragment)
ImageView mImageView;
@BindView(R.id.error_text_view_followed_users_listing_fragment)
TextView mErrorTextView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
BlockedUserViewModel blockedUserViewModel;
private BaseActivity mActivity;
private RequestManager mGlide;
private LinearLayoutManagerBugFixed mLinearLayoutManager;
public BlockedUsersListingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_followed_users_listing, container, false);
ButterKnife.bind(this, rootView);
((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
applyTheme();
Resources resources = getResources();
if ((mActivity instanceof BaseActivity && ((BaseActivity) mActivity).isImmersiveInterface())) {
mRecyclerView.setPadding(0, 0, 0, ((BaseActivity) mActivity).getNavBarHeight());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mSharedPreferences.getBoolean(SharedPreferencesUtils.IMMERSIVE_INTERFACE_KEY, true)) {
int navBarResourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (navBarResourceId > 0) {
mRecyclerView.setPadding(0, 0, 0, resources.getDimensionPixelSize(navBarResourceId));
}
}
mGlide = Glide.with(this);
String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
if (accessToken == null) {
mSwipeRefreshLayout.setEnabled(false);
}
mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
BlockedUsersRecyclerViewAdapter adapter = new BlockedUsersRecyclerViewAdapter(mActivity,
mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, accessToken);
mRecyclerView.setAdapter(adapter);
new FastScrollerBuilder(mRecyclerView).useMd2Style().build();
blockedUserViewModel = new ViewModelProvider(this,
new BlockedUserViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, getArguments().getString(EXTRA_ACCOUNT_NAME)))
.get(BlockedUserViewModel.class);
blockedUserViewModel.getAllSubscribedUsers().observe(getViewLifecycleOwner(), subscribedUserData -> {
mSwipeRefreshLayout.setRefreshing(false);
if (subscribedUserData == null || subscribedUserData.size() == 0) {
mRecyclerView.setVisibility(View.GONE);
mLinearLayout.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.error_image).into(mImageView);
} else {
mLinearLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mGlide.clear(mImageView);
}
adapter.setSubscribedUsers(subscribedUserData);
});
return rootView;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mActivity = (BaseActivity) context;
}
@Override
public void stopRefreshProgressbar() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void applyTheme() {
if (mActivity instanceof BlockedThingListingActivity) {
mSwipeRefreshLayout.setOnRefreshListener(() -> ((BlockedThingListingActivity) mActivity).loadBlocks(true));
mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
} else {
mSwipeRefreshLayout.setEnabled(false);
}
mErrorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
if (mActivity.typeface != null) {
mErrorTextView.setTypeface(mActivity.typeface);
}
}
public void goBackToTop() {
if (mLinearLayoutManager != null) {
mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
public void changeSearchQuery(String searchQuery) {
blockedUserViewModel.setSearchQuery(searchQuery);
}
}

View File

@ -27,7 +27,7 @@ public class ParseSubredditData {
} }
@Nullable @Nullable
private static SubredditData parseSubredditData(JSONObject subredditDataJsonObject, boolean nsfw) throws JSONException { public static SubredditData parseSubredditData(JSONObject subredditDataJsonObject, boolean nsfw) throws JSONException {
JSONObject community = subredditDataJsonObject.getJSONObject("community"); JSONObject community = subredditDataJsonObject.getJSONObject("community");
boolean isNSFW = community.getBoolean("nsfw"); boolean isNSFW = community.getBoolean("nsfw");
if (!nsfw && isNSFW) { if (!nsfw && isNSFW) {
@ -69,9 +69,10 @@ public class ParseSubredditData {
boolean hidden = community.getBoolean("hidden"); boolean hidden = community.getBoolean("hidden");
boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods"); boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods");
int instanceId = community.getInt("instance_id"); int instanceId = community.getInt("instance_id");
int subscribers = subredditDataJsonObject.getJSONObject("counts").getInt("subscribers"); int subscribers = (subredditDataJsonObject.has("counts")) ? subredditDataJsonObject.getJSONObject("counts").getInt("subscribers") : 0;
boolean blocked = (subredditDataJsonObject.has("blocked")) ? subredditDataJsonObject.getBoolean("blocked") : true;
return new SubredditData(id,name,title,description,removed,published,updated,deleted,isNSFW,actorId,local,iconUrl,bannerImageUrl,hidden,postingRestrictedToMods,instanceId,subscribers); return new SubredditData(id, name, title, description, removed, published, updated, deleted, isNSFW, actorId, local, iconUrl, bannerImageUrl, hidden, postingRestrictedToMods, instanceId, subscribers, blocked);
} }
interface ParseSubredditDataListener { interface ParseSubredditDataListener {

View File

@ -61,6 +61,9 @@ public class SubredditData {
@ColumnInfo(name = "subscribers") @ColumnInfo(name = "subscribers")
private int subscribers; private int subscribers;
@ColumnInfo(name = "blocked")
private boolean blocked;
@Ignore @Ignore
private boolean isSelected; private boolean isSelected;
@ -201,7 +204,7 @@ public class SubredditData {
this.subscribers = subscribers; this.subscribers = subscribers;
} }
public SubredditData(int id, String name, String title, String description, boolean removed, String published, String updated, boolean deleted, boolean nsfw, String actorId, boolean local, String icon, String banner, boolean hidden, boolean postingRestrictedToMods, int instanceId, int subscribers) { public SubredditData(int id, String name, String title, String description, boolean removed, String published, String updated, boolean deleted, boolean nsfw, String actorId, boolean local, String icon, String banner, boolean hidden, boolean postingRestrictedToMods, int instanceId, int subscribers, boolean blocked) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.title = title; this.title = title;
@ -219,6 +222,7 @@ public class SubredditData {
this.postingRestrictedToMods = postingRestrictedToMods; this.postingRestrictedToMods = postingRestrictedToMods;
this.instanceId = instanceId; this.instanceId = instanceId;
this.subscribers = subscribers; this.subscribers = subscribers;
this.blocked = blocked;
} }
public boolean isNSFW() { public boolean isNSFW() {
@ -250,6 +254,14 @@ public class SubredditData {
} }
public void setSelected(boolean b) { public void setSelected(boolean b) {
isSelected =b; isSelected = b;
}
public boolean isBlocked() {
return blocked;
}
public void setBlocked(boolean blocked) {
this.blocked = blocked;
} }
} }

View File

@ -21,7 +21,7 @@ public class ParseUserData {
new ParseUserListingDataAsyncTask(response, parseUserListingDataListener).execute(); new ParseUserListingDataAsyncTask(response, parseUserListingDataListener).execute();
} }
private static UserData parseUserDataBase(JSONObject userDataJson, boolean parseFullKarma) throws JSONException { public static UserData parseUserDataBase(JSONObject userDataJson, boolean parseFullKarma) throws JSONException {
if (userDataJson == null) { if (userDataJson == null) {
return null; return null;
} }
@ -38,10 +38,7 @@ public class ParseUserData {
if (!personJson.isNull("banner")) { if (!personJson.isNull("banner")) {
bannerImageUrl = personJson.getString("banner"); bannerImageUrl = personJson.getString("banner");
} }
JSONObject countsJson = (userDataJson.has("person_view")) ? userDataJson.getJSONObject("person_view").getJSONObject("counts") : userDataJson.getJSONObject("counts");
int linkKarma = countsJson.getInt(JSONUtils.POST_SCORE_KEY);
int commentKarma = countsJson.getInt(JSONUtils.COMMENT_SCORE_KEY);
int account_id = personJson.getInt("id"); int account_id = personJson.getInt("id");
int instance_id = personJson.getInt("instance_id"); int instance_id = personJson.getInt("instance_id");

View File

@ -0,0 +1,64 @@
package eu.toldi.infinityforlemmy.community
import eu.toldi.infinityforlemmy.apis.LemmyAPI
import eu.toldi.infinityforlemmy.dto.BlockCommunityDTO
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
object BlockCommunity {
fun blockCommunity(
retrofit: Retrofit,
communityId: Int,
auth: String,
blockCommunityListener: BlockCommunityListener
) {
val api = retrofit.create(LemmyAPI::class.java)
api.communityBlock(BlockCommunityDTO(communityId, true, auth))?.enqueue(
object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.isSuccessful) {
blockCommunityListener.onBlockCommunitySuccess()
} else {
blockCommunityListener.onBlockCommunityError()
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
blockCommunityListener.onBlockCommunityError()
}
}
)
}
fun unBlockCommunity(
retrofit: Retrofit,
communityId: Int,
auth: String,
blockCommunityListener: BlockCommunityListener
) {
val api = retrofit.create(LemmyAPI::class.java)
api.communityBlock(BlockCommunityDTO(communityId, false, auth))?.enqueue(
object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.isSuccessful) {
blockCommunityListener.onBlockCommunitySuccess()
} else {
blockCommunityListener.onBlockCommunityError()
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
blockCommunityListener.onBlockCommunityError()
}
}
)
}
interface BlockCommunityListener {
fun onBlockCommunitySuccess()
fun onBlockCommunityError()
}
}

View File

@ -0,0 +1,3 @@
package eu.toldi.infinityforlemmy.dto
data class BlockCommunityDTO(val community_id: Int, val block: Boolean, val auth: String)

View File

@ -0,0 +1,10 @@
<vector android:height="24dp"
android:tint="#000000"
android:viewportHeight="24"
android:viewportWidth="24"
android:width="24dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<path
android:fillColor="@android:color/white"
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z" />
</vector>

View File

@ -30,9 +30,15 @@
app:showAsAction="never" /> app:showAsAction="never" />
<item <item
android:id="@+id/action_select_user_flair_view_subreddit_detail_activity" android:id="@+id/block_community_view_subreddit_detail_activity"
android:orderInCategory="5" android:orderInCategory="5"
android:title="@string/action_select_user_flair" android:title="@string/block_community"
app:showAsAction="never" />
<item
android:id="@+id/unblock_community_view_subreddit_detail_activity"
android:orderInCategory="5"
android:title="@string/unblock_community"
app:showAsAction="never" /> app:showAsAction="never" />

View File

@ -1353,4 +1353,13 @@
<string name="username_cannot_be_empty">The username field cannot be left empty.</string> <string name="username_cannot_be_empty">The username field cannot be left empty.</string>
<string name="password_cannot_be_empty">The password field cannot be left empty.</string> <string name="password_cannot_be_empty">The password field cannot be left empty.</string>
<string name="separate_down_and_up_votes">Separate Up and Down votes</string> <string name="separate_down_and_up_votes">Separate Up and Down votes</string>
<string name="block_community_success">Community blocked!</string>
<string name="block_community_failed">Failed to block community</string>
<string name="unblock_community">Unblock Community</string>
<string name="unblock_community_success">Community unblocked!</string>
<string name="unblock_community_failed">Failed to unblock community</string>
<string name="instance_info">Instance Info</string>
<string name="blocked_communities">Blocked Communities</string>
<string name="blocked_users">Blocked users</string>
<string name="blocks">Blocks</string>
</resources> </resources>