Multi communities (#209)

Reviewed-on: https://codeberg.org/Bazsalanszky/Eternity/pulls/209
Co-authored-by: Balazs Toldi <balazs@toldi.eu>
Co-committed-by: Balazs Toldi <balazs@toldi.eu>
This commit is contained in:
Balazs Toldi 2024-01-06 10:18:16 +00:00 committed by Bazsalanszky
parent 1a1b92bb72
commit 0fd7203fa3
34 changed files with 663 additions and 524 deletions

View File

@ -49,7 +49,7 @@ public class FetchPostFilterReadPostsAndConcatenatedSubredditNames {
if (anonymousSubscribedSubreddits != null && !anonymousSubscribedSubreddits.isEmpty()) {
StringBuilder stringBuilder = new StringBuilder();
for (SubscribedSubredditData s : anonymousSubscribedSubreddits) {
stringBuilder.append(s.getName()).append("+");
stringBuilder.append(s.getQualified_name()).append(",");
}
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);

View File

@ -34,13 +34,13 @@ import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.multireddit.CreateMultiReddit;
import eu.toldi.infinityforlemmy.multireddit.MultiRedditJSONModel;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Retrofit;
public class CreateMultiRedditActivity extends BaseActivity {
@ -71,8 +71,8 @@ public class CreateMultiRedditActivity extends BaseActivity {
@BindView(R.id.select_subreddit_text_view_create_multi_reddit_activity)
TextView selectSubredditTextView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@ -87,7 +87,7 @@ public class CreateMultiRedditActivity extends BaseActivity {
Executor mExecutor;
private String mAccessToken;
private String mAccountName;
private ArrayList<String> mSubreddits;
private ArrayList<SubredditWithSelection> mSubreddits;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -114,10 +114,10 @@ public class CreateMultiRedditActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "-");
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, "-");
if (mAccessToken == null) {
visibilityLinearLayout.setVisibility(View.GONE);
if (mAccessToken == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
nameEditText.setImeOptions(nameEditText.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
descriptionEditText.setImeOptions(descriptionEditText.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
@ -125,7 +125,7 @@ public class CreateMultiRedditActivity extends BaseActivity {
}
if (savedInstanceState != null) {
mSubreddits = savedInstanceState.getStringArrayList(SELECTED_SUBREDDITS_STATE);
mSubreddits = savedInstanceState.getParcelableArrayList(SELECTED_SUBREDDITS_STATE);
} else {
mSubreddits = new ArrayList<>();
}
@ -135,7 +135,7 @@ public class CreateMultiRedditActivity extends BaseActivity {
private void bindView() {
selectSubredditTextView.setOnClickListener(view -> {
Intent intent = new Intent(CreateMultiRedditActivity.this, SelectedSubredditsAndUsersActivity.class);
intent.putStringArrayListExtra(SelectedSubredditsAndUsersActivity.EXTRA_SELECTED_SUBREDDITS, mSubreddits);
intent.putParcelableArrayListExtra(SelectedSubredditsAndUsersActivity.EXTRA_SELECTED_SUBREDDITS, mSubreddits);
startActivityForResult(intent, SUBREDDIT_SELECTION_REQUEST_CODE);
});
}
@ -159,29 +159,17 @@ public class CreateMultiRedditActivity extends BaseActivity {
return true;
}
if (mAccessToken != null) {
String jsonModel = new MultiRedditJSONModel(nameEditText.getText().toString(), descriptionEditText.getText().toString(),
visibilitySwitch.isChecked(), mSubreddits).createJSONModel();
CreateMultiReddit.createMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase, mAccessToken,
"/user/" + mAccountName + "/m/" + nameEditText.getText().toString(),
jsonModel, new CreateMultiReddit.CreateMultiRedditListener() {
@Override
public void success() {
finish();
// Create a list of community qualified names seperated by a comma
StringBuilder subredditList = new StringBuilder();
String prefix = "";
for (SubredditWithSelection s : mSubreddits) {
subredditList.append(prefix);
prefix = ",";
subredditList.append(s.getQualifiedName());
}
@Override
public void failed(int errorCode) {
if (errorCode == 409) {
Snackbar.make(coordinatorLayout, R.string.duplicate_multi_reddit, Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(coordinatorLayout, R.string.create_multi_reddit_failed, Snackbar.LENGTH_SHORT).show();
}
}
});
} else {
CreateMultiReddit.anonymousCreateMultiReddit(mExecutor, new Handler(), mRedditDataRoomDatabase,
"/user/-/m/" + nameEditText.getText().toString(),
mAccountName, subredditList.toString(),
nameEditText.getText().toString(), descriptionEditText.getText().toString(),
mSubreddits, new CreateMultiReddit.CreateMultiRedditListener() {
@Override
@ -195,7 +183,6 @@ public class CreateMultiRedditActivity extends BaseActivity {
}
});
}
}
return false;
}
@ -204,7 +191,7 @@ public class CreateMultiRedditActivity extends BaseActivity {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
mSubreddits = data.getStringArrayListExtra(
mSubreddits = data.getParcelableArrayListExtra(
SubredditMultiselectionActivity.EXTRA_RETURN_SELECTED_SUBREDDITS);
}
}
@ -213,7 +200,7 @@ public class CreateMultiRedditActivity extends BaseActivity {
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList(SELECTED_SUBREDDITS_STATE, mSubreddits);
outState.putParcelableArrayList(SELECTED_SUBREDDITS_STATE, mSubreddits);
}
@Override

View File

@ -12,7 +12,6 @@ import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
@ -25,6 +24,7 @@ import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import javax.inject.Inject;
@ -40,7 +40,7 @@ import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.multireddit.EditMultiReddit;
import eu.toldi.infinityforlemmy.multireddit.FetchMultiRedditInfo;
import eu.toldi.infinityforlemmy.multireddit.MultiReddit;
import eu.toldi.infinityforlemmy.multireddit.MultiRedditJSONModel;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Retrofit;
@ -70,12 +70,6 @@ public class EditMultiRedditActivity extends BaseActivity {
EditText descriptionEditText;
@BindView(R.id.divider_2_edit_multi_reddit_activity)
View divider2;
@BindView(R.id.visibility_wrapper_linear_layout_edit_multi_reddit_activity)
LinearLayout visibilityLinearLayout;
@BindView(R.id.visibility_text_view_edit_multi_reddit_activity)
TextView visibilityTextView;
@BindView(R.id.visibility_switch_edit_multi_reddit_activity)
Switch visibilitySwitch;
@BindView(R.id.select_subreddit_text_view_edit_multi_reddit_activity)
TextView selectSubredditTextView;
@Inject
@ -123,10 +117,9 @@ public class EditMultiRedditActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "-");
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, "-");
if (mAccessToken == null) {
visibilityLinearLayout.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
nameEditText.setImeOptions(nameEditText.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
descriptionEditText.setImeOptions(descriptionEditText.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
@ -145,9 +138,9 @@ public class EditMultiRedditActivity extends BaseActivity {
private void bindView() {
if (multiReddit == null) {
if (mAccessToken == null) {
FetchMultiRedditInfo.anonymousFetchMultiRedditInfo(mExecutor, new Handler(),
mRedditDataRoomDatabase, multipath, new FetchMultiRedditInfo.FetchMultiRedditInfoListener() {
mRedditDataRoomDatabase, multipath, mAccountName, new FetchMultiRedditInfo.FetchMultiRedditInfoListener() {
@Override
public void success(MultiReddit multiReddit) {
EditMultiRedditActivity.this.multiReddit = multiReddit;
@ -162,36 +155,27 @@ public class EditMultiRedditActivity extends BaseActivity {
//Will not be called
}
});
} else {
FetchMultiRedditInfo.fetchMultiRedditInfo(mRetrofit, mAccessToken, multipath, new FetchMultiRedditInfo.FetchMultiRedditInfoListener() {
@Override
public void success(MultiReddit multiReddit) {
EditMultiRedditActivity.this.multiReddit = multiReddit;
progressBar.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
nameEditText.setText(multiReddit.getDisplayName());
descriptionEditText.setText(multiReddit.getDescription());
visibilitySwitch.setChecked(!multiReddit.getVisibility().equals("public"));
}
@Override
public void failed() {
Snackbar.make(coordinatorLayout, R.string.cannot_fetch_multireddit, Snackbar.LENGTH_SHORT).show();
}
});
}
} else {
progressBar.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
nameEditText.setText(multiReddit.getDisplayName());
descriptionEditText.setText(multiReddit.getDescription());
visibilitySwitch.setChecked(!multiReddit.getVisibility().equals("public"));
}
selectSubredditTextView.setOnClickListener(view -> {
Intent intent = new Intent(EditMultiRedditActivity.this, SelectedSubredditsAndUsersActivity.class);
if (multiReddit.getSubreddits() != null) {
intent.putStringArrayListExtra(SelectedSubredditsAndUsersActivity.EXTRA_SELECTED_SUBREDDITS, multiReddit.getSubreddits());
if (multiReddit.getSubreddits().isEmpty() && !multiReddit.getPath().equals("")) {
String[] communities = multiReddit.getPath().split(",");
ArrayList<SubredditWithSelection> communitiesList = new ArrayList<>();
for (String community : communities) {
communitiesList.add(new SubredditWithSelection(community.substring(0, community.indexOf('@')), null, community));
}
intent.putParcelableArrayListExtra(SelectedSubredditsAndUsersActivity.EXTRA_SELECTED_SUBREDDITS, communitiesList);
} else {
intent.putParcelableArrayListExtra(SelectedSubredditsAndUsersActivity.EXTRA_SELECTED_SUBREDDITS, multiReddit.getSubreddits());
}
}
startActivityForResult(intent, SUBREDDIT_SELECTION_REQUEST_CODE);
});
@ -216,13 +200,23 @@ public class EditMultiRedditActivity extends BaseActivity {
return true;
}
if (mAccessToken == null) {
String name = nameEditText.getText().toString();
multiReddit.setDisplayName(name);
multiReddit.setName(name);
multiReddit.setDescription(descriptionEditText.getText().toString());
StringBuilder pathStringBuilder = new StringBuilder();
String prefix = "";
for (SubredditWithSelection s : multiReddit.getSubreddits()) {
pathStringBuilder.append(prefix);
prefix = ",";
pathStringBuilder.append(s.getQualifiedName());
}
multiReddit.setPath(pathStringBuilder.toString());
EditMultiReddit.anonymousEditMultiReddit(mExecutor, new Handler(), mRedditDataRoomDatabase,
multiReddit, new EditMultiReddit.EditMultiRedditListener() {
multiReddit, multipath, new EditMultiReddit.EditMultiRedditListener() {
@Override
public void success() {
finish();
@ -233,22 +227,7 @@ public class EditMultiRedditActivity extends BaseActivity {
//Will not be called
}
});
} else {
String jsonModel = new MultiRedditJSONModel(nameEditText.getText().toString(), descriptionEditText.getText().toString(),
visibilitySwitch.isChecked(), multiReddit.getSubreddits()).createJSONModel();
EditMultiReddit.editMultiReddit(mRetrofit, mAccessToken, multiReddit.getPath(),
jsonModel, new EditMultiReddit.EditMultiRedditListener() {
@Override
public void success() {
finish();
}
@Override
public void failed() {
Snackbar.make(coordinatorLayout, R.string.edit_multi_reddit_failed, Snackbar.LENGTH_SHORT).show();
}
});
}
return true;
}
return false;
@ -259,7 +238,7 @@ public class EditMultiRedditActivity extends BaseActivity {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
multiReddit.setSubreddits(data.getStringArrayListExtra(
multiReddit.setSubreddits(data.getParcelableArrayListExtra(
SelectedSubredditsAndUsersActivity.EXTRA_RETURN_SELECTED_SUBREDDITS));
}
}
@ -296,7 +275,6 @@ public class EditMultiRedditActivity extends BaseActivity {
divider2.setBackgroundColor(dividerColor);
descriptionEditText.setTextColor(primaryTextColor);
descriptionEditText.setHintTextColor(secondaryTextColor);
visibilityTextView.setTextColor(primaryTextColor);
selectSubredditTextView.setTextColor(primaryTextColor);
if (typeface != null) {

View File

@ -371,20 +371,17 @@ public class FilteredPostsActivity extends BaseActivity implements SortTypeSelec
} else if (itemId == R.id.action_sort_filtered_thing_activity) {
switch (postType) {
case PostPagingSource.TYPE_FRONT_PAGE:
SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(false, mFragment.getSortType());
case PostPagingSource.TYPE_SUBREDDIT:
case PostPagingSource.TYPE_MULTI_REDDIT:
case PostPagingSource.TYPE_ANONYMOUS_MULTIREDDIT:
case PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE:
SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(postType, mFragment.getSortType());
bestSortTypeBottomSheetFragment.show(getSupportFragmentManager(), bestSortTypeBottomSheetFragment.getTag());
break;
case PostPagingSource.TYPE_SEARCH:
SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment = SearchPostSortTypeBottomSheetFragment.getNewInstance(mFragment.getSortType());
searchPostSortTypeBottomSheetFragment.show(getSupportFragmentManager(), searchPostSortTypeBottomSheetFragment.getTag());
break;
case PostPagingSource.TYPE_SUBREDDIT:
case PostPagingSource.TYPE_MULTI_REDDIT:
case PostPagingSource.TYPE_ANONYMOUS_MULTIREDDIT:
case PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE:
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(true, mFragment.getSortType());
sortTypeBottomSheetFragment.show(getSupportFragmentManager(), sortTypeBottomSheetFragment.getTag());
break;
case PostPagingSource.TYPE_USER:
UserThingSortTypeBottomSheetFragment userThingSortTypeBottomSheetFragment = UserThingSortTypeBottomSheetFragment.getNewInstance(mFragment.getSortType());
userThingSortTypeBottomSheetFragment.show(getSupportFragmentManager(), userThingSortTypeBottomSheetFragment.getTag());

View File

@ -1166,7 +1166,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
int currentPostType = sectionsPagerAdapter.getCurrentPostType();
PostFragment postFragment = sectionsPagerAdapter.getCurrentFragment();
if (postFragment != null) {
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(currentPostType != PostPagingSource.TYPE_FRONT_PAGE, postFragment.getSortType());
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(currentPostType, postFragment.getSortType());
sortTypeBottomSheetFragment.show(getSupportFragmentManager(), sortTypeBottomSheetFragment.getTag());
}
}

View File

@ -117,7 +117,7 @@ public class MultiredditSelectionActivity extends BaseActivity implements Activi
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, null);
if (savedInstanceState == null) {
bindView(true);

View File

@ -55,8 +55,10 @@ import eu.toldi.infinityforlemmy.recentsearchquery.RecentSearchQuery;
import eu.toldi.infinityforlemmy.recentsearchquery.RecentSearchQueryViewModel;
import eu.toldi.infinityforlemmy.subreddit.ParseSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Call;
@ -190,9 +192,9 @@ public class SearchActivity extends BaseActivity {
if (searchOnlySubreddits) {
Intent returnIntent = new Intent();
if (getIntent().getBooleanExtra(EXTRA_IS_MULTI_SELECTION, false)) {
ArrayList<String> subredditNameList = new ArrayList<>();
subredditNameList.add(subredditData.getName());
returnIntent.putStringArrayListExtra(RETURN_EXTRA_SELECTED_SUBREDDIT_NAMES, subredditNameList);
ArrayList<SubredditWithSelection> subredditNameList = new ArrayList<>();
subredditNameList.add(new SubredditWithSelection(subredditData.getName(), subredditData.getIconUrl(), LemmyUtils.actorID2FullName(subredditData.getActorId())));
returnIntent.putParcelableArrayListExtra(RETURN_EXTRA_SELECTED_SUBREDDIT_NAMES, subredditNameList);
} else {
returnIntent.putExtra(EXTRA_RETURN_SUBREDDIT_NAME, new SubscribedSubredditData(subredditData));
returnIntent.putExtra(EXTRA_RETURN_SUBREDDIT_ICON_URL, subredditData.getIconUrl());

View File

@ -18,7 +18,6 @@ import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.Collections;
import javax.inject.Inject;
import javax.inject.Named;
@ -29,10 +28,10 @@ import eu.toldi.infinityforlemmy.ActivityToolbarInterface;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.adapters.SelectedSubredditsRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SelectSubredditsOrUsersOptionsBottomSheetFragment;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
public class SelectedSubredditsAndUsersActivity extends BaseActivity implements ActivityToolbarInterface {
@ -62,7 +61,7 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
CustomThemeWrapper mCustomThemeWrapper;
private LinearLayoutManagerBugFixed linearLayoutManager;
private SelectedSubredditsRecyclerViewAdapter adapter;
private ArrayList<String> subreddits;
private ArrayList<SubredditWithSelection> subreddits;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -86,12 +85,11 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
setToolbarGoToTop(toolbar);
if (savedInstanceState != null) {
subreddits = savedInstanceState.getStringArrayList(SELECTED_SUBREDDITS_STATE);
subreddits = savedInstanceState.getParcelableArrayList(SELECTED_SUBREDDITS_STATE);
} else {
subreddits = getIntent().getStringArrayListExtra(EXTRA_SELECTED_SUBREDDITS);
subreddits = getIntent().getParcelableArrayListExtra(EXTRA_SELECTED_SUBREDDITS);
}
Collections.sort(subreddits);
adapter = new SelectedSubredditsRecyclerViewAdapter(this, mCustomThemeWrapper, subreddits);
linearLayoutManager = new LinearLayoutManagerBugFixed(this);
@ -110,8 +108,7 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
});
fab.setOnClickListener(view -> {
SelectSubredditsOrUsersOptionsBottomSheetFragment selectSubredditsOrUsersOptionsBottomSheetFragment = new SelectSubredditsOrUsersOptionsBottomSheetFragment();
selectSubredditsOrUsersOptionsBottomSheetFragment.show(getSupportFragmentManager(), selectSubredditsOrUsersOptionsBottomSheetFragment.getTag());
selectSubreddits();
});
}
@ -158,7 +155,7 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
if (subreddits == null) {
subreddits = new ArrayList<>();
}
subreddits = data.getStringArrayListExtra(SubredditMultiselectionActivity.EXTRA_RETURN_SELECTED_SUBREDDITS);
subreddits = data.getParcelableArrayListExtra(SubredditMultiselectionActivity.EXTRA_RETURN_SELECTED_SUBREDDITS);
adapter.addSubreddits(subreddits);
}
} else if (requestCode == USER_SELECTION_REQUEST_CODE) {
@ -176,7 +173,7 @@ public class SelectedSubredditsAndUsersActivity extends BaseActivity implements
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (adapter != null) {
outState.putStringArrayList(SELECTED_SUBREDDITS_STATE, adapter.getSubreddits());
outState.putParcelableArrayList(SELECTED_SUBREDDITS_STATE, adapter.getSubreddits());
}
}

View File

@ -37,13 +37,14 @@ import eu.toldi.infinityforlemmy.ActivityToolbarInterface;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.adapters.SubredditMultiselectionRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditViewModel;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
public class SubredditMultiselectionActivity extends BaseActivity implements ActivityToolbarInterface {
@ -70,8 +71,8 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act
@BindView(R.id.error_text_view_subscribed_subreddits_multiselection_activity)
TextView mErrorTextView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@ -131,7 +132,7 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act
mSwipeRefreshLayout.setEnabled(false);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "-");
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, "-");
bindView();
}
@ -177,7 +178,7 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act
} else if (itemId == R.id.action_save_subreddit_multiselection_activity) {
if (mAdapter != null) {
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra(EXTRA_RETURN_SELECTED_SUBREDDITS,
returnIntent.putExtra(EXTRA_RETURN_SELECTED_SUBREDDITS,
mAdapter.getAllSelectedSubreddits());
setResult(RESULT_OK, returnIntent);
}
@ -198,12 +199,12 @@ public class SubredditMultiselectionActivity extends BaseActivity implements Act
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SUBREDDIT_SEARCH_REQUEST_CODE && resultCode == RESULT_OK && data != null && mAdapter != null) {
Intent returnIntent = new Intent();
ArrayList<String> selectedSubreddits = mAdapter.getAllSelectedSubreddits();
ArrayList<String> searchedSubreddits = data.getStringArrayListExtra(SearchActivity.RETURN_EXTRA_SELECTED_SUBREDDIT_NAMES);
ArrayList<SubredditWithSelection> selectedSubreddits = mAdapter.getAllSelectedSubreddits();
ArrayList<SubredditWithSelection> searchedSubreddits = data.getParcelableArrayListExtra(SearchActivity.RETURN_EXTRA_SELECTED_SUBREDDIT_NAMES);
if (searchedSubreddits != null) {
selectedSubreddits.addAll(searchedSubreddits);
}
returnIntent.putStringArrayListExtra(EXTRA_RETURN_SELECTED_SUBREDDITS, selectedSubreddits);
returnIntent.putParcelableArrayListExtra(EXTRA_RETURN_SELECTED_SUBREDDITS, selectedSubreddits);
setResult(RESULT_OK, returnIntent);
finish();
}

View File

@ -63,7 +63,6 @@ import eu.toldi.infinityforlemmy.events.SwitchAccountEvent;
import eu.toldi.infinityforlemmy.fragments.FollowedUsersListingFragment;
import eu.toldi.infinityforlemmy.fragments.MultiRedditListingFragment;
import eu.toldi.infinityforlemmy.fragments.SubscribedSubredditsListingFragment;
import eu.toldi.infinityforlemmy.multireddit.DeleteMultiReddit;
import eu.toldi.infinityforlemmy.multireddit.FetchMyMultiReddits;
import eu.toldi.infinityforlemmy.multireddit.MultiReddit;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
@ -236,7 +235,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(1);
if (viewPager.getCurrentItem() != 2) {
if (viewPager.getCurrentItem() != 1) {
fab.hide();
}
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@ -247,7 +246,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
fab.hide();
} else {
lockSwipeRightToGoBack();
if (position != 2) {
if (position != 1) {
fab.hide();
} else {
fab.show();
@ -258,7 +257,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
tabLayout.setupWithViewPager(viewPager);
if (showMultiReddits) {
viewPager.setCurrentItem(2, false);
viewPager.setCurrentItem(1, false);
}
loadSubscriptions(false);
@ -386,7 +385,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
FetchMyMultiReddits.fetchMyMultiReddits(mOauthRetrofit, mAccessToken, new FetchMyMultiReddits.FetchMyMultiRedditsListener() {
@Override
public void success(ArrayList<MultiReddit> multiReddits) {
InsertMultireddit.insertMultireddits(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddits, mAccountName, () -> {
InsertMultireddit.insertMultireddits(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddits, mAccountQualifiedName, () -> {
mInsertMultiredditSuccess = true;
sectionsPagerAdapter.stopMultiRedditRefreshProgressbar();
});
@ -408,27 +407,11 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
.setMessage(R.string.delete_multi_reddit_dialog_message)
.setPositiveButton(R.string.delete, (dialogInterface, i)
-> {
if (mAccessToken == null) {
DeleteMultiredditInDatabase.deleteMultiredditInDatabase(mExecutor, new Handler(), mRedditDataRoomDatabase, mAccountName, multiReddit.getPath(),
DeleteMultiredditInDatabase.deleteMultiredditInDatabase(mExecutor, new Handler(), mRedditDataRoomDatabase, mAccountQualifiedName, multiReddit.getPath(),
() -> Toast.makeText(SubscribedThingListingActivity.this,
R.string.delete_multi_reddit_success, Toast.LENGTH_SHORT).show());
} else {
DeleteMultiReddit.deleteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, mAccountName, multiReddit.getPath(), new DeleteMultiReddit.DeleteMultiRedditListener() {
@Override
public void success() {
Toast.makeText(SubscribedThingListingActivity.this,
R.string.delete_multi_reddit_success, Toast.LENGTH_SHORT).show();
//loadMultiReddits();
}
@Override
public void failed() {
Toast.makeText(SubscribedThingListingActivity.this,
R.string.delete_multi_reddit_failed, Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton(R.string.cancel, null)
.show();
@ -484,7 +467,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
@Override
public Fragment getItem(int position) {
switch (position) {
default:
case 0: {
SubscribedSubredditsListingFragment fragment = new SubscribedSubredditsListingFragment();
Bundle bundle = new Bundle();
@ -495,12 +478,20 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
fragment.setArguments(bundle);
return fragment;
}
default: {
MultiRedditListingFragment fragment = new MultiRedditListingFragment();
Bundle bundle = new Bundle();
bundle.putString(MultiRedditListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(MultiRedditListingFragment.EXTRA_ACCOUNT_NAME, mAccountName == null ? "-" : mAccountQualifiedName);
fragment.setArguments(bundle);
return fragment;
}
}
}
@Override
public int getCount() {
return 1;
return 2;
}
@Override
@ -509,8 +500,6 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
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));
}
@ -523,8 +512,6 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
Fragment fragment = (Fragment) super.instantiateItem(container, position);
if (position == 0) {
subscribedSubredditsListingFragment = (SubscribedSubredditsListingFragment) fragment;
} else if (position == 1) {
followedUsersListingFragment = (FollowedUsersListingFragment) fragment;
} else {
multiRedditListingFragment = (MultiRedditListingFragment) fragment;
}

View File

@ -62,10 +62,8 @@ import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.NavigationWrapper;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.events.GoBackToMainPageEvent;
import eu.toldi.infinityforlemmy.events.RefreshMultiRedditsEvent;
import eu.toldi.infinityforlemmy.events.SwitchAccountEvent;
import eu.toldi.infinityforlemmy.fragments.PostFragment;
import eu.toldi.infinityforlemmy.multireddit.DeleteMultiReddit;
import eu.toldi.infinityforlemmy.multireddit.MultiReddit;
import eu.toldi.infinityforlemmy.post.MarkPostAsRead;
import eu.toldi.infinityforlemmy.post.Post;
@ -592,7 +590,7 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
private void showSortTypeBottomSheetFragment() {
if (mFragment instanceof PostFragment) {
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(true, ((PostFragment) mFragment).getSortType());
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(SortTypeBottomSheetFragment.PAGE_TYPE_MULTICOMMUNITY, ((PostFragment) mFragment).getSortType());
sortTypeBottomSheetFragment.show(getSupportFragmentManager(), sortTypeBottomSheetFragment.getTag());
}
}
@ -678,7 +676,7 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
-> {
Utils.hideKeyboard(this);
Intent subredditIntent = new Intent(this, ViewSubredditDetailActivity.class);
subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, thingEditText.getText().toString());
subredditIntent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY, thingEditText.getText().toString());
startActivity(subredditIntent);
})
.setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
@ -699,7 +697,7 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
if (i == EditorInfo.IME_ACTION_DONE) {
Utils.hideKeyboard(this);
Intent userIntent = new Intent(this, ViewUserDetailActivity.class);
userIntent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, thingEditText.getText().toString());
userIntent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, thingEditText.getText().toString());
startActivity(userIntent);
return true;
}
@ -764,6 +762,7 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
Intent editIntent = new Intent(this, EditMultiRedditActivity.class);
editIntent.putExtra(EditMultiRedditActivity.EXTRA_MULTI_PATH, multiPath);
startActivity(editIntent);
finish();
return true;
} else if (itemId == R.id.action_delete_view_multi_reddit_detail_activity) {
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
@ -771,30 +770,13 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
.setMessage(R.string.delete_multi_reddit_dialog_message)
.setPositiveButton(R.string.delete, (dialogInterface, i)
-> {
if (mAccessToken == null) {
DeleteMultiredditInDatabase.deleteMultiredditInDatabase(mExecutor, new Handler(), mRedditDataRoomDatabase, mAccountName, multiPath,
() -> {
Toast.makeText(this, R.string.delete_multi_reddit_success, Toast.LENGTH_SHORT).show();
finish();
});
} else {
DeleteMultiReddit.deleteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, mAccountName, multiPath, new DeleteMultiReddit.DeleteMultiRedditListener() {
@Override
public void success() {
Toast.makeText(ViewMultiRedditDetailActivity.this,
R.string.delete_multi_reddit_success, Toast.LENGTH_SHORT).show();
EventBus.getDefault().post(new RefreshMultiRedditsEvent());
finish();
}
@Override
public void failed() {
Toast.makeText(ViewMultiRedditDetailActivity.this,
R.string.delete_multi_reddit_failed, Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton(R.string.cancel, null)
.show();

View File

@ -1214,7 +1214,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private void displaySortTypeBottomSheetFragment() {
Fragment fragment = fragmentManager.findFragmentByTag("f0");
if (fragment instanceof PostFragment) {
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(true, ((PostFragment) fragment).getSortType());
SortTypeBottomSheetFragment sortTypeBottomSheetFragment = SortTypeBottomSheetFragment.getNewInstance(SortTypeBottomSheetFragment.PAGE_TYPE_COMMUNITY, ((PostFragment) fragment).getSortType());
sortTypeBottomSheetFragment.show(fragmentManager, sortTypeBottomSheetFragment.getTag());
}
}

View File

@ -6,7 +6,6 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
@ -20,15 +19,14 @@ import java.util.concurrent.Executor;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import me.zhanghai.android.fastscroll.PopupTextProvider;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.asynctasks.InsertMultireddit;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.multireddit.FavoriteMultiReddit;
import eu.toldi.infinityforlemmy.multireddit.MultiReddit;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import me.zhanghai.android.fastscroll.PopupTextProvider;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
@ -54,6 +52,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
public interface OnItemClickListener {
void onClick(MultiReddit multiReddit);
void onLongClick(MultiReddit multiReddit);
}
@ -120,80 +119,31 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
MultiReddit multiReddit = mMultiReddits.get(holder.getBindingAdapterPosition() - offset);
name = multiReddit.getDisplayName();
iconUrl = multiReddit.getIconUrl();
if(multiReddit.isFavorite()) {
if (multiReddit.isFavorite()) {
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
} else {
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
((MultiRedditViewHolder) holder).favoriteImageView.setOnClickListener(view -> {
if(multiReddit.isFavorite()) {
if (multiReddit.isFavorite()) {
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
multiReddit.setFavorite(false);
if (mAccessToken == null) {
InsertMultireddit.insertMultireddit(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddit,
() -> {
//Do nothing
});
} else {
FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, false, multiReddit,
new FavoriteMultiReddit.FavoriteMultiRedditListener() {
@Override
public void success() {
int position = holder.getBindingAdapterPosition() - offset;
if(position >= 0 && mMultiReddits.size() > position) {
mMultiReddits.get(position).setFavorite(false);
}
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_unfavorite_failed, Toast.LENGTH_SHORT).show();
int position = holder.getBindingAdapterPosition() - offset;
if(position >= 0 && mMultiReddits.size() > position) {
mMultiReddits.get(position).setFavorite(true);
}
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
}
);
}
} else {
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
multiReddit.setFavorite(true);
if (mAccessToken == null) {
InsertMultireddit.insertMultireddit(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddit,
() -> {
//Do nothing
});
} else {
FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, true, multiReddit,
new FavoriteMultiReddit.FavoriteMultiRedditListener() {
@Override
public void success() {
int position = holder.getBindingAdapterPosition() - offset;
if(position >= 0 && mMultiReddits.size() > position) {
mMultiReddits.get(position).setFavorite(true);
}
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_favorite_failed, Toast.LENGTH_SHORT).show();
int position = holder.getBindingAdapterPosition() - offset;
if(position >= 0 && mMultiReddits.size() > position) {
mMultiReddits.get(position).setFavorite(false);
}
((MultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
}
);
}
}
});
holder.itemView.setOnClickListener(view -> {
mOnItemClickListener.onClick(multiReddit);
@ -220,79 +170,29 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
MultiReddit multiReddit = mFavoriteMultiReddits.get(holder.getBindingAdapterPosition() - 1);
String name = multiReddit.getDisplayName();
String iconUrl = multiReddit.getIconUrl();
if(multiReddit.isFavorite()) {
if (multiReddit.isFavorite()) {
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
} else {
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setOnClickListener(view -> {
if(multiReddit.isFavorite()) {
if (multiReddit.isFavorite()) {
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
multiReddit.setFavorite(false);
if (mAccessToken == null) {
InsertMultireddit.insertMultireddit(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddit,
() -> {
//Do nothing
});
} else {
FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, false, multiReddit,
new FavoriteMultiReddit.FavoriteMultiRedditListener() {
@Override
public void success() {
int position = holder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteMultiReddits.size() > position) {
mFavoriteMultiReddits.get(position).setFavorite(false);
}
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_unfavorite_failed, Toast.LENGTH_SHORT).show();
int position = holder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteMultiReddits.size() > position) {
mFavoriteMultiReddits.get(position).setFavorite(true);
}
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
}
);
}
} else {
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
multiReddit.setFavorite(true);
if (mAccessToken == null) {
InsertMultireddit.insertMultireddit(mExecutor, new Handler(), mRedditDataRoomDatabase, multiReddit,
() -> {
//Do nothing
});
} else {
FavoriteMultiReddit.favoriteMultiReddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, true, multiReddit,
new FavoriteMultiReddit.FavoriteMultiRedditListener() {
@Override
public void success() {
int position = holder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteMultiReddits.size() > position) {
mFavoriteMultiReddits.get(position).setFavorite(true);
}
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_favorite_failed, Toast.LENGTH_SHORT).show();
int position = holder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteMultiReddits.size() > position) {
mFavoriteMultiReddits.get(position).setFavorite(false);
}
((FavoriteMultiRedditViewHolder) holder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
}
);
}
}
});
holder.itemView.setOnClickListener(view -> {
@ -322,7 +222,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
@Override
public int getItemCount() {
if (mMultiReddits != null) {
if(mFavoriteMultiReddits != null && mFavoriteMultiReddits.size() > 0) {
if (mFavoriteMultiReddits != null && mFavoriteMultiReddits.size() > 0) {
return mMultiReddits.size() > 0 ?
mFavoriteMultiReddits.size() + mMultiReddits.size() + 2 : 0;
}
@ -334,7 +234,7 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if(holder instanceof MultiRedditViewHolder) {
if (holder instanceof MultiRedditViewHolder) {
mGlide.clear(((MultiRedditViewHolder) holder).iconImageView);
} else if (holder instanceof FavoriteMultiRedditViewHolder) {
mGlide.clear(((FavoriteMultiRedditViewHolder) holder).iconImageView);
@ -403,7 +303,8 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
}
class FavoriteMultiRedditsDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider) TextView dividerTextView;
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
FavoriteMultiRedditsDividerViewHolder(@NonNull View itemView) {
super(itemView);
@ -417,7 +318,8 @@ public class MultiRedditListingRecyclerViewAdapter extends RecyclerView.Adapter<
}
class AllMultiRedditsDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider) TextView dividerTextView;
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
AllMultiRedditsDividerViewHolder(@NonNull View itemView) {
super(itemView);

View File

@ -16,13 +16,14 @@ import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
public class SelectedSubredditsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private BaseActivity activity;
private CustomThemeWrapper customThemeWrapper;
private ArrayList<String> subreddits;
private ArrayList<SubredditWithSelection> subreddits;
public SelectedSubredditsRecyclerViewAdapter(BaseActivity activity, CustomThemeWrapper customThemeWrapper, ArrayList<String> subreddits) {
public SelectedSubredditsRecyclerViewAdapter(BaseActivity activity, CustomThemeWrapper customThemeWrapper, ArrayList<SubredditWithSelection> subreddits) {
this.activity = activity;
this.customThemeWrapper = customThemeWrapper;
if (subreddits == null) {
@ -42,7 +43,7 @@ public class SelectedSubredditsRecyclerViewAdapter extends RecyclerView.Adapter<
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof SubredditViewHolder) {
((SubredditViewHolder) holder).subredditNameTextView.setText(subreddits.get(holder.getBindingAdapterPosition()));
((SubredditViewHolder) holder).subredditNameTextView.setText(subreddits.get(holder.getBindingAdapterPosition()).getQualifiedName());
((SubredditViewHolder) holder).deleteButton.setOnClickListener(view -> {
subreddits.remove(holder.getBindingAdapterPosition());
notifyItemRemoved(holder.getBindingAdapterPosition());
@ -55,18 +56,22 @@ public class SelectedSubredditsRecyclerViewAdapter extends RecyclerView.Adapter<
return subreddits.size();
}
public void addSubreddits(ArrayList<String> newSubreddits) {
public void addSubreddits(ArrayList<SubredditWithSelection> newSubreddits) {
int oldSize = subreddits.size();
subreddits.addAll(newSubreddits);
for (SubredditWithSelection subreddit : newSubreddits) {
if (!subreddits.contains(subreddit)) {
subreddits.add(subreddit);
}
}
notifyItemRangeInserted(oldSize, newSubreddits.size());
}
public void addUserInSubredditType(String username) {
subreddits.add(username);
notifyItemInserted(subreddits.size());
/*subreddits.add(username);
notifyItemInserted(subreddits.size());*/
}
public ArrayList<String> getSubreddits() {
public ArrayList<SubredditWithSelection> getSubreddits() {
return subreddits;
}

View File

@ -19,12 +19,12 @@ import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import pl.droidsonroids.gif.GifImageView;
public class SubredditMultiselectionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@ -53,6 +53,7 @@ public class SubredditMultiselectionRecyclerViewAdapter extends RecyclerView.Ada
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof SubscribedSubredditViewHolder) {
((SubscribedSubredditViewHolder) holder).nameTextView.setText(subscribedSubreddits.get(position).getName());
((SubscribedSubredditViewHolder) holder).instanceTextView.setText(subscribedSubreddits.get(position).getQualifiedName().substring(subscribedSubreddits.get(position).getQualifiedName().indexOf("@")));
glide.load(subscribedSubreddits.get(position).getIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
@ -91,11 +92,11 @@ public class SubredditMultiselectionRecyclerViewAdapter extends RecyclerView.Ada
notifyDataSetChanged();
}
public ArrayList<String> getAllSelectedSubreddits() {
ArrayList<String> selectedSubreddits = new ArrayList<>();
public ArrayList<SubredditWithSelection> getAllSelectedSubreddits() {
ArrayList<SubredditWithSelection> selectedSubreddits = new ArrayList<>();
for (SubredditWithSelection s : subscribedSubreddits) {
if (s.isSelected()) {
selectedSubreddits.add(s.getName());
selectedSubreddits.add(s);
}
}
return selectedSubreddits;
@ -107,6 +108,9 @@ public class SubredditMultiselectionRecyclerViewAdapter extends RecyclerView.Ada
GifImageView iconImageView;
@BindView(R.id.name_text_view_item_subscribed_subreddit_multiselection)
TextView nameTextView;
@BindView(R.id.instance_text_view_item_subscribed_subreddit_multiselection)
TextView instanceTextView;
@BindView(R.id.checkbox_item_subscribed_subreddit_multiselection)
CheckBox checkBox;
@ -115,10 +119,12 @@ public class SubredditMultiselectionRecyclerViewAdapter extends RecyclerView.Ada
this.itemView = itemView;
ButterKnife.bind(this, itemView);
nameTextView.setTextColor(primaryTextColor);
instanceTextView.setTextColor(primaryTextColor);
checkBox.setButtonTintList(ColorStateList.valueOf(colorAccent));
if (activity.typeface != null) {
nameTextView.setTypeface(activity.typeface);
instanceTextView.setTypeface(activity.typeface);
}
}
}

View File

@ -24,8 +24,8 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1;
private static final int VIEW_TYPE_MENU_ITEM = 2;
private static final int ACCOUNT_SECTION_ITEMS = 4;
private static final int ANONYMOUS_ACCOUNT_SECTION_ITEMS = 1;
private static final int ACCOUNT_SECTION_ITEMS = 5;
private static final int ANONYMOUS_ACCOUNT_SECTION_ITEMS = 2;
private BaseActivity baseActivity;
private int inboxCount;
@ -113,6 +113,10 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
baseActivity.startActivity(intent);
});
break;
case 4:
stringId = R.string.multi_reddit;
drawableId = R.drawable.ic_multi_reddit_24dp;
break;
default:
stringId = R.string.account_saved_thing_activity_label;
drawableId = R.drawable.ic_outline_bookmarks_24dp;
@ -125,6 +129,10 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
stringId = R.string.subscriptions;
drawableId = R.drawable.ic_subscritptions_bottom_app_bar_24dp;
break;
case 2:
stringId = R.string.multi_reddit;
drawableId = R.drawable.ic_multi_reddit_24dp;
break;
default:
stringId = R.string.anonymous_account_instance;
drawableId = R.drawable.ic_account_circle_24dp;

View File

@ -13,11 +13,7 @@ public class DeleteMultiredditInDatabase {
String accountName, String multipath,
DeleteMultiredditInDatabaseListener deleteMultiredditInDatabaseListener) {
executor.execute(() -> {
if (accountName.equals("-")) {
redditDataRoomDatabase.multiRedditDao().anonymousDeleteMultiReddit(multipath);
} else {
redditDataRoomDatabase.multiRedditDao().deleteMultiReddit(multipath, accountName);
}
handler.post(deleteMultiredditInDatabaseListener::success);
});
}

View File

@ -29,11 +29,20 @@ import eu.toldi.infinityforlemmy.utils.Utils;
*/
public class SortTypeBottomSheetFragment extends LandscapeExpandedRoundedBottomSheetDialogFragment {
public static final String EXTRA_NO_BEST_TYPE = "ENBT";
public static final String EXTRA_CURRENT_SORT_TYPE = "ECST";
public static final String EXTRA_PAGE_TYPE = "EPT";
public static final int PAGE_TYPE_FRONT_PAGE = 0;
public static final int PAGE_TYPE_COMMUNITY = 1;
public static final int PAGE_TYPE_USER = 2;
public static final int PAGE_TYPE_SEARCH = 3;
public static final int PAGE_TYPE_MULTICOMMUNITY = 4;
public static final int PAGE_TYPE_ANONYMOUS_FRONT_PAGE = 5;
@BindView(R.id.best_type_text_view_sort_type_bottom_sheet_fragment)
TextView bestTypeTextView;
TextView activeTypeTextView;
@BindView(R.id.hot_type_text_view_sort_type_bottom_sheet_fragment)
TextView hotTypeTextView;
@BindView(R.id.new_type_text_view_sort_type_bottom_sheet_fragment)
@ -55,10 +64,10 @@ public class SortTypeBottomSheetFragment extends LandscapeExpandedRoundedBottomS
// Required empty public constructor
}
public static SortTypeBottomSheetFragment getNewInstance(boolean isNoBestType, SortType currentSortType) {
public static SortTypeBottomSheetFragment getNewInstance(int pageType, SortType currentSortType) {
SortTypeBottomSheetFragment fragment = new SortTypeBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putBoolean(EXTRA_NO_BEST_TYPE, isNoBestType);
bundle.putInt(EXTRA_PAGE_TYPE, pageType);
bundle.putString(EXTRA_CURRENT_SORT_TYPE, currentSortType.getType().fullName);
fragment.setArguments(bundle);
return fragment;
@ -75,18 +84,27 @@ public class SortTypeBottomSheetFragment extends LandscapeExpandedRoundedBottomS
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
if (getArguments().getBoolean(EXTRA_NO_BEST_TYPE)) {
bestTypeTextView.setVisibility(View.GONE);
} else {
bestTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.ACTIVE));
dismiss();
});
int pageType = getArguments().getInt(EXTRA_PAGE_TYPE, PAGE_TYPE_USER);
switch (pageType) {
case PAGE_TYPE_MULTICOMMUNITY:
case PAGE_TYPE_USER:
case PAGE_TYPE_ANONYMOUS_FRONT_PAGE:
activeTypeTextView.setVisibility(View.GONE);
hotTypeTextView.setVisibility(View.GONE);
break;
default:
case PAGE_TYPE_COMMUNITY:
case PAGE_TYPE_FRONT_PAGE:
break;
}
String currentSortType = getArguments().getString(EXTRA_CURRENT_SORT_TYPE);
if (currentSortType.equals(SortType.Type.ACTIVE.fullName)) {
bestTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(bestTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
activeTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(activeTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.HOT.fullName)) {
hotTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(hotTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.NEW.fullName)) {
@ -101,6 +119,11 @@ public class SortTypeBottomSheetFragment extends LandscapeExpandedRoundedBottomS
controversialTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(controversialTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
}
activeTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.ACTIVE));
dismiss();
});
hotTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.HOT));
dismiss();

View File

@ -37,8 +37,6 @@ public class UserThingSortTypeBottomSheetFragment extends LandscapeExpandedRound
TextView hotTypeTextView;
@BindView(R.id.top_type_text_view_user_thing_sort_type_bottom_sheet_fragment)
TextView topTypeTextView;
@BindView(R.id.controversial_type_text_view_user_thing_sort_type_bottom_sheet_fragment)
TextView controversialTypeTextView;
private BaseActivity activity;
public UserThingSortTypeBottomSheetFragment() {
@ -95,12 +93,6 @@ public class UserThingSortTypeBottomSheetFragment extends LandscapeExpandedRound
dismiss();
});
/* controversialTypeTextView.setOnClickListener(view -> {
if (activity != null) {
((SortTypeSelectionCallback) activity).sortTypeSelected(SortType.Type.CONTROVERSIAL.name());
}
dismiss();
});*/
if (activity.typeface != null) {
Utils.setFontToAllTextViews(rootView, activity.typeface);

View File

@ -29,7 +29,6 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
@ -45,6 +44,7 @@ import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.multireddit.MultiReddit;
import eu.toldi.infinityforlemmy.multireddit.MultiRedditViewModel;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;
import retrofit2.Retrofit;
public class MultiRedditListingFragment extends Fragment implements FragmentCommunicator {
@ -111,9 +111,9 @@ public class MultiRedditListingFragment extends Fragment implements FragmentComm
String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
boolean isGettingMultiredditInfo = getArguments().getBoolean(EXTRA_IS_GETTING_MULTIREDDIT_INFO, false);
if (accessToken == null) {
mSwipeRefreshLayout.setEnabled(false);
}
mGlide = Glide.with(this);

View File

@ -435,7 +435,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
postType = getArguments().getInt(EXTRA_POST_TYPE);
mSwipeRefreshLayout.setEnabled(mSharedPreferences.getBoolean(SharedPreferencesUtils.PULL_TO_REFRESH, true) && postType != PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE);
mSwipeRefreshLayout.setEnabled(mSharedPreferences.getBoolean(SharedPreferencesUtils.PULL_TO_REFRESH, true));
mSwipeRefreshLayout.setOnRefreshListener(this::refresh);
accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
@ -597,7 +597,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
String sortTime = null;
sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_MULTI_REDDIT_POST_BASE + multiRedditPath,
SortType.Type.HOT.name());
SortType.Type.NEW.name());
if (sort.equals(SortType.Type.TOP.name())) {
sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_MULTI_REDDIT_POST_BASE + multiRedditPath,
SortType.Time.ALL.name());
@ -728,7 +728,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
nameOfUsage = PostFilterUsage.NO_USAGE;
subredditName = getArguments().getString(EXTRA_NAME);
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE + "-", SortType.Type.HOT.name());
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE + "-", SortType.Type.NEW.name());
String sortTime = null;
if (sort.equals(SortType.Type.TOP.name())) {
sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_SUBREDDIT_POST_BASE + "-", SortType.Time.ALL.name());
@ -967,7 +967,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
this.postFilter = postFilter;
postFilter.allowNSFW = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean(SharedPreferencesUtils.NSFW_BASE, false);
this.concatenatedSubredditNames = concatenatedSubredditNames;
showErrorView(R.string.anonymous_homepage_not_implemented);
//showErrorView(R.string.anonymous_homepage_not_implemented);
initializeAndBindPostViewModelForAnonymous(concatenatedSubredditNames);
}
});
} else {
@ -1009,7 +1010,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
if (activity != null && !activity.isFinishing() && !activity.isDestroyed() && !isDetached()) {
postFilter.allowNSFW = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean(SharedPreferencesUtils.NSFW_BASE, false);
this.concatenatedSubredditNames = concatenatedSubredditNames;
showErrorView(R.string.anonymous_homepage_not_implemented);
//showErrorView(R.string.anonymous_homepage_not_implemented);
initializeAndBindPostViewModelForAnonymous(concatenatedSubredditNames);
}
});
} else {

View File

@ -4,7 +4,6 @@ import android.os.Handler;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -13,6 +12,7 @@ import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import retrofit2.Call;
import retrofit2.Callback;
@ -62,21 +62,22 @@ public class CreateMultiReddit {
public static void anonymousCreateMultiReddit(Executor executor, Handler handler,
RedditDataRoomDatabase redditDataRoomDatabase,
String accountName,
String multipath, String name, String description,
List<String> subreddits,
List<SubredditWithSelection> subreddits,
CreateMultiRedditListener createMultiRedditListener) {
executor.execute(() -> {
if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) {
redditDataRoomDatabase.accountDao().insert(Account.getAnonymousAccount());
}
redditDataRoomDatabase.multiRedditDao().insert(new MultiReddit(multipath, name, name, description,
null, null, "private", "-", 0, System.currentTimeMillis(), true, false, false));
List<AnonymousMultiredditSubreddit> anonymousMultiredditSubreddits = new ArrayList<>();
for (String s : subreddits) {
anonymousMultiredditSubreddits.add(new AnonymousMultiredditSubreddit(multipath, s));
null, null, "private", accountName, 0, System.currentTimeMillis(), true, false, false));
/*List<AnonymousMultiredditSubreddit> anonymousMultiredditSubreddits = new ArrayList<>();
for (SubredditWithSelection s : subreddits) {
anonymousMultiredditSubreddits.add(new AnonymousMultiredditSubreddit(multipath, s.getQualifiedName()));
}
redditDataRoomDatabase.anonymousMultiredditSubredditDao().insertAll(anonymousMultiredditSubreddits);
*/
handler.post(createMultiRedditListener::success);
});
}

View File

@ -11,6 +11,7 @@ import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import retrofit2.Call;
import retrofit2.Callback;
@ -48,16 +49,14 @@ public class EditMultiReddit {
public static void anonymousEditMultiReddit(Executor executor, Handler handler,
RedditDataRoomDatabase redditDataRoomDatabase,
MultiReddit multiReddit,
MultiReddit multiReddit, String oldPath,
EditMultiRedditListener editMultiRedditListener) {
executor.execute(() -> {
ArrayList<AnonymousMultiredditSubreddit> anonymousMultiredditSubreddits = new ArrayList<>();
ArrayList<String> subreddits = multiReddit.getSubreddits();
ArrayList<SubredditWithSelection> subreddits = multiReddit.getSubreddits();
redditDataRoomDatabase.multiRedditDao().anonymousDeleteMultiReddit(oldPath);
redditDataRoomDatabase.multiRedditDao().insert(multiReddit);
for (String s : subreddits) {
anonymousMultiredditSubreddits.add(new AnonymousMultiredditSubreddit(multiReddit.getPath(), s));
}
redditDataRoomDatabase.anonymousMultiredditSubredditDao().insertAll(anonymousMultiredditSubreddits);
handler.post(editMultiRedditListener::success);
});
}

View File

@ -14,8 +14,9 @@ import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@ -49,16 +50,14 @@ public class FetchMultiRedditInfo {
public static void anonymousFetchMultiRedditInfo(Executor executor, Handler handler,
RedditDataRoomDatabase redditDataRoomDatabase,
String multipath,
String multipath, String accountName,
FetchMultiRedditInfoListener fetchMultiRedditInfoListener) {
executor.execute(() -> {
MultiReddit multiReddit = redditDataRoomDatabase.multiRedditDao().getMultiReddit(multipath, "-");
MultiReddit multiReddit = redditDataRoomDatabase.multiRedditDao().getMultiReddit(multipath, accountName);
ArrayList<AnonymousMultiredditSubreddit> anonymousMultiredditSubreddits =
(ArrayList<AnonymousMultiredditSubreddit>) redditDataRoomDatabase.anonymousMultiredditSubredditDao().getAllAnonymousMultiRedditSubreddits(multipath);
ArrayList<String> subredditNames = new ArrayList<>();
for (AnonymousMultiredditSubreddit a : anonymousMultiredditSubreddits) {
subredditNames.add(a.getSubredditName());
}
ArrayList<SubredditWithSelection> subredditNames = new ArrayList<>();
multiReddit.setSubreddits(subredditNames);
handler.post(() -> fetchMultiRedditInfoListener.success(multiReddit));
});
@ -93,11 +92,9 @@ public class FetchMultiRedditInfo {
boolean over18 = object.getBoolean(JSONUtils.OVER_18_KEY);
boolean isSubscriber = object.getBoolean(JSONUtils.IS_SUBSCRIBER_KEY);
boolean isFavorite = object.getBoolean(JSONUtils.IS_FAVORITED_KEY);
ArrayList<String> subreddits = new ArrayList<>();
ArrayList<SubredditWithSelection> subreddits = new ArrayList<>();
JSONArray subredditsArray = object.getJSONArray(JSONUtils.SUBREDDITS_KEY);
for (int i = 0; i < subredditsArray.length(); i++) {
subreddits.add(subredditsArray.getJSONObject(i).getString(JSONUtils.NAME_KEY));
}
multiReddit = new MultiReddit(path, displayName, name, description, copiedFrom, iconUrl,
visibility, owner, nSubscribers, createdUTC, over18, isSubscriber, isFavorite,

View File

@ -12,6 +12,7 @@ import androidx.room.Ignore;
import java.util.ArrayList;
import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
@Entity(tableName = "multi_reddits", primaryKeys = {"path", "username"},
foreignKeys = @ForeignKey(entity = Account.class, parentColumns = "username",
@ -48,7 +49,7 @@ public class MultiReddit implements Parcelable {
@ColumnInfo(name = "is_favorite")
private boolean isFavorite;
@Ignore
private ArrayList<String> subreddits;
private ArrayList<SubredditWithSelection> subreddits;
public MultiReddit(@NonNull String path, @NonNull String displayName, @NonNull String name,
String description, String copiedFrom, String iconUrl, String visibility,
@ -72,7 +73,7 @@ public class MultiReddit implements Parcelable {
public MultiReddit(@NonNull String path, @NonNull String displayName, @NonNull String name,
String description, String copiedFrom, String iconUrl, String visibility,
@NonNull String owner, int nSubscribers, long createdUTC, boolean over18,
boolean isSubscriber, boolean isFavorite, ArrayList<String> subreddits) {
boolean isSubscriber, boolean isFavorite, ArrayList<SubredditWithSelection> subreddits) {
this.displayName = displayName;
this.name = name;
this.description = description;
@ -104,7 +105,7 @@ public class MultiReddit implements Parcelable {
isSubscriber = in.readByte() != 0;
isFavorite = in.readByte() != 0;
subreddits = new ArrayList<>();
in.readStringList(subreddits);
in.readList(subreddits, SubredditWithSelection.class.getClassLoader());
}
public static final Creator<MultiReddit> CREATOR = new Creator<>() {
@ -226,11 +227,11 @@ public class MultiReddit implements Parcelable {
isFavorite = favorite;
}
public ArrayList<String> getSubreddits() {
public ArrayList<SubredditWithSelection> getSubreddits() {
return subreddits;
}
public void setSubreddits(ArrayList<String> subreddits) {
public void setSubreddits(ArrayList<SubredditWithSelection> subreddits) {
this.subreddits = subreddits;
}
@ -254,6 +255,6 @@ public class MultiReddit implements Parcelable {
parcel.writeByte((byte) (over18 ? 1 : 0));
parcel.writeByte((byte) (isSubscriber ? 1 : 0));
parcel.writeByte((byte) (isFavorite ? 1 : 0));
parcel.writeStringList(subreddits);
parcel.writeList(subreddits);
}
}

View File

@ -9,6 +9,7 @@ import org.json.JSONObject;
import java.util.ArrayList;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.subreddit.SubredditWithSelection;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
public class ParseMultiReddit {
@ -47,10 +48,8 @@ public class ParseMultiReddit {
boolean isFavorited = singleMultiRedditJSON.getBoolean(JSONUtils.IS_FAVORITED_KEY);
JSONArray subredditsArray = singleMultiRedditJSON.getJSONArray(JSONUtils.SUBREDDITS_KEY);
ArrayList<String> subreddits = new ArrayList<>();
for (int j = 0; j < subredditsArray.length(); j++) {
subreddits.add(subredditsArray.getJSONObject(j).getString(JSONUtils.NAME_KEY));
}
ArrayList<SubredditWithSelection> subreddits = new ArrayList<>();
return new MultiReddit(path, displayName, name, description, copiedFrom,
iconUrl, visibility, owner, nSubscribers, createdUTC, over18, isSubscriber,

View File

@ -13,16 +13,21 @@ import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.regex.Pattern;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.post.enrich.PostEnricher;
import eu.toldi.infinityforlemmy.postfilter.PostFilter;
import eu.toldi.infinityforlemmy.utils.MultiCommunityUtils;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import retrofit2.HttpException;
import retrofit2.Response;
@ -95,17 +100,9 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
if (postType == TYPE_SUBREDDIT || postType == TYPE_ANONYMOUS_FRONT_PAGE) {
this.subredditOrUserName = path;
} else {
if (sortType != null) {
if (path.endsWith("/")) {
multiRedditPath = path + sortType.getType().value;
} else {
multiRedditPath = path + "/" + sortType.getType().value;
}
} else {
multiRedditPath = path;
}
}
this.postType = postType;
if (sortType == null) {
if (path.equals("local") || path.equals("all")) {
@ -183,14 +180,11 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
return loadSearchPosts(loadParams, api);
case TYPE_SUBREDDIT:
return loadSubredditPosts(loadParams, api);
default:
case TYPE_MULTI_REDDIT:
return loadMultipleSubredditPosts(loadParams, api, List.of(multiRedditPath.split(Pattern.quote(","))));
case TYPE_ANONYMOUS_FRONT_PAGE:
// Return a dummy result
return Futures.immediateFuture(new LoadResult.Page<>(new ArrayList<>(), null, null));
/* case TYPE_MULTI_REDDIT:
return loadMultiRedditPosts(loadParams, api);
default:
return loadAnonymousHomePosts(loadParams, api);*/
return loadAnonymousHomePosts(loadParams, api);
}
}
@ -234,7 +228,7 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
if (savePostFeedScrolledPosition) {
String accountNameForCache = accountName == null ? SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_ANONYMOUS : accountName;
// TODO: Fix this. Save the page number?
page = null ; // postFeedScrolledPositionSharedPreferences.getString(accountNameForCache + SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_FRONT_PAGE_BASE, null);
page = null; // postFeedScrolledPositionSharedPreferences.getString(accountNameForCache + SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_FRONT_PAGE_BASE, null);
} else {
page = null;
}
@ -301,6 +295,81 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
Map<String, List<Post>> undisplayedPosts = new HashMap<>();
private ListenableFuture<LoadResult<Integer, Post>> loadMultipleSubredditPosts(@NonNull LoadParams<Integer> loadParams, LemmyAPI api, List<String> communities) {
List<ListenableFuture<LoadResult<Integer, Post>>> futures = new ArrayList<>();
List<Post> combinedPostsFromCache = new ArrayList<>();
// Check and use undisplayed posts first
for (String community : communities) {
futures.add(fetchPostsFromCommunity(api, loadParams, community));
}
// Combine and sort posts from cache and fetched
return Futures.transform(Futures.successfulAsList(futures),
results -> {
for (LoadResult<Integer, Post> result : results) {
if (result instanceof LoadResult.Page) {
combinedPostsFromCache.addAll(((LoadResult.Page<Integer, Post>) result).getData());
}
}
switch (sortType.getType()) {
default:
case NEW:
MultiCommunityUtils.INSTANCE.sortByNewest(combinedPostsFromCache);
case TOP_ALL:
case TOP_YEAR:
case TOP_NINE_MONTHS:
case TOP_SIX_MONTHS:
case TOP_THREE_MONTHS:
case TOP_MONTH:
case TOP_WEEK:
case TOP_DAY:
case TOP_TWELVE_HOURS:
case TOP_SIX_HOURS:
case TOP_HOUR:
MultiCommunityUtils.INSTANCE.sortByScore(combinedPostsFromCache);
}
List<Post> result = MultiCommunityUtils.INSTANCE.takeFirstN(combinedPostsFromCache, 25);
// Gather undisplayed posts
for (int i = result.size(); i < combinedPostsFromCache.size(); i++) {
Post post = combinedPostsFromCache.get(i);
if (undisplayedPosts.containsKey(post.getCommunityInfo().getQualifiedName())) {
undisplayedPosts.get(post.getCommunityInfo().getQualifiedName()).add(post);
} else {
undisplayedPosts.put(post.getCommunityInfo().getQualifiedName(), new ArrayList<>(Arrays.asList(post)));
}
}
Integer prevKey = result.size() > 0 ? (loadParams.getKey() != null) ? loadParams.getKey() : 1 : null;
Integer nextKey = (prevKey != null) ? prevKey + 1 : null;
return new LoadResult.Page<>(result, prevKey, nextKey);
}, executor);
}
private ListenableFuture<LoadResult<Integer, Post>> fetchPostsFromCommunity(LemmyAPI api, LoadParams<Integer> loadParams, String community) {
ListenableFuture<Response<String>> subredditPost;
subredditPost = api.getPostsListenableFuture(null, sortType.getType().value, loadParams.getKey(), 25, null, community, false, accessToken);
ListenableFuture<LoadResult<Integer, Post>> communityFuture = Futures.transform(subredditPost,
this::transformData, executor);
ListenableFuture<LoadResult<Integer, Post>> partialLoadResultFuture =
Futures.catching(communityFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
/*
private ListenableFuture<LoadResult<String, Post>> loadMultiRedditPosts(@NonNull LoadParams<String> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> multiRedditPosts;
@ -313,20 +382,6 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(multiRedditPosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
private ListenableFuture<LoadResult<String, Post>> loadAnonymousHomePosts(@NonNull LoadParams<String> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> anonymousHomePosts;
anonymousHomePosts = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType(), sortType.getTime(), loadParams.getKey());
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(anonymousHomePosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
@ -335,6 +390,14 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
IOException.class, LoadResult.Error::new, executor);
}*/
private ListenableFuture<LoadResult<Integer, Post>> loadAnonymousHomePosts(@NonNull LoadParams<Integer> loadParams, LemmyAPI api) {
if (subredditOrUserName == null) {
// Return empty list
return Futures.immediateFuture(new LoadResult.Page<>(new ArrayList<>(), null, null));
}
return loadMultipleSubredditPosts(loadParams, api, Arrays.asList(subredditOrUserName.split(Pattern.quote(","))));
}
@Override
public boolean getKeyReuseSupported() {
//TODO: Figure out why this is needed

View File

@ -17,12 +17,17 @@ import androidx.paging.PagingConfig;
import androidx.paging.PagingData;
import androidx.paging.PagingDataTransforms;
import androidx.paging.PagingLiveData;
import androidx.paging.PagingSource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.regex.Pattern;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.multicommunity.MulticommunityPagingSource;
import eu.toldi.infinityforlemmy.post.enrich.PostEnricher;
import eu.toldi.infinityforlemmy.postfilter.PostFilter;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
@ -230,8 +235,8 @@ public class PostViewModel extends ViewModel {
currentlyReadPostIdsLiveData.setValue(true);
}
public PostPagingSource returnPagingSoruce() {
PostPagingSource paging3PagingSource;
public PagingSource returnPagingSoruce() {
PagingSource paging3PagingSource;
switch (postType) {
case PostPagingSource.TYPE_FRONT_PAGE:
paging3PagingSource = new PostPagingSource(executor, retrofit, accessToken, accountName,
@ -239,12 +244,16 @@ public class PostViewModel extends ViewModel {
postFilter, readPostList, name, postEnricher);
break;
case PostPagingSource.TYPE_SUBREDDIT:
case PostPagingSource.TYPE_MULTI_REDDIT:
case PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE:
paging3PagingSource = new PostPagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, postType,
sortType, postFilter, readPostList, postEnricher);
break;
case PostPagingSource.TYPE_MULTI_REDDIT:
case PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE:
String[] communities = (name != null) ? name.split(Pattern.quote(",")) : new String[0];
paging3PagingSource = new MulticommunityPagingSource(retrofit.getRetrofit().create(LemmyAPI.class), List.of(communities), accessToken,
sortType, executor, postFilter, (readPostList != null) ? readPostList : new ArrayList<>(), postEnricher);
break;
case PostPagingSource.TYPE_SEARCH:
paging3PagingSource = new PostPagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, query, trendingSource,
@ -380,12 +389,12 @@ public class PostViewModel extends ViewModel {
this.executor = executor;
this.retrofit = retrofit;
this.sharedPreferences = sharedPreferences;
// TODO is this used? because it is getting overwritten with opt
this.name = concatenatedSubredditNames;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
this.name = opt;
this.postEnricher = postEnricher;
}

View File

@ -9,21 +9,26 @@ import java.util.ArrayList;
import java.util.List;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
public class SubredditWithSelection implements Parcelable {
private String name;
private String iconUrl;
private final String name;
private final String iconUrl;
private final String qualifiedName;
private boolean selected;
public SubredditWithSelection(String name, String iconUrl) {
public SubredditWithSelection(String name, String iconUrl, String qualifiedName) {
this.name = name;
this.iconUrl = iconUrl;
this.qualifiedName = qualifiedName;
selected = false;
}
protected SubredditWithSelection(Parcel in) {
name = in.readString();
iconUrl = in.readString();
qualifiedName = in.readString();
selected = in.readByte() != 0;
}
@ -51,6 +56,10 @@ public class SubredditWithSelection implements Parcelable {
return selected;
}
public String getQualifiedName() {
return qualifiedName;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
@ -59,14 +68,14 @@ public class SubredditWithSelection implements Parcelable {
List<SubscribedSubredditData> subscribedSubredditData) {
ArrayList<SubredditWithSelection> subredditWithSelections = new ArrayList<>();
for (SubscribedSubredditData s : subscribedSubredditData) {
subredditWithSelections.add(new SubredditWithSelection(s.getName(), s.getIconUrl()));
subredditWithSelections.add(new SubredditWithSelection(s.getName(), s.getIconUrl(), s.getQualified_name()));
}
return subredditWithSelections;
}
public static SubredditWithSelection convertSubreddit(SubredditData subreddit) {
return new SubredditWithSelection(subreddit.getName(), subreddit.getIconUrl());
return new SubredditWithSelection(subreddit.getName(), subreddit.getIconUrl(), LemmyUtils.actorID2FullName(subreddit.getActorId()));
}
public int compareName(SubredditWithSelection subredditWithSelection) {
@ -82,7 +91,7 @@ public class SubredditWithSelection implements Parcelable {
if (!(obj instanceof SubredditWithSelection)) {
return false;
} else {
return this.getName().compareToIgnoreCase(((SubredditWithSelection) obj).getName()) == 0;
return this.getQualifiedName().compareToIgnoreCase(((SubredditWithSelection) obj).getQualifiedName()) == 0;
}
}
@ -95,6 +104,7 @@ public class SubredditWithSelection implements Parcelable {
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(iconUrl);
parcel.writeString(qualifiedName);
parcel.writeByte((byte) (selected ? 1 : 0));
}
}

View File

@ -0,0 +1,192 @@
package eu.toldi.infinityforlemmy.multicommunity
import androidx.paging.ListenableFuturePagingSource
import androidx.paging.PagingState
import com.google.common.base.Function
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import eu.toldi.infinityforlemmy.SortType
import eu.toldi.infinityforlemmy.apis.LemmyAPI
import eu.toldi.infinityforlemmy.post.ParsePost
import eu.toldi.infinityforlemmy.post.Post
import eu.toldi.infinityforlemmy.post.enrich.PostEnricher
import eu.toldi.infinityforlemmy.postfilter.PostFilter
import eu.toldi.infinityforlemmy.utils.MultiCommunityUtils.sortByNewest
import eu.toldi.infinityforlemmy.utils.MultiCommunityUtils.sortByScore
import retrofit2.HttpException
import retrofit2.Response
import java.io.IOException
import java.util.concurrent.Executor
class MulticommunityPagingSource(
private val api: LemmyAPI,
private val communities: List<String>,
private val accessToken: String?,
private val sortType: SortType,
private val executor: Executor,
private val postFilter: PostFilter,
private val readPostList: List<String>, private val postEnricher: PostEnricher
) : ListenableFuturePagingSource<Map<String, Int>, Post>() {
private val postLinkedHashSet: LinkedHashSet<Post> = LinkedHashSet()
private val undisplayedPosts = mutableMapOf<String, MutableList<Post>>()
override fun loadFuture(loadParams: LoadParams<Map<String, Int>>): ListenableFuture<LoadResult<Map<String, Int>, Post>> {
val currentPageMap = loadParams.key ?: communities.associateWith { 1 }
// Initialize a list to hold futures of post loading results
val futuresList = mutableListOf<ListenableFuture<LoadResult<Int, Post>>>()
val combinedPosts = mutableListOf<Post>()
val wasCached = mutableMapOf<String, Boolean>()
// Loop through each community and fetch posts
for ((community, pageNumber) in currentPageMap) {
if (community == "all") continue // Skip all
if (undisplayedPosts.containsKey(community) && undisplayedPosts[community]!!.size > 10) {
val posts: List<Post> = undisplayedPosts[community] ?: listOf()
combinedPosts.addAll(posts)
undisplayedPosts[community]!!.clear() // Clear used posts
wasCached[community] = true
// Add a dummy future to the list
futuresList.add(Futures.immediateFuture(LoadResult.Page(posts, null, null)))
} else {
val future = fetchPostsFromCommunity(api, pageNumber, community)
futuresList.add(future)
wasCached[community] = false
}
}
val combinedFuture: ListenableFuture<LoadResult<Map<String, Int>, Post>> =
Futures.transform(Futures.successfulAsList(futuresList), { individualResults ->
// Combine the results from individual communities
val nextPageMap = mutableMapOf<String, Int>()
for ((index, result) in individualResults.withIndex()) {
if (result is LoadResult.Page<Int, Post>) {
combinedPosts.addAll(result.data)
val addition = if (wasCached[communities[index]] == true) 0 else 1
nextPageMap[communities[index]] =
result.nextKey ?: (currentPageMap[communities[index]]?.plus(addition))
?: 1
}
// Handle other cases like LoadResult.Error
}
val sorted = when (sortType.type) {
SortType.Type.NEW -> {
sortByNewest(combinedPosts)
}
SortType.Type.TOP_ALL, SortType.Type.TOP_YEAR, SortType.Type.TOP_NINE_MONTHS, SortType.Type.TOP_SIX_MONTHS, SortType.Type.TOP_THREE_MONTHS, SortType.Type.TOP_MONTH, SortType.Type.TOP_WEEK, SortType.Type.TOP_DAY, SortType.Type.TOP_TWELVE_HOURS, SortType.Type.TOP_SIX_HOURS, SortType.Type.TOP_HOUR
-> sortByScore(combinedPosts)
else -> {
sortByNewest(combinedPosts)
}
}
val filteredPosts = sorted.take(25)
// Store undisplayed posts
for (post in combinedPosts) {
if (!filteredPosts.contains(post)) {
if (undisplayedPosts.containsKey(post.subredditNamePrefixed)) {
undisplayedPosts[post.subredditNamePrefixed]?.add(post)
} else {
undisplayedPosts[post.subredditNamePrefixed] = mutableListOf(post)
}
}
}
if (currentPageMap.containsKey("all")) {
nextPageMap["all"] = filteredPosts.size + currentPageMap["all"]!!
} else {
nextPageMap["all"] = filteredPosts.size
}
LoadResult.Page(
data = filteredPosts,
prevKey = null, // Define prevKey logic if needed
nextKey = if (filteredPosts.isNotEmpty()) nextPageMap else null
)
}, executor)
val partialLoadResultFuture =
Futures.catching<LoadResult<Map<String, Int>, Post>, HttpException>(
combinedFuture,
HttpException::class.java,
Function<HttpException, LoadResult<Map<String, Int>, Post>> { throwable: HttpException ->
LoadResult.Error(throwable)
}, executor
)
return partialLoadResultFuture
}
private fun fetchPostsFromCommunity(
api: LemmyAPI,
pageNumber: Int,
community: String
): ListenableFuture<LoadResult<Int, Post>> {
val subredditPost: ListenableFuture<Response<String>>
subredditPost = api.getPostsListenableFuture(
null,
sortType.getType().value,
pageNumber,
25,
null,
community,
false,
accessToken
)
val communityFuture: ListenableFuture<LoadResult<Int, Post>> = Futures.transform(
subredditPost,
{ response -> transformData(response, pageNumber) }, executor
)
val partialLoadResultFuture: ListenableFuture<LoadResult<Int, Post>> =
Futures.catching(
communityFuture,
HttpException::class.java,
{ throwable -> LoadResult.Error<Int, Post>(throwable) },
executor
)
return Futures.catching(
partialLoadResultFuture,
IOException::class.java,
Function<IOException, LoadResult<Int, Post>> { throwable ->
LoadResult.Error<Int, Post>(throwable)
}, executor
)
}
fun transformData(response: Response<String>, pageNumber: Int): LoadResult<Int, Post> {
if (!response.isSuccessful) return LoadResult.Error(Exception("Response failed"))
val responseString =
response.body() ?: return LoadResult.Error(Exception("Empty response body"))
val newPosts =
ParsePost.parsePostsSync(responseString, -1, postFilter, readPostList, postEnricher)
?: return LoadResult.Error(Exception("Error parsing posts"))
// Filter out already linked posts
val trulyNewPosts = newPosts.filterNot(postLinkedHashSet::contains)
postLinkedHashSet.addAll(trulyNewPosts)
val nextKey = if (trulyNewPosts.isNotEmpty()) pageNumber + 1 else null
return LoadResult.Page(trulyNewPosts, null, nextKey)
}
override fun getRefreshKey(pagingState: PagingState<Map<String, Int>, Post>): Map<String, Int>? {
return null
}
// Additional methods and logic...
}

View File

@ -0,0 +1,27 @@
package eu.toldi.infinityforlemmy.utils
import eu.toldi.infinityforlemmy.post.Post
object MultiCommunityUtils {
fun takeFirstN(posts: List<Post>, take: Int = 25): List<Post> {
return posts.take(take)
}
fun sortByNewest(posts: List<Post>): List<Post> {
return posts.sortedByDescending { it.postTimeMillis }
}
fun sortByOldest(posts: List<Post>): List<Post> {
return posts.sortedBy { it.postTimeMillis }
}
fun sortByMostComments(posts: List<Post>): List<Post> {
return posts.sortedByDescending { it.nComments }
}
fun sortByScore(posts: List<Post>): List<Post> {
return posts.sortedByDescending { it.score }
}
}

View File

@ -85,32 +85,6 @@
android:layout_width="match_parent"
android:layout_height="1dp" />
<LinearLayout
android:id="@+id/visibility_wrapper_linear_layout_edit_multi_reddit_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:clickable="true"
android:focusable="true"
android:background="?attr/selectableItemBackground">
<TextView
android:id="@+id/visibility_text_view_edit_multi_reddit_activity"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/private_multi_reddit"
android:textSize="?attr/font_default"
android:textColor="?attr/primaryTextColor" />
<Switch
android:id="@+id/visibility_switch_edit_multi_reddit_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" />
</LinearLayout>
<TextView
android:id="@+id/select_subreddit_text_view_edit_multi_reddit_activity"
android:layout_width="match_parent"

View File

@ -63,23 +63,4 @@
android:textSize="?attr/font_default"
app:drawableTint="?attr/primaryTextColor" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/controversial_type_text_view_user_thing_sort_type_bottom_sheet_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:drawableStart="@drawable/ic_controversial_24"
android:drawablePadding="48dp"
android:focusable="true"
android:fontFamily="?attr/font_family"
android:paddingStart="32dp"
android:paddingTop="16dp"
android:paddingEnd="32dp"
android:paddingBottom="16dp"
android:text="@string/sort_controversial"
android:textColor="?attr/primaryTextColor"
android:textSize="?attr/font_default"
app:drawableTint="?attr/primaryTextColor" />
</LinearLayout>

View File

@ -18,15 +18,36 @@
android:layout_gravity="center_vertical"
android:layout_marginEnd="32dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="@+id/name_text_view_item_subscribed_subreddit_multiselection"
android:layout_width="0dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginEnd="0dp"
android:ellipsize="end"
android:gravity="start"
android:maxLines="1"
android:fontFamily="?attr/font_family"
android:textSize="?attr/font_default" />
<TextView
android:id="@+id/instance_text_view_item_subscribed_subreddit_multiselection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:layout_marginEnd="32dp"
android:textSize="?attr/font_default"
android:fontFamily="?attr/font_family" />
android:ellipsize="end"
android:gravity="start"
android:maxLines="1"
android:fontFamily="?attr/font_family"
android:textSize="?attr/font_default" />
</LinearLayout>
<CheckBox
android:id="@+id/checkbox_item_subscribed_subreddit_multiselection"